Harbor format: 210 business_automation tasks (part 7)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- tasks/service-hr-certifications-41834/solution/solve.shAdded+4
- tasks/service-hr-certifications-41834/task.tomlAdded+46
- tasks/service-hr-certifications-41834/tests/expected.jsonAdded+9
- tasks/service-hr-certifications-41834/tests/grade.pyAdded+330
- tasks/service-hr-certifications-41834/tests/replay.pyAdded+68
- tasks/service-hr-certifications-41834/tests/target.jsonAdded+133
- tasks/service-hr-certifications-41834/tests/test.shAdded+4
- tasks/service-hr-certifications-41834/tests/world.jsonAdded+112
- tasks/service-hr-certifications-41834/tests/world_check.pyAdded+26
- tasks/service-hr-certifications-41834/validation/openenv.jsonAdded+28
- tasks/service-hr-certifications-41837/environment/inputs/apps.pyAdded+68
- tasks/service-hr-certifications-41837/environment/inputs/world.jsonAdded+76
- tasks/service-hr-certifications-41837/instruction.mdAdded+13
- tasks/service-hr-certifications-41837/solution/files/actions.jsonlAdded+8
- tasks/service-hr-certifications-41837/solution/solve.shAdded+4
- tasks/service-hr-certifications-41837/task.tomlAdded+46
- tasks/service-hr-certifications-41837/tests/expected.jsonAdded+9
- tasks/service-hr-certifications-41837/tests/grade.pyAdded+330
- tasks/service-hr-certifications-41837/tests/replay.pyAdded+68
- tasks/service-hr-certifications-41837/tests/target.jsonAdded+87
- tasks/service-hr-certifications-41837/tests/test.shAdded+4
- tasks/service-hr-certifications-41837/tests/world.jsonAdded+76
- tasks/service-hr-certifications-41837/tests/world_check.pyAdded+26
- tasks/service-hr-certifications-41837/validation/openenv.jsonAdded+28
- tasks/service-hr-certifications-41840/environment/inputs/apps.pyAdded+68
- tasks/service-hr-certifications-41840/environment/inputs/world.jsonAdded+85
- tasks/service-hr-certifications-41840/instruction.mdAdded+13
- tasks/service-hr-certifications-41840/solution/files/actions.jsonlAdded+9
- tasks/service-hr-certifications-41840/solution/solve.shAdded+4
- tasks/service-hr-certifications-41840/task.tomlAdded+46
- tasks/service-hr-certifications-41840/tests/expected.jsonAdded+9
- tasks/service-hr-certifications-41840/tests/grade.pyAdded+330
- tasks/service-hr-certifications-41840/tests/replay.pyAdded+68
- tasks/service-hr-certifications-41840/tests/target.jsonAdded+101
- tasks/service-hr-certifications-41840/tests/test.shAdded+4
- tasks/service-hr-certifications-41840/tests/world.jsonAdded+85
- tasks/service-hr-certifications-41840/tests/world_check.pyAdded+26
- tasks/service-hr-certifications-41840/validation/openenv.jsonAdded+28
- tasks/service-hr-certifications-41843/environment/inputs/apps.pyAdded+68
- tasks/service-hr-certifications-41843/environment/inputs/world.jsonAdded+103
- tasks/service-hr-certifications-41843/instruction.mdAdded+13
- tasks/service-hr-certifications-41843/solution/files/actions.jsonlAdded+12
- tasks/service-hr-certifications-41843/solution/solve.shAdded+4
- tasks/service-hr-certifications-41843/task.tomlAdded+46
- tasks/service-hr-certifications-41843/tests/expected.jsonAdded+9
- tasks/service-hr-certifications-41843/tests/grade.pyAdded+330
- tasks/service-hr-certifications-41843/tests/replay.pyAdded+68
- tasks/service-hr-certifications-41843/tests/target.jsonAdded+119
- tasks/service-hr-certifications-41843/tests/test.shAdded+4
- tasks/service-hr-certifications-41843/tests/world.jsonAdded+103
1234#!/bin/shset -eumkdir -p /workspace/outputscp -R /solution/files/. /workspace/outputs/12345678910111213141516171819202122232425262728293031323334353637383940414243444546schema_version = "1.3"
[task]name = "apex-gap/service-hr-certifications-41834"
[metadata.apex_gap]capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"]dataset = "Original simulated workflows"job = "hr"seed = 41834source = "local/original-automation-workflows"source_revision = "1"source_split = "synthetic"source_task_id = "service-hr-certifications-41834"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 = truenetwork_enabled = true
[environment]docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf"workdir = "/workspace"cpus = 1memory_mb = 4096build_timeout_sec = 600network_mode = "public"
[agent]timeout_sec = 1800network_mode = "public"
[verifier]timeout_sec = 600network_mode = "public"environment_mode = "separate"
[verifier.environment]network_mode = "public"cpus = 1memory_mb = 4096
[[artifacts]]source = "/workspace/outputs"123456789{ "checks": [ { "id": "business-outcomes", "type": "custom", "module": "world_check" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330"""Deterministic grader shared by converted knowledge-work tasks.
Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects thesubmitted /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/<file> vs tests/<target> over sheet!range (SpreadsheetBench rules) xlsx_cell recalculated outputs/<file> sheet!cell vs value with tolerance (optional alt_values) file_contains outputs/<file> text (docx/pdf/ics/eml/txt) must contain every needle custom tests/<module>.py defines check(spec, outputs_dir, tests_dir) -> (bool, str)"""
import datetime as dtimport jsonimport reimport shutilimport subprocessimport sysimport tempfileimport unicodedatafrom 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 = """<?xml version="1.0" encoding="UTF-8"?><oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema"><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="OOXMLRecalcMode" oor:op="fuse"><value>0</value></prop></item><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="ODFRecalcMode" oor:op="fuse"><value>0</value></prop></item></oor:items>"""
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())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Offline business-app client. Print usage with --help."""import argparseimport copyimport fcntlimport jsonimport osfrom 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133{ "certs": { "R14795": { "course": "induction", "expires_day": 475, "person": "S47232", "state": "deferred" }, "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": "enrolled" }, "R32632": { "course": "privacy", "expires_day": 455, "person": "S13138", "state": "enrolled" }, "R49769": { "course": "records", "expires_day": 455, "person": "S58788", "state": "enrolled" }, "R61393": { "course": "records", "expires_day": 451, "person": "S65830", "state": "deferred" }, "R63021": { "course": "privacy", "expires_day": 473, "person": "S81260", "state": "waitlisted" }, "R70074": { "course": "induction", "expires_day": 480, "person": "S96518", "state": "waitlisted" }, "R78798": { "course": "records", "expires_day": 455, "person": "S69713", "state": "enrolled" }, "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": { "renew-R31665": { "course": "privacy", "person": "S34408", "session": "renewal" }, "renew-R32632": { "course": "privacy", "person": "S13138", "session": "renewal" }, "renew-R49769": { "course": "records", "person": "S58788", "session": "renewal" }, "renew-R78798": { "course": "records", "person": "S69713", "session": "renewal" } }, "sessions": { "renewal": { "seats": 0, "start_day": 485 } }}1234#!/bin/shset -eumkdir -p /logs/verifier /workspace/outputsexec python3 -B -I /tests/grade.py123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112{ "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 } }}1234567891011121314151617181920212223242526"""Replay submitted mutations from the private verifier's initial state."""from types import ModuleTypeimport 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,''12345678910111213141516171819202122232425262728{ "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}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Offline business-app client. Print usage with --help."""import argparseimport copyimport fcntlimport jsonimport osfrom 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()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576{ "certs": { "R11647": { "course": "privacy", "expires_day": 418, "person": "S62317", "state": "active" }, "R21370": { "course": "privacy", "expires_day": 396, "person": "S26846", "state": "retired" }, "R27606": { "course": "privacy", "expires_day": 399, "person": "S62428", "state": "active" }, "R35407": { "course": "privacy", "expires_day": 415, "person": "S31028", "state": "active" }, "R39621": { "course": "privacy", "expires_day": 386, "person": "S48952", "state": "active" }, "R40742": { "course": "records", "expires_day": 386, "person": "S57195", "state": "active" }, "R77131": { "course": "privacy", "expires_day": 404, "person": "S67523", "state": "active" } }, "leave": { "S26846": { "available_day": 406 }, "S31028": { "available_day": 420 }, "S48952": { "available_day": 390 }, "S57195": { "available_day": 390 }, "S62317": { "available_day": 413 }, "S62428": { "available_day": 420 }, "S67523": { "available_day": 420 } }, "renewals": {}, "sessions": { "renewal": { "seats": 4, "start_day": 416 } }}12345678910111213Allocate 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-<cert ID> 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.12345678{"app": "certs", "fields": {"state": "enrolled"}, "id": "R39621", "op": "update"}{"app": "certs", "fields": {"state": "enrolled"}, "id": "R40742", "op": "update"}{"app": "certs", "fields": {"state": "deferred"}, "id": "R77131", "op": "update"}{"app": "certs", "fields": {"state": "deferred"}, "id": "R27606", "op": "update"}{"app": "certs", "fields": {"state": "deferred"}, "id": "R35407", "op": "update"}{"app": "renewals", "fields": {"course": "privacy", "person": "S48952", "session": "renewal"}, "id": "renew-R39621", "op": "create"}{"app": "renewals", "fields": {"course": "records", "person": "S57195", "session": "renewal"}, "id": "renew-R40742", "op": "create"}{"app": "sessions", "fields": {"seats": 2}, "id": "renewal", "op": "update"}1234#!/bin/shset -eumkdir -p /workspace/outputscp -R /solution/files/. /workspace/outputs/12345678910111213141516171819202122232425262728293031323334353637383940414243444546schema_version = "1.3"
[task]name = "apex-gap/service-hr-certifications-41837"
[metadata.apex_gap]capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"]dataset = "Original simulated workflows"job = "hr"seed = 41837source = "local/original-automation-workflows"source_revision = "1"source_split = "synthetic"source_task_id = "service-hr-certifications-41837"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 = truenetwork_enabled = true
[environment]docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf"workdir = "/workspace"cpus = 1memory_mb = 4096build_timeout_sec = 600network_mode = "public"
[agent]timeout_sec = 1800network_mode = "public"
[verifier]timeout_sec = 600network_mode = "public"environment_mode = "separate"
[verifier.environment]network_mode = "public"cpus = 1memory_mb = 4096
[[artifacts]]source = "/workspace/outputs"123456789{ "checks": [ { "id": "business-outcomes", "type": "custom", "module": "world_check" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330"""Deterministic grader shared by converted knowledge-work tasks.
Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects thesubmitted /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/<file> vs tests/<target> over sheet!range (SpreadsheetBench rules) xlsx_cell recalculated outputs/<file> sheet!cell vs value with tolerance (optional alt_values) file_contains outputs/<file> text (docx/pdf/ics/eml/txt) must contain every needle custom tests/<module>.py defines check(spec, outputs_dir, tests_dir) -> (bool, str)"""
import datetime as dtimport jsonimport reimport shutilimport subprocessimport sysimport tempfileimport unicodedatafrom 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 = """<?xml version="1.0" encoding="UTF-8"?><oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema"><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="OOXMLRecalcMode" oor:op="fuse"><value>0</value></prop></item><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="ODFRecalcMode" oor:op="fuse"><value>0</value></prop></item></oor:items>"""
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())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Offline business-app client. Print usage with --help."""import argparseimport copyimport fcntlimport jsonimport osfrom 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687{ "certs": { "R11647": { "course": "privacy", "expires_day": 418, "person": "S62317", "state": "active" }, "R21370": { "course": "privacy", "expires_day": 396, "person": "S26846", "state": "retired" }, "R27606": { "course": "privacy", "expires_day": 399, "person": "S62428", "state": "deferred" }, "R35407": { "course": "privacy", "expires_day": 415, "person": "S31028", "state": "deferred" }, "R39621": { "course": "privacy", "expires_day": 386, "person": "S48952", "state": "enrolled" }, "R40742": { "course": "records", "expires_day": 386, "person": "S57195", "state": "enrolled" }, "R77131": { "course": "privacy", "expires_day": 404, "person": "S67523", "state": "deferred" } }, "leave": { "S26846": { "available_day": 406 }, "S31028": { "available_day": 420 }, "S48952": { "available_day": 390 }, "S57195": { "available_day": 390 }, "S62317": { "available_day": 413 }, "S62428": { "available_day": 420 }, "S67523": { "available_day": 420 } }, "renewals": { "renew-R39621": { "course": "privacy", "person": "S48952", "session": "renewal" }, "renew-R40742": { "course": "records", "person": "S57195", "session": "renewal" } }, "sessions": { "renewal": { "seats": 2, "start_day": 416 } }}1234#!/bin/shset -eumkdir -p /logs/verifier /workspace/outputsexec python3 -B -I /tests/grade.py12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576{ "certs": { "R11647": { "course": "privacy", "expires_day": 418, "person": "S62317", "state": "active" }, "R21370": { "course": "privacy", "expires_day": 396, "person": "S26846", "state": "retired" }, "R27606": { "course": "privacy", "expires_day": 399, "person": "S62428", "state": "active" }, "R35407": { "course": "privacy", "expires_day": 415, "person": "S31028", "state": "active" }, "R39621": { "course": "privacy", "expires_day": 386, "person": "S48952", "state": "active" }, "R40742": { "course": "records", "expires_day": 386, "person": "S57195", "state": "active" }, "R77131": { "course": "privacy", "expires_day": 404, "person": "S67523", "state": "active" } }, "leave": { "S26846": { "available_day": 406 }, "S31028": { "available_day": 420 }, "S48952": { "available_day": 390 }, "S57195": { "available_day": 390 }, "S62317": { "available_day": 413 }, "S62428": { "available_day": 420 }, "S67523": { "available_day": 420 } }, "renewals": {}, "sessions": { "renewal": { "seats": 4, "start_day": 416 } }}1234567891011121314151617181920212223242526"""Replay submitted mutations from the private verifier's initial state."""from types import ModuleTypeimport 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,''12345678910111213141516171819202122232425262728{ "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}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Offline business-app client. Print usage with --help."""import argparseimport copyimport fcntlimport jsonimport osfrom 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()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485{ "certs": { "R14020": { "course": "induction", "expires_day": 398, "person": "S37318", "state": "active" }, "R14981": { "course": "induction", "expires_day": 411, "person": "S83572", "state": "active" }, "R21547": { "course": "induction", "expires_day": 424, "person": "S37724", "state": "active" }, "R34688": { "course": "records", "expires_day": 397, "person": "S29462", "state": "active" }, "R35432": { "course": "records", "expires_day": 395, "person": "S18548", "state": "active" }, "R69002": { "course": "induction", "expires_day": 422, "person": "S78988", "state": "active" }, "R79833": { "course": "records", "expires_day": 430, "person": "S98094", "state": "retired" }, "R83170": { "course": "privacy", "expires_day": 420, "person": "S63123", "state": "active" } }, "leave": { "S18548": { "available_day": 419 }, "S29462": { "available_day": 400 }, "S37318": { "available_day": 400 }, "S37724": { "available_day": 419 }, "S63123": { "available_day": 424 }, "S78988": { "available_day": 417 }, "S83572": { "available_day": 424 }, "S98094": { "available_day": 417 } }, "renewals": {}, "sessions": { "renewal": { "seats": 3, "start_day": 420 } }}12345678910111213Allocate 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-<cert ID> 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.123456789{"app": "certs", "fields": {"state": "enrolled"}, "id": "R14020", "op": "update"}{"app": "certs", "fields": {"state": "enrolled"}, "id": "R34688", "op": "update"}{"app": "certs", "fields": {"state": "enrolled"}, "id": "R35432", "op": "update"}{"app": "certs", "fields": {"state": "deferred"}, "id": "R83170", "op": "update"}{"app": "certs", "fields": {"state": "deferred"}, "id": "R14981", "op": "update"}{"app": "renewals", "fields": {"course": "records", "person": "S18548", "session": "renewal"}, "id": "renew-R35432", "op": "create"}{"app": "renewals", "fields": {"course": "records", "person": "S29462", "session": "renewal"}, "id": "renew-R34688", "op": "create"}{"app": "renewals", "fields": {"course": "induction", "person": "S37318", "session": "renewal"}, "id": "renew-R14020", "op": "create"}{"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"}1234#!/bin/shset -eumkdir -p /workspace/outputscp -R /solution/files/. /workspace/outputs/12345678910111213141516171819202122232425262728293031323334353637383940414243444546schema_version = "1.3"
[task]name = "apex-gap/service-hr-certifications-41840"
[metadata.apex_gap]capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"]dataset = "Original simulated workflows"job = "hr"seed = 41840source = "local/original-automation-workflows"source_revision = "1"source_split = "synthetic"source_task_id = "service-hr-certifications-41840"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 = truenetwork_enabled = true
[environment]docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf"workdir = "/workspace"cpus = 1memory_mb = 4096build_timeout_sec = 600network_mode = "public"
[agent]timeout_sec = 1800network_mode = "public"
[verifier]timeout_sec = 600network_mode = "public"environment_mode = "separate"
[verifier.environment]network_mode = "public"cpus = 1memory_mb = 4096
[[artifacts]]source = "/workspace/outputs"123456789{ "checks": [ { "id": "business-outcomes", "type": "custom", "module": "world_check" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330"""Deterministic grader shared by converted knowledge-work tasks.
Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects thesubmitted /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/<file> vs tests/<target> over sheet!range (SpreadsheetBench rules) xlsx_cell recalculated outputs/<file> sheet!cell vs value with tolerance (optional alt_values) file_contains outputs/<file> text (docx/pdf/ics/eml/txt) must contain every needle custom tests/<module>.py defines check(spec, outputs_dir, tests_dir) -> (bool, str)"""
import datetime as dtimport jsonimport reimport shutilimport subprocessimport sysimport tempfileimport unicodedatafrom 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 = """<?xml version="1.0" encoding="UTF-8"?><oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema"><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="OOXMLRecalcMode" oor:op="fuse"><value>0</value></prop></item><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="ODFRecalcMode" oor:op="fuse"><value>0</value></prop></item></oor:items>"""
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())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Offline business-app client. Print usage with --help."""import argparseimport copyimport fcntlimport jsonimport osfrom 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101{ "certs": { "R14020": { "course": "induction", "expires_day": 398, "person": "S37318", "state": "enrolled" }, "R14981": { "course": "induction", "expires_day": 411, "person": "S83572", "state": "deferred" }, "R21547": { "course": "induction", "expires_day": 424, "person": "S37724", "state": "active" }, "R34688": { "course": "records", "expires_day": 397, "person": "S29462", "state": "enrolled" }, "R35432": { "course": "records", "expires_day": 395, "person": "S18548", "state": "enrolled" }, "R69002": { "course": "induction", "expires_day": 422, "person": "S78988", "state": "active" }, "R79833": { "course": "records", "expires_day": 430, "person": "S98094", "state": "retired" }, "R83170": { "course": "privacy", "expires_day": 420, "person": "S63123", "state": "deferred" } }, "leave": { "S18548": { "available_day": 419 }, "S29462": { "available_day": 400 }, "S37318": { "available_day": 400 }, "S37724": { "available_day": 419 }, "S63123": { "available_day": 424 }, "S78988": { "available_day": 417 }, "S83572": { "available_day": 424 }, "S98094": { "available_day": 417 } }, "renewals": { "renew-R14020": { "course": "induction", "person": "S37318", "session": "renewal" }, "renew-R34688": { "course": "records", "person": "S29462", "session": "renewal" }, "renew-R35432": { "course": "records", "person": "S18548", "session": "renewal" } }, "sessions": { "renewal": { "seats": 0, "start_day": 420 } }}1234#!/bin/shset -eumkdir -p /logs/verifier /workspace/outputsexec python3 -B -I /tests/grade.py12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485{ "certs": { "R14020": { "course": "induction", "expires_day": 398, "person": "S37318", "state": "active" }, "R14981": { "course": "induction", "expires_day": 411, "person": "S83572", "state": "active" }, "R21547": { "course": "induction", "expires_day": 424, "person": "S37724", "state": "active" }, "R34688": { "course": "records", "expires_day": 397, "person": "S29462", "state": "active" }, "R35432": { "course": "records", "expires_day": 395, "person": "S18548", "state": "active" }, "R69002": { "course": "induction", "expires_day": 422, "person": "S78988", "state": "active" }, "R79833": { "course": "records", "expires_day": 430, "person": "S98094", "state": "retired" }, "R83170": { "course": "privacy", "expires_day": 420, "person": "S63123", "state": "active" } }, "leave": { "S18548": { "available_day": 419 }, "S29462": { "available_day": 400 }, "S37318": { "available_day": 400 }, "S37724": { "available_day": 419 }, "S63123": { "available_day": 424 }, "S78988": { "available_day": 417 }, "S83572": { "available_day": 424 }, "S98094": { "available_day": 417 } }, "renewals": {}, "sessions": { "renewal": { "seats": 3, "start_day": 420 } }}1234567891011121314151617181920212223242526"""Replay submitted mutations from the private verifier's initial state."""from types import ModuleTypeimport 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,''12345678910111213141516171819202122232425262728{ "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}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Offline business-app client. Print usage with --help."""import argparseimport copyimport fcntlimport jsonimport osfrom 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103{ "certs": { "R16980": { "course": "privacy", "expires_day": 293, "person": "S63970", "state": "active" }, "R30399": { "course": "privacy", "expires_day": 269, "person": "S56563", "state": "active" }, "R33656": { "course": "induction", "expires_day": 304, "person": "S41205", "state": "active" }, "R35602": { "course": "privacy", "expires_day": 279, "person": "S40135", "state": "active" }, "R35640": { "course": "records", "expires_day": 275, "person": "S92541", "state": "active" }, "R46749": { "course": "privacy", "expires_day": 293, "person": "S96230", "state": "active" }, "R47822": { "course": "induction", "expires_day": 274, "person": "S83162", "state": "active" }, "R59901": { "course": "privacy", "expires_day": 295, "person": "S73569", "state": "active" }, "R66677": { "course": "records", "expires_day": 286, "person": "S93638", "state": "retired" }, "R69349": { "course": "records", "expires_day": 274, "person": "S96936", "state": "active" } }, "leave": { "S40135": { "available_day": 300 }, "S41205": { "available_day": 286 }, "S56563": { "available_day": 295 }, "S63970": { "available_day": 286 }, "S73569": { "available_day": 300 }, "S83162": { "available_day": 295 }, "S92541": { "available_day": 278 }, "S93638": { "available_day": 300 }, "S96230": { "available_day": 293 }, "S96936": { "available_day": 278 } }, "renewals": {}, "sessions": { "renewal": { "seats": 3, "start_day": 296 } }}12345678910111213Allocate 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-<cert ID> 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.123456789101112{"app": "certs", "fields": {"state": "enrolled"}, "id": "R69349", "op": "update"}{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R35640", "op": "update"}{"app": "certs", "fields": {"state": "deferred"}, "id": "R59901", "op": "update"}{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R46749", "op": "update"}{"app": "certs", "fields": {"state": "deferred"}, "id": "R35602", "op": "update"}{"app": "certs", "fields": {"state": "enrolled"}, "id": "R47822", "op": "update"}{"app": "certs", "fields": {"state": "enrolled"}, "id": "R30399", "op": "update"}{"app": "certs", "fields": {"state": "waitlisted"}, "id": "R16980", "op": "update"}{"app": "renewals", "fields": {"course": "privacy", "person": "S56563", "session": "renewal"}, "id": "renew-R30399", "op": "create"}{"app": "renewals", "fields": {"course": "induction", "person": "S83162", "session": "renewal"}, "id": "renew-R47822", "op": "create"}{"app": "renewals", "fields": {"course": "records", "person": "S96936", "session": "renewal"}, "id": "renew-R69349", "op": "create"}{"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"}1234#!/bin/shset -eumkdir -p /workspace/outputscp -R /solution/files/. /workspace/outputs/12345678910111213141516171819202122232425262728293031323334353637383940414243444546schema_version = "1.3"
[task]name = "apex-gap/service-hr-certifications-41843"
[metadata.apex_gap]capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"]dataset = "Original simulated workflows"job = "hr"seed = 41843source = "local/original-automation-workflows"source_revision = "1"source_split = "synthetic"source_task_id = "service-hr-certifications-41843"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 = truenetwork_enabled = true
[environment]docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf"workdir = "/workspace"cpus = 1memory_mb = 4096build_timeout_sec = 600network_mode = "public"
[agent]timeout_sec = 1800network_mode = "public"
[verifier]timeout_sec = 600network_mode = "public"environment_mode = "separate"
[verifier.environment]network_mode = "public"cpus = 1memory_mb = 4096
[[artifacts]]source = "/workspace/outputs"123456789{ "checks": [ { "id": "business-outcomes", "type": "custom", "module": "world_check" } ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330"""Deterministic grader shared by converted knowledge-work tasks.
Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects thesubmitted /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/<file> vs tests/<target> over sheet!range (SpreadsheetBench rules) xlsx_cell recalculated outputs/<file> sheet!cell vs value with tolerance (optional alt_values) file_contains outputs/<file> text (docx/pdf/ics/eml/txt) must contain every needle custom tests/<module>.py defines check(spec, outputs_dir, tests_dir) -> (bool, str)"""
import datetime as dtimport jsonimport reimport shutilimport subprocessimport sysimport tempfileimport unicodedatafrom 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 = """<?xml version="1.0" encoding="UTF-8"?><oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema"><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="OOXMLRecalcMode" oor:op="fuse"><value>0</value></prop></item><item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="ODFRecalcMode" oor:op="fuse"><value>0</value></prop></item></oor:items>"""
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())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Offline business-app client. Print usage with --help."""import argparseimport copyimport fcntlimport jsonimport osfrom 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119{ "certs": { "R16980": { "course": "privacy", "expires_day": 293, "person": "S63970", "state": "waitlisted" }, "R30399": { "course": "privacy", "expires_day": 269, "person": "S56563", "state": "enrolled" }, "R33656": { "course": "induction", "expires_day": 304, "person": "S41205", "state": "active" }, "R35602": { "course": "privacy", "expires_day": 279, "person": "S40135", "state": "deferred" }, "R35640": { "course": "records", "expires_day": 275, "person": "S92541", "state": "waitlisted" }, "R46749": { "course": "privacy", "expires_day": 293, "person": "S96230", "state": "waitlisted" }, "R47822": { "course": "induction", "expires_day": 274, "person": "S83162", "state": "enrolled" }, "R59901": { "course": "privacy", "expires_day": 295, "person": "S73569", "state": "deferred" }, "R66677": { "course": "records", "expires_day": 286, "person": "S93638", "state": "retired" }, "R69349": { "course": "records", "expires_day": 274, "person": "S96936", "state": "enrolled" } }, "leave": { "S40135": { "available_day": 300 }, "S41205": { "available_day": 286 }, "S56563": { "available_day": 295 }, "S63970": { "available_day": 286 }, "S73569": { "available_day": 300 }, "S83162": { "available_day": 295 }, "S92541": { "available_day": 278 }, "S93638": { "available_day": 300 }, "S96230": { "available_day": 293 }, "S96936": { "available_day": 278 } }, "renewals": { "renew-R30399": { "course": "privacy", "person": "S56563", "session": "renewal" }, "renew-R47822": { "course": "induction", "person": "S83162", "session": "renewal" }, "renew-R69349": { "course": "records", "person": "S96936", "session": "renewal" } }, "sessions": { "renewal": { "seats": 0, "start_day": 296 } }}1234#!/bin/shset -eumkdir -p /logs/verifier /workspace/outputsexec python3 -B -I /tests/grade.py123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103{ "certs": { "R16980": { "course": "privacy", "expires_day": 293, "person": "S63970", "state": "active" }, "R30399": { "course": "privacy", "expires_day": 269, "person": "S56563", "state": "active" }, "R33656": { "course": "induction", "expires_day": 304, "person": "S41205", "state": "active" }, "R35602": { "course": "privacy", "expires_day": 279, "person": "S40135", "state": "active" }, "R35640": { "course": "records", "expires_day": 275, "person": "S92541", "state": "active" }, "R46749": { "course": "privacy", "expires_day": 293, "person": "S96230", "state": "active" }, "R47822": { "course": "induction", "expires_day": 274, "person": "S83162", "state": "active" }, "R59901": { "course": "privacy", "expires_day": 295, "person": "S73569", "state": "active" }, "R66677": { "course": "records", "expires_day": 286, "person": "S93638", "state": "retired" }, "R69349": { "course": "records", "expires_day": 274, "person": "S96936", "state": "active" } }, "leave": { "S40135": { "available_day": 300 }, "S41205": { "available_day": 286 }, "S56563": { "available_day": 295 }, "S63970": { "available_day": 286 }, "S73569": { "available_day": 300 }, "S83162": { "available_day": 295 }, "S92541": { "available_day": 278 }, "S93638": { "available_day": 300 }, "S96230": { "available_day": 293 }, "S96936": { "available_day": 278 } }, "renewals": {}, "sessions": { "renewal": { "seats": 3, "start_day": 296 } }}tasks/service-hr-certifications-41834/solution/solve.shAdded+4
tasks/service-hr-certifications-41834/task.tomlAdded+46
tasks/service-hr-certifications-41834/tests/expected.jsonAdded+9
tasks/service-hr-certifications-41834/tests/grade.pyAdded+330
tasks/service-hr-certifications-41834/tests/replay.pyAdded+68
tasks/service-hr-certifications-41834/tests/target.jsonAdded+133
tasks/service-hr-certifications-41834/tests/test.shAdded+4
tasks/service-hr-certifications-41834/tests/world.jsonAdded+112
tasks/service-hr-certifications-41834/tests/world_check.pyAdded+26
tasks/service-hr-certifications-41834/validation/openenv.jsonAdded+28
tasks/service-hr-certifications-41837/environment/inputs/apps.pyAdded+68
tasks/service-hr-certifications-41837/environment/inputs/world.jsonAdded+76
tasks/service-hr-certifications-41837/instruction.mdAdded+13
tasks/service-hr-certifications-41837/solution/files/actions.jsonlAdded+8
tasks/service-hr-certifications-41837/solution/solve.shAdded+4
tasks/service-hr-certifications-41837/task.tomlAdded+46
tasks/service-hr-certifications-41837/tests/expected.jsonAdded+9
tasks/service-hr-certifications-41837/tests/grade.pyAdded+330
tasks/service-hr-certifications-41837/tests/replay.pyAdded+68
tasks/service-hr-certifications-41837/tests/target.jsonAdded+87
tasks/service-hr-certifications-41837/tests/test.shAdded+4
tasks/service-hr-certifications-41837/tests/world.jsonAdded+76
tasks/service-hr-certifications-41837/tests/world_check.pyAdded+26
tasks/service-hr-certifications-41837/validation/openenv.jsonAdded+28
tasks/service-hr-certifications-41840/environment/inputs/apps.pyAdded+68
tasks/service-hr-certifications-41840/environment/inputs/world.jsonAdded+85
tasks/service-hr-certifications-41840/instruction.mdAdded+13
tasks/service-hr-certifications-41840/solution/files/actions.jsonlAdded+9
tasks/service-hr-certifications-41840/solution/solve.shAdded+4
tasks/service-hr-certifications-41840/task.tomlAdded+46
tasks/service-hr-certifications-41840/tests/expected.jsonAdded+9
tasks/service-hr-certifications-41840/tests/grade.pyAdded+330
tasks/service-hr-certifications-41840/tests/replay.pyAdded+68
tasks/service-hr-certifications-41840/tests/target.jsonAdded+101
tasks/service-hr-certifications-41840/tests/test.shAdded+4
tasks/service-hr-certifications-41840/tests/world.jsonAdded+85
tasks/service-hr-certifications-41840/tests/world_check.pyAdded+26
tasks/service-hr-certifications-41840/validation/openenv.jsonAdded+28
tasks/service-hr-certifications-41843/environment/inputs/apps.pyAdded+68
tasks/service-hr-certifications-41843/environment/inputs/world.jsonAdded+103
tasks/service-hr-certifications-41843/instruction.mdAdded+13
tasks/service-hr-certifications-41843/solution/files/actions.jsonlAdded+12
tasks/service-hr-certifications-41843/solution/solve.shAdded+4
tasks/service-hr-certifications-41843/task.tomlAdded+46
tasks/service-hr-certifications-41843/tests/expected.jsonAdded+9
tasks/service-hr-certifications-41843/tests/grade.pyAdded+330
tasks/service-hr-certifications-41843/tests/replay.pyAdded+68
tasks/service-hr-certifications-41843/tests/target.jsonAdded+119
tasks/service-hr-certifications-41843/tests/test.shAdded+4
tasks/service-hr-certifications-41843/tests/world.jsonAdded+103