diff --git a/tasks/autom-supplier-invoice-match-007/tests/test.sh b/tasks/autom-supplier-invoice-match-007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-007/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-007/tests/world.json b/tasks/autom-supplier-invoice-match-007/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..ff10834d54678d2a5794fd3c400c8db5ebaebb9b --- /dev/null +++ b/tasks/autom-supplier-invoice-match-007/tests/world.json @@ -0,0 +1,446 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 3 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 1 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 1 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 6 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 5 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 8 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-07-07", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-1": { + "date": "2025-07-05", + "po": "PO0", + "state": "accepted", + "units": 28 + }, + "GI-0-2": { + "date": "2025-07-12", + "po": "PO0", + "state": "quarantine", + "units": 28 + }, + "GI-0-3": { + "date": "2025-06-26", + "po": "PO0", + "state": "accepted", + "units": 25 + }, + "GI-1-0": { + "date": "2025-07-07", + "po": "PO1", + "state": "accepted", + "units": 18 + }, + "GI-1-1": { + "date": "2025-07-09", + "po": "PO1", + "state": "accepted", + "units": 14 + }, + "GI-1-2": { + "date": "2025-06-28", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-1-3": { + "date": "2025-07-10", + "po": "PO1", + "state": "accepted", + "units": 14 + }, + "GI-2-0": { + "date": "2025-07-07", + "po": "PO2", + "state": "accepted", + "units": 13 + }, + "GI-2-1": { + "date": "2025-07-13", + "po": "PO2", + "state": "quarantine", + "units": 22 + }, + "GI-2-2": { + "date": "2025-07-10", + "po": "PO2", + "state": "quarantine", + "units": 19 + }, + "GI-2-3": { + "date": "2025-06-19", + "po": "PO2", + "state": "accepted", + "units": 16 + }, + "GI-3-0": { + "date": "2025-07-07", + "po": "PO3", + "state": "accepted", + "units": 20 + }, + "GI-3-1": { + "date": "2025-07-02", + "po": "PO3", + "state": "accepted", + "units": 27 + }, + "GI-3-2": { + "date": "2025-06-14", + "po": "PO3", + "state": "accepted", + "units": 14 + }, + "GI-3-3": { + "date": "2025-06-17", + "po": "PO3", + "state": "accepted", + "units": 12 + }, + "GI-4-0": { + "date": "2025-07-07", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-4-1": { + "date": "2025-06-16", + "po": "PO4", + "state": "accepted", + "units": 14 + }, + "GI-4-2": { + "date": "2025-06-24", + "po": "PO4", + "state": "quarantine", + "units": 13 + }, + "GI-4-3": { + "date": "2025-07-09", + "po": "PO4", + "state": "accepted", + "units": 25 + }, + "GI-5-0": { + "date": "2025-07-07", + "po": "PO5", + "state": "accepted", + "units": 15 + }, + "GI-5-1": { + "date": "2025-07-06", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-5-2": { + "date": "2025-07-12", + "po": "PO5", + "state": "quarantine", + "units": 24 + }, + "GI-5-3": { + "date": "2025-07-13", + "po": "PO5", + "state": "quarantine", + "units": 23 + }, + "GI-6-0": { + "date": "2025-07-07", + "po": "PO6", + "state": "accepted", + "units": 21 + }, + "GI-6-1": { + "date": "2025-07-07", + "po": "PO6", + "state": "accepted", + "units": 26 + }, + "GI-6-2": { + "date": "2025-06-21", + "po": "PO6", + "state": "accepted", + "units": 22 + }, + "GI-6-3": { + "date": "2025-06-16", + "po": "PO6", + "state": "quarantine", + "units": 26 + } + }, + "invoice_inbox": { + "IV-2655-0-1": { + "date": "2025-06-20", + "po": "PO0", + "state": "review", + "unit_price_cents": 20529, + "units": 10, + "vendor": "V3" + }, + "IV-2809-6-2": { + "date": "2025-06-23", + "po": "PO6", + "state": "review", + "unit_price_cents": 4548, + "units": 7, + "vendor": "V2" + }, + "IV-3227-2-0": { + "date": "2025-06-24", + "po": "PO2", + "state": "review", + "unit_price_cents": 18498, + "units": 5, + "vendor": "V4" + }, + "IV-3392-5-0": { + "date": "2025-06-24", + "po": "PO5", + "state": "review", + "unit_price_cents": 15272, + "units": 13, + "vendor": "V3" + }, + "IV-3483-2-1": { + "date": "2025-06-18", + "po": "PO2", + "state": "void", + "unit_price_cents": 18955, + "units": 9, + "vendor": "V4" + }, + "IV-3518-4-1": { + "date": "2025-07-02", + "po": "PO4", + "state": "review", + "unit_price_cents": 4246, + "units": 13, + "vendor": "V1" + }, + "IV-3522-4-2": { + "date": "2025-07-02", + "po": "PO4", + "state": "void", + "unit_price_cents": 2844, + "units": 13, + "vendor": "V1" + }, + "IV-3568-3-1": { + "date": "2025-07-04", + "po": "PO3", + "state": "review", + "unit_price_cents": 11063, + "units": 9, + "vendor": "Unknown" + }, + "IV-3822-3-0": { + "date": "2025-06-24", + "po": "PO3", + "state": "review", + "unit_price_cents": 10013, + "units": 24, + "vendor": "V1" + }, + "IV-3847-3-2": { + "date": "2025-06-23", + "po": "PO3", + "state": "review", + "unit_price_cents": 11651, + "units": 22, + "vendor": "V1" + }, + "IV-4156-2-2": { + "date": "2025-06-27", + "po": "PO2", + "state": "review", + "unit_price_cents": 19365, + "units": 4, + "vendor": "V4" + }, + "IV-4193-1-3": { + "date": "2025-07-06", + "po": "PO1", + "state": "review", + "unit_price_cents": 18727, + "units": 21, + "vendor": "Unknown" + }, + "IV-5034-1-0": { + "date": "2025-06-24", + "po": "PO1", + "state": "review", + "unit_price_cents": 17713, + "units": 21, + "vendor": "V3" + }, + "IV-5385-5-1": { + "date": "2025-06-26", + "po": "PO5", + "state": "review", + "unit_price_cents": 15209, + "units": 10, + "vendor": "V3" + }, + "IV-5419-6-1": { + "date": "2025-06-25", + "po": "PO6", + "state": "review", + "unit_price_cents": 4843, + "units": 13, + "vendor": "V2" + }, + "IV-5742-3-3": { + "date": "2025-06-25", + "po": "PO3", + "state": "review", + "unit_price_cents": 10967, + "units": 5, + "vendor": "V1" + }, + "IV-7082-4-0": { + "date": "2025-06-24", + "po": "PO4", + "state": "review", + "unit_price_cents": 2670, + "units": 17, + "vendor": "V1" + }, + "IV-8006-6-0": { + "date": "2025-06-24", + "po": "PO6", + "state": "review", + "unit_price_cents": 3349, + "units": 6, + "vendor": "V2" + }, + "IV-8060-6-3": { + "date": "2025-06-22", + "po": "PO6", + "state": "review", + "unit_price_cents": 3811, + "units": 8, + "vendor": "V2" + }, + "IV-8204-1-2": { + "date": "2025-07-06", + "po": "PO1", + "state": "review", + "unit_price_cents": 19493, + "units": 8, + "vendor": "V3" + }, + "IV-8321-0-0": { + "date": "2025-06-24", + "po": "PO0", + "state": "review", + "unit_price_cents": 18473, + "units": 1, + "vendor": "V3" + }, + "IV-8848-1-1": { + "date": "2025-06-25", + "po": "PO1", + "state": "review", + "unit_price_cents": 19793, + "units": 20, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 18473, + "vendor": "V3" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 17713, + "vendor": "V3" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 18498, + "vendor": "V4" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 10013, + "vendor": "V1" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 2670, + "vendor": "V1" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 15272, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 3349, + "vendor": "V2" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 21 + }, + "V1": { + "net_days": 45 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 45 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-007/tests/world_check.py b/tasks/autom-supplier-invoice-match-007/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-007/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-007/validation/openenv.json b/tasks/autom-supplier-invoice-match-007/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-007/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-008/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-008/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-008/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-008/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-008/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..760d79aebbd7d0ec794f277d8ac42abb47a8eaf1 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-008/environment/inputs/world.json @@ -0,0 +1,430 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 3 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 2 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 2 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 2 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 5 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 6 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-07-30", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-1": { + "date": "2025-07-14", + "po": "PO0", + "state": "quarantine", + "units": 27 + }, + "GI-0-2": { + "date": "2025-07-27", + "po": "PO0", + "state": "quarantine", + "units": 22 + }, + "GI-0-3": { + "date": "2025-08-01", + "po": "PO0", + "state": "accepted", + "units": 15 + }, + "GI-1-0": { + "date": "2025-07-30", + "po": "PO1", + "state": "accepted", + "units": 15 + }, + "GI-1-1": { + "date": "2025-08-01", + "po": "PO1", + "state": "accepted", + "units": 14 + }, + "GI-1-2": { + "date": "2025-07-30", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-1-3": { + "date": "2025-07-31", + "po": "PO1", + "state": "accepted", + "units": 27 + }, + "GI-2-0": { + "date": "2025-07-30", + "po": "PO2", + "state": "accepted", + "units": 22 + }, + "GI-2-1": { + "date": "2025-07-19", + "po": "PO2", + "state": "accepted", + "units": 17 + }, + "GI-2-2": { + "date": "2025-07-18", + "po": "PO2", + "state": "quarantine", + "units": 16 + }, + "GI-2-3": { + "date": "2025-08-03", + "po": "PO2", + "state": "accepted", + "units": 19 + }, + "GI-3-0": { + "date": "2025-07-30", + "po": "PO3", + "state": "accepted", + "units": 18 + }, + "GI-3-1": { + "date": "2025-07-20", + "po": "PO3", + "state": "quarantine", + "units": 22 + }, + "GI-3-2": { + "date": "2025-07-31", + "po": "PO3", + "state": "quarantine", + "units": 21 + }, + "GI-3-3": { + "date": "2025-07-19", + "po": "PO3", + "state": "accepted", + "units": 23 + }, + "GI-4-0": { + "date": "2025-07-30", + "po": "PO4", + "state": "accepted", + "units": 25 + }, + "GI-4-1": { + "date": "2025-07-14", + "po": "PO4", + "state": "quarantine", + "units": 14 + }, + "GI-4-2": { + "date": "2025-07-23", + "po": "PO4", + "state": "quarantine", + "units": 14 + }, + "GI-4-3": { + "date": "2025-07-26", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-5-0": { + "date": "2025-07-30", + "po": "PO5", + "state": "accepted", + "units": 13 + }, + "GI-5-1": { + "date": "2025-07-07", + "po": "PO5", + "state": "quarantine", + "units": 20 + }, + "GI-5-2": { + "date": "2025-07-21", + "po": "PO5", + "state": "quarantine", + "units": 18 + }, + "GI-5-3": { + "date": "2025-07-08", + "po": "PO5", + "state": "accepted", + "units": 25 + }, + "GI-6-0": { + "date": "2025-07-30", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-1": { + "date": "2025-08-02", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-2": { + "date": "2025-07-13", + "po": "PO6", + "state": "accepted", + "units": 27 + }, + "GI-6-3": { + "date": "2025-08-04", + "po": "PO6", + "state": "quarantine", + "units": 23 + } + }, + "invoice_inbox": { + "IV-1042-6-1": { + "date": "2025-07-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 23221, + "units": 24, + "vendor": "V2" + }, + "IV-2441-2-0": { + "date": "2025-07-10", + "po": "PO2", + "state": "review", + "unit_price_cents": 3352, + "units": 24, + "vendor": "V0" + }, + "IV-2499-2-2": { + "date": "2025-07-14", + "po": "PO2", + "state": "review", + "unit_price_cents": 3672, + "units": 24, + "vendor": "V0" + }, + "IV-2842-1-3": { + "date": "2025-07-29", + "po": "PO1", + "state": "review", + "unit_price_cents": 14234, + "units": 15, + "vendor": "V2" + }, + "IV-3512-2-1": { + "date": "2025-07-12", + "po": "PO2", + "state": "void", + "unit_price_cents": 5366, + "units": 7, + "vendor": "V0" + }, + "IV-3645-2-3": { + "date": "2025-07-06", + "po": "PO2", + "state": "review", + "unit_price_cents": 4141, + "units": 14, + "vendor": "V0" + }, + "IV-4781-1-1": { + "date": "2025-07-10", + "po": "PO1", + "state": "void", + "unit_price_cents": 14048, + "units": 12, + "vendor": "V2" + }, + "IV-5355-0-3": { + "date": "2025-07-27", + "po": "PO0", + "state": "review", + "unit_price_cents": 22436, + "units": 9, + "vendor": "V1" + }, + "IV-5362-5-1": { + "date": "2025-07-23", + "po": "PO5", + "state": "review", + "unit_price_cents": 19908, + "units": 6, + "vendor": "Unknown" + }, + "IV-5898-1-2": { + "date": "2025-07-17", + "po": "PO1", + "state": "review", + "unit_price_cents": 12052, + "units": 11, + "vendor": "V2" + }, + "IV-6039-3-0": { + "date": "2025-07-10", + "po": "PO3", + "state": "review", + "unit_price_cents": 11188, + "units": 24, + "vendor": "V4" + }, + "IV-6192-4-1": { + "date": "2025-07-29", + "po": "PO4", + "state": "review", + "unit_price_cents": 12050, + "units": 9, + "vendor": "V0" + }, + "IV-6195-1-0": { + "date": "2025-07-10", + "po": "PO1", + "state": "review", + "unit_price_cents": 12069, + "units": 4, + "vendor": "V2" + }, + "IV-6673-0-0": { + "date": "2025-07-10", + "po": "PO0", + "state": "review", + "unit_price_cents": 20814, + "units": 1, + "vendor": "V1" + }, + "IV-7091-3-1": { + "date": "2025-07-21", + "po": "PO3", + "state": "review", + "unit_price_cents": 11644, + "units": 13, + "vendor": "V4" + }, + "IV-7714-4-0": { + "date": "2025-07-10", + "po": "PO4", + "state": "review", + "unit_price_cents": 10466, + "units": 8, + "vendor": "V0" + }, + "IV-8313-6-0": { + "date": "2025-07-10", + "po": "PO6", + "state": "review", + "unit_price_cents": 21349, + "units": 9, + "vendor": "V2" + }, + "IV-8475-0-1": { + "date": "2025-07-11", + "po": "PO0", + "state": "void", + "unit_price_cents": 22241, + "units": 3, + "vendor": "Unknown" + }, + "IV-8625-5-0": { + "date": "2025-07-10", + "po": "PO5", + "state": "review", + "unit_price_cents": 18133, + "units": 9, + "vendor": "V4" + }, + "IV-8964-0-2": { + "date": "2025-07-14", + "po": "PO0", + "state": "review", + "unit_price_cents": 22581, + "units": 21, + "vendor": "V1" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 20814, + "vendor": "V1" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 12069, + "vendor": "V2" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 3352, + "vendor": "V0" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 11188, + "vendor": "V4" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 10466, + "vendor": "V0" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 18133, + "vendor": "V4" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 21349, + "vendor": "V2" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 21 + }, + "V1": { + "net_days": 30 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-008/instruction.md b/tasks/autom-supplier-invoice-match-008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5f1765a57bd37d10fc35693728c4b35ec40700b6 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-008/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit South at 2025-07-31. Handle invoices in review attached to that unit's purchase orders, invoice dates 2025-07-10 through 2025-07-31 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 100 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-008/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-008/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c807e7aebc681d256d7603e435940a4a8b95cf78 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-008/solution/files/actions.jsonl @@ -0,0 +1,28 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6673-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-8964-0-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-5355-0-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6195-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5898-1-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-2842-1-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-2441-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-2499-2-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6039-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7091-3-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-7714-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-6192-4-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8625-5-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-5362-5-1", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 80448, "due": "2025-07-31", "invoice": "IV-2441-2-0", "po": "PO2", "status": "posted", "units": 24}, "id": "book-IV-2441-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 268512, "due": "2025-07-25", "invoice": "IV-6039-3-0", "po": "PO3", "status": "posted", "units": 24}, "id": "book-IV-6039-3-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 48276, "due": "2025-07-25", "invoice": "IV-6195-1-0", "po": "PO1", "status": "posted", "units": 4}, "id": "book-IV-6195-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 20814, "due": "2025-08-11", "invoice": "IV-6673-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-6673-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 83728, "due": "2025-07-31", "invoice": "IV-7714-4-0", "po": "PO4", "status": "posted", "units": 8}, "id": "book-IV-7714-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 163197, "due": "2025-07-25", "invoice": "IV-8625-5-0", "po": "PO5", "status": "posted", "units": 9}, "id": "book-IV-8625-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 132572, "due": "2025-08-01", "invoice": "IV-5898-1-2", "po": "PO1", "status": "posted", "units": 11}, "id": "book-IV-5898-1-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-2499-2-2", "issues": ["price", "units"], "po": "PO2"}, "id": "case-IV-2499-2-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-8964-0-2", "issues": ["price", "units"], "po": "PO0"}, "id": "case-IV-8964-0-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7091-3-1", "issues": ["price"], "po": "PO3"}, "id": "case-IV-7091-3-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-5362-5-1", "issues": ["vendor", "price"], "po": "PO5"}, "id": "case-IV-5362-5-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-5355-0-3", "issues": ["price"], "po": "PO0"}, "id": "case-IV-5355-0-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-2842-1-3", "issues": ["price"], "po": "PO1"}, "id": "case-IV-2842-1-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-6192-4-1", "issues": ["price"], "po": "PO4"}, "id": "case-IV-6192-4-1", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-008/solution/solve.sh b/tasks/autom-supplier-invoice-match-008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-008/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-008/task.toml b/tasks/autom-supplier-invoice-match-008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..05270ccc50538d046a336a783990e99caed71d3f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-008/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-008" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 8 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-008" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-008/tests/expected.json b/tasks/autom-supplier-invoice-match-008/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-008/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-008/tests/grade.py b/tasks/autom-supplier-invoice-match-008/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-008/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-008/tests/replay.py b/tasks/autom-supplier-invoice-match-008/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-008/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-008/tests/target.json b/tasks/autom-supplier-invoice-match-008/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..c796aa6360eafeab856ba73897558831e4aac0e7 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-008/tests/target.json @@ -0,0 +1,538 @@ +{ + "ap_postings": { + "book-IV-2441-2-0": { + "amount_cents": 80448, + "due": "2025-07-31", + "invoice": "IV-2441-2-0", + "po": "PO2", + "status": "posted", + "units": 24 + }, + "book-IV-5898-1-2": { + "amount_cents": 132572, + "due": "2025-08-01", + "invoice": "IV-5898-1-2", + "po": "PO1", + "status": "posted", + "units": 11 + }, + "book-IV-6039-3-0": { + "amount_cents": 268512, + "due": "2025-07-25", + "invoice": "IV-6039-3-0", + "po": "PO3", + "status": "posted", + "units": 24 + }, + "book-IV-6195-1-0": { + "amount_cents": 48276, + "due": "2025-07-25", + "invoice": "IV-6195-1-0", + "po": "PO1", + "status": "posted", + "units": 4 + }, + "book-IV-6673-0-0": { + "amount_cents": 20814, + "due": "2025-08-11", + "invoice": "IV-6673-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "book-IV-7714-4-0": { + "amount_cents": 83728, + "due": "2025-07-31", + "invoice": "IV-7714-4-0", + "po": "PO4", + "status": "posted", + "units": 8 + }, + "book-IV-8625-5-0": { + "amount_cents": 163197, + "due": "2025-07-25", + "invoice": "IV-8625-5-0", + "po": "PO5", + "status": "posted", + "units": 9 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 3 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 2 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 2 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 2 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 5 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 6 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-07-30", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-1": { + "date": "2025-07-14", + "po": "PO0", + "state": "quarantine", + "units": 27 + }, + "GI-0-2": { + "date": "2025-07-27", + "po": "PO0", + "state": "quarantine", + "units": 22 + }, + "GI-0-3": { + "date": "2025-08-01", + "po": "PO0", + "state": "accepted", + "units": 15 + }, + "GI-1-0": { + "date": "2025-07-30", + "po": "PO1", + "state": "accepted", + "units": 15 + }, + "GI-1-1": { + "date": "2025-08-01", + "po": "PO1", + "state": "accepted", + "units": 14 + }, + "GI-1-2": { + "date": "2025-07-30", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-1-3": { + "date": "2025-07-31", + "po": "PO1", + "state": "accepted", + "units": 27 + }, + "GI-2-0": { + "date": "2025-07-30", + "po": "PO2", + "state": "accepted", + "units": 22 + }, + "GI-2-1": { + "date": "2025-07-19", + "po": "PO2", + "state": "accepted", + "units": 17 + }, + "GI-2-2": { + "date": "2025-07-18", + "po": "PO2", + "state": "quarantine", + "units": 16 + }, + "GI-2-3": { + "date": "2025-08-03", + "po": "PO2", + "state": "accepted", + "units": 19 + }, + "GI-3-0": { + "date": "2025-07-30", + "po": "PO3", + "state": "accepted", + "units": 18 + }, + "GI-3-1": { + "date": "2025-07-20", + "po": "PO3", + "state": "quarantine", + "units": 22 + }, + "GI-3-2": { + "date": "2025-07-31", + "po": "PO3", + "state": "quarantine", + "units": 21 + }, + "GI-3-3": { + "date": "2025-07-19", + "po": "PO3", + "state": "accepted", + "units": 23 + }, + "GI-4-0": { + "date": "2025-07-30", + "po": "PO4", + "state": "accepted", + "units": 25 + }, + "GI-4-1": { + "date": "2025-07-14", + "po": "PO4", + "state": "quarantine", + "units": 14 + }, + "GI-4-2": { + "date": "2025-07-23", + "po": "PO4", + "state": "quarantine", + "units": 14 + }, + "GI-4-3": { + "date": "2025-07-26", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-5-0": { + "date": "2025-07-30", + "po": "PO5", + "state": "accepted", + "units": 13 + }, + "GI-5-1": { + "date": "2025-07-07", + "po": "PO5", + "state": "quarantine", + "units": 20 + }, + "GI-5-2": { + "date": "2025-07-21", + "po": "PO5", + "state": "quarantine", + "units": 18 + }, + "GI-5-3": { + "date": "2025-07-08", + "po": "PO5", + "state": "accepted", + "units": 25 + }, + "GI-6-0": { + "date": "2025-07-30", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-1": { + "date": "2025-08-02", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-2": { + "date": "2025-07-13", + "po": "PO6", + "state": "accepted", + "units": 27 + }, + "GI-6-3": { + "date": "2025-08-04", + "po": "PO6", + "state": "quarantine", + "units": 23 + } + }, + "invoice_inbox": { + "IV-1042-6-1": { + "date": "2025-07-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 23221, + "units": 24, + "vendor": "V2" + }, + "IV-2441-2-0": { + "date": "2025-07-10", + "po": "PO2", + "state": "posted", + "unit_price_cents": 3352, + "units": 24, + "vendor": "V0" + }, + "IV-2499-2-2": { + "date": "2025-07-14", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 3672, + "units": 24, + "vendor": "V0" + }, + "IV-2842-1-3": { + "date": "2025-07-29", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 14234, + "units": 15, + "vendor": "V2" + }, + "IV-3512-2-1": { + "date": "2025-07-12", + "po": "PO2", + "state": "void", + "unit_price_cents": 5366, + "units": 7, + "vendor": "V0" + }, + "IV-3645-2-3": { + "date": "2025-07-06", + "po": "PO2", + "state": "review", + "unit_price_cents": 4141, + "units": 14, + "vendor": "V0" + }, + "IV-4781-1-1": { + "date": "2025-07-10", + "po": "PO1", + "state": "void", + "unit_price_cents": 14048, + "units": 12, + "vendor": "V2" + }, + "IV-5355-0-3": { + "date": "2025-07-27", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 22436, + "units": 9, + "vendor": "V1" + }, + "IV-5362-5-1": { + "date": "2025-07-23", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 19908, + "units": 6, + "vendor": "Unknown" + }, + "IV-5898-1-2": { + "date": "2025-07-17", + "po": "PO1", + "state": "posted", + "unit_price_cents": 12052, + "units": 11, + "vendor": "V2" + }, + "IV-6039-3-0": { + "date": "2025-07-10", + "po": "PO3", + "state": "posted", + "unit_price_cents": 11188, + "units": 24, + "vendor": "V4" + }, + "IV-6192-4-1": { + "date": "2025-07-29", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 12050, + "units": 9, + "vendor": "V0" + }, + "IV-6195-1-0": { + "date": "2025-07-10", + "po": "PO1", + "state": "posted", + "unit_price_cents": 12069, + "units": 4, + "vendor": "V2" + }, + "IV-6673-0-0": { + "date": "2025-07-10", + "po": "PO0", + "state": "posted", + "unit_price_cents": 20814, + "units": 1, + "vendor": "V1" + }, + "IV-7091-3-1": { + "date": "2025-07-21", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 11644, + "units": 13, + "vendor": "V4" + }, + "IV-7714-4-0": { + "date": "2025-07-10", + "po": "PO4", + "state": "posted", + "unit_price_cents": 10466, + "units": 8, + "vendor": "V0" + }, + "IV-8313-6-0": { + "date": "2025-07-10", + "po": "PO6", + "state": "review", + "unit_price_cents": 21349, + "units": 9, + "vendor": "V2" + }, + "IV-8475-0-1": { + "date": "2025-07-11", + "po": "PO0", + "state": "void", + "unit_price_cents": 22241, + "units": 3, + "vendor": "Unknown" + }, + "IV-8625-5-0": { + "date": "2025-07-10", + "po": "PO5", + "state": "posted", + "unit_price_cents": 18133, + "units": 9, + "vendor": "V4" + }, + "IV-8964-0-2": { + "date": "2025-07-14", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 22581, + "units": 21, + "vendor": "V1" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 20814, + "vendor": "V1" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 12069, + "vendor": "V2" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 3352, + "vendor": "V0" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 11188, + "vendor": "V4" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 10466, + "vendor": "V0" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 18133, + "vendor": "V4" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 21349, + "vendor": "V2" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-2499-2-2": { + "invoice": "IV-2499-2-2", + "issues": [ + "price", + "units" + ], + "po": "PO2" + }, + "case-IV-2842-1-3": { + "invoice": "IV-2842-1-3", + "issues": [ + "price" + ], + "po": "PO1" + }, + "case-IV-5355-0-3": { + "invoice": "IV-5355-0-3", + "issues": [ + "price" + ], + "po": "PO0" + }, + "case-IV-5362-5-1": { + "invoice": "IV-5362-5-1", + "issues": [ + "vendor", + "price" + ], + "po": "PO5" + }, + "case-IV-6192-4-1": { + "invoice": "IV-6192-4-1", + "issues": [ + "price" + ], + "po": "PO4" + }, + "case-IV-7091-3-1": { + "invoice": "IV-7091-3-1", + "issues": [ + "price" + ], + "po": "PO3" + }, + "case-IV-8964-0-2": { + "invoice": "IV-8964-0-2", + "issues": [ + "price", + "units" + ], + "po": "PO0" + } + }, + "vendors": { + "V0": { + "net_days": 21 + }, + "V1": { + "net_days": 30 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-008/tests/test.sh b/tasks/autom-supplier-invoice-match-008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-008/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-008/tests/world.json b/tasks/autom-supplier-invoice-match-008/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..760d79aebbd7d0ec794f277d8ac42abb47a8eaf1 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-008/tests/world.json @@ -0,0 +1,430 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 3 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 2 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 2 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 2 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 5 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 6 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-07-30", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-1": { + "date": "2025-07-14", + "po": "PO0", + "state": "quarantine", + "units": 27 + }, + "GI-0-2": { + "date": "2025-07-27", + "po": "PO0", + "state": "quarantine", + "units": 22 + }, + "GI-0-3": { + "date": "2025-08-01", + "po": "PO0", + "state": "accepted", + "units": 15 + }, + "GI-1-0": { + "date": "2025-07-30", + "po": "PO1", + "state": "accepted", + "units": 15 + }, + "GI-1-1": { + "date": "2025-08-01", + "po": "PO1", + "state": "accepted", + "units": 14 + }, + "GI-1-2": { + "date": "2025-07-30", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-1-3": { + "date": "2025-07-31", + "po": "PO1", + "state": "accepted", + "units": 27 + }, + "GI-2-0": { + "date": "2025-07-30", + "po": "PO2", + "state": "accepted", + "units": 22 + }, + "GI-2-1": { + "date": "2025-07-19", + "po": "PO2", + "state": "accepted", + "units": 17 + }, + "GI-2-2": { + "date": "2025-07-18", + "po": "PO2", + "state": "quarantine", + "units": 16 + }, + "GI-2-3": { + "date": "2025-08-03", + "po": "PO2", + "state": "accepted", + "units": 19 + }, + "GI-3-0": { + "date": "2025-07-30", + "po": "PO3", + "state": "accepted", + "units": 18 + }, + "GI-3-1": { + "date": "2025-07-20", + "po": "PO3", + "state": "quarantine", + "units": 22 + }, + "GI-3-2": { + "date": "2025-07-31", + "po": "PO3", + "state": "quarantine", + "units": 21 + }, + "GI-3-3": { + "date": "2025-07-19", + "po": "PO3", + "state": "accepted", + "units": 23 + }, + "GI-4-0": { + "date": "2025-07-30", + "po": "PO4", + "state": "accepted", + "units": 25 + }, + "GI-4-1": { + "date": "2025-07-14", + "po": "PO4", + "state": "quarantine", + "units": 14 + }, + "GI-4-2": { + "date": "2025-07-23", + "po": "PO4", + "state": "quarantine", + "units": 14 + }, + "GI-4-3": { + "date": "2025-07-26", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-5-0": { + "date": "2025-07-30", + "po": "PO5", + "state": "accepted", + "units": 13 + }, + "GI-5-1": { + "date": "2025-07-07", + "po": "PO5", + "state": "quarantine", + "units": 20 + }, + "GI-5-2": { + "date": "2025-07-21", + "po": "PO5", + "state": "quarantine", + "units": 18 + }, + "GI-5-3": { + "date": "2025-07-08", + "po": "PO5", + "state": "accepted", + "units": 25 + }, + "GI-6-0": { + "date": "2025-07-30", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-1": { + "date": "2025-08-02", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-2": { + "date": "2025-07-13", + "po": "PO6", + "state": "accepted", + "units": 27 + }, + "GI-6-3": { + "date": "2025-08-04", + "po": "PO6", + "state": "quarantine", + "units": 23 + } + }, + "invoice_inbox": { + "IV-1042-6-1": { + "date": "2025-07-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 23221, + "units": 24, + "vendor": "V2" + }, + "IV-2441-2-0": { + "date": "2025-07-10", + "po": "PO2", + "state": "review", + "unit_price_cents": 3352, + "units": 24, + "vendor": "V0" + }, + "IV-2499-2-2": { + "date": "2025-07-14", + "po": "PO2", + "state": "review", + "unit_price_cents": 3672, + "units": 24, + "vendor": "V0" + }, + "IV-2842-1-3": { + "date": "2025-07-29", + "po": "PO1", + "state": "review", + "unit_price_cents": 14234, + "units": 15, + "vendor": "V2" + }, + "IV-3512-2-1": { + "date": "2025-07-12", + "po": "PO2", + "state": "void", + "unit_price_cents": 5366, + "units": 7, + "vendor": "V0" + }, + "IV-3645-2-3": { + "date": "2025-07-06", + "po": "PO2", + "state": "review", + "unit_price_cents": 4141, + "units": 14, + "vendor": "V0" + }, + "IV-4781-1-1": { + "date": "2025-07-10", + "po": "PO1", + "state": "void", + "unit_price_cents": 14048, + "units": 12, + "vendor": "V2" + }, + "IV-5355-0-3": { + "date": "2025-07-27", + "po": "PO0", + "state": "review", + "unit_price_cents": 22436, + "units": 9, + "vendor": "V1" + }, + "IV-5362-5-1": { + "date": "2025-07-23", + "po": "PO5", + "state": "review", + "unit_price_cents": 19908, + "units": 6, + "vendor": "Unknown" + }, + "IV-5898-1-2": { + "date": "2025-07-17", + "po": "PO1", + "state": "review", + "unit_price_cents": 12052, + "units": 11, + "vendor": "V2" + }, + "IV-6039-3-0": { + "date": "2025-07-10", + "po": "PO3", + "state": "review", + "unit_price_cents": 11188, + "units": 24, + "vendor": "V4" + }, + "IV-6192-4-1": { + "date": "2025-07-29", + "po": "PO4", + "state": "review", + "unit_price_cents": 12050, + "units": 9, + "vendor": "V0" + }, + "IV-6195-1-0": { + "date": "2025-07-10", + "po": "PO1", + "state": "review", + "unit_price_cents": 12069, + "units": 4, + "vendor": "V2" + }, + "IV-6673-0-0": { + "date": "2025-07-10", + "po": "PO0", + "state": "review", + "unit_price_cents": 20814, + "units": 1, + "vendor": "V1" + }, + "IV-7091-3-1": { + "date": "2025-07-21", + "po": "PO3", + "state": "review", + "unit_price_cents": 11644, + "units": 13, + "vendor": "V4" + }, + "IV-7714-4-0": { + "date": "2025-07-10", + "po": "PO4", + "state": "review", + "unit_price_cents": 10466, + "units": 8, + "vendor": "V0" + }, + "IV-8313-6-0": { + "date": "2025-07-10", + "po": "PO6", + "state": "review", + "unit_price_cents": 21349, + "units": 9, + "vendor": "V2" + }, + "IV-8475-0-1": { + "date": "2025-07-11", + "po": "PO0", + "state": "void", + "unit_price_cents": 22241, + "units": 3, + "vendor": "Unknown" + }, + "IV-8625-5-0": { + "date": "2025-07-10", + "po": "PO5", + "state": "review", + "unit_price_cents": 18133, + "units": 9, + "vendor": "V4" + }, + "IV-8964-0-2": { + "date": "2025-07-14", + "po": "PO0", + "state": "review", + "unit_price_cents": 22581, + "units": 21, + "vendor": "V1" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 20814, + "vendor": "V1" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 12069, + "vendor": "V2" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 3352, + "vendor": "V0" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 11188, + "vendor": "V4" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 10466, + "vendor": "V0" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 18133, + "vendor": "V4" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 21349, + "vendor": "V2" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 21 + }, + "V1": { + "net_days": 30 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-008/tests/world_check.py b/tasks/autom-supplier-invoice-match-008/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-008/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-008/validation/openenv.json b/tasks/autom-supplier-invoice-match-008/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-008/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-009/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-009/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-009/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-009/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-009/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..9b705358aa52126723034ad31a049cde666617b6 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-009/environment/inputs/world.json @@ -0,0 +1,422 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 1 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 0 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 5 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 0 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 2 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 6 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-08-22", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-1": { + "date": "2025-08-26", + "po": "PO0", + "state": "quarantine", + "units": 28 + }, + "GI-0-2": { + "date": "2025-08-04", + "po": "PO0", + "state": "accepted", + "units": 22 + }, + "GI-0-3": { + "date": "2025-08-19", + "po": "PO0", + "state": "accepted", + "units": 12 + }, + "GI-1-0": { + "date": "2025-08-22", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-1-1": { + "date": "2025-08-07", + "po": "PO1", + "state": "quarantine", + "units": 12 + }, + "GI-1-2": { + "date": "2025-08-20", + "po": "PO1", + "state": "quarantine", + "units": 26 + }, + "GI-1-3": { + "date": "2025-08-25", + "po": "PO1", + "state": "accepted", + "units": 26 + }, + "GI-2-0": { + "date": "2025-08-22", + "po": "PO2", + "state": "accepted", + "units": 17 + }, + "GI-2-1": { + "date": "2025-07-31", + "po": "PO2", + "state": "accepted", + "units": 13 + }, + "GI-2-2": { + "date": "2025-08-27", + "po": "PO2", + "state": "accepted", + "units": 22 + }, + "GI-2-3": { + "date": "2025-08-19", + "po": "PO2", + "state": "quarantine", + "units": 26 + }, + "GI-3-0": { + "date": "2025-08-22", + "po": "PO3", + "state": "accepted", + "units": 21 + }, + "GI-3-1": { + "date": "2025-08-19", + "po": "PO3", + "state": "accepted", + "units": 22 + }, + "GI-3-2": { + "date": "2025-08-27", + "po": "PO3", + "state": "accepted", + "units": 16 + }, + "GI-3-3": { + "date": "2025-08-14", + "po": "PO3", + "state": "accepted", + "units": 13 + }, + "GI-4-0": { + "date": "2025-08-22", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-1": { + "date": "2025-08-15", + "po": "PO4", + "state": "quarantine", + "units": 15 + }, + "GI-4-2": { + "date": "2025-07-31", + "po": "PO4", + "state": "accepted", + "units": 28 + }, + "GI-4-3": { + "date": "2025-08-09", + "po": "PO4", + "state": "quarantine", + "units": 18 + }, + "GI-5-0": { + "date": "2025-08-22", + "po": "PO5", + "state": "accepted", + "units": 13 + }, + "GI-5-1": { + "date": "2025-08-21", + "po": "PO5", + "state": "accepted", + "units": 25 + }, + "GI-5-2": { + "date": "2025-08-07", + "po": "PO5", + "state": "quarantine", + "units": 13 + }, + "GI-5-3": { + "date": "2025-08-18", + "po": "PO5", + "state": "accepted", + "units": 22 + }, + "GI-6-0": { + "date": "2025-08-22", + "po": "PO6", + "state": "accepted", + "units": 16 + }, + "GI-6-1": { + "date": "2025-08-17", + "po": "PO6", + "state": "accepted", + "units": 14 + }, + "GI-6-2": { + "date": "2025-08-17", + "po": "PO6", + "state": "accepted", + "units": 15 + }, + "GI-6-3": { + "date": "2025-08-19", + "po": "PO6", + "state": "quarantine", + "units": 20 + } + }, + "invoice_inbox": { + "IV-2613-5-2": { + "date": "2025-08-22", + "po": "PO5", + "state": "review", + "unit_price_cents": 12821, + "units": 18, + "vendor": "V4" + }, + "IV-3037-6-1": { + "date": "2025-08-15", + "po": "PO6", + "state": "void", + "unit_price_cents": 22140, + "units": 25, + "vendor": "V0" + }, + "IV-3482-1-1": { + "date": "2025-08-23", + "po": "PO1", + "state": "review", + "unit_price_cents": 19000, + "units": 13, + "vendor": "Unknown" + }, + "IV-4155-4-1": { + "date": "2025-08-03", + "po": "PO4", + "state": "void", + "unit_price_cents": 8752, + "units": 13, + "vendor": "V2" + }, + "IV-4801-3-1": { + "date": "2025-08-04", + "po": "PO3", + "state": "review", + "unit_price_cents": 14648, + "units": 10, + "vendor": "V3" + }, + "IV-4811-2-1": { + "date": "2025-08-16", + "po": "PO2", + "state": "review", + "unit_price_cents": 4453, + "units": 25, + "vendor": "Unknown" + }, + "IV-5537-5-0": { + "date": "2025-08-09", + "po": "PO5", + "state": "review", + "unit_price_cents": 13177, + "units": 19, + "vendor": "V4" + }, + "IV-6510-3-2": { + "date": "2025-08-09", + "po": "PO3", + "state": "review", + "unit_price_cents": 13059, + "units": 3, + "vendor": "V3" + }, + "IV-6764-0-1": { + "date": "2025-08-15", + "po": "PO0", + "state": "review", + "unit_price_cents": 4492, + "units": 9, + "vendor": "V0" + }, + "IV-6912-6-2": { + "date": "2025-08-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 23343, + "units": 19, + "vendor": "V0" + }, + "IV-7893-4-2": { + "date": "2025-08-20", + "po": "PO4", + "state": "review", + "unit_price_cents": 9742, + "units": 11, + "vendor": "V2" + }, + "IV-7924-5-1": { + "date": "2025-08-09", + "po": "PO5", + "state": "review", + "unit_price_cents": 15219, + "units": 13, + "vendor": "V4" + }, + "IV-8036-3-0": { + "date": "2025-08-09", + "po": "PO3", + "state": "review", + "unit_price_cents": 13187, + "units": 5, + "vendor": "V3" + }, + "IV-8332-6-3": { + "date": "2025-08-22", + "po": "PO6", + "state": "review", + "unit_price_cents": 23448, + "units": 5, + "vendor": "V0" + }, + "IV-8473-0-0": { + "date": "2025-08-09", + "po": "PO0", + "state": "review", + "unit_price_cents": 4672, + "units": 1, + "vendor": "V0" + }, + "IV-8711-4-0": { + "date": "2025-08-09", + "po": "PO4", + "state": "review", + "unit_price_cents": 8944, + "units": 17, + "vendor": "V2" + }, + "IV-9039-1-0": { + "date": "2025-08-09", + "po": "PO1", + "state": "review", + "unit_price_cents": 18388, + "units": 16, + "vendor": "V0" + }, + "IV-9189-6-0": { + "date": "2025-08-09", + "po": "PO6", + "state": "review", + "unit_price_cents": 21322, + "units": 17, + "vendor": "V0" + }, + "IV-9422-2-0": { + "date": "2025-08-09", + "po": "PO2", + "state": "review", + "unit_price_cents": 3223, + "units": 3, + "vendor": "V1" + } + }, + "purchase_orders": { + "PO0": { + "unit": "North", + "unit_price_cents": 4672, + "vendor": "V0" + }, + "PO1": { + "unit": "North", + "unit_price_cents": 18388, + "vendor": "V0" + }, + "PO2": { + "unit": "North", + "unit_price_cents": 3223, + "vendor": "V1" + }, + "PO3": { + "unit": "North", + "unit_price_cents": 13187, + "vendor": "V3" + }, + "PO4": { + "unit": "North", + "unit_price_cents": 8944, + "vendor": "V2" + }, + "PO5": { + "unit": "North", + "unit_price_cents": 13177, + "vendor": "V4" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 21322, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 21 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-009/instruction.md b/tasks/autom-supplier-invoice-match-009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f72ee218233a4799e08801397495c2d2067fb86a --- /dev/null +++ b/tasks/autom-supplier-invoice-match-009/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit North at 2025-08-23. Handle invoices in review attached to that unit's purchase orders, invoice dates 2025-08-09 through 2025-08-23 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 200 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-009/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-009/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b2b7203c28dd2de55c0fb4832355fb1d924027b3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-009/solution/files/actions.jsonl @@ -0,0 +1,26 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8473-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6764-0-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-9039-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3482-1-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-9422-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4811-2-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8036-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6510-3-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8711-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7893-4-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5537-5-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7924-5-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-2613-5-2", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 250363, "due": "2025-08-25", "invoice": "IV-5537-5-0", "po": "PO5", "status": "posted", "units": 19}, "id": "book-IV-5537-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 39177, "due": "2025-09-23", "invoice": "IV-6510-3-2", "po": "PO3", "status": "posted", "units": 3}, "id": "book-IV-6510-3-2", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 65935, "due": "2025-09-23", "invoice": "IV-8036-3-0", "po": "PO3", "status": "posted", "units": 5}, "id": "book-IV-8036-3-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 4672, "due": "2025-09-08", "invoice": "IV-8473-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-8473-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 152048, "due": "2025-09-01", "invoice": "IV-8711-4-0", "po": "PO4", "status": "posted", "units": 17}, "id": "book-IV-8711-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 294208, "due": "2025-09-08", "invoice": "IV-9039-1-0", "po": "PO1", "status": "posted", "units": 16}, "id": "book-IV-9039-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 9669, "due": "2025-08-25", "invoice": "IV-9422-2-0", "po": "PO2", "status": "posted", "units": 3}, "id": "book-IV-9422-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 40428, "due": "2025-09-15", "invoice": "IV-6764-0-1", "po": "PO0", "status": "posted", "units": 9}, "id": "book-IV-6764-0-1", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 230778, "due": "2025-09-08", "invoice": "IV-2613-5-2", "po": "PO5", "status": "posted", "units": 18}, "id": "book-IV-2613-5-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7924-5-1", "issues": ["price"], "po": "PO5"}, "id": "case-IV-7924-5-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4811-2-1", "issues": ["vendor", "price", "units"], "po": "PO2"}, "id": "case-IV-4811-2-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7893-4-2", "issues": ["price"], "po": "PO4"}, "id": "case-IV-7893-4-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3482-1-1", "issues": ["vendor", "price", "units"], "po": "PO1"}, "id": "case-IV-3482-1-1", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-009/solution/solve.sh b/tasks/autom-supplier-invoice-match-009/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-009/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-009/task.toml b/tasks/autom-supplier-invoice-match-009/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f77812481754570e772536f134129737d860c3bd --- /dev/null +++ b/tasks/autom-supplier-invoice-match-009/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-009" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 9 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-009" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-009/tests/expected.json b/tasks/autom-supplier-invoice-match-009/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-009/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-009/tests/grade.py b/tasks/autom-supplier-invoice-match-009/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-009/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-009/tests/replay.py b/tasks/autom-supplier-invoice-match-009/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-009/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-009/tests/target.json b/tasks/autom-supplier-invoice-match-009/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..3f6bf40a32e4158df0eb029c1e316e5574e8b44b --- /dev/null +++ b/tasks/autom-supplier-invoice-match-009/tests/target.json @@ -0,0 +1,526 @@ +{ + "ap_postings": { + "book-IV-2613-5-2": { + "amount_cents": 230778, + "due": "2025-09-08", + "invoice": "IV-2613-5-2", + "po": "PO5", + "status": "posted", + "units": 18 + }, + "book-IV-5537-5-0": { + "amount_cents": 250363, + "due": "2025-08-25", + "invoice": "IV-5537-5-0", + "po": "PO5", + "status": "posted", + "units": 19 + }, + "book-IV-6510-3-2": { + "amount_cents": 39177, + "due": "2025-09-23", + "invoice": "IV-6510-3-2", + "po": "PO3", + "status": "posted", + "units": 3 + }, + "book-IV-6764-0-1": { + "amount_cents": 40428, + "due": "2025-09-15", + "invoice": "IV-6764-0-1", + "po": "PO0", + "status": "posted", + "units": 9 + }, + "book-IV-8036-3-0": { + "amount_cents": 65935, + "due": "2025-09-23", + "invoice": "IV-8036-3-0", + "po": "PO3", + "status": "posted", + "units": 5 + }, + "book-IV-8473-0-0": { + "amount_cents": 4672, + "due": "2025-09-08", + "invoice": "IV-8473-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "book-IV-8711-4-0": { + "amount_cents": 152048, + "due": "2025-09-01", + "invoice": "IV-8711-4-0", + "po": "PO4", + "status": "posted", + "units": 17 + }, + "book-IV-9039-1-0": { + "amount_cents": 294208, + "due": "2025-09-08", + "invoice": "IV-9039-1-0", + "po": "PO1", + "status": "posted", + "units": 16 + }, + "book-IV-9422-2-0": { + "amount_cents": 9669, + "due": "2025-08-25", + "invoice": "IV-9422-2-0", + "po": "PO2", + "status": "posted", + "units": 3 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 1 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 0 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 5 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 0 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 2 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 6 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-08-22", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-1": { + "date": "2025-08-26", + "po": "PO0", + "state": "quarantine", + "units": 28 + }, + "GI-0-2": { + "date": "2025-08-04", + "po": "PO0", + "state": "accepted", + "units": 22 + }, + "GI-0-3": { + "date": "2025-08-19", + "po": "PO0", + "state": "accepted", + "units": 12 + }, + "GI-1-0": { + "date": "2025-08-22", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-1-1": { + "date": "2025-08-07", + "po": "PO1", + "state": "quarantine", + "units": 12 + }, + "GI-1-2": { + "date": "2025-08-20", + "po": "PO1", + "state": "quarantine", + "units": 26 + }, + "GI-1-3": { + "date": "2025-08-25", + "po": "PO1", + "state": "accepted", + "units": 26 + }, + "GI-2-0": { + "date": "2025-08-22", + "po": "PO2", + "state": "accepted", + "units": 17 + }, + "GI-2-1": { + "date": "2025-07-31", + "po": "PO2", + "state": "accepted", + "units": 13 + }, + "GI-2-2": { + "date": "2025-08-27", + "po": "PO2", + "state": "accepted", + "units": 22 + }, + "GI-2-3": { + "date": "2025-08-19", + "po": "PO2", + "state": "quarantine", + "units": 26 + }, + "GI-3-0": { + "date": "2025-08-22", + "po": "PO3", + "state": "accepted", + "units": 21 + }, + "GI-3-1": { + "date": "2025-08-19", + "po": "PO3", + "state": "accepted", + "units": 22 + }, + "GI-3-2": { + "date": "2025-08-27", + "po": "PO3", + "state": "accepted", + "units": 16 + }, + "GI-3-3": { + "date": "2025-08-14", + "po": "PO3", + "state": "accepted", + "units": 13 + }, + "GI-4-0": { + "date": "2025-08-22", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-1": { + "date": "2025-08-15", + "po": "PO4", + "state": "quarantine", + "units": 15 + }, + "GI-4-2": { + "date": "2025-07-31", + "po": "PO4", + "state": "accepted", + "units": 28 + }, + "GI-4-3": { + "date": "2025-08-09", + "po": "PO4", + "state": "quarantine", + "units": 18 + }, + "GI-5-0": { + "date": "2025-08-22", + "po": "PO5", + "state": "accepted", + "units": 13 + }, + "GI-5-1": { + "date": "2025-08-21", + "po": "PO5", + "state": "accepted", + "units": 25 + }, + "GI-5-2": { + "date": "2025-08-07", + "po": "PO5", + "state": "quarantine", + "units": 13 + }, + "GI-5-3": { + "date": "2025-08-18", + "po": "PO5", + "state": "accepted", + "units": 22 + }, + "GI-6-0": { + "date": "2025-08-22", + "po": "PO6", + "state": "accepted", + "units": 16 + }, + "GI-6-1": { + "date": "2025-08-17", + "po": "PO6", + "state": "accepted", + "units": 14 + }, + "GI-6-2": { + "date": "2025-08-17", + "po": "PO6", + "state": "accepted", + "units": 15 + }, + "GI-6-3": { + "date": "2025-08-19", + "po": "PO6", + "state": "quarantine", + "units": 20 + } + }, + "invoice_inbox": { + "IV-2613-5-2": { + "date": "2025-08-22", + "po": "PO5", + "state": "posted", + "unit_price_cents": 12821, + "units": 18, + "vendor": "V4" + }, + "IV-3037-6-1": { + "date": "2025-08-15", + "po": "PO6", + "state": "void", + "unit_price_cents": 22140, + "units": 25, + "vendor": "V0" + }, + "IV-3482-1-1": { + "date": "2025-08-23", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 19000, + "units": 13, + "vendor": "Unknown" + }, + "IV-4155-4-1": { + "date": "2025-08-03", + "po": "PO4", + "state": "void", + "unit_price_cents": 8752, + "units": 13, + "vendor": "V2" + }, + "IV-4801-3-1": { + "date": "2025-08-04", + "po": "PO3", + "state": "review", + "unit_price_cents": 14648, + "units": 10, + "vendor": "V3" + }, + "IV-4811-2-1": { + "date": "2025-08-16", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 4453, + "units": 25, + "vendor": "Unknown" + }, + "IV-5537-5-0": { + "date": "2025-08-09", + "po": "PO5", + "state": "posted", + "unit_price_cents": 13177, + "units": 19, + "vendor": "V4" + }, + "IV-6510-3-2": { + "date": "2025-08-09", + "po": "PO3", + "state": "posted", + "unit_price_cents": 13059, + "units": 3, + "vendor": "V3" + }, + "IV-6764-0-1": { + "date": "2025-08-15", + "po": "PO0", + "state": "posted", + "unit_price_cents": 4492, + "units": 9, + "vendor": "V0" + }, + "IV-6912-6-2": { + "date": "2025-08-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 23343, + "units": 19, + "vendor": "V0" + }, + "IV-7893-4-2": { + "date": "2025-08-20", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 9742, + "units": 11, + "vendor": "V2" + }, + "IV-7924-5-1": { + "date": "2025-08-09", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 15219, + "units": 13, + "vendor": "V4" + }, + "IV-8036-3-0": { + "date": "2025-08-09", + "po": "PO3", + "state": "posted", + "unit_price_cents": 13187, + "units": 5, + "vendor": "V3" + }, + "IV-8332-6-3": { + "date": "2025-08-22", + "po": "PO6", + "state": "review", + "unit_price_cents": 23448, + "units": 5, + "vendor": "V0" + }, + "IV-8473-0-0": { + "date": "2025-08-09", + "po": "PO0", + "state": "posted", + "unit_price_cents": 4672, + "units": 1, + "vendor": "V0" + }, + "IV-8711-4-0": { + "date": "2025-08-09", + "po": "PO4", + "state": "posted", + "unit_price_cents": 8944, + "units": 17, + "vendor": "V2" + }, + "IV-9039-1-0": { + "date": "2025-08-09", + "po": "PO1", + "state": "posted", + "unit_price_cents": 18388, + "units": 16, + "vendor": "V0" + }, + "IV-9189-6-0": { + "date": "2025-08-09", + "po": "PO6", + "state": "review", + "unit_price_cents": 21322, + "units": 17, + "vendor": "V0" + }, + "IV-9422-2-0": { + "date": "2025-08-09", + "po": "PO2", + "state": "posted", + "unit_price_cents": 3223, + "units": 3, + "vendor": "V1" + } + }, + "purchase_orders": { + "PO0": { + "unit": "North", + "unit_price_cents": 4672, + "vendor": "V0" + }, + "PO1": { + "unit": "North", + "unit_price_cents": 18388, + "vendor": "V0" + }, + "PO2": { + "unit": "North", + "unit_price_cents": 3223, + "vendor": "V1" + }, + "PO3": { + "unit": "North", + "unit_price_cents": 13187, + "vendor": "V3" + }, + "PO4": { + "unit": "North", + "unit_price_cents": 8944, + "vendor": "V2" + }, + "PO5": { + "unit": "North", + "unit_price_cents": 13177, + "vendor": "V4" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 21322, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-3482-1-1": { + "invoice": "IV-3482-1-1", + "issues": [ + "vendor", + "price", + "units" + ], + "po": "PO1" + }, + "case-IV-4811-2-1": { + "invoice": "IV-4811-2-1", + "issues": [ + "vendor", + "price", + "units" + ], + "po": "PO2" + }, + "case-IV-7893-4-2": { + "invoice": "IV-7893-4-2", + "issues": [ + "price" + ], + "po": "PO4" + }, + "case-IV-7924-5-1": { + "invoice": "IV-7924-5-1", + "issues": [ + "price" + ], + "po": "PO5" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 21 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-009/tests/test.sh b/tasks/autom-supplier-invoice-match-009/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-009/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-009/tests/world.json b/tasks/autom-supplier-invoice-match-009/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..9b705358aa52126723034ad31a049cde666617b6 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-009/tests/world.json @@ -0,0 +1,422 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 1 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 0 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 5 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 0 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 2 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 6 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-08-22", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-1": { + "date": "2025-08-26", + "po": "PO0", + "state": "quarantine", + "units": 28 + }, + "GI-0-2": { + "date": "2025-08-04", + "po": "PO0", + "state": "accepted", + "units": 22 + }, + "GI-0-3": { + "date": "2025-08-19", + "po": "PO0", + "state": "accepted", + "units": 12 + }, + "GI-1-0": { + "date": "2025-08-22", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-1-1": { + "date": "2025-08-07", + "po": "PO1", + "state": "quarantine", + "units": 12 + }, + "GI-1-2": { + "date": "2025-08-20", + "po": "PO1", + "state": "quarantine", + "units": 26 + }, + "GI-1-3": { + "date": "2025-08-25", + "po": "PO1", + "state": "accepted", + "units": 26 + }, + "GI-2-0": { + "date": "2025-08-22", + "po": "PO2", + "state": "accepted", + "units": 17 + }, + "GI-2-1": { + "date": "2025-07-31", + "po": "PO2", + "state": "accepted", + "units": 13 + }, + "GI-2-2": { + "date": "2025-08-27", + "po": "PO2", + "state": "accepted", + "units": 22 + }, + "GI-2-3": { + "date": "2025-08-19", + "po": "PO2", + "state": "quarantine", + "units": 26 + }, + "GI-3-0": { + "date": "2025-08-22", + "po": "PO3", + "state": "accepted", + "units": 21 + }, + "GI-3-1": { + "date": "2025-08-19", + "po": "PO3", + "state": "accepted", + "units": 22 + }, + "GI-3-2": { + "date": "2025-08-27", + "po": "PO3", + "state": "accepted", + "units": 16 + }, + "GI-3-3": { + "date": "2025-08-14", + "po": "PO3", + "state": "accepted", + "units": 13 + }, + "GI-4-0": { + "date": "2025-08-22", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-1": { + "date": "2025-08-15", + "po": "PO4", + "state": "quarantine", + "units": 15 + }, + "GI-4-2": { + "date": "2025-07-31", + "po": "PO4", + "state": "accepted", + "units": 28 + }, + "GI-4-3": { + "date": "2025-08-09", + "po": "PO4", + "state": "quarantine", + "units": 18 + }, + "GI-5-0": { + "date": "2025-08-22", + "po": "PO5", + "state": "accepted", + "units": 13 + }, + "GI-5-1": { + "date": "2025-08-21", + "po": "PO5", + "state": "accepted", + "units": 25 + }, + "GI-5-2": { + "date": "2025-08-07", + "po": "PO5", + "state": "quarantine", + "units": 13 + }, + "GI-5-3": { + "date": "2025-08-18", + "po": "PO5", + "state": "accepted", + "units": 22 + }, + "GI-6-0": { + "date": "2025-08-22", + "po": "PO6", + "state": "accepted", + "units": 16 + }, + "GI-6-1": { + "date": "2025-08-17", + "po": "PO6", + "state": "accepted", + "units": 14 + }, + "GI-6-2": { + "date": "2025-08-17", + "po": "PO6", + "state": "accepted", + "units": 15 + }, + "GI-6-3": { + "date": "2025-08-19", + "po": "PO6", + "state": "quarantine", + "units": 20 + } + }, + "invoice_inbox": { + "IV-2613-5-2": { + "date": "2025-08-22", + "po": "PO5", + "state": "review", + "unit_price_cents": 12821, + "units": 18, + "vendor": "V4" + }, + "IV-3037-6-1": { + "date": "2025-08-15", + "po": "PO6", + "state": "void", + "unit_price_cents": 22140, + "units": 25, + "vendor": "V0" + }, + "IV-3482-1-1": { + "date": "2025-08-23", + "po": "PO1", + "state": "review", + "unit_price_cents": 19000, + "units": 13, + "vendor": "Unknown" + }, + "IV-4155-4-1": { + "date": "2025-08-03", + "po": "PO4", + "state": "void", + "unit_price_cents": 8752, + "units": 13, + "vendor": "V2" + }, + "IV-4801-3-1": { + "date": "2025-08-04", + "po": "PO3", + "state": "review", + "unit_price_cents": 14648, + "units": 10, + "vendor": "V3" + }, + "IV-4811-2-1": { + "date": "2025-08-16", + "po": "PO2", + "state": "review", + "unit_price_cents": 4453, + "units": 25, + "vendor": "Unknown" + }, + "IV-5537-5-0": { + "date": "2025-08-09", + "po": "PO5", + "state": "review", + "unit_price_cents": 13177, + "units": 19, + "vendor": "V4" + }, + "IV-6510-3-2": { + "date": "2025-08-09", + "po": "PO3", + "state": "review", + "unit_price_cents": 13059, + "units": 3, + "vendor": "V3" + }, + "IV-6764-0-1": { + "date": "2025-08-15", + "po": "PO0", + "state": "review", + "unit_price_cents": 4492, + "units": 9, + "vendor": "V0" + }, + "IV-6912-6-2": { + "date": "2025-08-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 23343, + "units": 19, + "vendor": "V0" + }, + "IV-7893-4-2": { + "date": "2025-08-20", + "po": "PO4", + "state": "review", + "unit_price_cents": 9742, + "units": 11, + "vendor": "V2" + }, + "IV-7924-5-1": { + "date": "2025-08-09", + "po": "PO5", + "state": "review", + "unit_price_cents": 15219, + "units": 13, + "vendor": "V4" + }, + "IV-8036-3-0": { + "date": "2025-08-09", + "po": "PO3", + "state": "review", + "unit_price_cents": 13187, + "units": 5, + "vendor": "V3" + }, + "IV-8332-6-3": { + "date": "2025-08-22", + "po": "PO6", + "state": "review", + "unit_price_cents": 23448, + "units": 5, + "vendor": "V0" + }, + "IV-8473-0-0": { + "date": "2025-08-09", + "po": "PO0", + "state": "review", + "unit_price_cents": 4672, + "units": 1, + "vendor": "V0" + }, + "IV-8711-4-0": { + "date": "2025-08-09", + "po": "PO4", + "state": "review", + "unit_price_cents": 8944, + "units": 17, + "vendor": "V2" + }, + "IV-9039-1-0": { + "date": "2025-08-09", + "po": "PO1", + "state": "review", + "unit_price_cents": 18388, + "units": 16, + "vendor": "V0" + }, + "IV-9189-6-0": { + "date": "2025-08-09", + "po": "PO6", + "state": "review", + "unit_price_cents": 21322, + "units": 17, + "vendor": "V0" + }, + "IV-9422-2-0": { + "date": "2025-08-09", + "po": "PO2", + "state": "review", + "unit_price_cents": 3223, + "units": 3, + "vendor": "V1" + } + }, + "purchase_orders": { + "PO0": { + "unit": "North", + "unit_price_cents": 4672, + "vendor": "V0" + }, + "PO1": { + "unit": "North", + "unit_price_cents": 18388, + "vendor": "V0" + }, + "PO2": { + "unit": "North", + "unit_price_cents": 3223, + "vendor": "V1" + }, + "PO3": { + "unit": "North", + "unit_price_cents": 13187, + "vendor": "V3" + }, + "PO4": { + "unit": "North", + "unit_price_cents": 8944, + "vendor": "V2" + }, + "PO5": { + "unit": "North", + "unit_price_cents": 13177, + "vendor": "V4" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 21322, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 21 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-009/tests/world_check.py b/tasks/autom-supplier-invoice-match-009/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-009/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-009/validation/openenv.json b/tasks/autom-supplier-invoice-match-009/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-009/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-010/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-010/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-010/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-010/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-010/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..90caa5213e80cb588f42fa14f860f06e2e705a44 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-010/environment/inputs/world.json @@ -0,0 +1,446 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 2 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 6 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 4 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 2 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 4 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-09-14", + "po": "PO0", + "state": "accepted", + "units": 26 + }, + "GI-0-1": { + "date": "2025-09-12", + "po": "PO0", + "state": "quarantine", + "units": 13 + }, + "GI-0-2": { + "date": "2025-09-09", + "po": "PO0", + "state": "accepted", + "units": 15 + }, + "GI-0-3": { + "date": "2025-09-10", + "po": "PO0", + "state": "accepted", + "units": 18 + }, + "GI-1-0": { + "date": "2025-09-14", + "po": "PO1", + "state": "accepted", + "units": 17 + }, + "GI-1-1": { + "date": "2025-09-07", + "po": "PO1", + "state": "accepted", + "units": 24 + }, + "GI-1-2": { + "date": "2025-09-08", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-1-3": { + "date": "2025-09-02", + "po": "PO1", + "state": "accepted", + "units": 25 + }, + "GI-2-0": { + "date": "2025-09-14", + "po": "PO2", + "state": "accepted", + "units": 19 + }, + "GI-2-1": { + "date": "2025-09-09", + "po": "PO2", + "state": "accepted", + "units": 14 + }, + "GI-2-2": { + "date": "2025-08-22", + "po": "PO2", + "state": "accepted", + "units": 17 + }, + "GI-2-3": { + "date": "2025-09-16", + "po": "PO2", + "state": "quarantine", + "units": 25 + }, + "GI-3-0": { + "date": "2025-09-14", + "po": "PO3", + "state": "accepted", + "units": 28 + }, + "GI-3-1": { + "date": "2025-09-16", + "po": "PO3", + "state": "accepted", + "units": 20 + }, + "GI-3-2": { + "date": "2025-09-10", + "po": "PO3", + "state": "quarantine", + "units": 14 + }, + "GI-3-3": { + "date": "2025-09-08", + "po": "PO3", + "state": "quarantine", + "units": 12 + }, + "GI-4-0": { + "date": "2025-09-14", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-1": { + "date": "2025-09-09", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-4-2": { + "date": "2025-09-20", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-3": { + "date": "2025-08-27", + "po": "PO4", + "state": "quarantine", + "units": 24 + }, + "GI-5-0": { + "date": "2025-09-14", + "po": "PO5", + "state": "accepted", + "units": 22 + }, + "GI-5-1": { + "date": "2025-09-10", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-5-2": { + "date": "2025-08-26", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-3": { + "date": "2025-09-13", + "po": "PO5", + "state": "quarantine", + "units": 22 + }, + "GI-6-0": { + "date": "2025-09-14", + "po": "PO6", + "state": "accepted", + "units": 15 + }, + "GI-6-1": { + "date": "2025-09-05", + "po": "PO6", + "state": "accepted", + "units": 27 + }, + "GI-6-2": { + "date": "2025-09-04", + "po": "PO6", + "state": "accepted", + "units": 15 + }, + "GI-6-3": { + "date": "2025-08-22", + "po": "PO6", + "state": "quarantine", + "units": 26 + } + }, + "invoice_inbox": { + "IV-1121-4-0": { + "date": "2025-09-01", + "po": "PO4", + "state": "review", + "unit_price_cents": 17924, + "units": 13, + "vendor": "V1" + }, + "IV-1208-6-0": { + "date": "2025-09-01", + "po": "PO6", + "state": "review", + "unit_price_cents": 8042, + "units": 3, + "vendor": "V0" + }, + "IV-1673-5-0": { + "date": "2025-09-01", + "po": "PO5", + "state": "review", + "unit_price_cents": 1621, + "units": 22, + "vendor": "V2" + }, + "IV-1942-2-3": { + "date": "2025-08-26", + "po": "PO2", + "state": "review", + "unit_price_cents": 10900, + "units": 25, + "vendor": "V2" + }, + "IV-1960-5-1": { + "date": "2025-09-10", + "po": "PO5", + "state": "void", + "unit_price_cents": 1254, + "units": 22, + "vendor": "V2" + }, + "IV-2764-4-1": { + "date": "2025-09-06", + "po": "PO4", + "state": "review", + "unit_price_cents": 19899, + "units": 12, + "vendor": "Unknown" + }, + "IV-2815-2-1": { + "date": "2025-08-27", + "po": "PO2", + "state": "review", + "unit_price_cents": 11257, + "units": 17, + "vendor": "Unknown" + }, + "IV-3112-5-2": { + "date": "2025-08-28", + "po": "PO5", + "state": "review", + "unit_price_cents": 3159, + "units": 9, + "vendor": "V2" + }, + "IV-3145-6-3": { + "date": "2025-08-30", + "po": "PO6", + "state": "void", + "unit_price_cents": 8002, + "units": 19, + "vendor": "V0" + }, + "IV-3547-1-1": { + "date": "2025-09-05", + "po": "PO1", + "state": "review", + "unit_price_cents": 12078, + "units": 17, + "vendor": "V0" + }, + "IV-3914-6-2": { + "date": "2025-09-07", + "po": "PO6", + "state": "void", + "unit_price_cents": 8669, + "units": 12, + "vendor": "Unknown" + }, + "IV-4018-5-3": { + "date": "2025-09-13", + "po": "PO5", + "state": "void", + "unit_price_cents": 2185, + "units": 18, + "vendor": "V2" + }, + "IV-4805-2-0": { + "date": "2025-09-01", + "po": "PO2", + "state": "review", + "unit_price_cents": 9571, + "units": 10, + "vendor": "V2" + }, + "IV-5145-6-1": { + "date": "2025-09-02", + "po": "PO6", + "state": "review", + "unit_price_cents": 10087, + "units": 12, + "vendor": "V0" + }, + "IV-5313-3-0": { + "date": "2025-09-01", + "po": "PO3", + "state": "review", + "unit_price_cents": 9903, + "units": 4, + "vendor": "V4" + }, + "IV-5395-0-1": { + "date": "2025-08-28", + "po": "PO0", + "state": "review", + "unit_price_cents": 11242, + "units": 18, + "vendor": "V1" + }, + "IV-5915-0-2": { + "date": "2025-08-29", + "po": "PO0", + "state": "void", + "unit_price_cents": 10505, + "units": 11, + "vendor": "V1" + }, + "IV-6603-1-0": { + "date": "2025-09-01", + "po": "PO1", + "state": "review", + "unit_price_cents": 12252, + "units": 5, + "vendor": "V0" + }, + "IV-7380-2-2": { + "date": "2025-08-29", + "po": "PO2", + "state": "review", + "unit_price_cents": 9671, + "units": 6, + "vendor": "V2" + }, + "IV-7506-1-2": { + "date": "2025-09-08", + "po": "PO1", + "state": "review", + "unit_price_cents": 13175, + "units": 14, + "vendor": "V0" + }, + "IV-8304-3-1": { + "date": "2025-09-06", + "po": "PO3", + "state": "review", + "unit_price_cents": 9567, + "units": 20, + "vendor": "V4" + }, + "IV-9162-0-0": { + "date": "2025-09-01", + "po": "PO0", + "state": "review", + "unit_price_cents": 9684, + "units": 1, + "vendor": "V1" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 9684, + "vendor": "V1" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 12252, + "vendor": "V0" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 9571, + "vendor": "V2" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 9903, + "vendor": "V4" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 17924, + "vendor": "V1" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 1621, + "vendor": "V2" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 8042, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 45 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-010/instruction.md b/tasks/autom-supplier-invoice-match-010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0786a1807fa37a5978c95a76436cfa0b6484418 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-010/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit South at 2025-09-15. Handle invoices in review attached to that unit's purchase orders, invoice dates 2025-09-01 through 2025-09-15 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 500 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-010/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-010/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..23c32da610a1f2fdca796f273066394133ed8cb4 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-010/solution/files/actions.jsonl @@ -0,0 +1,20 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-9162-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6603-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-3547-1-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7506-1-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-4805-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5313-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8304-3-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-1121-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-2764-4-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-1673-5-0", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 233012, "due": "2025-09-16", "invoice": "IV-1121-4-0", "po": "PO4", "status": "posted", "units": 13}, "id": "book-IV-1121-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 35662, "due": "2025-09-16", "invoice": "IV-1673-5-0", "po": "PO5", "status": "posted", "units": 22}, "id": "book-IV-1673-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 95710, "due": "2025-09-16", "invoice": "IV-4805-2-0", "po": "PO2", "status": "posted", "units": 10}, "id": "book-IV-4805-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 39612, "due": "2025-10-01", "invoice": "IV-5313-3-0", "po": "PO3", "status": "posted", "units": 4}, "id": "book-IV-5313-3-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 61260, "due": "2025-10-16", "invoice": "IV-6603-1-0", "po": "PO1", "status": "posted", "units": 5}, "id": "book-IV-6603-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 9684, "due": "2025-09-16", "invoice": "IV-9162-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-9162-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 205326, "due": "2025-10-20", "invoice": "IV-3547-1-1", "po": "PO1", "status": "posted", "units": 17}, "id": "book-IV-3547-1-1", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 191340, "due": "2025-10-06", "invoice": "IV-8304-3-1", "po": "PO3", "status": "posted", "units": 20}, "id": "book-IV-8304-3-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-2764-4-1", "issues": ["vendor", "price"], "po": "PO4"}, "id": "case-IV-2764-4-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7506-1-2", "issues": ["price"], "po": "PO1"}, "id": "case-IV-7506-1-2", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-010/solution/solve.sh b/tasks/autom-supplier-invoice-match-010/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-010/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-010/task.toml b/tasks/autom-supplier-invoice-match-010/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ef60586f218ddd285e2994db16849a17c3a4b015 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-010/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-010" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 10 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-010" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-010/tests/expected.json b/tasks/autom-supplier-invoice-match-010/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-010/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-010/tests/grade.py b/tasks/autom-supplier-invoice-match-010/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-010/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-010/tests/replay.py b/tasks/autom-supplier-invoice-match-010/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-010/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-010/tests/target.json b/tasks/autom-supplier-invoice-match-010/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..61fbd3c43080851d415887184b3a91d48794d38e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-010/tests/target.json @@ -0,0 +1,525 @@ +{ + "ap_postings": { + "book-IV-1121-4-0": { + "amount_cents": 233012, + "due": "2025-09-16", + "invoice": "IV-1121-4-0", + "po": "PO4", + "status": "posted", + "units": 13 + }, + "book-IV-1673-5-0": { + "amount_cents": 35662, + "due": "2025-09-16", + "invoice": "IV-1673-5-0", + "po": "PO5", + "status": "posted", + "units": 22 + }, + "book-IV-3547-1-1": { + "amount_cents": 205326, + "due": "2025-10-20", + "invoice": "IV-3547-1-1", + "po": "PO1", + "status": "posted", + "units": 17 + }, + "book-IV-4805-2-0": { + "amount_cents": 95710, + "due": "2025-09-16", + "invoice": "IV-4805-2-0", + "po": "PO2", + "status": "posted", + "units": 10 + }, + "book-IV-5313-3-0": { + "amount_cents": 39612, + "due": "2025-10-01", + "invoice": "IV-5313-3-0", + "po": "PO3", + "status": "posted", + "units": 4 + }, + "book-IV-6603-1-0": { + "amount_cents": 61260, + "due": "2025-10-16", + "invoice": "IV-6603-1-0", + "po": "PO1", + "status": "posted", + "units": 5 + }, + "book-IV-8304-3-1": { + "amount_cents": 191340, + "due": "2025-10-06", + "invoice": "IV-8304-3-1", + "po": "PO3", + "status": "posted", + "units": 20 + }, + "book-IV-9162-0-0": { + "amount_cents": 9684, + "due": "2025-09-16", + "invoice": "IV-9162-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 2 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 6 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 4 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 2 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 4 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-09-14", + "po": "PO0", + "state": "accepted", + "units": 26 + }, + "GI-0-1": { + "date": "2025-09-12", + "po": "PO0", + "state": "quarantine", + "units": 13 + }, + "GI-0-2": { + "date": "2025-09-09", + "po": "PO0", + "state": "accepted", + "units": 15 + }, + "GI-0-3": { + "date": "2025-09-10", + "po": "PO0", + "state": "accepted", + "units": 18 + }, + "GI-1-0": { + "date": "2025-09-14", + "po": "PO1", + "state": "accepted", + "units": 17 + }, + "GI-1-1": { + "date": "2025-09-07", + "po": "PO1", + "state": "accepted", + "units": 24 + }, + "GI-1-2": { + "date": "2025-09-08", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-1-3": { + "date": "2025-09-02", + "po": "PO1", + "state": "accepted", + "units": 25 + }, + "GI-2-0": { + "date": "2025-09-14", + "po": "PO2", + "state": "accepted", + "units": 19 + }, + "GI-2-1": { + "date": "2025-09-09", + "po": "PO2", + "state": "accepted", + "units": 14 + }, + "GI-2-2": { + "date": "2025-08-22", + "po": "PO2", + "state": "accepted", + "units": 17 + }, + "GI-2-3": { + "date": "2025-09-16", + "po": "PO2", + "state": "quarantine", + "units": 25 + }, + "GI-3-0": { + "date": "2025-09-14", + "po": "PO3", + "state": "accepted", + "units": 28 + }, + "GI-3-1": { + "date": "2025-09-16", + "po": "PO3", + "state": "accepted", + "units": 20 + }, + "GI-3-2": { + "date": "2025-09-10", + "po": "PO3", + "state": "quarantine", + "units": 14 + }, + "GI-3-3": { + "date": "2025-09-08", + "po": "PO3", + "state": "quarantine", + "units": 12 + }, + "GI-4-0": { + "date": "2025-09-14", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-1": { + "date": "2025-09-09", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-4-2": { + "date": "2025-09-20", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-3": { + "date": "2025-08-27", + "po": "PO4", + "state": "quarantine", + "units": 24 + }, + "GI-5-0": { + "date": "2025-09-14", + "po": "PO5", + "state": "accepted", + "units": 22 + }, + "GI-5-1": { + "date": "2025-09-10", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-5-2": { + "date": "2025-08-26", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-3": { + "date": "2025-09-13", + "po": "PO5", + "state": "quarantine", + "units": 22 + }, + "GI-6-0": { + "date": "2025-09-14", + "po": "PO6", + "state": "accepted", + "units": 15 + }, + "GI-6-1": { + "date": "2025-09-05", + "po": "PO6", + "state": "accepted", + "units": 27 + }, + "GI-6-2": { + "date": "2025-09-04", + "po": "PO6", + "state": "accepted", + "units": 15 + }, + "GI-6-3": { + "date": "2025-08-22", + "po": "PO6", + "state": "quarantine", + "units": 26 + } + }, + "invoice_inbox": { + "IV-1121-4-0": { + "date": "2025-09-01", + "po": "PO4", + "state": "posted", + "unit_price_cents": 17924, + "units": 13, + "vendor": "V1" + }, + "IV-1208-6-0": { + "date": "2025-09-01", + "po": "PO6", + "state": "review", + "unit_price_cents": 8042, + "units": 3, + "vendor": "V0" + }, + "IV-1673-5-0": { + "date": "2025-09-01", + "po": "PO5", + "state": "posted", + "unit_price_cents": 1621, + "units": 22, + "vendor": "V2" + }, + "IV-1942-2-3": { + "date": "2025-08-26", + "po": "PO2", + "state": "review", + "unit_price_cents": 10900, + "units": 25, + "vendor": "V2" + }, + "IV-1960-5-1": { + "date": "2025-09-10", + "po": "PO5", + "state": "void", + "unit_price_cents": 1254, + "units": 22, + "vendor": "V2" + }, + "IV-2764-4-1": { + "date": "2025-09-06", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 19899, + "units": 12, + "vendor": "Unknown" + }, + "IV-2815-2-1": { + "date": "2025-08-27", + "po": "PO2", + "state": "review", + "unit_price_cents": 11257, + "units": 17, + "vendor": "Unknown" + }, + "IV-3112-5-2": { + "date": "2025-08-28", + "po": "PO5", + "state": "review", + "unit_price_cents": 3159, + "units": 9, + "vendor": "V2" + }, + "IV-3145-6-3": { + "date": "2025-08-30", + "po": "PO6", + "state": "void", + "unit_price_cents": 8002, + "units": 19, + "vendor": "V0" + }, + "IV-3547-1-1": { + "date": "2025-09-05", + "po": "PO1", + "state": "posted", + "unit_price_cents": 12078, + "units": 17, + "vendor": "V0" + }, + "IV-3914-6-2": { + "date": "2025-09-07", + "po": "PO6", + "state": "void", + "unit_price_cents": 8669, + "units": 12, + "vendor": "Unknown" + }, + "IV-4018-5-3": { + "date": "2025-09-13", + "po": "PO5", + "state": "void", + "unit_price_cents": 2185, + "units": 18, + "vendor": "V2" + }, + "IV-4805-2-0": { + "date": "2025-09-01", + "po": "PO2", + "state": "posted", + "unit_price_cents": 9571, + "units": 10, + "vendor": "V2" + }, + "IV-5145-6-1": { + "date": "2025-09-02", + "po": "PO6", + "state": "review", + "unit_price_cents": 10087, + "units": 12, + "vendor": "V0" + }, + "IV-5313-3-0": { + "date": "2025-09-01", + "po": "PO3", + "state": "posted", + "unit_price_cents": 9903, + "units": 4, + "vendor": "V4" + }, + "IV-5395-0-1": { + "date": "2025-08-28", + "po": "PO0", + "state": "review", + "unit_price_cents": 11242, + "units": 18, + "vendor": "V1" + }, + "IV-5915-0-2": { + "date": "2025-08-29", + "po": "PO0", + "state": "void", + "unit_price_cents": 10505, + "units": 11, + "vendor": "V1" + }, + "IV-6603-1-0": { + "date": "2025-09-01", + "po": "PO1", + "state": "posted", + "unit_price_cents": 12252, + "units": 5, + "vendor": "V0" + }, + "IV-7380-2-2": { + "date": "2025-08-29", + "po": "PO2", + "state": "review", + "unit_price_cents": 9671, + "units": 6, + "vendor": "V2" + }, + "IV-7506-1-2": { + "date": "2025-09-08", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 13175, + "units": 14, + "vendor": "V0" + }, + "IV-8304-3-1": { + "date": "2025-09-06", + "po": "PO3", + "state": "posted", + "unit_price_cents": 9567, + "units": 20, + "vendor": "V4" + }, + "IV-9162-0-0": { + "date": "2025-09-01", + "po": "PO0", + "state": "posted", + "unit_price_cents": 9684, + "units": 1, + "vendor": "V1" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 9684, + "vendor": "V1" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 12252, + "vendor": "V0" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 9571, + "vendor": "V2" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 9903, + "vendor": "V4" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 17924, + "vendor": "V1" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 1621, + "vendor": "V2" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 8042, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-2764-4-1": { + "invoice": "IV-2764-4-1", + "issues": [ + "vendor", + "price" + ], + "po": "PO4" + }, + "case-IV-7506-1-2": { + "invoice": "IV-7506-1-2", + "issues": [ + "price" + ], + "po": "PO1" + } + }, + "vendors": { + "V0": { + "net_days": 45 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-010/tests/test.sh b/tasks/autom-supplier-invoice-match-010/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-010/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-010/tests/world.json b/tasks/autom-supplier-invoice-match-010/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..90caa5213e80cb588f42fa14f860f06e2e705a44 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-010/tests/world.json @@ -0,0 +1,446 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 2 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 6 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 4 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 2 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 4 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-09-14", + "po": "PO0", + "state": "accepted", + "units": 26 + }, + "GI-0-1": { + "date": "2025-09-12", + "po": "PO0", + "state": "quarantine", + "units": 13 + }, + "GI-0-2": { + "date": "2025-09-09", + "po": "PO0", + "state": "accepted", + "units": 15 + }, + "GI-0-3": { + "date": "2025-09-10", + "po": "PO0", + "state": "accepted", + "units": 18 + }, + "GI-1-0": { + "date": "2025-09-14", + "po": "PO1", + "state": "accepted", + "units": 17 + }, + "GI-1-1": { + "date": "2025-09-07", + "po": "PO1", + "state": "accepted", + "units": 24 + }, + "GI-1-2": { + "date": "2025-09-08", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-1-3": { + "date": "2025-09-02", + "po": "PO1", + "state": "accepted", + "units": 25 + }, + "GI-2-0": { + "date": "2025-09-14", + "po": "PO2", + "state": "accepted", + "units": 19 + }, + "GI-2-1": { + "date": "2025-09-09", + "po": "PO2", + "state": "accepted", + "units": 14 + }, + "GI-2-2": { + "date": "2025-08-22", + "po": "PO2", + "state": "accepted", + "units": 17 + }, + "GI-2-3": { + "date": "2025-09-16", + "po": "PO2", + "state": "quarantine", + "units": 25 + }, + "GI-3-0": { + "date": "2025-09-14", + "po": "PO3", + "state": "accepted", + "units": 28 + }, + "GI-3-1": { + "date": "2025-09-16", + "po": "PO3", + "state": "accepted", + "units": 20 + }, + "GI-3-2": { + "date": "2025-09-10", + "po": "PO3", + "state": "quarantine", + "units": 14 + }, + "GI-3-3": { + "date": "2025-09-08", + "po": "PO3", + "state": "quarantine", + "units": 12 + }, + "GI-4-0": { + "date": "2025-09-14", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-1": { + "date": "2025-09-09", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-4-2": { + "date": "2025-09-20", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-3": { + "date": "2025-08-27", + "po": "PO4", + "state": "quarantine", + "units": 24 + }, + "GI-5-0": { + "date": "2025-09-14", + "po": "PO5", + "state": "accepted", + "units": 22 + }, + "GI-5-1": { + "date": "2025-09-10", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-5-2": { + "date": "2025-08-26", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-3": { + "date": "2025-09-13", + "po": "PO5", + "state": "quarantine", + "units": 22 + }, + "GI-6-0": { + "date": "2025-09-14", + "po": "PO6", + "state": "accepted", + "units": 15 + }, + "GI-6-1": { + "date": "2025-09-05", + "po": "PO6", + "state": "accepted", + "units": 27 + }, + "GI-6-2": { + "date": "2025-09-04", + "po": "PO6", + "state": "accepted", + "units": 15 + }, + "GI-6-3": { + "date": "2025-08-22", + "po": "PO6", + "state": "quarantine", + "units": 26 + } + }, + "invoice_inbox": { + "IV-1121-4-0": { + "date": "2025-09-01", + "po": "PO4", + "state": "review", + "unit_price_cents": 17924, + "units": 13, + "vendor": "V1" + }, + "IV-1208-6-0": { + "date": "2025-09-01", + "po": "PO6", + "state": "review", + "unit_price_cents": 8042, + "units": 3, + "vendor": "V0" + }, + "IV-1673-5-0": { + "date": "2025-09-01", + "po": "PO5", + "state": "review", + "unit_price_cents": 1621, + "units": 22, + "vendor": "V2" + }, + "IV-1942-2-3": { + "date": "2025-08-26", + "po": "PO2", + "state": "review", + "unit_price_cents": 10900, + "units": 25, + "vendor": "V2" + }, + "IV-1960-5-1": { + "date": "2025-09-10", + "po": "PO5", + "state": "void", + "unit_price_cents": 1254, + "units": 22, + "vendor": "V2" + }, + "IV-2764-4-1": { + "date": "2025-09-06", + "po": "PO4", + "state": "review", + "unit_price_cents": 19899, + "units": 12, + "vendor": "Unknown" + }, + "IV-2815-2-1": { + "date": "2025-08-27", + "po": "PO2", + "state": "review", + "unit_price_cents": 11257, + "units": 17, + "vendor": "Unknown" + }, + "IV-3112-5-2": { + "date": "2025-08-28", + "po": "PO5", + "state": "review", + "unit_price_cents": 3159, + "units": 9, + "vendor": "V2" + }, + "IV-3145-6-3": { + "date": "2025-08-30", + "po": "PO6", + "state": "void", + "unit_price_cents": 8002, + "units": 19, + "vendor": "V0" + }, + "IV-3547-1-1": { + "date": "2025-09-05", + "po": "PO1", + "state": "review", + "unit_price_cents": 12078, + "units": 17, + "vendor": "V0" + }, + "IV-3914-6-2": { + "date": "2025-09-07", + "po": "PO6", + "state": "void", + "unit_price_cents": 8669, + "units": 12, + "vendor": "Unknown" + }, + "IV-4018-5-3": { + "date": "2025-09-13", + "po": "PO5", + "state": "void", + "unit_price_cents": 2185, + "units": 18, + "vendor": "V2" + }, + "IV-4805-2-0": { + "date": "2025-09-01", + "po": "PO2", + "state": "review", + "unit_price_cents": 9571, + "units": 10, + "vendor": "V2" + }, + "IV-5145-6-1": { + "date": "2025-09-02", + "po": "PO6", + "state": "review", + "unit_price_cents": 10087, + "units": 12, + "vendor": "V0" + }, + "IV-5313-3-0": { + "date": "2025-09-01", + "po": "PO3", + "state": "review", + "unit_price_cents": 9903, + "units": 4, + "vendor": "V4" + }, + "IV-5395-0-1": { + "date": "2025-08-28", + "po": "PO0", + "state": "review", + "unit_price_cents": 11242, + "units": 18, + "vendor": "V1" + }, + "IV-5915-0-2": { + "date": "2025-08-29", + "po": "PO0", + "state": "void", + "unit_price_cents": 10505, + "units": 11, + "vendor": "V1" + }, + "IV-6603-1-0": { + "date": "2025-09-01", + "po": "PO1", + "state": "review", + "unit_price_cents": 12252, + "units": 5, + "vendor": "V0" + }, + "IV-7380-2-2": { + "date": "2025-08-29", + "po": "PO2", + "state": "review", + "unit_price_cents": 9671, + "units": 6, + "vendor": "V2" + }, + "IV-7506-1-2": { + "date": "2025-09-08", + "po": "PO1", + "state": "review", + "unit_price_cents": 13175, + "units": 14, + "vendor": "V0" + }, + "IV-8304-3-1": { + "date": "2025-09-06", + "po": "PO3", + "state": "review", + "unit_price_cents": 9567, + "units": 20, + "vendor": "V4" + }, + "IV-9162-0-0": { + "date": "2025-09-01", + "po": "PO0", + "state": "review", + "unit_price_cents": 9684, + "units": 1, + "vendor": "V1" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 9684, + "vendor": "V1" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 12252, + "vendor": "V0" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 9571, + "vendor": "V2" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 9903, + "vendor": "V4" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 17924, + "vendor": "V1" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 1621, + "vendor": "V2" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 8042, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 45 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-010/tests/world_check.py b/tasks/autom-supplier-invoice-match-010/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-010/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-010/validation/openenv.json b/tasks/autom-supplier-invoice-match-010/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-010/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-011/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-011/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-011/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-011/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-011/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..fcea2302956acfe755b31b1ab4d75a871a4c2208 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-011/environment/inputs/world.json @@ -0,0 +1,398 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 4 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 5 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 8 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 8 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 4 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 1 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-10-07", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-1": { + "date": "2025-09-19", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-0-2": { + "date": "2025-09-17", + "po": "PO0", + "state": "accepted", + "units": 26 + }, + "GI-0-3": { + "date": "2025-09-16", + "po": "PO0", + "state": "quarantine", + "units": 13 + }, + "GI-1-0": { + "date": "2025-10-07", + "po": "PO1", + "state": "accepted", + "units": 14 + }, + "GI-1-1": { + "date": "2025-10-03", + "po": "PO1", + "state": "quarantine", + "units": 14 + }, + "GI-1-2": { + "date": "2025-09-30", + "po": "PO1", + "state": "quarantine", + "units": 17 + }, + "GI-1-3": { + "date": "2025-10-03", + "po": "PO1", + "state": "quarantine", + "units": 20 + }, + "GI-2-0": { + "date": "2025-10-07", + "po": "PO2", + "state": "accepted", + "units": 24 + }, + "GI-2-1": { + "date": "2025-09-27", + "po": "PO2", + "state": "quarantine", + "units": 21 + }, + "GI-2-2": { + "date": "2025-10-12", + "po": "PO2", + "state": "quarantine", + "units": 28 + }, + "GI-2-3": { + "date": "2025-09-22", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-3-0": { + "date": "2025-10-07", + "po": "PO3", + "state": "accepted", + "units": 16 + }, + "GI-3-1": { + "date": "2025-10-05", + "po": "PO3", + "state": "quarantine", + "units": 21 + }, + "GI-3-2": { + "date": "2025-10-06", + "po": "PO3", + "state": "accepted", + "units": 19 + }, + "GI-3-3": { + "date": "2025-09-28", + "po": "PO3", + "state": "quarantine", + "units": 14 + }, + "GI-4-0": { + "date": "2025-10-07", + "po": "PO4", + "state": "accepted", + "units": 28 + }, + "GI-4-1": { + "date": "2025-09-23", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-4-2": { + "date": "2025-10-06", + "po": "PO4", + "state": "quarantine", + "units": 23 + }, + "GI-4-3": { + "date": "2025-10-12", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-5-0": { + "date": "2025-10-07", + "po": "PO5", + "state": "accepted", + "units": 22 + }, + "GI-5-1": { + "date": "2025-10-05", + "po": "PO5", + "state": "quarantine", + "units": 22 + }, + "GI-5-2": { + "date": "2025-09-23", + "po": "PO5", + "state": "accepted", + "units": 23 + }, + "GI-5-3": { + "date": "2025-10-10", + "po": "PO5", + "state": "quarantine", + "units": 17 + }, + "GI-6-0": { + "date": "2025-10-07", + "po": "PO6", + "state": "accepted", + "units": 14 + }, + "GI-6-1": { + "date": "2025-10-01", + "po": "PO6", + "state": "accepted", + "units": 13 + }, + "GI-6-2": { + "date": "2025-10-08", + "po": "PO6", + "state": "accepted", + "units": 12 + }, + "GI-6-3": { + "date": "2025-09-14", + "po": "PO6", + "state": "quarantine", + "units": 22 + } + }, + "invoice_inbox": { + "IV-1334-4-0": { + "date": "2025-09-24", + "po": "PO4", + "state": "review", + "unit_price_cents": 14638, + "units": 9, + "vendor": "V1" + }, + "IV-2153-1-0": { + "date": "2025-09-24", + "po": "PO1", + "state": "review", + "unit_price_cents": 20655, + "units": 8, + "vendor": "V4" + }, + "IV-2781-0-1": { + "date": "2025-10-05", + "po": "PO0", + "state": "void", + "unit_price_cents": 5848, + "units": 18, + "vendor": "V4" + }, + "IV-2933-0-2": { + "date": "2025-09-25", + "po": "PO0", + "state": "review", + "unit_price_cents": 7430, + "units": 5, + "vendor": "V4" + }, + "IV-3552-0-0": { + "date": "2025-09-24", + "po": "PO0", + "state": "review", + "unit_price_cents": 5813, + "units": 1, + "vendor": "V4" + }, + "IV-3593-6-2": { + "date": "2025-09-18", + "po": "PO6", + "state": "review", + "unit_price_cents": 11607, + "units": 15, + "vendor": "V1" + }, + "IV-3774-6-1": { + "date": "2025-10-01", + "po": "PO6", + "state": "review", + "unit_price_cents": 10525, + "units": 7, + "vendor": "V1" + }, + "IV-4767-2-0": { + "date": "2025-09-24", + "po": "PO2", + "state": "review", + "unit_price_cents": 17886, + "units": 17, + "vendor": "V2" + }, + "IV-5330-5-1": { + "date": "2025-09-27", + "po": "PO5", + "state": "review", + "unit_price_cents": 22682, + "units": 4, + "vendor": "V2" + }, + "IV-5377-4-1": { + "date": "2025-10-04", + "po": "PO4", + "state": "review", + "unit_price_cents": 16044, + "units": 12, + "vendor": "Unknown" + }, + "IV-5439-3-1": { + "date": "2025-10-09", + "po": "PO3", + "state": "review", + "unit_price_cents": 23248, + "units": 19, + "vendor": "V3" + }, + "IV-5831-3-0": { + "date": "2025-09-24", + "po": "PO3", + "state": "review", + "unit_price_cents": 22729, + "units": 21, + "vendor": "V3" + }, + "IV-7311-5-0": { + "date": "2025-09-24", + "po": "PO5", + "state": "review", + "unit_price_cents": 22413, + "units": 10, + "vendor": "V2" + }, + "IV-7466-2-1": { + "date": "2025-09-28", + "po": "PO2", + "state": "void", + "unit_price_cents": 17667, + "units": 9, + "vendor": "V2" + }, + "IV-7884-1-1": { + "date": "2025-09-18", + "po": "PO1", + "state": "review", + "unit_price_cents": 21929, + "units": 6, + "vendor": "V4" + }, + "IV-8927-6-0": { + "date": "2025-09-24", + "po": "PO6", + "state": "review", + "unit_price_cents": 10535, + "units": 7, + "vendor": "V1" + } + }, + "purchase_orders": { + "PO0": { + "unit": "West", + "unit_price_cents": 5813, + "vendor": "V4" + }, + "PO1": { + "unit": "West", + "unit_price_cents": 20655, + "vendor": "V4" + }, + "PO2": { + "unit": "West", + "unit_price_cents": 17886, + "vendor": "V2" + }, + "PO3": { + "unit": "West", + "unit_price_cents": 22729, + "vendor": "V3" + }, + "PO4": { + "unit": "West", + "unit_price_cents": 14638, + "vendor": "V1" + }, + "PO5": { + "unit": "West", + "unit_price_cents": 22413, + "vendor": "V2" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 10535, + "vendor": "V1" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 15 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-011/instruction.md b/tasks/autom-supplier-invoice-match-011/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a533927d796f891f78096a904dd9976be26b61df --- /dev/null +++ b/tasks/autom-supplier-invoice-match-011/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit West at 2025-10-08. Handle invoices in review attached to that unit's purchase orders, invoice dates 2025-09-24 through 2025-10-08 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 200 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-011/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-011/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2ba6c382a5fe5340ec0ea00317df7f5b01403e37 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-011/solution/files/actions.jsonl @@ -0,0 +1,18 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-3552-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-2933-0-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-2153-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-4767-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5831-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-1334-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-5377-4-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-7311-5-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5330-5-1", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 131742, "due": "2025-10-09", "invoice": "IV-1334-4-0", "po": "PO4", "status": "posted", "units": 9}, "id": "book-IV-1334-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 165240, "due": "2025-10-24", "invoice": "IV-2153-1-0", "po": "PO1", "status": "posted", "units": 8}, "id": "book-IV-2153-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 5813, "due": "2025-10-24", "invoice": "IV-3552-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-3552-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 304062, "due": "2025-10-24", "invoice": "IV-4767-2-0", "po": "PO2", "status": "posted", "units": 17}, "id": "book-IV-4767-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 477309, "due": "2025-11-10", "invoice": "IV-5831-3-0", "po": "PO3", "status": "posted", "units": 21}, "id": "book-IV-5831-3-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 224130, "due": "2025-10-24", "invoice": "IV-7311-5-0", "po": "PO5", "status": "posted", "units": 10}, "id": "book-IV-7311-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 90728, "due": "2025-10-27", "invoice": "IV-5330-5-1", "po": "PO5", "status": "posted", "units": 4}, "id": "book-IV-5330-5-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-2933-0-2", "issues": ["price"], "po": "PO0"}, "id": "case-IV-2933-0-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-5377-4-1", "issues": ["vendor", "price"], "po": "PO4"}, "id": "case-IV-5377-4-1", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-011/solution/solve.sh b/tasks/autom-supplier-invoice-match-011/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-011/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-011/task.toml b/tasks/autom-supplier-invoice-match-011/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..51f929a581f3c6472a88bcb5e04b0f97499c9f3a --- /dev/null +++ b/tasks/autom-supplier-invoice-match-011/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-011" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 11 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-011" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-011/tests/expected.json b/tasks/autom-supplier-invoice-match-011/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-011/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-011/tests/grade.py b/tasks/autom-supplier-invoice-match-011/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-011/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-011/tests/replay.py b/tasks/autom-supplier-invoice-match-011/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-011/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-011/tests/target.json b/tasks/autom-supplier-invoice-match-011/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..0afce74d3ebbdd12498d2c910151a1b743260690 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-011/tests/target.json @@ -0,0 +1,469 @@ +{ + "ap_postings": { + "book-IV-1334-4-0": { + "amount_cents": 131742, + "due": "2025-10-09", + "invoice": "IV-1334-4-0", + "po": "PO4", + "status": "posted", + "units": 9 + }, + "book-IV-2153-1-0": { + "amount_cents": 165240, + "due": "2025-10-24", + "invoice": "IV-2153-1-0", + "po": "PO1", + "status": "posted", + "units": 8 + }, + "book-IV-3552-0-0": { + "amount_cents": 5813, + "due": "2025-10-24", + "invoice": "IV-3552-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "book-IV-4767-2-0": { + "amount_cents": 304062, + "due": "2025-10-24", + "invoice": "IV-4767-2-0", + "po": "PO2", + "status": "posted", + "units": 17 + }, + "book-IV-5330-5-1": { + "amount_cents": 90728, + "due": "2025-10-27", + "invoice": "IV-5330-5-1", + "po": "PO5", + "status": "posted", + "units": 4 + }, + "book-IV-5831-3-0": { + "amount_cents": 477309, + "due": "2025-11-10", + "invoice": "IV-5831-3-0", + "po": "PO3", + "status": "posted", + "units": 21 + }, + "book-IV-7311-5-0": { + "amount_cents": 224130, + "due": "2025-10-24", + "invoice": "IV-7311-5-0", + "po": "PO5", + "status": "posted", + "units": 10 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 4 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 5 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 8 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 8 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 4 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 1 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-10-07", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-1": { + "date": "2025-09-19", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-0-2": { + "date": "2025-09-17", + "po": "PO0", + "state": "accepted", + "units": 26 + }, + "GI-0-3": { + "date": "2025-09-16", + "po": "PO0", + "state": "quarantine", + "units": 13 + }, + "GI-1-0": { + "date": "2025-10-07", + "po": "PO1", + "state": "accepted", + "units": 14 + }, + "GI-1-1": { + "date": "2025-10-03", + "po": "PO1", + "state": "quarantine", + "units": 14 + }, + "GI-1-2": { + "date": "2025-09-30", + "po": "PO1", + "state": "quarantine", + "units": 17 + }, + "GI-1-3": { + "date": "2025-10-03", + "po": "PO1", + "state": "quarantine", + "units": 20 + }, + "GI-2-0": { + "date": "2025-10-07", + "po": "PO2", + "state": "accepted", + "units": 24 + }, + "GI-2-1": { + "date": "2025-09-27", + "po": "PO2", + "state": "quarantine", + "units": 21 + }, + "GI-2-2": { + "date": "2025-10-12", + "po": "PO2", + "state": "quarantine", + "units": 28 + }, + "GI-2-3": { + "date": "2025-09-22", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-3-0": { + "date": "2025-10-07", + "po": "PO3", + "state": "accepted", + "units": 16 + }, + "GI-3-1": { + "date": "2025-10-05", + "po": "PO3", + "state": "quarantine", + "units": 21 + }, + "GI-3-2": { + "date": "2025-10-06", + "po": "PO3", + "state": "accepted", + "units": 19 + }, + "GI-3-3": { + "date": "2025-09-28", + "po": "PO3", + "state": "quarantine", + "units": 14 + }, + "GI-4-0": { + "date": "2025-10-07", + "po": "PO4", + "state": "accepted", + "units": 28 + }, + "GI-4-1": { + "date": "2025-09-23", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-4-2": { + "date": "2025-10-06", + "po": "PO4", + "state": "quarantine", + "units": 23 + }, + "GI-4-3": { + "date": "2025-10-12", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-5-0": { + "date": "2025-10-07", + "po": "PO5", + "state": "accepted", + "units": 22 + }, + "GI-5-1": { + "date": "2025-10-05", + "po": "PO5", + "state": "quarantine", + "units": 22 + }, + "GI-5-2": { + "date": "2025-09-23", + "po": "PO5", + "state": "accepted", + "units": 23 + }, + "GI-5-3": { + "date": "2025-10-10", + "po": "PO5", + "state": "quarantine", + "units": 17 + }, + "GI-6-0": { + "date": "2025-10-07", + "po": "PO6", + "state": "accepted", + "units": 14 + }, + "GI-6-1": { + "date": "2025-10-01", + "po": "PO6", + "state": "accepted", + "units": 13 + }, + "GI-6-2": { + "date": "2025-10-08", + "po": "PO6", + "state": "accepted", + "units": 12 + }, + "GI-6-3": { + "date": "2025-09-14", + "po": "PO6", + "state": "quarantine", + "units": 22 + } + }, + "invoice_inbox": { + "IV-1334-4-0": { + "date": "2025-09-24", + "po": "PO4", + "state": "posted", + "unit_price_cents": 14638, + "units": 9, + "vendor": "V1" + }, + "IV-2153-1-0": { + "date": "2025-09-24", + "po": "PO1", + "state": "posted", + "unit_price_cents": 20655, + "units": 8, + "vendor": "V4" + }, + "IV-2781-0-1": { + "date": "2025-10-05", + "po": "PO0", + "state": "void", + "unit_price_cents": 5848, + "units": 18, + "vendor": "V4" + }, + "IV-2933-0-2": { + "date": "2025-09-25", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 7430, + "units": 5, + "vendor": "V4" + }, + "IV-3552-0-0": { + "date": "2025-09-24", + "po": "PO0", + "state": "posted", + "unit_price_cents": 5813, + "units": 1, + "vendor": "V4" + }, + "IV-3593-6-2": { + "date": "2025-09-18", + "po": "PO6", + "state": "review", + "unit_price_cents": 11607, + "units": 15, + "vendor": "V1" + }, + "IV-3774-6-1": { + "date": "2025-10-01", + "po": "PO6", + "state": "review", + "unit_price_cents": 10525, + "units": 7, + "vendor": "V1" + }, + "IV-4767-2-0": { + "date": "2025-09-24", + "po": "PO2", + "state": "posted", + "unit_price_cents": 17886, + "units": 17, + "vendor": "V2" + }, + "IV-5330-5-1": { + "date": "2025-09-27", + "po": "PO5", + "state": "posted", + "unit_price_cents": 22682, + "units": 4, + "vendor": "V2" + }, + "IV-5377-4-1": { + "date": "2025-10-04", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 16044, + "units": 12, + "vendor": "Unknown" + }, + "IV-5439-3-1": { + "date": "2025-10-09", + "po": "PO3", + "state": "review", + "unit_price_cents": 23248, + "units": 19, + "vendor": "V3" + }, + "IV-5831-3-0": { + "date": "2025-09-24", + "po": "PO3", + "state": "posted", + "unit_price_cents": 22729, + "units": 21, + "vendor": "V3" + }, + "IV-7311-5-0": { + "date": "2025-09-24", + "po": "PO5", + "state": "posted", + "unit_price_cents": 22413, + "units": 10, + "vendor": "V2" + }, + "IV-7466-2-1": { + "date": "2025-09-28", + "po": "PO2", + "state": "void", + "unit_price_cents": 17667, + "units": 9, + "vendor": "V2" + }, + "IV-7884-1-1": { + "date": "2025-09-18", + "po": "PO1", + "state": "review", + "unit_price_cents": 21929, + "units": 6, + "vendor": "V4" + }, + "IV-8927-6-0": { + "date": "2025-09-24", + "po": "PO6", + "state": "review", + "unit_price_cents": 10535, + "units": 7, + "vendor": "V1" + } + }, + "purchase_orders": { + "PO0": { + "unit": "West", + "unit_price_cents": 5813, + "vendor": "V4" + }, + "PO1": { + "unit": "West", + "unit_price_cents": 20655, + "vendor": "V4" + }, + "PO2": { + "unit": "West", + "unit_price_cents": 17886, + "vendor": "V2" + }, + "PO3": { + "unit": "West", + "unit_price_cents": 22729, + "vendor": "V3" + }, + "PO4": { + "unit": "West", + "unit_price_cents": 14638, + "vendor": "V1" + }, + "PO5": { + "unit": "West", + "unit_price_cents": 22413, + "vendor": "V2" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 10535, + "vendor": "V1" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-2933-0-2": { + "invoice": "IV-2933-0-2", + "issues": [ + "price" + ], + "po": "PO0" + }, + "case-IV-5377-4-1": { + "invoice": "IV-5377-4-1", + "issues": [ + "vendor", + "price" + ], + "po": "PO4" + } + }, + "vendors": { + "V0": { + "net_days": 15 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-011/tests/test.sh b/tasks/autom-supplier-invoice-match-011/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-011/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-011/tests/world.json b/tasks/autom-supplier-invoice-match-011/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..fcea2302956acfe755b31b1ab4d75a871a4c2208 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-011/tests/world.json @@ -0,0 +1,398 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 4 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 5 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 8 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 8 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 4 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 1 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-10-07", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-1": { + "date": "2025-09-19", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-0-2": { + "date": "2025-09-17", + "po": "PO0", + "state": "accepted", + "units": 26 + }, + "GI-0-3": { + "date": "2025-09-16", + "po": "PO0", + "state": "quarantine", + "units": 13 + }, + "GI-1-0": { + "date": "2025-10-07", + "po": "PO1", + "state": "accepted", + "units": 14 + }, + "GI-1-1": { + "date": "2025-10-03", + "po": "PO1", + "state": "quarantine", + "units": 14 + }, + "GI-1-2": { + "date": "2025-09-30", + "po": "PO1", + "state": "quarantine", + "units": 17 + }, + "GI-1-3": { + "date": "2025-10-03", + "po": "PO1", + "state": "quarantine", + "units": 20 + }, + "GI-2-0": { + "date": "2025-10-07", + "po": "PO2", + "state": "accepted", + "units": 24 + }, + "GI-2-1": { + "date": "2025-09-27", + "po": "PO2", + "state": "quarantine", + "units": 21 + }, + "GI-2-2": { + "date": "2025-10-12", + "po": "PO2", + "state": "quarantine", + "units": 28 + }, + "GI-2-3": { + "date": "2025-09-22", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-3-0": { + "date": "2025-10-07", + "po": "PO3", + "state": "accepted", + "units": 16 + }, + "GI-3-1": { + "date": "2025-10-05", + "po": "PO3", + "state": "quarantine", + "units": 21 + }, + "GI-3-2": { + "date": "2025-10-06", + "po": "PO3", + "state": "accepted", + "units": 19 + }, + "GI-3-3": { + "date": "2025-09-28", + "po": "PO3", + "state": "quarantine", + "units": 14 + }, + "GI-4-0": { + "date": "2025-10-07", + "po": "PO4", + "state": "accepted", + "units": 28 + }, + "GI-4-1": { + "date": "2025-09-23", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-4-2": { + "date": "2025-10-06", + "po": "PO4", + "state": "quarantine", + "units": 23 + }, + "GI-4-3": { + "date": "2025-10-12", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-5-0": { + "date": "2025-10-07", + "po": "PO5", + "state": "accepted", + "units": 22 + }, + "GI-5-1": { + "date": "2025-10-05", + "po": "PO5", + "state": "quarantine", + "units": 22 + }, + "GI-5-2": { + "date": "2025-09-23", + "po": "PO5", + "state": "accepted", + "units": 23 + }, + "GI-5-3": { + "date": "2025-10-10", + "po": "PO5", + "state": "quarantine", + "units": 17 + }, + "GI-6-0": { + "date": "2025-10-07", + "po": "PO6", + "state": "accepted", + "units": 14 + }, + "GI-6-1": { + "date": "2025-10-01", + "po": "PO6", + "state": "accepted", + "units": 13 + }, + "GI-6-2": { + "date": "2025-10-08", + "po": "PO6", + "state": "accepted", + "units": 12 + }, + "GI-6-3": { + "date": "2025-09-14", + "po": "PO6", + "state": "quarantine", + "units": 22 + } + }, + "invoice_inbox": { + "IV-1334-4-0": { + "date": "2025-09-24", + "po": "PO4", + "state": "review", + "unit_price_cents": 14638, + "units": 9, + "vendor": "V1" + }, + "IV-2153-1-0": { + "date": "2025-09-24", + "po": "PO1", + "state": "review", + "unit_price_cents": 20655, + "units": 8, + "vendor": "V4" + }, + "IV-2781-0-1": { + "date": "2025-10-05", + "po": "PO0", + "state": "void", + "unit_price_cents": 5848, + "units": 18, + "vendor": "V4" + }, + "IV-2933-0-2": { + "date": "2025-09-25", + "po": "PO0", + "state": "review", + "unit_price_cents": 7430, + "units": 5, + "vendor": "V4" + }, + "IV-3552-0-0": { + "date": "2025-09-24", + "po": "PO0", + "state": "review", + "unit_price_cents": 5813, + "units": 1, + "vendor": "V4" + }, + "IV-3593-6-2": { + "date": "2025-09-18", + "po": "PO6", + "state": "review", + "unit_price_cents": 11607, + "units": 15, + "vendor": "V1" + }, + "IV-3774-6-1": { + "date": "2025-10-01", + "po": "PO6", + "state": "review", + "unit_price_cents": 10525, + "units": 7, + "vendor": "V1" + }, + "IV-4767-2-0": { + "date": "2025-09-24", + "po": "PO2", + "state": "review", + "unit_price_cents": 17886, + "units": 17, + "vendor": "V2" + }, + "IV-5330-5-1": { + "date": "2025-09-27", + "po": "PO5", + "state": "review", + "unit_price_cents": 22682, + "units": 4, + "vendor": "V2" + }, + "IV-5377-4-1": { + "date": "2025-10-04", + "po": "PO4", + "state": "review", + "unit_price_cents": 16044, + "units": 12, + "vendor": "Unknown" + }, + "IV-5439-3-1": { + "date": "2025-10-09", + "po": "PO3", + "state": "review", + "unit_price_cents": 23248, + "units": 19, + "vendor": "V3" + }, + "IV-5831-3-0": { + "date": "2025-09-24", + "po": "PO3", + "state": "review", + "unit_price_cents": 22729, + "units": 21, + "vendor": "V3" + }, + "IV-7311-5-0": { + "date": "2025-09-24", + "po": "PO5", + "state": "review", + "unit_price_cents": 22413, + "units": 10, + "vendor": "V2" + }, + "IV-7466-2-1": { + "date": "2025-09-28", + "po": "PO2", + "state": "void", + "unit_price_cents": 17667, + "units": 9, + "vendor": "V2" + }, + "IV-7884-1-1": { + "date": "2025-09-18", + "po": "PO1", + "state": "review", + "unit_price_cents": 21929, + "units": 6, + "vendor": "V4" + }, + "IV-8927-6-0": { + "date": "2025-09-24", + "po": "PO6", + "state": "review", + "unit_price_cents": 10535, + "units": 7, + "vendor": "V1" + } + }, + "purchase_orders": { + "PO0": { + "unit": "West", + "unit_price_cents": 5813, + "vendor": "V4" + }, + "PO1": { + "unit": "West", + "unit_price_cents": 20655, + "vendor": "V4" + }, + "PO2": { + "unit": "West", + "unit_price_cents": 17886, + "vendor": "V2" + }, + "PO3": { + "unit": "West", + "unit_price_cents": 22729, + "vendor": "V3" + }, + "PO4": { + "unit": "West", + "unit_price_cents": 14638, + "vendor": "V1" + }, + "PO5": { + "unit": "West", + "unit_price_cents": 22413, + "vendor": "V2" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 10535, + "vendor": "V1" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 15 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-011/tests/world_check.py b/tasks/autom-supplier-invoice-match-011/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-011/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-011/validation/openenv.json b/tasks/autom-supplier-invoice-match-011/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-011/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-012/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-012/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-012/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-012/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-012/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..c7f294765493754464435a16a96b458db2387e77 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-012/environment/inputs/world.json @@ -0,0 +1,430 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 3 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 8 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 1 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 4 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 2 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 5 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-10-30", + "po": "PO0", + "state": "accepted", + "units": 24 + }, + "GI-0-1": { + "date": "2025-10-07", + "po": "PO0", + "state": "quarantine", + "units": 15 + }, + "GI-0-2": { + "date": "2025-10-27", + "po": "PO0", + "state": "quarantine", + "units": 24 + }, + "GI-0-3": { + "date": "2025-11-05", + "po": "PO0", + "state": "quarantine", + "units": 14 + }, + "GI-1-0": { + "date": "2025-10-30", + "po": "PO1", + "state": "accepted", + "units": 27 + }, + "GI-1-1": { + "date": "2025-10-07", + "po": "PO1", + "state": "quarantine", + "units": 27 + }, + "GI-1-2": { + "date": "2025-11-03", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-1-3": { + "date": "2025-10-09", + "po": "PO1", + "state": "accepted", + "units": 21 + }, + "GI-2-0": { + "date": "2025-10-30", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-2-1": { + "date": "2025-10-15", + "po": "PO2", + "state": "quarantine", + "units": 22 + }, + "GI-2-2": { + "date": "2025-10-24", + "po": "PO2", + "state": "quarantine", + "units": 24 + }, + "GI-2-3": { + "date": "2025-10-19", + "po": "PO2", + "state": "accepted", + "units": 22 + }, + "GI-3-0": { + "date": "2025-10-30", + "po": "PO3", + "state": "accepted", + "units": 22 + }, + "GI-3-1": { + "date": "2025-10-26", + "po": "PO3", + "state": "accepted", + "units": 21 + }, + "GI-3-2": { + "date": "2025-10-12", + "po": "PO3", + "state": "quarantine", + "units": 27 + }, + "GI-3-3": { + "date": "2025-10-31", + "po": "PO3", + "state": "quarantine", + "units": 16 + }, + "GI-4-0": { + "date": "2025-10-30", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-1": { + "date": "2025-10-07", + "po": "PO4", + "state": "quarantine", + "units": 14 + }, + "GI-4-2": { + "date": "2025-10-28", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-4-3": { + "date": "2025-11-02", + "po": "PO4", + "state": "quarantine", + "units": 21 + }, + "GI-5-0": { + "date": "2025-10-30", + "po": "PO5", + "state": "accepted", + "units": 25 + }, + "GI-5-1": { + "date": "2025-10-10", + "po": "PO5", + "state": "quarantine", + "units": 22 + }, + "GI-5-2": { + "date": "2025-10-15", + "po": "PO5", + "state": "quarantine", + "units": 24 + }, + "GI-5-3": { + "date": "2025-10-10", + "po": "PO5", + "state": "quarantine", + "units": 25 + }, + "GI-6-0": { + "date": "2025-10-30", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-1": { + "date": "2025-10-22", + "po": "PO6", + "state": "accepted", + "units": 20 + }, + "GI-6-2": { + "date": "2025-10-28", + "po": "PO6", + "state": "accepted", + "units": 17 + }, + "GI-6-3": { + "date": "2025-10-08", + "po": "PO6", + "state": "accepted", + "units": 16 + } + }, + "invoice_inbox": { + "IV-1290-2-0": { + "date": "2025-10-03", + "po": "PO2", + "state": "review", + "unit_price_cents": 12973, + "units": 17, + "vendor": "V3" + }, + "IV-1952-2-1": { + "date": "2025-10-15", + "po": "PO2", + "state": "void", + "unit_price_cents": 14994, + "units": 21, + "vendor": "V3" + }, + "IV-2121-5-0": { + "date": "2025-10-03", + "po": "PO5", + "state": "review", + "unit_price_cents": 15274, + "units": 19, + "vendor": "V3" + }, + "IV-2254-0-1": { + "date": "2025-10-31", + "po": "PO0", + "state": "void", + "unit_price_cents": 3992, + "units": 4, + "vendor": "V0" + }, + "IV-3255-6-0": { + "date": "2025-10-03", + "po": "PO6", + "state": "review", + "unit_price_cents": 2779, + "units": 9, + "vendor": "V4" + }, + "IV-4250-2-3": { + "date": "2025-10-26", + "po": "PO2", + "state": "review", + "unit_price_cents": 12584, + "units": 10, + "vendor": "V3" + }, + "IV-4260-3-1": { + "date": "2025-10-04", + "po": "PO3", + "state": "review", + "unit_price_cents": 4237, + "units": 15, + "vendor": "V2" + }, + "IV-5479-6-1": { + "date": "2025-10-14", + "po": "PO6", + "state": "review", + "unit_price_cents": 2463, + "units": 19, + "vendor": "V4" + }, + "IV-5671-1-2": { + "date": "2025-10-15", + "po": "PO1", + "state": "review", + "unit_price_cents": 5391, + "units": 3, + "vendor": "V3" + }, + "IV-6130-1-0": { + "date": "2025-10-03", + "po": "PO1", + "state": "review", + "unit_price_cents": 4479, + "units": 16, + "vendor": "V3" + }, + "IV-6914-0-0": { + "date": "2025-10-03", + "po": "PO0", + "state": "review", + "unit_price_cents": 3001, + "units": 1, + "vendor": "V0" + }, + "IV-7116-3-2": { + "date": "2025-10-15", + "po": "PO3", + "state": "review", + "unit_price_cents": 4504, + "units": 12, + "vendor": "V2" + }, + "IV-7602-4-1": { + "date": "2025-10-14", + "po": "PO4", + "state": "review", + "unit_price_cents": 13523, + "units": 22, + "vendor": "V1" + }, + "IV-7953-5-1": { + "date": "2025-09-29", + "po": "PO5", + "state": "review", + "unit_price_cents": 16988, + "units": 12, + "vendor": "V3" + }, + "IV-8176-3-0": { + "date": "2025-10-03", + "po": "PO3", + "state": "review", + "unit_price_cents": 3099, + "units": 4, + "vendor": "V2" + }, + "IV-8342-5-2": { + "date": "2025-10-09", + "po": "PO5", + "state": "review", + "unit_price_cents": 15332, + "units": 25, + "vendor": "V3" + }, + "IV-8764-1-3": { + "date": "2025-10-27", + "po": "PO1", + "state": "review", + "unit_price_cents": 4299, + "units": 5, + "vendor": "V3" + }, + "IV-8898-1-1": { + "date": "2025-10-22", + "po": "PO1", + "state": "review", + "unit_price_cents": 4287, + "units": 6, + "vendor": "V3" + }, + "IV-9329-4-0": { + "date": "2025-10-03", + "po": "PO4", + "state": "review", + "unit_price_cents": 12278, + "units": 14, + "vendor": "V1" + }, + "IV-9489-2-2": { + "date": "2025-10-02", + "po": "PO2", + "state": "review", + "unit_price_cents": 15026, + "units": 9, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 3001, + "vendor": "V0" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 4479, + "vendor": "V3" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 12973, + "vendor": "V3" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 3099, + "vendor": "V2" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 12278, + "vendor": "V1" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 15274, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 2779, + "vendor": "V4" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 21 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 15 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-012/instruction.md b/tasks/autom-supplier-invoice-match-012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f30144c14f4683c44b6f73078461f67399a65ba9 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-012/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit South at 2025-10-31. Handle invoices in review attached to that unit's purchase orders, invoice dates 2025-10-03 through 2025-10-31 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 0 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-012/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-012/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..54f4faa396e3c8ccadedaf7a6e73aac630d06952 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-012/solution/files/actions.jsonl @@ -0,0 +1,28 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6914-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6130-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8898-1-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-5671-1-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8764-1-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-1290-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-4250-2-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8176-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4260-3-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7116-3-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-9329-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7602-4-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-2121-5-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-8342-5-2", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 220541, "due": "2025-10-20", "invoice": "IV-1290-2-0", "po": "PO2", "status": "posted", "units": 17}, "id": "book-IV-1290-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 290206, "due": "2025-10-20", "invoice": "IV-2121-5-0", "po": "PO5", "status": "posted", "units": 19}, "id": "book-IV-2121-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 71664, "due": "2025-10-20", "invoice": "IV-6130-1-0", "po": "PO1", "status": "posted", "units": 16}, "id": "book-IV-6130-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 3001, "due": "2025-10-24", "invoice": "IV-6914-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-6914-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 12396, "due": "2025-11-03", "invoice": "IV-8176-3-0", "po": "PO3", "status": "posted", "units": 4}, "id": "book-IV-8176-3-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 171892, "due": "2025-10-20", "invoice": "IV-9329-4-0", "po": "PO4", "status": "posted", "units": 14}, "id": "book-IV-9329-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 25722, "due": "2025-11-06", "invoice": "IV-8898-1-1", "po": "PO1", "status": "posted", "units": 6}, "id": "book-IV-8898-1-1", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 125840, "due": "2025-11-10", "invoice": "IV-4250-2-3", "po": "PO2", "status": "posted", "units": 10}, "id": "book-IV-4250-2-3", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 21495, "due": "2025-11-11", "invoice": "IV-8764-1-3", "po": "PO1", "status": "posted", "units": 5}, "id": "book-IV-8764-1-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4260-3-1", "issues": ["price"], "po": "PO3"}, "id": "case-IV-4260-3-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-8342-5-2", "issues": ["price", "units"], "po": "PO5"}, "id": "case-IV-8342-5-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7602-4-1", "issues": ["price"], "po": "PO4"}, "id": "case-IV-7602-4-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-5671-1-2", "issues": ["price"], "po": "PO1"}, "id": "case-IV-5671-1-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7116-3-2", "issues": ["price"], "po": "PO3"}, "id": "case-IV-7116-3-2", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-012/solution/solve.sh b/tasks/autom-supplier-invoice-match-012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-012/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-012/task.toml b/tasks/autom-supplier-invoice-match-012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..490a699d995bf3917d12b6105f0ed36169d60fd2 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-012/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-012" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 12 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-012" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-012/tests/expected.json b/tasks/autom-supplier-invoice-match-012/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-012/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-012/tests/grade.py b/tasks/autom-supplier-invoice-match-012/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-012/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-012/tests/replay.py b/tasks/autom-supplier-invoice-match-012/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-012/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-012/tests/target.json b/tasks/autom-supplier-invoice-match-012/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..9e8d24090160244fb6d29e5ca9755d7393584df1 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-012/tests/target.json @@ -0,0 +1,538 @@ +{ + "ap_postings": { + "book-IV-1290-2-0": { + "amount_cents": 220541, + "due": "2025-10-20", + "invoice": "IV-1290-2-0", + "po": "PO2", + "status": "posted", + "units": 17 + }, + "book-IV-2121-5-0": { + "amount_cents": 290206, + "due": "2025-10-20", + "invoice": "IV-2121-5-0", + "po": "PO5", + "status": "posted", + "units": 19 + }, + "book-IV-4250-2-3": { + "amount_cents": 125840, + "due": "2025-11-10", + "invoice": "IV-4250-2-3", + "po": "PO2", + "status": "posted", + "units": 10 + }, + "book-IV-6130-1-0": { + "amount_cents": 71664, + "due": "2025-10-20", + "invoice": "IV-6130-1-0", + "po": "PO1", + "status": "posted", + "units": 16 + }, + "book-IV-6914-0-0": { + "amount_cents": 3001, + "due": "2025-10-24", + "invoice": "IV-6914-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "book-IV-8176-3-0": { + "amount_cents": 12396, + "due": "2025-11-03", + "invoice": "IV-8176-3-0", + "po": "PO3", + "status": "posted", + "units": 4 + }, + "book-IV-8764-1-3": { + "amount_cents": 21495, + "due": "2025-11-11", + "invoice": "IV-8764-1-3", + "po": "PO1", + "status": "posted", + "units": 5 + }, + "book-IV-8898-1-1": { + "amount_cents": 25722, + "due": "2025-11-06", + "invoice": "IV-8898-1-1", + "po": "PO1", + "status": "posted", + "units": 6 + }, + "book-IV-9329-4-0": { + "amount_cents": 171892, + "due": "2025-10-20", + "invoice": "IV-9329-4-0", + "po": "PO4", + "status": "posted", + "units": 14 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 3 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 8 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 1 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 4 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 2 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 5 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-10-30", + "po": "PO0", + "state": "accepted", + "units": 24 + }, + "GI-0-1": { + "date": "2025-10-07", + "po": "PO0", + "state": "quarantine", + "units": 15 + }, + "GI-0-2": { + "date": "2025-10-27", + "po": "PO0", + "state": "quarantine", + "units": 24 + }, + "GI-0-3": { + "date": "2025-11-05", + "po": "PO0", + "state": "quarantine", + "units": 14 + }, + "GI-1-0": { + "date": "2025-10-30", + "po": "PO1", + "state": "accepted", + "units": 27 + }, + "GI-1-1": { + "date": "2025-10-07", + "po": "PO1", + "state": "quarantine", + "units": 27 + }, + "GI-1-2": { + "date": "2025-11-03", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-1-3": { + "date": "2025-10-09", + "po": "PO1", + "state": "accepted", + "units": 21 + }, + "GI-2-0": { + "date": "2025-10-30", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-2-1": { + "date": "2025-10-15", + "po": "PO2", + "state": "quarantine", + "units": 22 + }, + "GI-2-2": { + "date": "2025-10-24", + "po": "PO2", + "state": "quarantine", + "units": 24 + }, + "GI-2-3": { + "date": "2025-10-19", + "po": "PO2", + "state": "accepted", + "units": 22 + }, + "GI-3-0": { + "date": "2025-10-30", + "po": "PO3", + "state": "accepted", + "units": 22 + }, + "GI-3-1": { + "date": "2025-10-26", + "po": "PO3", + "state": "accepted", + "units": 21 + }, + "GI-3-2": { + "date": "2025-10-12", + "po": "PO3", + "state": "quarantine", + "units": 27 + }, + "GI-3-3": { + "date": "2025-10-31", + "po": "PO3", + "state": "quarantine", + "units": 16 + }, + "GI-4-0": { + "date": "2025-10-30", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-1": { + "date": "2025-10-07", + "po": "PO4", + "state": "quarantine", + "units": 14 + }, + "GI-4-2": { + "date": "2025-10-28", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-4-3": { + "date": "2025-11-02", + "po": "PO4", + "state": "quarantine", + "units": 21 + }, + "GI-5-0": { + "date": "2025-10-30", + "po": "PO5", + "state": "accepted", + "units": 25 + }, + "GI-5-1": { + "date": "2025-10-10", + "po": "PO5", + "state": "quarantine", + "units": 22 + }, + "GI-5-2": { + "date": "2025-10-15", + "po": "PO5", + "state": "quarantine", + "units": 24 + }, + "GI-5-3": { + "date": "2025-10-10", + "po": "PO5", + "state": "quarantine", + "units": 25 + }, + "GI-6-0": { + "date": "2025-10-30", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-1": { + "date": "2025-10-22", + "po": "PO6", + "state": "accepted", + "units": 20 + }, + "GI-6-2": { + "date": "2025-10-28", + "po": "PO6", + "state": "accepted", + "units": 17 + }, + "GI-6-3": { + "date": "2025-10-08", + "po": "PO6", + "state": "accepted", + "units": 16 + } + }, + "invoice_inbox": { + "IV-1290-2-0": { + "date": "2025-10-03", + "po": "PO2", + "state": "posted", + "unit_price_cents": 12973, + "units": 17, + "vendor": "V3" + }, + "IV-1952-2-1": { + "date": "2025-10-15", + "po": "PO2", + "state": "void", + "unit_price_cents": 14994, + "units": 21, + "vendor": "V3" + }, + "IV-2121-5-0": { + "date": "2025-10-03", + "po": "PO5", + "state": "posted", + "unit_price_cents": 15274, + "units": 19, + "vendor": "V3" + }, + "IV-2254-0-1": { + "date": "2025-10-31", + "po": "PO0", + "state": "void", + "unit_price_cents": 3992, + "units": 4, + "vendor": "V0" + }, + "IV-3255-6-0": { + "date": "2025-10-03", + "po": "PO6", + "state": "review", + "unit_price_cents": 2779, + "units": 9, + "vendor": "V4" + }, + "IV-4250-2-3": { + "date": "2025-10-26", + "po": "PO2", + "state": "posted", + "unit_price_cents": 12584, + "units": 10, + "vendor": "V3" + }, + "IV-4260-3-1": { + "date": "2025-10-04", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 4237, + "units": 15, + "vendor": "V2" + }, + "IV-5479-6-1": { + "date": "2025-10-14", + "po": "PO6", + "state": "review", + "unit_price_cents": 2463, + "units": 19, + "vendor": "V4" + }, + "IV-5671-1-2": { + "date": "2025-10-15", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 5391, + "units": 3, + "vendor": "V3" + }, + "IV-6130-1-0": { + "date": "2025-10-03", + "po": "PO1", + "state": "posted", + "unit_price_cents": 4479, + "units": 16, + "vendor": "V3" + }, + "IV-6914-0-0": { + "date": "2025-10-03", + "po": "PO0", + "state": "posted", + "unit_price_cents": 3001, + "units": 1, + "vendor": "V0" + }, + "IV-7116-3-2": { + "date": "2025-10-15", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 4504, + "units": 12, + "vendor": "V2" + }, + "IV-7602-4-1": { + "date": "2025-10-14", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 13523, + "units": 22, + "vendor": "V1" + }, + "IV-7953-5-1": { + "date": "2025-09-29", + "po": "PO5", + "state": "review", + "unit_price_cents": 16988, + "units": 12, + "vendor": "V3" + }, + "IV-8176-3-0": { + "date": "2025-10-03", + "po": "PO3", + "state": "posted", + "unit_price_cents": 3099, + "units": 4, + "vendor": "V2" + }, + "IV-8342-5-2": { + "date": "2025-10-09", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 15332, + "units": 25, + "vendor": "V3" + }, + "IV-8764-1-3": { + "date": "2025-10-27", + "po": "PO1", + "state": "posted", + "unit_price_cents": 4299, + "units": 5, + "vendor": "V3" + }, + "IV-8898-1-1": { + "date": "2025-10-22", + "po": "PO1", + "state": "posted", + "unit_price_cents": 4287, + "units": 6, + "vendor": "V3" + }, + "IV-9329-4-0": { + "date": "2025-10-03", + "po": "PO4", + "state": "posted", + "unit_price_cents": 12278, + "units": 14, + "vendor": "V1" + }, + "IV-9489-2-2": { + "date": "2025-10-02", + "po": "PO2", + "state": "review", + "unit_price_cents": 15026, + "units": 9, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 3001, + "vendor": "V0" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 4479, + "vendor": "V3" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 12973, + "vendor": "V3" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 3099, + "vendor": "V2" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 12278, + "vendor": "V1" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 15274, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 2779, + "vendor": "V4" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-4260-3-1": { + "invoice": "IV-4260-3-1", + "issues": [ + "price" + ], + "po": "PO3" + }, + "case-IV-5671-1-2": { + "invoice": "IV-5671-1-2", + "issues": [ + "price" + ], + "po": "PO1" + }, + "case-IV-7116-3-2": { + "invoice": "IV-7116-3-2", + "issues": [ + "price" + ], + "po": "PO3" + }, + "case-IV-7602-4-1": { + "invoice": "IV-7602-4-1", + "issues": [ + "price" + ], + "po": "PO4" + }, + "case-IV-8342-5-2": { + "invoice": "IV-8342-5-2", + "issues": [ + "price", + "units" + ], + "po": "PO5" + } + }, + "vendors": { + "V0": { + "net_days": 21 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 15 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-012/tests/test.sh b/tasks/autom-supplier-invoice-match-012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-012/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-012/tests/world.json b/tasks/autom-supplier-invoice-match-012/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..c7f294765493754464435a16a96b458db2387e77 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-012/tests/world.json @@ -0,0 +1,430 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 3 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 8 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 1 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 4 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 2 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 5 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-10-30", + "po": "PO0", + "state": "accepted", + "units": 24 + }, + "GI-0-1": { + "date": "2025-10-07", + "po": "PO0", + "state": "quarantine", + "units": 15 + }, + "GI-0-2": { + "date": "2025-10-27", + "po": "PO0", + "state": "quarantine", + "units": 24 + }, + "GI-0-3": { + "date": "2025-11-05", + "po": "PO0", + "state": "quarantine", + "units": 14 + }, + "GI-1-0": { + "date": "2025-10-30", + "po": "PO1", + "state": "accepted", + "units": 27 + }, + "GI-1-1": { + "date": "2025-10-07", + "po": "PO1", + "state": "quarantine", + "units": 27 + }, + "GI-1-2": { + "date": "2025-11-03", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-1-3": { + "date": "2025-10-09", + "po": "PO1", + "state": "accepted", + "units": 21 + }, + "GI-2-0": { + "date": "2025-10-30", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-2-1": { + "date": "2025-10-15", + "po": "PO2", + "state": "quarantine", + "units": 22 + }, + "GI-2-2": { + "date": "2025-10-24", + "po": "PO2", + "state": "quarantine", + "units": 24 + }, + "GI-2-3": { + "date": "2025-10-19", + "po": "PO2", + "state": "accepted", + "units": 22 + }, + "GI-3-0": { + "date": "2025-10-30", + "po": "PO3", + "state": "accepted", + "units": 22 + }, + "GI-3-1": { + "date": "2025-10-26", + "po": "PO3", + "state": "accepted", + "units": 21 + }, + "GI-3-2": { + "date": "2025-10-12", + "po": "PO3", + "state": "quarantine", + "units": 27 + }, + "GI-3-3": { + "date": "2025-10-31", + "po": "PO3", + "state": "quarantine", + "units": 16 + }, + "GI-4-0": { + "date": "2025-10-30", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-1": { + "date": "2025-10-07", + "po": "PO4", + "state": "quarantine", + "units": 14 + }, + "GI-4-2": { + "date": "2025-10-28", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-4-3": { + "date": "2025-11-02", + "po": "PO4", + "state": "quarantine", + "units": 21 + }, + "GI-5-0": { + "date": "2025-10-30", + "po": "PO5", + "state": "accepted", + "units": 25 + }, + "GI-5-1": { + "date": "2025-10-10", + "po": "PO5", + "state": "quarantine", + "units": 22 + }, + "GI-5-2": { + "date": "2025-10-15", + "po": "PO5", + "state": "quarantine", + "units": 24 + }, + "GI-5-3": { + "date": "2025-10-10", + "po": "PO5", + "state": "quarantine", + "units": 25 + }, + "GI-6-0": { + "date": "2025-10-30", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-1": { + "date": "2025-10-22", + "po": "PO6", + "state": "accepted", + "units": 20 + }, + "GI-6-2": { + "date": "2025-10-28", + "po": "PO6", + "state": "accepted", + "units": 17 + }, + "GI-6-3": { + "date": "2025-10-08", + "po": "PO6", + "state": "accepted", + "units": 16 + } + }, + "invoice_inbox": { + "IV-1290-2-0": { + "date": "2025-10-03", + "po": "PO2", + "state": "review", + "unit_price_cents": 12973, + "units": 17, + "vendor": "V3" + }, + "IV-1952-2-1": { + "date": "2025-10-15", + "po": "PO2", + "state": "void", + "unit_price_cents": 14994, + "units": 21, + "vendor": "V3" + }, + "IV-2121-5-0": { + "date": "2025-10-03", + "po": "PO5", + "state": "review", + "unit_price_cents": 15274, + "units": 19, + "vendor": "V3" + }, + "IV-2254-0-1": { + "date": "2025-10-31", + "po": "PO0", + "state": "void", + "unit_price_cents": 3992, + "units": 4, + "vendor": "V0" + }, + "IV-3255-6-0": { + "date": "2025-10-03", + "po": "PO6", + "state": "review", + "unit_price_cents": 2779, + "units": 9, + "vendor": "V4" + }, + "IV-4250-2-3": { + "date": "2025-10-26", + "po": "PO2", + "state": "review", + "unit_price_cents": 12584, + "units": 10, + "vendor": "V3" + }, + "IV-4260-3-1": { + "date": "2025-10-04", + "po": "PO3", + "state": "review", + "unit_price_cents": 4237, + "units": 15, + "vendor": "V2" + }, + "IV-5479-6-1": { + "date": "2025-10-14", + "po": "PO6", + "state": "review", + "unit_price_cents": 2463, + "units": 19, + "vendor": "V4" + }, + "IV-5671-1-2": { + "date": "2025-10-15", + "po": "PO1", + "state": "review", + "unit_price_cents": 5391, + "units": 3, + "vendor": "V3" + }, + "IV-6130-1-0": { + "date": "2025-10-03", + "po": "PO1", + "state": "review", + "unit_price_cents": 4479, + "units": 16, + "vendor": "V3" + }, + "IV-6914-0-0": { + "date": "2025-10-03", + "po": "PO0", + "state": "review", + "unit_price_cents": 3001, + "units": 1, + "vendor": "V0" + }, + "IV-7116-3-2": { + "date": "2025-10-15", + "po": "PO3", + "state": "review", + "unit_price_cents": 4504, + "units": 12, + "vendor": "V2" + }, + "IV-7602-4-1": { + "date": "2025-10-14", + "po": "PO4", + "state": "review", + "unit_price_cents": 13523, + "units": 22, + "vendor": "V1" + }, + "IV-7953-5-1": { + "date": "2025-09-29", + "po": "PO5", + "state": "review", + "unit_price_cents": 16988, + "units": 12, + "vendor": "V3" + }, + "IV-8176-3-0": { + "date": "2025-10-03", + "po": "PO3", + "state": "review", + "unit_price_cents": 3099, + "units": 4, + "vendor": "V2" + }, + "IV-8342-5-2": { + "date": "2025-10-09", + "po": "PO5", + "state": "review", + "unit_price_cents": 15332, + "units": 25, + "vendor": "V3" + }, + "IV-8764-1-3": { + "date": "2025-10-27", + "po": "PO1", + "state": "review", + "unit_price_cents": 4299, + "units": 5, + "vendor": "V3" + }, + "IV-8898-1-1": { + "date": "2025-10-22", + "po": "PO1", + "state": "review", + "unit_price_cents": 4287, + "units": 6, + "vendor": "V3" + }, + "IV-9329-4-0": { + "date": "2025-10-03", + "po": "PO4", + "state": "review", + "unit_price_cents": 12278, + "units": 14, + "vendor": "V1" + }, + "IV-9489-2-2": { + "date": "2025-10-02", + "po": "PO2", + "state": "review", + "unit_price_cents": 15026, + "units": 9, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 3001, + "vendor": "V0" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 4479, + "vendor": "V3" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 12973, + "vendor": "V3" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 3099, + "vendor": "V2" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 12278, + "vendor": "V1" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 15274, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 2779, + "vendor": "V4" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 21 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 15 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-012/tests/world_check.py b/tasks/autom-supplier-invoice-match-012/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-012/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-012/validation/openenv.json b/tasks/autom-supplier-invoice-match-012/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-012/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-013/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-013/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-013/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-013/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-013/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..6c835a3d9673dbaa3fe91cd2ef1cde9723b51f74 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-013/environment/inputs/world.json @@ -0,0 +1,462 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 2 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 3 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 1 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 7 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 5 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 2 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 3 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-11-22", + "po": "PO0", + "state": "accepted", + "units": 22 + }, + "GI-0-1": { + "date": "2025-11-13", + "po": "PO0", + "state": "quarantine", + "units": 23 + }, + "GI-0-2": { + "date": "2025-11-13", + "po": "PO0", + "state": "quarantine", + "units": 15 + }, + "GI-0-3": { + "date": "2025-11-06", + "po": "PO0", + "state": "accepted", + "units": 13 + }, + "GI-1-0": { + "date": "2025-11-22", + "po": "PO1", + "state": "accepted", + "units": 18 + }, + "GI-1-1": { + "date": "2025-11-24", + "po": "PO1", + "state": "accepted", + "units": 21 + }, + "GI-1-2": { + "date": "2025-11-01", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-1-3": { + "date": "2025-11-10", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-2-0": { + "date": "2025-11-22", + "po": "PO2", + "state": "accepted", + "units": 28 + }, + "GI-2-1": { + "date": "2025-11-01", + "po": "PO2", + "state": "quarantine", + "units": 27 + }, + "GI-2-2": { + "date": "2025-11-24", + "po": "PO2", + "state": "quarantine", + "units": 28 + }, + "GI-2-3": { + "date": "2025-11-13", + "po": "PO2", + "state": "accepted", + "units": 19 + }, + "GI-3-0": { + "date": "2025-11-22", + "po": "PO3", + "state": "accepted", + "units": 16 + }, + "GI-3-1": { + "date": "2025-11-22", + "po": "PO3", + "state": "accepted", + "units": 25 + }, + "GI-3-2": { + "date": "2025-11-08", + "po": "PO3", + "state": "accepted", + "units": 26 + }, + "GI-3-3": { + "date": "2025-11-07", + "po": "PO3", + "state": "accepted", + "units": 17 + }, + "GI-4-0": { + "date": "2025-11-22", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-4-1": { + "date": "2025-11-27", + "po": "PO4", + "state": "accepted", + "units": 23 + }, + "GI-4-2": { + "date": "2025-11-14", + "po": "PO4", + "state": "quarantine", + "units": 13 + }, + "GI-4-3": { + "date": "2025-11-10", + "po": "PO4", + "state": "accepted", + "units": 25 + }, + "GI-5-0": { + "date": "2025-11-22", + "po": "PO5", + "state": "accepted", + "units": 24 + }, + "GI-5-1": { + "date": "2025-11-24", + "po": "PO5", + "state": "accepted", + "units": 22 + }, + "GI-5-2": { + "date": "2025-11-05", + "po": "PO5", + "state": "quarantine", + "units": 13 + }, + "GI-5-3": { + "date": "2025-11-27", + "po": "PO5", + "state": "accepted", + "units": 21 + }, + "GI-6-0": { + "date": "2025-11-22", + "po": "PO6", + "state": "accepted", + "units": 20 + }, + "GI-6-1": { + "date": "2025-10-31", + "po": "PO6", + "state": "quarantine", + "units": 13 + }, + "GI-6-2": { + "date": "2025-11-10", + "po": "PO6", + "state": "accepted", + "units": 12 + }, + "GI-6-3": { + "date": "2025-11-26", + "po": "PO6", + "state": "accepted", + "units": 14 + } + }, + "invoice_inbox": { + "IV-1064-5-0": { + "date": "2025-11-02", + "po": "PO5", + "state": "review", + "unit_price_cents": 16932, + "units": 17, + "vendor": "V3" + }, + "IV-1559-0-3": { + "date": "2025-11-07", + "po": "PO0", + "state": "review", + "unit_price_cents": 21849, + "units": 14, + "vendor": "V1" + }, + "IV-2063-2-0": { + "date": "2025-11-02", + "po": "PO2", + "state": "review", + "unit_price_cents": 3812, + "units": 15, + "vendor": "V2" + }, + "IV-2764-2-2": { + "date": "2025-11-16", + "po": "PO2", + "state": "review", + "unit_price_cents": 4587, + "units": 15, + "vendor": "V2" + }, + "IV-3164-0-2": { + "date": "2025-11-13", + "po": "PO0", + "state": "review", + "unit_price_cents": 21556, + "units": 8, + "vendor": "V1" + }, + "IV-3195-1-1": { + "date": "2025-11-23", + "po": "PO1", + "state": "review", + "unit_price_cents": 13135, + "units": 13, + "vendor": "V0" + }, + "IV-3741-4-0": { + "date": "2025-11-02", + "po": "PO4", + "state": "review", + "unit_price_cents": 22004, + "units": 13, + "vendor": "V0" + }, + "IV-3770-2-3": { + "date": "2025-11-07", + "po": "PO2", + "state": "review", + "unit_price_cents": 3653, + "units": 20, + "vendor": "V2" + }, + "IV-3852-6-0": { + "date": "2025-11-02", + "po": "PO6", + "state": "review", + "unit_price_cents": 21007, + "units": 12, + "vendor": "V2" + }, + "IV-4195-4-2": { + "date": "2025-11-23", + "po": "PO4", + "state": "void", + "unit_price_cents": 23299, + "units": 15, + "vendor": "Unknown" + }, + "IV-4210-5-1": { + "date": "2025-11-23", + "po": "PO5", + "state": "void", + "unit_price_cents": 18403, + "units": 9, + "vendor": "V3" + }, + "IV-4547-1-0": { + "date": "2025-11-02", + "po": "PO1", + "state": "review", + "unit_price_cents": 12135, + "units": 13, + "vendor": "V0" + }, + "IV-4813-0-0": { + "date": "2025-11-02", + "po": "PO0", + "state": "review", + "unit_price_cents": 20738, + "units": 1, + "vendor": "V1" + }, + "IV-5470-3-2": { + "date": "2025-11-18", + "po": "PO3", + "state": "review", + "unit_price_cents": 12160, + "units": 18, + "vendor": "V0" + }, + "IV-5503-2-1": { + "date": "2025-10-31", + "po": "PO2", + "state": "review", + "unit_price_cents": 5202, + "units": 12, + "vendor": "V2" + }, + "IV-5736-4-3": { + "date": "2025-11-21", + "po": "PO4", + "state": "review", + "unit_price_cents": 21884, + "units": 8, + "vendor": "V0" + }, + "IV-5787-6-2": { + "date": "2025-11-18", + "po": "PO6", + "state": "review", + "unit_price_cents": 22886, + "units": 24, + "vendor": "V2" + }, + "IV-5968-5-2": { + "date": "2025-10-31", + "po": "PO5", + "state": "review", + "unit_price_cents": 17674, + "units": 10, + "vendor": "V3" + }, + "IV-6053-3-0": { + "date": "2025-11-02", + "po": "PO3", + "state": "review", + "unit_price_cents": 10738, + "units": 14, + "vendor": "V0" + }, + "IV-6211-5-3": { + "date": "2025-11-21", + "po": "PO5", + "state": "void", + "unit_price_cents": 18729, + "units": 13, + "vendor": "V3" + }, + "IV-7196-3-1": { + "date": "2025-11-20", + "po": "PO3", + "state": "review", + "unit_price_cents": 12568, + "units": 11, + "vendor": "V0" + }, + "IV-7256-0-1": { + "date": "2025-11-11", + "po": "PO0", + "state": "review", + "unit_price_cents": 21447, + "units": 5, + "vendor": "V1" + }, + "IV-8846-4-1": { + "date": "2025-11-21", + "po": "PO4", + "state": "void", + "unit_price_cents": 21945, + "units": 11, + "vendor": "V0" + }, + "IV-9404-6-1": { + "date": "2025-11-14", + "po": "PO6", + "state": "void", + "unit_price_cents": 22733, + "units": 15, + "vendor": "V2" + } + }, + "purchase_orders": { + "PO0": { + "unit": "East", + "unit_price_cents": 20738, + "vendor": "V1" + }, + "PO1": { + "unit": "East", + "unit_price_cents": 12135, + "vendor": "V0" + }, + "PO2": { + "unit": "East", + "unit_price_cents": 3812, + "vendor": "V2" + }, + "PO3": { + "unit": "East", + "unit_price_cents": 10738, + "vendor": "V0" + }, + "PO4": { + "unit": "East", + "unit_price_cents": 22004, + "vendor": "V0" + }, + "PO5": { + "unit": "East", + "unit_price_cents": 16932, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 21007, + "vendor": "V2" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 45 + }, + "V1": { + "net_days": 30 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 15 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-013/instruction.md b/tasks/autom-supplier-invoice-match-013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..41eab560205bf1fc8920f96445298ce33fca8222 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-013/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit East at 2025-11-23. Handle invoices in review attached to that unit's purchase orders, invoice dates 2025-11-02 through 2025-11-23 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 200 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-013/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-013/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6b0c026c77dde19331afa857bd7bb0c0654a13a2 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-013/solution/files/actions.jsonl @@ -0,0 +1,30 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-4813-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7256-0-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3164-0-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-1559-0-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-4547-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3195-1-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-2063-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-2764-2-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-3770-2-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6053-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7196-3-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-5470-3-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-3741-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5736-4-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-1064-5-0", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 287844, "due": "2025-11-17", "invoice": "IV-1064-5-0", "po": "PO5", "status": "posted", "units": 17}, "id": "book-IV-1064-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 57180, "due": "2025-12-17", "invoice": "IV-2063-2-0", "po": "PO2", "status": "posted", "units": 15}, "id": "book-IV-2063-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 286052, "due": "2025-12-17", "invoice": "IV-3741-4-0", "po": "PO4", "status": "posted", "units": 13}, "id": "book-IV-3741-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 157755, "due": "2025-12-17", "invoice": "IV-4547-1-0", "po": "PO1", "status": "posted", "units": 13}, "id": "book-IV-4547-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 20738, "due": "2025-12-02", "invoice": "IV-4813-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-4813-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 150332, "due": "2025-12-17", "invoice": "IV-6053-3-0", "po": "PO3", "status": "posted", "units": 14}, "id": "book-IV-6053-3-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 73060, "due": "2025-12-22", "invoice": "IV-3770-2-3", "po": "PO2", "status": "posted", "units": 20}, "id": "book-IV-3770-2-3", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 175072, "due": "2026-01-05", "invoice": "IV-5736-4-3", "po": "PO4", "status": "posted", "units": 8}, "id": "book-IV-5736-4-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-1559-0-3", "issues": ["price"], "po": "PO0"}, "id": "case-IV-1559-0-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7256-0-1", "issues": ["price"], "po": "PO0"}, "id": "case-IV-7256-0-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3164-0-2", "issues": ["price"], "po": "PO0"}, "id": "case-IV-3164-0-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-2764-2-2", "issues": ["price", "units"], "po": "PO2"}, "id": "case-IV-2764-2-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-5470-3-2", "issues": ["price"], "po": "PO3"}, "id": "case-IV-5470-3-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7196-3-1", "issues": ["price"], "po": "PO3"}, "id": "case-IV-7196-3-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3195-1-1", "issues": ["price"], "po": "PO1"}, "id": "case-IV-3195-1-1", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-013/solution/solve.sh b/tasks/autom-supplier-invoice-match-013/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-013/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-013/task.toml b/tasks/autom-supplier-invoice-match-013/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..10f3ee92e5a3598324c424864daa9512587d7dea --- /dev/null +++ b/tasks/autom-supplier-invoice-match-013/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-013" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 13 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-013" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-013/tests/expected.json b/tasks/autom-supplier-invoice-match-013/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-013/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-013/tests/grade.py b/tasks/autom-supplier-invoice-match-013/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-013/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-013/tests/replay.py b/tasks/autom-supplier-invoice-match-013/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-013/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-013/tests/target.json b/tasks/autom-supplier-invoice-match-013/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..cb4904ab6b75222832ea4847e360858f53215681 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-013/tests/target.json @@ -0,0 +1,576 @@ +{ + "ap_postings": { + "book-IV-1064-5-0": { + "amount_cents": 287844, + "due": "2025-11-17", + "invoice": "IV-1064-5-0", + "po": "PO5", + "status": "posted", + "units": 17 + }, + "book-IV-2063-2-0": { + "amount_cents": 57180, + "due": "2025-12-17", + "invoice": "IV-2063-2-0", + "po": "PO2", + "status": "posted", + "units": 15 + }, + "book-IV-3741-4-0": { + "amount_cents": 286052, + "due": "2025-12-17", + "invoice": "IV-3741-4-0", + "po": "PO4", + "status": "posted", + "units": 13 + }, + "book-IV-3770-2-3": { + "amount_cents": 73060, + "due": "2025-12-22", + "invoice": "IV-3770-2-3", + "po": "PO2", + "status": "posted", + "units": 20 + }, + "book-IV-4547-1-0": { + "amount_cents": 157755, + "due": "2025-12-17", + "invoice": "IV-4547-1-0", + "po": "PO1", + "status": "posted", + "units": 13 + }, + "book-IV-4813-0-0": { + "amount_cents": 20738, + "due": "2025-12-02", + "invoice": "IV-4813-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "book-IV-5736-4-3": { + "amount_cents": 175072, + "due": "2026-01-05", + "invoice": "IV-5736-4-3", + "po": "PO4", + "status": "posted", + "units": 8 + }, + "book-IV-6053-3-0": { + "amount_cents": 150332, + "due": "2025-12-17", + "invoice": "IV-6053-3-0", + "po": "PO3", + "status": "posted", + "units": 14 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 2 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 3 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 1 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 7 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 5 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 2 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 3 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-11-22", + "po": "PO0", + "state": "accepted", + "units": 22 + }, + "GI-0-1": { + "date": "2025-11-13", + "po": "PO0", + "state": "quarantine", + "units": 23 + }, + "GI-0-2": { + "date": "2025-11-13", + "po": "PO0", + "state": "quarantine", + "units": 15 + }, + "GI-0-3": { + "date": "2025-11-06", + "po": "PO0", + "state": "accepted", + "units": 13 + }, + "GI-1-0": { + "date": "2025-11-22", + "po": "PO1", + "state": "accepted", + "units": 18 + }, + "GI-1-1": { + "date": "2025-11-24", + "po": "PO1", + "state": "accepted", + "units": 21 + }, + "GI-1-2": { + "date": "2025-11-01", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-1-3": { + "date": "2025-11-10", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-2-0": { + "date": "2025-11-22", + "po": "PO2", + "state": "accepted", + "units": 28 + }, + "GI-2-1": { + "date": "2025-11-01", + "po": "PO2", + "state": "quarantine", + "units": 27 + }, + "GI-2-2": { + "date": "2025-11-24", + "po": "PO2", + "state": "quarantine", + "units": 28 + }, + "GI-2-3": { + "date": "2025-11-13", + "po": "PO2", + "state": "accepted", + "units": 19 + }, + "GI-3-0": { + "date": "2025-11-22", + "po": "PO3", + "state": "accepted", + "units": 16 + }, + "GI-3-1": { + "date": "2025-11-22", + "po": "PO3", + "state": "accepted", + "units": 25 + }, + "GI-3-2": { + "date": "2025-11-08", + "po": "PO3", + "state": "accepted", + "units": 26 + }, + "GI-3-3": { + "date": "2025-11-07", + "po": "PO3", + "state": "accepted", + "units": 17 + }, + "GI-4-0": { + "date": "2025-11-22", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-4-1": { + "date": "2025-11-27", + "po": "PO4", + "state": "accepted", + "units": 23 + }, + "GI-4-2": { + "date": "2025-11-14", + "po": "PO4", + "state": "quarantine", + "units": 13 + }, + "GI-4-3": { + "date": "2025-11-10", + "po": "PO4", + "state": "accepted", + "units": 25 + }, + "GI-5-0": { + "date": "2025-11-22", + "po": "PO5", + "state": "accepted", + "units": 24 + }, + "GI-5-1": { + "date": "2025-11-24", + "po": "PO5", + "state": "accepted", + "units": 22 + }, + "GI-5-2": { + "date": "2025-11-05", + "po": "PO5", + "state": "quarantine", + "units": 13 + }, + "GI-5-3": { + "date": "2025-11-27", + "po": "PO5", + "state": "accepted", + "units": 21 + }, + "GI-6-0": { + "date": "2025-11-22", + "po": "PO6", + "state": "accepted", + "units": 20 + }, + "GI-6-1": { + "date": "2025-10-31", + "po": "PO6", + "state": "quarantine", + "units": 13 + }, + "GI-6-2": { + "date": "2025-11-10", + "po": "PO6", + "state": "accepted", + "units": 12 + }, + "GI-6-3": { + "date": "2025-11-26", + "po": "PO6", + "state": "accepted", + "units": 14 + } + }, + "invoice_inbox": { + "IV-1064-5-0": { + "date": "2025-11-02", + "po": "PO5", + "state": "posted", + "unit_price_cents": 16932, + "units": 17, + "vendor": "V3" + }, + "IV-1559-0-3": { + "date": "2025-11-07", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 21849, + "units": 14, + "vendor": "V1" + }, + "IV-2063-2-0": { + "date": "2025-11-02", + "po": "PO2", + "state": "posted", + "unit_price_cents": 3812, + "units": 15, + "vendor": "V2" + }, + "IV-2764-2-2": { + "date": "2025-11-16", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 4587, + "units": 15, + "vendor": "V2" + }, + "IV-3164-0-2": { + "date": "2025-11-13", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 21556, + "units": 8, + "vendor": "V1" + }, + "IV-3195-1-1": { + "date": "2025-11-23", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 13135, + "units": 13, + "vendor": "V0" + }, + "IV-3741-4-0": { + "date": "2025-11-02", + "po": "PO4", + "state": "posted", + "unit_price_cents": 22004, + "units": 13, + "vendor": "V0" + }, + "IV-3770-2-3": { + "date": "2025-11-07", + "po": "PO2", + "state": "posted", + "unit_price_cents": 3653, + "units": 20, + "vendor": "V2" + }, + "IV-3852-6-0": { + "date": "2025-11-02", + "po": "PO6", + "state": "review", + "unit_price_cents": 21007, + "units": 12, + "vendor": "V2" + }, + "IV-4195-4-2": { + "date": "2025-11-23", + "po": "PO4", + "state": "void", + "unit_price_cents": 23299, + "units": 15, + "vendor": "Unknown" + }, + "IV-4210-5-1": { + "date": "2025-11-23", + "po": "PO5", + "state": "void", + "unit_price_cents": 18403, + "units": 9, + "vendor": "V3" + }, + "IV-4547-1-0": { + "date": "2025-11-02", + "po": "PO1", + "state": "posted", + "unit_price_cents": 12135, + "units": 13, + "vendor": "V0" + }, + "IV-4813-0-0": { + "date": "2025-11-02", + "po": "PO0", + "state": "posted", + "unit_price_cents": 20738, + "units": 1, + "vendor": "V1" + }, + "IV-5470-3-2": { + "date": "2025-11-18", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 12160, + "units": 18, + "vendor": "V0" + }, + "IV-5503-2-1": { + "date": "2025-10-31", + "po": "PO2", + "state": "review", + "unit_price_cents": 5202, + "units": 12, + "vendor": "V2" + }, + "IV-5736-4-3": { + "date": "2025-11-21", + "po": "PO4", + "state": "posted", + "unit_price_cents": 21884, + "units": 8, + "vendor": "V0" + }, + "IV-5787-6-2": { + "date": "2025-11-18", + "po": "PO6", + "state": "review", + "unit_price_cents": 22886, + "units": 24, + "vendor": "V2" + }, + "IV-5968-5-2": { + "date": "2025-10-31", + "po": "PO5", + "state": "review", + "unit_price_cents": 17674, + "units": 10, + "vendor": "V3" + }, + "IV-6053-3-0": { + "date": "2025-11-02", + "po": "PO3", + "state": "posted", + "unit_price_cents": 10738, + "units": 14, + "vendor": "V0" + }, + "IV-6211-5-3": { + "date": "2025-11-21", + "po": "PO5", + "state": "void", + "unit_price_cents": 18729, + "units": 13, + "vendor": "V3" + }, + "IV-7196-3-1": { + "date": "2025-11-20", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 12568, + "units": 11, + "vendor": "V0" + }, + "IV-7256-0-1": { + "date": "2025-11-11", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 21447, + "units": 5, + "vendor": "V1" + }, + "IV-8846-4-1": { + "date": "2025-11-21", + "po": "PO4", + "state": "void", + "unit_price_cents": 21945, + "units": 11, + "vendor": "V0" + }, + "IV-9404-6-1": { + "date": "2025-11-14", + "po": "PO6", + "state": "void", + "unit_price_cents": 22733, + "units": 15, + "vendor": "V2" + } + }, + "purchase_orders": { + "PO0": { + "unit": "East", + "unit_price_cents": 20738, + "vendor": "V1" + }, + "PO1": { + "unit": "East", + "unit_price_cents": 12135, + "vendor": "V0" + }, + "PO2": { + "unit": "East", + "unit_price_cents": 3812, + "vendor": "V2" + }, + "PO3": { + "unit": "East", + "unit_price_cents": 10738, + "vendor": "V0" + }, + "PO4": { + "unit": "East", + "unit_price_cents": 22004, + "vendor": "V0" + }, + "PO5": { + "unit": "East", + "unit_price_cents": 16932, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 21007, + "vendor": "V2" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-1559-0-3": { + "invoice": "IV-1559-0-3", + "issues": [ + "price" + ], + "po": "PO0" + }, + "case-IV-2764-2-2": { + "invoice": "IV-2764-2-2", + "issues": [ + "price", + "units" + ], + "po": "PO2" + }, + "case-IV-3164-0-2": { + "invoice": "IV-3164-0-2", + "issues": [ + "price" + ], + "po": "PO0" + }, + "case-IV-3195-1-1": { + "invoice": "IV-3195-1-1", + "issues": [ + "price" + ], + "po": "PO1" + }, + "case-IV-5470-3-2": { + "invoice": "IV-5470-3-2", + "issues": [ + "price" + ], + "po": "PO3" + }, + "case-IV-7196-3-1": { + "invoice": "IV-7196-3-1", + "issues": [ + "price" + ], + "po": "PO3" + }, + "case-IV-7256-0-1": { + "invoice": "IV-7256-0-1", + "issues": [ + "price" + ], + "po": "PO0" + } + }, + "vendors": { + "V0": { + "net_days": 45 + }, + "V1": { + "net_days": 30 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 15 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-013/tests/test.sh b/tasks/autom-supplier-invoice-match-013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-013/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-013/tests/world.json b/tasks/autom-supplier-invoice-match-013/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..6c835a3d9673dbaa3fe91cd2ef1cde9723b51f74 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-013/tests/world.json @@ -0,0 +1,462 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 2 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 3 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 1 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 7 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 5 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 2 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 3 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-11-22", + "po": "PO0", + "state": "accepted", + "units": 22 + }, + "GI-0-1": { + "date": "2025-11-13", + "po": "PO0", + "state": "quarantine", + "units": 23 + }, + "GI-0-2": { + "date": "2025-11-13", + "po": "PO0", + "state": "quarantine", + "units": 15 + }, + "GI-0-3": { + "date": "2025-11-06", + "po": "PO0", + "state": "accepted", + "units": 13 + }, + "GI-1-0": { + "date": "2025-11-22", + "po": "PO1", + "state": "accepted", + "units": 18 + }, + "GI-1-1": { + "date": "2025-11-24", + "po": "PO1", + "state": "accepted", + "units": 21 + }, + "GI-1-2": { + "date": "2025-11-01", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-1-3": { + "date": "2025-11-10", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-2-0": { + "date": "2025-11-22", + "po": "PO2", + "state": "accepted", + "units": 28 + }, + "GI-2-1": { + "date": "2025-11-01", + "po": "PO2", + "state": "quarantine", + "units": 27 + }, + "GI-2-2": { + "date": "2025-11-24", + "po": "PO2", + "state": "quarantine", + "units": 28 + }, + "GI-2-3": { + "date": "2025-11-13", + "po": "PO2", + "state": "accepted", + "units": 19 + }, + "GI-3-0": { + "date": "2025-11-22", + "po": "PO3", + "state": "accepted", + "units": 16 + }, + "GI-3-1": { + "date": "2025-11-22", + "po": "PO3", + "state": "accepted", + "units": 25 + }, + "GI-3-2": { + "date": "2025-11-08", + "po": "PO3", + "state": "accepted", + "units": 26 + }, + "GI-3-3": { + "date": "2025-11-07", + "po": "PO3", + "state": "accepted", + "units": 17 + }, + "GI-4-0": { + "date": "2025-11-22", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-4-1": { + "date": "2025-11-27", + "po": "PO4", + "state": "accepted", + "units": 23 + }, + "GI-4-2": { + "date": "2025-11-14", + "po": "PO4", + "state": "quarantine", + "units": 13 + }, + "GI-4-3": { + "date": "2025-11-10", + "po": "PO4", + "state": "accepted", + "units": 25 + }, + "GI-5-0": { + "date": "2025-11-22", + "po": "PO5", + "state": "accepted", + "units": 24 + }, + "GI-5-1": { + "date": "2025-11-24", + "po": "PO5", + "state": "accepted", + "units": 22 + }, + "GI-5-2": { + "date": "2025-11-05", + "po": "PO5", + "state": "quarantine", + "units": 13 + }, + "GI-5-3": { + "date": "2025-11-27", + "po": "PO5", + "state": "accepted", + "units": 21 + }, + "GI-6-0": { + "date": "2025-11-22", + "po": "PO6", + "state": "accepted", + "units": 20 + }, + "GI-6-1": { + "date": "2025-10-31", + "po": "PO6", + "state": "quarantine", + "units": 13 + }, + "GI-6-2": { + "date": "2025-11-10", + "po": "PO6", + "state": "accepted", + "units": 12 + }, + "GI-6-3": { + "date": "2025-11-26", + "po": "PO6", + "state": "accepted", + "units": 14 + } + }, + "invoice_inbox": { + "IV-1064-5-0": { + "date": "2025-11-02", + "po": "PO5", + "state": "review", + "unit_price_cents": 16932, + "units": 17, + "vendor": "V3" + }, + "IV-1559-0-3": { + "date": "2025-11-07", + "po": "PO0", + "state": "review", + "unit_price_cents": 21849, + "units": 14, + "vendor": "V1" + }, + "IV-2063-2-0": { + "date": "2025-11-02", + "po": "PO2", + "state": "review", + "unit_price_cents": 3812, + "units": 15, + "vendor": "V2" + }, + "IV-2764-2-2": { + "date": "2025-11-16", + "po": "PO2", + "state": "review", + "unit_price_cents": 4587, + "units": 15, + "vendor": "V2" + }, + "IV-3164-0-2": { + "date": "2025-11-13", + "po": "PO0", + "state": "review", + "unit_price_cents": 21556, + "units": 8, + "vendor": "V1" + }, + "IV-3195-1-1": { + "date": "2025-11-23", + "po": "PO1", + "state": "review", + "unit_price_cents": 13135, + "units": 13, + "vendor": "V0" + }, + "IV-3741-4-0": { + "date": "2025-11-02", + "po": "PO4", + "state": "review", + "unit_price_cents": 22004, + "units": 13, + "vendor": "V0" + }, + "IV-3770-2-3": { + "date": "2025-11-07", + "po": "PO2", + "state": "review", + "unit_price_cents": 3653, + "units": 20, + "vendor": "V2" + }, + "IV-3852-6-0": { + "date": "2025-11-02", + "po": "PO6", + "state": "review", + "unit_price_cents": 21007, + "units": 12, + "vendor": "V2" + }, + "IV-4195-4-2": { + "date": "2025-11-23", + "po": "PO4", + "state": "void", + "unit_price_cents": 23299, + "units": 15, + "vendor": "Unknown" + }, + "IV-4210-5-1": { + "date": "2025-11-23", + "po": "PO5", + "state": "void", + "unit_price_cents": 18403, + "units": 9, + "vendor": "V3" + }, + "IV-4547-1-0": { + "date": "2025-11-02", + "po": "PO1", + "state": "review", + "unit_price_cents": 12135, + "units": 13, + "vendor": "V0" + }, + "IV-4813-0-0": { + "date": "2025-11-02", + "po": "PO0", + "state": "review", + "unit_price_cents": 20738, + "units": 1, + "vendor": "V1" + }, + "IV-5470-3-2": { + "date": "2025-11-18", + "po": "PO3", + "state": "review", + "unit_price_cents": 12160, + "units": 18, + "vendor": "V0" + }, + "IV-5503-2-1": { + "date": "2025-10-31", + "po": "PO2", + "state": "review", + "unit_price_cents": 5202, + "units": 12, + "vendor": "V2" + }, + "IV-5736-4-3": { + "date": "2025-11-21", + "po": "PO4", + "state": "review", + "unit_price_cents": 21884, + "units": 8, + "vendor": "V0" + }, + "IV-5787-6-2": { + "date": "2025-11-18", + "po": "PO6", + "state": "review", + "unit_price_cents": 22886, + "units": 24, + "vendor": "V2" + }, + "IV-5968-5-2": { + "date": "2025-10-31", + "po": "PO5", + "state": "review", + "unit_price_cents": 17674, + "units": 10, + "vendor": "V3" + }, + "IV-6053-3-0": { + "date": "2025-11-02", + "po": "PO3", + "state": "review", + "unit_price_cents": 10738, + "units": 14, + "vendor": "V0" + }, + "IV-6211-5-3": { + "date": "2025-11-21", + "po": "PO5", + "state": "void", + "unit_price_cents": 18729, + "units": 13, + "vendor": "V3" + }, + "IV-7196-3-1": { + "date": "2025-11-20", + "po": "PO3", + "state": "review", + "unit_price_cents": 12568, + "units": 11, + "vendor": "V0" + }, + "IV-7256-0-1": { + "date": "2025-11-11", + "po": "PO0", + "state": "review", + "unit_price_cents": 21447, + "units": 5, + "vendor": "V1" + }, + "IV-8846-4-1": { + "date": "2025-11-21", + "po": "PO4", + "state": "void", + "unit_price_cents": 21945, + "units": 11, + "vendor": "V0" + }, + "IV-9404-6-1": { + "date": "2025-11-14", + "po": "PO6", + "state": "void", + "unit_price_cents": 22733, + "units": 15, + "vendor": "V2" + } + }, + "purchase_orders": { + "PO0": { + "unit": "East", + "unit_price_cents": 20738, + "vendor": "V1" + }, + "PO1": { + "unit": "East", + "unit_price_cents": 12135, + "vendor": "V0" + }, + "PO2": { + "unit": "East", + "unit_price_cents": 3812, + "vendor": "V2" + }, + "PO3": { + "unit": "East", + "unit_price_cents": 10738, + "vendor": "V0" + }, + "PO4": { + "unit": "East", + "unit_price_cents": 22004, + "vendor": "V0" + }, + "PO5": { + "unit": "East", + "unit_price_cents": 16932, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 21007, + "vendor": "V2" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 45 + }, + "V1": { + "net_days": 30 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 15 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-013/tests/world_check.py b/tasks/autom-supplier-invoice-match-013/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-013/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-013/validation/openenv.json b/tasks/autom-supplier-invoice-match-013/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-013/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-014/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-014/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-014/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-014/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-014/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..45b9f07f81317cf14b05e0e2babcddbd09ee0a4c --- /dev/null +++ b/tasks/autom-supplier-invoice-match-014/environment/inputs/world.json @@ -0,0 +1,446 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 6 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 4 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 1 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 4 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 5 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 7 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 3 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-12-15", + "po": "PO0", + "state": "accepted", + "units": 12 + }, + "GI-0-1": { + "date": "2025-12-18", + "po": "PO0", + "state": "quarantine", + "units": 18 + }, + "GI-0-2": { + "date": "2025-12-02", + "po": "PO0", + "state": "accepted", + "units": 21 + }, + "GI-0-3": { + "date": "2025-12-06", + "po": "PO0", + "state": "accepted", + "units": 18 + }, + "GI-1-0": { + "date": "2025-12-15", + "po": "PO1", + "state": "accepted", + "units": 17 + }, + "GI-1-1": { + "date": "2025-11-27", + "po": "PO1", + "state": "quarantine", + "units": 24 + }, + "GI-1-2": { + "date": "2025-12-04", + "po": "PO1", + "state": "accepted", + "units": 26 + }, + "GI-1-3": { + "date": "2025-12-18", + "po": "PO1", + "state": "quarantine", + "units": 24 + }, + "GI-2-0": { + "date": "2025-12-15", + "po": "PO2", + "state": "accepted", + "units": 19 + }, + "GI-2-1": { + "date": "2025-12-06", + "po": "PO2", + "state": "accepted", + "units": 21 + }, + "GI-2-2": { + "date": "2025-12-16", + "po": "PO2", + "state": "quarantine", + "units": 17 + }, + "GI-2-3": { + "date": "2025-11-30", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-3-0": { + "date": "2025-12-15", + "po": "PO3", + "state": "accepted", + "units": 12 + }, + "GI-3-1": { + "date": "2025-12-07", + "po": "PO3", + "state": "quarantine", + "units": 25 + }, + "GI-3-2": { + "date": "2025-11-27", + "po": "PO3", + "state": "quarantine", + "units": 23 + }, + "GI-3-3": { + "date": "2025-12-11", + "po": "PO3", + "state": "quarantine", + "units": 22 + }, + "GI-4-0": { + "date": "2025-12-15", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-1": { + "date": "2025-12-21", + "po": "PO4", + "state": "accepted", + "units": 26 + }, + "GI-4-2": { + "date": "2025-12-19", + "po": "PO4", + "state": "accepted", + "units": 23 + }, + "GI-4-3": { + "date": "2025-12-03", + "po": "PO4", + "state": "accepted", + "units": 17 + }, + "GI-5-0": { + "date": "2025-12-15", + "po": "PO5", + "state": "accepted", + "units": 13 + }, + "GI-5-1": { + "date": "2025-11-23", + "po": "PO5", + "state": "accepted", + "units": 26 + }, + "GI-5-2": { + "date": "2025-12-13", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-5-3": { + "date": "2025-12-04", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-6-0": { + "date": "2025-12-15", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-1": { + "date": "2025-11-27", + "po": "PO6", + "state": "quarantine", + "units": 18 + }, + "GI-6-2": { + "date": "2025-12-18", + "po": "PO6", + "state": "quarantine", + "units": 16 + }, + "GI-6-3": { + "date": "2025-11-24", + "po": "PO6", + "state": "accepted", + "units": 14 + } + }, + "invoice_inbox": { + "IV-1591-2-0": { + "date": "2025-12-02", + "po": "PO2", + "state": "review", + "unit_price_cents": 21090, + "units": 25, + "vendor": "V3" + }, + "IV-1772-4-2": { + "date": "2025-12-02", + "po": "PO4", + "state": "void", + "unit_price_cents": 4635, + "units": 17, + "vendor": "Unknown" + }, + "IV-1792-4-1": { + "date": "2025-11-28", + "po": "PO4", + "state": "review", + "unit_price_cents": 4838, + "units": 8, + "vendor": "V1" + }, + "IV-1979-1-3": { + "date": "2025-12-15", + "po": "PO1", + "state": "review", + "unit_price_cents": 20627, + "units": 10, + "vendor": "V1" + }, + "IV-2176-1-0": { + "date": "2025-12-02", + "po": "PO1", + "state": "review", + "unit_price_cents": 20291, + "units": 15, + "vendor": "V1" + }, + "IV-2445-1-1": { + "date": "2025-12-13", + "po": "PO1", + "state": "review", + "unit_price_cents": 20346, + "units": 3, + "vendor": "Unknown" + }, + "IV-2604-0-1": { + "date": "2025-12-02", + "po": "PO0", + "state": "review", + "unit_price_cents": 20790, + "units": 8, + "vendor": "V2" + }, + "IV-3077-2-1": { + "date": "2025-12-07", + "po": "PO2", + "state": "review", + "unit_price_cents": 22743, + "units": 8, + "vendor": "V3" + }, + "IV-3286-6-1": { + "date": "2025-12-15", + "po": "PO6", + "state": "review", + "unit_price_cents": 20022, + "units": 11, + "vendor": "Unknown" + }, + "IV-3466-6-0": { + "date": "2025-12-02", + "po": "PO6", + "state": "review", + "unit_price_cents": 20204, + "units": 3, + "vendor": "V2" + }, + "IV-3527-3-1": { + "date": "2025-12-16", + "po": "PO3", + "state": "void", + "unit_price_cents": 13721, + "units": 7, + "vendor": "V2" + }, + "IV-3598-5-1": { + "date": "2025-12-15", + "po": "PO5", + "state": "review", + "unit_price_cents": 3666, + "units": 16, + "vendor": "V0" + }, + "IV-3936-1-2": { + "date": "2025-12-12", + "po": "PO1", + "state": "review", + "unit_price_cents": 20529, + "units": 9, + "vendor": "V1" + }, + "IV-4232-2-3": { + "date": "2025-12-17", + "po": "PO2", + "state": "review", + "unit_price_cents": 22997, + "units": 5, + "vendor": "Unknown" + }, + "IV-5012-6-2": { + "date": "2025-12-16", + "po": "PO6", + "state": "review", + "unit_price_cents": 20211, + "units": 4, + "vendor": "Unknown" + }, + "IV-6259-4-0": { + "date": "2025-12-02", + "po": "PO4", + "state": "review", + "unit_price_cents": 4615, + "units": 13, + "vendor": "V1" + }, + "IV-6692-3-2": { + "date": "2025-12-08", + "po": "PO3", + "state": "void", + "unit_price_cents": 12183, + "units": 9, + "vendor": "V2" + }, + "IV-7879-2-2": { + "date": "2025-12-06", + "po": "PO2", + "state": "review", + "unit_price_cents": 21292, + "units": 3, + "vendor": "V3" + }, + "IV-7962-3-0": { + "date": "2025-12-02", + "po": "PO3", + "state": "review", + "unit_price_cents": 11531, + "units": 15, + "vendor": "V2" + }, + "IV-8122-5-0": { + "date": "2025-12-02", + "po": "PO5", + "state": "review", + "unit_price_cents": 3642, + "units": 10, + "vendor": "V0" + }, + "IV-9127-6-3": { + "date": "2025-11-28", + "po": "PO6", + "state": "review", + "unit_price_cents": 20822, + "units": 4, + "vendor": "V2" + }, + "IV-9669-0-0": { + "date": "2025-12-02", + "po": "PO0", + "state": "review", + "unit_price_cents": 19310, + "units": 1, + "vendor": "V2" + } + }, + "purchase_orders": { + "PO0": { + "unit": "West", + "unit_price_cents": 19310, + "vendor": "V2" + }, + "PO1": { + "unit": "West", + "unit_price_cents": 20291, + "vendor": "V1" + }, + "PO2": { + "unit": "West", + "unit_price_cents": 21090, + "vendor": "V3" + }, + "PO3": { + "unit": "West", + "unit_price_cents": 11531, + "vendor": "V2" + }, + "PO4": { + "unit": "West", + "unit_price_cents": 4615, + "vendor": "V1" + }, + "PO5": { + "unit": "West", + "unit_price_cents": 3642, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 20204, + "vendor": "V2" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 30 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-014/instruction.md b/tasks/autom-supplier-invoice-match-014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2d7d31c64d14941c1f887bde4a2549b47a962e1a --- /dev/null +++ b/tasks/autom-supplier-invoice-match-014/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit West at 2025-12-16. Handle invoices in review attached to that unit's purchase orders, invoice dates 2025-12-02 through 2025-12-16 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 100 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-014/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-014/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..404ef9b93cb6f876255442901c628c01e4d2379e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-014/solution/files/actions.jsonl @@ -0,0 +1,26 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-9669-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-2604-0-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-2176-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-2445-1-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3936-1-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-1979-1-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-1591-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3077-2-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-7879-2-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7962-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6259-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8122-5-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-3598-5-1", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 527250, "due": "2026-01-16", "invoice": "IV-1591-2-0", "po": "PO2", "status": "posted", "units": 25}, "id": "book-IV-1591-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 304365, "due": "2026-01-01", "invoice": "IV-2176-1-0", "po": "PO1", "status": "posted", "units": 15}, "id": "book-IV-2176-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 59995, "due": "2026-01-01", "invoice": "IV-6259-4-0", "po": "PO4", "status": "posted", "units": 13}, "id": "book-IV-6259-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 36420, "due": "2026-01-01", "invoice": "IV-8122-5-0", "po": "PO5", "status": "posted", "units": 10}, "id": "book-IV-8122-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 19310, "due": "2025-12-17", "invoice": "IV-9669-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-9669-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 63876, "due": "2026-01-20", "invoice": "IV-7879-2-2", "po": "PO2", "status": "posted", "units": 3}, "id": "book-IV-7879-2-2", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 58656, "due": "2026-01-14", "invoice": "IV-3598-5-1", "po": "PO5", "status": "posted", "units": 16}, "id": "book-IV-3598-5-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-2604-0-1", "issues": ["price"], "po": "PO0"}, "id": "case-IV-2604-0-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7962-3-0", "issues": ["units"], "po": "PO3"}, "id": "case-IV-7962-3-0", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3077-2-1", "issues": ["price"], "po": "PO2"}, "id": "case-IV-3077-2-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3936-1-2", "issues": ["price"], "po": "PO1"}, "id": "case-IV-3936-1-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-2445-1-1", "issues": ["vendor"], "po": "PO1"}, "id": "case-IV-2445-1-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-1979-1-3", "issues": ["price"], "po": "PO1"}, "id": "case-IV-1979-1-3", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-014/solution/solve.sh b/tasks/autom-supplier-invoice-match-014/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-014/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-014/task.toml b/tasks/autom-supplier-invoice-match-014/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6d8995ef16afb54b4e482054b28114e82bec79f1 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-014/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-014" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 14 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-014" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-014/tests/expected.json b/tasks/autom-supplier-invoice-match-014/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-014/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-014/tests/grade.py b/tasks/autom-supplier-invoice-match-014/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-014/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-014/tests/replay.py b/tasks/autom-supplier-invoice-match-014/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-014/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-014/tests/target.json b/tasks/autom-supplier-invoice-match-014/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..4ce7fe6f2747556e62359f09d000b8340575d271 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-014/tests/target.json @@ -0,0 +1,544 @@ +{ + "ap_postings": { + "book-IV-1591-2-0": { + "amount_cents": 527250, + "due": "2026-01-16", + "invoice": "IV-1591-2-0", + "po": "PO2", + "status": "posted", + "units": 25 + }, + "book-IV-2176-1-0": { + "amount_cents": 304365, + "due": "2026-01-01", + "invoice": "IV-2176-1-0", + "po": "PO1", + "status": "posted", + "units": 15 + }, + "book-IV-3598-5-1": { + "amount_cents": 58656, + "due": "2026-01-14", + "invoice": "IV-3598-5-1", + "po": "PO5", + "status": "posted", + "units": 16 + }, + "book-IV-6259-4-0": { + "amount_cents": 59995, + "due": "2026-01-01", + "invoice": "IV-6259-4-0", + "po": "PO4", + "status": "posted", + "units": 13 + }, + "book-IV-7879-2-2": { + "amount_cents": 63876, + "due": "2026-01-20", + "invoice": "IV-7879-2-2", + "po": "PO2", + "status": "posted", + "units": 3 + }, + "book-IV-8122-5-0": { + "amount_cents": 36420, + "due": "2026-01-01", + "invoice": "IV-8122-5-0", + "po": "PO5", + "status": "posted", + "units": 10 + }, + "book-IV-9669-0-0": { + "amount_cents": 19310, + "due": "2025-12-17", + "invoice": "IV-9669-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 6 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 4 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 1 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 4 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 5 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 7 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 3 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-12-15", + "po": "PO0", + "state": "accepted", + "units": 12 + }, + "GI-0-1": { + "date": "2025-12-18", + "po": "PO0", + "state": "quarantine", + "units": 18 + }, + "GI-0-2": { + "date": "2025-12-02", + "po": "PO0", + "state": "accepted", + "units": 21 + }, + "GI-0-3": { + "date": "2025-12-06", + "po": "PO0", + "state": "accepted", + "units": 18 + }, + "GI-1-0": { + "date": "2025-12-15", + "po": "PO1", + "state": "accepted", + "units": 17 + }, + "GI-1-1": { + "date": "2025-11-27", + "po": "PO1", + "state": "quarantine", + "units": 24 + }, + "GI-1-2": { + "date": "2025-12-04", + "po": "PO1", + "state": "accepted", + "units": 26 + }, + "GI-1-3": { + "date": "2025-12-18", + "po": "PO1", + "state": "quarantine", + "units": 24 + }, + "GI-2-0": { + "date": "2025-12-15", + "po": "PO2", + "state": "accepted", + "units": 19 + }, + "GI-2-1": { + "date": "2025-12-06", + "po": "PO2", + "state": "accepted", + "units": 21 + }, + "GI-2-2": { + "date": "2025-12-16", + "po": "PO2", + "state": "quarantine", + "units": 17 + }, + "GI-2-3": { + "date": "2025-11-30", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-3-0": { + "date": "2025-12-15", + "po": "PO3", + "state": "accepted", + "units": 12 + }, + "GI-3-1": { + "date": "2025-12-07", + "po": "PO3", + "state": "quarantine", + "units": 25 + }, + "GI-3-2": { + "date": "2025-11-27", + "po": "PO3", + "state": "quarantine", + "units": 23 + }, + "GI-3-3": { + "date": "2025-12-11", + "po": "PO3", + "state": "quarantine", + "units": 22 + }, + "GI-4-0": { + "date": "2025-12-15", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-1": { + "date": "2025-12-21", + "po": "PO4", + "state": "accepted", + "units": 26 + }, + "GI-4-2": { + "date": "2025-12-19", + "po": "PO4", + "state": "accepted", + "units": 23 + }, + "GI-4-3": { + "date": "2025-12-03", + "po": "PO4", + "state": "accepted", + "units": 17 + }, + "GI-5-0": { + "date": "2025-12-15", + "po": "PO5", + "state": "accepted", + "units": 13 + }, + "GI-5-1": { + "date": "2025-11-23", + "po": "PO5", + "state": "accepted", + "units": 26 + }, + "GI-5-2": { + "date": "2025-12-13", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-5-3": { + "date": "2025-12-04", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-6-0": { + "date": "2025-12-15", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-1": { + "date": "2025-11-27", + "po": "PO6", + "state": "quarantine", + "units": 18 + }, + "GI-6-2": { + "date": "2025-12-18", + "po": "PO6", + "state": "quarantine", + "units": 16 + }, + "GI-6-3": { + "date": "2025-11-24", + "po": "PO6", + "state": "accepted", + "units": 14 + } + }, + "invoice_inbox": { + "IV-1591-2-0": { + "date": "2025-12-02", + "po": "PO2", + "state": "posted", + "unit_price_cents": 21090, + "units": 25, + "vendor": "V3" + }, + "IV-1772-4-2": { + "date": "2025-12-02", + "po": "PO4", + "state": "void", + "unit_price_cents": 4635, + "units": 17, + "vendor": "Unknown" + }, + "IV-1792-4-1": { + "date": "2025-11-28", + "po": "PO4", + "state": "review", + "unit_price_cents": 4838, + "units": 8, + "vendor": "V1" + }, + "IV-1979-1-3": { + "date": "2025-12-15", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 20627, + "units": 10, + "vendor": "V1" + }, + "IV-2176-1-0": { + "date": "2025-12-02", + "po": "PO1", + "state": "posted", + "unit_price_cents": 20291, + "units": 15, + "vendor": "V1" + }, + "IV-2445-1-1": { + "date": "2025-12-13", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 20346, + "units": 3, + "vendor": "Unknown" + }, + "IV-2604-0-1": { + "date": "2025-12-02", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 20790, + "units": 8, + "vendor": "V2" + }, + "IV-3077-2-1": { + "date": "2025-12-07", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 22743, + "units": 8, + "vendor": "V3" + }, + "IV-3286-6-1": { + "date": "2025-12-15", + "po": "PO6", + "state": "review", + "unit_price_cents": 20022, + "units": 11, + "vendor": "Unknown" + }, + "IV-3466-6-0": { + "date": "2025-12-02", + "po": "PO6", + "state": "review", + "unit_price_cents": 20204, + "units": 3, + "vendor": "V2" + }, + "IV-3527-3-1": { + "date": "2025-12-16", + "po": "PO3", + "state": "void", + "unit_price_cents": 13721, + "units": 7, + "vendor": "V2" + }, + "IV-3598-5-1": { + "date": "2025-12-15", + "po": "PO5", + "state": "posted", + "unit_price_cents": 3666, + "units": 16, + "vendor": "V0" + }, + "IV-3936-1-2": { + "date": "2025-12-12", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 20529, + "units": 9, + "vendor": "V1" + }, + "IV-4232-2-3": { + "date": "2025-12-17", + "po": "PO2", + "state": "review", + "unit_price_cents": 22997, + "units": 5, + "vendor": "Unknown" + }, + "IV-5012-6-2": { + "date": "2025-12-16", + "po": "PO6", + "state": "review", + "unit_price_cents": 20211, + "units": 4, + "vendor": "Unknown" + }, + "IV-6259-4-0": { + "date": "2025-12-02", + "po": "PO4", + "state": "posted", + "unit_price_cents": 4615, + "units": 13, + "vendor": "V1" + }, + "IV-6692-3-2": { + "date": "2025-12-08", + "po": "PO3", + "state": "void", + "unit_price_cents": 12183, + "units": 9, + "vendor": "V2" + }, + "IV-7879-2-2": { + "date": "2025-12-06", + "po": "PO2", + "state": "posted", + "unit_price_cents": 21292, + "units": 3, + "vendor": "V3" + }, + "IV-7962-3-0": { + "date": "2025-12-02", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 11531, + "units": 15, + "vendor": "V2" + }, + "IV-8122-5-0": { + "date": "2025-12-02", + "po": "PO5", + "state": "posted", + "unit_price_cents": 3642, + "units": 10, + "vendor": "V0" + }, + "IV-9127-6-3": { + "date": "2025-11-28", + "po": "PO6", + "state": "review", + "unit_price_cents": 20822, + "units": 4, + "vendor": "V2" + }, + "IV-9669-0-0": { + "date": "2025-12-02", + "po": "PO0", + "state": "posted", + "unit_price_cents": 19310, + "units": 1, + "vendor": "V2" + } + }, + "purchase_orders": { + "PO0": { + "unit": "West", + "unit_price_cents": 19310, + "vendor": "V2" + }, + "PO1": { + "unit": "West", + "unit_price_cents": 20291, + "vendor": "V1" + }, + "PO2": { + "unit": "West", + "unit_price_cents": 21090, + "vendor": "V3" + }, + "PO3": { + "unit": "West", + "unit_price_cents": 11531, + "vendor": "V2" + }, + "PO4": { + "unit": "West", + "unit_price_cents": 4615, + "vendor": "V1" + }, + "PO5": { + "unit": "West", + "unit_price_cents": 3642, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 20204, + "vendor": "V2" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-1979-1-3": { + "invoice": "IV-1979-1-3", + "issues": [ + "price" + ], + "po": "PO1" + }, + "case-IV-2445-1-1": { + "invoice": "IV-2445-1-1", + "issues": [ + "vendor" + ], + "po": "PO1" + }, + "case-IV-2604-0-1": { + "invoice": "IV-2604-0-1", + "issues": [ + "price" + ], + "po": "PO0" + }, + "case-IV-3077-2-1": { + "invoice": "IV-3077-2-1", + "issues": [ + "price" + ], + "po": "PO2" + }, + "case-IV-3936-1-2": { + "invoice": "IV-3936-1-2", + "issues": [ + "price" + ], + "po": "PO1" + }, + "case-IV-7962-3-0": { + "invoice": "IV-7962-3-0", + "issues": [ + "units" + ], + "po": "PO3" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 30 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-014/tests/test.sh b/tasks/autom-supplier-invoice-match-014/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-014/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-014/tests/world.json b/tasks/autom-supplier-invoice-match-014/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..45b9f07f81317cf14b05e0e2babcddbd09ee0a4c --- /dev/null +++ b/tasks/autom-supplier-invoice-match-014/tests/world.json @@ -0,0 +1,446 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 6 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 4 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 1 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 4 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 5 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 7 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 3 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-12-15", + "po": "PO0", + "state": "accepted", + "units": 12 + }, + "GI-0-1": { + "date": "2025-12-18", + "po": "PO0", + "state": "quarantine", + "units": 18 + }, + "GI-0-2": { + "date": "2025-12-02", + "po": "PO0", + "state": "accepted", + "units": 21 + }, + "GI-0-3": { + "date": "2025-12-06", + "po": "PO0", + "state": "accepted", + "units": 18 + }, + "GI-1-0": { + "date": "2025-12-15", + "po": "PO1", + "state": "accepted", + "units": 17 + }, + "GI-1-1": { + "date": "2025-11-27", + "po": "PO1", + "state": "quarantine", + "units": 24 + }, + "GI-1-2": { + "date": "2025-12-04", + "po": "PO1", + "state": "accepted", + "units": 26 + }, + "GI-1-3": { + "date": "2025-12-18", + "po": "PO1", + "state": "quarantine", + "units": 24 + }, + "GI-2-0": { + "date": "2025-12-15", + "po": "PO2", + "state": "accepted", + "units": 19 + }, + "GI-2-1": { + "date": "2025-12-06", + "po": "PO2", + "state": "accepted", + "units": 21 + }, + "GI-2-2": { + "date": "2025-12-16", + "po": "PO2", + "state": "quarantine", + "units": 17 + }, + "GI-2-3": { + "date": "2025-11-30", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-3-0": { + "date": "2025-12-15", + "po": "PO3", + "state": "accepted", + "units": 12 + }, + "GI-3-1": { + "date": "2025-12-07", + "po": "PO3", + "state": "quarantine", + "units": 25 + }, + "GI-3-2": { + "date": "2025-11-27", + "po": "PO3", + "state": "quarantine", + "units": 23 + }, + "GI-3-3": { + "date": "2025-12-11", + "po": "PO3", + "state": "quarantine", + "units": 22 + }, + "GI-4-0": { + "date": "2025-12-15", + "po": "PO4", + "state": "accepted", + "units": 22 + }, + "GI-4-1": { + "date": "2025-12-21", + "po": "PO4", + "state": "accepted", + "units": 26 + }, + "GI-4-2": { + "date": "2025-12-19", + "po": "PO4", + "state": "accepted", + "units": 23 + }, + "GI-4-3": { + "date": "2025-12-03", + "po": "PO4", + "state": "accepted", + "units": 17 + }, + "GI-5-0": { + "date": "2025-12-15", + "po": "PO5", + "state": "accepted", + "units": 13 + }, + "GI-5-1": { + "date": "2025-11-23", + "po": "PO5", + "state": "accepted", + "units": 26 + }, + "GI-5-2": { + "date": "2025-12-13", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-5-3": { + "date": "2025-12-04", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-6-0": { + "date": "2025-12-15", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-1": { + "date": "2025-11-27", + "po": "PO6", + "state": "quarantine", + "units": 18 + }, + "GI-6-2": { + "date": "2025-12-18", + "po": "PO6", + "state": "quarantine", + "units": 16 + }, + "GI-6-3": { + "date": "2025-11-24", + "po": "PO6", + "state": "accepted", + "units": 14 + } + }, + "invoice_inbox": { + "IV-1591-2-0": { + "date": "2025-12-02", + "po": "PO2", + "state": "review", + "unit_price_cents": 21090, + "units": 25, + "vendor": "V3" + }, + "IV-1772-4-2": { + "date": "2025-12-02", + "po": "PO4", + "state": "void", + "unit_price_cents": 4635, + "units": 17, + "vendor": "Unknown" + }, + "IV-1792-4-1": { + "date": "2025-11-28", + "po": "PO4", + "state": "review", + "unit_price_cents": 4838, + "units": 8, + "vendor": "V1" + }, + "IV-1979-1-3": { + "date": "2025-12-15", + "po": "PO1", + "state": "review", + "unit_price_cents": 20627, + "units": 10, + "vendor": "V1" + }, + "IV-2176-1-0": { + "date": "2025-12-02", + "po": "PO1", + "state": "review", + "unit_price_cents": 20291, + "units": 15, + "vendor": "V1" + }, + "IV-2445-1-1": { + "date": "2025-12-13", + "po": "PO1", + "state": "review", + "unit_price_cents": 20346, + "units": 3, + "vendor": "Unknown" + }, + "IV-2604-0-1": { + "date": "2025-12-02", + "po": "PO0", + "state": "review", + "unit_price_cents": 20790, + "units": 8, + "vendor": "V2" + }, + "IV-3077-2-1": { + "date": "2025-12-07", + "po": "PO2", + "state": "review", + "unit_price_cents": 22743, + "units": 8, + "vendor": "V3" + }, + "IV-3286-6-1": { + "date": "2025-12-15", + "po": "PO6", + "state": "review", + "unit_price_cents": 20022, + "units": 11, + "vendor": "Unknown" + }, + "IV-3466-6-0": { + "date": "2025-12-02", + "po": "PO6", + "state": "review", + "unit_price_cents": 20204, + "units": 3, + "vendor": "V2" + }, + "IV-3527-3-1": { + "date": "2025-12-16", + "po": "PO3", + "state": "void", + "unit_price_cents": 13721, + "units": 7, + "vendor": "V2" + }, + "IV-3598-5-1": { + "date": "2025-12-15", + "po": "PO5", + "state": "review", + "unit_price_cents": 3666, + "units": 16, + "vendor": "V0" + }, + "IV-3936-1-2": { + "date": "2025-12-12", + "po": "PO1", + "state": "review", + "unit_price_cents": 20529, + "units": 9, + "vendor": "V1" + }, + "IV-4232-2-3": { + "date": "2025-12-17", + "po": "PO2", + "state": "review", + "unit_price_cents": 22997, + "units": 5, + "vendor": "Unknown" + }, + "IV-5012-6-2": { + "date": "2025-12-16", + "po": "PO6", + "state": "review", + "unit_price_cents": 20211, + "units": 4, + "vendor": "Unknown" + }, + "IV-6259-4-0": { + "date": "2025-12-02", + "po": "PO4", + "state": "review", + "unit_price_cents": 4615, + "units": 13, + "vendor": "V1" + }, + "IV-6692-3-2": { + "date": "2025-12-08", + "po": "PO3", + "state": "void", + "unit_price_cents": 12183, + "units": 9, + "vendor": "V2" + }, + "IV-7879-2-2": { + "date": "2025-12-06", + "po": "PO2", + "state": "review", + "unit_price_cents": 21292, + "units": 3, + "vendor": "V3" + }, + "IV-7962-3-0": { + "date": "2025-12-02", + "po": "PO3", + "state": "review", + "unit_price_cents": 11531, + "units": 15, + "vendor": "V2" + }, + "IV-8122-5-0": { + "date": "2025-12-02", + "po": "PO5", + "state": "review", + "unit_price_cents": 3642, + "units": 10, + "vendor": "V0" + }, + "IV-9127-6-3": { + "date": "2025-11-28", + "po": "PO6", + "state": "review", + "unit_price_cents": 20822, + "units": 4, + "vendor": "V2" + }, + "IV-9669-0-0": { + "date": "2025-12-02", + "po": "PO0", + "state": "review", + "unit_price_cents": 19310, + "units": 1, + "vendor": "V2" + } + }, + "purchase_orders": { + "PO0": { + "unit": "West", + "unit_price_cents": 19310, + "vendor": "V2" + }, + "PO1": { + "unit": "West", + "unit_price_cents": 20291, + "vendor": "V1" + }, + "PO2": { + "unit": "West", + "unit_price_cents": 21090, + "vendor": "V3" + }, + "PO3": { + "unit": "West", + "unit_price_cents": 11531, + "vendor": "V2" + }, + "PO4": { + "unit": "West", + "unit_price_cents": 4615, + "vendor": "V1" + }, + "PO5": { + "unit": "West", + "unit_price_cents": 3642, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 20204, + "vendor": "V2" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 30 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-014/tests/world_check.py b/tasks/autom-supplier-invoice-match-014/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-014/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-014/validation/openenv.json b/tasks/autom-supplier-invoice-match-014/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-014/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-015/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-015/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-015/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-015/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-015/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..c3f56eefab5e1118a350cb9b3269eddc7ee2d0c9 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-015/environment/inputs/world.json @@ -0,0 +1,438 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 5 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 0 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 3 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 2 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 8 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 8 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 3 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-01-07", + "po": "PO0", + "state": "accepted", + "units": 19 + }, + "GI-0-1": { + "date": "2025-12-24", + "po": "PO0", + "state": "accepted", + "units": 27 + }, + "GI-0-2": { + "date": "2026-01-07", + "po": "PO0", + "state": "accepted", + "units": 18 + }, + "GI-0-3": { + "date": "2025-12-15", + "po": "PO0", + "state": "quarantine", + "units": 13 + }, + "GI-1-0": { + "date": "2026-01-07", + "po": "PO1", + "state": "accepted", + "units": 26 + }, + "GI-1-1": { + "date": "2026-01-07", + "po": "PO1", + "state": "quarantine", + "units": 13 + }, + "GI-1-2": { + "date": "2026-01-02", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-1-3": { + "date": "2026-01-10", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-2-0": { + "date": "2026-01-07", + "po": "PO2", + "state": "accepted", + "units": 27 + }, + "GI-2-1": { + "date": "2025-12-25", + "po": "PO2", + "state": "accepted", + "units": 24 + }, + "GI-2-2": { + "date": "2026-01-02", + "po": "PO2", + "state": "quarantine", + "units": 18 + }, + "GI-2-3": { + "date": "2026-01-01", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-3-0": { + "date": "2026-01-07", + "po": "PO3", + "state": "accepted", + "units": 28 + }, + "GI-3-1": { + "date": "2025-12-23", + "po": "PO3", + "state": "quarantine", + "units": 18 + }, + "GI-3-2": { + "date": "2025-12-25", + "po": "PO3", + "state": "accepted", + "units": 23 + }, + "GI-3-3": { + "date": "2026-01-13", + "po": "PO3", + "state": "quarantine", + "units": 17 + }, + "GI-4-0": { + "date": "2026-01-07", + "po": "PO4", + "state": "accepted", + "units": 20 + }, + "GI-4-1": { + "date": "2025-12-16", + "po": "PO4", + "state": "quarantine", + "units": 23 + }, + "GI-4-2": { + "date": "2026-01-08", + "po": "PO4", + "state": "accepted", + "units": 18 + }, + "GI-4-3": { + "date": "2026-01-09", + "po": "PO4", + "state": "accepted", + "units": 16 + }, + "GI-5-0": { + "date": "2026-01-07", + "po": "PO5", + "state": "accepted", + "units": 16 + }, + "GI-5-1": { + "date": "2025-12-28", + "po": "PO5", + "state": "quarantine", + "units": 24 + }, + "GI-5-2": { + "date": "2026-01-03", + "po": "PO5", + "state": "accepted", + "units": 17 + }, + "GI-5-3": { + "date": "2025-12-18", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-6-0": { + "date": "2026-01-07", + "po": "PO6", + "state": "accepted", + "units": 16 + }, + "GI-6-1": { + "date": "2025-12-21", + "po": "PO6", + "state": "quarantine", + "units": 24 + }, + "GI-6-2": { + "date": "2026-01-13", + "po": "PO6", + "state": "accepted", + "units": 22 + }, + "GI-6-3": { + "date": "2026-01-03", + "po": "PO6", + "state": "accepted", + "units": 14 + } + }, + "invoice_inbox": { + "IV-1363-4-1": { + "date": "2025-12-22", + "po": "PO4", + "state": "review", + "unit_price_cents": 5641, + "units": 21, + "vendor": "V1" + }, + "IV-1888-6-2": { + "date": "2025-12-30", + "po": "PO6", + "state": "void", + "unit_price_cents": 14592, + "units": 19, + "vendor": "V0" + }, + "IV-2327-1-1": { + "date": "2026-01-02", + "po": "PO1", + "state": "void", + "unit_price_cents": 23839, + "units": 17, + "vendor": "Unknown" + }, + "IV-2446-2-3": { + "date": "2025-12-28", + "po": "PO2", + "state": "review", + "unit_price_cents": 7979, + "units": 7, + "vendor": "V4" + }, + "IV-2713-0-0": { + "date": "2025-12-25", + "po": "PO0", + "state": "review", + "unit_price_cents": 19004, + "units": 1, + "vendor": "V0" + }, + "IV-2717-3-0": { + "date": "2025-12-25", + "po": "PO3", + "state": "review", + "unit_price_cents": 15500, + "units": 23, + "vendor": "V4" + }, + "IV-3267-6-1": { + "date": "2025-12-30", + "po": "PO6", + "state": "review", + "unit_price_cents": 14678, + "units": 18, + "vendor": "V0" + }, + "IV-3406-4-0": { + "date": "2025-12-25", + "po": "PO4", + "state": "review", + "unit_price_cents": 4615, + "units": 15, + "vendor": "V1" + }, + "IV-4086-0-3": { + "date": "2025-12-29", + "po": "PO0", + "state": "review", + "unit_price_cents": 19961, + "units": 15, + "vendor": "V0" + }, + "IV-4604-2-2": { + "date": "2025-12-29", + "po": "PO2", + "state": "review", + "unit_price_cents": 7304, + "units": 4, + "vendor": "Unknown" + }, + "IV-4760-3-1": { + "date": "2026-01-05", + "po": "PO3", + "state": "review", + "unit_price_cents": 15369, + "units": 16, + "vendor": "Unknown" + }, + "IV-4797-6-0": { + "date": "2025-12-25", + "po": "PO6", + "state": "review", + "unit_price_cents": 13630, + "units": 4, + "vendor": "V0" + }, + "IV-5095-5-0": { + "date": "2025-12-25", + "po": "PO5", + "state": "review", + "unit_price_cents": 22473, + "units": 4, + "vendor": "V3" + }, + "IV-5279-1-0": { + "date": "2025-12-25", + "po": "PO1", + "state": "review", + "unit_price_cents": 21786, + "units": 5, + "vendor": "V1" + }, + "IV-5456-2-0": { + "date": "2025-12-25", + "po": "PO2", + "state": "review", + "unit_price_cents": 7036, + "units": 16, + "vendor": "V4" + }, + "IV-7150-1-2": { + "date": "2026-01-07", + "po": "PO1", + "state": "review", + "unit_price_cents": 23315, + "units": 12, + "vendor": "V1" + }, + "IV-8011-3-2": { + "date": "2026-01-01", + "po": "PO3", + "state": "review", + "unit_price_cents": 16832, + "units": 5, + "vendor": "V4" + }, + "IV-8428-2-1": { + "date": "2025-12-21", + "po": "PO2", + "state": "review", + "unit_price_cents": 8552, + "units": 21, + "vendor": "V4" + }, + "IV-8452-0-2": { + "date": "2025-12-22", + "po": "PO0", + "state": "review", + "unit_price_cents": 20464, + "units": 25, + "vendor": "Unknown" + }, + "IV-8879-5-1": { + "date": "2025-12-24", + "po": "PO5", + "state": "review", + "unit_price_cents": 23470, + "units": 16, + "vendor": "V3" + }, + "IV-9221-0-1": { + "date": "2026-01-02", + "po": "PO0", + "state": "void", + "unit_price_cents": 21031, + "units": 14, + "vendor": "V0" + } + }, + "purchase_orders": { + "PO0": { + "unit": "West", + "unit_price_cents": 19004, + "vendor": "V0" + }, + "PO1": { + "unit": "West", + "unit_price_cents": 21786, + "vendor": "V1" + }, + "PO2": { + "unit": "West", + "unit_price_cents": 7036, + "vendor": "V4" + }, + "PO3": { + "unit": "West", + "unit_price_cents": 15500, + "vendor": "V4" + }, + "PO4": { + "unit": "West", + "unit_price_cents": 4615, + "vendor": "V1" + }, + "PO5": { + "unit": "West", + "unit_price_cents": 22473, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 13630, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 21 + }, + "V1": { + "net_days": 21 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-015/instruction.md b/tasks/autom-supplier-invoice-match-015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3db709f1e2d9250fbdeb23ec38c25bc0346836f9 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-015/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit West at 2026-01-08. Handle invoices in review attached to that unit's purchase orders, invoice dates 2025-12-25 through 2026-01-08 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 300 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-015/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-015/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1f10d9cd9a0e8e18049f5ef1553aa1b89faab824 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-015/solution/files/actions.jsonl @@ -0,0 +1,24 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-2713-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4086-0-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5279-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7150-1-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5456-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4604-2-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-2446-2-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-2717-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4760-3-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-8011-3-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-3406-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5095-5-0", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 19004, "due": "2026-01-15", "invoice": "IV-2713-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-2713-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 356500, "due": "2026-01-15", "invoice": "IV-2717-3-0", "po": "PO3", "status": "posted", "units": 23}, "id": "book-IV-2717-3-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 69225, "due": "2026-01-15", "invoice": "IV-3406-4-0", "po": "PO4", "status": "posted", "units": 15}, "id": "book-IV-3406-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 89892, "due": "2026-01-26", "invoice": "IV-5095-5-0", "po": "PO5", "status": "posted", "units": 4}, "id": "book-IV-5095-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 108930, "due": "2026-01-15", "invoice": "IV-5279-1-0", "po": "PO1", "status": "posted", "units": 5}, "id": "book-IV-5279-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 112576, "due": "2026-01-15", "invoice": "IV-5456-2-0", "po": "PO2", "status": "posted", "units": 16}, "id": "book-IV-5456-2-0", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-2446-2-3", "issues": ["price"], "po": "PO2"}, "id": "case-IV-2446-2-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4086-0-3", "issues": ["price"], "po": "PO0"}, "id": "case-IV-4086-0-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4604-2-2", "issues": ["vendor", "price"], "po": "PO2"}, "id": "case-IV-4604-2-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-8011-3-2", "issues": ["price"], "po": "PO3"}, "id": "case-IV-8011-3-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4760-3-1", "issues": ["vendor"], "po": "PO3"}, "id": "case-IV-4760-3-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7150-1-2", "issues": ["price"], "po": "PO1"}, "id": "case-IV-7150-1-2", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-015/solution/solve.sh b/tasks/autom-supplier-invoice-match-015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-015/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-015/task.toml b/tasks/autom-supplier-invoice-match-015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cf2094486a2b8d7c8236ff4968007e2a102f8b8b --- /dev/null +++ b/tasks/autom-supplier-invoice-match-015/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-015" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 15 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-015" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-015/tests/expected.json b/tasks/autom-supplier-invoice-match-015/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-015/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-015/tests/grade.py b/tasks/autom-supplier-invoice-match-015/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-015/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-015/tests/replay.py b/tasks/autom-supplier-invoice-match-015/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-015/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-015/tests/target.json b/tasks/autom-supplier-invoice-match-015/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..52691d605378668c180533930b26fbf2c9d73783 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-015/tests/target.json @@ -0,0 +1,529 @@ +{ + "ap_postings": { + "book-IV-2713-0-0": { + "amount_cents": 19004, + "due": "2026-01-15", + "invoice": "IV-2713-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "book-IV-2717-3-0": { + "amount_cents": 356500, + "due": "2026-01-15", + "invoice": "IV-2717-3-0", + "po": "PO3", + "status": "posted", + "units": 23 + }, + "book-IV-3406-4-0": { + "amount_cents": 69225, + "due": "2026-01-15", + "invoice": "IV-3406-4-0", + "po": "PO4", + "status": "posted", + "units": 15 + }, + "book-IV-5095-5-0": { + "amount_cents": 89892, + "due": "2026-01-26", + "invoice": "IV-5095-5-0", + "po": "PO5", + "status": "posted", + "units": 4 + }, + "book-IV-5279-1-0": { + "amount_cents": 108930, + "due": "2026-01-15", + "invoice": "IV-5279-1-0", + "po": "PO1", + "status": "posted", + "units": 5 + }, + "book-IV-5456-2-0": { + "amount_cents": 112576, + "due": "2026-01-15", + "invoice": "IV-5456-2-0", + "po": "PO2", + "status": "posted", + "units": 16 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 5 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 0 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 3 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 2 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 8 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 8 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 3 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-01-07", + "po": "PO0", + "state": "accepted", + "units": 19 + }, + "GI-0-1": { + "date": "2025-12-24", + "po": "PO0", + "state": "accepted", + "units": 27 + }, + "GI-0-2": { + "date": "2026-01-07", + "po": "PO0", + "state": "accepted", + "units": 18 + }, + "GI-0-3": { + "date": "2025-12-15", + "po": "PO0", + "state": "quarantine", + "units": 13 + }, + "GI-1-0": { + "date": "2026-01-07", + "po": "PO1", + "state": "accepted", + "units": 26 + }, + "GI-1-1": { + "date": "2026-01-07", + "po": "PO1", + "state": "quarantine", + "units": 13 + }, + "GI-1-2": { + "date": "2026-01-02", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-1-3": { + "date": "2026-01-10", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-2-0": { + "date": "2026-01-07", + "po": "PO2", + "state": "accepted", + "units": 27 + }, + "GI-2-1": { + "date": "2025-12-25", + "po": "PO2", + "state": "accepted", + "units": 24 + }, + "GI-2-2": { + "date": "2026-01-02", + "po": "PO2", + "state": "quarantine", + "units": 18 + }, + "GI-2-3": { + "date": "2026-01-01", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-3-0": { + "date": "2026-01-07", + "po": "PO3", + "state": "accepted", + "units": 28 + }, + "GI-3-1": { + "date": "2025-12-23", + "po": "PO3", + "state": "quarantine", + "units": 18 + }, + "GI-3-2": { + "date": "2025-12-25", + "po": "PO3", + "state": "accepted", + "units": 23 + }, + "GI-3-3": { + "date": "2026-01-13", + "po": "PO3", + "state": "quarantine", + "units": 17 + }, + "GI-4-0": { + "date": "2026-01-07", + "po": "PO4", + "state": "accepted", + "units": 20 + }, + "GI-4-1": { + "date": "2025-12-16", + "po": "PO4", + "state": "quarantine", + "units": 23 + }, + "GI-4-2": { + "date": "2026-01-08", + "po": "PO4", + "state": "accepted", + "units": 18 + }, + "GI-4-3": { + "date": "2026-01-09", + "po": "PO4", + "state": "accepted", + "units": 16 + }, + "GI-5-0": { + "date": "2026-01-07", + "po": "PO5", + "state": "accepted", + "units": 16 + }, + "GI-5-1": { + "date": "2025-12-28", + "po": "PO5", + "state": "quarantine", + "units": 24 + }, + "GI-5-2": { + "date": "2026-01-03", + "po": "PO5", + "state": "accepted", + "units": 17 + }, + "GI-5-3": { + "date": "2025-12-18", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-6-0": { + "date": "2026-01-07", + "po": "PO6", + "state": "accepted", + "units": 16 + }, + "GI-6-1": { + "date": "2025-12-21", + "po": "PO6", + "state": "quarantine", + "units": 24 + }, + "GI-6-2": { + "date": "2026-01-13", + "po": "PO6", + "state": "accepted", + "units": 22 + }, + "GI-6-3": { + "date": "2026-01-03", + "po": "PO6", + "state": "accepted", + "units": 14 + } + }, + "invoice_inbox": { + "IV-1363-4-1": { + "date": "2025-12-22", + "po": "PO4", + "state": "review", + "unit_price_cents": 5641, + "units": 21, + "vendor": "V1" + }, + "IV-1888-6-2": { + "date": "2025-12-30", + "po": "PO6", + "state": "void", + "unit_price_cents": 14592, + "units": 19, + "vendor": "V0" + }, + "IV-2327-1-1": { + "date": "2026-01-02", + "po": "PO1", + "state": "void", + "unit_price_cents": 23839, + "units": 17, + "vendor": "Unknown" + }, + "IV-2446-2-3": { + "date": "2025-12-28", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 7979, + "units": 7, + "vendor": "V4" + }, + "IV-2713-0-0": { + "date": "2025-12-25", + "po": "PO0", + "state": "posted", + "unit_price_cents": 19004, + "units": 1, + "vendor": "V0" + }, + "IV-2717-3-0": { + "date": "2025-12-25", + "po": "PO3", + "state": "posted", + "unit_price_cents": 15500, + "units": 23, + "vendor": "V4" + }, + "IV-3267-6-1": { + "date": "2025-12-30", + "po": "PO6", + "state": "review", + "unit_price_cents": 14678, + "units": 18, + "vendor": "V0" + }, + "IV-3406-4-0": { + "date": "2025-12-25", + "po": "PO4", + "state": "posted", + "unit_price_cents": 4615, + "units": 15, + "vendor": "V1" + }, + "IV-4086-0-3": { + "date": "2025-12-29", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 19961, + "units": 15, + "vendor": "V0" + }, + "IV-4604-2-2": { + "date": "2025-12-29", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 7304, + "units": 4, + "vendor": "Unknown" + }, + "IV-4760-3-1": { + "date": "2026-01-05", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 15369, + "units": 16, + "vendor": "Unknown" + }, + "IV-4797-6-0": { + "date": "2025-12-25", + "po": "PO6", + "state": "review", + "unit_price_cents": 13630, + "units": 4, + "vendor": "V0" + }, + "IV-5095-5-0": { + "date": "2025-12-25", + "po": "PO5", + "state": "posted", + "unit_price_cents": 22473, + "units": 4, + "vendor": "V3" + }, + "IV-5279-1-0": { + "date": "2025-12-25", + "po": "PO1", + "state": "posted", + "unit_price_cents": 21786, + "units": 5, + "vendor": "V1" + }, + "IV-5456-2-0": { + "date": "2025-12-25", + "po": "PO2", + "state": "posted", + "unit_price_cents": 7036, + "units": 16, + "vendor": "V4" + }, + "IV-7150-1-2": { + "date": "2026-01-07", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 23315, + "units": 12, + "vendor": "V1" + }, + "IV-8011-3-2": { + "date": "2026-01-01", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 16832, + "units": 5, + "vendor": "V4" + }, + "IV-8428-2-1": { + "date": "2025-12-21", + "po": "PO2", + "state": "review", + "unit_price_cents": 8552, + "units": 21, + "vendor": "V4" + }, + "IV-8452-0-2": { + "date": "2025-12-22", + "po": "PO0", + "state": "review", + "unit_price_cents": 20464, + "units": 25, + "vendor": "Unknown" + }, + "IV-8879-5-1": { + "date": "2025-12-24", + "po": "PO5", + "state": "review", + "unit_price_cents": 23470, + "units": 16, + "vendor": "V3" + }, + "IV-9221-0-1": { + "date": "2026-01-02", + "po": "PO0", + "state": "void", + "unit_price_cents": 21031, + "units": 14, + "vendor": "V0" + } + }, + "purchase_orders": { + "PO0": { + "unit": "West", + "unit_price_cents": 19004, + "vendor": "V0" + }, + "PO1": { + "unit": "West", + "unit_price_cents": 21786, + "vendor": "V1" + }, + "PO2": { + "unit": "West", + "unit_price_cents": 7036, + "vendor": "V4" + }, + "PO3": { + "unit": "West", + "unit_price_cents": 15500, + "vendor": "V4" + }, + "PO4": { + "unit": "West", + "unit_price_cents": 4615, + "vendor": "V1" + }, + "PO5": { + "unit": "West", + "unit_price_cents": 22473, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 13630, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-2446-2-3": { + "invoice": "IV-2446-2-3", + "issues": [ + "price" + ], + "po": "PO2" + }, + "case-IV-4086-0-3": { + "invoice": "IV-4086-0-3", + "issues": [ + "price" + ], + "po": "PO0" + }, + "case-IV-4604-2-2": { + "invoice": "IV-4604-2-2", + "issues": [ + "vendor", + "price" + ], + "po": "PO2" + }, + "case-IV-4760-3-1": { + "invoice": "IV-4760-3-1", + "issues": [ + "vendor" + ], + "po": "PO3" + }, + "case-IV-7150-1-2": { + "invoice": "IV-7150-1-2", + "issues": [ + "price" + ], + "po": "PO1" + }, + "case-IV-8011-3-2": { + "invoice": "IV-8011-3-2", + "issues": [ + "price" + ], + "po": "PO3" + } + }, + "vendors": { + "V0": { + "net_days": 21 + }, + "V1": { + "net_days": 21 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-015/tests/test.sh b/tasks/autom-supplier-invoice-match-015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-015/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-015/tests/world.json b/tasks/autom-supplier-invoice-match-015/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..c3f56eefab5e1118a350cb9b3269eddc7ee2d0c9 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-015/tests/world.json @@ -0,0 +1,438 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 5 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 0 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 3 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 2 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 8 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 8 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 3 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-01-07", + "po": "PO0", + "state": "accepted", + "units": 19 + }, + "GI-0-1": { + "date": "2025-12-24", + "po": "PO0", + "state": "accepted", + "units": 27 + }, + "GI-0-2": { + "date": "2026-01-07", + "po": "PO0", + "state": "accepted", + "units": 18 + }, + "GI-0-3": { + "date": "2025-12-15", + "po": "PO0", + "state": "quarantine", + "units": 13 + }, + "GI-1-0": { + "date": "2026-01-07", + "po": "PO1", + "state": "accepted", + "units": 26 + }, + "GI-1-1": { + "date": "2026-01-07", + "po": "PO1", + "state": "quarantine", + "units": 13 + }, + "GI-1-2": { + "date": "2026-01-02", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-1-3": { + "date": "2026-01-10", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-2-0": { + "date": "2026-01-07", + "po": "PO2", + "state": "accepted", + "units": 27 + }, + "GI-2-1": { + "date": "2025-12-25", + "po": "PO2", + "state": "accepted", + "units": 24 + }, + "GI-2-2": { + "date": "2026-01-02", + "po": "PO2", + "state": "quarantine", + "units": 18 + }, + "GI-2-3": { + "date": "2026-01-01", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-3-0": { + "date": "2026-01-07", + "po": "PO3", + "state": "accepted", + "units": 28 + }, + "GI-3-1": { + "date": "2025-12-23", + "po": "PO3", + "state": "quarantine", + "units": 18 + }, + "GI-3-2": { + "date": "2025-12-25", + "po": "PO3", + "state": "accepted", + "units": 23 + }, + "GI-3-3": { + "date": "2026-01-13", + "po": "PO3", + "state": "quarantine", + "units": 17 + }, + "GI-4-0": { + "date": "2026-01-07", + "po": "PO4", + "state": "accepted", + "units": 20 + }, + "GI-4-1": { + "date": "2025-12-16", + "po": "PO4", + "state": "quarantine", + "units": 23 + }, + "GI-4-2": { + "date": "2026-01-08", + "po": "PO4", + "state": "accepted", + "units": 18 + }, + "GI-4-3": { + "date": "2026-01-09", + "po": "PO4", + "state": "accepted", + "units": 16 + }, + "GI-5-0": { + "date": "2026-01-07", + "po": "PO5", + "state": "accepted", + "units": 16 + }, + "GI-5-1": { + "date": "2025-12-28", + "po": "PO5", + "state": "quarantine", + "units": 24 + }, + "GI-5-2": { + "date": "2026-01-03", + "po": "PO5", + "state": "accepted", + "units": 17 + }, + "GI-5-3": { + "date": "2025-12-18", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-6-0": { + "date": "2026-01-07", + "po": "PO6", + "state": "accepted", + "units": 16 + }, + "GI-6-1": { + "date": "2025-12-21", + "po": "PO6", + "state": "quarantine", + "units": 24 + }, + "GI-6-2": { + "date": "2026-01-13", + "po": "PO6", + "state": "accepted", + "units": 22 + }, + "GI-6-3": { + "date": "2026-01-03", + "po": "PO6", + "state": "accepted", + "units": 14 + } + }, + "invoice_inbox": { + "IV-1363-4-1": { + "date": "2025-12-22", + "po": "PO4", + "state": "review", + "unit_price_cents": 5641, + "units": 21, + "vendor": "V1" + }, + "IV-1888-6-2": { + "date": "2025-12-30", + "po": "PO6", + "state": "void", + "unit_price_cents": 14592, + "units": 19, + "vendor": "V0" + }, + "IV-2327-1-1": { + "date": "2026-01-02", + "po": "PO1", + "state": "void", + "unit_price_cents": 23839, + "units": 17, + "vendor": "Unknown" + }, + "IV-2446-2-3": { + "date": "2025-12-28", + "po": "PO2", + "state": "review", + "unit_price_cents": 7979, + "units": 7, + "vendor": "V4" + }, + "IV-2713-0-0": { + "date": "2025-12-25", + "po": "PO0", + "state": "review", + "unit_price_cents": 19004, + "units": 1, + "vendor": "V0" + }, + "IV-2717-3-0": { + "date": "2025-12-25", + "po": "PO3", + "state": "review", + "unit_price_cents": 15500, + "units": 23, + "vendor": "V4" + }, + "IV-3267-6-1": { + "date": "2025-12-30", + "po": "PO6", + "state": "review", + "unit_price_cents": 14678, + "units": 18, + "vendor": "V0" + }, + "IV-3406-4-0": { + "date": "2025-12-25", + "po": "PO4", + "state": "review", + "unit_price_cents": 4615, + "units": 15, + "vendor": "V1" + }, + "IV-4086-0-3": { + "date": "2025-12-29", + "po": "PO0", + "state": "review", + "unit_price_cents": 19961, + "units": 15, + "vendor": "V0" + }, + "IV-4604-2-2": { + "date": "2025-12-29", + "po": "PO2", + "state": "review", + "unit_price_cents": 7304, + "units": 4, + "vendor": "Unknown" + }, + "IV-4760-3-1": { + "date": "2026-01-05", + "po": "PO3", + "state": "review", + "unit_price_cents": 15369, + "units": 16, + "vendor": "Unknown" + }, + "IV-4797-6-0": { + "date": "2025-12-25", + "po": "PO6", + "state": "review", + "unit_price_cents": 13630, + "units": 4, + "vendor": "V0" + }, + "IV-5095-5-0": { + "date": "2025-12-25", + "po": "PO5", + "state": "review", + "unit_price_cents": 22473, + "units": 4, + "vendor": "V3" + }, + "IV-5279-1-0": { + "date": "2025-12-25", + "po": "PO1", + "state": "review", + "unit_price_cents": 21786, + "units": 5, + "vendor": "V1" + }, + "IV-5456-2-0": { + "date": "2025-12-25", + "po": "PO2", + "state": "review", + "unit_price_cents": 7036, + "units": 16, + "vendor": "V4" + }, + "IV-7150-1-2": { + "date": "2026-01-07", + "po": "PO1", + "state": "review", + "unit_price_cents": 23315, + "units": 12, + "vendor": "V1" + }, + "IV-8011-3-2": { + "date": "2026-01-01", + "po": "PO3", + "state": "review", + "unit_price_cents": 16832, + "units": 5, + "vendor": "V4" + }, + "IV-8428-2-1": { + "date": "2025-12-21", + "po": "PO2", + "state": "review", + "unit_price_cents": 8552, + "units": 21, + "vendor": "V4" + }, + "IV-8452-0-2": { + "date": "2025-12-22", + "po": "PO0", + "state": "review", + "unit_price_cents": 20464, + "units": 25, + "vendor": "Unknown" + }, + "IV-8879-5-1": { + "date": "2025-12-24", + "po": "PO5", + "state": "review", + "unit_price_cents": 23470, + "units": 16, + "vendor": "V3" + }, + "IV-9221-0-1": { + "date": "2026-01-02", + "po": "PO0", + "state": "void", + "unit_price_cents": 21031, + "units": 14, + "vendor": "V0" + } + }, + "purchase_orders": { + "PO0": { + "unit": "West", + "unit_price_cents": 19004, + "vendor": "V0" + }, + "PO1": { + "unit": "West", + "unit_price_cents": 21786, + "vendor": "V1" + }, + "PO2": { + "unit": "West", + "unit_price_cents": 7036, + "vendor": "V4" + }, + "PO3": { + "unit": "West", + "unit_price_cents": 15500, + "vendor": "V4" + }, + "PO4": { + "unit": "West", + "unit_price_cents": 4615, + "vendor": "V1" + }, + "PO5": { + "unit": "West", + "unit_price_cents": 22473, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 13630, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 21 + }, + "V1": { + "net_days": 21 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-015/tests/world_check.py b/tasks/autom-supplier-invoice-match-015/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-015/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-015/validation/openenv.json b/tasks/autom-supplier-invoice-match-015/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-015/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-016/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-016/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-016/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-016/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-016/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..060ce2e73d837e2216d8bf12df2fb744195e3414 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-016/environment/inputs/world.json @@ -0,0 +1,406 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 5 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 8 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 3 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 0 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 4 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 6 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 4 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-01-30", + "po": "PO0", + "state": "accepted", + "units": 25 + }, + "GI-0-1": { + "date": "2026-01-12", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-2": { + "date": "2026-02-05", + "po": "PO0", + "state": "quarantine", + "units": 18 + }, + "GI-0-3": { + "date": "2026-01-20", + "po": "PO0", + "state": "accepted", + "units": 23 + }, + "GI-1-0": { + "date": "2026-01-30", + "po": "PO1", + "state": "accepted", + "units": 25 + }, + "GI-1-1": { + "date": "2026-01-31", + "po": "PO1", + "state": "accepted", + "units": 21 + }, + "GI-1-2": { + "date": "2026-01-20", + "po": "PO1", + "state": "quarantine", + "units": 21 + }, + "GI-1-3": { + "date": "2026-01-25", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-2-0": { + "date": "2026-01-30", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-2-1": { + "date": "2026-02-03", + "po": "PO2", + "state": "quarantine", + "units": 18 + }, + "GI-2-2": { + "date": "2026-02-04", + "po": "PO2", + "state": "quarantine", + "units": 15 + }, + "GI-2-3": { + "date": "2026-01-29", + "po": "PO2", + "state": "accepted", + "units": 12 + }, + "GI-3-0": { + "date": "2026-01-30", + "po": "PO3", + "state": "accepted", + "units": 14 + }, + "GI-3-1": { + "date": "2026-01-15", + "po": "PO3", + "state": "quarantine", + "units": 15 + }, + "GI-3-2": { + "date": "2026-01-26", + "po": "PO3", + "state": "quarantine", + "units": 28 + }, + "GI-3-3": { + "date": "2026-02-01", + "po": "PO3", + "state": "quarantine", + "units": 25 + }, + "GI-4-0": { + "date": "2026-01-30", + "po": "PO4", + "state": "accepted", + "units": 12 + }, + "GI-4-1": { + "date": "2026-01-23", + "po": "PO4", + "state": "quarantine", + "units": 24 + }, + "GI-4-2": { + "date": "2026-01-08", + "po": "PO4", + "state": "quarantine", + "units": 16 + }, + "GI-4-3": { + "date": "2026-01-14", + "po": "PO4", + "state": "quarantine", + "units": 16 + }, + "GI-5-0": { + "date": "2026-01-30", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-1": { + "date": "2026-01-11", + "po": "PO5", + "state": "accepted", + "units": 15 + }, + "GI-5-2": { + "date": "2026-02-01", + "po": "PO5", + "state": "accepted", + "units": 20 + }, + "GI-5-3": { + "date": "2026-01-25", + "po": "PO5", + "state": "accepted", + "units": 20 + }, + "GI-6-0": { + "date": "2026-01-30", + "po": "PO6", + "state": "accepted", + "units": 27 + }, + "GI-6-1": { + "date": "2026-01-24", + "po": "PO6", + "state": "accepted", + "units": 16 + }, + "GI-6-2": { + "date": "2026-01-31", + "po": "PO6", + "state": "quarantine", + "units": 22 + }, + "GI-6-3": { + "date": "2026-01-24", + "po": "PO6", + "state": "quarantine", + "units": 15 + } + }, + "invoice_inbox": { + "IV-3028-5-1": { + "date": "2026-01-29", + "po": "PO5", + "state": "review", + "unit_price_cents": 23121, + "units": 5, + "vendor": "V0" + }, + "IV-3268-4-2": { + "date": "2026-01-12", + "po": "PO4", + "state": "review", + "unit_price_cents": 10352, + "units": 7, + "vendor": "V2" + }, + "IV-3433-6-1": { + "date": "2026-01-08", + "po": "PO6", + "state": "review", + "unit_price_cents": 18606, + "units": 24, + "vendor": "V1" + }, + "IV-3863-4-1": { + "date": "2026-01-20", + "po": "PO4", + "state": "review", + "unit_price_cents": 10498, + "units": 25, + "vendor": "V2" + }, + "IV-3887-2-2": { + "date": "2026-01-28", + "po": "PO2", + "state": "review", + "unit_price_cents": 13565, + "units": 25, + "vendor": "V2" + }, + "IV-4592-4-0": { + "date": "2026-01-10", + "po": "PO4", + "state": "review", + "unit_price_cents": 9501, + "units": 12, + "vendor": "V2" + }, + "IV-4680-2-0": { + "date": "2026-01-10", + "po": "PO2", + "state": "review", + "unit_price_cents": 11393, + "units": 10, + "vendor": "V2" + }, + "IV-4728-1-1": { + "date": "2026-01-23", + "po": "PO1", + "state": "review", + "unit_price_cents": 21414, + "units": 5, + "vendor": "V1" + }, + "IV-5200-0-0": { + "date": "2026-01-10", + "po": "PO0", + "state": "review", + "unit_price_cents": 17387, + "units": 1, + "vendor": "V2" + }, + "IV-5238-6-0": { + "date": "2026-01-10", + "po": "PO6", + "state": "review", + "unit_price_cents": 17032, + "units": 13, + "vendor": "V1" + }, + "IV-5373-2-1": { + "date": "2026-01-05", + "po": "PO2", + "state": "review", + "unit_price_cents": 12029, + "units": 8, + "vendor": "V2" + }, + "IV-6022-3-1": { + "date": "2026-01-13", + "po": "PO3", + "state": "review", + "unit_price_cents": 5596, + "units": 8, + "vendor": "Unknown" + }, + "IV-6025-2-3": { + "date": "2026-01-14", + "po": "PO2", + "state": "review", + "unit_price_cents": 11664, + "units": 16, + "vendor": "V2" + }, + "IV-8121-3-0": { + "date": "2026-01-10", + "po": "PO3", + "state": "review", + "unit_price_cents": 5134, + "units": 20, + "vendor": "V1" + }, + "IV-8178-5-0": { + "date": "2026-01-10", + "po": "PO5", + "state": "review", + "unit_price_cents": 22877, + "units": 3, + "vendor": "V0" + }, + "IV-8187-1-0": { + "date": "2026-01-10", + "po": "PO1", + "state": "review", + "unit_price_cents": 19332, + "units": 20, + "vendor": "V1" + }, + "IV-8820-0-1": { + "date": "2026-01-09", + "po": "PO0", + "state": "review", + "unit_price_cents": 19434, + "units": 16, + "vendor": "Unknown" + } + }, + "purchase_orders": { + "PO0": { + "unit": "Central", + "unit_price_cents": 17387, + "vendor": "V2" + }, + "PO1": { + "unit": "Central", + "unit_price_cents": 19332, + "vendor": "V1" + }, + "PO2": { + "unit": "Central", + "unit_price_cents": 11393, + "vendor": "V2" + }, + "PO3": { + "unit": "Central", + "unit_price_cents": 5134, + "vendor": "V1" + }, + "PO4": { + "unit": "Central", + "unit_price_cents": 9501, + "vendor": "V2" + }, + "PO5": { + "unit": "Central", + "unit_price_cents": 22877, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 17032, + "vendor": "V1" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 45 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-016/instruction.md b/tasks/autom-supplier-invoice-match-016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b760a62a05da83b81454eb1c26a84b989770c6b0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-016/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit Central at 2026-01-31. Handle invoices in review attached to that unit's purchase orders, invoice dates 2026-01-10 through 2026-01-31 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 100 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-016/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-016/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b28ba09f2c57c7722912117aea1a77e37bd88323 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-016/solution/files/actions.jsonl @@ -0,0 +1,26 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5200-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8187-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4728-1-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-4680-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3887-2-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-6025-2-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-8121-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-6022-3-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4592-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3863-4-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3268-4-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8178-5-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3028-5-1", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 113930, "due": "2026-02-24", "invoice": "IV-4680-2-0", "po": "PO2", "status": "posted", "units": 10}, "id": "book-IV-4680-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 17387, "due": "2026-02-24", "invoice": "IV-5200-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-5200-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 68631, "due": "2026-02-24", "invoice": "IV-8178-5-0", "po": "PO5", "status": "posted", "units": 3}, "id": "book-IV-8178-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 386640, "due": "2026-01-26", "invoice": "IV-8187-1-0", "po": "PO1", "status": "posted", "units": 20}, "id": "book-IV-8187-1-0", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4592-4-0", "issues": ["units"], "po": "PO4"}, "id": "case-IV-4592-4-0", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-8121-3-0", "issues": ["units"], "po": "PO3"}, "id": "case-IV-8121-3-0", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3268-4-2", "issues": ["price"], "po": "PO4"}, "id": "case-IV-3268-4-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-6022-3-1", "issues": ["vendor", "price"], "po": "PO3"}, "id": "case-IV-6022-3-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-6025-2-3", "issues": ["price"], "po": "PO2"}, "id": "case-IV-6025-2-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3863-4-1", "issues": ["price", "units"], "po": "PO4"}, "id": "case-IV-3863-4-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4728-1-1", "issues": ["price"], "po": "PO1"}, "id": "case-IV-4728-1-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3887-2-2", "issues": ["price", "units"], "po": "PO2"}, "id": "case-IV-3887-2-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3028-5-1", "issues": ["price"], "po": "PO5"}, "id": "case-IV-3028-5-1", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-016/solution/solve.sh b/tasks/autom-supplier-invoice-match-016/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-016/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-016/task.toml b/tasks/autom-supplier-invoice-match-016/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cd9da882fdf8317f960f005505a6fbb8986427ae --- /dev/null +++ b/tasks/autom-supplier-invoice-match-016/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-016" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 16 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-016" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-016/tests/expected.json b/tasks/autom-supplier-invoice-match-016/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-016/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-016/tests/grade.py b/tasks/autom-supplier-invoice-match-016/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-016/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-016/tests/replay.py b/tasks/autom-supplier-invoice-match-016/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-016/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-016/tests/target.json b/tasks/autom-supplier-invoice-match-016/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..1e977439ca8ed67cc612b7c561c5ea7bad777c84 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-016/tests/target.json @@ -0,0 +1,504 @@ +{ + "ap_postings": { + "book-IV-4680-2-0": { + "amount_cents": 113930, + "due": "2026-02-24", + "invoice": "IV-4680-2-0", + "po": "PO2", + "status": "posted", + "units": 10 + }, + "book-IV-5200-0-0": { + "amount_cents": 17387, + "due": "2026-02-24", + "invoice": "IV-5200-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "book-IV-8178-5-0": { + "amount_cents": 68631, + "due": "2026-02-24", + "invoice": "IV-8178-5-0", + "po": "PO5", + "status": "posted", + "units": 3 + }, + "book-IV-8187-1-0": { + "amount_cents": 386640, + "due": "2026-01-26", + "invoice": "IV-8187-1-0", + "po": "PO1", + "status": "posted", + "units": 20 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 5 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 8 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 3 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 0 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 4 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 6 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 4 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-01-30", + "po": "PO0", + "state": "accepted", + "units": 25 + }, + "GI-0-1": { + "date": "2026-01-12", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-2": { + "date": "2026-02-05", + "po": "PO0", + "state": "quarantine", + "units": 18 + }, + "GI-0-3": { + "date": "2026-01-20", + "po": "PO0", + "state": "accepted", + "units": 23 + }, + "GI-1-0": { + "date": "2026-01-30", + "po": "PO1", + "state": "accepted", + "units": 25 + }, + "GI-1-1": { + "date": "2026-01-31", + "po": "PO1", + "state": "accepted", + "units": 21 + }, + "GI-1-2": { + "date": "2026-01-20", + "po": "PO1", + "state": "quarantine", + "units": 21 + }, + "GI-1-3": { + "date": "2026-01-25", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-2-0": { + "date": "2026-01-30", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-2-1": { + "date": "2026-02-03", + "po": "PO2", + "state": "quarantine", + "units": 18 + }, + "GI-2-2": { + "date": "2026-02-04", + "po": "PO2", + "state": "quarantine", + "units": 15 + }, + "GI-2-3": { + "date": "2026-01-29", + "po": "PO2", + "state": "accepted", + "units": 12 + }, + "GI-3-0": { + "date": "2026-01-30", + "po": "PO3", + "state": "accepted", + "units": 14 + }, + "GI-3-1": { + "date": "2026-01-15", + "po": "PO3", + "state": "quarantine", + "units": 15 + }, + "GI-3-2": { + "date": "2026-01-26", + "po": "PO3", + "state": "quarantine", + "units": 28 + }, + "GI-3-3": { + "date": "2026-02-01", + "po": "PO3", + "state": "quarantine", + "units": 25 + }, + "GI-4-0": { + "date": "2026-01-30", + "po": "PO4", + "state": "accepted", + "units": 12 + }, + "GI-4-1": { + "date": "2026-01-23", + "po": "PO4", + "state": "quarantine", + "units": 24 + }, + "GI-4-2": { + "date": "2026-01-08", + "po": "PO4", + "state": "quarantine", + "units": 16 + }, + "GI-4-3": { + "date": "2026-01-14", + "po": "PO4", + "state": "quarantine", + "units": 16 + }, + "GI-5-0": { + "date": "2026-01-30", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-1": { + "date": "2026-01-11", + "po": "PO5", + "state": "accepted", + "units": 15 + }, + "GI-5-2": { + "date": "2026-02-01", + "po": "PO5", + "state": "accepted", + "units": 20 + }, + "GI-5-3": { + "date": "2026-01-25", + "po": "PO5", + "state": "accepted", + "units": 20 + }, + "GI-6-0": { + "date": "2026-01-30", + "po": "PO6", + "state": "accepted", + "units": 27 + }, + "GI-6-1": { + "date": "2026-01-24", + "po": "PO6", + "state": "accepted", + "units": 16 + }, + "GI-6-2": { + "date": "2026-01-31", + "po": "PO6", + "state": "quarantine", + "units": 22 + }, + "GI-6-3": { + "date": "2026-01-24", + "po": "PO6", + "state": "quarantine", + "units": 15 + } + }, + "invoice_inbox": { + "IV-3028-5-1": { + "date": "2026-01-29", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 23121, + "units": 5, + "vendor": "V0" + }, + "IV-3268-4-2": { + "date": "2026-01-12", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 10352, + "units": 7, + "vendor": "V2" + }, + "IV-3433-6-1": { + "date": "2026-01-08", + "po": "PO6", + "state": "review", + "unit_price_cents": 18606, + "units": 24, + "vendor": "V1" + }, + "IV-3863-4-1": { + "date": "2026-01-20", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 10498, + "units": 25, + "vendor": "V2" + }, + "IV-3887-2-2": { + "date": "2026-01-28", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 13565, + "units": 25, + "vendor": "V2" + }, + "IV-4592-4-0": { + "date": "2026-01-10", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 9501, + "units": 12, + "vendor": "V2" + }, + "IV-4680-2-0": { + "date": "2026-01-10", + "po": "PO2", + "state": "posted", + "unit_price_cents": 11393, + "units": 10, + "vendor": "V2" + }, + "IV-4728-1-1": { + "date": "2026-01-23", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 21414, + "units": 5, + "vendor": "V1" + }, + "IV-5200-0-0": { + "date": "2026-01-10", + "po": "PO0", + "state": "posted", + "unit_price_cents": 17387, + "units": 1, + "vendor": "V2" + }, + "IV-5238-6-0": { + "date": "2026-01-10", + "po": "PO6", + "state": "review", + "unit_price_cents": 17032, + "units": 13, + "vendor": "V1" + }, + "IV-5373-2-1": { + "date": "2026-01-05", + "po": "PO2", + "state": "review", + "unit_price_cents": 12029, + "units": 8, + "vendor": "V2" + }, + "IV-6022-3-1": { + "date": "2026-01-13", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 5596, + "units": 8, + "vendor": "Unknown" + }, + "IV-6025-2-3": { + "date": "2026-01-14", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 11664, + "units": 16, + "vendor": "V2" + }, + "IV-8121-3-0": { + "date": "2026-01-10", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 5134, + "units": 20, + "vendor": "V1" + }, + "IV-8178-5-0": { + "date": "2026-01-10", + "po": "PO5", + "state": "posted", + "unit_price_cents": 22877, + "units": 3, + "vendor": "V0" + }, + "IV-8187-1-0": { + "date": "2026-01-10", + "po": "PO1", + "state": "posted", + "unit_price_cents": 19332, + "units": 20, + "vendor": "V1" + }, + "IV-8820-0-1": { + "date": "2026-01-09", + "po": "PO0", + "state": "review", + "unit_price_cents": 19434, + "units": 16, + "vendor": "Unknown" + } + }, + "purchase_orders": { + "PO0": { + "unit": "Central", + "unit_price_cents": 17387, + "vendor": "V2" + }, + "PO1": { + "unit": "Central", + "unit_price_cents": 19332, + "vendor": "V1" + }, + "PO2": { + "unit": "Central", + "unit_price_cents": 11393, + "vendor": "V2" + }, + "PO3": { + "unit": "Central", + "unit_price_cents": 5134, + "vendor": "V1" + }, + "PO4": { + "unit": "Central", + "unit_price_cents": 9501, + "vendor": "V2" + }, + "PO5": { + "unit": "Central", + "unit_price_cents": 22877, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 17032, + "vendor": "V1" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-3028-5-1": { + "invoice": "IV-3028-5-1", + "issues": [ + "price" + ], + "po": "PO5" + }, + "case-IV-3268-4-2": { + "invoice": "IV-3268-4-2", + "issues": [ + "price" + ], + "po": "PO4" + }, + "case-IV-3863-4-1": { + "invoice": "IV-3863-4-1", + "issues": [ + "price", + "units" + ], + "po": "PO4" + }, + "case-IV-3887-2-2": { + "invoice": "IV-3887-2-2", + "issues": [ + "price", + "units" + ], + "po": "PO2" + }, + "case-IV-4592-4-0": { + "invoice": "IV-4592-4-0", + "issues": [ + "units" + ], + "po": "PO4" + }, + "case-IV-4728-1-1": { + "invoice": "IV-4728-1-1", + "issues": [ + "price" + ], + "po": "PO1" + }, + "case-IV-6022-3-1": { + "invoice": "IV-6022-3-1", + "issues": [ + "vendor", + "price" + ], + "po": "PO3" + }, + "case-IV-6025-2-3": { + "invoice": "IV-6025-2-3", + "issues": [ + "price" + ], + "po": "PO2" + }, + "case-IV-8121-3-0": { + "invoice": "IV-8121-3-0", + "issues": [ + "units" + ], + "po": "PO3" + } + }, + "vendors": { + "V0": { + "net_days": 45 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-016/tests/test.sh b/tasks/autom-supplier-invoice-match-016/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-016/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-016/tests/world.json b/tasks/autom-supplier-invoice-match-016/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..060ce2e73d837e2216d8bf12df2fb744195e3414 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-016/tests/world.json @@ -0,0 +1,406 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 5 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 8 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 3 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 0 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 4 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 6 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 4 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-01-30", + "po": "PO0", + "state": "accepted", + "units": 25 + }, + "GI-0-1": { + "date": "2026-01-12", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-2": { + "date": "2026-02-05", + "po": "PO0", + "state": "quarantine", + "units": 18 + }, + "GI-0-3": { + "date": "2026-01-20", + "po": "PO0", + "state": "accepted", + "units": 23 + }, + "GI-1-0": { + "date": "2026-01-30", + "po": "PO1", + "state": "accepted", + "units": 25 + }, + "GI-1-1": { + "date": "2026-01-31", + "po": "PO1", + "state": "accepted", + "units": 21 + }, + "GI-1-2": { + "date": "2026-01-20", + "po": "PO1", + "state": "quarantine", + "units": 21 + }, + "GI-1-3": { + "date": "2026-01-25", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-2-0": { + "date": "2026-01-30", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-2-1": { + "date": "2026-02-03", + "po": "PO2", + "state": "quarantine", + "units": 18 + }, + "GI-2-2": { + "date": "2026-02-04", + "po": "PO2", + "state": "quarantine", + "units": 15 + }, + "GI-2-3": { + "date": "2026-01-29", + "po": "PO2", + "state": "accepted", + "units": 12 + }, + "GI-3-0": { + "date": "2026-01-30", + "po": "PO3", + "state": "accepted", + "units": 14 + }, + "GI-3-1": { + "date": "2026-01-15", + "po": "PO3", + "state": "quarantine", + "units": 15 + }, + "GI-3-2": { + "date": "2026-01-26", + "po": "PO3", + "state": "quarantine", + "units": 28 + }, + "GI-3-3": { + "date": "2026-02-01", + "po": "PO3", + "state": "quarantine", + "units": 25 + }, + "GI-4-0": { + "date": "2026-01-30", + "po": "PO4", + "state": "accepted", + "units": 12 + }, + "GI-4-1": { + "date": "2026-01-23", + "po": "PO4", + "state": "quarantine", + "units": 24 + }, + "GI-4-2": { + "date": "2026-01-08", + "po": "PO4", + "state": "quarantine", + "units": 16 + }, + "GI-4-3": { + "date": "2026-01-14", + "po": "PO4", + "state": "quarantine", + "units": 16 + }, + "GI-5-0": { + "date": "2026-01-30", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-1": { + "date": "2026-01-11", + "po": "PO5", + "state": "accepted", + "units": 15 + }, + "GI-5-2": { + "date": "2026-02-01", + "po": "PO5", + "state": "accepted", + "units": 20 + }, + "GI-5-3": { + "date": "2026-01-25", + "po": "PO5", + "state": "accepted", + "units": 20 + }, + "GI-6-0": { + "date": "2026-01-30", + "po": "PO6", + "state": "accepted", + "units": 27 + }, + "GI-6-1": { + "date": "2026-01-24", + "po": "PO6", + "state": "accepted", + "units": 16 + }, + "GI-6-2": { + "date": "2026-01-31", + "po": "PO6", + "state": "quarantine", + "units": 22 + }, + "GI-6-3": { + "date": "2026-01-24", + "po": "PO6", + "state": "quarantine", + "units": 15 + } + }, + "invoice_inbox": { + "IV-3028-5-1": { + "date": "2026-01-29", + "po": "PO5", + "state": "review", + "unit_price_cents": 23121, + "units": 5, + "vendor": "V0" + }, + "IV-3268-4-2": { + "date": "2026-01-12", + "po": "PO4", + "state": "review", + "unit_price_cents": 10352, + "units": 7, + "vendor": "V2" + }, + "IV-3433-6-1": { + "date": "2026-01-08", + "po": "PO6", + "state": "review", + "unit_price_cents": 18606, + "units": 24, + "vendor": "V1" + }, + "IV-3863-4-1": { + "date": "2026-01-20", + "po": "PO4", + "state": "review", + "unit_price_cents": 10498, + "units": 25, + "vendor": "V2" + }, + "IV-3887-2-2": { + "date": "2026-01-28", + "po": "PO2", + "state": "review", + "unit_price_cents": 13565, + "units": 25, + "vendor": "V2" + }, + "IV-4592-4-0": { + "date": "2026-01-10", + "po": "PO4", + "state": "review", + "unit_price_cents": 9501, + "units": 12, + "vendor": "V2" + }, + "IV-4680-2-0": { + "date": "2026-01-10", + "po": "PO2", + "state": "review", + "unit_price_cents": 11393, + "units": 10, + "vendor": "V2" + }, + "IV-4728-1-1": { + "date": "2026-01-23", + "po": "PO1", + "state": "review", + "unit_price_cents": 21414, + "units": 5, + "vendor": "V1" + }, + "IV-5200-0-0": { + "date": "2026-01-10", + "po": "PO0", + "state": "review", + "unit_price_cents": 17387, + "units": 1, + "vendor": "V2" + }, + "IV-5238-6-0": { + "date": "2026-01-10", + "po": "PO6", + "state": "review", + "unit_price_cents": 17032, + "units": 13, + "vendor": "V1" + }, + "IV-5373-2-1": { + "date": "2026-01-05", + "po": "PO2", + "state": "review", + "unit_price_cents": 12029, + "units": 8, + "vendor": "V2" + }, + "IV-6022-3-1": { + "date": "2026-01-13", + "po": "PO3", + "state": "review", + "unit_price_cents": 5596, + "units": 8, + "vendor": "Unknown" + }, + "IV-6025-2-3": { + "date": "2026-01-14", + "po": "PO2", + "state": "review", + "unit_price_cents": 11664, + "units": 16, + "vendor": "V2" + }, + "IV-8121-3-0": { + "date": "2026-01-10", + "po": "PO3", + "state": "review", + "unit_price_cents": 5134, + "units": 20, + "vendor": "V1" + }, + "IV-8178-5-0": { + "date": "2026-01-10", + "po": "PO5", + "state": "review", + "unit_price_cents": 22877, + "units": 3, + "vendor": "V0" + }, + "IV-8187-1-0": { + "date": "2026-01-10", + "po": "PO1", + "state": "review", + "unit_price_cents": 19332, + "units": 20, + "vendor": "V1" + }, + "IV-8820-0-1": { + "date": "2026-01-09", + "po": "PO0", + "state": "review", + "unit_price_cents": 19434, + "units": 16, + "vendor": "Unknown" + } + }, + "purchase_orders": { + "PO0": { + "unit": "Central", + "unit_price_cents": 17387, + "vendor": "V2" + }, + "PO1": { + "unit": "Central", + "unit_price_cents": 19332, + "vendor": "V1" + }, + "PO2": { + "unit": "Central", + "unit_price_cents": 11393, + "vendor": "V2" + }, + "PO3": { + "unit": "Central", + "unit_price_cents": 5134, + "vendor": "V1" + }, + "PO4": { + "unit": "Central", + "unit_price_cents": 9501, + "vendor": "V2" + }, + "PO5": { + "unit": "Central", + "unit_price_cents": 22877, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 17032, + "vendor": "V1" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 45 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-016/tests/world_check.py b/tasks/autom-supplier-invoice-match-016/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-016/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-016/validation/openenv.json b/tasks/autom-supplier-invoice-match-016/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-016/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-017/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-017/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-017/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-017/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-017/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..67bc39574fbab55658095700589418f8823a01e3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-017/environment/inputs/world.json @@ -0,0 +1,486 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 4 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 5 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 6 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 2 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 8 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 8 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-02-22", + "po": "PO0", + "state": "accepted", + "units": 12 + }, + "GI-0-1": { + "date": "2026-02-09", + "po": "PO0", + "state": "quarantine", + "units": 23 + }, + "GI-0-2": { + "date": "2026-02-03", + "po": "PO0", + "state": "quarantine", + "units": 23 + }, + "GI-0-3": { + "date": "2026-01-31", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-1-0": { + "date": "2026-02-22", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-1-1": { + "date": "2026-02-26", + "po": "PO1", + "state": "accepted", + "units": 19 + }, + "GI-1-2": { + "date": "2026-02-04", + "po": "PO1", + "state": "quarantine", + "units": 21 + }, + "GI-1-3": { + "date": "2026-02-27", + "po": "PO1", + "state": "quarantine", + "units": 18 + }, + "GI-2-0": { + "date": "2026-02-22", + "po": "PO2", + "state": "accepted", + "units": 28 + }, + "GI-2-1": { + "date": "2026-02-18", + "po": "PO2", + "state": "accepted", + "units": 15 + }, + "GI-2-2": { + "date": "2026-02-25", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-2-3": { + "date": "2026-02-27", + "po": "PO2", + "state": "accepted", + "units": 12 + }, + "GI-3-0": { + "date": "2026-02-22", + "po": "PO3", + "state": "accepted", + "units": 23 + }, + "GI-3-1": { + "date": "2026-02-27", + "po": "PO3", + "state": "accepted", + "units": 20 + }, + "GI-3-2": { + "date": "2026-02-26", + "po": "PO3", + "state": "accepted", + "units": 24 + }, + "GI-3-3": { + "date": "2026-02-26", + "po": "PO3", + "state": "accepted", + "units": 15 + }, + "GI-4-0": { + "date": "2026-02-22", + "po": "PO4", + "state": "accepted", + "units": 20 + }, + "GI-4-1": { + "date": "2026-02-08", + "po": "PO4", + "state": "accepted", + "units": 15 + }, + "GI-4-2": { + "date": "2026-02-10", + "po": "PO4", + "state": "accepted", + "units": 23 + }, + "GI-4-3": { + "date": "2026-02-15", + "po": "PO4", + "state": "accepted", + "units": 18 + }, + "GI-5-0": { + "date": "2026-02-22", + "po": "PO5", + "state": "accepted", + "units": 26 + }, + "GI-5-1": { + "date": "2026-02-21", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-2": { + "date": "2026-02-24", + "po": "PO5", + "state": "accepted", + "units": 23 + }, + "GI-5-3": { + "date": "2026-02-12", + "po": "PO5", + "state": "quarantine", + "units": 17 + }, + "GI-6-0": { + "date": "2026-02-22", + "po": "PO6", + "state": "accepted", + "units": 24 + }, + "GI-6-1": { + "date": "2026-02-05", + "po": "PO6", + "state": "accepted", + "units": 13 + }, + "GI-6-2": { + "date": "2026-02-21", + "po": "PO6", + "state": "accepted", + "units": 12 + }, + "GI-6-3": { + "date": "2026-02-13", + "po": "PO6", + "state": "accepted", + "units": 26 + } + }, + "invoice_inbox": { + "IV-1121-1-3": { + "date": "2026-02-06", + "po": "PO1", + "state": "review", + "unit_price_cents": 11687, + "units": 24, + "vendor": "Unknown" + }, + "IV-1564-2-3": { + "date": "2026-01-27", + "po": "PO2", + "state": "void", + "unit_price_cents": 16167, + "units": 15, + "vendor": "V1" + }, + "IV-1603-3-2": { + "date": "2026-02-20", + "po": "PO3", + "state": "review", + "unit_price_cents": 2659, + "units": 23, + "vendor": "V4" + }, + "IV-2430-4-2": { + "date": "2026-02-22", + "po": "PO4", + "state": "review", + "unit_price_cents": 21158, + "units": 4, + "vendor": "V3" + }, + "IV-2605-5-1": { + "date": "2026-02-09", + "po": "PO5", + "state": "void", + "unit_price_cents": 23404, + "units": 25, + "vendor": "V3" + }, + "IV-3502-2-0": { + "date": "2026-02-02", + "po": "PO2", + "state": "review", + "unit_price_cents": 15195, + "units": 20, + "vendor": "V1" + }, + "IV-3634-6-2": { + "date": "2026-02-23", + "po": "PO6", + "state": "void", + "unit_price_cents": 15547, + "units": 8, + "vendor": "V1" + }, + "IV-3671-4-3": { + "date": "2026-02-04", + "po": "PO4", + "state": "review", + "unit_price_cents": 20735, + "units": 5, + "vendor": "Unknown" + }, + "IV-4795-3-1": { + "date": "2026-02-09", + "po": "PO3", + "state": "review", + "unit_price_cents": 4959, + "units": 25, + "vendor": "V4" + }, + "IV-5394-0-3": { + "date": "2026-02-21", + "po": "PO0", + "state": "review", + "unit_price_cents": 24238, + "units": 19, + "vendor": "V2" + }, + "IV-5893-0-0": { + "date": "2026-02-02", + "po": "PO0", + "state": "review", + "unit_price_cents": 22476, + "units": 1, + "vendor": "V2" + }, + "IV-6741-2-2": { + "date": "2026-02-10", + "po": "PO2", + "state": "review", + "unit_price_cents": 17008, + "units": 17, + "vendor": "V1" + }, + "IV-6763-4-1": { + "date": "2026-02-15", + "po": "PO4", + "state": "review", + "unit_price_cents": 19617, + "units": 19, + "vendor": "V3" + }, + "IV-7233-1-2": { + "date": "2026-01-29", + "po": "PO1", + "state": "review", + "unit_price_cents": 12305, + "units": 21, + "vendor": "Unknown" + }, + "IV-7263-6-1": { + "date": "2026-01-28", + "po": "PO6", + "state": "review", + "unit_price_cents": 16767, + "units": 12, + "vendor": "V1" + }, + "IV-7528-5-3": { + "date": "2026-02-23", + "po": "PO5", + "state": "review", + "unit_price_cents": 23840, + "units": 21, + "vendor": "V3" + }, + "IV-7705-3-3": { + "date": "2026-02-13", + "po": "PO3", + "state": "review", + "unit_price_cents": 4757, + "units": 24, + "vendor": "V4" + }, + "IV-7763-0-1": { + "date": "2026-02-11", + "po": "PO0", + "state": "void", + "unit_price_cents": 23439, + "units": 10, + "vendor": "V2" + }, + "IV-7765-5-2": { + "date": "2026-02-10", + "po": "PO5", + "state": "review", + "unit_price_cents": 23340, + "units": 24, + "vendor": "V3" + }, + "IV-7986-3-0": { + "date": "2026-02-02", + "po": "PO3", + "state": "review", + "unit_price_cents": 2818, + "units": 20, + "vendor": "V4" + }, + "IV-8613-2-1": { + "date": "2026-01-28", + "po": "PO2", + "state": "review", + "unit_price_cents": 16729, + "units": 12, + "vendor": "V1" + }, + "IV-8668-1-1": { + "date": "2026-02-06", + "po": "PO1", + "state": "review", + "unit_price_cents": 12859, + "units": 19, + "vendor": "Unknown" + }, + "IV-8830-5-0": { + "date": "2026-02-02", + "po": "PO5", + "state": "review", + "unit_price_cents": 22646, + "units": 16, + "vendor": "V3" + }, + "IV-8977-0-2": { + "date": "2026-02-02", + "po": "PO0", + "state": "review", + "unit_price_cents": 24200, + "units": 14, + "vendor": "V2" + }, + "IV-9433-6-0": { + "date": "2026-02-02", + "po": "PO6", + "state": "review", + "unit_price_cents": 15212, + "units": 13, + "vendor": "V1" + }, + "IV-9636-1-0": { + "date": "2026-02-02", + "po": "PO1", + "state": "review", + "unit_price_cents": 10711, + "units": 11, + "vendor": "V4" + }, + "IV-9672-4-0": { + "date": "2026-02-02", + "po": "PO4", + "state": "review", + "unit_price_cents": 19462, + "units": 13, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "Central", + "unit_price_cents": 22476, + "vendor": "V2" + }, + "PO1": { + "unit": "Central", + "unit_price_cents": 10711, + "vendor": "V4" + }, + "PO2": { + "unit": "Central", + "unit_price_cents": 15195, + "vendor": "V1" + }, + "PO3": { + "unit": "Central", + "unit_price_cents": 2818, + "vendor": "V4" + }, + "PO4": { + "unit": "Central", + "unit_price_cents": 19462, + "vendor": "V3" + }, + "PO5": { + "unit": "Central", + "unit_price_cents": 22646, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 15212, + "vendor": "V1" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-017/instruction.md b/tasks/autom-supplier-invoice-match-017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..105285591c09c2bd63e227592dfb90bd65494755 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-017/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit Central at 2026-02-23. Handle invoices in review attached to that unit's purchase orders, invoice dates 2026-02-02 through 2026-02-23 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 0 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-017/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-017/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f8051a364df4e0034b8a4833c1dc6996763fa53c --- /dev/null +++ b/tasks/autom-supplier-invoice-match-017/solution/files/actions.jsonl @@ -0,0 +1,38 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5893-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-8977-0-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-5394-0-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-9636-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-8668-1-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-1121-1-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-3502-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-6741-2-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-7986-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4795-3-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-1603-3-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7705-3-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-9672-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-6763-4-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-2430-4-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3671-4-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8830-5-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7765-5-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7528-5-3", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 303900, "due": "2026-02-17", "invoice": "IV-3502-2-0", "po": "PO2", "status": "posted", "units": 20}, "id": "book-IV-3502-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 22476, "due": "2026-03-19", "invoice": "IV-5893-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-5893-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 56360, "due": "2026-02-17", "invoice": "IV-7986-3-0", "po": "PO3", "status": "posted", "units": 20}, "id": "book-IV-7986-3-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 362336, "due": "2026-03-04", "invoice": "IV-8830-5-0", "po": "PO5", "status": "posted", "units": 16}, "id": "book-IV-8830-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 117821, "due": "2026-02-17", "invoice": "IV-9636-1-0", "po": "PO1", "status": "posted", "units": 11}, "id": "book-IV-9636-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 253006, "due": "2026-03-04", "invoice": "IV-9672-4-0", "po": "PO4", "status": "posted", "units": 13}, "id": "book-IV-9672-4-0", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-8977-0-2", "issues": ["price"], "po": "PO0"}, "id": "case-IV-8977-0-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3671-4-3", "issues": ["vendor", "price"], "po": "PO4"}, "id": "case-IV-3671-4-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-1121-1-3", "issues": ["vendor", "price", "units"], "po": "PO1"}, "id": "case-IV-1121-1-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-8668-1-1", "issues": ["vendor", "price", "units"], "po": "PO1"}, "id": "case-IV-8668-1-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4795-3-1", "issues": ["price", "units"], "po": "PO3"}, "id": "case-IV-4795-3-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-6741-2-2", "issues": ["price"], "po": "PO2"}, "id": "case-IV-6741-2-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7765-5-2", "issues": ["price"], "po": "PO5"}, "id": "case-IV-7765-5-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7705-3-3", "issues": ["price", "units"], "po": "PO3"}, "id": "case-IV-7705-3-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-6763-4-1", "issues": ["price"], "po": "PO4"}, "id": "case-IV-6763-4-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-1603-3-2", "issues": ["units"], "po": "PO3"}, "id": "case-IV-1603-3-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-5394-0-3", "issues": ["price"], "po": "PO0"}, "id": "case-IV-5394-0-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-2430-4-2", "issues": ["price"], "po": "PO4"}, "id": "case-IV-2430-4-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7528-5-3", "issues": ["price"], "po": "PO5"}, "id": "case-IV-7528-5-3", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-017/solution/solve.sh b/tasks/autom-supplier-invoice-match-017/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-017/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-017/task.toml b/tasks/autom-supplier-invoice-match-017/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..efb2823d27f5df5c36dd1f83a92b550fb6f44703 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-017/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-017" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 17 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-017" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-017/tests/expected.json b/tasks/autom-supplier-invoice-match-017/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-017/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-017/tests/grade.py b/tasks/autom-supplier-invoice-match-017/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-017/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-017/tests/replay.py b/tasks/autom-supplier-invoice-match-017/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-017/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-017/tests/target.json b/tasks/autom-supplier-invoice-match-017/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..72e67b883dc43c59185b14cbf3b722cf8982c80d --- /dev/null +++ b/tasks/autom-supplier-invoice-match-017/tests/target.json @@ -0,0 +1,632 @@ +{ + "ap_postings": { + "book-IV-3502-2-0": { + "amount_cents": 303900, + "due": "2026-02-17", + "invoice": "IV-3502-2-0", + "po": "PO2", + "status": "posted", + "units": 20 + }, + "book-IV-5893-0-0": { + "amount_cents": 22476, + "due": "2026-03-19", + "invoice": "IV-5893-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "book-IV-7986-3-0": { + "amount_cents": 56360, + "due": "2026-02-17", + "invoice": "IV-7986-3-0", + "po": "PO3", + "status": "posted", + "units": 20 + }, + "book-IV-8830-5-0": { + "amount_cents": 362336, + "due": "2026-03-04", + "invoice": "IV-8830-5-0", + "po": "PO5", + "status": "posted", + "units": 16 + }, + "book-IV-9636-1-0": { + "amount_cents": 117821, + "due": "2026-02-17", + "invoice": "IV-9636-1-0", + "po": "PO1", + "status": "posted", + "units": 11 + }, + "book-IV-9672-4-0": { + "amount_cents": 253006, + "due": "2026-03-04", + "invoice": "IV-9672-4-0", + "po": "PO4", + "status": "posted", + "units": 13 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 4 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 5 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 6 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 2 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 8 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 8 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-02-22", + "po": "PO0", + "state": "accepted", + "units": 12 + }, + "GI-0-1": { + "date": "2026-02-09", + "po": "PO0", + "state": "quarantine", + "units": 23 + }, + "GI-0-2": { + "date": "2026-02-03", + "po": "PO0", + "state": "quarantine", + "units": 23 + }, + "GI-0-3": { + "date": "2026-01-31", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-1-0": { + "date": "2026-02-22", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-1-1": { + "date": "2026-02-26", + "po": "PO1", + "state": "accepted", + "units": 19 + }, + "GI-1-2": { + "date": "2026-02-04", + "po": "PO1", + "state": "quarantine", + "units": 21 + }, + "GI-1-3": { + "date": "2026-02-27", + "po": "PO1", + "state": "quarantine", + "units": 18 + }, + "GI-2-0": { + "date": "2026-02-22", + "po": "PO2", + "state": "accepted", + "units": 28 + }, + "GI-2-1": { + "date": "2026-02-18", + "po": "PO2", + "state": "accepted", + "units": 15 + }, + "GI-2-2": { + "date": "2026-02-25", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-2-3": { + "date": "2026-02-27", + "po": "PO2", + "state": "accepted", + "units": 12 + }, + "GI-3-0": { + "date": "2026-02-22", + "po": "PO3", + "state": "accepted", + "units": 23 + }, + "GI-3-1": { + "date": "2026-02-27", + "po": "PO3", + "state": "accepted", + "units": 20 + }, + "GI-3-2": { + "date": "2026-02-26", + "po": "PO3", + "state": "accepted", + "units": 24 + }, + "GI-3-3": { + "date": "2026-02-26", + "po": "PO3", + "state": "accepted", + "units": 15 + }, + "GI-4-0": { + "date": "2026-02-22", + "po": "PO4", + "state": "accepted", + "units": 20 + }, + "GI-4-1": { + "date": "2026-02-08", + "po": "PO4", + "state": "accepted", + "units": 15 + }, + "GI-4-2": { + "date": "2026-02-10", + "po": "PO4", + "state": "accepted", + "units": 23 + }, + "GI-4-3": { + "date": "2026-02-15", + "po": "PO4", + "state": "accepted", + "units": 18 + }, + "GI-5-0": { + "date": "2026-02-22", + "po": "PO5", + "state": "accepted", + "units": 26 + }, + "GI-5-1": { + "date": "2026-02-21", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-2": { + "date": "2026-02-24", + "po": "PO5", + "state": "accepted", + "units": 23 + }, + "GI-5-3": { + "date": "2026-02-12", + "po": "PO5", + "state": "quarantine", + "units": 17 + }, + "GI-6-0": { + "date": "2026-02-22", + "po": "PO6", + "state": "accepted", + "units": 24 + }, + "GI-6-1": { + "date": "2026-02-05", + "po": "PO6", + "state": "accepted", + "units": 13 + }, + "GI-6-2": { + "date": "2026-02-21", + "po": "PO6", + "state": "accepted", + "units": 12 + }, + "GI-6-3": { + "date": "2026-02-13", + "po": "PO6", + "state": "accepted", + "units": 26 + } + }, + "invoice_inbox": { + "IV-1121-1-3": { + "date": "2026-02-06", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 11687, + "units": 24, + "vendor": "Unknown" + }, + "IV-1564-2-3": { + "date": "2026-01-27", + "po": "PO2", + "state": "void", + "unit_price_cents": 16167, + "units": 15, + "vendor": "V1" + }, + "IV-1603-3-2": { + "date": "2026-02-20", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 2659, + "units": 23, + "vendor": "V4" + }, + "IV-2430-4-2": { + "date": "2026-02-22", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 21158, + "units": 4, + "vendor": "V3" + }, + "IV-2605-5-1": { + "date": "2026-02-09", + "po": "PO5", + "state": "void", + "unit_price_cents": 23404, + "units": 25, + "vendor": "V3" + }, + "IV-3502-2-0": { + "date": "2026-02-02", + "po": "PO2", + "state": "posted", + "unit_price_cents": 15195, + "units": 20, + "vendor": "V1" + }, + "IV-3634-6-2": { + "date": "2026-02-23", + "po": "PO6", + "state": "void", + "unit_price_cents": 15547, + "units": 8, + "vendor": "V1" + }, + "IV-3671-4-3": { + "date": "2026-02-04", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 20735, + "units": 5, + "vendor": "Unknown" + }, + "IV-4795-3-1": { + "date": "2026-02-09", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 4959, + "units": 25, + "vendor": "V4" + }, + "IV-5394-0-3": { + "date": "2026-02-21", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 24238, + "units": 19, + "vendor": "V2" + }, + "IV-5893-0-0": { + "date": "2026-02-02", + "po": "PO0", + "state": "posted", + "unit_price_cents": 22476, + "units": 1, + "vendor": "V2" + }, + "IV-6741-2-2": { + "date": "2026-02-10", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 17008, + "units": 17, + "vendor": "V1" + }, + "IV-6763-4-1": { + "date": "2026-02-15", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 19617, + "units": 19, + "vendor": "V3" + }, + "IV-7233-1-2": { + "date": "2026-01-29", + "po": "PO1", + "state": "review", + "unit_price_cents": 12305, + "units": 21, + "vendor": "Unknown" + }, + "IV-7263-6-1": { + "date": "2026-01-28", + "po": "PO6", + "state": "review", + "unit_price_cents": 16767, + "units": 12, + "vendor": "V1" + }, + "IV-7528-5-3": { + "date": "2026-02-23", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 23840, + "units": 21, + "vendor": "V3" + }, + "IV-7705-3-3": { + "date": "2026-02-13", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 4757, + "units": 24, + "vendor": "V4" + }, + "IV-7763-0-1": { + "date": "2026-02-11", + "po": "PO0", + "state": "void", + "unit_price_cents": 23439, + "units": 10, + "vendor": "V2" + }, + "IV-7765-5-2": { + "date": "2026-02-10", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 23340, + "units": 24, + "vendor": "V3" + }, + "IV-7986-3-0": { + "date": "2026-02-02", + "po": "PO3", + "state": "posted", + "unit_price_cents": 2818, + "units": 20, + "vendor": "V4" + }, + "IV-8613-2-1": { + "date": "2026-01-28", + "po": "PO2", + "state": "review", + "unit_price_cents": 16729, + "units": 12, + "vendor": "V1" + }, + "IV-8668-1-1": { + "date": "2026-02-06", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 12859, + "units": 19, + "vendor": "Unknown" + }, + "IV-8830-5-0": { + "date": "2026-02-02", + "po": "PO5", + "state": "posted", + "unit_price_cents": 22646, + "units": 16, + "vendor": "V3" + }, + "IV-8977-0-2": { + "date": "2026-02-02", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 24200, + "units": 14, + "vendor": "V2" + }, + "IV-9433-6-0": { + "date": "2026-02-02", + "po": "PO6", + "state": "review", + "unit_price_cents": 15212, + "units": 13, + "vendor": "V1" + }, + "IV-9636-1-0": { + "date": "2026-02-02", + "po": "PO1", + "state": "posted", + "unit_price_cents": 10711, + "units": 11, + "vendor": "V4" + }, + "IV-9672-4-0": { + "date": "2026-02-02", + "po": "PO4", + "state": "posted", + "unit_price_cents": 19462, + "units": 13, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "Central", + "unit_price_cents": 22476, + "vendor": "V2" + }, + "PO1": { + "unit": "Central", + "unit_price_cents": 10711, + "vendor": "V4" + }, + "PO2": { + "unit": "Central", + "unit_price_cents": 15195, + "vendor": "V1" + }, + "PO3": { + "unit": "Central", + "unit_price_cents": 2818, + "vendor": "V4" + }, + "PO4": { + "unit": "Central", + "unit_price_cents": 19462, + "vendor": "V3" + }, + "PO5": { + "unit": "Central", + "unit_price_cents": 22646, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 15212, + "vendor": "V1" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-1121-1-3": { + "invoice": "IV-1121-1-3", + "issues": [ + "vendor", + "price", + "units" + ], + "po": "PO1" + }, + "case-IV-1603-3-2": { + "invoice": "IV-1603-3-2", + "issues": [ + "units" + ], + "po": "PO3" + }, + "case-IV-2430-4-2": { + "invoice": "IV-2430-4-2", + "issues": [ + "price" + ], + "po": "PO4" + }, + "case-IV-3671-4-3": { + "invoice": "IV-3671-4-3", + "issues": [ + "vendor", + "price" + ], + "po": "PO4" + }, + "case-IV-4795-3-1": { + "invoice": "IV-4795-3-1", + "issues": [ + "price", + "units" + ], + "po": "PO3" + }, + "case-IV-5394-0-3": { + "invoice": "IV-5394-0-3", + "issues": [ + "price" + ], + "po": "PO0" + }, + "case-IV-6741-2-2": { + "invoice": "IV-6741-2-2", + "issues": [ + "price" + ], + "po": "PO2" + }, + "case-IV-6763-4-1": { + "invoice": "IV-6763-4-1", + "issues": [ + "price" + ], + "po": "PO4" + }, + "case-IV-7528-5-3": { + "invoice": "IV-7528-5-3", + "issues": [ + "price" + ], + "po": "PO5" + }, + "case-IV-7705-3-3": { + "invoice": "IV-7705-3-3", + "issues": [ + "price", + "units" + ], + "po": "PO3" + }, + "case-IV-7765-5-2": { + "invoice": "IV-7765-5-2", + "issues": [ + "price" + ], + "po": "PO5" + }, + "case-IV-8668-1-1": { + "invoice": "IV-8668-1-1", + "issues": [ + "vendor", + "price", + "units" + ], + "po": "PO1" + }, + "case-IV-8977-0-2": { + "invoice": "IV-8977-0-2", + "issues": [ + "price" + ], + "po": "PO0" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-017/tests/test.sh b/tasks/autom-supplier-invoice-match-017/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-017/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-017/tests/world.json b/tasks/autom-supplier-invoice-match-017/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..67bc39574fbab55658095700589418f8823a01e3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-017/tests/world.json @@ -0,0 +1,486 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 4 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 5 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 6 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 2 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 8 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 8 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-02-22", + "po": "PO0", + "state": "accepted", + "units": 12 + }, + "GI-0-1": { + "date": "2026-02-09", + "po": "PO0", + "state": "quarantine", + "units": 23 + }, + "GI-0-2": { + "date": "2026-02-03", + "po": "PO0", + "state": "quarantine", + "units": 23 + }, + "GI-0-3": { + "date": "2026-01-31", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-1-0": { + "date": "2026-02-22", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-1-1": { + "date": "2026-02-26", + "po": "PO1", + "state": "accepted", + "units": 19 + }, + "GI-1-2": { + "date": "2026-02-04", + "po": "PO1", + "state": "quarantine", + "units": 21 + }, + "GI-1-3": { + "date": "2026-02-27", + "po": "PO1", + "state": "quarantine", + "units": 18 + }, + "GI-2-0": { + "date": "2026-02-22", + "po": "PO2", + "state": "accepted", + "units": 28 + }, + "GI-2-1": { + "date": "2026-02-18", + "po": "PO2", + "state": "accepted", + "units": 15 + }, + "GI-2-2": { + "date": "2026-02-25", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-2-3": { + "date": "2026-02-27", + "po": "PO2", + "state": "accepted", + "units": 12 + }, + "GI-3-0": { + "date": "2026-02-22", + "po": "PO3", + "state": "accepted", + "units": 23 + }, + "GI-3-1": { + "date": "2026-02-27", + "po": "PO3", + "state": "accepted", + "units": 20 + }, + "GI-3-2": { + "date": "2026-02-26", + "po": "PO3", + "state": "accepted", + "units": 24 + }, + "GI-3-3": { + "date": "2026-02-26", + "po": "PO3", + "state": "accepted", + "units": 15 + }, + "GI-4-0": { + "date": "2026-02-22", + "po": "PO4", + "state": "accepted", + "units": 20 + }, + "GI-4-1": { + "date": "2026-02-08", + "po": "PO4", + "state": "accepted", + "units": 15 + }, + "GI-4-2": { + "date": "2026-02-10", + "po": "PO4", + "state": "accepted", + "units": 23 + }, + "GI-4-3": { + "date": "2026-02-15", + "po": "PO4", + "state": "accepted", + "units": 18 + }, + "GI-5-0": { + "date": "2026-02-22", + "po": "PO5", + "state": "accepted", + "units": 26 + }, + "GI-5-1": { + "date": "2026-02-21", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-2": { + "date": "2026-02-24", + "po": "PO5", + "state": "accepted", + "units": 23 + }, + "GI-5-3": { + "date": "2026-02-12", + "po": "PO5", + "state": "quarantine", + "units": 17 + }, + "GI-6-0": { + "date": "2026-02-22", + "po": "PO6", + "state": "accepted", + "units": 24 + }, + "GI-6-1": { + "date": "2026-02-05", + "po": "PO6", + "state": "accepted", + "units": 13 + }, + "GI-6-2": { + "date": "2026-02-21", + "po": "PO6", + "state": "accepted", + "units": 12 + }, + "GI-6-3": { + "date": "2026-02-13", + "po": "PO6", + "state": "accepted", + "units": 26 + } + }, + "invoice_inbox": { + "IV-1121-1-3": { + "date": "2026-02-06", + "po": "PO1", + "state": "review", + "unit_price_cents": 11687, + "units": 24, + "vendor": "Unknown" + }, + "IV-1564-2-3": { + "date": "2026-01-27", + "po": "PO2", + "state": "void", + "unit_price_cents": 16167, + "units": 15, + "vendor": "V1" + }, + "IV-1603-3-2": { + "date": "2026-02-20", + "po": "PO3", + "state": "review", + "unit_price_cents": 2659, + "units": 23, + "vendor": "V4" + }, + "IV-2430-4-2": { + "date": "2026-02-22", + "po": "PO4", + "state": "review", + "unit_price_cents": 21158, + "units": 4, + "vendor": "V3" + }, + "IV-2605-5-1": { + "date": "2026-02-09", + "po": "PO5", + "state": "void", + "unit_price_cents": 23404, + "units": 25, + "vendor": "V3" + }, + "IV-3502-2-0": { + "date": "2026-02-02", + "po": "PO2", + "state": "review", + "unit_price_cents": 15195, + "units": 20, + "vendor": "V1" + }, + "IV-3634-6-2": { + "date": "2026-02-23", + "po": "PO6", + "state": "void", + "unit_price_cents": 15547, + "units": 8, + "vendor": "V1" + }, + "IV-3671-4-3": { + "date": "2026-02-04", + "po": "PO4", + "state": "review", + "unit_price_cents": 20735, + "units": 5, + "vendor": "Unknown" + }, + "IV-4795-3-1": { + "date": "2026-02-09", + "po": "PO3", + "state": "review", + "unit_price_cents": 4959, + "units": 25, + "vendor": "V4" + }, + "IV-5394-0-3": { + "date": "2026-02-21", + "po": "PO0", + "state": "review", + "unit_price_cents": 24238, + "units": 19, + "vendor": "V2" + }, + "IV-5893-0-0": { + "date": "2026-02-02", + "po": "PO0", + "state": "review", + "unit_price_cents": 22476, + "units": 1, + "vendor": "V2" + }, + "IV-6741-2-2": { + "date": "2026-02-10", + "po": "PO2", + "state": "review", + "unit_price_cents": 17008, + "units": 17, + "vendor": "V1" + }, + "IV-6763-4-1": { + "date": "2026-02-15", + "po": "PO4", + "state": "review", + "unit_price_cents": 19617, + "units": 19, + "vendor": "V3" + }, + "IV-7233-1-2": { + "date": "2026-01-29", + "po": "PO1", + "state": "review", + "unit_price_cents": 12305, + "units": 21, + "vendor": "Unknown" + }, + "IV-7263-6-1": { + "date": "2026-01-28", + "po": "PO6", + "state": "review", + "unit_price_cents": 16767, + "units": 12, + "vendor": "V1" + }, + "IV-7528-5-3": { + "date": "2026-02-23", + "po": "PO5", + "state": "review", + "unit_price_cents": 23840, + "units": 21, + "vendor": "V3" + }, + "IV-7705-3-3": { + "date": "2026-02-13", + "po": "PO3", + "state": "review", + "unit_price_cents": 4757, + "units": 24, + "vendor": "V4" + }, + "IV-7763-0-1": { + "date": "2026-02-11", + "po": "PO0", + "state": "void", + "unit_price_cents": 23439, + "units": 10, + "vendor": "V2" + }, + "IV-7765-5-2": { + "date": "2026-02-10", + "po": "PO5", + "state": "review", + "unit_price_cents": 23340, + "units": 24, + "vendor": "V3" + }, + "IV-7986-3-0": { + "date": "2026-02-02", + "po": "PO3", + "state": "review", + "unit_price_cents": 2818, + "units": 20, + "vendor": "V4" + }, + "IV-8613-2-1": { + "date": "2026-01-28", + "po": "PO2", + "state": "review", + "unit_price_cents": 16729, + "units": 12, + "vendor": "V1" + }, + "IV-8668-1-1": { + "date": "2026-02-06", + "po": "PO1", + "state": "review", + "unit_price_cents": 12859, + "units": 19, + "vendor": "Unknown" + }, + "IV-8830-5-0": { + "date": "2026-02-02", + "po": "PO5", + "state": "review", + "unit_price_cents": 22646, + "units": 16, + "vendor": "V3" + }, + "IV-8977-0-2": { + "date": "2026-02-02", + "po": "PO0", + "state": "review", + "unit_price_cents": 24200, + "units": 14, + "vendor": "V2" + }, + "IV-9433-6-0": { + "date": "2026-02-02", + "po": "PO6", + "state": "review", + "unit_price_cents": 15212, + "units": 13, + "vendor": "V1" + }, + "IV-9636-1-0": { + "date": "2026-02-02", + "po": "PO1", + "state": "review", + "unit_price_cents": 10711, + "units": 11, + "vendor": "V4" + }, + "IV-9672-4-0": { + "date": "2026-02-02", + "po": "PO4", + "state": "review", + "unit_price_cents": 19462, + "units": 13, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "Central", + "unit_price_cents": 22476, + "vendor": "V2" + }, + "PO1": { + "unit": "Central", + "unit_price_cents": 10711, + "vendor": "V4" + }, + "PO2": { + "unit": "Central", + "unit_price_cents": 15195, + "vendor": "V1" + }, + "PO3": { + "unit": "Central", + "unit_price_cents": 2818, + "vendor": "V4" + }, + "PO4": { + "unit": "Central", + "unit_price_cents": 19462, + "vendor": "V3" + }, + "PO5": { + "unit": "Central", + "unit_price_cents": 22646, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 15212, + "vendor": "V1" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-017/tests/world_check.py b/tasks/autom-supplier-invoice-match-017/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-017/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-017/validation/openenv.json b/tasks/autom-supplier-invoice-match-017/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-017/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-018/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-018/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-018/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-018/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-018/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..2a4a2945d1258d554ca62cf4195e443e430547ed --- /dev/null +++ b/tasks/autom-supplier-invoice-match-018/environment/inputs/world.json @@ -0,0 +1,430 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 3 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 3 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 7 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 6 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 7 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 7 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-03-17", + "po": "PO0", + "state": "accepted", + "units": 25 + }, + "GI-0-1": { + "date": "2026-03-01", + "po": "PO0", + "state": "accepted", + "units": 23 + }, + "GI-0-2": { + "date": "2026-03-04", + "po": "PO0", + "state": "accepted", + "units": 27 + }, + "GI-0-3": { + "date": "2026-03-21", + "po": "PO0", + "state": "quarantine", + "units": 20 + }, + "GI-1-0": { + "date": "2026-03-17", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-1-1": { + "date": "2026-03-03", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-1-2": { + "date": "2026-03-12", + "po": "PO1", + "state": "quarantine", + "units": 12 + }, + "GI-1-3": { + "date": "2026-03-19", + "po": "PO1", + "state": "accepted", + "units": 15 + }, + "GI-2-0": { + "date": "2026-03-17", + "po": "PO2", + "state": "accepted", + "units": 27 + }, + "GI-2-1": { + "date": "2026-02-24", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-2-2": { + "date": "2026-03-20", + "po": "PO2", + "state": "accepted", + "units": 21 + }, + "GI-2-3": { + "date": "2026-03-09", + "po": "PO2", + "state": "quarantine", + "units": 13 + }, + "GI-3-0": { + "date": "2026-03-17", + "po": "PO3", + "state": "accepted", + "units": 17 + }, + "GI-3-1": { + "date": "2026-03-19", + "po": "PO3", + "state": "accepted", + "units": 14 + }, + "GI-3-2": { + "date": "2026-02-28", + "po": "PO3", + "state": "accepted", + "units": 19 + }, + "GI-3-3": { + "date": "2026-03-10", + "po": "PO3", + "state": "quarantine", + "units": 18 + }, + "GI-4-0": { + "date": "2026-03-17", + "po": "PO4", + "state": "accepted", + "units": 18 + }, + "GI-4-1": { + "date": "2026-03-17", + "po": "PO4", + "state": "accepted", + "units": 14 + }, + "GI-4-2": { + "date": "2026-02-27", + "po": "PO4", + "state": "quarantine", + "units": 12 + }, + "GI-4-3": { + "date": "2026-03-21", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-5-0": { + "date": "2026-03-17", + "po": "PO5", + "state": "accepted", + "units": 20 + }, + "GI-5-1": { + "date": "2026-02-27", + "po": "PO5", + "state": "quarantine", + "units": 19 + }, + "GI-5-2": { + "date": "2026-03-14", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-5-3": { + "date": "2026-03-02", + "po": "PO5", + "state": "accepted", + "units": 23 + }, + "GI-6-0": { + "date": "2026-03-17", + "po": "PO6", + "state": "accepted", + "units": 22 + }, + "GI-6-1": { + "date": "2026-03-12", + "po": "PO6", + "state": "quarantine", + "units": 28 + }, + "GI-6-2": { + "date": "2026-03-16", + "po": "PO6", + "state": "quarantine", + "units": 18 + }, + "GI-6-3": { + "date": "2026-02-26", + "po": "PO6", + "state": "accepted", + "units": 17 + } + }, + "invoice_inbox": { + "IV-1124-0-2": { + "date": "2026-03-07", + "po": "PO0", + "state": "review", + "unit_price_cents": 21934, + "units": 17, + "vendor": "V3" + }, + "IV-1863-2-1": { + "date": "2026-03-04", + "po": "PO2", + "state": "review", + "unit_price_cents": 8107, + "units": 16, + "vendor": "V4" + }, + "IV-2305-2-0": { + "date": "2026-02-18", + "po": "PO2", + "state": "review", + "unit_price_cents": 8334, + "units": 19, + "vendor": "V4" + }, + "IV-2337-0-0": { + "date": "2026-02-18", + "po": "PO0", + "state": "review", + "unit_price_cents": 22141, + "units": 1, + "vendor": "V3" + }, + "IV-2397-2-2": { + "date": "2026-03-08", + "po": "PO2", + "state": "review", + "unit_price_cents": 9722, + "units": 16, + "vendor": "V4" + }, + "IV-2555-6-1": { + "date": "2026-02-16", + "po": "PO6", + "state": "review", + "unit_price_cents": 17338, + "units": 12, + "vendor": "V4" + }, + "IV-3286-0-3": { + "date": "2026-02-28", + "po": "PO0", + "state": "review", + "unit_price_cents": 22785, + "units": 15, + "vendor": "V3" + }, + "IV-4221-1-2": { + "date": "2026-03-08", + "po": "PO1", + "state": "review", + "unit_price_cents": 13390, + "units": 6, + "vendor": "V4" + }, + "IV-4362-3-1": { + "date": "2026-02-15", + "po": "PO3", + "state": "review", + "unit_price_cents": 8022, + "units": 8, + "vendor": "V3" + }, + "IV-4485-1-3": { + "date": "2026-03-18", + "po": "PO1", + "state": "review", + "unit_price_cents": 13306, + "units": 11, + "vendor": "V4" + }, + "IV-4800-1-0": { + "date": "2026-02-18", + "po": "PO1", + "state": "review", + "unit_price_cents": 11741, + "units": 3, + "vendor": "V4" + }, + "IV-5656-5-1": { + "date": "2026-03-04", + "po": "PO5", + "state": "void", + "unit_price_cents": 1130, + "units": 9, + "vendor": "V3" + }, + "IV-6021-5-0": { + "date": "2026-02-18", + "po": "PO5", + "state": "review", + "unit_price_cents": 1021, + "units": 3, + "vendor": "V3" + }, + "IV-6723-0-1": { + "date": "2026-03-04", + "po": "PO0", + "state": "review", + "unit_price_cents": 23467, + "units": 19, + "vendor": "V3" + }, + "IV-6920-2-3": { + "date": "2026-03-09", + "po": "PO2", + "state": "void", + "unit_price_cents": 9440, + "units": 14, + "vendor": "V4" + }, + "IV-7563-6-0": { + "date": "2026-02-18", + "po": "PO6", + "state": "review", + "unit_price_cents": 16135, + "units": 11, + "vendor": "V4" + }, + "IV-8469-4-0": { + "date": "2026-02-18", + "po": "PO4", + "state": "review", + "unit_price_cents": 6463, + "units": 10, + "vendor": "V4" + }, + "IV-8690-4-1": { + "date": "2026-02-24", + "po": "PO4", + "state": "review", + "unit_price_cents": 6966, + "units": 21, + "vendor": "V4" + }, + "IV-9768-1-1": { + "date": "2026-03-14", + "po": "PO1", + "state": "review", + "unit_price_cents": 12142, + "units": 5, + "vendor": "V4" + }, + "IV-9782-3-0": { + "date": "2026-02-18", + "po": "PO3", + "state": "review", + "unit_price_cents": 8346, + "units": 4, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "East", + "unit_price_cents": 22141, + "vendor": "V3" + }, + "PO1": { + "unit": "East", + "unit_price_cents": 11741, + "vendor": "V4" + }, + "PO2": { + "unit": "East", + "unit_price_cents": 8334, + "vendor": "V4" + }, + "PO3": { + "unit": "East", + "unit_price_cents": 8346, + "vendor": "V3" + }, + "PO4": { + "unit": "East", + "unit_price_cents": 6463, + "vendor": "V4" + }, + "PO5": { + "unit": "East", + "unit_price_cents": 1021, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 16135, + "vendor": "V4" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 45 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-018/instruction.md b/tasks/autom-supplier-invoice-match-018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..700782aa75666beee9899cfb9a4f582a580d336f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-018/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit East at 2026-03-18. Handle invoices in review attached to that unit's purchase orders, invoice dates 2026-02-18 through 2026-03-18 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 0 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-018/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-018/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e2cfe28f921e8ab7253c4bbb7ba3f1384edb39d2 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-018/solution/files/actions.jsonl @@ -0,0 +1,30 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-2337-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-6723-0-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-1124-0-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3286-0-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-4800-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-9768-1-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4221-1-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4485-1-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-2305-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-1863-2-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-2397-2-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-9782-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8469-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-8690-4-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6021-5-0", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 158346, "due": "2026-03-11", "invoice": "IV-2305-2-0", "po": "PO2", "status": "posted", "units": 19}, "id": "book-IV-2305-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 22141, "due": "2026-03-20", "invoice": "IV-2337-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-2337-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 35223, "due": "2026-03-11", "invoice": "IV-4800-1-0", "po": "PO1", "status": "posted", "units": 3}, "id": "book-IV-4800-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 3063, "due": "2026-03-20", "invoice": "IV-6021-5-0", "po": "PO5", "status": "posted", "units": 3}, "id": "book-IV-6021-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 64630, "due": "2026-03-11", "invoice": "IV-8469-4-0", "po": "PO4", "status": "posted", "units": 10}, "id": "book-IV-8469-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 33384, "due": "2026-03-20", "invoice": "IV-9782-3-0", "po": "PO3", "status": "posted", "units": 4}, "id": "book-IV-9782-3-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 129712, "due": "2026-03-25", "invoice": "IV-1863-2-1", "po": "PO2", "status": "posted", "units": 16}, "id": "book-IV-1863-2-1", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 372878, "due": "2026-04-06", "invoice": "IV-1124-0-2", "po": "PO0", "status": "posted", "units": 17}, "id": "book-IV-1124-0-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-8690-4-1", "issues": ["price", "units"], "po": "PO4"}, "id": "case-IV-8690-4-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3286-0-3", "issues": ["price"], "po": "PO0"}, "id": "case-IV-3286-0-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-6723-0-1", "issues": ["price"], "po": "PO0"}, "id": "case-IV-6723-0-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-2397-2-2", "issues": ["price", "units"], "po": "PO2"}, "id": "case-IV-2397-2-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4221-1-2", "issues": ["price"], "po": "PO1"}, "id": "case-IV-4221-1-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-9768-1-1", "issues": ["price"], "po": "PO1"}, "id": "case-IV-9768-1-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4485-1-3", "issues": ["price"], "po": "PO1"}, "id": "case-IV-4485-1-3", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-018/solution/solve.sh b/tasks/autom-supplier-invoice-match-018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-018/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-018/task.toml b/tasks/autom-supplier-invoice-match-018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3faeaaa87a079dc622afc37928a8bc630b7a3c8d --- /dev/null +++ b/tasks/autom-supplier-invoice-match-018/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-018" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 18 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-018" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-018/tests/expected.json b/tasks/autom-supplier-invoice-match-018/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-018/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-018/tests/grade.py b/tasks/autom-supplier-invoice-match-018/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-018/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-018/tests/replay.py b/tasks/autom-supplier-invoice-match-018/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-018/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-018/tests/target.json b/tasks/autom-supplier-invoice-match-018/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..26e2f87e832d39785da7721922e28aab6d57458d --- /dev/null +++ b/tasks/autom-supplier-invoice-match-018/tests/target.json @@ -0,0 +1,545 @@ +{ + "ap_postings": { + "book-IV-1124-0-2": { + "amount_cents": 372878, + "due": "2026-04-06", + "invoice": "IV-1124-0-2", + "po": "PO0", + "status": "posted", + "units": 17 + }, + "book-IV-1863-2-1": { + "amount_cents": 129712, + "due": "2026-03-25", + "invoice": "IV-1863-2-1", + "po": "PO2", + "status": "posted", + "units": 16 + }, + "book-IV-2305-2-0": { + "amount_cents": 158346, + "due": "2026-03-11", + "invoice": "IV-2305-2-0", + "po": "PO2", + "status": "posted", + "units": 19 + }, + "book-IV-2337-0-0": { + "amount_cents": 22141, + "due": "2026-03-20", + "invoice": "IV-2337-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "book-IV-4800-1-0": { + "amount_cents": 35223, + "due": "2026-03-11", + "invoice": "IV-4800-1-0", + "po": "PO1", + "status": "posted", + "units": 3 + }, + "book-IV-6021-5-0": { + "amount_cents": 3063, + "due": "2026-03-20", + "invoice": "IV-6021-5-0", + "po": "PO5", + "status": "posted", + "units": 3 + }, + "book-IV-8469-4-0": { + "amount_cents": 64630, + "due": "2026-03-11", + "invoice": "IV-8469-4-0", + "po": "PO4", + "status": "posted", + "units": 10 + }, + "book-IV-9782-3-0": { + "amount_cents": 33384, + "due": "2026-03-20", + "invoice": "IV-9782-3-0", + "po": "PO3", + "status": "posted", + "units": 4 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 3 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 3 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 7 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 6 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 7 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 7 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-03-17", + "po": "PO0", + "state": "accepted", + "units": 25 + }, + "GI-0-1": { + "date": "2026-03-01", + "po": "PO0", + "state": "accepted", + "units": 23 + }, + "GI-0-2": { + "date": "2026-03-04", + "po": "PO0", + "state": "accepted", + "units": 27 + }, + "GI-0-3": { + "date": "2026-03-21", + "po": "PO0", + "state": "quarantine", + "units": 20 + }, + "GI-1-0": { + "date": "2026-03-17", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-1-1": { + "date": "2026-03-03", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-1-2": { + "date": "2026-03-12", + "po": "PO1", + "state": "quarantine", + "units": 12 + }, + "GI-1-3": { + "date": "2026-03-19", + "po": "PO1", + "state": "accepted", + "units": 15 + }, + "GI-2-0": { + "date": "2026-03-17", + "po": "PO2", + "state": "accepted", + "units": 27 + }, + "GI-2-1": { + "date": "2026-02-24", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-2-2": { + "date": "2026-03-20", + "po": "PO2", + "state": "accepted", + "units": 21 + }, + "GI-2-3": { + "date": "2026-03-09", + "po": "PO2", + "state": "quarantine", + "units": 13 + }, + "GI-3-0": { + "date": "2026-03-17", + "po": "PO3", + "state": "accepted", + "units": 17 + }, + "GI-3-1": { + "date": "2026-03-19", + "po": "PO3", + "state": "accepted", + "units": 14 + }, + "GI-3-2": { + "date": "2026-02-28", + "po": "PO3", + "state": "accepted", + "units": 19 + }, + "GI-3-3": { + "date": "2026-03-10", + "po": "PO3", + "state": "quarantine", + "units": 18 + }, + "GI-4-0": { + "date": "2026-03-17", + "po": "PO4", + "state": "accepted", + "units": 18 + }, + "GI-4-1": { + "date": "2026-03-17", + "po": "PO4", + "state": "accepted", + "units": 14 + }, + "GI-4-2": { + "date": "2026-02-27", + "po": "PO4", + "state": "quarantine", + "units": 12 + }, + "GI-4-3": { + "date": "2026-03-21", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-5-0": { + "date": "2026-03-17", + "po": "PO5", + "state": "accepted", + "units": 20 + }, + "GI-5-1": { + "date": "2026-02-27", + "po": "PO5", + "state": "quarantine", + "units": 19 + }, + "GI-5-2": { + "date": "2026-03-14", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-5-3": { + "date": "2026-03-02", + "po": "PO5", + "state": "accepted", + "units": 23 + }, + "GI-6-0": { + "date": "2026-03-17", + "po": "PO6", + "state": "accepted", + "units": 22 + }, + "GI-6-1": { + "date": "2026-03-12", + "po": "PO6", + "state": "quarantine", + "units": 28 + }, + "GI-6-2": { + "date": "2026-03-16", + "po": "PO6", + "state": "quarantine", + "units": 18 + }, + "GI-6-3": { + "date": "2026-02-26", + "po": "PO6", + "state": "accepted", + "units": 17 + } + }, + "invoice_inbox": { + "IV-1124-0-2": { + "date": "2026-03-07", + "po": "PO0", + "state": "posted", + "unit_price_cents": 21934, + "units": 17, + "vendor": "V3" + }, + "IV-1863-2-1": { + "date": "2026-03-04", + "po": "PO2", + "state": "posted", + "unit_price_cents": 8107, + "units": 16, + "vendor": "V4" + }, + "IV-2305-2-0": { + "date": "2026-02-18", + "po": "PO2", + "state": "posted", + "unit_price_cents": 8334, + "units": 19, + "vendor": "V4" + }, + "IV-2337-0-0": { + "date": "2026-02-18", + "po": "PO0", + "state": "posted", + "unit_price_cents": 22141, + "units": 1, + "vendor": "V3" + }, + "IV-2397-2-2": { + "date": "2026-03-08", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 9722, + "units": 16, + "vendor": "V4" + }, + "IV-2555-6-1": { + "date": "2026-02-16", + "po": "PO6", + "state": "review", + "unit_price_cents": 17338, + "units": 12, + "vendor": "V4" + }, + "IV-3286-0-3": { + "date": "2026-02-28", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 22785, + "units": 15, + "vendor": "V3" + }, + "IV-4221-1-2": { + "date": "2026-03-08", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 13390, + "units": 6, + "vendor": "V4" + }, + "IV-4362-3-1": { + "date": "2026-02-15", + "po": "PO3", + "state": "review", + "unit_price_cents": 8022, + "units": 8, + "vendor": "V3" + }, + "IV-4485-1-3": { + "date": "2026-03-18", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 13306, + "units": 11, + "vendor": "V4" + }, + "IV-4800-1-0": { + "date": "2026-02-18", + "po": "PO1", + "state": "posted", + "unit_price_cents": 11741, + "units": 3, + "vendor": "V4" + }, + "IV-5656-5-1": { + "date": "2026-03-04", + "po": "PO5", + "state": "void", + "unit_price_cents": 1130, + "units": 9, + "vendor": "V3" + }, + "IV-6021-5-0": { + "date": "2026-02-18", + "po": "PO5", + "state": "posted", + "unit_price_cents": 1021, + "units": 3, + "vendor": "V3" + }, + "IV-6723-0-1": { + "date": "2026-03-04", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 23467, + "units": 19, + "vendor": "V3" + }, + "IV-6920-2-3": { + "date": "2026-03-09", + "po": "PO2", + "state": "void", + "unit_price_cents": 9440, + "units": 14, + "vendor": "V4" + }, + "IV-7563-6-0": { + "date": "2026-02-18", + "po": "PO6", + "state": "review", + "unit_price_cents": 16135, + "units": 11, + "vendor": "V4" + }, + "IV-8469-4-0": { + "date": "2026-02-18", + "po": "PO4", + "state": "posted", + "unit_price_cents": 6463, + "units": 10, + "vendor": "V4" + }, + "IV-8690-4-1": { + "date": "2026-02-24", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 6966, + "units": 21, + "vendor": "V4" + }, + "IV-9768-1-1": { + "date": "2026-03-14", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 12142, + "units": 5, + "vendor": "V4" + }, + "IV-9782-3-0": { + "date": "2026-02-18", + "po": "PO3", + "state": "posted", + "unit_price_cents": 8346, + "units": 4, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "East", + "unit_price_cents": 22141, + "vendor": "V3" + }, + "PO1": { + "unit": "East", + "unit_price_cents": 11741, + "vendor": "V4" + }, + "PO2": { + "unit": "East", + "unit_price_cents": 8334, + "vendor": "V4" + }, + "PO3": { + "unit": "East", + "unit_price_cents": 8346, + "vendor": "V3" + }, + "PO4": { + "unit": "East", + "unit_price_cents": 6463, + "vendor": "V4" + }, + "PO5": { + "unit": "East", + "unit_price_cents": 1021, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 16135, + "vendor": "V4" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-2397-2-2": { + "invoice": "IV-2397-2-2", + "issues": [ + "price", + "units" + ], + "po": "PO2" + }, + "case-IV-3286-0-3": { + "invoice": "IV-3286-0-3", + "issues": [ + "price" + ], + "po": "PO0" + }, + "case-IV-4221-1-2": { + "invoice": "IV-4221-1-2", + "issues": [ + "price" + ], + "po": "PO1" + }, + "case-IV-4485-1-3": { + "invoice": "IV-4485-1-3", + "issues": [ + "price" + ], + "po": "PO1" + }, + "case-IV-6723-0-1": { + "invoice": "IV-6723-0-1", + "issues": [ + "price" + ], + "po": "PO0" + }, + "case-IV-8690-4-1": { + "invoice": "IV-8690-4-1", + "issues": [ + "price", + "units" + ], + "po": "PO4" + }, + "case-IV-9768-1-1": { + "invoice": "IV-9768-1-1", + "issues": [ + "price" + ], + "po": "PO1" + } + }, + "vendors": { + "V0": { + "net_days": 45 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-018/tests/test.sh b/tasks/autom-supplier-invoice-match-018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-018/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-018/tests/world.json b/tasks/autom-supplier-invoice-match-018/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..2a4a2945d1258d554ca62cf4195e443e430547ed --- /dev/null +++ b/tasks/autom-supplier-invoice-match-018/tests/world.json @@ -0,0 +1,430 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 3 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 3 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 7 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 6 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 7 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 7 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-03-17", + "po": "PO0", + "state": "accepted", + "units": 25 + }, + "GI-0-1": { + "date": "2026-03-01", + "po": "PO0", + "state": "accepted", + "units": 23 + }, + "GI-0-2": { + "date": "2026-03-04", + "po": "PO0", + "state": "accepted", + "units": 27 + }, + "GI-0-3": { + "date": "2026-03-21", + "po": "PO0", + "state": "quarantine", + "units": 20 + }, + "GI-1-0": { + "date": "2026-03-17", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-1-1": { + "date": "2026-03-03", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-1-2": { + "date": "2026-03-12", + "po": "PO1", + "state": "quarantine", + "units": 12 + }, + "GI-1-3": { + "date": "2026-03-19", + "po": "PO1", + "state": "accepted", + "units": 15 + }, + "GI-2-0": { + "date": "2026-03-17", + "po": "PO2", + "state": "accepted", + "units": 27 + }, + "GI-2-1": { + "date": "2026-02-24", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-2-2": { + "date": "2026-03-20", + "po": "PO2", + "state": "accepted", + "units": 21 + }, + "GI-2-3": { + "date": "2026-03-09", + "po": "PO2", + "state": "quarantine", + "units": 13 + }, + "GI-3-0": { + "date": "2026-03-17", + "po": "PO3", + "state": "accepted", + "units": 17 + }, + "GI-3-1": { + "date": "2026-03-19", + "po": "PO3", + "state": "accepted", + "units": 14 + }, + "GI-3-2": { + "date": "2026-02-28", + "po": "PO3", + "state": "accepted", + "units": 19 + }, + "GI-3-3": { + "date": "2026-03-10", + "po": "PO3", + "state": "quarantine", + "units": 18 + }, + "GI-4-0": { + "date": "2026-03-17", + "po": "PO4", + "state": "accepted", + "units": 18 + }, + "GI-4-1": { + "date": "2026-03-17", + "po": "PO4", + "state": "accepted", + "units": 14 + }, + "GI-4-2": { + "date": "2026-02-27", + "po": "PO4", + "state": "quarantine", + "units": 12 + }, + "GI-4-3": { + "date": "2026-03-21", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-5-0": { + "date": "2026-03-17", + "po": "PO5", + "state": "accepted", + "units": 20 + }, + "GI-5-1": { + "date": "2026-02-27", + "po": "PO5", + "state": "quarantine", + "units": 19 + }, + "GI-5-2": { + "date": "2026-03-14", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-5-3": { + "date": "2026-03-02", + "po": "PO5", + "state": "accepted", + "units": 23 + }, + "GI-6-0": { + "date": "2026-03-17", + "po": "PO6", + "state": "accepted", + "units": 22 + }, + "GI-6-1": { + "date": "2026-03-12", + "po": "PO6", + "state": "quarantine", + "units": 28 + }, + "GI-6-2": { + "date": "2026-03-16", + "po": "PO6", + "state": "quarantine", + "units": 18 + }, + "GI-6-3": { + "date": "2026-02-26", + "po": "PO6", + "state": "accepted", + "units": 17 + } + }, + "invoice_inbox": { + "IV-1124-0-2": { + "date": "2026-03-07", + "po": "PO0", + "state": "review", + "unit_price_cents": 21934, + "units": 17, + "vendor": "V3" + }, + "IV-1863-2-1": { + "date": "2026-03-04", + "po": "PO2", + "state": "review", + "unit_price_cents": 8107, + "units": 16, + "vendor": "V4" + }, + "IV-2305-2-0": { + "date": "2026-02-18", + "po": "PO2", + "state": "review", + "unit_price_cents": 8334, + "units": 19, + "vendor": "V4" + }, + "IV-2337-0-0": { + "date": "2026-02-18", + "po": "PO0", + "state": "review", + "unit_price_cents": 22141, + "units": 1, + "vendor": "V3" + }, + "IV-2397-2-2": { + "date": "2026-03-08", + "po": "PO2", + "state": "review", + "unit_price_cents": 9722, + "units": 16, + "vendor": "V4" + }, + "IV-2555-6-1": { + "date": "2026-02-16", + "po": "PO6", + "state": "review", + "unit_price_cents": 17338, + "units": 12, + "vendor": "V4" + }, + "IV-3286-0-3": { + "date": "2026-02-28", + "po": "PO0", + "state": "review", + "unit_price_cents": 22785, + "units": 15, + "vendor": "V3" + }, + "IV-4221-1-2": { + "date": "2026-03-08", + "po": "PO1", + "state": "review", + "unit_price_cents": 13390, + "units": 6, + "vendor": "V4" + }, + "IV-4362-3-1": { + "date": "2026-02-15", + "po": "PO3", + "state": "review", + "unit_price_cents": 8022, + "units": 8, + "vendor": "V3" + }, + "IV-4485-1-3": { + "date": "2026-03-18", + "po": "PO1", + "state": "review", + "unit_price_cents": 13306, + "units": 11, + "vendor": "V4" + }, + "IV-4800-1-0": { + "date": "2026-02-18", + "po": "PO1", + "state": "review", + "unit_price_cents": 11741, + "units": 3, + "vendor": "V4" + }, + "IV-5656-5-1": { + "date": "2026-03-04", + "po": "PO5", + "state": "void", + "unit_price_cents": 1130, + "units": 9, + "vendor": "V3" + }, + "IV-6021-5-0": { + "date": "2026-02-18", + "po": "PO5", + "state": "review", + "unit_price_cents": 1021, + "units": 3, + "vendor": "V3" + }, + "IV-6723-0-1": { + "date": "2026-03-04", + "po": "PO0", + "state": "review", + "unit_price_cents": 23467, + "units": 19, + "vendor": "V3" + }, + "IV-6920-2-3": { + "date": "2026-03-09", + "po": "PO2", + "state": "void", + "unit_price_cents": 9440, + "units": 14, + "vendor": "V4" + }, + "IV-7563-6-0": { + "date": "2026-02-18", + "po": "PO6", + "state": "review", + "unit_price_cents": 16135, + "units": 11, + "vendor": "V4" + }, + "IV-8469-4-0": { + "date": "2026-02-18", + "po": "PO4", + "state": "review", + "unit_price_cents": 6463, + "units": 10, + "vendor": "V4" + }, + "IV-8690-4-1": { + "date": "2026-02-24", + "po": "PO4", + "state": "review", + "unit_price_cents": 6966, + "units": 21, + "vendor": "V4" + }, + "IV-9768-1-1": { + "date": "2026-03-14", + "po": "PO1", + "state": "review", + "unit_price_cents": 12142, + "units": 5, + "vendor": "V4" + }, + "IV-9782-3-0": { + "date": "2026-02-18", + "po": "PO3", + "state": "review", + "unit_price_cents": 8346, + "units": 4, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "East", + "unit_price_cents": 22141, + "vendor": "V3" + }, + "PO1": { + "unit": "East", + "unit_price_cents": 11741, + "vendor": "V4" + }, + "PO2": { + "unit": "East", + "unit_price_cents": 8334, + "vendor": "V4" + }, + "PO3": { + "unit": "East", + "unit_price_cents": 8346, + "vendor": "V3" + }, + "PO4": { + "unit": "East", + "unit_price_cents": 6463, + "vendor": "V4" + }, + "PO5": { + "unit": "East", + "unit_price_cents": 1021, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 16135, + "vendor": "V4" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 45 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-018/tests/world_check.py b/tasks/autom-supplier-invoice-match-018/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-018/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-018/validation/openenv.json b/tasks/autom-supplier-invoice-match-018/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-018/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-019/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-019/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-019/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-019/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-019/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..ed60244e1365874b64561b98e47322025e202caa --- /dev/null +++ b/tasks/autom-supplier-invoice-match-019/environment/inputs/world.json @@ -0,0 +1,430 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 7 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 0 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 3 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 0 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 5 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 5 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 2 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-04-09", + "po": "PO0", + "state": "accepted", + "units": 14 + }, + "GI-0-1": { + "date": "2026-04-04", + "po": "PO0", + "state": "quarantine", + "units": 15 + }, + "GI-0-2": { + "date": "2026-04-01", + "po": "PO0", + "state": "quarantine", + "units": 21 + }, + "GI-0-3": { + "date": "2026-04-05", + "po": "PO0", + "state": "quarantine", + "units": 18 + }, + "GI-1-0": { + "date": "2026-04-09", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-1-1": { + "date": "2026-03-20", + "po": "PO1", + "state": "accepted", + "units": 17 + }, + "GI-1-2": { + "date": "2026-03-27", + "po": "PO1", + "state": "accepted", + "units": 21 + }, + "GI-1-3": { + "date": "2026-04-03", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-2-0": { + "date": "2026-04-09", + "po": "PO2", + "state": "accepted", + "units": 21 + }, + "GI-2-1": { + "date": "2026-04-03", + "po": "PO2", + "state": "quarantine", + "units": 21 + }, + "GI-2-2": { + "date": "2026-04-10", + "po": "PO2", + "state": "quarantine", + "units": 16 + }, + "GI-2-3": { + "date": "2026-03-25", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-3-0": { + "date": "2026-04-09", + "po": "PO3", + "state": "accepted", + "units": 20 + }, + "GI-3-1": { + "date": "2026-04-05", + "po": "PO3", + "state": "accepted", + "units": 24 + }, + "GI-3-2": { + "date": "2026-04-13", + "po": "PO3", + "state": "quarantine", + "units": 22 + }, + "GI-3-3": { + "date": "2026-03-30", + "po": "PO3", + "state": "quarantine", + "units": 23 + }, + "GI-4-0": { + "date": "2026-04-09", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-4-1": { + "date": "2026-04-07", + "po": "PO4", + "state": "accepted", + "units": 16 + }, + "GI-4-2": { + "date": "2026-04-05", + "po": "PO4", + "state": "accepted", + "units": 28 + }, + "GI-4-3": { + "date": "2026-04-12", + "po": "PO4", + "state": "quarantine", + "units": 27 + }, + "GI-5-0": { + "date": "2026-04-09", + "po": "PO5", + "state": "accepted", + "units": 21 + }, + "GI-5-1": { + "date": "2026-03-30", + "po": "PO5", + "state": "accepted", + "units": 17 + }, + "GI-5-2": { + "date": "2026-03-19", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-3": { + "date": "2026-03-26", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-6-0": { + "date": "2026-04-09", + "po": "PO6", + "state": "accepted", + "units": 18 + }, + "GI-6-1": { + "date": "2026-03-23", + "po": "PO6", + "state": "quarantine", + "units": 23 + }, + "GI-6-2": { + "date": "2026-03-30", + "po": "PO6", + "state": "quarantine", + "units": 28 + }, + "GI-6-3": { + "date": "2026-03-26", + "po": "PO6", + "state": "accepted", + "units": 15 + } + }, + "invoice_inbox": { + "IV-1498-5-2": { + "date": "2026-03-25", + "po": "PO5", + "state": "void", + "unit_price_cents": 1821, + "units": 9, + "vendor": "V2" + }, + "IV-1981-3-1": { + "date": "2026-04-01", + "po": "PO3", + "state": "review", + "unit_price_cents": 19408, + "units": 17, + "vendor": "V4" + }, + "IV-2024-1-2": { + "date": "2026-04-07", + "po": "PO1", + "state": "review", + "unit_price_cents": 14495, + "units": 22, + "vendor": "V4" + }, + "IV-3157-0-0": { + "date": "2026-03-20", + "po": "PO0", + "state": "review", + "unit_price_cents": 19605, + "units": 1, + "vendor": "V4" + }, + "IV-3216-1-1": { + "date": "2026-04-03", + "po": "PO1", + "state": "review", + "unit_price_cents": 14413, + "units": 4, + "vendor": "Unknown" + }, + "IV-3911-4-0": { + "date": "2026-03-20", + "po": "PO4", + "state": "review", + "unit_price_cents": 7131, + "units": 16, + "vendor": "V4" + }, + "IV-4159-4-1": { + "date": "2026-03-22", + "po": "PO4", + "state": "review", + "unit_price_cents": 7020, + "units": 13, + "vendor": "V4" + }, + "IV-4738-5-3": { + "date": "2026-03-29", + "po": "PO5", + "state": "review", + "unit_price_cents": 3769, + "units": 24, + "vendor": "V2" + }, + "IV-4949-6-1": { + "date": "2026-04-05", + "po": "PO6", + "state": "review", + "unit_price_cents": 8208, + "units": 3, + "vendor": "V2" + }, + "IV-5216-5-0": { + "date": "2026-03-20", + "po": "PO5", + "state": "review", + "unit_price_cents": 2168, + "units": 18, + "vendor": "V2" + }, + "IV-6169-0-1": { + "date": "2026-03-21", + "po": "PO0", + "state": "review", + "unit_price_cents": 19889, + "units": 15, + "vendor": "V4" + }, + "IV-6905-6-2": { + "date": "2026-03-19", + "po": "PO6", + "state": "review", + "unit_price_cents": 9054, + "units": 25, + "vendor": "V2" + }, + "IV-7340-3-0": { + "date": "2026-03-20", + "po": "PO3", + "state": "review", + "unit_price_cents": 17613, + "units": 3, + "vendor": "V4" + }, + "IV-7828-6-3": { + "date": "2026-03-14", + "po": "PO6", + "state": "void", + "unit_price_cents": 8596, + "units": 3, + "vendor": "V2" + }, + "IV-7853-3-2": { + "date": "2026-03-25", + "po": "PO3", + "state": "review", + "unit_price_cents": 18800, + "units": 13, + "vendor": "Unknown" + }, + "IV-7936-2-0": { + "date": "2026-03-20", + "po": "PO2", + "state": "review", + "unit_price_cents": 20243, + "units": 3, + "vendor": "V3" + }, + "IV-8071-1-0": { + "date": "2026-03-20", + "po": "PO1", + "state": "review", + "unit_price_cents": 14261, + "units": 5, + "vendor": "V4" + }, + "IV-8386-5-1": { + "date": "2026-04-08", + "po": "PO5", + "state": "review", + "unit_price_cents": 1898, + "units": 22, + "vendor": "Unknown" + }, + "IV-9110-6-0": { + "date": "2026-03-20", + "po": "PO6", + "state": "review", + "unit_price_cents": 8551, + "units": 5, + "vendor": "V2" + }, + "IV-9111-2-1": { + "date": "2026-03-27", + "po": "PO2", + "state": "review", + "unit_price_cents": 21789, + "units": 22, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "Central", + "unit_price_cents": 19605, + "vendor": "V4" + }, + "PO1": { + "unit": "Central", + "unit_price_cents": 14261, + "vendor": "V4" + }, + "PO2": { + "unit": "Central", + "unit_price_cents": 20243, + "vendor": "V3" + }, + "PO3": { + "unit": "Central", + "unit_price_cents": 17613, + "vendor": "V4" + }, + "PO4": { + "unit": "Central", + "unit_price_cents": 7131, + "vendor": "V4" + }, + "PO5": { + "unit": "Central", + "unit_price_cents": 2168, + "vendor": "V2" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 8551, + "vendor": "V2" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 21 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 15 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-019/instruction.md b/tasks/autom-supplier-invoice-match-019/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..37b8e8d53bb3a0216191ecfbb06ffc72f8653465 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-019/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit Central at 2026-04-10. Handle invoices in review attached to that unit's purchase orders, invoice dates 2026-03-20 through 2026-04-10 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 100 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-019/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-019/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..19043c79508e696377b6a720157afe3b48d2e5ca --- /dev/null +++ b/tasks/autom-supplier-invoice-match-019/solution/files/actions.jsonl @@ -0,0 +1,30 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-3157-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-6169-0-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8071-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3216-1-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-2024-1-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-7936-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-9111-2-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-7340-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-1981-3-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7853-3-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-3911-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-4159-4-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5216-5-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-8386-5-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4738-5-3", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 19605, "due": "2026-04-20", "invoice": "IV-3157-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-3157-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 114096, "due": "2026-04-20", "invoice": "IV-3911-4-0", "po": "PO4", "status": "posted", "units": 16}, "id": "book-IV-3911-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 39024, "due": "2026-04-20", "invoice": "IV-5216-5-0", "po": "PO5", "status": "posted", "units": 18}, "id": "book-IV-5216-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 52839, "due": "2026-04-20", "invoice": "IV-7340-3-0", "po": "PO3", "status": "posted", "units": 3}, "id": "book-IV-7340-3-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 60729, "due": "2026-04-06", "invoice": "IV-7936-2-0", "po": "PO2", "status": "posted", "units": 3}, "id": "book-IV-7936-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 71305, "due": "2026-04-20", "invoice": "IV-8071-1-0", "po": "PO1", "status": "posted", "units": 5}, "id": "book-IV-8071-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 91260, "due": "2026-04-21", "invoice": "IV-4159-4-1", "po": "PO4", "status": "posted", "units": 13}, "id": "book-IV-4159-4-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-6169-0-1", "issues": ["price", "units"], "po": "PO0"}, "id": "case-IV-6169-0-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7853-3-2", "issues": ["vendor", "price"], "po": "PO3"}, "id": "case-IV-7853-3-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-9111-2-1", "issues": ["price"], "po": "PO2"}, "id": "case-IV-9111-2-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4738-5-3", "issues": ["price"], "po": "PO5"}, "id": "case-IV-4738-5-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-1981-3-1", "issues": ["price"], "po": "PO3"}, "id": "case-IV-1981-3-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3216-1-1", "issues": ["vendor", "price"], "po": "PO1"}, "id": "case-IV-3216-1-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-2024-1-2", "issues": ["price"], "po": "PO1"}, "id": "case-IV-2024-1-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-8386-5-1", "issues": ["vendor"], "po": "PO5"}, "id": "case-IV-8386-5-1", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-019/solution/solve.sh b/tasks/autom-supplier-invoice-match-019/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-019/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-019/task.toml b/tasks/autom-supplier-invoice-match-019/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..415da38fb0969f37dec5968619476d6aca025d22 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-019/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-019" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 19 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-019" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-019/tests/expected.json b/tasks/autom-supplier-invoice-match-019/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-019/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-019/tests/grade.py b/tasks/autom-supplier-invoice-match-019/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-019/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-019/tests/replay.py b/tasks/autom-supplier-invoice-match-019/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-019/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-019/tests/target.json b/tasks/autom-supplier-invoice-match-019/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..d292bdd5742f0077723d4809b582014fc3fcec36 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-019/tests/target.json @@ -0,0 +1,545 @@ +{ + "ap_postings": { + "book-IV-3157-0-0": { + "amount_cents": 19605, + "due": "2026-04-20", + "invoice": "IV-3157-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "book-IV-3911-4-0": { + "amount_cents": 114096, + "due": "2026-04-20", + "invoice": "IV-3911-4-0", + "po": "PO4", + "status": "posted", + "units": 16 + }, + "book-IV-4159-4-1": { + "amount_cents": 91260, + "due": "2026-04-21", + "invoice": "IV-4159-4-1", + "po": "PO4", + "status": "posted", + "units": 13 + }, + "book-IV-5216-5-0": { + "amount_cents": 39024, + "due": "2026-04-20", + "invoice": "IV-5216-5-0", + "po": "PO5", + "status": "posted", + "units": 18 + }, + "book-IV-7340-3-0": { + "amount_cents": 52839, + "due": "2026-04-20", + "invoice": "IV-7340-3-0", + "po": "PO3", + "status": "posted", + "units": 3 + }, + "book-IV-7936-2-0": { + "amount_cents": 60729, + "due": "2026-04-06", + "invoice": "IV-7936-2-0", + "po": "PO2", + "status": "posted", + "units": 3 + }, + "book-IV-8071-1-0": { + "amount_cents": 71305, + "due": "2026-04-20", + "invoice": "IV-8071-1-0", + "po": "PO1", + "status": "posted", + "units": 5 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 7 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 0 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 3 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 0 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 5 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 5 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 2 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-04-09", + "po": "PO0", + "state": "accepted", + "units": 14 + }, + "GI-0-1": { + "date": "2026-04-04", + "po": "PO0", + "state": "quarantine", + "units": 15 + }, + "GI-0-2": { + "date": "2026-04-01", + "po": "PO0", + "state": "quarantine", + "units": 21 + }, + "GI-0-3": { + "date": "2026-04-05", + "po": "PO0", + "state": "quarantine", + "units": 18 + }, + "GI-1-0": { + "date": "2026-04-09", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-1-1": { + "date": "2026-03-20", + "po": "PO1", + "state": "accepted", + "units": 17 + }, + "GI-1-2": { + "date": "2026-03-27", + "po": "PO1", + "state": "accepted", + "units": 21 + }, + "GI-1-3": { + "date": "2026-04-03", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-2-0": { + "date": "2026-04-09", + "po": "PO2", + "state": "accepted", + "units": 21 + }, + "GI-2-1": { + "date": "2026-04-03", + "po": "PO2", + "state": "quarantine", + "units": 21 + }, + "GI-2-2": { + "date": "2026-04-10", + "po": "PO2", + "state": "quarantine", + "units": 16 + }, + "GI-2-3": { + "date": "2026-03-25", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-3-0": { + "date": "2026-04-09", + "po": "PO3", + "state": "accepted", + "units": 20 + }, + "GI-3-1": { + "date": "2026-04-05", + "po": "PO3", + "state": "accepted", + "units": 24 + }, + "GI-3-2": { + "date": "2026-04-13", + "po": "PO3", + "state": "quarantine", + "units": 22 + }, + "GI-3-3": { + "date": "2026-03-30", + "po": "PO3", + "state": "quarantine", + "units": 23 + }, + "GI-4-0": { + "date": "2026-04-09", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-4-1": { + "date": "2026-04-07", + "po": "PO4", + "state": "accepted", + "units": 16 + }, + "GI-4-2": { + "date": "2026-04-05", + "po": "PO4", + "state": "accepted", + "units": 28 + }, + "GI-4-3": { + "date": "2026-04-12", + "po": "PO4", + "state": "quarantine", + "units": 27 + }, + "GI-5-0": { + "date": "2026-04-09", + "po": "PO5", + "state": "accepted", + "units": 21 + }, + "GI-5-1": { + "date": "2026-03-30", + "po": "PO5", + "state": "accepted", + "units": 17 + }, + "GI-5-2": { + "date": "2026-03-19", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-3": { + "date": "2026-03-26", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-6-0": { + "date": "2026-04-09", + "po": "PO6", + "state": "accepted", + "units": 18 + }, + "GI-6-1": { + "date": "2026-03-23", + "po": "PO6", + "state": "quarantine", + "units": 23 + }, + "GI-6-2": { + "date": "2026-03-30", + "po": "PO6", + "state": "quarantine", + "units": 28 + }, + "GI-6-3": { + "date": "2026-03-26", + "po": "PO6", + "state": "accepted", + "units": 15 + } + }, + "invoice_inbox": { + "IV-1498-5-2": { + "date": "2026-03-25", + "po": "PO5", + "state": "void", + "unit_price_cents": 1821, + "units": 9, + "vendor": "V2" + }, + "IV-1981-3-1": { + "date": "2026-04-01", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 19408, + "units": 17, + "vendor": "V4" + }, + "IV-2024-1-2": { + "date": "2026-04-07", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 14495, + "units": 22, + "vendor": "V4" + }, + "IV-3157-0-0": { + "date": "2026-03-20", + "po": "PO0", + "state": "posted", + "unit_price_cents": 19605, + "units": 1, + "vendor": "V4" + }, + "IV-3216-1-1": { + "date": "2026-04-03", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 14413, + "units": 4, + "vendor": "Unknown" + }, + "IV-3911-4-0": { + "date": "2026-03-20", + "po": "PO4", + "state": "posted", + "unit_price_cents": 7131, + "units": 16, + "vendor": "V4" + }, + "IV-4159-4-1": { + "date": "2026-03-22", + "po": "PO4", + "state": "posted", + "unit_price_cents": 7020, + "units": 13, + "vendor": "V4" + }, + "IV-4738-5-3": { + "date": "2026-03-29", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 3769, + "units": 24, + "vendor": "V2" + }, + "IV-4949-6-1": { + "date": "2026-04-05", + "po": "PO6", + "state": "review", + "unit_price_cents": 8208, + "units": 3, + "vendor": "V2" + }, + "IV-5216-5-0": { + "date": "2026-03-20", + "po": "PO5", + "state": "posted", + "unit_price_cents": 2168, + "units": 18, + "vendor": "V2" + }, + "IV-6169-0-1": { + "date": "2026-03-21", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 19889, + "units": 15, + "vendor": "V4" + }, + "IV-6905-6-2": { + "date": "2026-03-19", + "po": "PO6", + "state": "review", + "unit_price_cents": 9054, + "units": 25, + "vendor": "V2" + }, + "IV-7340-3-0": { + "date": "2026-03-20", + "po": "PO3", + "state": "posted", + "unit_price_cents": 17613, + "units": 3, + "vendor": "V4" + }, + "IV-7828-6-3": { + "date": "2026-03-14", + "po": "PO6", + "state": "void", + "unit_price_cents": 8596, + "units": 3, + "vendor": "V2" + }, + "IV-7853-3-2": { + "date": "2026-03-25", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 18800, + "units": 13, + "vendor": "Unknown" + }, + "IV-7936-2-0": { + "date": "2026-03-20", + "po": "PO2", + "state": "posted", + "unit_price_cents": 20243, + "units": 3, + "vendor": "V3" + }, + "IV-8071-1-0": { + "date": "2026-03-20", + "po": "PO1", + "state": "posted", + "unit_price_cents": 14261, + "units": 5, + "vendor": "V4" + }, + "IV-8386-5-1": { + "date": "2026-04-08", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 1898, + "units": 22, + "vendor": "Unknown" + }, + "IV-9110-6-0": { + "date": "2026-03-20", + "po": "PO6", + "state": "review", + "unit_price_cents": 8551, + "units": 5, + "vendor": "V2" + }, + "IV-9111-2-1": { + "date": "2026-03-27", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 21789, + "units": 22, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "Central", + "unit_price_cents": 19605, + "vendor": "V4" + }, + "PO1": { + "unit": "Central", + "unit_price_cents": 14261, + "vendor": "V4" + }, + "PO2": { + "unit": "Central", + "unit_price_cents": 20243, + "vendor": "V3" + }, + "PO3": { + "unit": "Central", + "unit_price_cents": 17613, + "vendor": "V4" + }, + "PO4": { + "unit": "Central", + "unit_price_cents": 7131, + "vendor": "V4" + }, + "PO5": { + "unit": "Central", + "unit_price_cents": 2168, + "vendor": "V2" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 8551, + "vendor": "V2" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-1981-3-1": { + "invoice": "IV-1981-3-1", + "issues": [ + "price" + ], + "po": "PO3" + }, + "case-IV-2024-1-2": { + "invoice": "IV-2024-1-2", + "issues": [ + "price" + ], + "po": "PO1" + }, + "case-IV-3216-1-1": { + "invoice": "IV-3216-1-1", + "issues": [ + "vendor", + "price" + ], + "po": "PO1" + }, + "case-IV-4738-5-3": { + "invoice": "IV-4738-5-3", + "issues": [ + "price" + ], + "po": "PO5" + }, + "case-IV-6169-0-1": { + "invoice": "IV-6169-0-1", + "issues": [ + "price", + "units" + ], + "po": "PO0" + }, + "case-IV-7853-3-2": { + "invoice": "IV-7853-3-2", + "issues": [ + "vendor", + "price" + ], + "po": "PO3" + }, + "case-IV-8386-5-1": { + "invoice": "IV-8386-5-1", + "issues": [ + "vendor" + ], + "po": "PO5" + }, + "case-IV-9111-2-1": { + "invoice": "IV-9111-2-1", + "issues": [ + "price" + ], + "po": "PO2" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 21 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 15 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-019/tests/test.sh b/tasks/autom-supplier-invoice-match-019/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-019/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-019/tests/world.json b/tasks/autom-supplier-invoice-match-019/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..ed60244e1365874b64561b98e47322025e202caa --- /dev/null +++ b/tasks/autom-supplier-invoice-match-019/tests/world.json @@ -0,0 +1,430 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 7 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 0 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 3 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 0 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 5 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 5 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 2 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-04-09", + "po": "PO0", + "state": "accepted", + "units": 14 + }, + "GI-0-1": { + "date": "2026-04-04", + "po": "PO0", + "state": "quarantine", + "units": 15 + }, + "GI-0-2": { + "date": "2026-04-01", + "po": "PO0", + "state": "quarantine", + "units": 21 + }, + "GI-0-3": { + "date": "2026-04-05", + "po": "PO0", + "state": "quarantine", + "units": 18 + }, + "GI-1-0": { + "date": "2026-04-09", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-1-1": { + "date": "2026-03-20", + "po": "PO1", + "state": "accepted", + "units": 17 + }, + "GI-1-2": { + "date": "2026-03-27", + "po": "PO1", + "state": "accepted", + "units": 21 + }, + "GI-1-3": { + "date": "2026-04-03", + "po": "PO1", + "state": "accepted", + "units": 16 + }, + "GI-2-0": { + "date": "2026-04-09", + "po": "PO2", + "state": "accepted", + "units": 21 + }, + "GI-2-1": { + "date": "2026-04-03", + "po": "PO2", + "state": "quarantine", + "units": 21 + }, + "GI-2-2": { + "date": "2026-04-10", + "po": "PO2", + "state": "quarantine", + "units": 16 + }, + "GI-2-3": { + "date": "2026-03-25", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-3-0": { + "date": "2026-04-09", + "po": "PO3", + "state": "accepted", + "units": 20 + }, + "GI-3-1": { + "date": "2026-04-05", + "po": "PO3", + "state": "accepted", + "units": 24 + }, + "GI-3-2": { + "date": "2026-04-13", + "po": "PO3", + "state": "quarantine", + "units": 22 + }, + "GI-3-3": { + "date": "2026-03-30", + "po": "PO3", + "state": "quarantine", + "units": 23 + }, + "GI-4-0": { + "date": "2026-04-09", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-4-1": { + "date": "2026-04-07", + "po": "PO4", + "state": "accepted", + "units": 16 + }, + "GI-4-2": { + "date": "2026-04-05", + "po": "PO4", + "state": "accepted", + "units": 28 + }, + "GI-4-3": { + "date": "2026-04-12", + "po": "PO4", + "state": "quarantine", + "units": 27 + }, + "GI-5-0": { + "date": "2026-04-09", + "po": "PO5", + "state": "accepted", + "units": 21 + }, + "GI-5-1": { + "date": "2026-03-30", + "po": "PO5", + "state": "accepted", + "units": 17 + }, + "GI-5-2": { + "date": "2026-03-19", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-3": { + "date": "2026-03-26", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-6-0": { + "date": "2026-04-09", + "po": "PO6", + "state": "accepted", + "units": 18 + }, + "GI-6-1": { + "date": "2026-03-23", + "po": "PO6", + "state": "quarantine", + "units": 23 + }, + "GI-6-2": { + "date": "2026-03-30", + "po": "PO6", + "state": "quarantine", + "units": 28 + }, + "GI-6-3": { + "date": "2026-03-26", + "po": "PO6", + "state": "accepted", + "units": 15 + } + }, + "invoice_inbox": { + "IV-1498-5-2": { + "date": "2026-03-25", + "po": "PO5", + "state": "void", + "unit_price_cents": 1821, + "units": 9, + "vendor": "V2" + }, + "IV-1981-3-1": { + "date": "2026-04-01", + "po": "PO3", + "state": "review", + "unit_price_cents": 19408, + "units": 17, + "vendor": "V4" + }, + "IV-2024-1-2": { + "date": "2026-04-07", + "po": "PO1", + "state": "review", + "unit_price_cents": 14495, + "units": 22, + "vendor": "V4" + }, + "IV-3157-0-0": { + "date": "2026-03-20", + "po": "PO0", + "state": "review", + "unit_price_cents": 19605, + "units": 1, + "vendor": "V4" + }, + "IV-3216-1-1": { + "date": "2026-04-03", + "po": "PO1", + "state": "review", + "unit_price_cents": 14413, + "units": 4, + "vendor": "Unknown" + }, + "IV-3911-4-0": { + "date": "2026-03-20", + "po": "PO4", + "state": "review", + "unit_price_cents": 7131, + "units": 16, + "vendor": "V4" + }, + "IV-4159-4-1": { + "date": "2026-03-22", + "po": "PO4", + "state": "review", + "unit_price_cents": 7020, + "units": 13, + "vendor": "V4" + }, + "IV-4738-5-3": { + "date": "2026-03-29", + "po": "PO5", + "state": "review", + "unit_price_cents": 3769, + "units": 24, + "vendor": "V2" + }, + "IV-4949-6-1": { + "date": "2026-04-05", + "po": "PO6", + "state": "review", + "unit_price_cents": 8208, + "units": 3, + "vendor": "V2" + }, + "IV-5216-5-0": { + "date": "2026-03-20", + "po": "PO5", + "state": "review", + "unit_price_cents": 2168, + "units": 18, + "vendor": "V2" + }, + "IV-6169-0-1": { + "date": "2026-03-21", + "po": "PO0", + "state": "review", + "unit_price_cents": 19889, + "units": 15, + "vendor": "V4" + }, + "IV-6905-6-2": { + "date": "2026-03-19", + "po": "PO6", + "state": "review", + "unit_price_cents": 9054, + "units": 25, + "vendor": "V2" + }, + "IV-7340-3-0": { + "date": "2026-03-20", + "po": "PO3", + "state": "review", + "unit_price_cents": 17613, + "units": 3, + "vendor": "V4" + }, + "IV-7828-6-3": { + "date": "2026-03-14", + "po": "PO6", + "state": "void", + "unit_price_cents": 8596, + "units": 3, + "vendor": "V2" + }, + "IV-7853-3-2": { + "date": "2026-03-25", + "po": "PO3", + "state": "review", + "unit_price_cents": 18800, + "units": 13, + "vendor": "Unknown" + }, + "IV-7936-2-0": { + "date": "2026-03-20", + "po": "PO2", + "state": "review", + "unit_price_cents": 20243, + "units": 3, + "vendor": "V3" + }, + "IV-8071-1-0": { + "date": "2026-03-20", + "po": "PO1", + "state": "review", + "unit_price_cents": 14261, + "units": 5, + "vendor": "V4" + }, + "IV-8386-5-1": { + "date": "2026-04-08", + "po": "PO5", + "state": "review", + "unit_price_cents": 1898, + "units": 22, + "vendor": "Unknown" + }, + "IV-9110-6-0": { + "date": "2026-03-20", + "po": "PO6", + "state": "review", + "unit_price_cents": 8551, + "units": 5, + "vendor": "V2" + }, + "IV-9111-2-1": { + "date": "2026-03-27", + "po": "PO2", + "state": "review", + "unit_price_cents": 21789, + "units": 22, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "Central", + "unit_price_cents": 19605, + "vendor": "V4" + }, + "PO1": { + "unit": "Central", + "unit_price_cents": 14261, + "vendor": "V4" + }, + "PO2": { + "unit": "Central", + "unit_price_cents": 20243, + "vendor": "V3" + }, + "PO3": { + "unit": "Central", + "unit_price_cents": 17613, + "vendor": "V4" + }, + "PO4": { + "unit": "Central", + "unit_price_cents": 7131, + "vendor": "V4" + }, + "PO5": { + "unit": "Central", + "unit_price_cents": 2168, + "vendor": "V2" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 8551, + "vendor": "V2" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 21 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 15 + }, + "V4": { + "net_days": 30 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-019/tests/world_check.py b/tasks/autom-supplier-invoice-match-019/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-019/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-019/validation/openenv.json b/tasks/autom-supplier-invoice-match-019/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-019/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-020/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-020/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-020/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-020/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-020/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..b0214ff19a0e832f80478a4d997988306275f0f3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-020/environment/inputs/world.json @@ -0,0 +1,446 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 3 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 7 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 2 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 4 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 4 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 5 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-05-02", + "po": "PO0", + "state": "accepted", + "units": 27 + }, + "GI-0-1": { + "date": "2026-05-01", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-0-2": { + "date": "2026-04-13", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-0-3": { + "date": "2026-04-29", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-1-0": { + "date": "2026-05-02", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-1-1": { + "date": "2026-04-25", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-1-2": { + "date": "2026-04-13", + "po": "PO1", + "state": "accepted", + "units": 28 + }, + "GI-1-3": { + "date": "2026-04-13", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-2-0": { + "date": "2026-05-02", + "po": "PO2", + "state": "accepted", + "units": 17 + }, + "GI-2-1": { + "date": "2026-05-04", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-2-2": { + "date": "2026-04-21", + "po": "PO2", + "state": "accepted", + "units": 16 + }, + "GI-2-3": { + "date": "2026-04-18", + "po": "PO2", + "state": "accepted", + "units": 18 + }, + "GI-3-0": { + "date": "2026-05-02", + "po": "PO3", + "state": "accepted", + "units": 13 + }, + "GI-3-1": { + "date": "2026-04-14", + "po": "PO3", + "state": "accepted", + "units": 24 + }, + "GI-3-2": { + "date": "2026-05-04", + "po": "PO3", + "state": "quarantine", + "units": 18 + }, + "GI-3-3": { + "date": "2026-04-22", + "po": "PO3", + "state": "quarantine", + "units": 16 + }, + "GI-4-0": { + "date": "2026-05-02", + "po": "PO4", + "state": "accepted", + "units": 25 + }, + "GI-4-1": { + "date": "2026-05-07", + "po": "PO4", + "state": "quarantine", + "units": 12 + }, + "GI-4-2": { + "date": "2026-04-12", + "po": "PO4", + "state": "quarantine", + "units": 27 + }, + "GI-4-3": { + "date": "2026-04-25", + "po": "PO4", + "state": "accepted", + "units": 24 + }, + "GI-5-0": { + "date": "2026-05-02", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-1": { + "date": "2026-04-29", + "po": "PO5", + "state": "quarantine", + "units": 14 + }, + "GI-5-2": { + "date": "2026-04-11", + "po": "PO5", + "state": "quarantine", + "units": 13 + }, + "GI-5-3": { + "date": "2026-05-04", + "po": "PO5", + "state": "accepted", + "units": 28 + }, + "GI-6-0": { + "date": "2026-05-02", + "po": "PO6", + "state": "accepted", + "units": 24 + }, + "GI-6-1": { + "date": "2026-04-12", + "po": "PO6", + "state": "accepted", + "units": 18 + }, + "GI-6-2": { + "date": "2026-05-03", + "po": "PO6", + "state": "accepted", + "units": 14 + }, + "GI-6-3": { + "date": "2026-04-11", + "po": "PO6", + "state": "accepted", + "units": 22 + } + }, + "invoice_inbox": { + "IV-1164-4-0": { + "date": "2026-04-12", + "po": "PO4", + "state": "review", + "unit_price_cents": 15618, + "units": 3, + "vendor": "V1" + }, + "IV-2376-5-0": { + "date": "2026-04-12", + "po": "PO5", + "state": "review", + "unit_price_cents": 15480, + "units": 23, + "vendor": "V1" + }, + "IV-2431-5-1": { + "date": "2026-04-26", + "po": "PO5", + "state": "void", + "unit_price_cents": 15581, + "units": 25, + "vendor": "V1" + }, + "IV-2518-0-3": { + "date": "2026-04-18", + "po": "PO0", + "state": "void", + "unit_price_cents": 963, + "units": 21, + "vendor": "V4" + }, + "IV-2888-3-1": { + "date": "2026-04-16", + "po": "PO3", + "state": "review", + "unit_price_cents": 12471, + "units": 7, + "vendor": "V1" + }, + "IV-2891-2-0": { + "date": "2026-04-12", + "po": "PO2", + "state": "review", + "unit_price_cents": 7385, + "units": 7, + "vendor": "V0" + }, + "IV-2920-5-2": { + "date": "2026-05-03", + "po": "PO5", + "state": "review", + "unit_price_cents": 17548, + "units": 14, + "vendor": "V1" + }, + "IV-3756-5-3": { + "date": "2026-05-01", + "po": "PO5", + "state": "review", + "unit_price_cents": 15739, + "units": 3, + "vendor": "V1" + }, + "IV-4110-3-2": { + "date": "2026-04-22", + "po": "PO3", + "state": "void", + "unit_price_cents": 11509, + "units": 18, + "vendor": "V1" + }, + "IV-5169-0-2": { + "date": "2026-05-01", + "po": "PO0", + "state": "void", + "unit_price_cents": 3014, + "units": 23, + "vendor": "V4" + }, + "IV-5531-6-0": { + "date": "2026-04-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 15416, + "units": 17, + "vendor": "V3" + }, + "IV-6035-4-1": { + "date": "2026-04-10", + "po": "PO4", + "state": "review", + "unit_price_cents": 17478, + "units": 11, + "vendor": "V1" + }, + "IV-6750-2-1": { + "date": "2026-05-04", + "po": "PO2", + "state": "review", + "unit_price_cents": 9117, + "units": 3, + "vendor": "V0" + }, + "IV-7778-0-1": { + "date": "2026-04-09", + "po": "PO0", + "state": "void", + "unit_price_cents": 2982, + "units": 22, + "vendor": "V4" + }, + "IV-7862-4-2": { + "date": "2026-04-13", + "po": "PO4", + "state": "review", + "unit_price_cents": 16207, + "units": 5, + "vendor": "V1" + }, + "IV-8073-1-0": { + "date": "2026-04-12", + "po": "PO1", + "state": "review", + "unit_price_cents": 21692, + "units": 21, + "vendor": "V4" + }, + "IV-8527-6-1": { + "date": "2026-04-08", + "po": "PO6", + "state": "review", + "unit_price_cents": 15539, + "units": 20, + "vendor": "Unknown" + }, + "IV-8653-0-0": { + "date": "2026-04-12", + "po": "PO0", + "state": "review", + "unit_price_cents": 1303, + "units": 1, + "vendor": "V4" + }, + "IV-8722-3-0": { + "date": "2026-04-12", + "po": "PO3", + "state": "review", + "unit_price_cents": 10974, + "units": 18, + "vendor": "V1" + }, + "IV-8771-2-2": { + "date": "2026-04-19", + "po": "PO2", + "state": "void", + "unit_price_cents": 9117, + "units": 13, + "vendor": "V0" + }, + "IV-9566-1-1": { + "date": "2026-04-09", + "po": "PO1", + "state": "review", + "unit_price_cents": 23455, + "units": 8, + "vendor": "V4" + }, + "IV-9610-1-2": { + "date": "2026-04-13", + "po": "PO1", + "state": "review", + "unit_price_cents": 22993, + "units": 6, + "vendor": "V4" + } + }, + "purchase_orders": { + "PO0": { + "unit": "North", + "unit_price_cents": 1303, + "vendor": "V4" + }, + "PO1": { + "unit": "North", + "unit_price_cents": 21692, + "vendor": "V4" + }, + "PO2": { + "unit": "North", + "unit_price_cents": 7385, + "vendor": "V0" + }, + "PO3": { + "unit": "North", + "unit_price_cents": 10974, + "vendor": "V1" + }, + "PO4": { + "unit": "North", + "unit_price_cents": 15618, + "vendor": "V1" + }, + "PO5": { + "unit": "North", + "unit_price_cents": 15480, + "vendor": "V1" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 15416, + "vendor": "V3" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 21 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-020/instruction.md b/tasks/autom-supplier-invoice-match-020/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c8d5a6d04e33e48c37c9253d531caaa605bfd803 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-020/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit North at 2026-05-03. Handle invoices in review attached to that unit's purchase orders, invoice dates 2026-04-12 through 2026-05-03 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 500 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-020/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-020/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d2a3d26b12e74f7acf8582e96af755e79659f183 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-020/solution/files/actions.jsonl @@ -0,0 +1,22 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8653-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8073-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-9610-1-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-2891-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8722-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-2888-3-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-1164-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-7862-4-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-2376-5-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-2920-5-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3756-5-3", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 46854, "due": "2026-05-04", "invoice": "IV-1164-4-0", "po": "PO4", "status": "posted", "units": 3}, "id": "book-IV-1164-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 356040, "due": "2026-05-04", "invoice": "IV-2376-5-0", "po": "PO5", "status": "posted", "units": 23}, "id": "book-IV-2376-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 51695, "due": "2026-05-12", "invoice": "IV-2891-2-0", "po": "PO2", "status": "posted", "units": 7}, "id": "book-IV-2891-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 455532, "due": "2026-05-04", "invoice": "IV-8073-1-0", "po": "PO1", "status": "posted", "units": 21}, "id": "book-IV-8073-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 1303, "due": "2026-05-04", "invoice": "IV-8653-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-8653-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 197532, "due": "2026-05-04", "invoice": "IV-8722-3-0", "po": "PO3", "status": "posted", "units": 18}, "id": "book-IV-8722-3-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 81035, "due": "2026-05-04", "invoice": "IV-7862-4-2", "po": "PO4", "status": "posted", "units": 5}, "id": "book-IV-7862-4-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-9610-1-2", "issues": ["price"], "po": "PO1"}, "id": "case-IV-9610-1-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-2888-3-1", "issues": ["price"], "po": "PO3"}, "id": "case-IV-2888-3-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3756-5-3", "issues": ["units"], "po": "PO5"}, "id": "case-IV-3756-5-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-2920-5-2", "issues": ["price", "units"], "po": "PO5"}, "id": "case-IV-2920-5-2", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-020/solution/solve.sh b/tasks/autom-supplier-invoice-match-020/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-020/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-020/task.toml b/tasks/autom-supplier-invoice-match-020/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3155967d658c711cfce486bfd563ce5c11820110 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-020/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-020" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 20 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-020" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-020/tests/expected.json b/tasks/autom-supplier-invoice-match-020/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-020/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-020/tests/grade.py b/tasks/autom-supplier-invoice-match-020/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-020/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-020/tests/replay.py b/tasks/autom-supplier-invoice-match-020/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-020/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-020/tests/target.json b/tasks/autom-supplier-invoice-match-020/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..e29267516aa13519d898514d9d38b117e6b70beb --- /dev/null +++ b/tasks/autom-supplier-invoice-match-020/tests/target.json @@ -0,0 +1,531 @@ +{ + "ap_postings": { + "book-IV-1164-4-0": { + "amount_cents": 46854, + "due": "2026-05-04", + "invoice": "IV-1164-4-0", + "po": "PO4", + "status": "posted", + "units": 3 + }, + "book-IV-2376-5-0": { + "amount_cents": 356040, + "due": "2026-05-04", + "invoice": "IV-2376-5-0", + "po": "PO5", + "status": "posted", + "units": 23 + }, + "book-IV-2891-2-0": { + "amount_cents": 51695, + "due": "2026-05-12", + "invoice": "IV-2891-2-0", + "po": "PO2", + "status": "posted", + "units": 7 + }, + "book-IV-7862-4-2": { + "amount_cents": 81035, + "due": "2026-05-04", + "invoice": "IV-7862-4-2", + "po": "PO4", + "status": "posted", + "units": 5 + }, + "book-IV-8073-1-0": { + "amount_cents": 455532, + "due": "2026-05-04", + "invoice": "IV-8073-1-0", + "po": "PO1", + "status": "posted", + "units": 21 + }, + "book-IV-8653-0-0": { + "amount_cents": 1303, + "due": "2026-05-04", + "invoice": "IV-8653-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "book-IV-8722-3-0": { + "amount_cents": 197532, + "due": "2026-05-04", + "invoice": "IV-8722-3-0", + "po": "PO3", + "status": "posted", + "units": 18 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 3 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 7 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 2 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 4 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 4 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 5 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-05-02", + "po": "PO0", + "state": "accepted", + "units": 27 + }, + "GI-0-1": { + "date": "2026-05-01", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-0-2": { + "date": "2026-04-13", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-0-3": { + "date": "2026-04-29", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-1-0": { + "date": "2026-05-02", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-1-1": { + "date": "2026-04-25", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-1-2": { + "date": "2026-04-13", + "po": "PO1", + "state": "accepted", + "units": 28 + }, + "GI-1-3": { + "date": "2026-04-13", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-2-0": { + "date": "2026-05-02", + "po": "PO2", + "state": "accepted", + "units": 17 + }, + "GI-2-1": { + "date": "2026-05-04", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-2-2": { + "date": "2026-04-21", + "po": "PO2", + "state": "accepted", + "units": 16 + }, + "GI-2-3": { + "date": "2026-04-18", + "po": "PO2", + "state": "accepted", + "units": 18 + }, + "GI-3-0": { + "date": "2026-05-02", + "po": "PO3", + "state": "accepted", + "units": 13 + }, + "GI-3-1": { + "date": "2026-04-14", + "po": "PO3", + "state": "accepted", + "units": 24 + }, + "GI-3-2": { + "date": "2026-05-04", + "po": "PO3", + "state": "quarantine", + "units": 18 + }, + "GI-3-3": { + "date": "2026-04-22", + "po": "PO3", + "state": "quarantine", + "units": 16 + }, + "GI-4-0": { + "date": "2026-05-02", + "po": "PO4", + "state": "accepted", + "units": 25 + }, + "GI-4-1": { + "date": "2026-05-07", + "po": "PO4", + "state": "quarantine", + "units": 12 + }, + "GI-4-2": { + "date": "2026-04-12", + "po": "PO4", + "state": "quarantine", + "units": 27 + }, + "GI-4-3": { + "date": "2026-04-25", + "po": "PO4", + "state": "accepted", + "units": 24 + }, + "GI-5-0": { + "date": "2026-05-02", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-1": { + "date": "2026-04-29", + "po": "PO5", + "state": "quarantine", + "units": 14 + }, + "GI-5-2": { + "date": "2026-04-11", + "po": "PO5", + "state": "quarantine", + "units": 13 + }, + "GI-5-3": { + "date": "2026-05-04", + "po": "PO5", + "state": "accepted", + "units": 28 + }, + "GI-6-0": { + "date": "2026-05-02", + "po": "PO6", + "state": "accepted", + "units": 24 + }, + "GI-6-1": { + "date": "2026-04-12", + "po": "PO6", + "state": "accepted", + "units": 18 + }, + "GI-6-2": { + "date": "2026-05-03", + "po": "PO6", + "state": "accepted", + "units": 14 + }, + "GI-6-3": { + "date": "2026-04-11", + "po": "PO6", + "state": "accepted", + "units": 22 + } + }, + "invoice_inbox": { + "IV-1164-4-0": { + "date": "2026-04-12", + "po": "PO4", + "state": "posted", + "unit_price_cents": 15618, + "units": 3, + "vendor": "V1" + }, + "IV-2376-5-0": { + "date": "2026-04-12", + "po": "PO5", + "state": "posted", + "unit_price_cents": 15480, + "units": 23, + "vendor": "V1" + }, + "IV-2431-5-1": { + "date": "2026-04-26", + "po": "PO5", + "state": "void", + "unit_price_cents": 15581, + "units": 25, + "vendor": "V1" + }, + "IV-2518-0-3": { + "date": "2026-04-18", + "po": "PO0", + "state": "void", + "unit_price_cents": 963, + "units": 21, + "vendor": "V4" + }, + "IV-2888-3-1": { + "date": "2026-04-16", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 12471, + "units": 7, + "vendor": "V1" + }, + "IV-2891-2-0": { + "date": "2026-04-12", + "po": "PO2", + "state": "posted", + "unit_price_cents": 7385, + "units": 7, + "vendor": "V0" + }, + "IV-2920-5-2": { + "date": "2026-05-03", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 17548, + "units": 14, + "vendor": "V1" + }, + "IV-3756-5-3": { + "date": "2026-05-01", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 15739, + "units": 3, + "vendor": "V1" + }, + "IV-4110-3-2": { + "date": "2026-04-22", + "po": "PO3", + "state": "void", + "unit_price_cents": 11509, + "units": 18, + "vendor": "V1" + }, + "IV-5169-0-2": { + "date": "2026-05-01", + "po": "PO0", + "state": "void", + "unit_price_cents": 3014, + "units": 23, + "vendor": "V4" + }, + "IV-5531-6-0": { + "date": "2026-04-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 15416, + "units": 17, + "vendor": "V3" + }, + "IV-6035-4-1": { + "date": "2026-04-10", + "po": "PO4", + "state": "review", + "unit_price_cents": 17478, + "units": 11, + "vendor": "V1" + }, + "IV-6750-2-1": { + "date": "2026-05-04", + "po": "PO2", + "state": "review", + "unit_price_cents": 9117, + "units": 3, + "vendor": "V0" + }, + "IV-7778-0-1": { + "date": "2026-04-09", + "po": "PO0", + "state": "void", + "unit_price_cents": 2982, + "units": 22, + "vendor": "V4" + }, + "IV-7862-4-2": { + "date": "2026-04-13", + "po": "PO4", + "state": "posted", + "unit_price_cents": 16207, + "units": 5, + "vendor": "V1" + }, + "IV-8073-1-0": { + "date": "2026-04-12", + "po": "PO1", + "state": "posted", + "unit_price_cents": 21692, + "units": 21, + "vendor": "V4" + }, + "IV-8527-6-1": { + "date": "2026-04-08", + "po": "PO6", + "state": "review", + "unit_price_cents": 15539, + "units": 20, + "vendor": "Unknown" + }, + "IV-8653-0-0": { + "date": "2026-04-12", + "po": "PO0", + "state": "posted", + "unit_price_cents": 1303, + "units": 1, + "vendor": "V4" + }, + "IV-8722-3-0": { + "date": "2026-04-12", + "po": "PO3", + "state": "posted", + "unit_price_cents": 10974, + "units": 18, + "vendor": "V1" + }, + "IV-8771-2-2": { + "date": "2026-04-19", + "po": "PO2", + "state": "void", + "unit_price_cents": 9117, + "units": 13, + "vendor": "V0" + }, + "IV-9566-1-1": { + "date": "2026-04-09", + "po": "PO1", + "state": "review", + "unit_price_cents": 23455, + "units": 8, + "vendor": "V4" + }, + "IV-9610-1-2": { + "date": "2026-04-13", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 22993, + "units": 6, + "vendor": "V4" + } + }, + "purchase_orders": { + "PO0": { + "unit": "North", + "unit_price_cents": 1303, + "vendor": "V4" + }, + "PO1": { + "unit": "North", + "unit_price_cents": 21692, + "vendor": "V4" + }, + "PO2": { + "unit": "North", + "unit_price_cents": 7385, + "vendor": "V0" + }, + "PO3": { + "unit": "North", + "unit_price_cents": 10974, + "vendor": "V1" + }, + "PO4": { + "unit": "North", + "unit_price_cents": 15618, + "vendor": "V1" + }, + "PO5": { + "unit": "North", + "unit_price_cents": 15480, + "vendor": "V1" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 15416, + "vendor": "V3" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-2888-3-1": { + "invoice": "IV-2888-3-1", + "issues": [ + "price" + ], + "po": "PO3" + }, + "case-IV-2920-5-2": { + "invoice": "IV-2920-5-2", + "issues": [ + "price", + "units" + ], + "po": "PO5" + }, + "case-IV-3756-5-3": { + "invoice": "IV-3756-5-3", + "issues": [ + "units" + ], + "po": "PO5" + }, + "case-IV-9610-1-2": { + "invoice": "IV-9610-1-2", + "issues": [ + "price" + ], + "po": "PO1" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 21 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-020/tests/test.sh b/tasks/autom-supplier-invoice-match-020/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-020/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-020/tests/world.json b/tasks/autom-supplier-invoice-match-020/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..b0214ff19a0e832f80478a4d997988306275f0f3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-020/tests/world.json @@ -0,0 +1,446 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 3 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 7 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 2 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 4 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 4 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 5 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-05-02", + "po": "PO0", + "state": "accepted", + "units": 27 + }, + "GI-0-1": { + "date": "2026-05-01", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-0-2": { + "date": "2026-04-13", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-0-3": { + "date": "2026-04-29", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-1-0": { + "date": "2026-05-02", + "po": "PO1", + "state": "accepted", + "units": 22 + }, + "GI-1-1": { + "date": "2026-04-25", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-1-2": { + "date": "2026-04-13", + "po": "PO1", + "state": "accepted", + "units": 28 + }, + "GI-1-3": { + "date": "2026-04-13", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-2-0": { + "date": "2026-05-02", + "po": "PO2", + "state": "accepted", + "units": 17 + }, + "GI-2-1": { + "date": "2026-05-04", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-2-2": { + "date": "2026-04-21", + "po": "PO2", + "state": "accepted", + "units": 16 + }, + "GI-2-3": { + "date": "2026-04-18", + "po": "PO2", + "state": "accepted", + "units": 18 + }, + "GI-3-0": { + "date": "2026-05-02", + "po": "PO3", + "state": "accepted", + "units": 13 + }, + "GI-3-1": { + "date": "2026-04-14", + "po": "PO3", + "state": "accepted", + "units": 24 + }, + "GI-3-2": { + "date": "2026-05-04", + "po": "PO3", + "state": "quarantine", + "units": 18 + }, + "GI-3-3": { + "date": "2026-04-22", + "po": "PO3", + "state": "quarantine", + "units": 16 + }, + "GI-4-0": { + "date": "2026-05-02", + "po": "PO4", + "state": "accepted", + "units": 25 + }, + "GI-4-1": { + "date": "2026-05-07", + "po": "PO4", + "state": "quarantine", + "units": 12 + }, + "GI-4-2": { + "date": "2026-04-12", + "po": "PO4", + "state": "quarantine", + "units": 27 + }, + "GI-4-3": { + "date": "2026-04-25", + "po": "PO4", + "state": "accepted", + "units": 24 + }, + "GI-5-0": { + "date": "2026-05-02", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-1": { + "date": "2026-04-29", + "po": "PO5", + "state": "quarantine", + "units": 14 + }, + "GI-5-2": { + "date": "2026-04-11", + "po": "PO5", + "state": "quarantine", + "units": 13 + }, + "GI-5-3": { + "date": "2026-05-04", + "po": "PO5", + "state": "accepted", + "units": 28 + }, + "GI-6-0": { + "date": "2026-05-02", + "po": "PO6", + "state": "accepted", + "units": 24 + }, + "GI-6-1": { + "date": "2026-04-12", + "po": "PO6", + "state": "accepted", + "units": 18 + }, + "GI-6-2": { + "date": "2026-05-03", + "po": "PO6", + "state": "accepted", + "units": 14 + }, + "GI-6-3": { + "date": "2026-04-11", + "po": "PO6", + "state": "accepted", + "units": 22 + } + }, + "invoice_inbox": { + "IV-1164-4-0": { + "date": "2026-04-12", + "po": "PO4", + "state": "review", + "unit_price_cents": 15618, + "units": 3, + "vendor": "V1" + }, + "IV-2376-5-0": { + "date": "2026-04-12", + "po": "PO5", + "state": "review", + "unit_price_cents": 15480, + "units": 23, + "vendor": "V1" + }, + "IV-2431-5-1": { + "date": "2026-04-26", + "po": "PO5", + "state": "void", + "unit_price_cents": 15581, + "units": 25, + "vendor": "V1" + }, + "IV-2518-0-3": { + "date": "2026-04-18", + "po": "PO0", + "state": "void", + "unit_price_cents": 963, + "units": 21, + "vendor": "V4" + }, + "IV-2888-3-1": { + "date": "2026-04-16", + "po": "PO3", + "state": "review", + "unit_price_cents": 12471, + "units": 7, + "vendor": "V1" + }, + "IV-2891-2-0": { + "date": "2026-04-12", + "po": "PO2", + "state": "review", + "unit_price_cents": 7385, + "units": 7, + "vendor": "V0" + }, + "IV-2920-5-2": { + "date": "2026-05-03", + "po": "PO5", + "state": "review", + "unit_price_cents": 17548, + "units": 14, + "vendor": "V1" + }, + "IV-3756-5-3": { + "date": "2026-05-01", + "po": "PO5", + "state": "review", + "unit_price_cents": 15739, + "units": 3, + "vendor": "V1" + }, + "IV-4110-3-2": { + "date": "2026-04-22", + "po": "PO3", + "state": "void", + "unit_price_cents": 11509, + "units": 18, + "vendor": "V1" + }, + "IV-5169-0-2": { + "date": "2026-05-01", + "po": "PO0", + "state": "void", + "unit_price_cents": 3014, + "units": 23, + "vendor": "V4" + }, + "IV-5531-6-0": { + "date": "2026-04-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 15416, + "units": 17, + "vendor": "V3" + }, + "IV-6035-4-1": { + "date": "2026-04-10", + "po": "PO4", + "state": "review", + "unit_price_cents": 17478, + "units": 11, + "vendor": "V1" + }, + "IV-6750-2-1": { + "date": "2026-05-04", + "po": "PO2", + "state": "review", + "unit_price_cents": 9117, + "units": 3, + "vendor": "V0" + }, + "IV-7778-0-1": { + "date": "2026-04-09", + "po": "PO0", + "state": "void", + "unit_price_cents": 2982, + "units": 22, + "vendor": "V4" + }, + "IV-7862-4-2": { + "date": "2026-04-13", + "po": "PO4", + "state": "review", + "unit_price_cents": 16207, + "units": 5, + "vendor": "V1" + }, + "IV-8073-1-0": { + "date": "2026-04-12", + "po": "PO1", + "state": "review", + "unit_price_cents": 21692, + "units": 21, + "vendor": "V4" + }, + "IV-8527-6-1": { + "date": "2026-04-08", + "po": "PO6", + "state": "review", + "unit_price_cents": 15539, + "units": 20, + "vendor": "Unknown" + }, + "IV-8653-0-0": { + "date": "2026-04-12", + "po": "PO0", + "state": "review", + "unit_price_cents": 1303, + "units": 1, + "vendor": "V4" + }, + "IV-8722-3-0": { + "date": "2026-04-12", + "po": "PO3", + "state": "review", + "unit_price_cents": 10974, + "units": 18, + "vendor": "V1" + }, + "IV-8771-2-2": { + "date": "2026-04-19", + "po": "PO2", + "state": "void", + "unit_price_cents": 9117, + "units": 13, + "vendor": "V0" + }, + "IV-9566-1-1": { + "date": "2026-04-09", + "po": "PO1", + "state": "review", + "unit_price_cents": 23455, + "units": 8, + "vendor": "V4" + }, + "IV-9610-1-2": { + "date": "2026-04-13", + "po": "PO1", + "state": "review", + "unit_price_cents": 22993, + "units": 6, + "vendor": "V4" + } + }, + "purchase_orders": { + "PO0": { + "unit": "North", + "unit_price_cents": 1303, + "vendor": "V4" + }, + "PO1": { + "unit": "North", + "unit_price_cents": 21692, + "vendor": "V4" + }, + "PO2": { + "unit": "North", + "unit_price_cents": 7385, + "vendor": "V0" + }, + "PO3": { + "unit": "North", + "unit_price_cents": 10974, + "vendor": "V1" + }, + "PO4": { + "unit": "North", + "unit_price_cents": 15618, + "vendor": "V1" + }, + "PO5": { + "unit": "North", + "unit_price_cents": 15480, + "vendor": "V1" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 15416, + "vendor": "V3" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 21 + }, + "V2": { + "net_days": 15 + }, + "V3": { + "net_days": 30 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-020/tests/world_check.py b/tasks/autom-supplier-invoice-match-020/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-020/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-020/validation/openenv.json b/tasks/autom-supplier-invoice-match-020/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-020/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-021/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-021/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-021/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-021/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-021/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..05f1b316ae4488505b9ec1781b72b5a999fe573e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-021/environment/inputs/world.json @@ -0,0 +1,470 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 5 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 4 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 7 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 1 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 3 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-05-25", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-0-1": { + "date": "2026-05-06", + "po": "PO0", + "state": "quarantine", + "units": 26 + }, + "GI-0-2": { + "date": "2026-05-14", + "po": "PO0", + "state": "quarantine", + "units": 28 + }, + "GI-0-3": { + "date": "2026-05-15", + "po": "PO0", + "state": "accepted", + "units": 15 + }, + "GI-1-0": { + "date": "2026-05-25", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-1-1": { + "date": "2026-05-19", + "po": "PO1", + "state": "accepted", + "units": 20 + }, + "GI-1-2": { + "date": "2026-05-29", + "po": "PO1", + "state": "accepted", + "units": 17 + }, + "GI-1-3": { + "date": "2026-05-03", + "po": "PO1", + "state": "accepted", + "units": 28 + }, + "GI-2-0": { + "date": "2026-05-25", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-2-1": { + "date": "2026-05-10", + "po": "PO2", + "state": "accepted", + "units": 15 + }, + "GI-2-2": { + "date": "2026-05-28", + "po": "PO2", + "state": "accepted", + "units": 20 + }, + "GI-2-3": { + "date": "2026-05-22", + "po": "PO2", + "state": "accepted", + "units": 28 + }, + "GI-3-0": { + "date": "2026-05-25", + "po": "PO3", + "state": "accepted", + "units": 24 + }, + "GI-3-1": { + "date": "2026-05-29", + "po": "PO3", + "state": "accepted", + "units": 15 + }, + "GI-3-2": { + "date": "2026-05-11", + "po": "PO3", + "state": "accepted", + "units": 27 + }, + "GI-3-3": { + "date": "2026-05-17", + "po": "PO3", + "state": "quarantine", + "units": 27 + }, + "GI-4-0": { + "date": "2026-05-25", + "po": "PO4", + "state": "accepted", + "units": 26 + }, + "GI-4-1": { + "date": "2026-05-16", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-4-2": { + "date": "2026-05-10", + "po": "PO4", + "state": "accepted", + "units": 18 + }, + "GI-4-3": { + "date": "2026-05-03", + "po": "PO4", + "state": "quarantine", + "units": 26 + }, + "GI-5-0": { + "date": "2026-05-25", + "po": "PO5", + "state": "accepted", + "units": 12 + }, + "GI-5-1": { + "date": "2026-05-11", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-5-2": { + "date": "2026-05-22", + "po": "PO5", + "state": "quarantine", + "units": 14 + }, + "GI-5-3": { + "date": "2026-05-26", + "po": "PO5", + "state": "accepted", + "units": 23 + }, + "GI-6-0": { + "date": "2026-05-25", + "po": "PO6", + "state": "accepted", + "units": 19 + }, + "GI-6-1": { + "date": "2026-05-31", + "po": "PO6", + "state": "accepted", + "units": 24 + }, + "GI-6-2": { + "date": "2026-05-30", + "po": "PO6", + "state": "accepted", + "units": 22 + }, + "GI-6-3": { + "date": "2026-05-24", + "po": "PO6", + "state": "quarantine", + "units": 18 + } + }, + "invoice_inbox": { + "IV-1295-5-1": { + "date": "2026-05-06", + "po": "PO5", + "state": "void", + "unit_price_cents": 15606, + "units": 23, + "vendor": "V3" + }, + "IV-1666-3-3": { + "date": "2026-05-11", + "po": "PO3", + "state": "review", + "unit_price_cents": 20391, + "units": 20, + "vendor": "V1" + }, + "IV-1688-1-3": { + "date": "2026-05-10", + "po": "PO1", + "state": "review", + "unit_price_cents": 9213, + "units": 16, + "vendor": "V4" + }, + "IV-2637-2-1": { + "date": "2026-05-08", + "po": "PO2", + "state": "review", + "unit_price_cents": 6714, + "units": 12, + "vendor": "V4" + }, + "IV-2744-4-3": { + "date": "2026-05-16", + "po": "PO4", + "state": "review", + "unit_price_cents": 9897, + "units": 7, + "vendor": "V1" + }, + "IV-2946-4-1": { + "date": "2026-05-09", + "po": "PO4", + "state": "review", + "unit_price_cents": 9406, + "units": 18, + "vendor": "V1" + }, + "IV-2957-6-1": { + "date": "2026-05-15", + "po": "PO6", + "state": "review", + "unit_price_cents": 11293, + "units": 11, + "vendor": "V0" + }, + "IV-3666-0-0": { + "date": "2026-05-12", + "po": "PO0", + "state": "review", + "unit_price_cents": 3548, + "units": 1, + "vendor": "V0" + }, + "IV-3872-0-3": { + "date": "2026-05-20", + "po": "PO0", + "state": "review", + "unit_price_cents": 3585, + "units": 24, + "vendor": "V0" + }, + "IV-3962-2-3": { + "date": "2026-05-17", + "po": "PO2", + "state": "review", + "unit_price_cents": 6698, + "units": 4, + "vendor": "V4" + }, + "IV-4393-4-0": { + "date": "2026-05-12", + "po": "PO4", + "state": "review", + "unit_price_cents": 9210, + "units": 24, + "vendor": "V1" + }, + "IV-4474-1-0": { + "date": "2026-05-12", + "po": "PO1", + "state": "review", + "unit_price_cents": 9005, + "units": 9, + "vendor": "V4" + }, + "IV-4699-2-0": { + "date": "2026-05-12", + "po": "PO2", + "state": "review", + "unit_price_cents": 6407, + "units": 25, + "vendor": "V4" + }, + "IV-4796-4-2": { + "date": "2026-05-11", + "po": "PO4", + "state": "review", + "unit_price_cents": 10593, + "units": 6, + "vendor": "Unknown" + }, + "IV-5048-3-1": { + "date": "2026-05-24", + "po": "PO3", + "state": "void", + "unit_price_cents": 19930, + "units": 3, + "vendor": "V1" + }, + "IV-6085-1-2": { + "date": "2026-05-09", + "po": "PO1", + "state": "review", + "unit_price_cents": 8670, + "units": 17, + "vendor": "V4" + }, + "IV-6544-3-2": { + "date": "2026-05-10", + "po": "PO3", + "state": "review", + "unit_price_cents": 21509, + "units": 13, + "vendor": "V1" + }, + "IV-6607-0-2": { + "date": "2026-05-06", + "po": "PO0", + "state": "review", + "unit_price_cents": 4699, + "units": 21, + "vendor": "V0" + }, + "IV-7265-1-1": { + "date": "2026-05-25", + "po": "PO1", + "state": "review", + "unit_price_cents": 8829, + "units": 9, + "vendor": "V4" + }, + "IV-7488-3-0": { + "date": "2026-05-12", + "po": "PO3", + "state": "review", + "unit_price_cents": 20188, + "units": 9, + "vendor": "V1" + }, + "IV-7904-0-1": { + "date": "2026-05-14", + "po": "PO0", + "state": "review", + "unit_price_cents": 5093, + "units": 13, + "vendor": "Unknown" + }, + "IV-8789-2-2": { + "date": "2026-05-08", + "po": "PO2", + "state": "review", + "unit_price_cents": 8452, + "units": 4, + "vendor": "V4" + }, + "IV-9604-5-0": { + "date": "2026-05-12", + "po": "PO5", + "state": "review", + "unit_price_cents": 15185, + "units": 11, + "vendor": "V3" + }, + "IV-9671-6-0": { + "date": "2026-05-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 11561, + "units": 14, + "vendor": "V0" + }, + "IV-9826-5-2": { + "date": "2026-05-13", + "po": "PO5", + "state": "review", + "unit_price_cents": 16200, + "units": 17, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 3548, + "vendor": "V0" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 9005, + "vendor": "V4" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 6407, + "vendor": "V4" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 20188, + "vendor": "V1" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 9210, + "vendor": "V1" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 15185, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 11561, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 15 + }, + "V4": { + "net_days": 45 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-021/instruction.md b/tasks/autom-supplier-invoice-match-021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0e4b0e169aab238c52002414f2f48cf0c8869315 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-021/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit South at 2026-05-26. Handle invoices in review attached to that unit's purchase orders, invoice dates 2026-05-12 through 2026-05-26 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 200 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-021/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-021/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4da59a73a8a2a61bd7aee36b6f09beaa55e3ee55 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-021/solution/files/actions.jsonl @@ -0,0 +1,24 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-3666-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7904-0-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-3872-0-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-4474-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-7265-1-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-4699-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3962-2-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-7488-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-4393-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-2744-4-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-9604-5-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-9826-5-2", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 3548, "due": "2026-06-11", "invoice": "IV-3666-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-3666-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 221040, "due": "2026-05-27", "invoice": "IV-4393-4-0", "po": "PO4", "status": "posted", "units": 24}, "id": "book-IV-4393-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 81045, "due": "2026-06-26", "invoice": "IV-4474-1-0", "po": "PO1", "status": "posted", "units": 9}, "id": "book-IV-4474-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 160175, "due": "2026-06-26", "invoice": "IV-4699-2-0", "po": "PO2", "status": "posted", "units": 25}, "id": "book-IV-4699-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 181692, "due": "2026-05-27", "invoice": "IV-7488-3-0", "po": "PO3", "status": "posted", "units": 9}, "id": "book-IV-7488-3-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 167035, "due": "2026-05-27", "invoice": "IV-9604-5-0", "po": "PO5", "status": "posted", "units": 11}, "id": "book-IV-9604-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 86040, "due": "2026-06-19", "invoice": "IV-3872-0-3", "po": "PO0", "status": "posted", "units": 24}, "id": "book-IV-3872-0-3", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 79461, "due": "2026-07-09", "invoice": "IV-7265-1-1", "po": "PO1", "status": "posted", "units": 9}, "id": "book-IV-7265-1-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-9826-5-2", "issues": ["price"], "po": "PO5"}, "id": "case-IV-9826-5-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7904-0-1", "issues": ["vendor", "price"], "po": "PO0"}, "id": "case-IV-7904-0-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-2744-4-3", "issues": ["price"], "po": "PO4"}, "id": "case-IV-2744-4-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3962-2-3", "issues": ["price"], "po": "PO2"}, "id": "case-IV-3962-2-3", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-021/solution/solve.sh b/tasks/autom-supplier-invoice-match-021/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-021/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-021/task.toml b/tasks/autom-supplier-invoice-match-021/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8f963e4ad67c7447234638b73d7b22286d092555 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-021/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-021" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 21 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-021" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-021/tests/expected.json b/tasks/autom-supplier-invoice-match-021/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-021/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-021/tests/grade.py b/tasks/autom-supplier-invoice-match-021/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-021/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-021/tests/replay.py b/tasks/autom-supplier-invoice-match-021/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-021/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-021/tests/target.json b/tasks/autom-supplier-invoice-match-021/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..7548da375c393acd7076ef3695bb1650bace5917 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-021/tests/target.json @@ -0,0 +1,563 @@ +{ + "ap_postings": { + "book-IV-3666-0-0": { + "amount_cents": 3548, + "due": "2026-06-11", + "invoice": "IV-3666-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "book-IV-3872-0-3": { + "amount_cents": 86040, + "due": "2026-06-19", + "invoice": "IV-3872-0-3", + "po": "PO0", + "status": "posted", + "units": 24 + }, + "book-IV-4393-4-0": { + "amount_cents": 221040, + "due": "2026-05-27", + "invoice": "IV-4393-4-0", + "po": "PO4", + "status": "posted", + "units": 24 + }, + "book-IV-4474-1-0": { + "amount_cents": 81045, + "due": "2026-06-26", + "invoice": "IV-4474-1-0", + "po": "PO1", + "status": "posted", + "units": 9 + }, + "book-IV-4699-2-0": { + "amount_cents": 160175, + "due": "2026-06-26", + "invoice": "IV-4699-2-0", + "po": "PO2", + "status": "posted", + "units": 25 + }, + "book-IV-7265-1-1": { + "amount_cents": 79461, + "due": "2026-07-09", + "invoice": "IV-7265-1-1", + "po": "PO1", + "status": "posted", + "units": 9 + }, + "book-IV-7488-3-0": { + "amount_cents": 181692, + "due": "2026-05-27", + "invoice": "IV-7488-3-0", + "po": "PO3", + "status": "posted", + "units": 9 + }, + "book-IV-9604-5-0": { + "amount_cents": 167035, + "due": "2026-05-27", + "invoice": "IV-9604-5-0", + "po": "PO5", + "status": "posted", + "units": 11 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 5 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 4 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 7 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 1 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 3 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-05-25", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-0-1": { + "date": "2026-05-06", + "po": "PO0", + "state": "quarantine", + "units": 26 + }, + "GI-0-2": { + "date": "2026-05-14", + "po": "PO0", + "state": "quarantine", + "units": 28 + }, + "GI-0-3": { + "date": "2026-05-15", + "po": "PO0", + "state": "accepted", + "units": 15 + }, + "GI-1-0": { + "date": "2026-05-25", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-1-1": { + "date": "2026-05-19", + "po": "PO1", + "state": "accepted", + "units": 20 + }, + "GI-1-2": { + "date": "2026-05-29", + "po": "PO1", + "state": "accepted", + "units": 17 + }, + "GI-1-3": { + "date": "2026-05-03", + "po": "PO1", + "state": "accepted", + "units": 28 + }, + "GI-2-0": { + "date": "2026-05-25", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-2-1": { + "date": "2026-05-10", + "po": "PO2", + "state": "accepted", + "units": 15 + }, + "GI-2-2": { + "date": "2026-05-28", + "po": "PO2", + "state": "accepted", + "units": 20 + }, + "GI-2-3": { + "date": "2026-05-22", + "po": "PO2", + "state": "accepted", + "units": 28 + }, + "GI-3-0": { + "date": "2026-05-25", + "po": "PO3", + "state": "accepted", + "units": 24 + }, + "GI-3-1": { + "date": "2026-05-29", + "po": "PO3", + "state": "accepted", + "units": 15 + }, + "GI-3-2": { + "date": "2026-05-11", + "po": "PO3", + "state": "accepted", + "units": 27 + }, + "GI-3-3": { + "date": "2026-05-17", + "po": "PO3", + "state": "quarantine", + "units": 27 + }, + "GI-4-0": { + "date": "2026-05-25", + "po": "PO4", + "state": "accepted", + "units": 26 + }, + "GI-4-1": { + "date": "2026-05-16", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-4-2": { + "date": "2026-05-10", + "po": "PO4", + "state": "accepted", + "units": 18 + }, + "GI-4-3": { + "date": "2026-05-03", + "po": "PO4", + "state": "quarantine", + "units": 26 + }, + "GI-5-0": { + "date": "2026-05-25", + "po": "PO5", + "state": "accepted", + "units": 12 + }, + "GI-5-1": { + "date": "2026-05-11", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-5-2": { + "date": "2026-05-22", + "po": "PO5", + "state": "quarantine", + "units": 14 + }, + "GI-5-3": { + "date": "2026-05-26", + "po": "PO5", + "state": "accepted", + "units": 23 + }, + "GI-6-0": { + "date": "2026-05-25", + "po": "PO6", + "state": "accepted", + "units": 19 + }, + "GI-6-1": { + "date": "2026-05-31", + "po": "PO6", + "state": "accepted", + "units": 24 + }, + "GI-6-2": { + "date": "2026-05-30", + "po": "PO6", + "state": "accepted", + "units": 22 + }, + "GI-6-3": { + "date": "2026-05-24", + "po": "PO6", + "state": "quarantine", + "units": 18 + } + }, + "invoice_inbox": { + "IV-1295-5-1": { + "date": "2026-05-06", + "po": "PO5", + "state": "void", + "unit_price_cents": 15606, + "units": 23, + "vendor": "V3" + }, + "IV-1666-3-3": { + "date": "2026-05-11", + "po": "PO3", + "state": "review", + "unit_price_cents": 20391, + "units": 20, + "vendor": "V1" + }, + "IV-1688-1-3": { + "date": "2026-05-10", + "po": "PO1", + "state": "review", + "unit_price_cents": 9213, + "units": 16, + "vendor": "V4" + }, + "IV-2637-2-1": { + "date": "2026-05-08", + "po": "PO2", + "state": "review", + "unit_price_cents": 6714, + "units": 12, + "vendor": "V4" + }, + "IV-2744-4-3": { + "date": "2026-05-16", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 9897, + "units": 7, + "vendor": "V1" + }, + "IV-2946-4-1": { + "date": "2026-05-09", + "po": "PO4", + "state": "review", + "unit_price_cents": 9406, + "units": 18, + "vendor": "V1" + }, + "IV-2957-6-1": { + "date": "2026-05-15", + "po": "PO6", + "state": "review", + "unit_price_cents": 11293, + "units": 11, + "vendor": "V0" + }, + "IV-3666-0-0": { + "date": "2026-05-12", + "po": "PO0", + "state": "posted", + "unit_price_cents": 3548, + "units": 1, + "vendor": "V0" + }, + "IV-3872-0-3": { + "date": "2026-05-20", + "po": "PO0", + "state": "posted", + "unit_price_cents": 3585, + "units": 24, + "vendor": "V0" + }, + "IV-3962-2-3": { + "date": "2026-05-17", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 6698, + "units": 4, + "vendor": "V4" + }, + "IV-4393-4-0": { + "date": "2026-05-12", + "po": "PO4", + "state": "posted", + "unit_price_cents": 9210, + "units": 24, + "vendor": "V1" + }, + "IV-4474-1-0": { + "date": "2026-05-12", + "po": "PO1", + "state": "posted", + "unit_price_cents": 9005, + "units": 9, + "vendor": "V4" + }, + "IV-4699-2-0": { + "date": "2026-05-12", + "po": "PO2", + "state": "posted", + "unit_price_cents": 6407, + "units": 25, + "vendor": "V4" + }, + "IV-4796-4-2": { + "date": "2026-05-11", + "po": "PO4", + "state": "review", + "unit_price_cents": 10593, + "units": 6, + "vendor": "Unknown" + }, + "IV-5048-3-1": { + "date": "2026-05-24", + "po": "PO3", + "state": "void", + "unit_price_cents": 19930, + "units": 3, + "vendor": "V1" + }, + "IV-6085-1-2": { + "date": "2026-05-09", + "po": "PO1", + "state": "review", + "unit_price_cents": 8670, + "units": 17, + "vendor": "V4" + }, + "IV-6544-3-2": { + "date": "2026-05-10", + "po": "PO3", + "state": "review", + "unit_price_cents": 21509, + "units": 13, + "vendor": "V1" + }, + "IV-6607-0-2": { + "date": "2026-05-06", + "po": "PO0", + "state": "review", + "unit_price_cents": 4699, + "units": 21, + "vendor": "V0" + }, + "IV-7265-1-1": { + "date": "2026-05-25", + "po": "PO1", + "state": "posted", + "unit_price_cents": 8829, + "units": 9, + "vendor": "V4" + }, + "IV-7488-3-0": { + "date": "2026-05-12", + "po": "PO3", + "state": "posted", + "unit_price_cents": 20188, + "units": 9, + "vendor": "V1" + }, + "IV-7904-0-1": { + "date": "2026-05-14", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 5093, + "units": 13, + "vendor": "Unknown" + }, + "IV-8789-2-2": { + "date": "2026-05-08", + "po": "PO2", + "state": "review", + "unit_price_cents": 8452, + "units": 4, + "vendor": "V4" + }, + "IV-9604-5-0": { + "date": "2026-05-12", + "po": "PO5", + "state": "posted", + "unit_price_cents": 15185, + "units": 11, + "vendor": "V3" + }, + "IV-9671-6-0": { + "date": "2026-05-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 11561, + "units": 14, + "vendor": "V0" + }, + "IV-9826-5-2": { + "date": "2026-05-13", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 16200, + "units": 17, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 3548, + "vendor": "V0" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 9005, + "vendor": "V4" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 6407, + "vendor": "V4" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 20188, + "vendor": "V1" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 9210, + "vendor": "V1" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 15185, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 11561, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-2744-4-3": { + "invoice": "IV-2744-4-3", + "issues": [ + "price" + ], + "po": "PO4" + }, + "case-IV-3962-2-3": { + "invoice": "IV-3962-2-3", + "issues": [ + "price" + ], + "po": "PO2" + }, + "case-IV-7904-0-1": { + "invoice": "IV-7904-0-1", + "issues": [ + "vendor", + "price" + ], + "po": "PO0" + }, + "case-IV-9826-5-2": { + "invoice": "IV-9826-5-2", + "issues": [ + "price" + ], + "po": "PO5" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 15 + }, + "V4": { + "net_days": 45 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-021/tests/test.sh b/tasks/autom-supplier-invoice-match-021/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-021/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-021/tests/world.json b/tasks/autom-supplier-invoice-match-021/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..05f1b316ae4488505b9ec1781b72b5a999fe573e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-021/tests/world.json @@ -0,0 +1,470 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 5 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 4 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 7 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 7 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 1 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 3 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2026-05-25", + "po": "PO0", + "state": "accepted", + "units": 16 + }, + "GI-0-1": { + "date": "2026-05-06", + "po": "PO0", + "state": "quarantine", + "units": 26 + }, + "GI-0-2": { + "date": "2026-05-14", + "po": "PO0", + "state": "quarantine", + "units": 28 + }, + "GI-0-3": { + "date": "2026-05-15", + "po": "PO0", + "state": "accepted", + "units": 15 + }, + "GI-1-0": { + "date": "2026-05-25", + "po": "PO1", + "state": "accepted", + "units": 23 + }, + "GI-1-1": { + "date": "2026-05-19", + "po": "PO1", + "state": "accepted", + "units": 20 + }, + "GI-1-2": { + "date": "2026-05-29", + "po": "PO1", + "state": "accepted", + "units": 17 + }, + "GI-1-3": { + "date": "2026-05-03", + "po": "PO1", + "state": "accepted", + "units": 28 + }, + "GI-2-0": { + "date": "2026-05-25", + "po": "PO2", + "state": "accepted", + "units": 23 + }, + "GI-2-1": { + "date": "2026-05-10", + "po": "PO2", + "state": "accepted", + "units": 15 + }, + "GI-2-2": { + "date": "2026-05-28", + "po": "PO2", + "state": "accepted", + "units": 20 + }, + "GI-2-3": { + "date": "2026-05-22", + "po": "PO2", + "state": "accepted", + "units": 28 + }, + "GI-3-0": { + "date": "2026-05-25", + "po": "PO3", + "state": "accepted", + "units": 24 + }, + "GI-3-1": { + "date": "2026-05-29", + "po": "PO3", + "state": "accepted", + "units": 15 + }, + "GI-3-2": { + "date": "2026-05-11", + "po": "PO3", + "state": "accepted", + "units": 27 + }, + "GI-3-3": { + "date": "2026-05-17", + "po": "PO3", + "state": "quarantine", + "units": 27 + }, + "GI-4-0": { + "date": "2026-05-25", + "po": "PO4", + "state": "accepted", + "units": 26 + }, + "GI-4-1": { + "date": "2026-05-16", + "po": "PO4", + "state": "accepted", + "units": 21 + }, + "GI-4-2": { + "date": "2026-05-10", + "po": "PO4", + "state": "accepted", + "units": 18 + }, + "GI-4-3": { + "date": "2026-05-03", + "po": "PO4", + "state": "quarantine", + "units": 26 + }, + "GI-5-0": { + "date": "2026-05-25", + "po": "PO5", + "state": "accepted", + "units": 12 + }, + "GI-5-1": { + "date": "2026-05-11", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-5-2": { + "date": "2026-05-22", + "po": "PO5", + "state": "quarantine", + "units": 14 + }, + "GI-5-3": { + "date": "2026-05-26", + "po": "PO5", + "state": "accepted", + "units": 23 + }, + "GI-6-0": { + "date": "2026-05-25", + "po": "PO6", + "state": "accepted", + "units": 19 + }, + "GI-6-1": { + "date": "2026-05-31", + "po": "PO6", + "state": "accepted", + "units": 24 + }, + "GI-6-2": { + "date": "2026-05-30", + "po": "PO6", + "state": "accepted", + "units": 22 + }, + "GI-6-3": { + "date": "2026-05-24", + "po": "PO6", + "state": "quarantine", + "units": 18 + } + }, + "invoice_inbox": { + "IV-1295-5-1": { + "date": "2026-05-06", + "po": "PO5", + "state": "void", + "unit_price_cents": 15606, + "units": 23, + "vendor": "V3" + }, + "IV-1666-3-3": { + "date": "2026-05-11", + "po": "PO3", + "state": "review", + "unit_price_cents": 20391, + "units": 20, + "vendor": "V1" + }, + "IV-1688-1-3": { + "date": "2026-05-10", + "po": "PO1", + "state": "review", + "unit_price_cents": 9213, + "units": 16, + "vendor": "V4" + }, + "IV-2637-2-1": { + "date": "2026-05-08", + "po": "PO2", + "state": "review", + "unit_price_cents": 6714, + "units": 12, + "vendor": "V4" + }, + "IV-2744-4-3": { + "date": "2026-05-16", + "po": "PO4", + "state": "review", + "unit_price_cents": 9897, + "units": 7, + "vendor": "V1" + }, + "IV-2946-4-1": { + "date": "2026-05-09", + "po": "PO4", + "state": "review", + "unit_price_cents": 9406, + "units": 18, + "vendor": "V1" + }, + "IV-2957-6-1": { + "date": "2026-05-15", + "po": "PO6", + "state": "review", + "unit_price_cents": 11293, + "units": 11, + "vendor": "V0" + }, + "IV-3666-0-0": { + "date": "2026-05-12", + "po": "PO0", + "state": "review", + "unit_price_cents": 3548, + "units": 1, + "vendor": "V0" + }, + "IV-3872-0-3": { + "date": "2026-05-20", + "po": "PO0", + "state": "review", + "unit_price_cents": 3585, + "units": 24, + "vendor": "V0" + }, + "IV-3962-2-3": { + "date": "2026-05-17", + "po": "PO2", + "state": "review", + "unit_price_cents": 6698, + "units": 4, + "vendor": "V4" + }, + "IV-4393-4-0": { + "date": "2026-05-12", + "po": "PO4", + "state": "review", + "unit_price_cents": 9210, + "units": 24, + "vendor": "V1" + }, + "IV-4474-1-0": { + "date": "2026-05-12", + "po": "PO1", + "state": "review", + "unit_price_cents": 9005, + "units": 9, + "vendor": "V4" + }, + "IV-4699-2-0": { + "date": "2026-05-12", + "po": "PO2", + "state": "review", + "unit_price_cents": 6407, + "units": 25, + "vendor": "V4" + }, + "IV-4796-4-2": { + "date": "2026-05-11", + "po": "PO4", + "state": "review", + "unit_price_cents": 10593, + "units": 6, + "vendor": "Unknown" + }, + "IV-5048-3-1": { + "date": "2026-05-24", + "po": "PO3", + "state": "void", + "unit_price_cents": 19930, + "units": 3, + "vendor": "V1" + }, + "IV-6085-1-2": { + "date": "2026-05-09", + "po": "PO1", + "state": "review", + "unit_price_cents": 8670, + "units": 17, + "vendor": "V4" + }, + "IV-6544-3-2": { + "date": "2026-05-10", + "po": "PO3", + "state": "review", + "unit_price_cents": 21509, + "units": 13, + "vendor": "V1" + }, + "IV-6607-0-2": { + "date": "2026-05-06", + "po": "PO0", + "state": "review", + "unit_price_cents": 4699, + "units": 21, + "vendor": "V0" + }, + "IV-7265-1-1": { + "date": "2026-05-25", + "po": "PO1", + "state": "review", + "unit_price_cents": 8829, + "units": 9, + "vendor": "V4" + }, + "IV-7488-3-0": { + "date": "2026-05-12", + "po": "PO3", + "state": "review", + "unit_price_cents": 20188, + "units": 9, + "vendor": "V1" + }, + "IV-7904-0-1": { + "date": "2026-05-14", + "po": "PO0", + "state": "review", + "unit_price_cents": 5093, + "units": 13, + "vendor": "Unknown" + }, + "IV-8789-2-2": { + "date": "2026-05-08", + "po": "PO2", + "state": "review", + "unit_price_cents": 8452, + "units": 4, + "vendor": "V4" + }, + "IV-9604-5-0": { + "date": "2026-05-12", + "po": "PO5", + "state": "review", + "unit_price_cents": 15185, + "units": 11, + "vendor": "V3" + }, + "IV-9671-6-0": { + "date": "2026-05-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 11561, + "units": 14, + "vendor": "V0" + }, + "IV-9826-5-2": { + "date": "2026-05-13", + "po": "PO5", + "state": "review", + "unit_price_cents": 16200, + "units": 17, + "vendor": "V3" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 3548, + "vendor": "V0" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 9005, + "vendor": "V4" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 6407, + "vendor": "V4" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 20188, + "vendor": "V1" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 9210, + "vendor": "V1" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 15185, + "vendor": "V3" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 11561, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 15 + }, + "V4": { + "net_days": 45 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-021/tests/world_check.py b/tasks/autom-supplier-invoice-match-021/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-021/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-021/validation/openenv.json b/tasks/autom-supplier-invoice-match-021/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-021/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-022/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-022/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-022/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-022/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-022/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..bf51a1db7331524dc19274462bff49efeb17641b --- /dev/null +++ b/tasks/autom-supplier-invoice-match-022/environment/inputs/world.json @@ -0,0 +1,438 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 8 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 7 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 6 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 3 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 4 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 8 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 6 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-02-12", + "po": "PO0", + "state": "accepted", + "units": 23 + }, + "GI-0-1": { + "date": "2025-02-04", + "po": "PO0", + "state": "quarantine", + "units": 28 + }, + "GI-0-2": { + "date": "2025-02-13", + "po": "PO0", + "state": "accepted", + "units": 24 + }, + "GI-0-3": { + "date": "2025-02-18", + "po": "PO0", + "state": "quarantine", + "units": 26 + }, + "GI-1-0": { + "date": "2025-02-12", + "po": "PO1", + "state": "accepted", + "units": 20 + }, + "GI-1-1": { + "date": "2025-02-16", + "po": "PO1", + "state": "quarantine", + "units": 24 + }, + "GI-1-2": { + "date": "2025-02-06", + "po": "PO1", + "state": "quarantine", + "units": 24 + }, + "GI-1-3": { + "date": "2025-01-30", + "po": "PO1", + "state": "accepted", + "units": 14 + }, + "GI-2-0": { + "date": "2025-02-12", + "po": "PO2", + "state": "accepted", + "units": 14 + }, + "GI-2-1": { + "date": "2025-02-03", + "po": "PO2", + "state": "quarantine", + "units": 16 + }, + "GI-2-2": { + "date": "2025-02-04", + "po": "PO2", + "state": "quarantine", + "units": 14 + }, + "GI-2-3": { + "date": "2025-02-07", + "po": "PO2", + "state": "accepted", + "units": 15 + }, + "GI-3-0": { + "date": "2025-02-12", + "po": "PO3", + "state": "accepted", + "units": 12 + }, + "GI-3-1": { + "date": "2025-01-31", + "po": "PO3", + "state": "quarantine", + "units": 22 + }, + "GI-3-2": { + "date": "2025-02-06", + "po": "PO3", + "state": "quarantine", + "units": 23 + }, + "GI-3-3": { + "date": "2025-02-02", + "po": "PO3", + "state": "accepted", + "units": 25 + }, + "GI-4-0": { + "date": "2025-02-12", + "po": "PO4", + "state": "accepted", + "units": 23 + }, + "GI-4-1": { + "date": "2025-01-27", + "po": "PO4", + "state": "accepted", + "units": 17 + }, + "GI-4-2": { + "date": "2025-01-29", + "po": "PO4", + "state": "quarantine", + "units": 18 + }, + "GI-4-3": { + "date": "2025-02-15", + "po": "PO4", + "state": "quarantine", + "units": 21 + }, + "GI-5-0": { + "date": "2025-02-12", + "po": "PO5", + "state": "accepted", + "units": 12 + }, + "GI-5-1": { + "date": "2025-02-05", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-5-2": { + "date": "2025-02-02", + "po": "PO5", + "state": "accepted", + "units": 26 + }, + "GI-5-3": { + "date": "2025-02-17", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-6-0": { + "date": "2025-02-12", + "po": "PO6", + "state": "accepted", + "units": 25 + }, + "GI-6-1": { + "date": "2025-02-05", + "po": "PO6", + "state": "accepted", + "units": 20 + }, + "GI-6-2": { + "date": "2025-02-13", + "po": "PO6", + "state": "accepted", + "units": 18 + }, + "GI-6-3": { + "date": "2025-02-09", + "po": "PO6", + "state": "accepted", + "units": 28 + } + }, + "invoice_inbox": { + "IV-1803-3-2": { + "date": "2025-01-27", + "po": "PO3", + "state": "review", + "unit_price_cents": 13950, + "units": 23, + "vendor": "V3" + }, + "IV-1858-4-2": { + "date": "2025-02-03", + "po": "PO4", + "state": "review", + "unit_price_cents": 5048, + "units": 18, + "vendor": "V1" + }, + "IV-1952-4-1": { + "date": "2025-01-28", + "po": "PO4", + "state": "void", + "unit_price_cents": 4547, + "units": 3, + "vendor": "V1" + }, + "IV-2958-2-1": { + "date": "2025-02-13", + "po": "PO2", + "state": "void", + "unit_price_cents": 3336, + "units": 12, + "vendor": "V3" + }, + "IV-3488-0-1": { + "date": "2025-02-02", + "po": "PO0", + "state": "void", + "unit_price_cents": 15823, + "units": 3, + "vendor": "V3" + }, + "IV-4276-2-3": { + "date": "2025-01-23", + "po": "PO2", + "state": "review", + "unit_price_cents": 2736, + "units": 24, + "vendor": "V3" + }, + "IV-4302-6-0": { + "date": "2025-01-23", + "po": "PO6", + "state": "review", + "unit_price_cents": 12215, + "units": 7, + "vendor": "V0" + }, + "IV-4439-1-1": { + "date": "2025-01-25", + "po": "PO1", + "state": "review", + "unit_price_cents": 2614, + "units": 7, + "vendor": "Unknown" + }, + "IV-4616-6-2": { + "date": "2025-01-19", + "po": "PO6", + "state": "review", + "unit_price_cents": 14216, + "units": 12, + "vendor": "V0" + }, + "IV-4644-5-0": { + "date": "2025-01-23", + "po": "PO5", + "state": "review", + "unit_price_cents": 11303, + "units": 13, + "vendor": "V0" + }, + "IV-4676-2-2": { + "date": "2025-01-29", + "po": "PO2", + "state": "review", + "unit_price_cents": 3732, + "units": 5, + "vendor": "Unknown" + }, + "IV-5197-6-3": { + "date": "2025-01-25", + "po": "PO6", + "state": "review", + "unit_price_cents": 12655, + "units": 18, + "vendor": "V0" + }, + "IV-5258-3-1": { + "date": "2025-02-07", + "po": "PO3", + "state": "review", + "unit_price_cents": 15026, + "units": 5, + "vendor": "V3" + }, + "IV-5399-3-0": { + "date": "2025-01-23", + "po": "PO3", + "state": "review", + "unit_price_cents": 13582, + "units": 14, + "vendor": "V3" + }, + "IV-5461-2-0": { + "date": "2025-01-23", + "po": "PO2", + "state": "review", + "unit_price_cents": 3119, + "units": 11, + "vendor": "V3" + }, + "IV-5562-1-0": { + "date": "2025-01-23", + "po": "PO1", + "state": "review", + "unit_price_cents": 2510, + "units": 25, + "vendor": "V1" + }, + "IV-6266-4-0": { + "date": "2025-01-23", + "po": "PO4", + "state": "review", + "unit_price_cents": 3442, + "units": 5, + "vendor": "V1" + }, + "IV-7449-6-1": { + "date": "2025-01-31", + "po": "PO6", + "state": "review", + "unit_price_cents": 14150, + "units": 12, + "vendor": "V0" + }, + "IV-7544-5-1": { + "date": "2025-02-11", + "po": "PO5", + "state": "review", + "unit_price_cents": 12021, + "units": 5, + "vendor": "V0" + }, + "IV-9017-0-0": { + "date": "2025-01-23", + "po": "PO0", + "state": "review", + "unit_price_cents": 15807, + "units": 1, + "vendor": "V3" + }, + "IV-9728-0-2": { + "date": "2025-02-11", + "po": "PO0", + "state": "review", + "unit_price_cents": 16430, + "units": 11, + "vendor": "Unknown" + } + }, + "purchase_orders": { + "PO0": { + "unit": "Central", + "unit_price_cents": 15807, + "vendor": "V3" + }, + "PO1": { + "unit": "Central", + "unit_price_cents": 2510, + "vendor": "V1" + }, + "PO2": { + "unit": "Central", + "unit_price_cents": 3119, + "vendor": "V3" + }, + "PO3": { + "unit": "Central", + "unit_price_cents": 13582, + "vendor": "V3" + }, + "PO4": { + "unit": "Central", + "unit_price_cents": 3442, + "vendor": "V1" + }, + "PO5": { + "unit": "Central", + "unit_price_cents": 11303, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 12215, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-022/instruction.md b/tasks/autom-supplier-invoice-match-022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..86e7f35008f5cd9ca22a05bdf1def5a3e54b2003 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-022/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit Central at 2025-02-13. Handle invoices in review attached to that unit's purchase orders, invoice dates 2025-01-23 through 2025-02-13 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 0 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-022/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-022/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..84fbfe4d1a517a9d3af4b9b4973868344d05888c --- /dev/null +++ b/tasks/autom-supplier-invoice-match-022/solution/files/actions.jsonl @@ -0,0 +1,28 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-9017-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-9728-0-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5562-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4439-1-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5461-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4676-2-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4276-2-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5399-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-5258-3-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-1803-3-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6266-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-1858-4-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-4644-5-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7544-5-1", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 146939, "due": "2025-02-24", "invoice": "IV-4644-5-0", "po": "PO5", "status": "posted", "units": 13}, "id": "book-IV-4644-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 190148, "due": "2025-03-10", "invoice": "IV-5399-3-0", "po": "PO3", "status": "posted", "units": 14}, "id": "book-IV-5399-3-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 34309, "due": "2025-03-10", "invoice": "IV-5461-2-0", "po": "PO2", "status": "posted", "units": 11}, "id": "book-IV-5461-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 62750, "due": "2025-02-07", "invoice": "IV-5562-1-0", "po": "PO1", "status": "posted", "units": 25}, "id": "book-IV-5562-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 17210, "due": "2025-02-07", "invoice": "IV-6266-4-0", "po": "PO4", "status": "posted", "units": 5}, "id": "book-IV-6266-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 15807, "due": "2025-03-10", "invoice": "IV-9017-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-9017-0-0", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4276-2-3", "issues": ["units"], "po": "PO2"}, "id": "case-IV-4276-2-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4439-1-1", "issues": ["vendor", "price", "units"], "po": "PO1"}, "id": "case-IV-4439-1-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-1803-3-2", "issues": ["price", "units"], "po": "PO3"}, "id": "case-IV-1803-3-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4676-2-2", "issues": ["vendor", "price"], "po": "PO2"}, "id": "case-IV-4676-2-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-1858-4-2", "issues": ["price"], "po": "PO4"}, "id": "case-IV-1858-4-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-5258-3-1", "issues": ["price"], "po": "PO3"}, "id": "case-IV-5258-3-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7544-5-1", "issues": ["price"], "po": "PO5"}, "id": "case-IV-7544-5-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-9728-0-2", "issues": ["vendor", "price"], "po": "PO0"}, "id": "case-IV-9728-0-2", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-022/solution/solve.sh b/tasks/autom-supplier-invoice-match-022/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-022/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-022/task.toml b/tasks/autom-supplier-invoice-match-022/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3f8e4996ec5345e108e7f9e2f2ff38a341c0a6f8 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-022/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-022" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 22 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-022" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-022/tests/expected.json b/tasks/autom-supplier-invoice-match-022/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-022/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-022/tests/grade.py b/tasks/autom-supplier-invoice-match-022/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-022/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-022/tests/replay.py b/tasks/autom-supplier-invoice-match-022/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-022/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-022/tests/target.json b/tasks/autom-supplier-invoice-match-022/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..61126696871eedcd0d7453f0ad2b8954469e7850 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-022/tests/target.json @@ -0,0 +1,547 @@ +{ + "ap_postings": { + "book-IV-4644-5-0": { + "amount_cents": 146939, + "due": "2025-02-24", + "invoice": "IV-4644-5-0", + "po": "PO5", + "status": "posted", + "units": 13 + }, + "book-IV-5399-3-0": { + "amount_cents": 190148, + "due": "2025-03-10", + "invoice": "IV-5399-3-0", + "po": "PO3", + "status": "posted", + "units": 14 + }, + "book-IV-5461-2-0": { + "amount_cents": 34309, + "due": "2025-03-10", + "invoice": "IV-5461-2-0", + "po": "PO2", + "status": "posted", + "units": 11 + }, + "book-IV-5562-1-0": { + "amount_cents": 62750, + "due": "2025-02-07", + "invoice": "IV-5562-1-0", + "po": "PO1", + "status": "posted", + "units": 25 + }, + "book-IV-6266-4-0": { + "amount_cents": 17210, + "due": "2025-02-07", + "invoice": "IV-6266-4-0", + "po": "PO4", + "status": "posted", + "units": 5 + }, + "book-IV-9017-0-0": { + "amount_cents": 15807, + "due": "2025-03-10", + "invoice": "IV-9017-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 8 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 7 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 6 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 3 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 4 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 8 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 6 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-02-12", + "po": "PO0", + "state": "accepted", + "units": 23 + }, + "GI-0-1": { + "date": "2025-02-04", + "po": "PO0", + "state": "quarantine", + "units": 28 + }, + "GI-0-2": { + "date": "2025-02-13", + "po": "PO0", + "state": "accepted", + "units": 24 + }, + "GI-0-3": { + "date": "2025-02-18", + "po": "PO0", + "state": "quarantine", + "units": 26 + }, + "GI-1-0": { + "date": "2025-02-12", + "po": "PO1", + "state": "accepted", + "units": 20 + }, + "GI-1-1": { + "date": "2025-02-16", + "po": "PO1", + "state": "quarantine", + "units": 24 + }, + "GI-1-2": { + "date": "2025-02-06", + "po": "PO1", + "state": "quarantine", + "units": 24 + }, + "GI-1-3": { + "date": "2025-01-30", + "po": "PO1", + "state": "accepted", + "units": 14 + }, + "GI-2-0": { + "date": "2025-02-12", + "po": "PO2", + "state": "accepted", + "units": 14 + }, + "GI-2-1": { + "date": "2025-02-03", + "po": "PO2", + "state": "quarantine", + "units": 16 + }, + "GI-2-2": { + "date": "2025-02-04", + "po": "PO2", + "state": "quarantine", + "units": 14 + }, + "GI-2-3": { + "date": "2025-02-07", + "po": "PO2", + "state": "accepted", + "units": 15 + }, + "GI-3-0": { + "date": "2025-02-12", + "po": "PO3", + "state": "accepted", + "units": 12 + }, + "GI-3-1": { + "date": "2025-01-31", + "po": "PO3", + "state": "quarantine", + "units": 22 + }, + "GI-3-2": { + "date": "2025-02-06", + "po": "PO3", + "state": "quarantine", + "units": 23 + }, + "GI-3-3": { + "date": "2025-02-02", + "po": "PO3", + "state": "accepted", + "units": 25 + }, + "GI-4-0": { + "date": "2025-02-12", + "po": "PO4", + "state": "accepted", + "units": 23 + }, + "GI-4-1": { + "date": "2025-01-27", + "po": "PO4", + "state": "accepted", + "units": 17 + }, + "GI-4-2": { + "date": "2025-01-29", + "po": "PO4", + "state": "quarantine", + "units": 18 + }, + "GI-4-3": { + "date": "2025-02-15", + "po": "PO4", + "state": "quarantine", + "units": 21 + }, + "GI-5-0": { + "date": "2025-02-12", + "po": "PO5", + "state": "accepted", + "units": 12 + }, + "GI-5-1": { + "date": "2025-02-05", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-5-2": { + "date": "2025-02-02", + "po": "PO5", + "state": "accepted", + "units": 26 + }, + "GI-5-3": { + "date": "2025-02-17", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-6-0": { + "date": "2025-02-12", + "po": "PO6", + "state": "accepted", + "units": 25 + }, + "GI-6-1": { + "date": "2025-02-05", + "po": "PO6", + "state": "accepted", + "units": 20 + }, + "GI-6-2": { + "date": "2025-02-13", + "po": "PO6", + "state": "accepted", + "units": 18 + }, + "GI-6-3": { + "date": "2025-02-09", + "po": "PO6", + "state": "accepted", + "units": 28 + } + }, + "invoice_inbox": { + "IV-1803-3-2": { + "date": "2025-01-27", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 13950, + "units": 23, + "vendor": "V3" + }, + "IV-1858-4-2": { + "date": "2025-02-03", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 5048, + "units": 18, + "vendor": "V1" + }, + "IV-1952-4-1": { + "date": "2025-01-28", + "po": "PO4", + "state": "void", + "unit_price_cents": 4547, + "units": 3, + "vendor": "V1" + }, + "IV-2958-2-1": { + "date": "2025-02-13", + "po": "PO2", + "state": "void", + "unit_price_cents": 3336, + "units": 12, + "vendor": "V3" + }, + "IV-3488-0-1": { + "date": "2025-02-02", + "po": "PO0", + "state": "void", + "unit_price_cents": 15823, + "units": 3, + "vendor": "V3" + }, + "IV-4276-2-3": { + "date": "2025-01-23", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 2736, + "units": 24, + "vendor": "V3" + }, + "IV-4302-6-0": { + "date": "2025-01-23", + "po": "PO6", + "state": "review", + "unit_price_cents": 12215, + "units": 7, + "vendor": "V0" + }, + "IV-4439-1-1": { + "date": "2025-01-25", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 2614, + "units": 7, + "vendor": "Unknown" + }, + "IV-4616-6-2": { + "date": "2025-01-19", + "po": "PO6", + "state": "review", + "unit_price_cents": 14216, + "units": 12, + "vendor": "V0" + }, + "IV-4644-5-0": { + "date": "2025-01-23", + "po": "PO5", + "state": "posted", + "unit_price_cents": 11303, + "units": 13, + "vendor": "V0" + }, + "IV-4676-2-2": { + "date": "2025-01-29", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 3732, + "units": 5, + "vendor": "Unknown" + }, + "IV-5197-6-3": { + "date": "2025-01-25", + "po": "PO6", + "state": "review", + "unit_price_cents": 12655, + "units": 18, + "vendor": "V0" + }, + "IV-5258-3-1": { + "date": "2025-02-07", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 15026, + "units": 5, + "vendor": "V3" + }, + "IV-5399-3-0": { + "date": "2025-01-23", + "po": "PO3", + "state": "posted", + "unit_price_cents": 13582, + "units": 14, + "vendor": "V3" + }, + "IV-5461-2-0": { + "date": "2025-01-23", + "po": "PO2", + "state": "posted", + "unit_price_cents": 3119, + "units": 11, + "vendor": "V3" + }, + "IV-5562-1-0": { + "date": "2025-01-23", + "po": "PO1", + "state": "posted", + "unit_price_cents": 2510, + "units": 25, + "vendor": "V1" + }, + "IV-6266-4-0": { + "date": "2025-01-23", + "po": "PO4", + "state": "posted", + "unit_price_cents": 3442, + "units": 5, + "vendor": "V1" + }, + "IV-7449-6-1": { + "date": "2025-01-31", + "po": "PO6", + "state": "review", + "unit_price_cents": 14150, + "units": 12, + "vendor": "V0" + }, + "IV-7544-5-1": { + "date": "2025-02-11", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 12021, + "units": 5, + "vendor": "V0" + }, + "IV-9017-0-0": { + "date": "2025-01-23", + "po": "PO0", + "state": "posted", + "unit_price_cents": 15807, + "units": 1, + "vendor": "V3" + }, + "IV-9728-0-2": { + "date": "2025-02-11", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 16430, + "units": 11, + "vendor": "Unknown" + } + }, + "purchase_orders": { + "PO0": { + "unit": "Central", + "unit_price_cents": 15807, + "vendor": "V3" + }, + "PO1": { + "unit": "Central", + "unit_price_cents": 2510, + "vendor": "V1" + }, + "PO2": { + "unit": "Central", + "unit_price_cents": 3119, + "vendor": "V3" + }, + "PO3": { + "unit": "Central", + "unit_price_cents": 13582, + "vendor": "V3" + }, + "PO4": { + "unit": "Central", + "unit_price_cents": 3442, + "vendor": "V1" + }, + "PO5": { + "unit": "Central", + "unit_price_cents": 11303, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 12215, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-1803-3-2": { + "invoice": "IV-1803-3-2", + "issues": [ + "price", + "units" + ], + "po": "PO3" + }, + "case-IV-1858-4-2": { + "invoice": "IV-1858-4-2", + "issues": [ + "price" + ], + "po": "PO4" + }, + "case-IV-4276-2-3": { + "invoice": "IV-4276-2-3", + "issues": [ + "units" + ], + "po": "PO2" + }, + "case-IV-4439-1-1": { + "invoice": "IV-4439-1-1", + "issues": [ + "vendor", + "price", + "units" + ], + "po": "PO1" + }, + "case-IV-4676-2-2": { + "invoice": "IV-4676-2-2", + "issues": [ + "vendor", + "price" + ], + "po": "PO2" + }, + "case-IV-5258-3-1": { + "invoice": "IV-5258-3-1", + "issues": [ + "price" + ], + "po": "PO3" + }, + "case-IV-7544-5-1": { + "invoice": "IV-7544-5-1", + "issues": [ + "price" + ], + "po": "PO5" + }, + "case-IV-9728-0-2": { + "invoice": "IV-9728-0-2", + "issues": [ + "vendor", + "price" + ], + "po": "PO0" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-022/tests/test.sh b/tasks/autom-supplier-invoice-match-022/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-022/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-022/tests/world.json b/tasks/autom-supplier-invoice-match-022/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..bf51a1db7331524dc19274462bff49efeb17641b --- /dev/null +++ b/tasks/autom-supplier-invoice-match-022/tests/world.json @@ -0,0 +1,438 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 8 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 7 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 6 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 3 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 4 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 8 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 6 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-02-12", + "po": "PO0", + "state": "accepted", + "units": 23 + }, + "GI-0-1": { + "date": "2025-02-04", + "po": "PO0", + "state": "quarantine", + "units": 28 + }, + "GI-0-2": { + "date": "2025-02-13", + "po": "PO0", + "state": "accepted", + "units": 24 + }, + "GI-0-3": { + "date": "2025-02-18", + "po": "PO0", + "state": "quarantine", + "units": 26 + }, + "GI-1-0": { + "date": "2025-02-12", + "po": "PO1", + "state": "accepted", + "units": 20 + }, + "GI-1-1": { + "date": "2025-02-16", + "po": "PO1", + "state": "quarantine", + "units": 24 + }, + "GI-1-2": { + "date": "2025-02-06", + "po": "PO1", + "state": "quarantine", + "units": 24 + }, + "GI-1-3": { + "date": "2025-01-30", + "po": "PO1", + "state": "accepted", + "units": 14 + }, + "GI-2-0": { + "date": "2025-02-12", + "po": "PO2", + "state": "accepted", + "units": 14 + }, + "GI-2-1": { + "date": "2025-02-03", + "po": "PO2", + "state": "quarantine", + "units": 16 + }, + "GI-2-2": { + "date": "2025-02-04", + "po": "PO2", + "state": "quarantine", + "units": 14 + }, + "GI-2-3": { + "date": "2025-02-07", + "po": "PO2", + "state": "accepted", + "units": 15 + }, + "GI-3-0": { + "date": "2025-02-12", + "po": "PO3", + "state": "accepted", + "units": 12 + }, + "GI-3-1": { + "date": "2025-01-31", + "po": "PO3", + "state": "quarantine", + "units": 22 + }, + "GI-3-2": { + "date": "2025-02-06", + "po": "PO3", + "state": "quarantine", + "units": 23 + }, + "GI-3-3": { + "date": "2025-02-02", + "po": "PO3", + "state": "accepted", + "units": 25 + }, + "GI-4-0": { + "date": "2025-02-12", + "po": "PO4", + "state": "accepted", + "units": 23 + }, + "GI-4-1": { + "date": "2025-01-27", + "po": "PO4", + "state": "accepted", + "units": 17 + }, + "GI-4-2": { + "date": "2025-01-29", + "po": "PO4", + "state": "quarantine", + "units": 18 + }, + "GI-4-3": { + "date": "2025-02-15", + "po": "PO4", + "state": "quarantine", + "units": 21 + }, + "GI-5-0": { + "date": "2025-02-12", + "po": "PO5", + "state": "accepted", + "units": 12 + }, + "GI-5-1": { + "date": "2025-02-05", + "po": "PO5", + "state": "quarantine", + "units": 15 + }, + "GI-5-2": { + "date": "2025-02-02", + "po": "PO5", + "state": "accepted", + "units": 26 + }, + "GI-5-3": { + "date": "2025-02-17", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-6-0": { + "date": "2025-02-12", + "po": "PO6", + "state": "accepted", + "units": 25 + }, + "GI-6-1": { + "date": "2025-02-05", + "po": "PO6", + "state": "accepted", + "units": 20 + }, + "GI-6-2": { + "date": "2025-02-13", + "po": "PO6", + "state": "accepted", + "units": 18 + }, + "GI-6-3": { + "date": "2025-02-09", + "po": "PO6", + "state": "accepted", + "units": 28 + } + }, + "invoice_inbox": { + "IV-1803-3-2": { + "date": "2025-01-27", + "po": "PO3", + "state": "review", + "unit_price_cents": 13950, + "units": 23, + "vendor": "V3" + }, + "IV-1858-4-2": { + "date": "2025-02-03", + "po": "PO4", + "state": "review", + "unit_price_cents": 5048, + "units": 18, + "vendor": "V1" + }, + "IV-1952-4-1": { + "date": "2025-01-28", + "po": "PO4", + "state": "void", + "unit_price_cents": 4547, + "units": 3, + "vendor": "V1" + }, + "IV-2958-2-1": { + "date": "2025-02-13", + "po": "PO2", + "state": "void", + "unit_price_cents": 3336, + "units": 12, + "vendor": "V3" + }, + "IV-3488-0-1": { + "date": "2025-02-02", + "po": "PO0", + "state": "void", + "unit_price_cents": 15823, + "units": 3, + "vendor": "V3" + }, + "IV-4276-2-3": { + "date": "2025-01-23", + "po": "PO2", + "state": "review", + "unit_price_cents": 2736, + "units": 24, + "vendor": "V3" + }, + "IV-4302-6-0": { + "date": "2025-01-23", + "po": "PO6", + "state": "review", + "unit_price_cents": 12215, + "units": 7, + "vendor": "V0" + }, + "IV-4439-1-1": { + "date": "2025-01-25", + "po": "PO1", + "state": "review", + "unit_price_cents": 2614, + "units": 7, + "vendor": "Unknown" + }, + "IV-4616-6-2": { + "date": "2025-01-19", + "po": "PO6", + "state": "review", + "unit_price_cents": 14216, + "units": 12, + "vendor": "V0" + }, + "IV-4644-5-0": { + "date": "2025-01-23", + "po": "PO5", + "state": "review", + "unit_price_cents": 11303, + "units": 13, + "vendor": "V0" + }, + "IV-4676-2-2": { + "date": "2025-01-29", + "po": "PO2", + "state": "review", + "unit_price_cents": 3732, + "units": 5, + "vendor": "Unknown" + }, + "IV-5197-6-3": { + "date": "2025-01-25", + "po": "PO6", + "state": "review", + "unit_price_cents": 12655, + "units": 18, + "vendor": "V0" + }, + "IV-5258-3-1": { + "date": "2025-02-07", + "po": "PO3", + "state": "review", + "unit_price_cents": 15026, + "units": 5, + "vendor": "V3" + }, + "IV-5399-3-0": { + "date": "2025-01-23", + "po": "PO3", + "state": "review", + "unit_price_cents": 13582, + "units": 14, + "vendor": "V3" + }, + "IV-5461-2-0": { + "date": "2025-01-23", + "po": "PO2", + "state": "review", + "unit_price_cents": 3119, + "units": 11, + "vendor": "V3" + }, + "IV-5562-1-0": { + "date": "2025-01-23", + "po": "PO1", + "state": "review", + "unit_price_cents": 2510, + "units": 25, + "vendor": "V1" + }, + "IV-6266-4-0": { + "date": "2025-01-23", + "po": "PO4", + "state": "review", + "unit_price_cents": 3442, + "units": 5, + "vendor": "V1" + }, + "IV-7449-6-1": { + "date": "2025-01-31", + "po": "PO6", + "state": "review", + "unit_price_cents": 14150, + "units": 12, + "vendor": "V0" + }, + "IV-7544-5-1": { + "date": "2025-02-11", + "po": "PO5", + "state": "review", + "unit_price_cents": 12021, + "units": 5, + "vendor": "V0" + }, + "IV-9017-0-0": { + "date": "2025-01-23", + "po": "PO0", + "state": "review", + "unit_price_cents": 15807, + "units": 1, + "vendor": "V3" + }, + "IV-9728-0-2": { + "date": "2025-02-11", + "po": "PO0", + "state": "review", + "unit_price_cents": 16430, + "units": 11, + "vendor": "Unknown" + } + }, + "purchase_orders": { + "PO0": { + "unit": "Central", + "unit_price_cents": 15807, + "vendor": "V3" + }, + "PO1": { + "unit": "Central", + "unit_price_cents": 2510, + "vendor": "V1" + }, + "PO2": { + "unit": "Central", + "unit_price_cents": 3119, + "vendor": "V3" + }, + "PO3": { + "unit": "Central", + "unit_price_cents": 13582, + "vendor": "V3" + }, + "PO4": { + "unit": "Central", + "unit_price_cents": 3442, + "vendor": "V1" + }, + "PO5": { + "unit": "Central", + "unit_price_cents": 11303, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 12215, + "vendor": "V0" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 30 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 45 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-022/tests/world_check.py b/tasks/autom-supplier-invoice-match-022/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-022/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-022/validation/openenv.json b/tasks/autom-supplier-invoice-match-022/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-022/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-023/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-023/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-023/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-023/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-023/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..08f0a19de220dff2f0673189df50f770f94756f6 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-023/environment/inputs/world.json @@ -0,0 +1,454 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 1 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 2 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 6 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 4 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 5 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 3 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 2 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-03-07", + "po": "PO0", + "state": "accepted", + "units": 19 + }, + "GI-0-1": { + "date": "2025-03-12", + "po": "PO0", + "state": "accepted", + "units": 23 + }, + "GI-0-2": { + "date": "2025-03-12", + "po": "PO0", + "state": "accepted", + "units": 13 + }, + "GI-0-3": { + "date": "2025-03-01", + "po": "PO0", + "state": "quarantine", + "units": 26 + }, + "GI-1-0": { + "date": "2025-03-07", + "po": "PO1", + "state": "accepted", + "units": 28 + }, + "GI-1-1": { + "date": "2025-03-04", + "po": "PO1", + "state": "quarantine", + "units": 28 + }, + "GI-1-2": { + "date": "2025-02-13", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-1-3": { + "date": "2025-02-17", + "po": "PO1", + "state": "quarantine", + "units": 22 + }, + "GI-2-0": { + "date": "2025-03-07", + "po": "PO2", + "state": "accepted", + "units": 22 + }, + "GI-2-1": { + "date": "2025-02-25", + "po": "PO2", + "state": "quarantine", + "units": 15 + }, + "GI-2-2": { + "date": "2025-03-12", + "po": "PO2", + "state": "quarantine", + "units": 20 + }, + "GI-2-3": { + "date": "2025-03-05", + "po": "PO2", + "state": "quarantine", + "units": 22 + }, + "GI-3-0": { + "date": "2025-03-07", + "po": "PO3", + "state": "accepted", + "units": 22 + }, + "GI-3-1": { + "date": "2025-02-19", + "po": "PO3", + "state": "quarantine", + "units": 12 + }, + "GI-3-2": { + "date": "2025-02-17", + "po": "PO3", + "state": "quarantine", + "units": 20 + }, + "GI-3-3": { + "date": "2025-02-15", + "po": "PO3", + "state": "accepted", + "units": 16 + }, + "GI-4-0": { + "date": "2025-03-07", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-4-1": { + "date": "2025-02-13", + "po": "PO4", + "state": "quarantine", + "units": 23 + }, + "GI-4-2": { + "date": "2025-03-03", + "po": "PO4", + "state": "accepted", + "units": 20 + }, + "GI-4-3": { + "date": "2025-02-21", + "po": "PO4", + "state": "quarantine", + "units": 21 + }, + "GI-5-0": { + "date": "2025-03-07", + "po": "PO5", + "state": "accepted", + "units": 25 + }, + "GI-5-1": { + "date": "2025-03-08", + "po": "PO5", + "state": "quarantine", + "units": 21 + }, + "GI-5-2": { + "date": "2025-02-18", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-5-3": { + "date": "2025-02-21", + "po": "PO5", + "state": "accepted", + "units": 13 + }, + "GI-6-0": { + "date": "2025-03-07", + "po": "PO6", + "state": "accepted", + "units": 19 + }, + "GI-6-1": { + "date": "2025-02-27", + "po": "PO6", + "state": "accepted", + "units": 16 + }, + "GI-6-2": { + "date": "2025-02-16", + "po": "PO6", + "state": "quarantine", + "units": 21 + }, + "GI-6-3": { + "date": "2025-02-13", + "po": "PO6", + "state": "quarantine", + "units": 15 + } + }, + "invoice_inbox": { + "IV-1157-2-0": { + "date": "2025-02-15", + "po": "PO2", + "state": "review", + "unit_price_cents": 5459, + "units": 14, + "vendor": "V4" + }, + "IV-1358-6-1": { + "date": "2025-02-24", + "po": "PO6", + "state": "review", + "unit_price_cents": 15422, + "units": 13, + "vendor": "Unknown" + }, + "IV-2106-3-1": { + "date": "2025-03-01", + "po": "PO3", + "state": "void", + "unit_price_cents": 5950, + "units": 9, + "vendor": "V4" + }, + "IV-2216-6-0": { + "date": "2025-02-15", + "po": "PO6", + "state": "review", + "unit_price_cents": 15574, + "units": 18, + "vendor": "V3" + }, + "IV-2536-5-0": { + "date": "2025-02-15", + "po": "PO5", + "state": "review", + "unit_price_cents": 8760, + "units": 13, + "vendor": "V0" + }, + "IV-3399-5-2": { + "date": "2025-03-01", + "po": "PO5", + "state": "void", + "unit_price_cents": 10909, + "units": 25, + "vendor": "V0" + }, + "IV-3524-3-2": { + "date": "2025-02-14", + "po": "PO3", + "state": "review", + "unit_price_cents": 6413, + "units": 14, + "vendor": "Unknown" + }, + "IV-3827-6-2": { + "date": "2025-02-20", + "po": "PO6", + "state": "review", + "unit_price_cents": 15640, + "units": 15, + "vendor": "V3" + }, + "IV-3928-0-1": { + "date": "2025-02-15", + "po": "PO0", + "state": "review", + "unit_price_cents": 13953, + "units": 20, + "vendor": "V1" + }, + "IV-4497-4-3": { + "date": "2025-03-05", + "po": "PO4", + "state": "review", + "unit_price_cents": 20741, + "units": 18, + "vendor": "V0" + }, + "IV-4593-2-1": { + "date": "2025-03-04", + "po": "PO2", + "state": "void", + "unit_price_cents": 5085, + "units": 14, + "vendor": "V4" + }, + "IV-4835-1-0": { + "date": "2025-02-15", + "po": "PO1", + "state": "review", + "unit_price_cents": 1916, + "units": 22, + "vendor": "V0" + }, + "IV-6332-4-0": { + "date": "2025-02-15", + "po": "PO4", + "state": "review", + "unit_price_cents": 19592, + "units": 20, + "vendor": "V0" + }, + "IV-6422-4-2": { + "date": "2025-03-09", + "po": "PO4", + "state": "void", + "unit_price_cents": 20212, + "units": 9, + "vendor": "Unknown" + }, + "IV-7380-5-3": { + "date": "2025-02-10", + "po": "PO5", + "state": "review", + "unit_price_cents": 9218, + "units": 23, + "vendor": "V0" + }, + "IV-7930-0-0": { + "date": "2025-02-15", + "po": "PO0", + "state": "review", + "unit_price_cents": 12319, + "units": 1, + "vendor": "V1" + }, + "IV-8608-3-0": { + "date": "2025-02-15", + "po": "PO3", + "state": "review", + "unit_price_cents": 4462, + "units": 4, + "vendor": "V4" + }, + "IV-8713-4-1": { + "date": "2025-03-09", + "po": "PO4", + "state": "review", + "unit_price_cents": 21709, + "units": 20, + "vendor": "V0" + }, + "IV-8718-1-1": { + "date": "2025-02-12", + "po": "PO1", + "state": "void", + "unit_price_cents": 1589, + "units": 9, + "vendor": "V0" + }, + "IV-8791-3-3": { + "date": "2025-02-19", + "po": "PO3", + "state": "review", + "unit_price_cents": 4498, + "units": 24, + "vendor": "V4" + }, + "IV-9174-5-1": { + "date": "2025-02-21", + "po": "PO5", + "state": "review", + "unit_price_cents": 10445, + "units": 11, + "vendor": "Unknown" + }, + "IV-9833-2-2": { + "date": "2025-02-22", + "po": "PO2", + "state": "void", + "unit_price_cents": 6782, + "units": 18, + "vendor": "V4" + }, + "IV-9850-2-3": { + "date": "2025-02-24", + "po": "PO2", + "state": "review", + "unit_price_cents": 5476, + "units": 8, + "vendor": "V4" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 12319, + "vendor": "V1" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 1916, + "vendor": "V0" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 5459, + "vendor": "V4" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 4462, + "vendor": "V4" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 19592, + "vendor": "V0" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 8760, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 15574, + "vendor": "V3" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 21 + }, + "V1": { + "net_days": 21 + }, + "V2": { + "net_days": 21 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-023/instruction.md b/tasks/autom-supplier-invoice-match-023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..01ad839481dd2aac39544da61a65d20cc4b0481b --- /dev/null +++ b/tasks/autom-supplier-invoice-match-023/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit South at 2025-03-08. Handle invoices in review attached to that unit's purchase orders, invoice dates 2025-02-15 through 2025-03-08 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 0 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-023/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-023/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..701080c1928c25b96cb853f1caa052f11057da8b --- /dev/null +++ b/tasks/autom-supplier-invoice-match-023/solution/files/actions.jsonl @@ -0,0 +1,22 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-7930-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3928-0-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-4835-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-1157-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-9850-2-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-8608-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-8791-3-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6332-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-4497-4-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-2536-5-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-9174-5-1", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 76426, "due": "2025-03-10", "invoice": "IV-1157-2-0", "po": "PO2", "status": "posted", "units": 14}, "id": "book-IV-1157-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 113880, "due": "2025-03-10", "invoice": "IV-2536-5-0", "po": "PO5", "status": "posted", "units": 13}, "id": "book-IV-2536-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 42152, "due": "2025-03-10", "invoice": "IV-4835-1-0", "po": "PO1", "status": "posted", "units": 22}, "id": "book-IV-4835-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 391840, "due": "2025-03-10", "invoice": "IV-6332-4-0", "po": "PO4", "status": "posted", "units": 20}, "id": "book-IV-6332-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 12319, "due": "2025-03-10", "invoice": "IV-7930-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-7930-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 17848, "due": "2025-03-10", "invoice": "IV-8608-3-0", "po": "PO3", "status": "posted", "units": 4}, "id": "book-IV-8608-3-0", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3928-0-1", "issues": ["price", "units"], "po": "PO0"}, "id": "case-IV-3928-0-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-8791-3-3", "issues": ["price"], "po": "PO3"}, "id": "case-IV-8791-3-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-9174-5-1", "issues": ["vendor", "price"], "po": "PO5"}, "id": "case-IV-9174-5-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-9850-2-3", "issues": ["price", "units"], "po": "PO2"}, "id": "case-IV-9850-2-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-4497-4-3", "issues": ["price", "units"], "po": "PO4"}, "id": "case-IV-4497-4-3", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-023/solution/solve.sh b/tasks/autom-supplier-invoice-match-023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-023/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-023/task.toml b/tasks/autom-supplier-invoice-match-023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1e6e29d82ccaac7dc7bb8a9ce899f91c7bfc5211 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-023/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-023" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 23 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-023" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-023/tests/expected.json b/tasks/autom-supplier-invoice-match-023/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-023/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-023/tests/grade.py b/tasks/autom-supplier-invoice-match-023/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-023/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-023/tests/replay.py b/tasks/autom-supplier-invoice-match-023/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-023/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-023/tests/target.json b/tasks/autom-supplier-invoice-match-023/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..68c13f163f9040185aea1fa44b7cceb3069a069d --- /dev/null +++ b/tasks/autom-supplier-invoice-match-023/tests/target.json @@ -0,0 +1,541 @@ +{ + "ap_postings": { + "book-IV-1157-2-0": { + "amount_cents": 76426, + "due": "2025-03-10", + "invoice": "IV-1157-2-0", + "po": "PO2", + "status": "posted", + "units": 14 + }, + "book-IV-2536-5-0": { + "amount_cents": 113880, + "due": "2025-03-10", + "invoice": "IV-2536-5-0", + "po": "PO5", + "status": "posted", + "units": 13 + }, + "book-IV-4835-1-0": { + "amount_cents": 42152, + "due": "2025-03-10", + "invoice": "IV-4835-1-0", + "po": "PO1", + "status": "posted", + "units": 22 + }, + "book-IV-6332-4-0": { + "amount_cents": 391840, + "due": "2025-03-10", + "invoice": "IV-6332-4-0", + "po": "PO4", + "status": "posted", + "units": 20 + }, + "book-IV-7930-0-0": { + "amount_cents": 12319, + "due": "2025-03-10", + "invoice": "IV-7930-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "book-IV-8608-3-0": { + "amount_cents": 17848, + "due": "2025-03-10", + "invoice": "IV-8608-3-0", + "po": "PO3", + "status": "posted", + "units": 4 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 1 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 2 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 6 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 4 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 5 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 3 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 2 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-03-07", + "po": "PO0", + "state": "accepted", + "units": 19 + }, + "GI-0-1": { + "date": "2025-03-12", + "po": "PO0", + "state": "accepted", + "units": 23 + }, + "GI-0-2": { + "date": "2025-03-12", + "po": "PO0", + "state": "accepted", + "units": 13 + }, + "GI-0-3": { + "date": "2025-03-01", + "po": "PO0", + "state": "quarantine", + "units": 26 + }, + "GI-1-0": { + "date": "2025-03-07", + "po": "PO1", + "state": "accepted", + "units": 28 + }, + "GI-1-1": { + "date": "2025-03-04", + "po": "PO1", + "state": "quarantine", + "units": 28 + }, + "GI-1-2": { + "date": "2025-02-13", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-1-3": { + "date": "2025-02-17", + "po": "PO1", + "state": "quarantine", + "units": 22 + }, + "GI-2-0": { + "date": "2025-03-07", + "po": "PO2", + "state": "accepted", + "units": 22 + }, + "GI-2-1": { + "date": "2025-02-25", + "po": "PO2", + "state": "quarantine", + "units": 15 + }, + "GI-2-2": { + "date": "2025-03-12", + "po": "PO2", + "state": "quarantine", + "units": 20 + }, + "GI-2-3": { + "date": "2025-03-05", + "po": "PO2", + "state": "quarantine", + "units": 22 + }, + "GI-3-0": { + "date": "2025-03-07", + "po": "PO3", + "state": "accepted", + "units": 22 + }, + "GI-3-1": { + "date": "2025-02-19", + "po": "PO3", + "state": "quarantine", + "units": 12 + }, + "GI-3-2": { + "date": "2025-02-17", + "po": "PO3", + "state": "quarantine", + "units": 20 + }, + "GI-3-3": { + "date": "2025-02-15", + "po": "PO3", + "state": "accepted", + "units": 16 + }, + "GI-4-0": { + "date": "2025-03-07", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-4-1": { + "date": "2025-02-13", + "po": "PO4", + "state": "quarantine", + "units": 23 + }, + "GI-4-2": { + "date": "2025-03-03", + "po": "PO4", + "state": "accepted", + "units": 20 + }, + "GI-4-3": { + "date": "2025-02-21", + "po": "PO4", + "state": "quarantine", + "units": 21 + }, + "GI-5-0": { + "date": "2025-03-07", + "po": "PO5", + "state": "accepted", + "units": 25 + }, + "GI-5-1": { + "date": "2025-03-08", + "po": "PO5", + "state": "quarantine", + "units": 21 + }, + "GI-5-2": { + "date": "2025-02-18", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-5-3": { + "date": "2025-02-21", + "po": "PO5", + "state": "accepted", + "units": 13 + }, + "GI-6-0": { + "date": "2025-03-07", + "po": "PO6", + "state": "accepted", + "units": 19 + }, + "GI-6-1": { + "date": "2025-02-27", + "po": "PO6", + "state": "accepted", + "units": 16 + }, + "GI-6-2": { + "date": "2025-02-16", + "po": "PO6", + "state": "quarantine", + "units": 21 + }, + "GI-6-3": { + "date": "2025-02-13", + "po": "PO6", + "state": "quarantine", + "units": 15 + } + }, + "invoice_inbox": { + "IV-1157-2-0": { + "date": "2025-02-15", + "po": "PO2", + "state": "posted", + "unit_price_cents": 5459, + "units": 14, + "vendor": "V4" + }, + "IV-1358-6-1": { + "date": "2025-02-24", + "po": "PO6", + "state": "review", + "unit_price_cents": 15422, + "units": 13, + "vendor": "Unknown" + }, + "IV-2106-3-1": { + "date": "2025-03-01", + "po": "PO3", + "state": "void", + "unit_price_cents": 5950, + "units": 9, + "vendor": "V4" + }, + "IV-2216-6-0": { + "date": "2025-02-15", + "po": "PO6", + "state": "review", + "unit_price_cents": 15574, + "units": 18, + "vendor": "V3" + }, + "IV-2536-5-0": { + "date": "2025-02-15", + "po": "PO5", + "state": "posted", + "unit_price_cents": 8760, + "units": 13, + "vendor": "V0" + }, + "IV-3399-5-2": { + "date": "2025-03-01", + "po": "PO5", + "state": "void", + "unit_price_cents": 10909, + "units": 25, + "vendor": "V0" + }, + "IV-3524-3-2": { + "date": "2025-02-14", + "po": "PO3", + "state": "review", + "unit_price_cents": 6413, + "units": 14, + "vendor": "Unknown" + }, + "IV-3827-6-2": { + "date": "2025-02-20", + "po": "PO6", + "state": "review", + "unit_price_cents": 15640, + "units": 15, + "vendor": "V3" + }, + "IV-3928-0-1": { + "date": "2025-02-15", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 13953, + "units": 20, + "vendor": "V1" + }, + "IV-4497-4-3": { + "date": "2025-03-05", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 20741, + "units": 18, + "vendor": "V0" + }, + "IV-4593-2-1": { + "date": "2025-03-04", + "po": "PO2", + "state": "void", + "unit_price_cents": 5085, + "units": 14, + "vendor": "V4" + }, + "IV-4835-1-0": { + "date": "2025-02-15", + "po": "PO1", + "state": "posted", + "unit_price_cents": 1916, + "units": 22, + "vendor": "V0" + }, + "IV-6332-4-0": { + "date": "2025-02-15", + "po": "PO4", + "state": "posted", + "unit_price_cents": 19592, + "units": 20, + "vendor": "V0" + }, + "IV-6422-4-2": { + "date": "2025-03-09", + "po": "PO4", + "state": "void", + "unit_price_cents": 20212, + "units": 9, + "vendor": "Unknown" + }, + "IV-7380-5-3": { + "date": "2025-02-10", + "po": "PO5", + "state": "review", + "unit_price_cents": 9218, + "units": 23, + "vendor": "V0" + }, + "IV-7930-0-0": { + "date": "2025-02-15", + "po": "PO0", + "state": "posted", + "unit_price_cents": 12319, + "units": 1, + "vendor": "V1" + }, + "IV-8608-3-0": { + "date": "2025-02-15", + "po": "PO3", + "state": "posted", + "unit_price_cents": 4462, + "units": 4, + "vendor": "V4" + }, + "IV-8713-4-1": { + "date": "2025-03-09", + "po": "PO4", + "state": "review", + "unit_price_cents": 21709, + "units": 20, + "vendor": "V0" + }, + "IV-8718-1-1": { + "date": "2025-02-12", + "po": "PO1", + "state": "void", + "unit_price_cents": 1589, + "units": 9, + "vendor": "V0" + }, + "IV-8791-3-3": { + "date": "2025-02-19", + "po": "PO3", + "state": "disputed", + "unit_price_cents": 4498, + "units": 24, + "vendor": "V4" + }, + "IV-9174-5-1": { + "date": "2025-02-21", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 10445, + "units": 11, + "vendor": "Unknown" + }, + "IV-9833-2-2": { + "date": "2025-02-22", + "po": "PO2", + "state": "void", + "unit_price_cents": 6782, + "units": 18, + "vendor": "V4" + }, + "IV-9850-2-3": { + "date": "2025-02-24", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 5476, + "units": 8, + "vendor": "V4" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 12319, + "vendor": "V1" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 1916, + "vendor": "V0" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 5459, + "vendor": "V4" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 4462, + "vendor": "V4" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 19592, + "vendor": "V0" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 8760, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 15574, + "vendor": "V3" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-3928-0-1": { + "invoice": "IV-3928-0-1", + "issues": [ + "price", + "units" + ], + "po": "PO0" + }, + "case-IV-4497-4-3": { + "invoice": "IV-4497-4-3", + "issues": [ + "price", + "units" + ], + "po": "PO4" + }, + "case-IV-8791-3-3": { + "invoice": "IV-8791-3-3", + "issues": [ + "price" + ], + "po": "PO3" + }, + "case-IV-9174-5-1": { + "invoice": "IV-9174-5-1", + "issues": [ + "vendor", + "price" + ], + "po": "PO5" + }, + "case-IV-9850-2-3": { + "invoice": "IV-9850-2-3", + "issues": [ + "price", + "units" + ], + "po": "PO2" + } + }, + "vendors": { + "V0": { + "net_days": 21 + }, + "V1": { + "net_days": 21 + }, + "V2": { + "net_days": 21 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-023/tests/test.sh b/tasks/autom-supplier-invoice-match-023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-023/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-023/tests/world.json b/tasks/autom-supplier-invoice-match-023/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..08f0a19de220dff2f0673189df50f770f94756f6 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-023/tests/world.json @@ -0,0 +1,454 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 1 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 2 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 6 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 4 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 5 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 3 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 2 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-03-07", + "po": "PO0", + "state": "accepted", + "units": 19 + }, + "GI-0-1": { + "date": "2025-03-12", + "po": "PO0", + "state": "accepted", + "units": 23 + }, + "GI-0-2": { + "date": "2025-03-12", + "po": "PO0", + "state": "accepted", + "units": 13 + }, + "GI-0-3": { + "date": "2025-03-01", + "po": "PO0", + "state": "quarantine", + "units": 26 + }, + "GI-1-0": { + "date": "2025-03-07", + "po": "PO1", + "state": "accepted", + "units": 28 + }, + "GI-1-1": { + "date": "2025-03-04", + "po": "PO1", + "state": "quarantine", + "units": 28 + }, + "GI-1-2": { + "date": "2025-02-13", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-1-3": { + "date": "2025-02-17", + "po": "PO1", + "state": "quarantine", + "units": 22 + }, + "GI-2-0": { + "date": "2025-03-07", + "po": "PO2", + "state": "accepted", + "units": 22 + }, + "GI-2-1": { + "date": "2025-02-25", + "po": "PO2", + "state": "quarantine", + "units": 15 + }, + "GI-2-2": { + "date": "2025-03-12", + "po": "PO2", + "state": "quarantine", + "units": 20 + }, + "GI-2-3": { + "date": "2025-03-05", + "po": "PO2", + "state": "quarantine", + "units": 22 + }, + "GI-3-0": { + "date": "2025-03-07", + "po": "PO3", + "state": "accepted", + "units": 22 + }, + "GI-3-1": { + "date": "2025-02-19", + "po": "PO3", + "state": "quarantine", + "units": 12 + }, + "GI-3-2": { + "date": "2025-02-17", + "po": "PO3", + "state": "quarantine", + "units": 20 + }, + "GI-3-3": { + "date": "2025-02-15", + "po": "PO3", + "state": "accepted", + "units": 16 + }, + "GI-4-0": { + "date": "2025-03-07", + "po": "PO4", + "state": "accepted", + "units": 13 + }, + "GI-4-1": { + "date": "2025-02-13", + "po": "PO4", + "state": "quarantine", + "units": 23 + }, + "GI-4-2": { + "date": "2025-03-03", + "po": "PO4", + "state": "accepted", + "units": 20 + }, + "GI-4-3": { + "date": "2025-02-21", + "po": "PO4", + "state": "quarantine", + "units": 21 + }, + "GI-5-0": { + "date": "2025-03-07", + "po": "PO5", + "state": "accepted", + "units": 25 + }, + "GI-5-1": { + "date": "2025-03-08", + "po": "PO5", + "state": "quarantine", + "units": 21 + }, + "GI-5-2": { + "date": "2025-02-18", + "po": "PO5", + "state": "quarantine", + "units": 27 + }, + "GI-5-3": { + "date": "2025-02-21", + "po": "PO5", + "state": "accepted", + "units": 13 + }, + "GI-6-0": { + "date": "2025-03-07", + "po": "PO6", + "state": "accepted", + "units": 19 + }, + "GI-6-1": { + "date": "2025-02-27", + "po": "PO6", + "state": "accepted", + "units": 16 + }, + "GI-6-2": { + "date": "2025-02-16", + "po": "PO6", + "state": "quarantine", + "units": 21 + }, + "GI-6-3": { + "date": "2025-02-13", + "po": "PO6", + "state": "quarantine", + "units": 15 + } + }, + "invoice_inbox": { + "IV-1157-2-0": { + "date": "2025-02-15", + "po": "PO2", + "state": "review", + "unit_price_cents": 5459, + "units": 14, + "vendor": "V4" + }, + "IV-1358-6-1": { + "date": "2025-02-24", + "po": "PO6", + "state": "review", + "unit_price_cents": 15422, + "units": 13, + "vendor": "Unknown" + }, + "IV-2106-3-1": { + "date": "2025-03-01", + "po": "PO3", + "state": "void", + "unit_price_cents": 5950, + "units": 9, + "vendor": "V4" + }, + "IV-2216-6-0": { + "date": "2025-02-15", + "po": "PO6", + "state": "review", + "unit_price_cents": 15574, + "units": 18, + "vendor": "V3" + }, + "IV-2536-5-0": { + "date": "2025-02-15", + "po": "PO5", + "state": "review", + "unit_price_cents": 8760, + "units": 13, + "vendor": "V0" + }, + "IV-3399-5-2": { + "date": "2025-03-01", + "po": "PO5", + "state": "void", + "unit_price_cents": 10909, + "units": 25, + "vendor": "V0" + }, + "IV-3524-3-2": { + "date": "2025-02-14", + "po": "PO3", + "state": "review", + "unit_price_cents": 6413, + "units": 14, + "vendor": "Unknown" + }, + "IV-3827-6-2": { + "date": "2025-02-20", + "po": "PO6", + "state": "review", + "unit_price_cents": 15640, + "units": 15, + "vendor": "V3" + }, + "IV-3928-0-1": { + "date": "2025-02-15", + "po": "PO0", + "state": "review", + "unit_price_cents": 13953, + "units": 20, + "vendor": "V1" + }, + "IV-4497-4-3": { + "date": "2025-03-05", + "po": "PO4", + "state": "review", + "unit_price_cents": 20741, + "units": 18, + "vendor": "V0" + }, + "IV-4593-2-1": { + "date": "2025-03-04", + "po": "PO2", + "state": "void", + "unit_price_cents": 5085, + "units": 14, + "vendor": "V4" + }, + "IV-4835-1-0": { + "date": "2025-02-15", + "po": "PO1", + "state": "review", + "unit_price_cents": 1916, + "units": 22, + "vendor": "V0" + }, + "IV-6332-4-0": { + "date": "2025-02-15", + "po": "PO4", + "state": "review", + "unit_price_cents": 19592, + "units": 20, + "vendor": "V0" + }, + "IV-6422-4-2": { + "date": "2025-03-09", + "po": "PO4", + "state": "void", + "unit_price_cents": 20212, + "units": 9, + "vendor": "Unknown" + }, + "IV-7380-5-3": { + "date": "2025-02-10", + "po": "PO5", + "state": "review", + "unit_price_cents": 9218, + "units": 23, + "vendor": "V0" + }, + "IV-7930-0-0": { + "date": "2025-02-15", + "po": "PO0", + "state": "review", + "unit_price_cents": 12319, + "units": 1, + "vendor": "V1" + }, + "IV-8608-3-0": { + "date": "2025-02-15", + "po": "PO3", + "state": "review", + "unit_price_cents": 4462, + "units": 4, + "vendor": "V4" + }, + "IV-8713-4-1": { + "date": "2025-03-09", + "po": "PO4", + "state": "review", + "unit_price_cents": 21709, + "units": 20, + "vendor": "V0" + }, + "IV-8718-1-1": { + "date": "2025-02-12", + "po": "PO1", + "state": "void", + "unit_price_cents": 1589, + "units": 9, + "vendor": "V0" + }, + "IV-8791-3-3": { + "date": "2025-02-19", + "po": "PO3", + "state": "review", + "unit_price_cents": 4498, + "units": 24, + "vendor": "V4" + }, + "IV-9174-5-1": { + "date": "2025-02-21", + "po": "PO5", + "state": "review", + "unit_price_cents": 10445, + "units": 11, + "vendor": "Unknown" + }, + "IV-9833-2-2": { + "date": "2025-02-22", + "po": "PO2", + "state": "void", + "unit_price_cents": 6782, + "units": 18, + "vendor": "V4" + }, + "IV-9850-2-3": { + "date": "2025-02-24", + "po": "PO2", + "state": "review", + "unit_price_cents": 5476, + "units": 8, + "vendor": "V4" + } + }, + "purchase_orders": { + "PO0": { + "unit": "South", + "unit_price_cents": 12319, + "vendor": "V1" + }, + "PO1": { + "unit": "South", + "unit_price_cents": 1916, + "vendor": "V0" + }, + "PO2": { + "unit": "South", + "unit_price_cents": 5459, + "vendor": "V4" + }, + "PO3": { + "unit": "South", + "unit_price_cents": 4462, + "vendor": "V4" + }, + "PO4": { + "unit": "South", + "unit_price_cents": 19592, + "vendor": "V0" + }, + "PO5": { + "unit": "South", + "unit_price_cents": 8760, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 15574, + "vendor": "V3" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 21 + }, + "V1": { + "net_days": 21 + }, + "V2": { + "net_days": 21 + }, + "V3": { + "net_days": 45 + }, + "V4": { + "net_days": 21 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-023/tests/world_check.py b/tasks/autom-supplier-invoice-match-023/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-023/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-023/validation/openenv.json b/tasks/autom-supplier-invoice-match-023/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-023/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-024/environment/inputs/apps.py b/tasks/autom-supplier-invoice-match-024/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-024/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-024/environment/inputs/world.json b/tasks/autom-supplier-invoice-match-024/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..5fb6900a487d9884185078f1c34734f85939001d --- /dev/null +++ b/tasks/autom-supplier-invoice-match-024/environment/inputs/world.json @@ -0,0 +1,438 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 8 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 2 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 1 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 4 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 1 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 8 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-03-30", + "po": "PO0", + "state": "accepted", + "units": 22 + }, + "GI-0-1": { + "date": "2025-03-14", + "po": "PO0", + "state": "quarantine", + "units": 24 + }, + "GI-0-2": { + "date": "2025-03-14", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-3": { + "date": "2025-03-24", + "po": "PO0", + "state": "quarantine", + "units": 27 + }, + "GI-1-0": { + "date": "2025-03-30", + "po": "PO1", + "state": "accepted", + "units": 26 + }, + "GI-1-1": { + "date": "2025-04-05", + "po": "PO1", + "state": "accepted", + "units": 25 + }, + "GI-1-2": { + "date": "2025-03-12", + "po": "PO1", + "state": "quarantine", + "units": 23 + }, + "GI-1-3": { + "date": "2025-03-11", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-2-0": { + "date": "2025-03-30", + "po": "PO2", + "state": "accepted", + "units": 13 + }, + "GI-2-1": { + "date": "2025-03-29", + "po": "PO2", + "state": "quarantine", + "units": 21 + }, + "GI-2-2": { + "date": "2025-03-20", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-2-3": { + "date": "2025-03-25", + "po": "PO2", + "state": "quarantine", + "units": 24 + }, + "GI-3-0": { + "date": "2025-03-30", + "po": "PO3", + "state": "accepted", + "units": 14 + }, + "GI-3-1": { + "date": "2025-03-24", + "po": "PO3", + "state": "accepted", + "units": 28 + }, + "GI-3-2": { + "date": "2025-03-22", + "po": "PO3", + "state": "accepted", + "units": 14 + }, + "GI-3-3": { + "date": "2025-03-10", + "po": "PO3", + "state": "accepted", + "units": 21 + }, + "GI-4-0": { + "date": "2025-03-30", + "po": "PO4", + "state": "accepted", + "units": 14 + }, + "GI-4-1": { + "date": "2025-03-10", + "po": "PO4", + "state": "quarantine", + "units": 13 + }, + "GI-4-2": { + "date": "2025-03-11", + "po": "PO4", + "state": "accepted", + "units": 19 + }, + "GI-4-3": { + "date": "2025-03-13", + "po": "PO4", + "state": "quarantine", + "units": 23 + }, + "GI-5-0": { + "date": "2025-03-30", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-1": { + "date": "2025-03-19", + "po": "PO5", + "state": "quarantine", + "units": 23 + }, + "GI-5-2": { + "date": "2025-03-31", + "po": "PO5", + "state": "quarantine", + "units": 17 + }, + "GI-5-3": { + "date": "2025-03-23", + "po": "PO5", + "state": "quarantine", + "units": 14 + }, + "GI-6-0": { + "date": "2025-03-30", + "po": "PO6", + "state": "accepted", + "units": 20 + }, + "GI-6-1": { + "date": "2025-03-18", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-2": { + "date": "2025-03-30", + "po": "PO6", + "state": "quarantine", + "units": 13 + }, + "GI-6-3": { + "date": "2025-03-31", + "po": "PO6", + "state": "quarantine", + "units": 17 + } + }, + "invoice_inbox": { + "IV-1094-2-1": { + "date": "2025-03-27", + "po": "PO2", + "state": "review", + "unit_price_cents": 6827, + "units": 10, + "vendor": "V2" + }, + "IV-1105-1-2": { + "date": "2025-03-30", + "po": "PO1", + "state": "void", + "unit_price_cents": 21702, + "units": 25, + "vendor": "V2" + }, + "IV-1437-4-0": { + "date": "2025-03-17", + "po": "PO4", + "state": "review", + "unit_price_cents": 8994, + "units": 21, + "vendor": "V1" + }, + "IV-1501-0-0": { + "date": "2025-03-17", + "po": "PO0", + "state": "review", + "unit_price_cents": 5526, + "units": 1, + "vendor": "V1" + }, + "IV-2094-3-1": { + "date": "2025-03-16", + "po": "PO3", + "state": "review", + "unit_price_cents": 5928, + "units": 24, + "vendor": "V2" + }, + "IV-2439-1-0": { + "date": "2025-03-17", + "po": "PO1", + "state": "review", + "unit_price_cents": 19657, + "units": 10, + "vendor": "V2" + }, + "IV-3365-5-2": { + "date": "2025-03-17", + "po": "PO5", + "state": "review", + "unit_price_cents": 1981, + "units": 25, + "vendor": "Unknown" + }, + "IV-3406-4-3": { + "date": "2025-03-24", + "po": "PO4", + "state": "void", + "unit_price_cents": 10955, + "units": 18, + "vendor": "V1" + }, + "IV-3779-4-1": { + "date": "2025-03-19", + "po": "PO4", + "state": "void", + "unit_price_cents": 8726, + "units": 14, + "vendor": "V1" + }, + "IV-5255-4-2": { + "date": "2025-03-21", + "po": "PO4", + "state": "review", + "unit_price_cents": 9898, + "units": 23, + "vendor": "Unknown" + }, + "IV-5545-3-0": { + "date": "2025-03-17", + "po": "PO3", + "state": "review", + "unit_price_cents": 5483, + "units": 25, + "vendor": "V2" + }, + "IV-5578-0-1": { + "date": "2025-03-30", + "po": "PO0", + "state": "review", + "unit_price_cents": 6960, + "units": 7, + "vendor": "Unknown" + }, + "IV-6139-2-0": { + "date": "2025-03-17", + "po": "PO2", + "state": "review", + "unit_price_cents": 4903, + "units": 5, + "vendor": "V2" + }, + "IV-6331-6-0": { + "date": "2025-03-17", + "po": "PO6", + "state": "review", + "unit_price_cents": 9397, + "units": 12, + "vendor": "V1" + }, + "IV-6394-5-0": { + "date": "2025-03-17", + "po": "PO5", + "state": "review", + "unit_price_cents": 1840, + "units": 25, + "vendor": "V0" + }, + "IV-6475-6-1": { + "date": "2025-03-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 9442, + "units": 8, + "vendor": "V1" + }, + "IV-6760-1-1": { + "date": "2025-03-26", + "po": "PO1", + "state": "review", + "unit_price_cents": 19486, + "units": 3, + "vendor": "V2" + }, + "IV-7645-0-3": { + "date": "2025-03-24", + "po": "PO0", + "state": "review", + "unit_price_cents": 7272, + "units": 16, + "vendor": "V1" + }, + "IV-8088-1-3": { + "date": "2025-03-28", + "po": "PO1", + "state": "review", + "unit_price_cents": 21063, + "units": 7, + "vendor": "V2" + }, + "IV-8886-0-2": { + "date": "2025-03-11", + "po": "PO0", + "state": "void", + "unit_price_cents": 5395, + "units": 25, + "vendor": "V1" + }, + "IV-9338-5-1": { + "date": "2025-03-24", + "po": "PO5", + "state": "review", + "unit_price_cents": 2042, + "units": 17, + "vendor": "Unknown" + } + }, + "purchase_orders": { + "PO0": { + "unit": "North", + "unit_price_cents": 5526, + "vendor": "V1" + }, + "PO1": { + "unit": "North", + "unit_price_cents": 19657, + "vendor": "V2" + }, + "PO2": { + "unit": "North", + "unit_price_cents": 4903, + "vendor": "V2" + }, + "PO3": { + "unit": "North", + "unit_price_cents": 5483, + "vendor": "V2" + }, + "PO4": { + "unit": "North", + "unit_price_cents": 8994, + "vendor": "V1" + }, + "PO5": { + "unit": "North", + "unit_price_cents": 1840, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 9397, + "vendor": "V1" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 15 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 21 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-024/instruction.md b/tasks/autom-supplier-invoice-match-024/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..31cd5816e4ca078f3f8ce547d083144a10650209 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-024/instruction.md @@ -0,0 +1,17 @@ +Close the invoice matching queue for purchasing unit North at 2025-03-31. Handle invoices in review attached to that unit's purchase orders, invoice dates 2025-03-17 through 2025-03-31 inclusive. Process by invoice date ascending, then invoice ID ascending. Available units per PO equal units on accepted goods receipts dated on or before cutoff, minus previously posted units and any units successfully matched earlier in this run. + +Match the invoice vendor exactly against the purchase order. A unit price above PO price is acceptable only up to 300 basis points above PO price (10,000 basis points = 100%; compare exactly, before rounding). Lower prices are acceptable. The invoice quantity must fit the available units in full. If any tests fail, update the invoice state to `disputed`, consume zero units, and create supplier_cases record `case-` with `invoice`, `po` and the list `issues` containing every failing check in vendor, price, units order; use those lowercase strings. + +For a match update invoice state to `posted` and create ap_postings record `book-` with `invoice`, `po`, `units`, `status=posted`, integer `amount_cents` equal to invoiced quantity times invoiced unit price, and ISO date `due`. Count the vendor's net_days calendar days from the invoice date, then roll Saturday or Sunday forward to Monday. Preserve all other fields and records. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/autom-supplier-invoice-match-024/solution/files/actions.jsonl b/tasks/autom-supplier-invoice-match-024/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..64407051b647ace478c8f528208516feb9627509 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-024/solution/files/actions.jsonl @@ -0,0 +1,28 @@ +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-1501-0-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-5578-0-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-7645-0-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-2439-1-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6760-1-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-8088-1-3", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6139-2-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-1094-2-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-5545-3-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-1437-4-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-5255-4-2", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "posted"}, "id": "IV-6394-5-0", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-9338-5-1", "op": "update"} +{"app": "invoice_inbox", "fields": {"state": "disputed"}, "id": "IV-3365-5-2", "op": "update"} +{"app": "ap_postings", "fields": {"amount_cents": 188874, "due": "2025-04-01", "invoice": "IV-1437-4-0", "po": "PO4", "status": "posted", "units": 21}, "id": "book-IV-1437-4-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 5526, "due": "2025-04-01", "invoice": "IV-1501-0-0", "po": "PO0", "status": "posted", "units": 1}, "id": "book-IV-1501-0-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 196570, "due": "2025-04-16", "invoice": "IV-2439-1-0", "po": "PO1", "status": "posted", "units": 10}, "id": "book-IV-2439-1-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 137075, "due": "2025-04-16", "invoice": "IV-5545-3-0", "po": "PO3", "status": "posted", "units": 25}, "id": "book-IV-5545-3-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 24515, "due": "2025-04-16", "invoice": "IV-6139-2-0", "po": "PO2", "status": "posted", "units": 5}, "id": "book-IV-6139-2-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 46000, "due": "2025-04-01", "invoice": "IV-6394-5-0", "po": "PO5", "status": "posted", "units": 25}, "id": "book-IV-6394-5-0", "op": "create"} +{"app": "ap_postings", "fields": {"amount_cents": 58458, "due": "2025-04-25", "invoice": "IV-6760-1-1", "po": "PO1", "status": "posted", "units": 3}, "id": "book-IV-6760-1-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-3365-5-2", "issues": ["vendor", "price"], "po": "PO5"}, "id": "case-IV-3365-5-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-5255-4-2", "issues": ["vendor", "price", "units"], "po": "PO4"}, "id": "case-IV-5255-4-2", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-7645-0-3", "issues": ["price"], "po": "PO0"}, "id": "case-IV-7645-0-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-9338-5-1", "issues": ["vendor", "price", "units"], "po": "PO5"}, "id": "case-IV-9338-5-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-1094-2-1", "issues": ["price", "units"], "po": "PO2"}, "id": "case-IV-1094-2-1", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-8088-1-3", "issues": ["price"], "po": "PO1"}, "id": "case-IV-8088-1-3", "op": "create"} +{"app": "supplier_cases", "fields": {"invoice": "IV-5578-0-1", "issues": ["vendor", "price"], "po": "PO0"}, "id": "case-IV-5578-0-1", "op": "create"} diff --git a/tasks/autom-supplier-invoice-match-024/solution/solve.sh b/tasks/autom-supplier-invoice-match-024/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-024/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/autom-supplier-invoice-match-024/task.toml b/tasks/autom-supplier-invoice-match-024/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09ad89eb9aa8fb440c0a495deefe892fa425506a --- /dev/null +++ b/tasks/autom-supplier-invoice-match-024/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/autom-supplier-invoice-match-024" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "finance"] +dataset = "Original simulated workflows" +job = "finance" +seed = 24 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "autom-supplier-invoice-match-024" +template_family = "automation:supplier-invoice-match" +workflow_template = "supplier-invoice-match" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/autom-supplier-invoice-match-024/tests/expected.json b/tasks/autom-supplier-invoice-match-024/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-024/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-024/tests/grade.py b/tasks/autom-supplier-invoice-match-024/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/autom-supplier-invoice-match-024/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/autom-supplier-invoice-match-024/tests/replay.py b/tasks/autom-supplier-invoice-match-024/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/autom-supplier-invoice-match-024/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/autom-supplier-invoice-match-024/tests/target.json b/tasks/autom-supplier-invoice-match-024/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..d5821df73ec5dd88176b944b9a4239e024eaa0ac --- /dev/null +++ b/tasks/autom-supplier-invoice-match-024/tests/target.json @@ -0,0 +1,550 @@ +{ + "ap_postings": { + "book-IV-1437-4-0": { + "amount_cents": 188874, + "due": "2025-04-01", + "invoice": "IV-1437-4-0", + "po": "PO4", + "status": "posted", + "units": 21 + }, + "book-IV-1501-0-0": { + "amount_cents": 5526, + "due": "2025-04-01", + "invoice": "IV-1501-0-0", + "po": "PO0", + "status": "posted", + "units": 1 + }, + "book-IV-2439-1-0": { + "amount_cents": 196570, + "due": "2025-04-16", + "invoice": "IV-2439-1-0", + "po": "PO1", + "status": "posted", + "units": 10 + }, + "book-IV-5545-3-0": { + "amount_cents": 137075, + "due": "2025-04-16", + "invoice": "IV-5545-3-0", + "po": "PO3", + "status": "posted", + "units": 25 + }, + "book-IV-6139-2-0": { + "amount_cents": 24515, + "due": "2025-04-16", + "invoice": "IV-6139-2-0", + "po": "PO2", + "status": "posted", + "units": 5 + }, + "book-IV-6394-5-0": { + "amount_cents": 46000, + "due": "2025-04-01", + "invoice": "IV-6394-5-0", + "po": "PO5", + "status": "posted", + "units": 25 + }, + "book-IV-6760-1-1": { + "amount_cents": 58458, + "due": "2025-04-25", + "invoice": "IV-6760-1-1", + "po": "PO1", + "status": "posted", + "units": 3 + }, + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 8 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 2 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 1 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 4 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 1 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 8 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-03-30", + "po": "PO0", + "state": "accepted", + "units": 22 + }, + "GI-0-1": { + "date": "2025-03-14", + "po": "PO0", + "state": "quarantine", + "units": 24 + }, + "GI-0-2": { + "date": "2025-03-14", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-3": { + "date": "2025-03-24", + "po": "PO0", + "state": "quarantine", + "units": 27 + }, + "GI-1-0": { + "date": "2025-03-30", + "po": "PO1", + "state": "accepted", + "units": 26 + }, + "GI-1-1": { + "date": "2025-04-05", + "po": "PO1", + "state": "accepted", + "units": 25 + }, + "GI-1-2": { + "date": "2025-03-12", + "po": "PO1", + "state": "quarantine", + "units": 23 + }, + "GI-1-3": { + "date": "2025-03-11", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-2-0": { + "date": "2025-03-30", + "po": "PO2", + "state": "accepted", + "units": 13 + }, + "GI-2-1": { + "date": "2025-03-29", + "po": "PO2", + "state": "quarantine", + "units": 21 + }, + "GI-2-2": { + "date": "2025-03-20", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-2-3": { + "date": "2025-03-25", + "po": "PO2", + "state": "quarantine", + "units": 24 + }, + "GI-3-0": { + "date": "2025-03-30", + "po": "PO3", + "state": "accepted", + "units": 14 + }, + "GI-3-1": { + "date": "2025-03-24", + "po": "PO3", + "state": "accepted", + "units": 28 + }, + "GI-3-2": { + "date": "2025-03-22", + "po": "PO3", + "state": "accepted", + "units": 14 + }, + "GI-3-3": { + "date": "2025-03-10", + "po": "PO3", + "state": "accepted", + "units": 21 + }, + "GI-4-0": { + "date": "2025-03-30", + "po": "PO4", + "state": "accepted", + "units": 14 + }, + "GI-4-1": { + "date": "2025-03-10", + "po": "PO4", + "state": "quarantine", + "units": 13 + }, + "GI-4-2": { + "date": "2025-03-11", + "po": "PO4", + "state": "accepted", + "units": 19 + }, + "GI-4-3": { + "date": "2025-03-13", + "po": "PO4", + "state": "quarantine", + "units": 23 + }, + "GI-5-0": { + "date": "2025-03-30", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-1": { + "date": "2025-03-19", + "po": "PO5", + "state": "quarantine", + "units": 23 + }, + "GI-5-2": { + "date": "2025-03-31", + "po": "PO5", + "state": "quarantine", + "units": 17 + }, + "GI-5-3": { + "date": "2025-03-23", + "po": "PO5", + "state": "quarantine", + "units": 14 + }, + "GI-6-0": { + "date": "2025-03-30", + "po": "PO6", + "state": "accepted", + "units": 20 + }, + "GI-6-1": { + "date": "2025-03-18", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-2": { + "date": "2025-03-30", + "po": "PO6", + "state": "quarantine", + "units": 13 + }, + "GI-6-3": { + "date": "2025-03-31", + "po": "PO6", + "state": "quarantine", + "units": 17 + } + }, + "invoice_inbox": { + "IV-1094-2-1": { + "date": "2025-03-27", + "po": "PO2", + "state": "disputed", + "unit_price_cents": 6827, + "units": 10, + "vendor": "V2" + }, + "IV-1105-1-2": { + "date": "2025-03-30", + "po": "PO1", + "state": "void", + "unit_price_cents": 21702, + "units": 25, + "vendor": "V2" + }, + "IV-1437-4-0": { + "date": "2025-03-17", + "po": "PO4", + "state": "posted", + "unit_price_cents": 8994, + "units": 21, + "vendor": "V1" + }, + "IV-1501-0-0": { + "date": "2025-03-17", + "po": "PO0", + "state": "posted", + "unit_price_cents": 5526, + "units": 1, + "vendor": "V1" + }, + "IV-2094-3-1": { + "date": "2025-03-16", + "po": "PO3", + "state": "review", + "unit_price_cents": 5928, + "units": 24, + "vendor": "V2" + }, + "IV-2439-1-0": { + "date": "2025-03-17", + "po": "PO1", + "state": "posted", + "unit_price_cents": 19657, + "units": 10, + "vendor": "V2" + }, + "IV-3365-5-2": { + "date": "2025-03-17", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 1981, + "units": 25, + "vendor": "Unknown" + }, + "IV-3406-4-3": { + "date": "2025-03-24", + "po": "PO4", + "state": "void", + "unit_price_cents": 10955, + "units": 18, + "vendor": "V1" + }, + "IV-3779-4-1": { + "date": "2025-03-19", + "po": "PO4", + "state": "void", + "unit_price_cents": 8726, + "units": 14, + "vendor": "V1" + }, + "IV-5255-4-2": { + "date": "2025-03-21", + "po": "PO4", + "state": "disputed", + "unit_price_cents": 9898, + "units": 23, + "vendor": "Unknown" + }, + "IV-5545-3-0": { + "date": "2025-03-17", + "po": "PO3", + "state": "posted", + "unit_price_cents": 5483, + "units": 25, + "vendor": "V2" + }, + "IV-5578-0-1": { + "date": "2025-03-30", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 6960, + "units": 7, + "vendor": "Unknown" + }, + "IV-6139-2-0": { + "date": "2025-03-17", + "po": "PO2", + "state": "posted", + "unit_price_cents": 4903, + "units": 5, + "vendor": "V2" + }, + "IV-6331-6-0": { + "date": "2025-03-17", + "po": "PO6", + "state": "review", + "unit_price_cents": 9397, + "units": 12, + "vendor": "V1" + }, + "IV-6394-5-0": { + "date": "2025-03-17", + "po": "PO5", + "state": "posted", + "unit_price_cents": 1840, + "units": 25, + "vendor": "V0" + }, + "IV-6475-6-1": { + "date": "2025-03-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 9442, + "units": 8, + "vendor": "V1" + }, + "IV-6760-1-1": { + "date": "2025-03-26", + "po": "PO1", + "state": "posted", + "unit_price_cents": 19486, + "units": 3, + "vendor": "V2" + }, + "IV-7645-0-3": { + "date": "2025-03-24", + "po": "PO0", + "state": "disputed", + "unit_price_cents": 7272, + "units": 16, + "vendor": "V1" + }, + "IV-8088-1-3": { + "date": "2025-03-28", + "po": "PO1", + "state": "disputed", + "unit_price_cents": 21063, + "units": 7, + "vendor": "V2" + }, + "IV-8886-0-2": { + "date": "2025-03-11", + "po": "PO0", + "state": "void", + "unit_price_cents": 5395, + "units": 25, + "vendor": "V1" + }, + "IV-9338-5-1": { + "date": "2025-03-24", + "po": "PO5", + "state": "disputed", + "unit_price_cents": 2042, + "units": 17, + "vendor": "Unknown" + } + }, + "purchase_orders": { + "PO0": { + "unit": "North", + "unit_price_cents": 5526, + "vendor": "V1" + }, + "PO1": { + "unit": "North", + "unit_price_cents": 19657, + "vendor": "V2" + }, + "PO2": { + "unit": "North", + "unit_price_cents": 4903, + "vendor": "V2" + }, + "PO3": { + "unit": "North", + "unit_price_cents": 5483, + "vendor": "V2" + }, + "PO4": { + "unit": "North", + "unit_price_cents": 8994, + "vendor": "V1" + }, + "PO5": { + "unit": "North", + "unit_price_cents": 1840, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 9397, + "vendor": "V1" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + }, + "case-IV-1094-2-1": { + "invoice": "IV-1094-2-1", + "issues": [ + "price", + "units" + ], + "po": "PO2" + }, + "case-IV-3365-5-2": { + "invoice": "IV-3365-5-2", + "issues": [ + "vendor", + "price" + ], + "po": "PO5" + }, + "case-IV-5255-4-2": { + "invoice": "IV-5255-4-2", + "issues": [ + "vendor", + "price", + "units" + ], + "po": "PO4" + }, + "case-IV-5578-0-1": { + "invoice": "IV-5578-0-1", + "issues": [ + "vendor", + "price" + ], + "po": "PO0" + }, + "case-IV-7645-0-3": { + "invoice": "IV-7645-0-3", + "issues": [ + "price" + ], + "po": "PO0" + }, + "case-IV-8088-1-3": { + "invoice": "IV-8088-1-3", + "issues": [ + "price" + ], + "po": "PO1" + }, + "case-IV-9338-5-1": { + "invoice": "IV-9338-5-1", + "issues": [ + "vendor", + "price", + "units" + ], + "po": "PO5" + } + }, + "vendors": { + "V0": { + "net_days": 15 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 21 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-024/tests/test.sh b/tasks/autom-supplier-invoice-match-024/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-024/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/autom-supplier-invoice-match-024/tests/world.json b/tasks/autom-supplier-invoice-match-024/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..5fb6900a487d9884185078f1c34734f85939001d --- /dev/null +++ b/tasks/autom-supplier-invoice-match-024/tests/world.json @@ -0,0 +1,438 @@ +{ + "ap_postings": { + "booked-PO0": { + "po": "PO0", + "status": "posted", + "units": 8 + }, + "booked-PO1": { + "po": "PO1", + "status": "posted", + "units": 2 + }, + "booked-PO2": { + "po": "PO2", + "status": "posted", + "units": 1 + }, + "booked-PO3": { + "po": "PO3", + "status": "posted", + "units": 1 + }, + "booked-PO4": { + "po": "PO4", + "status": "posted", + "units": 4 + }, + "booked-PO5": { + "po": "PO5", + "status": "posted", + "units": 1 + }, + "booked-PO6": { + "po": "PO6", + "status": "posted", + "units": 8 + } + }, + "goods_receipts": { + "GI-0-0": { + "date": "2025-03-30", + "po": "PO0", + "state": "accepted", + "units": 22 + }, + "GI-0-1": { + "date": "2025-03-14", + "po": "PO0", + "state": "quarantine", + "units": 24 + }, + "GI-0-2": { + "date": "2025-03-14", + "po": "PO0", + "state": "accepted", + "units": 20 + }, + "GI-0-3": { + "date": "2025-03-24", + "po": "PO0", + "state": "quarantine", + "units": 27 + }, + "GI-1-0": { + "date": "2025-03-30", + "po": "PO1", + "state": "accepted", + "units": 26 + }, + "GI-1-1": { + "date": "2025-04-05", + "po": "PO1", + "state": "accepted", + "units": 25 + }, + "GI-1-2": { + "date": "2025-03-12", + "po": "PO1", + "state": "quarantine", + "units": 23 + }, + "GI-1-3": { + "date": "2025-03-11", + "po": "PO1", + "state": "accepted", + "units": 12 + }, + "GI-2-0": { + "date": "2025-03-30", + "po": "PO2", + "state": "accepted", + "units": 13 + }, + "GI-2-1": { + "date": "2025-03-29", + "po": "PO2", + "state": "quarantine", + "units": 21 + }, + "GI-2-2": { + "date": "2025-03-20", + "po": "PO2", + "state": "quarantine", + "units": 12 + }, + "GI-2-3": { + "date": "2025-03-25", + "po": "PO2", + "state": "quarantine", + "units": 24 + }, + "GI-3-0": { + "date": "2025-03-30", + "po": "PO3", + "state": "accepted", + "units": 14 + }, + "GI-3-1": { + "date": "2025-03-24", + "po": "PO3", + "state": "accepted", + "units": 28 + }, + "GI-3-2": { + "date": "2025-03-22", + "po": "PO3", + "state": "accepted", + "units": 14 + }, + "GI-3-3": { + "date": "2025-03-10", + "po": "PO3", + "state": "accepted", + "units": 21 + }, + "GI-4-0": { + "date": "2025-03-30", + "po": "PO4", + "state": "accepted", + "units": 14 + }, + "GI-4-1": { + "date": "2025-03-10", + "po": "PO4", + "state": "quarantine", + "units": 13 + }, + "GI-4-2": { + "date": "2025-03-11", + "po": "PO4", + "state": "accepted", + "units": 19 + }, + "GI-4-3": { + "date": "2025-03-13", + "po": "PO4", + "state": "quarantine", + "units": 23 + }, + "GI-5-0": { + "date": "2025-03-30", + "po": "PO5", + "state": "accepted", + "units": 27 + }, + "GI-5-1": { + "date": "2025-03-19", + "po": "PO5", + "state": "quarantine", + "units": 23 + }, + "GI-5-2": { + "date": "2025-03-31", + "po": "PO5", + "state": "quarantine", + "units": 17 + }, + "GI-5-3": { + "date": "2025-03-23", + "po": "PO5", + "state": "quarantine", + "units": 14 + }, + "GI-6-0": { + "date": "2025-03-30", + "po": "PO6", + "state": "accepted", + "units": 20 + }, + "GI-6-1": { + "date": "2025-03-18", + "po": "PO6", + "state": "accepted", + "units": 28 + }, + "GI-6-2": { + "date": "2025-03-30", + "po": "PO6", + "state": "quarantine", + "units": 13 + }, + "GI-6-3": { + "date": "2025-03-31", + "po": "PO6", + "state": "quarantine", + "units": 17 + } + }, + "invoice_inbox": { + "IV-1094-2-1": { + "date": "2025-03-27", + "po": "PO2", + "state": "review", + "unit_price_cents": 6827, + "units": 10, + "vendor": "V2" + }, + "IV-1105-1-2": { + "date": "2025-03-30", + "po": "PO1", + "state": "void", + "unit_price_cents": 21702, + "units": 25, + "vendor": "V2" + }, + "IV-1437-4-0": { + "date": "2025-03-17", + "po": "PO4", + "state": "review", + "unit_price_cents": 8994, + "units": 21, + "vendor": "V1" + }, + "IV-1501-0-0": { + "date": "2025-03-17", + "po": "PO0", + "state": "review", + "unit_price_cents": 5526, + "units": 1, + "vendor": "V1" + }, + "IV-2094-3-1": { + "date": "2025-03-16", + "po": "PO3", + "state": "review", + "unit_price_cents": 5928, + "units": 24, + "vendor": "V2" + }, + "IV-2439-1-0": { + "date": "2025-03-17", + "po": "PO1", + "state": "review", + "unit_price_cents": 19657, + "units": 10, + "vendor": "V2" + }, + "IV-3365-5-2": { + "date": "2025-03-17", + "po": "PO5", + "state": "review", + "unit_price_cents": 1981, + "units": 25, + "vendor": "Unknown" + }, + "IV-3406-4-3": { + "date": "2025-03-24", + "po": "PO4", + "state": "void", + "unit_price_cents": 10955, + "units": 18, + "vendor": "V1" + }, + "IV-3779-4-1": { + "date": "2025-03-19", + "po": "PO4", + "state": "void", + "unit_price_cents": 8726, + "units": 14, + "vendor": "V1" + }, + "IV-5255-4-2": { + "date": "2025-03-21", + "po": "PO4", + "state": "review", + "unit_price_cents": 9898, + "units": 23, + "vendor": "Unknown" + }, + "IV-5545-3-0": { + "date": "2025-03-17", + "po": "PO3", + "state": "review", + "unit_price_cents": 5483, + "units": 25, + "vendor": "V2" + }, + "IV-5578-0-1": { + "date": "2025-03-30", + "po": "PO0", + "state": "review", + "unit_price_cents": 6960, + "units": 7, + "vendor": "Unknown" + }, + "IV-6139-2-0": { + "date": "2025-03-17", + "po": "PO2", + "state": "review", + "unit_price_cents": 4903, + "units": 5, + "vendor": "V2" + }, + "IV-6331-6-0": { + "date": "2025-03-17", + "po": "PO6", + "state": "review", + "unit_price_cents": 9397, + "units": 12, + "vendor": "V1" + }, + "IV-6394-5-0": { + "date": "2025-03-17", + "po": "PO5", + "state": "review", + "unit_price_cents": 1840, + "units": 25, + "vendor": "V0" + }, + "IV-6475-6-1": { + "date": "2025-03-12", + "po": "PO6", + "state": "review", + "unit_price_cents": 9442, + "units": 8, + "vendor": "V1" + }, + "IV-6760-1-1": { + "date": "2025-03-26", + "po": "PO1", + "state": "review", + "unit_price_cents": 19486, + "units": 3, + "vendor": "V2" + }, + "IV-7645-0-3": { + "date": "2025-03-24", + "po": "PO0", + "state": "review", + "unit_price_cents": 7272, + "units": 16, + "vendor": "V1" + }, + "IV-8088-1-3": { + "date": "2025-03-28", + "po": "PO1", + "state": "review", + "unit_price_cents": 21063, + "units": 7, + "vendor": "V2" + }, + "IV-8886-0-2": { + "date": "2025-03-11", + "po": "PO0", + "state": "void", + "unit_price_cents": 5395, + "units": 25, + "vendor": "V1" + }, + "IV-9338-5-1": { + "date": "2025-03-24", + "po": "PO5", + "state": "review", + "unit_price_cents": 2042, + "units": 17, + "vendor": "Unknown" + } + }, + "purchase_orders": { + "PO0": { + "unit": "North", + "unit_price_cents": 5526, + "vendor": "V1" + }, + "PO1": { + "unit": "North", + "unit_price_cents": 19657, + "vendor": "V2" + }, + "PO2": { + "unit": "North", + "unit_price_cents": 4903, + "vendor": "V2" + }, + "PO3": { + "unit": "North", + "unit_price_cents": 5483, + "vendor": "V2" + }, + "PO4": { + "unit": "North", + "unit_price_cents": 8994, + "vendor": "V1" + }, + "PO5": { + "unit": "North", + "unit_price_cents": 1840, + "vendor": "V0" + }, + "PO6": { + "unit": "Other", + "unit_price_cents": 9397, + "vendor": "V1" + } + }, + "supplier_cases": { + "PREEXISTING": { + "status": "investigating" + } + }, + "vendors": { + "V0": { + "net_days": 15 + }, + "V1": { + "net_days": 15 + }, + "V2": { + "net_days": 30 + }, + "V3": { + "net_days": 21 + }, + "V4": { + "net_days": 15 + } + } +} \ No newline at end of file diff --git a/tasks/autom-supplier-invoice-match-024/tests/world_check.py b/tasks/autom-supplier-invoice-match-024/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/autom-supplier-invoice-match-024/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/autom-supplier-invoice-match-024/validation/openenv.json b/tasks/autom-supplier-invoice-match-024/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4972aa192696511abccb7e39b14c83b0fc0ac126 --- /dev/null +++ b/tasks/autom-supplier-invoice-match-024/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "finance" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41801/environment/inputs/apps.py b/tasks/service-hr-certifications-41801/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41801/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41801/environment/inputs/world.json b/tasks/service-hr-certifications-41801/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..f71fc20d5195d186a7558c34e6f07e67b863f396 --- /dev/null +++ b/tasks/service-hr-certifications-41801/environment/inputs/world.json @@ -0,0 +1,121 @@ +{ + "certs": { + "R27040": { + "course": "privacy", + "expires_day": 262, + "person": "S55227", + "state": "active" + }, + "R31318": { + "course": "induction", + "expires_day": 261, + "person": "S14281", + "state": "active" + }, + "R41372": { + "course": "privacy", + "expires_day": 242, + "person": "S96425", + "state": "active" + }, + "R62911": { + "course": "privacy", + "expires_day": 269, + "person": "S37904", + "state": "active" + }, + "R66644": { + "course": "induction", + "expires_day": 238, + "person": "S67343", + "state": "active" + }, + "R67395": { + "course": "induction", + "expires_day": 240, + "person": "S34392", + "state": "active" + }, + "R74184": { + "course": "induction", + "expires_day": 260, + "person": "S41733", + "state": "active" + }, + "R78577": { + "course": "records", + "expires_day": 266, + "person": "S80107", + "state": "retired" + }, + "R79676": { + "course": "induction", + "expires_day": 242, + "person": "S54288", + "state": "active" + }, + "R83507": { + "course": "records", + "expires_day": 274, + "person": "S17826", + "state": "active" + }, + "R88229": { + "course": "records", + "expires_day": 264, + "person": "S33831", + "state": "active" + }, + "R93075": { + "course": "records", + "expires_day": 242, + "person": "S48117", + "state": "active" + } + }, + "leave": { + "S14281": { + "available_day": 267 + }, + "S17826": { + "available_day": 257 + }, + "S33831": { + "available_day": 267 + }, + "S34392": { + "available_day": 271 + }, + "S37904": { + "available_day": 267 + }, + "S41733": { + "available_day": 266 + }, + "S48117": { + "available_day": 244 + }, + "S54288": { + "available_day": 244 + }, + "S55227": { + "available_day": 266 + }, + "S67343": { + "available_day": 266 + }, + "S80107": { + "available_day": 264 + }, + "S96425": { + "available_day": 257 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 2, + "start_day": 267 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41801/instruction.md b/tasks/service-hr-certifications-41801/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ac4c86061f7dcc7cc59f093adb3410da4f196a3 --- /dev/null +++ b/tasks/service-hr-certifications-41801/instruction.md @@ -0,0 +1,13 @@ +Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew- in renewals with person, course and session set to renewal. Update the session's remaining seats. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/service-hr-certifications-41801/solution/files/actions.jsonl b/tasks/service-hr-certifications-41801/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d2779c1c96b618f3d05dea563337635d8cf8784a --- /dev/null +++ b/tasks/service-hr-certifications-41801/solution/files/actions.jsonl @@ -0,0 +1,12 @@ +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R79676", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R93075", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R74184", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R41372", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R27040", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R31318", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R88229", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R66644", "op": "update"} +{"app": "certs", "fields": {"state": "deferred"}, "id": "R67395", "op": "update"} +{"app": "renewals", "fields": {"course": "induction", "person": "S67343", "session": "renewal"}, "id": "renew-R66644", "op": "create"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S96425", "session": "renewal"}, "id": "renew-R41372", "op": "create"} +{"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"} diff --git a/tasks/service-hr-certifications-41801/solution/solve.sh b/tasks/service-hr-certifications-41801/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/service-hr-certifications-41801/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/service-hr-certifications-41801/task.toml b/tasks/service-hr-certifications-41801/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9032b6dbf0509922c07ce6726ddd50b7d85aee3c --- /dev/null +++ b/tasks/service-hr-certifications-41801/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/service-hr-certifications-41801" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"] +dataset = "Original simulated workflows" +job = "hr" +seed = 41801 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "service-hr-certifications-41801" +template_family = "automation:service-hr-certifications" +workflow_template = "service-hr-certifications" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/service-hr-certifications-41801/tests/expected.json b/tasks/service-hr-certifications-41801/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/service-hr-certifications-41801/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41801/tests/grade.py b/tasks/service-hr-certifications-41801/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/service-hr-certifications-41801/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/service-hr-certifications-41801/tests/replay.py b/tasks/service-hr-certifications-41801/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41801/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41801/tests/target.json b/tasks/service-hr-certifications-41801/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..bfb3e762f00704e1ea93faadb6c5589b4eba371f --- /dev/null +++ b/tasks/service-hr-certifications-41801/tests/target.json @@ -0,0 +1,132 @@ +{ + "certs": { + "R27040": { + "course": "privacy", + "expires_day": 262, + "person": "S55227", + "state": "waitlisted" + }, + "R31318": { + "course": "induction", + "expires_day": 261, + "person": "S14281", + "state": "waitlisted" + }, + "R41372": { + "course": "privacy", + "expires_day": 242, + "person": "S96425", + "state": "enrolled" + }, + "R62911": { + "course": "privacy", + "expires_day": 269, + "person": "S37904", + "state": "active" + }, + "R66644": { + "course": "induction", + "expires_day": 238, + "person": "S67343", + "state": "enrolled" + }, + "R67395": { + "course": "induction", + "expires_day": 240, + "person": "S34392", + "state": "deferred" + }, + "R74184": { + "course": "induction", + "expires_day": 260, + "person": "S41733", + "state": "waitlisted" + }, + "R78577": { + "course": "records", + "expires_day": 266, + "person": "S80107", + "state": "retired" + }, + "R79676": { + "course": "induction", + "expires_day": 242, + "person": "S54288", + "state": "waitlisted" + }, + "R83507": { + "course": "records", + "expires_day": 274, + "person": "S17826", + "state": "active" + }, + "R88229": { + "course": "records", + "expires_day": 264, + "person": "S33831", + "state": "waitlisted" + }, + "R93075": { + "course": "records", + "expires_day": 242, + "person": "S48117", + "state": "waitlisted" + } + }, + "leave": { + "S14281": { + "available_day": 267 + }, + "S17826": { + "available_day": 257 + }, + "S33831": { + "available_day": 267 + }, + "S34392": { + "available_day": 271 + }, + "S37904": { + "available_day": 267 + }, + "S41733": { + "available_day": 266 + }, + "S48117": { + "available_day": 244 + }, + "S54288": { + "available_day": 244 + }, + "S55227": { + "available_day": 266 + }, + "S67343": { + "available_day": 266 + }, + "S80107": { + "available_day": 264 + }, + "S96425": { + "available_day": 257 + } + }, + "renewals": { + "renew-R41372": { + "course": "privacy", + "person": "S96425", + "session": "renewal" + }, + "renew-R66644": { + "course": "induction", + "person": "S67343", + "session": "renewal" + } + }, + "sessions": { + "renewal": { + "seats": 0, + "start_day": 267 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41801/tests/test.sh b/tasks/service-hr-certifications-41801/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/service-hr-certifications-41801/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/service-hr-certifications-41801/tests/world.json b/tasks/service-hr-certifications-41801/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..f71fc20d5195d186a7558c34e6f07e67b863f396 --- /dev/null +++ b/tasks/service-hr-certifications-41801/tests/world.json @@ -0,0 +1,121 @@ +{ + "certs": { + "R27040": { + "course": "privacy", + "expires_day": 262, + "person": "S55227", + "state": "active" + }, + "R31318": { + "course": "induction", + "expires_day": 261, + "person": "S14281", + "state": "active" + }, + "R41372": { + "course": "privacy", + "expires_day": 242, + "person": "S96425", + "state": "active" + }, + "R62911": { + "course": "privacy", + "expires_day": 269, + "person": "S37904", + "state": "active" + }, + "R66644": { + "course": "induction", + "expires_day": 238, + "person": "S67343", + "state": "active" + }, + "R67395": { + "course": "induction", + "expires_day": 240, + "person": "S34392", + "state": "active" + }, + "R74184": { + "course": "induction", + "expires_day": 260, + "person": "S41733", + "state": "active" + }, + "R78577": { + "course": "records", + "expires_day": 266, + "person": "S80107", + "state": "retired" + }, + "R79676": { + "course": "induction", + "expires_day": 242, + "person": "S54288", + "state": "active" + }, + "R83507": { + "course": "records", + "expires_day": 274, + "person": "S17826", + "state": "active" + }, + "R88229": { + "course": "records", + "expires_day": 264, + "person": "S33831", + "state": "active" + }, + "R93075": { + "course": "records", + "expires_day": 242, + "person": "S48117", + "state": "active" + } + }, + "leave": { + "S14281": { + "available_day": 267 + }, + "S17826": { + "available_day": 257 + }, + "S33831": { + "available_day": 267 + }, + "S34392": { + "available_day": 271 + }, + "S37904": { + "available_day": 267 + }, + "S41733": { + "available_day": 266 + }, + "S48117": { + "available_day": 244 + }, + "S54288": { + "available_day": 244 + }, + "S55227": { + "available_day": 266 + }, + "S67343": { + "available_day": 266 + }, + "S80107": { + "available_day": 264 + }, + "S96425": { + "available_day": 257 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 2, + "start_day": 267 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41801/tests/world_check.py b/tasks/service-hr-certifications-41801/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/service-hr-certifications-41801/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/service-hr-certifications-41801/validation/openenv.json b/tasks/service-hr-certifications-41801/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..fddaa57ea849fa3e9762275b4fde1ffec6185cb7 --- /dev/null +++ b/tasks/service-hr-certifications-41801/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "hr" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41804/environment/inputs/apps.py b/tasks/service-hr-certifications-41804/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41804/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41804/environment/inputs/world.json b/tasks/service-hr-certifications-41804/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..8c79f97b6aa9e26dbbafaf3688735dbdfb6d38b6 --- /dev/null +++ b/tasks/service-hr-certifications-41804/environment/inputs/world.json @@ -0,0 +1,76 @@ +{ + "certs": { + "R10669": { + "course": "privacy", + "expires_day": 515, + "person": "S35627", + "state": "active" + }, + "R24181": { + "course": "privacy", + "expires_day": 516, + "person": "S27766", + "state": "retired" + }, + "R38571": { + "course": "induction", + "expires_day": 526, + "person": "S10531", + "state": "active" + }, + "R43953": { + "course": "privacy", + "expires_day": 523, + "person": "S31021", + "state": "active" + }, + "R69331": { + "course": "induction", + "expires_day": 515, + "person": "S61199", + "state": "active" + }, + "R77780": { + "course": "privacy", + "expires_day": 541, + "person": "S84249", + "state": "active" + }, + "R82484": { + "course": "records", + "expires_day": 515, + "person": "S85367", + "state": "active" + } + }, + "leave": { + "S10531": { + "available_day": 531 + }, + "S27766": { + "available_day": 538 + }, + "S31021": { + "available_day": 538 + }, + "S35627": { + "available_day": 518 + }, + "S61199": { + "available_day": 524 + }, + "S84249": { + "available_day": 533 + }, + "S85367": { + "available_day": 518 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 3, + "start_day": 534 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41804/instruction.md b/tasks/service-hr-certifications-41804/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ac4c86061f7dcc7cc59f093adb3410da4f196a3 --- /dev/null +++ b/tasks/service-hr-certifications-41804/instruction.md @@ -0,0 +1,13 @@ +Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew- in renewals with person, course and session set to renewal. Update the session's remaining seats. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/service-hr-certifications-41804/solution/files/actions.jsonl b/tasks/service-hr-certifications-41804/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0ba46e9fc1b40df5d71aeba36782e382aa91c120 --- /dev/null +++ b/tasks/service-hr-certifications-41804/solution/files/actions.jsonl @@ -0,0 +1,9 @@ +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R10669", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R82484", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R69331", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R38571", "op": "update"} +{"app": "certs", "fields": {"state": "deferred"}, "id": "R43953", "op": "update"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S35627", "session": "renewal"}, "id": "renew-R10669", "op": "create"} +{"app": "renewals", "fields": {"course": "induction", "person": "S61199", "session": "renewal"}, "id": "renew-R69331", "op": "create"} +{"app": "renewals", "fields": {"course": "records", "person": "S85367", "session": "renewal"}, "id": "renew-R82484", "op": "create"} +{"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"} diff --git a/tasks/service-hr-certifications-41804/solution/solve.sh b/tasks/service-hr-certifications-41804/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/service-hr-certifications-41804/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/service-hr-certifications-41804/task.toml b/tasks/service-hr-certifications-41804/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c074e83b7c358a7cc5787e01af8cec72813bd9d5 --- /dev/null +++ b/tasks/service-hr-certifications-41804/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/service-hr-certifications-41804" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"] +dataset = "Original simulated workflows" +job = "hr" +seed = 41804 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "service-hr-certifications-41804" +template_family = "automation:service-hr-certifications" +workflow_template = "service-hr-certifications" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/service-hr-certifications-41804/tests/expected.json b/tasks/service-hr-certifications-41804/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/service-hr-certifications-41804/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41804/tests/grade.py b/tasks/service-hr-certifications-41804/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/service-hr-certifications-41804/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/service-hr-certifications-41804/tests/replay.py b/tasks/service-hr-certifications-41804/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41804/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41804/tests/target.json b/tasks/service-hr-certifications-41804/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..0c13fd6159fe2bd8135a5f1040361037174d4bad --- /dev/null +++ b/tasks/service-hr-certifications-41804/tests/target.json @@ -0,0 +1,92 @@ +{ + "certs": { + "R10669": { + "course": "privacy", + "expires_day": 515, + "person": "S35627", + "state": "enrolled" + }, + "R24181": { + "course": "privacy", + "expires_day": 516, + "person": "S27766", + "state": "retired" + }, + "R38571": { + "course": "induction", + "expires_day": 526, + "person": "S10531", + "state": "waitlisted" + }, + "R43953": { + "course": "privacy", + "expires_day": 523, + "person": "S31021", + "state": "deferred" + }, + "R69331": { + "course": "induction", + "expires_day": 515, + "person": "S61199", + "state": "enrolled" + }, + "R77780": { + "course": "privacy", + "expires_day": 541, + "person": "S84249", + "state": "active" + }, + "R82484": { + "course": "records", + "expires_day": 515, + "person": "S85367", + "state": "enrolled" + } + }, + "leave": { + "S10531": { + "available_day": 531 + }, + "S27766": { + "available_day": 538 + }, + "S31021": { + "available_day": 538 + }, + "S35627": { + "available_day": 518 + }, + "S61199": { + "available_day": 524 + }, + "S84249": { + "available_day": 533 + }, + "S85367": { + "available_day": 518 + } + }, + "renewals": { + "renew-R10669": { + "course": "privacy", + "person": "S35627", + "session": "renewal" + }, + "renew-R69331": { + "course": "induction", + "person": "S61199", + "session": "renewal" + }, + "renew-R82484": { + "course": "records", + "person": "S85367", + "session": "renewal" + } + }, + "sessions": { + "renewal": { + "seats": 0, + "start_day": 534 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41804/tests/test.sh b/tasks/service-hr-certifications-41804/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/service-hr-certifications-41804/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/service-hr-certifications-41804/tests/world.json b/tasks/service-hr-certifications-41804/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..8c79f97b6aa9e26dbbafaf3688735dbdfb6d38b6 --- /dev/null +++ b/tasks/service-hr-certifications-41804/tests/world.json @@ -0,0 +1,76 @@ +{ + "certs": { + "R10669": { + "course": "privacy", + "expires_day": 515, + "person": "S35627", + "state": "active" + }, + "R24181": { + "course": "privacy", + "expires_day": 516, + "person": "S27766", + "state": "retired" + }, + "R38571": { + "course": "induction", + "expires_day": 526, + "person": "S10531", + "state": "active" + }, + "R43953": { + "course": "privacy", + "expires_day": 523, + "person": "S31021", + "state": "active" + }, + "R69331": { + "course": "induction", + "expires_day": 515, + "person": "S61199", + "state": "active" + }, + "R77780": { + "course": "privacy", + "expires_day": 541, + "person": "S84249", + "state": "active" + }, + "R82484": { + "course": "records", + "expires_day": 515, + "person": "S85367", + "state": "active" + } + }, + "leave": { + "S10531": { + "available_day": 531 + }, + "S27766": { + "available_day": 538 + }, + "S31021": { + "available_day": 538 + }, + "S35627": { + "available_day": 518 + }, + "S61199": { + "available_day": 524 + }, + "S84249": { + "available_day": 533 + }, + "S85367": { + "available_day": 518 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 3, + "start_day": 534 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41804/tests/world_check.py b/tasks/service-hr-certifications-41804/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/service-hr-certifications-41804/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/service-hr-certifications-41804/validation/openenv.json b/tasks/service-hr-certifications-41804/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..fddaa57ea849fa3e9762275b4fde1ffec6185cb7 --- /dev/null +++ b/tasks/service-hr-certifications-41804/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "hr" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41807/environment/inputs/apps.py b/tasks/service-hr-certifications-41807/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41807/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41807/environment/inputs/world.json b/tasks/service-hr-certifications-41807/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..2f00509bcc60ba53bd0f6291871ad6bd70ab1966 --- /dev/null +++ b/tasks/service-hr-certifications-41807/environment/inputs/world.json @@ -0,0 +1,67 @@ +{ + "certs": { + "R13045": { + "course": "induction", + "expires_day": 342, + "person": "S67059", + "state": "active" + }, + "R13744": { + "course": "records", + "expires_day": 337, + "person": "S63593", + "state": "active" + }, + "R58563": { + "course": "records", + "expires_day": 342, + "person": "S85262", + "state": "active" + }, + "R65931": { + "course": "records", + "expires_day": 344, + "person": "S78318", + "state": "active" + }, + "R83130": { + "course": "records", + "expires_day": 370, + "person": "S31324", + "state": "retired" + }, + "R93661": { + "course": "induction", + "expires_day": 393, + "person": "S91860", + "state": "active" + } + }, + "leave": { + "S31324": { + "available_day": 387 + }, + "S63593": { + "available_day": 380 + }, + "S67059": { + "available_day": 345 + }, + "S78318": { + "available_day": 345 + }, + "S85262": { + "available_day": 382 + }, + "S91860": { + "available_day": 387 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 2, + "start_day": 383 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41807/instruction.md b/tasks/service-hr-certifications-41807/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ac4c86061f7dcc7cc59f093adb3410da4f196a3 --- /dev/null +++ b/tasks/service-hr-certifications-41807/instruction.md @@ -0,0 +1,13 @@ +Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew- in renewals with person, course and session set to renewal. Update the session's remaining seats. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/service-hr-certifications-41807/solution/files/actions.jsonl b/tasks/service-hr-certifications-41807/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ee26e152e54256378cfd6a97c999e191fcdc5c24 --- /dev/null +++ b/tasks/service-hr-certifications-41807/solution/files/actions.jsonl @@ -0,0 +1,7 @@ +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R65931", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R13045", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R13744", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R58563", "op": "update"} +{"app": "renewals", "fields": {"course": "records", "person": "S63593", "session": "renewal"}, "id": "renew-R13744", "op": "create"} +{"app": "renewals", "fields": {"course": "induction", "person": "S67059", "session": "renewal"}, "id": "renew-R13045", "op": "create"} +{"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"} diff --git a/tasks/service-hr-certifications-41807/solution/solve.sh b/tasks/service-hr-certifications-41807/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/service-hr-certifications-41807/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/service-hr-certifications-41807/task.toml b/tasks/service-hr-certifications-41807/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c20b0cff016414a80e9ecb41d26d1c088767bd49 --- /dev/null +++ b/tasks/service-hr-certifications-41807/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/service-hr-certifications-41807" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"] +dataset = "Original simulated workflows" +job = "hr" +seed = 41807 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "service-hr-certifications-41807" +template_family = "automation:service-hr-certifications" +workflow_template = "service-hr-certifications" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/service-hr-certifications-41807/tests/expected.json b/tasks/service-hr-certifications-41807/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/service-hr-certifications-41807/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41807/tests/grade.py b/tasks/service-hr-certifications-41807/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/service-hr-certifications-41807/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/service-hr-certifications-41807/tests/replay.py b/tasks/service-hr-certifications-41807/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41807/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41807/tests/target.json b/tasks/service-hr-certifications-41807/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..9d0775ebcd07db5f93dfa83e0abfb4b11717f8b0 --- /dev/null +++ b/tasks/service-hr-certifications-41807/tests/target.json @@ -0,0 +1,78 @@ +{ + "certs": { + "R13045": { + "course": "induction", + "expires_day": 342, + "person": "S67059", + "state": "enrolled" + }, + "R13744": { + "course": "records", + "expires_day": 337, + "person": "S63593", + "state": "enrolled" + }, + "R58563": { + "course": "records", + "expires_day": 342, + "person": "S85262", + "state": "waitlisted" + }, + "R65931": { + "course": "records", + "expires_day": 344, + "person": "S78318", + "state": "waitlisted" + }, + "R83130": { + "course": "records", + "expires_day": 370, + "person": "S31324", + "state": "retired" + }, + "R93661": { + "course": "induction", + "expires_day": 393, + "person": "S91860", + "state": "active" + } + }, + "leave": { + "S31324": { + "available_day": 387 + }, + "S63593": { + "available_day": 380 + }, + "S67059": { + "available_day": 345 + }, + "S78318": { + "available_day": 345 + }, + "S85262": { + "available_day": 382 + }, + "S91860": { + "available_day": 387 + } + }, + "renewals": { + "renew-R13045": { + "course": "induction", + "person": "S67059", + "session": "renewal" + }, + "renew-R13744": { + "course": "records", + "person": "S63593", + "session": "renewal" + } + }, + "sessions": { + "renewal": { + "seats": 0, + "start_day": 383 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41807/tests/test.sh b/tasks/service-hr-certifications-41807/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/service-hr-certifications-41807/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/service-hr-certifications-41807/tests/world.json b/tasks/service-hr-certifications-41807/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..2f00509bcc60ba53bd0f6291871ad6bd70ab1966 --- /dev/null +++ b/tasks/service-hr-certifications-41807/tests/world.json @@ -0,0 +1,67 @@ +{ + "certs": { + "R13045": { + "course": "induction", + "expires_day": 342, + "person": "S67059", + "state": "active" + }, + "R13744": { + "course": "records", + "expires_day": 337, + "person": "S63593", + "state": "active" + }, + "R58563": { + "course": "records", + "expires_day": 342, + "person": "S85262", + "state": "active" + }, + "R65931": { + "course": "records", + "expires_day": 344, + "person": "S78318", + "state": "active" + }, + "R83130": { + "course": "records", + "expires_day": 370, + "person": "S31324", + "state": "retired" + }, + "R93661": { + "course": "induction", + "expires_day": 393, + "person": "S91860", + "state": "active" + } + }, + "leave": { + "S31324": { + "available_day": 387 + }, + "S63593": { + "available_day": 380 + }, + "S67059": { + "available_day": 345 + }, + "S78318": { + "available_day": 345 + }, + "S85262": { + "available_day": 382 + }, + "S91860": { + "available_day": 387 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 2, + "start_day": 383 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41807/tests/world_check.py b/tasks/service-hr-certifications-41807/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/service-hr-certifications-41807/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/service-hr-certifications-41807/validation/openenv.json b/tasks/service-hr-certifications-41807/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..fddaa57ea849fa3e9762275b4fde1ffec6185cb7 --- /dev/null +++ b/tasks/service-hr-certifications-41807/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "hr" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41810/environment/inputs/apps.py b/tasks/service-hr-certifications-41810/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41810/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41810/environment/inputs/world.json b/tasks/service-hr-certifications-41810/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..9cfb519901f3a36421d1f2f1d5d2d4b783a9bb4a --- /dev/null +++ b/tasks/service-hr-certifications-41810/environment/inputs/world.json @@ -0,0 +1,76 @@ +{ + "certs": { + "R15645": { + "course": "privacy", + "expires_day": 666, + "person": "S34630", + "state": "active" + }, + "R31786": { + "course": "induction", + "expires_day": 649, + "person": "S37963", + "state": "active" + }, + "R34804": { + "course": "induction", + "expires_day": 679, + "person": "S85713", + "state": "retired" + }, + "R37310": { + "course": "privacy", + "expires_day": 647, + "person": "S23825", + "state": "active" + }, + "R42043": { + "course": "privacy", + "expires_day": 681, + "person": "S60536", + "state": "active" + }, + "R48680": { + "course": "privacy", + "expires_day": 649, + "person": "S39859", + "state": "active" + }, + "R78852": { + "course": "records", + "expires_day": 675, + "person": "S71023", + "state": "active" + } + }, + "leave": { + "S23825": { + "available_day": 650 + }, + "S34630": { + "available_day": 672 + }, + "S37963": { + "available_day": 650 + }, + "S39859": { + "available_day": 673 + }, + "S60536": { + "available_day": 673 + }, + "S71023": { + "available_day": 663 + }, + "S85713": { + "available_day": 677 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 4, + "start_day": 673 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41810/instruction.md b/tasks/service-hr-certifications-41810/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ac4c86061f7dcc7cc59f093adb3410da4f196a3 --- /dev/null +++ b/tasks/service-hr-certifications-41810/instruction.md @@ -0,0 +1,13 @@ +Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew- in renewals with person, course and session set to renewal. Update the session's remaining seats. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/service-hr-certifications-41810/solution/files/actions.jsonl b/tasks/service-hr-certifications-41810/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..682a97a55ea561ad0ba92fda166a0bed61099cf4 --- /dev/null +++ b/tasks/service-hr-certifications-41810/solution/files/actions.jsonl @@ -0,0 +1,9 @@ +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R37310", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R31786", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R15645", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R48680", "op": "update"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S23825", "session": "renewal"}, "id": "renew-R37310", "op": "create"} +{"app": "renewals", "fields": {"course": "induction", "person": "S37963", "session": "renewal"}, "id": "renew-R31786", "op": "create"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S39859", "session": "renewal"}, "id": "renew-R48680", "op": "create"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S34630", "session": "renewal"}, "id": "renew-R15645", "op": "create"} +{"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"} diff --git a/tasks/service-hr-certifications-41810/solution/solve.sh b/tasks/service-hr-certifications-41810/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/service-hr-certifications-41810/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/service-hr-certifications-41810/task.toml b/tasks/service-hr-certifications-41810/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5ddbc7307018aa7b55b5321baa5fdf943aae5173 --- /dev/null +++ b/tasks/service-hr-certifications-41810/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/service-hr-certifications-41810" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"] +dataset = "Original simulated workflows" +job = "hr" +seed = 41810 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "service-hr-certifications-41810" +template_family = "automation:service-hr-certifications" +workflow_template = "service-hr-certifications" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/service-hr-certifications-41810/tests/expected.json b/tasks/service-hr-certifications-41810/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/service-hr-certifications-41810/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41810/tests/grade.py b/tasks/service-hr-certifications-41810/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/service-hr-certifications-41810/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/service-hr-certifications-41810/tests/replay.py b/tasks/service-hr-certifications-41810/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41810/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41810/tests/target.json b/tasks/service-hr-certifications-41810/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..6cb2724496f23098eef0869e2b93d253831b1287 --- /dev/null +++ b/tasks/service-hr-certifications-41810/tests/target.json @@ -0,0 +1,97 @@ +{ + "certs": { + "R15645": { + "course": "privacy", + "expires_day": 666, + "person": "S34630", + "state": "enrolled" + }, + "R31786": { + "course": "induction", + "expires_day": 649, + "person": "S37963", + "state": "enrolled" + }, + "R34804": { + "course": "induction", + "expires_day": 679, + "person": "S85713", + "state": "retired" + }, + "R37310": { + "course": "privacy", + "expires_day": 647, + "person": "S23825", + "state": "enrolled" + }, + "R42043": { + "course": "privacy", + "expires_day": 681, + "person": "S60536", + "state": "active" + }, + "R48680": { + "course": "privacy", + "expires_day": 649, + "person": "S39859", + "state": "enrolled" + }, + "R78852": { + "course": "records", + "expires_day": 675, + "person": "S71023", + "state": "active" + } + }, + "leave": { + "S23825": { + "available_day": 650 + }, + "S34630": { + "available_day": 672 + }, + "S37963": { + "available_day": 650 + }, + "S39859": { + "available_day": 673 + }, + "S60536": { + "available_day": 673 + }, + "S71023": { + "available_day": 663 + }, + "S85713": { + "available_day": 677 + } + }, + "renewals": { + "renew-R15645": { + "course": "privacy", + "person": "S34630", + "session": "renewal" + }, + "renew-R31786": { + "course": "induction", + "person": "S37963", + "session": "renewal" + }, + "renew-R37310": { + "course": "privacy", + "person": "S23825", + "session": "renewal" + }, + "renew-R48680": { + "course": "privacy", + "person": "S39859", + "session": "renewal" + } + }, + "sessions": { + "renewal": { + "seats": 0, + "start_day": 673 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41810/tests/test.sh b/tasks/service-hr-certifications-41810/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/service-hr-certifications-41810/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/service-hr-certifications-41810/tests/world.json b/tasks/service-hr-certifications-41810/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..9cfb519901f3a36421d1f2f1d5d2d4b783a9bb4a --- /dev/null +++ b/tasks/service-hr-certifications-41810/tests/world.json @@ -0,0 +1,76 @@ +{ + "certs": { + "R15645": { + "course": "privacy", + "expires_day": 666, + "person": "S34630", + "state": "active" + }, + "R31786": { + "course": "induction", + "expires_day": 649, + "person": "S37963", + "state": "active" + }, + "R34804": { + "course": "induction", + "expires_day": 679, + "person": "S85713", + "state": "retired" + }, + "R37310": { + "course": "privacy", + "expires_day": 647, + "person": "S23825", + "state": "active" + }, + "R42043": { + "course": "privacy", + "expires_day": 681, + "person": "S60536", + "state": "active" + }, + "R48680": { + "course": "privacy", + "expires_day": 649, + "person": "S39859", + "state": "active" + }, + "R78852": { + "course": "records", + "expires_day": 675, + "person": "S71023", + "state": "active" + } + }, + "leave": { + "S23825": { + "available_day": 650 + }, + "S34630": { + "available_day": 672 + }, + "S37963": { + "available_day": 650 + }, + "S39859": { + "available_day": 673 + }, + "S60536": { + "available_day": 673 + }, + "S71023": { + "available_day": 663 + }, + "S85713": { + "available_day": 677 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 4, + "start_day": 673 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41810/tests/world_check.py b/tasks/service-hr-certifications-41810/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/service-hr-certifications-41810/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/service-hr-certifications-41810/validation/openenv.json b/tasks/service-hr-certifications-41810/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..fddaa57ea849fa3e9762275b4fde1ffec6185cb7 --- /dev/null +++ b/tasks/service-hr-certifications-41810/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "hr" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41813/environment/inputs/apps.py b/tasks/service-hr-certifications-41813/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41813/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41813/environment/inputs/world.json b/tasks/service-hr-certifications-41813/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..f78079db3ae6af8e0d70b6322e1567594a05c8aa --- /dev/null +++ b/tasks/service-hr-certifications-41813/environment/inputs/world.json @@ -0,0 +1,85 @@ +{ + "certs": { + "R14031": { + "course": "induction", + "expires_day": 486, + "person": "S56981", + "state": "active" + }, + "R24909": { + "course": "induction", + "expires_day": 492, + "person": "S72441", + "state": "active" + }, + "R28414": { + "course": "induction", + "expires_day": 456, + "person": "S99677", + "state": "active" + }, + "R47475": { + "course": "induction", + "expires_day": 463, + "person": "S82398", + "state": "active" + }, + "R52033": { + "course": "privacy", + "expires_day": 457, + "person": "S58027", + "state": "active" + }, + "R60584": { + "course": "privacy", + "expires_day": 485, + "person": "S59017", + "state": "retired" + }, + "R79985": { + "course": "records", + "expires_day": 493, + "person": "S73436", + "state": "active" + }, + "R80694": { + "course": "privacy", + "expires_day": 460, + "person": "S21222", + "state": "active" + } + }, + "leave": { + "S21222": { + "available_day": 493 + }, + "S56981": { + "available_day": 495 + }, + "S58027": { + "available_day": 458 + }, + "S59017": { + "available_day": 496 + }, + "S72441": { + "available_day": 496 + }, + "S73436": { + "available_day": 496 + }, + "S82398": { + "available_day": 486 + }, + "S99677": { + "available_day": 458 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 4, + "start_day": 496 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41813/instruction.md b/tasks/service-hr-certifications-41813/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ac4c86061f7dcc7cc59f093adb3410da4f196a3 --- /dev/null +++ b/tasks/service-hr-certifications-41813/instruction.md @@ -0,0 +1,13 @@ +Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew- in renewals with person, course and session set to renewal. Update the session's remaining seats. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/service-hr-certifications-41813/solution/files/actions.jsonl b/tasks/service-hr-certifications-41813/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e5ebdcda57b67c966dc1bd9b788432b47a5a1645 --- /dev/null +++ b/tasks/service-hr-certifications-41813/solution/files/actions.jsonl @@ -0,0 +1,12 @@ +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R28414", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R52033", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R80694", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R79985", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R14031", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R47475", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R24909", "op": "update"} +{"app": "renewals", "fields": {"course": "induction", "person": "S99677", "session": "renewal"}, "id": "renew-R28414", "op": "create"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S58027", "session": "renewal"}, "id": "renew-R52033", "op": "create"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S21222", "session": "renewal"}, "id": "renew-R80694", "op": "create"} +{"app": "renewals", "fields": {"course": "induction", "person": "S82398", "session": "renewal"}, "id": "renew-R47475", "op": "create"} +{"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"} diff --git a/tasks/service-hr-certifications-41813/solution/solve.sh b/tasks/service-hr-certifications-41813/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/service-hr-certifications-41813/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/service-hr-certifications-41813/task.toml b/tasks/service-hr-certifications-41813/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ecfd46c34f682db88383858697a024d3836732e2 --- /dev/null +++ b/tasks/service-hr-certifications-41813/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/service-hr-certifications-41813" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"] +dataset = "Original simulated workflows" +job = "hr" +seed = 41813 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "service-hr-certifications-41813" +template_family = "automation:service-hr-certifications" +workflow_template = "service-hr-certifications" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/service-hr-certifications-41813/tests/expected.json b/tasks/service-hr-certifications-41813/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/service-hr-certifications-41813/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41813/tests/grade.py b/tasks/service-hr-certifications-41813/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/service-hr-certifications-41813/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/service-hr-certifications-41813/tests/replay.py b/tasks/service-hr-certifications-41813/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41813/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41813/tests/target.json b/tasks/service-hr-certifications-41813/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..b8f35720bf2e02169574b147ed38fba3078c7d07 --- /dev/null +++ b/tasks/service-hr-certifications-41813/tests/target.json @@ -0,0 +1,106 @@ +{ + "certs": { + "R14031": { + "course": "induction", + "expires_day": 486, + "person": "S56981", + "state": "waitlisted" + }, + "R24909": { + "course": "induction", + "expires_day": 492, + "person": "S72441", + "state": "waitlisted" + }, + "R28414": { + "course": "induction", + "expires_day": 456, + "person": "S99677", + "state": "enrolled" + }, + "R47475": { + "course": "induction", + "expires_day": 463, + "person": "S82398", + "state": "enrolled" + }, + "R52033": { + "course": "privacy", + "expires_day": 457, + "person": "S58027", + "state": "enrolled" + }, + "R60584": { + "course": "privacy", + "expires_day": 485, + "person": "S59017", + "state": "retired" + }, + "R79985": { + "course": "records", + "expires_day": 493, + "person": "S73436", + "state": "waitlisted" + }, + "R80694": { + "course": "privacy", + "expires_day": 460, + "person": "S21222", + "state": "enrolled" + } + }, + "leave": { + "S21222": { + "available_day": 493 + }, + "S56981": { + "available_day": 495 + }, + "S58027": { + "available_day": 458 + }, + "S59017": { + "available_day": 496 + }, + "S72441": { + "available_day": 496 + }, + "S73436": { + "available_day": 496 + }, + "S82398": { + "available_day": 486 + }, + "S99677": { + "available_day": 458 + } + }, + "renewals": { + "renew-R28414": { + "course": "induction", + "person": "S99677", + "session": "renewal" + }, + "renew-R47475": { + "course": "induction", + "person": "S82398", + "session": "renewal" + }, + "renew-R52033": { + "course": "privacy", + "person": "S58027", + "session": "renewal" + }, + "renew-R80694": { + "course": "privacy", + "person": "S21222", + "session": "renewal" + } + }, + "sessions": { + "renewal": { + "seats": 0, + "start_day": 496 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41813/tests/test.sh b/tasks/service-hr-certifications-41813/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/service-hr-certifications-41813/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/service-hr-certifications-41813/tests/world.json b/tasks/service-hr-certifications-41813/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..f78079db3ae6af8e0d70b6322e1567594a05c8aa --- /dev/null +++ b/tasks/service-hr-certifications-41813/tests/world.json @@ -0,0 +1,85 @@ +{ + "certs": { + "R14031": { + "course": "induction", + "expires_day": 486, + "person": "S56981", + "state": "active" + }, + "R24909": { + "course": "induction", + "expires_day": 492, + "person": "S72441", + "state": "active" + }, + "R28414": { + "course": "induction", + "expires_day": 456, + "person": "S99677", + "state": "active" + }, + "R47475": { + "course": "induction", + "expires_day": 463, + "person": "S82398", + "state": "active" + }, + "R52033": { + "course": "privacy", + "expires_day": 457, + "person": "S58027", + "state": "active" + }, + "R60584": { + "course": "privacy", + "expires_day": 485, + "person": "S59017", + "state": "retired" + }, + "R79985": { + "course": "records", + "expires_day": 493, + "person": "S73436", + "state": "active" + }, + "R80694": { + "course": "privacy", + "expires_day": 460, + "person": "S21222", + "state": "active" + } + }, + "leave": { + "S21222": { + "available_day": 493 + }, + "S56981": { + "available_day": 495 + }, + "S58027": { + "available_day": 458 + }, + "S59017": { + "available_day": 496 + }, + "S72441": { + "available_day": 496 + }, + "S73436": { + "available_day": 496 + }, + "S82398": { + "available_day": 486 + }, + "S99677": { + "available_day": 458 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 4, + "start_day": 496 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41813/tests/world_check.py b/tasks/service-hr-certifications-41813/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/service-hr-certifications-41813/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/service-hr-certifications-41813/validation/openenv.json b/tasks/service-hr-certifications-41813/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..fddaa57ea849fa3e9762275b4fde1ffec6185cb7 --- /dev/null +++ b/tasks/service-hr-certifications-41813/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "hr" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41816/environment/inputs/apps.py b/tasks/service-hr-certifications-41816/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41816/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41816/environment/inputs/world.json b/tasks/service-hr-certifications-41816/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..ed6ada9e397931edf9866f88ea0afca11af8331a --- /dev/null +++ b/tasks/service-hr-certifications-41816/environment/inputs/world.json @@ -0,0 +1,112 @@ +{ + "certs": { + "R29921": { + "course": "induction", + "expires_day": 259, + "person": "S62811", + "state": "active" + }, + "R30265": { + "course": "privacy", + "expires_day": 254, + "person": "S81965", + "state": "active" + }, + "R43710": { + "course": "privacy", + "expires_day": 255, + "person": "S93221", + "state": "active" + }, + "R53582": { + "course": "records", + "expires_day": 223, + "person": "S82401", + "state": "retired" + }, + "R61091": { + "course": "induction", + "expires_day": 229, + "person": "S46797", + "state": "active" + }, + "R65763": { + "course": "records", + "expires_day": 256, + "person": "S29681", + "state": "active" + }, + "R66492": { + "course": "induction", + "expires_day": 239, + "person": "S96182", + "state": "active" + }, + "R73350": { + "course": "induction", + "expires_day": 250, + "person": "S82885", + "state": "active" + }, + "R77084": { + "course": "induction", + "expires_day": 225, + "person": "S87514", + "state": "active" + }, + "R80354": { + "course": "privacy", + "expires_day": 254, + "person": "S49823", + "state": "active" + }, + "R99875": { + "course": "privacy", + "expires_day": 228, + "person": "S70994", + "state": "active" + } + }, + "leave": { + "S29681": { + "available_day": 253 + }, + "S46797": { + "available_day": 231 + }, + "S49823": { + "available_day": 256 + }, + "S62811": { + "available_day": 246 + }, + "S70994": { + "available_day": 231 + }, + "S81965": { + "available_day": 246 + }, + "S82401": { + "available_day": 256 + }, + "S82885": { + "available_day": 260 + }, + "S87514": { + "available_day": 253 + }, + "S93221": { + "available_day": 255 + }, + "S96182": { + "available_day": 260 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 2, + "start_day": 256 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41816/instruction.md b/tasks/service-hr-certifications-41816/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ac4c86061f7dcc7cc59f093adb3410da4f196a3 --- /dev/null +++ b/tasks/service-hr-certifications-41816/instruction.md @@ -0,0 +1,13 @@ +Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew- in renewals with person, course and session set to renewal. Update the session's remaining seats. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/service-hr-certifications-41816/solution/files/actions.jsonl b/tasks/service-hr-certifications-41816/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..74e12642ce3089fbef8cd95197bfc23fd8e05de6 --- /dev/null +++ b/tasks/service-hr-certifications-41816/solution/files/actions.jsonl @@ -0,0 +1,12 @@ +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R61091", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R99875", "op": "update"} +{"app": "certs", "fields": {"state": "deferred"}, "id": "R66492", "op": "update"} +{"app": "certs", "fields": {"state": "deferred"}, "id": "R73350", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R65763", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R80354", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R77084", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R30265", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R43710", "op": "update"} +{"app": "renewals", "fields": {"course": "induction", "person": "S87514", "session": "renewal"}, "id": "renew-R77084", "op": "create"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S70994", "session": "renewal"}, "id": "renew-R99875", "op": "create"} +{"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"} diff --git a/tasks/service-hr-certifications-41816/solution/solve.sh b/tasks/service-hr-certifications-41816/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/service-hr-certifications-41816/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/service-hr-certifications-41816/task.toml b/tasks/service-hr-certifications-41816/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9620dc58e82e52ea0b0c49adf369fb62eed5e353 --- /dev/null +++ b/tasks/service-hr-certifications-41816/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/service-hr-certifications-41816" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"] +dataset = "Original simulated workflows" +job = "hr" +seed = 41816 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "service-hr-certifications-41816" +template_family = "automation:service-hr-certifications" +workflow_template = "service-hr-certifications" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/service-hr-certifications-41816/tests/expected.json b/tasks/service-hr-certifications-41816/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/service-hr-certifications-41816/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41816/tests/grade.py b/tasks/service-hr-certifications-41816/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/service-hr-certifications-41816/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/service-hr-certifications-41816/tests/replay.py b/tasks/service-hr-certifications-41816/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41816/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41816/tests/target.json b/tasks/service-hr-certifications-41816/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..7d96558f179e1179a31b1e3001cc817fa3148552 --- /dev/null +++ b/tasks/service-hr-certifications-41816/tests/target.json @@ -0,0 +1,123 @@ +{ + "certs": { + "R29921": { + "course": "induction", + "expires_day": 259, + "person": "S62811", + "state": "active" + }, + "R30265": { + "course": "privacy", + "expires_day": 254, + "person": "S81965", + "state": "waitlisted" + }, + "R43710": { + "course": "privacy", + "expires_day": 255, + "person": "S93221", + "state": "waitlisted" + }, + "R53582": { + "course": "records", + "expires_day": 223, + "person": "S82401", + "state": "retired" + }, + "R61091": { + "course": "induction", + "expires_day": 229, + "person": "S46797", + "state": "waitlisted" + }, + "R65763": { + "course": "records", + "expires_day": 256, + "person": "S29681", + "state": "waitlisted" + }, + "R66492": { + "course": "induction", + "expires_day": 239, + "person": "S96182", + "state": "deferred" + }, + "R73350": { + "course": "induction", + "expires_day": 250, + "person": "S82885", + "state": "deferred" + }, + "R77084": { + "course": "induction", + "expires_day": 225, + "person": "S87514", + "state": "enrolled" + }, + "R80354": { + "course": "privacy", + "expires_day": 254, + "person": "S49823", + "state": "waitlisted" + }, + "R99875": { + "course": "privacy", + "expires_day": 228, + "person": "S70994", + "state": "enrolled" + } + }, + "leave": { + "S29681": { + "available_day": 253 + }, + "S46797": { + "available_day": 231 + }, + "S49823": { + "available_day": 256 + }, + "S62811": { + "available_day": 246 + }, + "S70994": { + "available_day": 231 + }, + "S81965": { + "available_day": 246 + }, + "S82401": { + "available_day": 256 + }, + "S82885": { + "available_day": 260 + }, + "S87514": { + "available_day": 253 + }, + "S93221": { + "available_day": 255 + }, + "S96182": { + "available_day": 260 + } + }, + "renewals": { + "renew-R77084": { + "course": "induction", + "person": "S87514", + "session": "renewal" + }, + "renew-R99875": { + "course": "privacy", + "person": "S70994", + "session": "renewal" + } + }, + "sessions": { + "renewal": { + "seats": 0, + "start_day": 256 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41816/tests/test.sh b/tasks/service-hr-certifications-41816/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/service-hr-certifications-41816/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/service-hr-certifications-41816/tests/world.json b/tasks/service-hr-certifications-41816/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..ed6ada9e397931edf9866f88ea0afca11af8331a --- /dev/null +++ b/tasks/service-hr-certifications-41816/tests/world.json @@ -0,0 +1,112 @@ +{ + "certs": { + "R29921": { + "course": "induction", + "expires_day": 259, + "person": "S62811", + "state": "active" + }, + "R30265": { + "course": "privacy", + "expires_day": 254, + "person": "S81965", + "state": "active" + }, + "R43710": { + "course": "privacy", + "expires_day": 255, + "person": "S93221", + "state": "active" + }, + "R53582": { + "course": "records", + "expires_day": 223, + "person": "S82401", + "state": "retired" + }, + "R61091": { + "course": "induction", + "expires_day": 229, + "person": "S46797", + "state": "active" + }, + "R65763": { + "course": "records", + "expires_day": 256, + "person": "S29681", + "state": "active" + }, + "R66492": { + "course": "induction", + "expires_day": 239, + "person": "S96182", + "state": "active" + }, + "R73350": { + "course": "induction", + "expires_day": 250, + "person": "S82885", + "state": "active" + }, + "R77084": { + "course": "induction", + "expires_day": 225, + "person": "S87514", + "state": "active" + }, + "R80354": { + "course": "privacy", + "expires_day": 254, + "person": "S49823", + "state": "active" + }, + "R99875": { + "course": "privacy", + "expires_day": 228, + "person": "S70994", + "state": "active" + } + }, + "leave": { + "S29681": { + "available_day": 253 + }, + "S46797": { + "available_day": 231 + }, + "S49823": { + "available_day": 256 + }, + "S62811": { + "available_day": 246 + }, + "S70994": { + "available_day": 231 + }, + "S81965": { + "available_day": 246 + }, + "S82401": { + "available_day": 256 + }, + "S82885": { + "available_day": 260 + }, + "S87514": { + "available_day": 253 + }, + "S93221": { + "available_day": 255 + }, + "S96182": { + "available_day": 260 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 2, + "start_day": 256 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41816/tests/world_check.py b/tasks/service-hr-certifications-41816/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/service-hr-certifications-41816/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/service-hr-certifications-41816/validation/openenv.json b/tasks/service-hr-certifications-41816/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..fddaa57ea849fa3e9762275b4fde1ffec6185cb7 --- /dev/null +++ b/tasks/service-hr-certifications-41816/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "hr" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41819/environment/inputs/apps.py b/tasks/service-hr-certifications-41819/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41819/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41819/environment/inputs/world.json b/tasks/service-hr-certifications-41819/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..8e61cbd9c98906c08e9e73c3666bdf2508435c3e --- /dev/null +++ b/tasks/service-hr-certifications-41819/environment/inputs/world.json @@ -0,0 +1,85 @@ +{ + "certs": { + "R43631": { + "course": "induction", + "expires_day": 302, + "person": "S76455", + "state": "active" + }, + "R45826": { + "course": "privacy", + "expires_day": 288, + "person": "S21433", + "state": "active" + }, + "R55270": { + "course": "records", + "expires_day": 283, + "person": "S18435", + "state": "retired" + }, + "R61168": { + "course": "records", + "expires_day": 286, + "person": "S45646", + "state": "active" + }, + "R65727": { + "course": "induction", + "expires_day": 290, + "person": "S38050", + "state": "active" + }, + "R69148": { + "course": "induction", + "expires_day": 320, + "person": "S17107", + "state": "active" + }, + "R74436": { + "course": "privacy", + "expires_day": 288, + "person": "S43307", + "state": "active" + }, + "R85509": { + "course": "privacy", + "expires_day": 286, + "person": "S86847", + "state": "active" + } + }, + "leave": { + "S17107": { + "available_day": 313 + }, + "S18435": { + "available_day": 310 + }, + "S21433": { + "available_day": 312 + }, + "S38050": { + "available_day": 310 + }, + "S43307": { + "available_day": 310 + }, + "S45646": { + "available_day": 289 + }, + "S76455": { + "available_day": 303 + }, + "S86847": { + "available_day": 289 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 3, + "start_day": 313 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41819/instruction.md b/tasks/service-hr-certifications-41819/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ac4c86061f7dcc7cc59f093adb3410da4f196a3 --- /dev/null +++ b/tasks/service-hr-certifications-41819/instruction.md @@ -0,0 +1,13 @@ +Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew- in renewals with person, course and session set to renewal. Update the session's remaining seats. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/service-hr-certifications-41819/solution/files/actions.jsonl b/tasks/service-hr-certifications-41819/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..51c519f89e875075fce9bb24fc4a843534bcb99c --- /dev/null +++ b/tasks/service-hr-certifications-41819/solution/files/actions.jsonl @@ -0,0 +1,10 @@ +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R61168", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R85509", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R45826", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R43631", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R74436", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R65727", "op": "update"} +{"app": "renewals", "fields": {"course": "records", "person": "S45646", "session": "renewal"}, "id": "renew-R61168", "op": "create"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S86847", "session": "renewal"}, "id": "renew-R85509", "op": "create"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S21433", "session": "renewal"}, "id": "renew-R45826", "op": "create"} +{"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"} diff --git a/tasks/service-hr-certifications-41819/solution/solve.sh b/tasks/service-hr-certifications-41819/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/service-hr-certifications-41819/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/service-hr-certifications-41819/task.toml b/tasks/service-hr-certifications-41819/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fcb96e3c61221eac7bccc1ae6795998ff6b4d06d --- /dev/null +++ b/tasks/service-hr-certifications-41819/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/service-hr-certifications-41819" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"] +dataset = "Original simulated workflows" +job = "hr" +seed = 41819 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "service-hr-certifications-41819" +template_family = "automation:service-hr-certifications" +workflow_template = "service-hr-certifications" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/service-hr-certifications-41819/tests/expected.json b/tasks/service-hr-certifications-41819/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/service-hr-certifications-41819/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41819/tests/grade.py b/tasks/service-hr-certifications-41819/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/service-hr-certifications-41819/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/service-hr-certifications-41819/tests/replay.py b/tasks/service-hr-certifications-41819/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41819/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41819/tests/target.json b/tasks/service-hr-certifications-41819/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..5739b3507d63032a7c1824f343f983d7defd77c4 --- /dev/null +++ b/tasks/service-hr-certifications-41819/tests/target.json @@ -0,0 +1,101 @@ +{ + "certs": { + "R43631": { + "course": "induction", + "expires_day": 302, + "person": "S76455", + "state": "waitlisted" + }, + "R45826": { + "course": "privacy", + "expires_day": 288, + "person": "S21433", + "state": "enrolled" + }, + "R55270": { + "course": "records", + "expires_day": 283, + "person": "S18435", + "state": "retired" + }, + "R61168": { + "course": "records", + "expires_day": 286, + "person": "S45646", + "state": "enrolled" + }, + "R65727": { + "course": "induction", + "expires_day": 290, + "person": "S38050", + "state": "waitlisted" + }, + "R69148": { + "course": "induction", + "expires_day": 320, + "person": "S17107", + "state": "active" + }, + "R74436": { + "course": "privacy", + "expires_day": 288, + "person": "S43307", + "state": "waitlisted" + }, + "R85509": { + "course": "privacy", + "expires_day": 286, + "person": "S86847", + "state": "enrolled" + } + }, + "leave": { + "S17107": { + "available_day": 313 + }, + "S18435": { + "available_day": 310 + }, + "S21433": { + "available_day": 312 + }, + "S38050": { + "available_day": 310 + }, + "S43307": { + "available_day": 310 + }, + "S45646": { + "available_day": 289 + }, + "S76455": { + "available_day": 303 + }, + "S86847": { + "available_day": 289 + } + }, + "renewals": { + "renew-R45826": { + "course": "privacy", + "person": "S21433", + "session": "renewal" + }, + "renew-R61168": { + "course": "records", + "person": "S45646", + "session": "renewal" + }, + "renew-R85509": { + "course": "privacy", + "person": "S86847", + "session": "renewal" + } + }, + "sessions": { + "renewal": { + "seats": 0, + "start_day": 313 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41819/tests/test.sh b/tasks/service-hr-certifications-41819/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/service-hr-certifications-41819/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/service-hr-certifications-41819/tests/world.json b/tasks/service-hr-certifications-41819/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..8e61cbd9c98906c08e9e73c3666bdf2508435c3e --- /dev/null +++ b/tasks/service-hr-certifications-41819/tests/world.json @@ -0,0 +1,85 @@ +{ + "certs": { + "R43631": { + "course": "induction", + "expires_day": 302, + "person": "S76455", + "state": "active" + }, + "R45826": { + "course": "privacy", + "expires_day": 288, + "person": "S21433", + "state": "active" + }, + "R55270": { + "course": "records", + "expires_day": 283, + "person": "S18435", + "state": "retired" + }, + "R61168": { + "course": "records", + "expires_day": 286, + "person": "S45646", + "state": "active" + }, + "R65727": { + "course": "induction", + "expires_day": 290, + "person": "S38050", + "state": "active" + }, + "R69148": { + "course": "induction", + "expires_day": 320, + "person": "S17107", + "state": "active" + }, + "R74436": { + "course": "privacy", + "expires_day": 288, + "person": "S43307", + "state": "active" + }, + "R85509": { + "course": "privacy", + "expires_day": 286, + "person": "S86847", + "state": "active" + } + }, + "leave": { + "S17107": { + "available_day": 313 + }, + "S18435": { + "available_day": 310 + }, + "S21433": { + "available_day": 312 + }, + "S38050": { + "available_day": 310 + }, + "S43307": { + "available_day": 310 + }, + "S45646": { + "available_day": 289 + }, + "S76455": { + "available_day": 303 + }, + "S86847": { + "available_day": 289 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 3, + "start_day": 313 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41819/tests/world_check.py b/tasks/service-hr-certifications-41819/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/service-hr-certifications-41819/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/service-hr-certifications-41819/validation/openenv.json b/tasks/service-hr-certifications-41819/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..fddaa57ea849fa3e9762275b4fde1ffec6185cb7 --- /dev/null +++ b/tasks/service-hr-certifications-41819/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "hr" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41822/environment/inputs/apps.py b/tasks/service-hr-certifications-41822/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41822/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41822/environment/inputs/world.json b/tasks/service-hr-certifications-41822/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..5581054e330b2ceb25ab1f76972b5d5a45646cc1 --- /dev/null +++ b/tasks/service-hr-certifications-41822/environment/inputs/world.json @@ -0,0 +1,112 @@ +{ + "certs": { + "R12307": { + "course": "induction", + "expires_day": 167, + "person": "S34504", + "state": "active" + }, + "R25618": { + "course": "induction", + "expires_day": 183, + "person": "S54662", + "state": "active" + }, + "R31142": { + "course": "records", + "expires_day": 205, + "person": "S94362", + "state": "active" + }, + "R35739": { + "course": "induction", + "expires_day": 165, + "person": "S86575", + "state": "active" + }, + "R41196": { + "course": "privacy", + "expires_day": 187, + "person": "S94478", + "state": "active" + }, + "R43299": { + "course": "privacy", + "expires_day": 180, + "person": "S40714", + "state": "active" + }, + "R55351": { + "course": "induction", + "expires_day": 205, + "person": "S21658", + "state": "active" + }, + "R56417": { + "course": "records", + "expires_day": 206, + "person": "S33178", + "state": "active" + }, + "R90030": { + "course": "privacy", + "expires_day": 215, + "person": "S20696", + "state": "retired" + }, + "R93723": { + "course": "records", + "expires_day": 180, + "person": "S42628", + "state": "active" + }, + "R97408": { + "course": "records", + "expires_day": 160, + "person": "S65265", + "state": "active" + } + }, + "leave": { + "S20696": { + "available_day": 205 + }, + "S21658": { + "available_day": 195 + }, + "S33178": { + "available_day": 202 + }, + "S34504": { + "available_day": 168 + }, + "S40714": { + "available_day": 205 + }, + "S42628": { + "available_day": 209 + }, + "S54662": { + "available_day": 209 + }, + "S65265": { + "available_day": 202 + }, + "S86575": { + "available_day": 168 + }, + "S94362": { + "available_day": 205 + }, + "S94478": { + "available_day": 204 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 2, + "start_day": 205 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41822/instruction.md b/tasks/service-hr-certifications-41822/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ac4c86061f7dcc7cc59f093adb3410da4f196a3 --- /dev/null +++ b/tasks/service-hr-certifications-41822/instruction.md @@ -0,0 +1,13 @@ +Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew- in renewals with person, course and session set to renewal. Update the session's remaining seats. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/service-hr-certifications-41822/solution/files/actions.jsonl b/tasks/service-hr-certifications-41822/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1759f6f74daabddfd09f9ce94a8abd640d1673d8 --- /dev/null +++ b/tasks/service-hr-certifications-41822/solution/files/actions.jsonl @@ -0,0 +1,12 @@ +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R35739", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R12307", "op": "update"} +{"app": "certs", "fields": {"state": "deferred"}, "id": "R93723", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R41196", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R55351", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R43299", "op": "update"} +{"app": "certs", "fields": {"state": "deferred"}, "id": "R25618", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R31142", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R97408", "op": "update"} +{"app": "renewals", "fields": {"course": "records", "person": "S65265", "session": "renewal"}, "id": "renew-R97408", "op": "create"} +{"app": "renewals", "fields": {"course": "induction", "person": "S86575", "session": "renewal"}, "id": "renew-R35739", "op": "create"} +{"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"} diff --git a/tasks/service-hr-certifications-41822/solution/solve.sh b/tasks/service-hr-certifications-41822/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/service-hr-certifications-41822/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/service-hr-certifications-41822/task.toml b/tasks/service-hr-certifications-41822/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..335ee4017b52a57694b993d898764344718ccaed --- /dev/null +++ b/tasks/service-hr-certifications-41822/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/service-hr-certifications-41822" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"] +dataset = "Original simulated workflows" +job = "hr" +seed = 41822 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "service-hr-certifications-41822" +template_family = "automation:service-hr-certifications" +workflow_template = "service-hr-certifications" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/service-hr-certifications-41822/tests/expected.json b/tasks/service-hr-certifications-41822/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/service-hr-certifications-41822/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41822/tests/grade.py b/tasks/service-hr-certifications-41822/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/service-hr-certifications-41822/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/service-hr-certifications-41822/tests/replay.py b/tasks/service-hr-certifications-41822/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41822/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41822/tests/target.json b/tasks/service-hr-certifications-41822/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..8408f435683d35460538d0b607599f7817bb3949 --- /dev/null +++ b/tasks/service-hr-certifications-41822/tests/target.json @@ -0,0 +1,123 @@ +{ + "certs": { + "R12307": { + "course": "induction", + "expires_day": 167, + "person": "S34504", + "state": "waitlisted" + }, + "R25618": { + "course": "induction", + "expires_day": 183, + "person": "S54662", + "state": "deferred" + }, + "R31142": { + "course": "records", + "expires_day": 205, + "person": "S94362", + "state": "waitlisted" + }, + "R35739": { + "course": "induction", + "expires_day": 165, + "person": "S86575", + "state": "enrolled" + }, + "R41196": { + "course": "privacy", + "expires_day": 187, + "person": "S94478", + "state": "waitlisted" + }, + "R43299": { + "course": "privacy", + "expires_day": 180, + "person": "S40714", + "state": "waitlisted" + }, + "R55351": { + "course": "induction", + "expires_day": 205, + "person": "S21658", + "state": "waitlisted" + }, + "R56417": { + "course": "records", + "expires_day": 206, + "person": "S33178", + "state": "active" + }, + "R90030": { + "course": "privacy", + "expires_day": 215, + "person": "S20696", + "state": "retired" + }, + "R93723": { + "course": "records", + "expires_day": 180, + "person": "S42628", + "state": "deferred" + }, + "R97408": { + "course": "records", + "expires_day": 160, + "person": "S65265", + "state": "enrolled" + } + }, + "leave": { + "S20696": { + "available_day": 205 + }, + "S21658": { + "available_day": 195 + }, + "S33178": { + "available_day": 202 + }, + "S34504": { + "available_day": 168 + }, + "S40714": { + "available_day": 205 + }, + "S42628": { + "available_day": 209 + }, + "S54662": { + "available_day": 209 + }, + "S65265": { + "available_day": 202 + }, + "S86575": { + "available_day": 168 + }, + "S94362": { + "available_day": 205 + }, + "S94478": { + "available_day": 204 + } + }, + "renewals": { + "renew-R35739": { + "course": "induction", + "person": "S86575", + "session": "renewal" + }, + "renew-R97408": { + "course": "records", + "person": "S65265", + "session": "renewal" + } + }, + "sessions": { + "renewal": { + "seats": 0, + "start_day": 205 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41822/tests/test.sh b/tasks/service-hr-certifications-41822/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/service-hr-certifications-41822/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/service-hr-certifications-41822/tests/world.json b/tasks/service-hr-certifications-41822/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..5581054e330b2ceb25ab1f76972b5d5a45646cc1 --- /dev/null +++ b/tasks/service-hr-certifications-41822/tests/world.json @@ -0,0 +1,112 @@ +{ + "certs": { + "R12307": { + "course": "induction", + "expires_day": 167, + "person": "S34504", + "state": "active" + }, + "R25618": { + "course": "induction", + "expires_day": 183, + "person": "S54662", + "state": "active" + }, + "R31142": { + "course": "records", + "expires_day": 205, + "person": "S94362", + "state": "active" + }, + "R35739": { + "course": "induction", + "expires_day": 165, + "person": "S86575", + "state": "active" + }, + "R41196": { + "course": "privacy", + "expires_day": 187, + "person": "S94478", + "state": "active" + }, + "R43299": { + "course": "privacy", + "expires_day": 180, + "person": "S40714", + "state": "active" + }, + "R55351": { + "course": "induction", + "expires_day": 205, + "person": "S21658", + "state": "active" + }, + "R56417": { + "course": "records", + "expires_day": 206, + "person": "S33178", + "state": "active" + }, + "R90030": { + "course": "privacy", + "expires_day": 215, + "person": "S20696", + "state": "retired" + }, + "R93723": { + "course": "records", + "expires_day": 180, + "person": "S42628", + "state": "active" + }, + "R97408": { + "course": "records", + "expires_day": 160, + "person": "S65265", + "state": "active" + } + }, + "leave": { + "S20696": { + "available_day": 205 + }, + "S21658": { + "available_day": 195 + }, + "S33178": { + "available_day": 202 + }, + "S34504": { + "available_day": 168 + }, + "S40714": { + "available_day": 205 + }, + "S42628": { + "available_day": 209 + }, + "S54662": { + "available_day": 209 + }, + "S65265": { + "available_day": 202 + }, + "S86575": { + "available_day": 168 + }, + "S94362": { + "available_day": 205 + }, + "S94478": { + "available_day": 204 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 2, + "start_day": 205 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41822/tests/world_check.py b/tasks/service-hr-certifications-41822/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/service-hr-certifications-41822/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/service-hr-certifications-41822/validation/openenv.json b/tasks/service-hr-certifications-41822/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..fddaa57ea849fa3e9762275b4fde1ffec6185cb7 --- /dev/null +++ b/tasks/service-hr-certifications-41822/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "hr" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41825/environment/inputs/apps.py b/tasks/service-hr-certifications-41825/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41825/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41825/environment/inputs/world.json b/tasks/service-hr-certifications-41825/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..1e2d95512b97b5456bd28a8b137346a25ed0d4ca --- /dev/null +++ b/tasks/service-hr-certifications-41825/environment/inputs/world.json @@ -0,0 +1,94 @@ +{ + "certs": { + "R17852": { + "course": "privacy", + "expires_day": 289, + "person": "S82744", + "state": "active" + }, + "R18885": { + "course": "records", + "expires_day": 311, + "person": "S82827", + "state": "active" + }, + "R24018": { + "course": "privacy", + "expires_day": 301, + "person": "S95980", + "state": "active" + }, + "R41559": { + "course": "induction", + "expires_day": 313, + "person": "S87397", + "state": "active" + }, + "R58857": { + "course": "privacy", + "expires_day": 290, + "person": "S96200", + "state": "active" + }, + "R60550": { + "course": "records", + "expires_day": 313, + "person": "S54159", + "state": "active" + }, + "R71450": { + "course": "induction", + "expires_day": 318, + "person": "S81318", + "state": "active" + }, + "R97392": { + "course": "records", + "expires_day": 318, + "person": "S48414", + "state": "retired" + }, + "R97400": { + "course": "privacy", + "expires_day": 290, + "person": "S38807", + "state": "active" + } + }, + "leave": { + "S38807": { + "available_day": 310 + }, + "S48414": { + "available_day": 300 + }, + "S54159": { + "available_day": 314 + }, + "S81318": { + "available_day": 307 + }, + "S82744": { + "available_day": 291 + }, + "S82827": { + "available_day": 310 + }, + "S87397": { + "available_day": 300 + }, + "S95980": { + "available_day": 300 + }, + "S96200": { + "available_day": 291 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 3, + "start_day": 310 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41825/instruction.md b/tasks/service-hr-certifications-41825/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ac4c86061f7dcc7cc59f093adb3410da4f196a3 --- /dev/null +++ b/tasks/service-hr-certifications-41825/instruction.md @@ -0,0 +1,13 @@ +Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew- in renewals with person, course and session set to renewal. Update the session's remaining seats. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/service-hr-certifications-41825/solution/files/actions.jsonl b/tasks/service-hr-certifications-41825/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..19ab4db99b2a1d3439493b1d96dc749246f6a5d7 --- /dev/null +++ b/tasks/service-hr-certifications-41825/solution/files/actions.jsonl @@ -0,0 +1,8 @@ +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R58857", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R17852", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R24018", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R97400", "op": "update"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S82744", "session": "renewal"}, "id": "renew-R17852", "op": "create"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S96200", "session": "renewal"}, "id": "renew-R58857", "op": "create"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S38807", "session": "renewal"}, "id": "renew-R97400", "op": "create"} +{"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"} diff --git a/tasks/service-hr-certifications-41825/solution/solve.sh b/tasks/service-hr-certifications-41825/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/service-hr-certifications-41825/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/service-hr-certifications-41825/task.toml b/tasks/service-hr-certifications-41825/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..503ea95d685dbc58fbad2273dbe5f4f95edf0519 --- /dev/null +++ b/tasks/service-hr-certifications-41825/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/service-hr-certifications-41825" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"] +dataset = "Original simulated workflows" +job = "hr" +seed = 41825 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "service-hr-certifications-41825" +template_family = "automation:service-hr-certifications" +workflow_template = "service-hr-certifications" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/service-hr-certifications-41825/tests/expected.json b/tasks/service-hr-certifications-41825/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/service-hr-certifications-41825/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41825/tests/grade.py b/tasks/service-hr-certifications-41825/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/service-hr-certifications-41825/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/service-hr-certifications-41825/tests/replay.py b/tasks/service-hr-certifications-41825/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41825/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41825/tests/target.json b/tasks/service-hr-certifications-41825/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..096af2ba1a872133093ed64f244e7d29935003d4 --- /dev/null +++ b/tasks/service-hr-certifications-41825/tests/target.json @@ -0,0 +1,110 @@ +{ + "certs": { + "R17852": { + "course": "privacy", + "expires_day": 289, + "person": "S82744", + "state": "enrolled" + }, + "R18885": { + "course": "records", + "expires_day": 311, + "person": "S82827", + "state": "active" + }, + "R24018": { + "course": "privacy", + "expires_day": 301, + "person": "S95980", + "state": "waitlisted" + }, + "R41559": { + "course": "induction", + "expires_day": 313, + "person": "S87397", + "state": "active" + }, + "R58857": { + "course": "privacy", + "expires_day": 290, + "person": "S96200", + "state": "enrolled" + }, + "R60550": { + "course": "records", + "expires_day": 313, + "person": "S54159", + "state": "active" + }, + "R71450": { + "course": "induction", + "expires_day": 318, + "person": "S81318", + "state": "active" + }, + "R97392": { + "course": "records", + "expires_day": 318, + "person": "S48414", + "state": "retired" + }, + "R97400": { + "course": "privacy", + "expires_day": 290, + "person": "S38807", + "state": "enrolled" + } + }, + "leave": { + "S38807": { + "available_day": 310 + }, + "S48414": { + "available_day": 300 + }, + "S54159": { + "available_day": 314 + }, + "S81318": { + "available_day": 307 + }, + "S82744": { + "available_day": 291 + }, + "S82827": { + "available_day": 310 + }, + "S87397": { + "available_day": 300 + }, + "S95980": { + "available_day": 300 + }, + "S96200": { + "available_day": 291 + } + }, + "renewals": { + "renew-R17852": { + "course": "privacy", + "person": "S82744", + "session": "renewal" + }, + "renew-R58857": { + "course": "privacy", + "person": "S96200", + "session": "renewal" + }, + "renew-R97400": { + "course": "privacy", + "person": "S38807", + "session": "renewal" + } + }, + "sessions": { + "renewal": { + "seats": 0, + "start_day": 310 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41825/tests/test.sh b/tasks/service-hr-certifications-41825/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/service-hr-certifications-41825/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/service-hr-certifications-41825/tests/world.json b/tasks/service-hr-certifications-41825/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..1e2d95512b97b5456bd28a8b137346a25ed0d4ca --- /dev/null +++ b/tasks/service-hr-certifications-41825/tests/world.json @@ -0,0 +1,94 @@ +{ + "certs": { + "R17852": { + "course": "privacy", + "expires_day": 289, + "person": "S82744", + "state": "active" + }, + "R18885": { + "course": "records", + "expires_day": 311, + "person": "S82827", + "state": "active" + }, + "R24018": { + "course": "privacy", + "expires_day": 301, + "person": "S95980", + "state": "active" + }, + "R41559": { + "course": "induction", + "expires_day": 313, + "person": "S87397", + "state": "active" + }, + "R58857": { + "course": "privacy", + "expires_day": 290, + "person": "S96200", + "state": "active" + }, + "R60550": { + "course": "records", + "expires_day": 313, + "person": "S54159", + "state": "active" + }, + "R71450": { + "course": "induction", + "expires_day": 318, + "person": "S81318", + "state": "active" + }, + "R97392": { + "course": "records", + "expires_day": 318, + "person": "S48414", + "state": "retired" + }, + "R97400": { + "course": "privacy", + "expires_day": 290, + "person": "S38807", + "state": "active" + } + }, + "leave": { + "S38807": { + "available_day": 310 + }, + "S48414": { + "available_day": 300 + }, + "S54159": { + "available_day": 314 + }, + "S81318": { + "available_day": 307 + }, + "S82744": { + "available_day": 291 + }, + "S82827": { + "available_day": 310 + }, + "S87397": { + "available_day": 300 + }, + "S95980": { + "available_day": 300 + }, + "S96200": { + "available_day": 291 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 3, + "start_day": 310 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41825/tests/world_check.py b/tasks/service-hr-certifications-41825/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/service-hr-certifications-41825/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/service-hr-certifications-41825/validation/openenv.json b/tasks/service-hr-certifications-41825/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..fddaa57ea849fa3e9762275b4fde1ffec6185cb7 --- /dev/null +++ b/tasks/service-hr-certifications-41825/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "hr" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41828/environment/inputs/apps.py b/tasks/service-hr-certifications-41828/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41828/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41828/environment/inputs/world.json b/tasks/service-hr-certifications-41828/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..80598d2fd4d13064ec35c40150de5b858a713690 --- /dev/null +++ b/tasks/service-hr-certifications-41828/environment/inputs/world.json @@ -0,0 +1,85 @@ +{ + "certs": { + "R17629": { + "course": "privacy", + "expires_day": 126, + "person": "S27945", + "state": "active" + }, + "R27947": { + "course": "privacy", + "expires_day": 163, + "person": "S36237", + "state": "active" + }, + "R34660": { + "course": "privacy", + "expires_day": 154, + "person": "S20474", + "state": "active" + }, + "R41030": { + "course": "records", + "expires_day": 148, + "person": "S41669", + "state": "retired" + }, + "R70349": { + "course": "privacy", + "expires_day": 121, + "person": "S16607", + "state": "active" + }, + "R73861": { + "course": "induction", + "expires_day": 122, + "person": "S44098", + "state": "active" + }, + "R75884": { + "course": "privacy", + "expires_day": 123, + "person": "S34350", + "state": "active" + }, + "R93130": { + "course": "records", + "expires_day": 162, + "person": "S95282", + "state": "active" + } + }, + "leave": { + "S16607": { + "available_day": 124 + }, + "S20474": { + "available_day": 167 + }, + "S27945": { + "available_day": 167 + }, + "S34350": { + "available_day": 124 + }, + "S36237": { + "available_day": 167 + }, + "S41669": { + "available_day": 162 + }, + "S44098": { + "available_day": 162 + }, + "S95282": { + "available_day": 160 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 3, + "start_day": 163 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41828/instruction.md b/tasks/service-hr-certifications-41828/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ac4c86061f7dcc7cc59f093adb3410da4f196a3 --- /dev/null +++ b/tasks/service-hr-certifications-41828/instruction.md @@ -0,0 +1,13 @@ +Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew- in renewals with person, course and session set to renewal. Update the session's remaining seats. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/service-hr-certifications-41828/solution/files/actions.jsonl b/tasks/service-hr-certifications-41828/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e9d77af763e497463f7103ee223d7932ca0c8bd3 --- /dev/null +++ b/tasks/service-hr-certifications-41828/solution/files/actions.jsonl @@ -0,0 +1,11 @@ +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R70349", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R75884", "op": "update"} +{"app": "certs", "fields": {"state": "deferred"}, "id": "R17629", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R93130", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R73861", "op": "update"} +{"app": "certs", "fields": {"state": "deferred"}, "id": "R34660", "op": "update"} +{"app": "certs", "fields": {"state": "deferred"}, "id": "R27947", "op": "update"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S16607", "session": "renewal"}, "id": "renew-R70349", "op": "create"} +{"app": "renewals", "fields": {"course": "induction", "person": "S44098", "session": "renewal"}, "id": "renew-R73861", "op": "create"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S34350", "session": "renewal"}, "id": "renew-R75884", "op": "create"} +{"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"} diff --git a/tasks/service-hr-certifications-41828/solution/solve.sh b/tasks/service-hr-certifications-41828/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/service-hr-certifications-41828/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/service-hr-certifications-41828/task.toml b/tasks/service-hr-certifications-41828/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5374ffde1a2d5b039ec9656ce55a034c6a48235c --- /dev/null +++ b/tasks/service-hr-certifications-41828/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/service-hr-certifications-41828" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"] +dataset = "Original simulated workflows" +job = "hr" +seed = 41828 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "service-hr-certifications-41828" +template_family = "automation:service-hr-certifications" +workflow_template = "service-hr-certifications" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/service-hr-certifications-41828/tests/expected.json b/tasks/service-hr-certifications-41828/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/service-hr-certifications-41828/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41828/tests/grade.py b/tasks/service-hr-certifications-41828/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/service-hr-certifications-41828/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/service-hr-certifications-41828/tests/replay.py b/tasks/service-hr-certifications-41828/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41828/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41828/tests/target.json b/tasks/service-hr-certifications-41828/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..432734f47db07d896c882be9f69cbbda72458627 --- /dev/null +++ b/tasks/service-hr-certifications-41828/tests/target.json @@ -0,0 +1,101 @@ +{ + "certs": { + "R17629": { + "course": "privacy", + "expires_day": 126, + "person": "S27945", + "state": "deferred" + }, + "R27947": { + "course": "privacy", + "expires_day": 163, + "person": "S36237", + "state": "deferred" + }, + "R34660": { + "course": "privacy", + "expires_day": 154, + "person": "S20474", + "state": "deferred" + }, + "R41030": { + "course": "records", + "expires_day": 148, + "person": "S41669", + "state": "retired" + }, + "R70349": { + "course": "privacy", + "expires_day": 121, + "person": "S16607", + "state": "enrolled" + }, + "R73861": { + "course": "induction", + "expires_day": 122, + "person": "S44098", + "state": "enrolled" + }, + "R75884": { + "course": "privacy", + "expires_day": 123, + "person": "S34350", + "state": "enrolled" + }, + "R93130": { + "course": "records", + "expires_day": 162, + "person": "S95282", + "state": "waitlisted" + } + }, + "leave": { + "S16607": { + "available_day": 124 + }, + "S20474": { + "available_day": 167 + }, + "S27945": { + "available_day": 167 + }, + "S34350": { + "available_day": 124 + }, + "S36237": { + "available_day": 167 + }, + "S41669": { + "available_day": 162 + }, + "S44098": { + "available_day": 162 + }, + "S95282": { + "available_day": 160 + } + }, + "renewals": { + "renew-R70349": { + "course": "privacy", + "person": "S16607", + "session": "renewal" + }, + "renew-R73861": { + "course": "induction", + "person": "S44098", + "session": "renewal" + }, + "renew-R75884": { + "course": "privacy", + "person": "S34350", + "session": "renewal" + } + }, + "sessions": { + "renewal": { + "seats": 0, + "start_day": 163 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41828/tests/test.sh b/tasks/service-hr-certifications-41828/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/service-hr-certifications-41828/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/service-hr-certifications-41828/tests/world.json b/tasks/service-hr-certifications-41828/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..80598d2fd4d13064ec35c40150de5b858a713690 --- /dev/null +++ b/tasks/service-hr-certifications-41828/tests/world.json @@ -0,0 +1,85 @@ +{ + "certs": { + "R17629": { + "course": "privacy", + "expires_day": 126, + "person": "S27945", + "state": "active" + }, + "R27947": { + "course": "privacy", + "expires_day": 163, + "person": "S36237", + "state": "active" + }, + "R34660": { + "course": "privacy", + "expires_day": 154, + "person": "S20474", + "state": "active" + }, + "R41030": { + "course": "records", + "expires_day": 148, + "person": "S41669", + "state": "retired" + }, + "R70349": { + "course": "privacy", + "expires_day": 121, + "person": "S16607", + "state": "active" + }, + "R73861": { + "course": "induction", + "expires_day": 122, + "person": "S44098", + "state": "active" + }, + "R75884": { + "course": "privacy", + "expires_day": 123, + "person": "S34350", + "state": "active" + }, + "R93130": { + "course": "records", + "expires_day": 162, + "person": "S95282", + "state": "active" + } + }, + "leave": { + "S16607": { + "available_day": 124 + }, + "S20474": { + "available_day": 167 + }, + "S27945": { + "available_day": 167 + }, + "S34350": { + "available_day": 124 + }, + "S36237": { + "available_day": 167 + }, + "S41669": { + "available_day": 162 + }, + "S44098": { + "available_day": 162 + }, + "S95282": { + "available_day": 160 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 3, + "start_day": 163 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41828/tests/world_check.py b/tasks/service-hr-certifications-41828/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/service-hr-certifications-41828/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/service-hr-certifications-41828/validation/openenv.json b/tasks/service-hr-certifications-41828/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..fddaa57ea849fa3e9762275b4fde1ffec6185cb7 --- /dev/null +++ b/tasks/service-hr-certifications-41828/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "hr" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41831/environment/inputs/apps.py b/tasks/service-hr-certifications-41831/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41831/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41831/environment/inputs/world.json b/tasks/service-hr-certifications-41831/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..a0cc14282a8cc7d9759b3798759c15e67f64defa --- /dev/null +++ b/tasks/service-hr-certifications-41831/environment/inputs/world.json @@ -0,0 +1,121 @@ +{ + "certs": { + "R12986": { + "course": "records", + "expires_day": 191, + "person": "S77649", + "state": "active" + }, + "R18310": { + "course": "privacy", + "expires_day": 173, + "person": "S33826", + "state": "active" + }, + "R43333": { + "course": "induction", + "expires_day": 179, + "person": "S27291", + "state": "active" + }, + "R47275": { + "course": "privacy", + "expires_day": 195, + "person": "S90080", + "state": "active" + }, + "R52109": { + "course": "privacy", + "expires_day": 197, + "person": "S32762", + "state": "active" + }, + "R52316": { + "course": "records", + "expires_day": 179, + "person": "S13988", + "state": "active" + }, + "R69404": { + "course": "records", + "expires_day": 175, + "person": "S28085", + "state": "active" + }, + "R72767": { + "course": "records", + "expires_day": 200, + "person": "S61200", + "state": "active" + }, + "R74822": { + "course": "records", + "expires_day": 175, + "person": "S61888", + "state": "active" + }, + "R83132": { + "course": "induction", + "expires_day": 205, + "person": "S14572", + "state": "retired" + }, + "R93767": { + "course": "privacy", + "expires_day": 200, + "person": "S60659", + "state": "active" + }, + "R96230": { + "course": "privacy", + "expires_day": 199, + "person": "S48267", + "state": "active" + } + }, + "leave": { + "S13988": { + "available_day": 183 + }, + "S14572": { + "available_day": 202 + }, + "S27291": { + "available_day": 183 + }, + "S28085": { + "available_day": 202 + }, + "S32762": { + "available_day": 203 + }, + "S33826": { + "available_day": 207 + }, + "S48267": { + "available_day": 200 + }, + "S60659": { + "available_day": 193 + }, + "S61200": { + "available_day": 193 + }, + "S61888": { + "available_day": 203 + }, + "S77649": { + "available_day": 207 + }, + "S90080": { + "available_day": 203 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 4, + "start_day": 203 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41831/instruction.md b/tasks/service-hr-certifications-41831/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ac4c86061f7dcc7cc59f093adb3410da4f196a3 --- /dev/null +++ b/tasks/service-hr-certifications-41831/instruction.md @@ -0,0 +1,13 @@ +Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew- in renewals with person, course and session set to renewal. Update the session's remaining seats. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/service-hr-certifications-41831/solution/files/actions.jsonl b/tasks/service-hr-certifications-41831/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f6bfd141aaf8fbc7e6ee59eaeda4d3817757ddfa --- /dev/null +++ b/tasks/service-hr-certifications-41831/solution/files/actions.jsonl @@ -0,0 +1,16 @@ +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R52316", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R43333", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R72767", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R52109", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R47275", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R74822", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R93767", "op": "update"} +{"app": "certs", "fields": {"state": "deferred"}, "id": "R12986", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R69404", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R96230", "op": "update"} +{"app": "certs", "fields": {"state": "deferred"}, "id": "R18310", "op": "update"} +{"app": "renewals", "fields": {"course": "records", "person": "S28085", "session": "renewal"}, "id": "renew-R69404", "op": "create"} +{"app": "renewals", "fields": {"course": "records", "person": "S61888", "session": "renewal"}, "id": "renew-R74822", "op": "create"} +{"app": "renewals", "fields": {"course": "induction", "person": "S27291", "session": "renewal"}, "id": "renew-R43333", "op": "create"} +{"app": "renewals", "fields": {"course": "records", "person": "S13988", "session": "renewal"}, "id": "renew-R52316", "op": "create"} +{"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"} diff --git a/tasks/service-hr-certifications-41831/solution/solve.sh b/tasks/service-hr-certifications-41831/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2a287da2db131d4ef042f5a6c2d1c3bed03acf0 --- /dev/null +++ b/tasks/service-hr-certifications-41831/solution/solve.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /workspace/outputs +cp -R /solution/files/. /workspace/outputs/ diff --git a/tasks/service-hr-certifications-41831/task.toml b/tasks/service-hr-certifications-41831/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..00b1baa390c9c20cac410aad4d9b4d335116b778 --- /dev/null +++ b/tasks/service-hr-certifications-41831/task.toml @@ -0,0 +1,46 @@ +schema_version = "1.3" + +[task] +name = "apex-gap/service-hr-certifications-41831" + +[metadata.apex_gap] +capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"] +dataset = "Original simulated workflows" +job = "hr" +seed = 41831 +source = "local/original-automation-workflows" +source_revision = "1" +source_split = "synthetic" +source_task_id = "service-hr-certifications-41831" +template_family = "automation:service-hr-certifications" +workflow_template = "service-hr-certifications" + +[metadata.openenv_hf_sandbox] +variant = "apex-gap-hfsandbox-v1" +task_modified_for_hf_sandbox = true +network_enabled = true + +[environment] +docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf" +workdir = "/workspace" +cpus = 1 +memory_mb = 4096 +build_timeout_sec = 600 +network_mode = "public" + +[agent] +timeout_sec = 1800 +network_mode = "public" + +[verifier] +timeout_sec = 600 +network_mode = "public" +environment_mode = "separate" + +[verifier.environment] +network_mode = "public" +cpus = 1 +memory_mb = 4096 + +[[artifacts]] +source = "/workspace/outputs" diff --git a/tasks/service-hr-certifications-41831/tests/expected.json b/tasks/service-hr-certifications-41831/tests/expected.json new file mode 100644 index 0000000000000000000000000000000000000000..404f50550b5d272df3418f73b71a3814579ffa30 --- /dev/null +++ b/tasks/service-hr-certifications-41831/tests/expected.json @@ -0,0 +1,9 @@ +{ + "checks": [ + { + "id": "business-outcomes", + "type": "custom", + "module": "world_check" + } + ] +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41831/tests/grade.py b/tasks/service-hr-certifications-41831/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..037f80a598ed5029d076841c21fa3c475432155e --- /dev/null +++ b/tasks/service-hr-certifications-41831/tests/grade.py @@ -0,0 +1,330 @@ +"""Deterministic grader shared by converted knowledge-work tasks. + +Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the +submitted /workspace/outputs tree and writes a binary reward plus per-check details. +No model calls and no network. + +expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]} +Check types: + answer field of outputs/answer.json; kind = number|text|choice|date|bool|list + xlsx_range recalculated outputs/ vs tests/ over sheet!range (SpreadsheetBench rules) + xlsx_cell recalculated outputs/ sheet!cell vs value with tolerance (optional alt_values) + file_contains outputs/ text (docx/pdf/ics/eml/txt) must contain every needle + custom tests/.py defines check(spec, outputs_dir, tests_dir) -> (bool, str) +""" + +import datetime as dt +import json +import re +import shutil +import subprocess +import sys +import tempfile +import unicodedata +from pathlib import Path + +OUT = Path("/workspace/outputs") +TESTS = Path("/tests") +LOGS = Path("/logs/verifier") + + +def norm_text(v): + v = unicodedata.normalize("NFKC", str(v)).casefold() + v = re.sub(r"[‘’“”]", "'", v) + v = re.sub(r"[^\w%.$/-]+", " ", v) + return " ".join(v.split()).strip(" .") + + +def to_number(v): + if isinstance(v, bool): + raise ValueError("bool") + if isinstance(v, (int, float)): + return float(v) + s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-") + neg = s.startswith("(") and s.endswith(")") + s = s.strip("()").strip() + pct = s.endswith("%") + s = s.rstrip("%").strip() + s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I) + x = float(s) + x = -x if neg else x + return x / 100 if pct else x + + +def number_ok(got, want, rel, abs_): + try: + g = to_number(got) + except (TypeError, ValueError): + return False + w = float(want) + tol = max(abs_, rel * abs(w)) + # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which. + candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g] + return any(abs(c - w) <= tol for c in candidates) + + +def parse_date(v): + if isinstance(v, (dt.date, dt.datetime)): + return v if isinstance(v, dt.date) else v.date() + s = str(v).strip() + for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"): + try: + return dt.datetime.strptime(s, fmt).date() + except ValueError: + continue + raise ValueError(s) + + +def check_answer(check, answers): + key = check["field"] + if key not in answers: + return False, f"missing field {key!r}" + got, want, kind = answers[key], check["value"], check.get("kind", "text") + if kind == "number": + ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01)) + if not ok and check.get("percent_either"): + ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or ( + number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100) + ) + elif kind == "date": + try: + ok = parse_date(got) == parse_date(want) + except ValueError: + ok = False + elif kind == "bool": + g = norm_text(got) + ok = g in {"yes", "true"} if want else g in {"no", "false"} + elif kind == "choice": + ok = norm_text(got) == norm_text(want) + elif kind == "list": + if not isinstance(got, list): + return False, f"{key}: expected a JSON list" + # Filenames may be given with a directory prefix; compare base names. + base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1]) + ok = sorted(base(x) for x in got) == sorted(base(x) for x in want) + else: + accepted = check.get("accept", [want]) + ok = norm_text(got) in {norm_text(a) for a in accepted} + return ok, "" if ok else f"{key}: got {got!r}" + + +# LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation. +RECALC_PROFILE = """ + +0 +0 + +""" + + +def recalc(path, tmp): + dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}" + dest.mkdir() + profile = Path(tmp) / "lo-profile" + if not profile.exists(): + (profile / "user").mkdir(parents=True) + (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE) + subprocess.run( + ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to", + "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=180, + check=False, + ) + out = dest / (Path(path).stem + ".xlsx") + return out if out.exists() else Path(path) + + +def cell_value(v): + if isinstance(v, (int, float)) and not isinstance(v, bool): + return round(float(v), 2) + if isinstance(v, dt.datetime): + return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0) + if isinstance(v, dt.time): + return v.strftime("%H:%M") + if isinstance(v, str): + try: + return round(float(v), 2) + except ValueError: + return v.strip() + return v + + +def time_of(v): + """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and + Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells.""" + if isinstance(v, dt.time): + v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400 + if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1: + return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M") + return None + + +def same_cell(a, b): + if isinstance(a, dt.time) is not isinstance(b, dt.time): + n = b if isinstance(a, dt.time) else a + if time_of(n) is not None: # a time against a plain day fraction + return time_of(a) == time_of(b) + a, b = cell_value(a), cell_value(b) + if a in (None, "") and b in (None, ""): + return True + return type(a) is type(b) and a == b + + +ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"} + + +def is_error(v): + return isinstance(v, str) and (v in ERRORS or v.startswith("Err:")) + + +def cells(rng): + if ":" not in rng: + return [rng] + from openpyxl.utils import range_boundaries, get_column_letter + + c1, r1, c2, r2 = range_boundaries(rng) + return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)] + + +def load(path, tmp): + import openpyxl + + return openpyxl.load_workbook(recalc(path, tmp), data_only=True) + + +def check_xlsx_range(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + tgt = TESTS / check["target"] + if tgt not in cache: + cache[tgt] = load(tgt, tmp) + got, want = cache[sub], cache[tgt] + cached = None # the target's stored (Excel-computed) values, read only when Calc errs + for sheet, rng in check["ranges"]: + sheet = sheet or want.sheetnames[0] + if sheet not in got.sheetnames: + return False, f"sheet {sheet!r} missing" + for name in cells(rng): + w = want[sheet][name].value + if is_error(w): + # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4). + # The value Excel stored is the intended answer. + if cached is None: + import openpyxl + + cached = openpyxl.load_workbook(tgt, data_only=True) + c = cached[sheet][name].value if sheet in cached.sheetnames else None + if c is not None and not is_error(c): + w = c + if not same_cell(w, got[sheet][name].value): + return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}" + return True, "" + + +def check_xlsx_cell(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + if sub not in cache: + cache[sub] = load(sub, tmp) + wb = cache[sub] + if check["sheet"] not in wb.sheetnames: + return False, f"sheet {check['sheet']!r} missing" + got = wb[check["sheet"]][check["cell"]].value + want = check["value"] + if isinstance(want, (int, float)): + # alt_values: other accepted golds where the source admits more than one reading. + ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01)) + for w in [want, *check.get("alt_values", [])]) + else: + ok = norm_text(got) == norm_text(want) + return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}" + + +def text_of(path): + suffix = path.suffix.lower() + if suffix == ".docx": + import docx + + d = docx.Document(path) + parts = [p.text for p in d.paragraphs] + for t in d.tables: + parts += [c.text for row in t.rows for c in row.cells] + return "\n".join(parts) + if suffix == ".pdf": + import pdfplumber + + with pdfplumber.open(path) as pdf: + return "\n".join(page.extract_text() or "" for page in pdf.pages) + return path.read_text(errors="replace") + + +def check_file_contains(check, tmp, cache): + sub = OUT / check["file"] + if not sub.is_file(): + return False, f"missing output {check['file']}" + text = text_of(sub) + hay = text if check.get("case_sensitive") else text.casefold() + for needle in check["needles"]: + n = needle if check.get("case_sensitive") else needle.casefold() + if n not in hay: + return False, f"{check['file']} lacks {needle!r}" + return True, "" + + +def main(): + LOGS.mkdir(parents=True, exist_ok=True) + reward_path = LOGS / "reward.txt" + reward_path.write_text("0\n") + spec = json.loads((TESTS / "expected.json").read_text()) + answers, details = {}, [] + answer_file = OUT / "answer.json" + if answer_file.is_file(): + try: + answers = json.loads(answer_file.read_text()) + if not isinstance(answers, dict): + answers = {} + except json.JSONDecodeError: + answers = {} + tmp = tempfile.mkdtemp() + cache = {} + try: + for check in spec["checks"]: + try: + if check["type"] == "answer": + ok, why = check_answer(check, answers) + elif check["type"] == "xlsx_range": + ok, why = check_xlsx_range(check, tmp, cache) + elif check["type"] == "xlsx_cell": + ok, why = check_xlsx_cell(check, tmp, cache) + elif check["type"] == "file_contains": + ok, why = check_file_contains(check, tmp, cache) + elif check["type"] == "custom": + import importlib.util + + spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py") + mod = importlib.util.module_from_spec(spec_) + spec_.loader.exec_module(mod) + ok, why = mod.check(check, OUT, TESTS) + else: + ok, why = False, f"unknown check type {check['type']}" + except Exception as exc: # a malformed submission fails the check, not the grader + ok, why = False, f"{type(exc).__name__}: {exc}" + details.append({"id": check["id"], "passed": ok, "detail": why}) + finally: + shutil.rmtree(tmp, ignore_errors=True) + passed = sum(d["passed"] for d in details) + total = len(details) + reward = 1 if total and passed == total else 0 + (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1)) + reward_path.write_text(f"{reward}\n") + print(f"{passed}/{total} checks passed; reward {reward}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/service-hr-certifications-41831/tests/replay.py b/tasks/service-hr-certifications-41831/tests/replay.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41831/tests/replay.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41831/tests/target.json b/tasks/service-hr-certifications-41831/tests/target.json new file mode 100644 index 0000000000000000000000000000000000000000..05578db11eb5123f62a933a3026003fcde64177a --- /dev/null +++ b/tasks/service-hr-certifications-41831/tests/target.json @@ -0,0 +1,142 @@ +{ + "certs": { + "R12986": { + "course": "records", + "expires_day": 191, + "person": "S77649", + "state": "deferred" + }, + "R18310": { + "course": "privacy", + "expires_day": 173, + "person": "S33826", + "state": "deferred" + }, + "R43333": { + "course": "induction", + "expires_day": 179, + "person": "S27291", + "state": "enrolled" + }, + "R47275": { + "course": "privacy", + "expires_day": 195, + "person": "S90080", + "state": "waitlisted" + }, + "R52109": { + "course": "privacy", + "expires_day": 197, + "person": "S32762", + "state": "waitlisted" + }, + "R52316": { + "course": "records", + "expires_day": 179, + "person": "S13988", + "state": "enrolled" + }, + "R69404": { + "course": "records", + "expires_day": 175, + "person": "S28085", + "state": "enrolled" + }, + "R72767": { + "course": "records", + "expires_day": 200, + "person": "S61200", + "state": "waitlisted" + }, + "R74822": { + "course": "records", + "expires_day": 175, + "person": "S61888", + "state": "enrolled" + }, + "R83132": { + "course": "induction", + "expires_day": 205, + "person": "S14572", + "state": "retired" + }, + "R93767": { + "course": "privacy", + "expires_day": 200, + "person": "S60659", + "state": "waitlisted" + }, + "R96230": { + "course": "privacy", + "expires_day": 199, + "person": "S48267", + "state": "waitlisted" + } + }, + "leave": { + "S13988": { + "available_day": 183 + }, + "S14572": { + "available_day": 202 + }, + "S27291": { + "available_day": 183 + }, + "S28085": { + "available_day": 202 + }, + "S32762": { + "available_day": 203 + }, + "S33826": { + "available_day": 207 + }, + "S48267": { + "available_day": 200 + }, + "S60659": { + "available_day": 193 + }, + "S61200": { + "available_day": 193 + }, + "S61888": { + "available_day": 203 + }, + "S77649": { + "available_day": 207 + }, + "S90080": { + "available_day": 203 + } + }, + "renewals": { + "renew-R43333": { + "course": "induction", + "person": "S27291", + "session": "renewal" + }, + "renew-R52316": { + "course": "records", + "person": "S13988", + "session": "renewal" + }, + "renew-R69404": { + "course": "records", + "person": "S28085", + "session": "renewal" + }, + "renew-R74822": { + "course": "records", + "person": "S61888", + "session": "renewal" + } + }, + "sessions": { + "renewal": { + "seats": 0, + "start_day": 203 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41831/tests/test.sh b/tasks/service-hr-certifications-41831/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..56afc332f7a5880f3b6f1fbcc47b0d82b2e327a3 --- /dev/null +++ b/tasks/service-hr-certifications-41831/tests/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +mkdir -p /logs/verifier /workspace/outputs +exec python3 -B -I /tests/grade.py diff --git a/tasks/service-hr-certifications-41831/tests/world.json b/tasks/service-hr-certifications-41831/tests/world.json new file mode 100644 index 0000000000000000000000000000000000000000..a0cc14282a8cc7d9759b3798759c15e67f64defa --- /dev/null +++ b/tasks/service-hr-certifications-41831/tests/world.json @@ -0,0 +1,121 @@ +{ + "certs": { + "R12986": { + "course": "records", + "expires_day": 191, + "person": "S77649", + "state": "active" + }, + "R18310": { + "course": "privacy", + "expires_day": 173, + "person": "S33826", + "state": "active" + }, + "R43333": { + "course": "induction", + "expires_day": 179, + "person": "S27291", + "state": "active" + }, + "R47275": { + "course": "privacy", + "expires_day": 195, + "person": "S90080", + "state": "active" + }, + "R52109": { + "course": "privacy", + "expires_day": 197, + "person": "S32762", + "state": "active" + }, + "R52316": { + "course": "records", + "expires_day": 179, + "person": "S13988", + "state": "active" + }, + "R69404": { + "course": "records", + "expires_day": 175, + "person": "S28085", + "state": "active" + }, + "R72767": { + "course": "records", + "expires_day": 200, + "person": "S61200", + "state": "active" + }, + "R74822": { + "course": "records", + "expires_day": 175, + "person": "S61888", + "state": "active" + }, + "R83132": { + "course": "induction", + "expires_day": 205, + "person": "S14572", + "state": "retired" + }, + "R93767": { + "course": "privacy", + "expires_day": 200, + "person": "S60659", + "state": "active" + }, + "R96230": { + "course": "privacy", + "expires_day": 199, + "person": "S48267", + "state": "active" + } + }, + "leave": { + "S13988": { + "available_day": 183 + }, + "S14572": { + "available_day": 202 + }, + "S27291": { + "available_day": 183 + }, + "S28085": { + "available_day": 202 + }, + "S32762": { + "available_day": 203 + }, + "S33826": { + "available_day": 207 + }, + "S48267": { + "available_day": 200 + }, + "S60659": { + "available_day": 193 + }, + "S61200": { + "available_day": 193 + }, + "S61888": { + "available_day": 203 + }, + "S77649": { + "available_day": 207 + }, + "S90080": { + "available_day": 203 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 4, + "start_day": 203 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41831/tests/world_check.py b/tasks/service-hr-certifications-41831/tests/world_check.py new file mode 100644 index 0000000000000000000000000000000000000000..c1ae1d241cf41e839dc140339b0367d0c9b3591f --- /dev/null +++ b/tasks/service-hr-certifications-41831/tests/world_check.py @@ -0,0 +1,26 @@ +"""Replay submitted mutations from the private verifier's initial state.""" +from types import ModuleType +import json + + +def check(spec, outputs, tests): + replay = ModuleType('workflow_replay') + exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__) + world = json.loads((tests/'world.json').read_text()) + target = json.loads((tests/'target.json').read_text()) + # Only fields whose starting and expected values differ may be changed. Attempts + # to temporarily alter a protected field fail even when a later write restores it. + allowed = { + (app,key): {field for field,value in doc.items() + if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)} + for app,records in target.items() for key,doc in records.items() + } + actions = replay.load_actions(outputs/'actions.jsonl') + for event in actions: + replay.apply(world,event) + touched = set(event['fields']) + if not touched <= allowed.get((event['app'],event['id']),set()): + return False,'protected field or record write' + if not replay.same(world,target): + return False,'required business outcomes incomplete' + return True,'' diff --git a/tasks/service-hr-certifications-41831/validation/openenv.json b/tasks/service-hr-certifications-41831/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..fddaa57ea849fa3e9762275b4fde1ffec6185cb7 --- /dev/null +++ b/tasks/service-hr-certifications-41831/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "profile": "harbor-semantic-v1", + "reward_key": "reward", + "reward": { + "range": [ + 0, + 1 + ], + "oracle_tolerance": 0, + "floor_margin": 0.1 + }, + "resources": { + "cpu": 1, + "memory_mb": 4096, + "disk_mb": 10240, + "episode_timeout_s": 1800 + }, + "types": { + "tags": [ + "knowledge-work", + "cross-app-workflows", + "conditional-execution", + "protected-state", + "hr" + ] + }, + "requires_credentials": false +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41834/environment/inputs/apps.py b/tasks/service-hr-certifications-41834/environment/inputs/apps.py new file mode 100644 index 0000000000000000000000000000000000000000..b977e92875fd7b16c40b939c4533b214315a31bc --- /dev/null +++ b/tasks/service-hr-certifications-41834/environment/inputs/apps.py @@ -0,0 +1,68 @@ +"""Offline business-app client. Print usage with --help.""" +import argparse +import copy +import fcntl +import json +import os +from pathlib import Path + + +def same(left, right): + return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False) + + +def apply(world, action): + if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}: + raise ValueError('expected op, app, id, fields') + op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields')) + if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields: + raise ValueError('unknown app, invalid id or empty fields') + collection = world[app] + if op == 'update' and key in collection: + collection[key].update(copy.deepcopy(fields)) + elif op == 'create' and key not in collection: + collection[key] = copy.deepcopy(fields) + else: + raise ValueError(f'invalid {op} for {app}/{key}') + + +def load_actions(path): + if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000): + raise ValueError('invalid action log') + if not path.exists(): + return [] + return [json.loads(s) for s in path.read_text().splitlines() if s.strip()] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('op', choices=('apps','list','get','update','create')) + parser.add_argument('app', nargs='?') + parser.add_argument('id', nargs='?') + parser.add_argument('fields', nargs='?', type=json.loads) + args = parser.parse_args() + world = json.loads(Path(__file__).with_name('world.json').read_text()) + out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs')) + out.mkdir(parents=True, exist_ok=True) + log = out/'actions.jsonl' + with (out/'.actions.lock').open('a') as lock: + fcntl.flock(lock.fileno(), fcntl.LOCK_EX) + for event in load_actions(log): + apply(world,event) + if args.op=='apps': + value=sorted(world) + elif args.op=='list': + value=world[args.app] + elif args.op=='get': + value=world[args.app][args.id] + else: + event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields} + apply(world,event) + with log.open('a') as handle: + handle.write(json.dumps(event,allow_nan=False)+'\n') + value=world[args.app][args.id] + print(json.dumps(value,sort_keys=True,allow_nan=False)) + + +if __name__=='__main__': + main() diff --git a/tasks/service-hr-certifications-41834/environment/inputs/world.json b/tasks/service-hr-certifications-41834/environment/inputs/world.json new file mode 100644 index 0000000000000000000000000000000000000000..53f3efd631c1934bf4ee37ae2bdd2cf89d918423 --- /dev/null +++ b/tasks/service-hr-certifications-41834/environment/inputs/world.json @@ -0,0 +1,112 @@ +{ + "certs": { + "R14795": { + "course": "induction", + "expires_day": 475, + "person": "S47232", + "state": "active" + }, + "R17387": { + "course": "privacy", + "expires_day": 493, + "person": "S44297", + "state": "active" + }, + "R29167": { + "course": "records", + "expires_day": 488, + "person": "S29415", + "state": "active" + }, + "R31665": { + "course": "privacy", + "expires_day": 460, + "person": "S34408", + "state": "active" + }, + "R32632": { + "course": "privacy", + "expires_day": 455, + "person": "S13138", + "state": "active" + }, + "R49769": { + "course": "records", + "expires_day": 455, + "person": "S58788", + "state": "active" + }, + "R61393": { + "course": "records", + "expires_day": 451, + "person": "S65830", + "state": "active" + }, + "R63021": { + "course": "privacy", + "expires_day": 473, + "person": "S81260", + "state": "active" + }, + "R70074": { + "course": "induction", + "expires_day": 480, + "person": "S96518", + "state": "active" + }, + "R78798": { + "course": "records", + "expires_day": 455, + "person": "S69713", + "state": "active" + }, + "R90130": { + "course": "induction", + "expires_day": 464, + "person": "S68520", + "state": "retired" + } + }, + "leave": { + "S13138": { + "available_day": 459 + }, + "S29415": { + "available_day": 475 + }, + "S34408": { + "available_day": 485 + }, + "S44297": { + "available_day": 485 + }, + "S47232": { + "available_day": 489 + }, + "S58788": { + "available_day": 484 + }, + "S65830": { + "available_day": 489 + }, + "S68520": { + "available_day": 482 + }, + "S69713": { + "available_day": 459 + }, + "S81260": { + "available_day": 482 + }, + "S96518": { + "available_day": 475 + } + }, + "renewals": {}, + "sessions": { + "renewal": { + "seats": 4, + "start_day": 485 + } + } +} \ No newline at end of file diff --git a/tasks/service-hr-certifications-41834/instruction.md b/tasks/service-hr-certifications-41834/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ac4c86061f7dcc7cc59f093adb3410da4f196a3 --- /dev/null +++ b/tasks/service-hr-certifications-41834/instruction.md @@ -0,0 +1,13 @@ +Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew- in renewals with person, course and session set to renewal. Update the session's remaining seats. + +Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run +`apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record. +Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`. +The client records successful writes in `/workspace/outputs/actions.jsonl`. +Apply exactly the required changes. Other records and fields must remain untouched, +including temporary changes. Actions take effect in the local simulation only. + +## Deliverable + +Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in +`/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory. diff --git a/tasks/service-hr-certifications-41834/solution/files/actions.jsonl b/tasks/service-hr-certifications-41834/solution/files/actions.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..92e1246b7d7414e246ec862a3f826632760ef934 --- /dev/null +++ b/tasks/service-hr-certifications-41834/solution/files/actions.jsonl @@ -0,0 +1,13 @@ +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R32632", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R78798", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R63021", "op": "update"} +{"app": "certs", "fields": {"state": "deferred"}, "id": "R14795", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R49769", "op": "update"} +{"app": "certs", "fields": {"state": "enrolled"}, "id": "R31665", "op": "update"} +{"app": "certs", "fields": {"state": "deferred"}, "id": "R61393", "op": "update"} +{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R70074", "op": "update"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S13138", "session": "renewal"}, "id": "renew-R32632", "op": "create"} +{"app": "renewals", "fields": {"course": "records", "person": "S58788", "session": "renewal"}, "id": "renew-R49769", "op": "create"} +{"app": "renewals", "fields": {"course": "records", "person": "S69713", "session": "renewal"}, "id": "renew-R78798", "op": "create"} +{"app": "renewals", "fields": {"course": "privacy", "person": "S34408", "session": "renewal"}, "id": "renew-R31665", "op": "create"} +{"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"}