ybelkada HF Staff commited on
Commit
edb10d7
·
verified ·
1 Parent(s): 3138704

Harbor format: 210 business_automation tasks (part 7)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/service-hr-certifications-41834/solution/solve.sh +4 -0
  2. tasks/service-hr-certifications-41834/task.toml +46 -0
  3. tasks/service-hr-certifications-41834/tests/expected.json +9 -0
  4. tasks/service-hr-certifications-41834/tests/grade.py +330 -0
  5. tasks/service-hr-certifications-41834/tests/replay.py +68 -0
  6. tasks/service-hr-certifications-41834/tests/target.json +133 -0
  7. tasks/service-hr-certifications-41834/tests/test.sh +4 -0
  8. tasks/service-hr-certifications-41834/tests/world.json +112 -0
  9. tasks/service-hr-certifications-41834/tests/world_check.py +26 -0
  10. tasks/service-hr-certifications-41834/validation/openenv.json +28 -0
  11. tasks/service-hr-certifications-41837/environment/inputs/apps.py +68 -0
  12. tasks/service-hr-certifications-41837/environment/inputs/world.json +76 -0
  13. tasks/service-hr-certifications-41837/instruction.md +13 -0
  14. tasks/service-hr-certifications-41837/solution/files/actions.jsonl +8 -0
  15. tasks/service-hr-certifications-41837/solution/solve.sh +4 -0
  16. tasks/service-hr-certifications-41837/task.toml +46 -0
  17. tasks/service-hr-certifications-41837/tests/expected.json +9 -0
  18. tasks/service-hr-certifications-41837/tests/grade.py +330 -0
  19. tasks/service-hr-certifications-41837/tests/replay.py +68 -0
  20. tasks/service-hr-certifications-41837/tests/target.json +87 -0
  21. tasks/service-hr-certifications-41837/tests/test.sh +4 -0
  22. tasks/service-hr-certifications-41837/tests/world.json +76 -0
  23. tasks/service-hr-certifications-41837/tests/world_check.py +26 -0
  24. tasks/service-hr-certifications-41837/validation/openenv.json +28 -0
  25. tasks/service-hr-certifications-41840/environment/inputs/apps.py +68 -0
  26. tasks/service-hr-certifications-41840/environment/inputs/world.json +85 -0
  27. tasks/service-hr-certifications-41840/instruction.md +13 -0
  28. tasks/service-hr-certifications-41840/solution/files/actions.jsonl +9 -0
  29. tasks/service-hr-certifications-41840/solution/solve.sh +4 -0
  30. tasks/service-hr-certifications-41840/task.toml +46 -0
  31. tasks/service-hr-certifications-41840/tests/expected.json +9 -0
  32. tasks/service-hr-certifications-41840/tests/grade.py +330 -0
  33. tasks/service-hr-certifications-41840/tests/replay.py +68 -0
  34. tasks/service-hr-certifications-41840/tests/target.json +101 -0
  35. tasks/service-hr-certifications-41840/tests/test.sh +4 -0
  36. tasks/service-hr-certifications-41840/tests/world.json +85 -0
  37. tasks/service-hr-certifications-41840/tests/world_check.py +26 -0
  38. tasks/service-hr-certifications-41840/validation/openenv.json +28 -0
  39. tasks/service-hr-certifications-41843/environment/inputs/apps.py +68 -0
  40. tasks/service-hr-certifications-41843/environment/inputs/world.json +103 -0
  41. tasks/service-hr-certifications-41843/instruction.md +13 -0
  42. tasks/service-hr-certifications-41843/solution/files/actions.jsonl +12 -0
  43. tasks/service-hr-certifications-41843/solution/solve.sh +4 -0
  44. tasks/service-hr-certifications-41843/task.toml +46 -0
  45. tasks/service-hr-certifications-41843/tests/expected.json +9 -0
  46. tasks/service-hr-certifications-41843/tests/grade.py +330 -0
  47. tasks/service-hr-certifications-41843/tests/replay.py +68 -0
  48. tasks/service-hr-certifications-41843/tests/target.json +119 -0
  49. tasks/service-hr-certifications-41843/tests/test.sh +4 -0
  50. tasks/service-hr-certifications-41843/tests/world.json +103 -0
tasks/service-hr-certifications-41834/solution/solve.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ mkdir -p /workspace/outputs
4
+ cp -R /solution/files/. /workspace/outputs/
tasks/service-hr-certifications-41834/task.toml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.3"
2
+
3
+ [task]
4
+ name = "apex-gap/service-hr-certifications-41834"
5
+
6
+ [metadata.apex_gap]
7
+ capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"]
8
+ dataset = "Original simulated workflows"
9
+ job = "hr"
10
+ seed = 41834
11
+ source = "local/original-automation-workflows"
12
+ source_revision = "1"
13
+ source_split = "synthetic"
14
+ source_task_id = "service-hr-certifications-41834"
15
+ template_family = "automation:service-hr-certifications"
16
+ workflow_template = "service-hr-certifications"
17
+
18
+ [metadata.openenv_hf_sandbox]
19
+ variant = "apex-gap-hfsandbox-v1"
20
+ task_modified_for_hf_sandbox = true
21
+ network_enabled = true
22
+
23
+ [environment]
24
+ docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf"
25
+ workdir = "/workspace"
26
+ cpus = 1
27
+ memory_mb = 4096
28
+ build_timeout_sec = 600
29
+ network_mode = "public"
30
+
31
+ [agent]
32
+ timeout_sec = 1800
33
+ network_mode = "public"
34
+
35
+ [verifier]
36
+ timeout_sec = 600
37
+ network_mode = "public"
38
+ environment_mode = "separate"
39
+
40
+ [verifier.environment]
41
+ network_mode = "public"
42
+ cpus = 1
43
+ memory_mb = 4096
44
+
45
+ [[artifacts]]
46
+ source = "/workspace/outputs"
tasks/service-hr-certifications-41834/tests/expected.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "checks": [
3
+ {
4
+ "id": "business-outcomes",
5
+ "type": "custom",
6
+ "module": "world_check"
7
+ }
8
+ ]
9
+ }
tasks/service-hr-certifications-41834/tests/grade.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic grader shared by converted knowledge-work tasks.
2
+
3
+ Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the
4
+ submitted /workspace/outputs tree and writes a binary reward plus per-check details.
5
+ No model calls and no network.
6
+
7
+ expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]}
8
+ Check types:
9
+ answer field of outputs/answer.json; kind = number|text|choice|date|bool|list
10
+ xlsx_range recalculated outputs/<file> vs tests/<target> over sheet!range (SpreadsheetBench rules)
11
+ xlsx_cell recalculated outputs/<file> sheet!cell vs value with tolerance (optional alt_values)
12
+ file_contains outputs/<file> text (docx/pdf/ics/eml/txt) must contain every needle
13
+ custom tests/<module>.py defines check(spec, outputs_dir, tests_dir) -> (bool, str)
14
+ """
15
+
16
+ import datetime as dt
17
+ import json
18
+ import re
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ import tempfile
23
+ import unicodedata
24
+ from pathlib import Path
25
+
26
+ OUT = Path("/workspace/outputs")
27
+ TESTS = Path("/tests")
28
+ LOGS = Path("/logs/verifier")
29
+
30
+
31
+ def norm_text(v):
32
+ v = unicodedata.normalize("NFKC", str(v)).casefold()
33
+ v = re.sub(r"[‘’“”]", "'", v)
34
+ v = re.sub(r"[^\w%.$/-]+", " ", v)
35
+ return " ".join(v.split()).strip(" .")
36
+
37
+
38
+ def to_number(v):
39
+ if isinstance(v, bool):
40
+ raise ValueError("bool")
41
+ if isinstance(v, (int, float)):
42
+ return float(v)
43
+ s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-")
44
+ neg = s.startswith("(") and s.endswith(")")
45
+ s = s.strip("()").strip()
46
+ pct = s.endswith("%")
47
+ s = s.rstrip("%").strip()
48
+ s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I)
49
+ x = float(s)
50
+ x = -x if neg else x
51
+ return x / 100 if pct else x
52
+
53
+
54
+ def number_ok(got, want, rel, abs_):
55
+ try:
56
+ g = to_number(got)
57
+ except (TypeError, ValueError):
58
+ return False
59
+ w = float(want)
60
+ tol = max(abs_, rel * abs(w))
61
+ # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which.
62
+ candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g]
63
+ return any(abs(c - w) <= tol for c in candidates)
64
+
65
+
66
+ def parse_date(v):
67
+ if isinstance(v, (dt.date, dt.datetime)):
68
+ return v if isinstance(v, dt.date) else v.date()
69
+ s = str(v).strip()
70
+ for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"):
71
+ try:
72
+ return dt.datetime.strptime(s, fmt).date()
73
+ except ValueError:
74
+ continue
75
+ raise ValueError(s)
76
+
77
+
78
+ def check_answer(check, answers):
79
+ key = check["field"]
80
+ if key not in answers:
81
+ return False, f"missing field {key!r}"
82
+ got, want, kind = answers[key], check["value"], check.get("kind", "text")
83
+ if kind == "number":
84
+ ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01))
85
+ if not ok and check.get("percent_either"):
86
+ ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or (
87
+ number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100)
88
+ )
89
+ elif kind == "date":
90
+ try:
91
+ ok = parse_date(got) == parse_date(want)
92
+ except ValueError:
93
+ ok = False
94
+ elif kind == "bool":
95
+ g = norm_text(got)
96
+ ok = g in {"yes", "true"} if want else g in {"no", "false"}
97
+ elif kind == "choice":
98
+ ok = norm_text(got) == norm_text(want)
99
+ elif kind == "list":
100
+ if not isinstance(got, list):
101
+ return False, f"{key}: expected a JSON list"
102
+ # Filenames may be given with a directory prefix; compare base names.
103
+ base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1])
104
+ ok = sorted(base(x) for x in got) == sorted(base(x) for x in want)
105
+ else:
106
+ accepted = check.get("accept", [want])
107
+ ok = norm_text(got) in {norm_text(a) for a in accepted}
108
+ return ok, "" if ok else f"{key}: got {got!r}"
109
+
110
+
111
+ # LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation.
112
+ RECALC_PROFILE = """<?xml version="1.0" encoding="UTF-8"?>
113
+ <oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema">
114
+ <item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="OOXMLRecalcMode" oor:op="fuse"><value>0</value></prop></item>
115
+ <item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="ODFRecalcMode" oor:op="fuse"><value>0</value></prop></item>
116
+ </oor:items>
117
+ """
118
+
119
+
120
+ def recalc(path, tmp):
121
+ dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}"
122
+ dest.mkdir()
123
+ profile = Path(tmp) / "lo-profile"
124
+ if not profile.exists():
125
+ (profile / "user").mkdir(parents=True)
126
+ (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE)
127
+ subprocess.run(
128
+ ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to",
129
+ "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)],
130
+ stdout=subprocess.DEVNULL,
131
+ stderr=subprocess.DEVNULL,
132
+ timeout=180,
133
+ check=False,
134
+ )
135
+ out = dest / (Path(path).stem + ".xlsx")
136
+ return out if out.exists() else Path(path)
137
+
138
+
139
+ def cell_value(v):
140
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
141
+ return round(float(v), 2)
142
+ if isinstance(v, dt.datetime):
143
+ return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0)
144
+ if isinstance(v, dt.time):
145
+ return v.strftime("%H:%M")
146
+ if isinstance(v, str):
147
+ try:
148
+ return round(float(v), 2)
149
+ except ValueError:
150
+ return v.strip()
151
+ return v
152
+
153
+
154
+ def time_of(v):
155
+ """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and
156
+ Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells."""
157
+ if isinstance(v, dt.time):
158
+ v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400
159
+ if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1:
160
+ return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M")
161
+ return None
162
+
163
+
164
+ def same_cell(a, b):
165
+ if isinstance(a, dt.time) is not isinstance(b, dt.time):
166
+ n = b if isinstance(a, dt.time) else a
167
+ if time_of(n) is not None: # a time against a plain day fraction
168
+ return time_of(a) == time_of(b)
169
+ a, b = cell_value(a), cell_value(b)
170
+ if a in (None, "") and b in (None, ""):
171
+ return True
172
+ return type(a) is type(b) and a == b
173
+
174
+
175
+ ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"}
176
+
177
+
178
+ def is_error(v):
179
+ return isinstance(v, str) and (v in ERRORS or v.startswith("Err:"))
180
+
181
+
182
+ def cells(rng):
183
+ if ":" not in rng:
184
+ return [rng]
185
+ from openpyxl.utils import range_boundaries, get_column_letter
186
+
187
+ c1, r1, c2, r2 = range_boundaries(rng)
188
+ return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)]
189
+
190
+
191
+ def load(path, tmp):
192
+ import openpyxl
193
+
194
+ return openpyxl.load_workbook(recalc(path, tmp), data_only=True)
195
+
196
+
197
+ def check_xlsx_range(check, tmp, cache):
198
+ sub = OUT / check["file"]
199
+ if not sub.is_file():
200
+ return False, f"missing output {check['file']}"
201
+ if sub not in cache:
202
+ cache[sub] = load(sub, tmp)
203
+ tgt = TESTS / check["target"]
204
+ if tgt not in cache:
205
+ cache[tgt] = load(tgt, tmp)
206
+ got, want = cache[sub], cache[tgt]
207
+ cached = None # the target's stored (Excel-computed) values, read only when Calc errs
208
+ for sheet, rng in check["ranges"]:
209
+ sheet = sheet or want.sheetnames[0]
210
+ if sheet not in got.sheetnames:
211
+ return False, f"sheet {sheet!r} missing"
212
+ for name in cells(rng):
213
+ w = want[sheet][name].value
214
+ if is_error(w):
215
+ # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4).
216
+ # The value Excel stored is the intended answer.
217
+ if cached is None:
218
+ import openpyxl
219
+
220
+ cached = openpyxl.load_workbook(tgt, data_only=True)
221
+ c = cached[sheet][name].value if sheet in cached.sheetnames else None
222
+ if c is not None and not is_error(c):
223
+ w = c
224
+ if not same_cell(w, got[sheet][name].value):
225
+ return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}"
226
+ return True, ""
227
+
228
+
229
+ def check_xlsx_cell(check, tmp, cache):
230
+ sub = OUT / check["file"]
231
+ if not sub.is_file():
232
+ return False, f"missing output {check['file']}"
233
+ if sub not in cache:
234
+ cache[sub] = load(sub, tmp)
235
+ wb = cache[sub]
236
+ if check["sheet"] not in wb.sheetnames:
237
+ return False, f"sheet {check['sheet']!r} missing"
238
+ got = wb[check["sheet"]][check["cell"]].value
239
+ want = check["value"]
240
+ if isinstance(want, (int, float)):
241
+ # alt_values: other accepted golds where the source admits more than one reading.
242
+ ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01))
243
+ for w in [want, *check.get("alt_values", [])])
244
+ else:
245
+ ok = norm_text(got) == norm_text(want)
246
+ return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}"
247
+
248
+
249
+ def text_of(path):
250
+ suffix = path.suffix.lower()
251
+ if suffix == ".docx":
252
+ import docx
253
+
254
+ d = docx.Document(path)
255
+ parts = [p.text for p in d.paragraphs]
256
+ for t in d.tables:
257
+ parts += [c.text for row in t.rows for c in row.cells]
258
+ return "\n".join(parts)
259
+ if suffix == ".pdf":
260
+ import pdfplumber
261
+
262
+ with pdfplumber.open(path) as pdf:
263
+ return "\n".join(page.extract_text() or "" for page in pdf.pages)
264
+ return path.read_text(errors="replace")
265
+
266
+
267
+ def check_file_contains(check, tmp, cache):
268
+ sub = OUT / check["file"]
269
+ if not sub.is_file():
270
+ return False, f"missing output {check['file']}"
271
+ text = text_of(sub)
272
+ hay = text if check.get("case_sensitive") else text.casefold()
273
+ for needle in check["needles"]:
274
+ n = needle if check.get("case_sensitive") else needle.casefold()
275
+ if n not in hay:
276
+ return False, f"{check['file']} lacks {needle!r}"
277
+ return True, ""
278
+
279
+
280
+ def main():
281
+ LOGS.mkdir(parents=True, exist_ok=True)
282
+ reward_path = LOGS / "reward.txt"
283
+ reward_path.write_text("0\n")
284
+ spec = json.loads((TESTS / "expected.json").read_text())
285
+ answers, details = {}, []
286
+ answer_file = OUT / "answer.json"
287
+ if answer_file.is_file():
288
+ try:
289
+ answers = json.loads(answer_file.read_text())
290
+ if not isinstance(answers, dict):
291
+ answers = {}
292
+ except json.JSONDecodeError:
293
+ answers = {}
294
+ tmp = tempfile.mkdtemp()
295
+ cache = {}
296
+ try:
297
+ for check in spec["checks"]:
298
+ try:
299
+ if check["type"] == "answer":
300
+ ok, why = check_answer(check, answers)
301
+ elif check["type"] == "xlsx_range":
302
+ ok, why = check_xlsx_range(check, tmp, cache)
303
+ elif check["type"] == "xlsx_cell":
304
+ ok, why = check_xlsx_cell(check, tmp, cache)
305
+ elif check["type"] == "file_contains":
306
+ ok, why = check_file_contains(check, tmp, cache)
307
+ elif check["type"] == "custom":
308
+ import importlib.util
309
+
310
+ spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py")
311
+ mod = importlib.util.module_from_spec(spec_)
312
+ spec_.loader.exec_module(mod)
313
+ ok, why = mod.check(check, OUT, TESTS)
314
+ else:
315
+ ok, why = False, f"unknown check type {check['type']}"
316
+ except Exception as exc: # a malformed submission fails the check, not the grader
317
+ ok, why = False, f"{type(exc).__name__}: {exc}"
318
+ details.append({"id": check["id"], "passed": ok, "detail": why})
319
+ finally:
320
+ shutil.rmtree(tmp, ignore_errors=True)
321
+ passed = sum(d["passed"] for d in details)
322
+ total = len(details)
323
+ reward = 1 if total and passed == total else 0
324
+ (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1))
325
+ reward_path.write_text(f"{reward}\n")
326
+ print(f"{passed}/{total} checks passed; reward {reward}")
327
+
328
+
329
+ if __name__ == "__main__":
330
+ sys.exit(main())
tasks/service-hr-certifications-41834/tests/replay.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline business-app client. Print usage with --help."""
2
+ import argparse
3
+ import copy
4
+ import fcntl
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+
10
+ def same(left, right):
11
+ return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False)
12
+
13
+
14
+ def apply(world, action):
15
+ if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}:
16
+ raise ValueError('expected op, app, id, fields')
17
+ op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields'))
18
+ if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields:
19
+ raise ValueError('unknown app, invalid id or empty fields')
20
+ collection = world[app]
21
+ if op == 'update' and key in collection:
22
+ collection[key].update(copy.deepcopy(fields))
23
+ elif op == 'create' and key not in collection:
24
+ collection[key] = copy.deepcopy(fields)
25
+ else:
26
+ raise ValueError(f'invalid {op} for {app}/{key}')
27
+
28
+
29
+ def load_actions(path):
30
+ if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000):
31
+ raise ValueError('invalid action log')
32
+ if not path.exists():
33
+ return []
34
+ return [json.loads(s) for s in path.read_text().splitlines() if s.strip()]
35
+
36
+
37
+ def main():
38
+ parser = argparse.ArgumentParser(description=__doc__)
39
+ parser.add_argument('op', choices=('apps','list','get','update','create'))
40
+ parser.add_argument('app', nargs='?')
41
+ parser.add_argument('id', nargs='?')
42
+ parser.add_argument('fields', nargs='?', type=json.loads)
43
+ args = parser.parse_args()
44
+ world = json.loads(Path(__file__).with_name('world.json').read_text())
45
+ out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs'))
46
+ out.mkdir(parents=True, exist_ok=True)
47
+ log = out/'actions.jsonl'
48
+ with (out/'.actions.lock').open('a') as lock:
49
+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
50
+ for event in load_actions(log):
51
+ apply(world,event)
52
+ if args.op=='apps':
53
+ value=sorted(world)
54
+ elif args.op=='list':
55
+ value=world[args.app]
56
+ elif args.op=='get':
57
+ value=world[args.app][args.id]
58
+ else:
59
+ event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields}
60
+ apply(world,event)
61
+ with log.open('a') as handle:
62
+ handle.write(json.dumps(event,allow_nan=False)+'\n')
63
+ value=world[args.app][args.id]
64
+ print(json.dumps(value,sort_keys=True,allow_nan=False))
65
+
66
+
67
+ if __name__=='__main__':
68
+ main()
tasks/service-hr-certifications-41834/tests/target.json ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "certs": {
3
+ "R14795": {
4
+ "course": "induction",
5
+ "expires_day": 475,
6
+ "person": "S47232",
7
+ "state": "deferred"
8
+ },
9
+ "R17387": {
10
+ "course": "privacy",
11
+ "expires_day": 493,
12
+ "person": "S44297",
13
+ "state": "active"
14
+ },
15
+ "R29167": {
16
+ "course": "records",
17
+ "expires_day": 488,
18
+ "person": "S29415",
19
+ "state": "active"
20
+ },
21
+ "R31665": {
22
+ "course": "privacy",
23
+ "expires_day": 460,
24
+ "person": "S34408",
25
+ "state": "enrolled"
26
+ },
27
+ "R32632": {
28
+ "course": "privacy",
29
+ "expires_day": 455,
30
+ "person": "S13138",
31
+ "state": "enrolled"
32
+ },
33
+ "R49769": {
34
+ "course": "records",
35
+ "expires_day": 455,
36
+ "person": "S58788",
37
+ "state": "enrolled"
38
+ },
39
+ "R61393": {
40
+ "course": "records",
41
+ "expires_day": 451,
42
+ "person": "S65830",
43
+ "state": "deferred"
44
+ },
45
+ "R63021": {
46
+ "course": "privacy",
47
+ "expires_day": 473,
48
+ "person": "S81260",
49
+ "state": "waitlisted"
50
+ },
51
+ "R70074": {
52
+ "course": "induction",
53
+ "expires_day": 480,
54
+ "person": "S96518",
55
+ "state": "waitlisted"
56
+ },
57
+ "R78798": {
58
+ "course": "records",
59
+ "expires_day": 455,
60
+ "person": "S69713",
61
+ "state": "enrolled"
62
+ },
63
+ "R90130": {
64
+ "course": "induction",
65
+ "expires_day": 464,
66
+ "person": "S68520",
67
+ "state": "retired"
68
+ }
69
+ },
70
+ "leave": {
71
+ "S13138": {
72
+ "available_day": 459
73
+ },
74
+ "S29415": {
75
+ "available_day": 475
76
+ },
77
+ "S34408": {
78
+ "available_day": 485
79
+ },
80
+ "S44297": {
81
+ "available_day": 485
82
+ },
83
+ "S47232": {
84
+ "available_day": 489
85
+ },
86
+ "S58788": {
87
+ "available_day": 484
88
+ },
89
+ "S65830": {
90
+ "available_day": 489
91
+ },
92
+ "S68520": {
93
+ "available_day": 482
94
+ },
95
+ "S69713": {
96
+ "available_day": 459
97
+ },
98
+ "S81260": {
99
+ "available_day": 482
100
+ },
101
+ "S96518": {
102
+ "available_day": 475
103
+ }
104
+ },
105
+ "renewals": {
106
+ "renew-R31665": {
107
+ "course": "privacy",
108
+ "person": "S34408",
109
+ "session": "renewal"
110
+ },
111
+ "renew-R32632": {
112
+ "course": "privacy",
113
+ "person": "S13138",
114
+ "session": "renewal"
115
+ },
116
+ "renew-R49769": {
117
+ "course": "records",
118
+ "person": "S58788",
119
+ "session": "renewal"
120
+ },
121
+ "renew-R78798": {
122
+ "course": "records",
123
+ "person": "S69713",
124
+ "session": "renewal"
125
+ }
126
+ },
127
+ "sessions": {
128
+ "renewal": {
129
+ "seats": 0,
130
+ "start_day": 485
131
+ }
132
+ }
133
+ }
tasks/service-hr-certifications-41834/tests/test.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ mkdir -p /logs/verifier /workspace/outputs
4
+ exec python3 -B -I /tests/grade.py
tasks/service-hr-certifications-41834/tests/world.json ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "certs": {
3
+ "R14795": {
4
+ "course": "induction",
5
+ "expires_day": 475,
6
+ "person": "S47232",
7
+ "state": "active"
8
+ },
9
+ "R17387": {
10
+ "course": "privacy",
11
+ "expires_day": 493,
12
+ "person": "S44297",
13
+ "state": "active"
14
+ },
15
+ "R29167": {
16
+ "course": "records",
17
+ "expires_day": 488,
18
+ "person": "S29415",
19
+ "state": "active"
20
+ },
21
+ "R31665": {
22
+ "course": "privacy",
23
+ "expires_day": 460,
24
+ "person": "S34408",
25
+ "state": "active"
26
+ },
27
+ "R32632": {
28
+ "course": "privacy",
29
+ "expires_day": 455,
30
+ "person": "S13138",
31
+ "state": "active"
32
+ },
33
+ "R49769": {
34
+ "course": "records",
35
+ "expires_day": 455,
36
+ "person": "S58788",
37
+ "state": "active"
38
+ },
39
+ "R61393": {
40
+ "course": "records",
41
+ "expires_day": 451,
42
+ "person": "S65830",
43
+ "state": "active"
44
+ },
45
+ "R63021": {
46
+ "course": "privacy",
47
+ "expires_day": 473,
48
+ "person": "S81260",
49
+ "state": "active"
50
+ },
51
+ "R70074": {
52
+ "course": "induction",
53
+ "expires_day": 480,
54
+ "person": "S96518",
55
+ "state": "active"
56
+ },
57
+ "R78798": {
58
+ "course": "records",
59
+ "expires_day": 455,
60
+ "person": "S69713",
61
+ "state": "active"
62
+ },
63
+ "R90130": {
64
+ "course": "induction",
65
+ "expires_day": 464,
66
+ "person": "S68520",
67
+ "state": "retired"
68
+ }
69
+ },
70
+ "leave": {
71
+ "S13138": {
72
+ "available_day": 459
73
+ },
74
+ "S29415": {
75
+ "available_day": 475
76
+ },
77
+ "S34408": {
78
+ "available_day": 485
79
+ },
80
+ "S44297": {
81
+ "available_day": 485
82
+ },
83
+ "S47232": {
84
+ "available_day": 489
85
+ },
86
+ "S58788": {
87
+ "available_day": 484
88
+ },
89
+ "S65830": {
90
+ "available_day": 489
91
+ },
92
+ "S68520": {
93
+ "available_day": 482
94
+ },
95
+ "S69713": {
96
+ "available_day": 459
97
+ },
98
+ "S81260": {
99
+ "available_day": 482
100
+ },
101
+ "S96518": {
102
+ "available_day": 475
103
+ }
104
+ },
105
+ "renewals": {},
106
+ "sessions": {
107
+ "renewal": {
108
+ "seats": 4,
109
+ "start_day": 485
110
+ }
111
+ }
112
+ }
tasks/service-hr-certifications-41834/tests/world_check.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay submitted mutations from the private verifier's initial state."""
2
+ from types import ModuleType
3
+ import json
4
+
5
+
6
+ def check(spec, outputs, tests):
7
+ replay = ModuleType('workflow_replay')
8
+ exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__)
9
+ world = json.loads((tests/'world.json').read_text())
10
+ target = json.loads((tests/'target.json').read_text())
11
+ # Only fields whose starting and expected values differ may be changed. Attempts
12
+ # to temporarily alter a protected field fail even when a later write restores it.
13
+ allowed = {
14
+ (app,key): {field for field,value in doc.items()
15
+ if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)}
16
+ for app,records in target.items() for key,doc in records.items()
17
+ }
18
+ actions = replay.load_actions(outputs/'actions.jsonl')
19
+ for event in actions:
20
+ replay.apply(world,event)
21
+ touched = set(event['fields'])
22
+ if not touched <= allowed.get((event['app'],event['id']),set()):
23
+ return False,'protected field or record write'
24
+ if not replay.same(world,target):
25
+ return False,'required business outcomes incomplete'
26
+ return True,''
tasks/service-hr-certifications-41834/validation/openenv.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "profile": "harbor-semantic-v1",
3
+ "reward_key": "reward",
4
+ "reward": {
5
+ "range": [
6
+ 0,
7
+ 1
8
+ ],
9
+ "oracle_tolerance": 0,
10
+ "floor_margin": 0.1
11
+ },
12
+ "resources": {
13
+ "cpu": 1,
14
+ "memory_mb": 4096,
15
+ "disk_mb": 10240,
16
+ "episode_timeout_s": 1800
17
+ },
18
+ "types": {
19
+ "tags": [
20
+ "knowledge-work",
21
+ "cross-app-workflows",
22
+ "conditional-execution",
23
+ "protected-state",
24
+ "hr"
25
+ ]
26
+ },
27
+ "requires_credentials": false
28
+ }
tasks/service-hr-certifications-41837/environment/inputs/apps.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline business-app client. Print usage with --help."""
2
+ import argparse
3
+ import copy
4
+ import fcntl
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+
10
+ def same(left, right):
11
+ return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False)
12
+
13
+
14
+ def apply(world, action):
15
+ if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}:
16
+ raise ValueError('expected op, app, id, fields')
17
+ op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields'))
18
+ if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields:
19
+ raise ValueError('unknown app, invalid id or empty fields')
20
+ collection = world[app]
21
+ if op == 'update' and key in collection:
22
+ collection[key].update(copy.deepcopy(fields))
23
+ elif op == 'create' and key not in collection:
24
+ collection[key] = copy.deepcopy(fields)
25
+ else:
26
+ raise ValueError(f'invalid {op} for {app}/{key}')
27
+
28
+
29
+ def load_actions(path):
30
+ if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000):
31
+ raise ValueError('invalid action log')
32
+ if not path.exists():
33
+ return []
34
+ return [json.loads(s) for s in path.read_text().splitlines() if s.strip()]
35
+
36
+
37
+ def main():
38
+ parser = argparse.ArgumentParser(description=__doc__)
39
+ parser.add_argument('op', choices=('apps','list','get','update','create'))
40
+ parser.add_argument('app', nargs='?')
41
+ parser.add_argument('id', nargs='?')
42
+ parser.add_argument('fields', nargs='?', type=json.loads)
43
+ args = parser.parse_args()
44
+ world = json.loads(Path(__file__).with_name('world.json').read_text())
45
+ out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs'))
46
+ out.mkdir(parents=True, exist_ok=True)
47
+ log = out/'actions.jsonl'
48
+ with (out/'.actions.lock').open('a') as lock:
49
+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
50
+ for event in load_actions(log):
51
+ apply(world,event)
52
+ if args.op=='apps':
53
+ value=sorted(world)
54
+ elif args.op=='list':
55
+ value=world[args.app]
56
+ elif args.op=='get':
57
+ value=world[args.app][args.id]
58
+ else:
59
+ event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields}
60
+ apply(world,event)
61
+ with log.open('a') as handle:
62
+ handle.write(json.dumps(event,allow_nan=False)+'\n')
63
+ value=world[args.app][args.id]
64
+ print(json.dumps(value,sort_keys=True,allow_nan=False))
65
+
66
+
67
+ if __name__=='__main__':
68
+ main()
tasks/service-hr-certifications-41837/environment/inputs/world.json ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "certs": {
3
+ "R11647": {
4
+ "course": "privacy",
5
+ "expires_day": 418,
6
+ "person": "S62317",
7
+ "state": "active"
8
+ },
9
+ "R21370": {
10
+ "course": "privacy",
11
+ "expires_day": 396,
12
+ "person": "S26846",
13
+ "state": "retired"
14
+ },
15
+ "R27606": {
16
+ "course": "privacy",
17
+ "expires_day": 399,
18
+ "person": "S62428",
19
+ "state": "active"
20
+ },
21
+ "R35407": {
22
+ "course": "privacy",
23
+ "expires_day": 415,
24
+ "person": "S31028",
25
+ "state": "active"
26
+ },
27
+ "R39621": {
28
+ "course": "privacy",
29
+ "expires_day": 386,
30
+ "person": "S48952",
31
+ "state": "active"
32
+ },
33
+ "R40742": {
34
+ "course": "records",
35
+ "expires_day": 386,
36
+ "person": "S57195",
37
+ "state": "active"
38
+ },
39
+ "R77131": {
40
+ "course": "privacy",
41
+ "expires_day": 404,
42
+ "person": "S67523",
43
+ "state": "active"
44
+ }
45
+ },
46
+ "leave": {
47
+ "S26846": {
48
+ "available_day": 406
49
+ },
50
+ "S31028": {
51
+ "available_day": 420
52
+ },
53
+ "S48952": {
54
+ "available_day": 390
55
+ },
56
+ "S57195": {
57
+ "available_day": 390
58
+ },
59
+ "S62317": {
60
+ "available_day": 413
61
+ },
62
+ "S62428": {
63
+ "available_day": 420
64
+ },
65
+ "S67523": {
66
+ "available_day": 420
67
+ }
68
+ },
69
+ "renewals": {},
70
+ "sessions": {
71
+ "renewal": {
72
+ "seats": 4,
73
+ "start_day": 416
74
+ }
75
+ }
76
+ }
tasks/service-hr-certifications-41837/instruction.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew-<cert ID> in renewals with person, course and session set to renewal. Update the session's remaining seats.
2
+
3
+ Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run
4
+ `apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record.
5
+ Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`.
6
+ The client records successful writes in `/workspace/outputs/actions.jsonl`.
7
+ Apply exactly the required changes. Other records and fields must remain untouched,
8
+ including temporary changes. Actions take effect in the local simulation only.
9
+
10
+ ## Deliverable
11
+
12
+ Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in
13
+ `/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory.
tasks/service-hr-certifications-41837/solution/files/actions.jsonl ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {"app": "certs", "fields": {"state": "enrolled"}, "id": "R39621", "op": "update"}
2
+ {"app": "certs", "fields": {"state": "enrolled"}, "id": "R40742", "op": "update"}
3
+ {"app": "certs", "fields": {"state": "deferred"}, "id": "R77131", "op": "update"}
4
+ {"app": "certs", "fields": {"state": "deferred"}, "id": "R27606", "op": "update"}
5
+ {"app": "certs", "fields": {"state": "deferred"}, "id": "R35407", "op": "update"}
6
+ {"app": "renewals", "fields": {"course": "privacy", "person": "S48952", "session": "renewal"}, "id": "renew-R39621", "op": "create"}
7
+ {"app": "renewals", "fields": {"course": "records", "person": "S57195", "session": "renewal"}, "id": "renew-R40742", "op": "create"}
8
+ {"app": "sessions", "fields": {"seats": 2}, "id": "renewal", "op": "update"}
tasks/service-hr-certifications-41837/solution/solve.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ mkdir -p /workspace/outputs
4
+ cp -R /solution/files/. /workspace/outputs/
tasks/service-hr-certifications-41837/task.toml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.3"
2
+
3
+ [task]
4
+ name = "apex-gap/service-hr-certifications-41837"
5
+
6
+ [metadata.apex_gap]
7
+ capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"]
8
+ dataset = "Original simulated workflows"
9
+ job = "hr"
10
+ seed = 41837
11
+ source = "local/original-automation-workflows"
12
+ source_revision = "1"
13
+ source_split = "synthetic"
14
+ source_task_id = "service-hr-certifications-41837"
15
+ template_family = "automation:service-hr-certifications"
16
+ workflow_template = "service-hr-certifications"
17
+
18
+ [metadata.openenv_hf_sandbox]
19
+ variant = "apex-gap-hfsandbox-v1"
20
+ task_modified_for_hf_sandbox = true
21
+ network_enabled = true
22
+
23
+ [environment]
24
+ docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf"
25
+ workdir = "/workspace"
26
+ cpus = 1
27
+ memory_mb = 4096
28
+ build_timeout_sec = 600
29
+ network_mode = "public"
30
+
31
+ [agent]
32
+ timeout_sec = 1800
33
+ network_mode = "public"
34
+
35
+ [verifier]
36
+ timeout_sec = 600
37
+ network_mode = "public"
38
+ environment_mode = "separate"
39
+
40
+ [verifier.environment]
41
+ network_mode = "public"
42
+ cpus = 1
43
+ memory_mb = 4096
44
+
45
+ [[artifacts]]
46
+ source = "/workspace/outputs"
tasks/service-hr-certifications-41837/tests/expected.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "checks": [
3
+ {
4
+ "id": "business-outcomes",
5
+ "type": "custom",
6
+ "module": "world_check"
7
+ }
8
+ ]
9
+ }
tasks/service-hr-certifications-41837/tests/grade.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic grader shared by converted knowledge-work tasks.
2
+
3
+ Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the
4
+ submitted /workspace/outputs tree and writes a binary reward plus per-check details.
5
+ No model calls and no network.
6
+
7
+ expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]}
8
+ Check types:
9
+ answer field of outputs/answer.json; kind = number|text|choice|date|bool|list
10
+ xlsx_range recalculated outputs/<file> vs tests/<target> over sheet!range (SpreadsheetBench rules)
11
+ xlsx_cell recalculated outputs/<file> sheet!cell vs value with tolerance (optional alt_values)
12
+ file_contains outputs/<file> text (docx/pdf/ics/eml/txt) must contain every needle
13
+ custom tests/<module>.py defines check(spec, outputs_dir, tests_dir) -> (bool, str)
14
+ """
15
+
16
+ import datetime as dt
17
+ import json
18
+ import re
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ import tempfile
23
+ import unicodedata
24
+ from pathlib import Path
25
+
26
+ OUT = Path("/workspace/outputs")
27
+ TESTS = Path("/tests")
28
+ LOGS = Path("/logs/verifier")
29
+
30
+
31
+ def norm_text(v):
32
+ v = unicodedata.normalize("NFKC", str(v)).casefold()
33
+ v = re.sub(r"[‘’“”]", "'", v)
34
+ v = re.sub(r"[^\w%.$/-]+", " ", v)
35
+ return " ".join(v.split()).strip(" .")
36
+
37
+
38
+ def to_number(v):
39
+ if isinstance(v, bool):
40
+ raise ValueError("bool")
41
+ if isinstance(v, (int, float)):
42
+ return float(v)
43
+ s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-")
44
+ neg = s.startswith("(") and s.endswith(")")
45
+ s = s.strip("()").strip()
46
+ pct = s.endswith("%")
47
+ s = s.rstrip("%").strip()
48
+ s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I)
49
+ x = float(s)
50
+ x = -x if neg else x
51
+ return x / 100 if pct else x
52
+
53
+
54
+ def number_ok(got, want, rel, abs_):
55
+ try:
56
+ g = to_number(got)
57
+ except (TypeError, ValueError):
58
+ return False
59
+ w = float(want)
60
+ tol = max(abs_, rel * abs(w))
61
+ # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which.
62
+ candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g]
63
+ return any(abs(c - w) <= tol for c in candidates)
64
+
65
+
66
+ def parse_date(v):
67
+ if isinstance(v, (dt.date, dt.datetime)):
68
+ return v if isinstance(v, dt.date) else v.date()
69
+ s = str(v).strip()
70
+ for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"):
71
+ try:
72
+ return dt.datetime.strptime(s, fmt).date()
73
+ except ValueError:
74
+ continue
75
+ raise ValueError(s)
76
+
77
+
78
+ def check_answer(check, answers):
79
+ key = check["field"]
80
+ if key not in answers:
81
+ return False, f"missing field {key!r}"
82
+ got, want, kind = answers[key], check["value"], check.get("kind", "text")
83
+ if kind == "number":
84
+ ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01))
85
+ if not ok and check.get("percent_either"):
86
+ ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or (
87
+ number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100)
88
+ )
89
+ elif kind == "date":
90
+ try:
91
+ ok = parse_date(got) == parse_date(want)
92
+ except ValueError:
93
+ ok = False
94
+ elif kind == "bool":
95
+ g = norm_text(got)
96
+ ok = g in {"yes", "true"} if want else g in {"no", "false"}
97
+ elif kind == "choice":
98
+ ok = norm_text(got) == norm_text(want)
99
+ elif kind == "list":
100
+ if not isinstance(got, list):
101
+ return False, f"{key}: expected a JSON list"
102
+ # Filenames may be given with a directory prefix; compare base names.
103
+ base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1])
104
+ ok = sorted(base(x) for x in got) == sorted(base(x) for x in want)
105
+ else:
106
+ accepted = check.get("accept", [want])
107
+ ok = norm_text(got) in {norm_text(a) for a in accepted}
108
+ return ok, "" if ok else f"{key}: got {got!r}"
109
+
110
+
111
+ # LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation.
112
+ RECALC_PROFILE = """<?xml version="1.0" encoding="UTF-8"?>
113
+ <oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema">
114
+ <item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="OOXMLRecalcMode" oor:op="fuse"><value>0</value></prop></item>
115
+ <item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="ODFRecalcMode" oor:op="fuse"><value>0</value></prop></item>
116
+ </oor:items>
117
+ """
118
+
119
+
120
+ def recalc(path, tmp):
121
+ dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}"
122
+ dest.mkdir()
123
+ profile = Path(tmp) / "lo-profile"
124
+ if not profile.exists():
125
+ (profile / "user").mkdir(parents=True)
126
+ (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE)
127
+ subprocess.run(
128
+ ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to",
129
+ "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)],
130
+ stdout=subprocess.DEVNULL,
131
+ stderr=subprocess.DEVNULL,
132
+ timeout=180,
133
+ check=False,
134
+ )
135
+ out = dest / (Path(path).stem + ".xlsx")
136
+ return out if out.exists() else Path(path)
137
+
138
+
139
+ def cell_value(v):
140
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
141
+ return round(float(v), 2)
142
+ if isinstance(v, dt.datetime):
143
+ return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0)
144
+ if isinstance(v, dt.time):
145
+ return v.strftime("%H:%M")
146
+ if isinstance(v, str):
147
+ try:
148
+ return round(float(v), 2)
149
+ except ValueError:
150
+ return v.strip()
151
+ return v
152
+
153
+
154
+ def time_of(v):
155
+ """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and
156
+ Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells."""
157
+ if isinstance(v, dt.time):
158
+ v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400
159
+ if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1:
160
+ return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M")
161
+ return None
162
+
163
+
164
+ def same_cell(a, b):
165
+ if isinstance(a, dt.time) is not isinstance(b, dt.time):
166
+ n = b if isinstance(a, dt.time) else a
167
+ if time_of(n) is not None: # a time against a plain day fraction
168
+ return time_of(a) == time_of(b)
169
+ a, b = cell_value(a), cell_value(b)
170
+ if a in (None, "") and b in (None, ""):
171
+ return True
172
+ return type(a) is type(b) and a == b
173
+
174
+
175
+ ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"}
176
+
177
+
178
+ def is_error(v):
179
+ return isinstance(v, str) and (v in ERRORS or v.startswith("Err:"))
180
+
181
+
182
+ def cells(rng):
183
+ if ":" not in rng:
184
+ return [rng]
185
+ from openpyxl.utils import range_boundaries, get_column_letter
186
+
187
+ c1, r1, c2, r2 = range_boundaries(rng)
188
+ return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)]
189
+
190
+
191
+ def load(path, tmp):
192
+ import openpyxl
193
+
194
+ return openpyxl.load_workbook(recalc(path, tmp), data_only=True)
195
+
196
+
197
+ def check_xlsx_range(check, tmp, cache):
198
+ sub = OUT / check["file"]
199
+ if not sub.is_file():
200
+ return False, f"missing output {check['file']}"
201
+ if sub not in cache:
202
+ cache[sub] = load(sub, tmp)
203
+ tgt = TESTS / check["target"]
204
+ if tgt not in cache:
205
+ cache[tgt] = load(tgt, tmp)
206
+ got, want = cache[sub], cache[tgt]
207
+ cached = None # the target's stored (Excel-computed) values, read only when Calc errs
208
+ for sheet, rng in check["ranges"]:
209
+ sheet = sheet or want.sheetnames[0]
210
+ if sheet not in got.sheetnames:
211
+ return False, f"sheet {sheet!r} missing"
212
+ for name in cells(rng):
213
+ w = want[sheet][name].value
214
+ if is_error(w):
215
+ # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4).
216
+ # The value Excel stored is the intended answer.
217
+ if cached is None:
218
+ import openpyxl
219
+
220
+ cached = openpyxl.load_workbook(tgt, data_only=True)
221
+ c = cached[sheet][name].value if sheet in cached.sheetnames else None
222
+ if c is not None and not is_error(c):
223
+ w = c
224
+ if not same_cell(w, got[sheet][name].value):
225
+ return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}"
226
+ return True, ""
227
+
228
+
229
+ def check_xlsx_cell(check, tmp, cache):
230
+ sub = OUT / check["file"]
231
+ if not sub.is_file():
232
+ return False, f"missing output {check['file']}"
233
+ if sub not in cache:
234
+ cache[sub] = load(sub, tmp)
235
+ wb = cache[sub]
236
+ if check["sheet"] not in wb.sheetnames:
237
+ return False, f"sheet {check['sheet']!r} missing"
238
+ got = wb[check["sheet"]][check["cell"]].value
239
+ want = check["value"]
240
+ if isinstance(want, (int, float)):
241
+ # alt_values: other accepted golds where the source admits more than one reading.
242
+ ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01))
243
+ for w in [want, *check.get("alt_values", [])])
244
+ else:
245
+ ok = norm_text(got) == norm_text(want)
246
+ return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}"
247
+
248
+
249
+ def text_of(path):
250
+ suffix = path.suffix.lower()
251
+ if suffix == ".docx":
252
+ import docx
253
+
254
+ d = docx.Document(path)
255
+ parts = [p.text for p in d.paragraphs]
256
+ for t in d.tables:
257
+ parts += [c.text for row in t.rows for c in row.cells]
258
+ return "\n".join(parts)
259
+ if suffix == ".pdf":
260
+ import pdfplumber
261
+
262
+ with pdfplumber.open(path) as pdf:
263
+ return "\n".join(page.extract_text() or "" for page in pdf.pages)
264
+ return path.read_text(errors="replace")
265
+
266
+
267
+ def check_file_contains(check, tmp, cache):
268
+ sub = OUT / check["file"]
269
+ if not sub.is_file():
270
+ return False, f"missing output {check['file']}"
271
+ text = text_of(sub)
272
+ hay = text if check.get("case_sensitive") else text.casefold()
273
+ for needle in check["needles"]:
274
+ n = needle if check.get("case_sensitive") else needle.casefold()
275
+ if n not in hay:
276
+ return False, f"{check['file']} lacks {needle!r}"
277
+ return True, ""
278
+
279
+
280
+ def main():
281
+ LOGS.mkdir(parents=True, exist_ok=True)
282
+ reward_path = LOGS / "reward.txt"
283
+ reward_path.write_text("0\n")
284
+ spec = json.loads((TESTS / "expected.json").read_text())
285
+ answers, details = {}, []
286
+ answer_file = OUT / "answer.json"
287
+ if answer_file.is_file():
288
+ try:
289
+ answers = json.loads(answer_file.read_text())
290
+ if not isinstance(answers, dict):
291
+ answers = {}
292
+ except json.JSONDecodeError:
293
+ answers = {}
294
+ tmp = tempfile.mkdtemp()
295
+ cache = {}
296
+ try:
297
+ for check in spec["checks"]:
298
+ try:
299
+ if check["type"] == "answer":
300
+ ok, why = check_answer(check, answers)
301
+ elif check["type"] == "xlsx_range":
302
+ ok, why = check_xlsx_range(check, tmp, cache)
303
+ elif check["type"] == "xlsx_cell":
304
+ ok, why = check_xlsx_cell(check, tmp, cache)
305
+ elif check["type"] == "file_contains":
306
+ ok, why = check_file_contains(check, tmp, cache)
307
+ elif check["type"] == "custom":
308
+ import importlib.util
309
+
310
+ spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py")
311
+ mod = importlib.util.module_from_spec(spec_)
312
+ spec_.loader.exec_module(mod)
313
+ ok, why = mod.check(check, OUT, TESTS)
314
+ else:
315
+ ok, why = False, f"unknown check type {check['type']}"
316
+ except Exception as exc: # a malformed submission fails the check, not the grader
317
+ ok, why = False, f"{type(exc).__name__}: {exc}"
318
+ details.append({"id": check["id"], "passed": ok, "detail": why})
319
+ finally:
320
+ shutil.rmtree(tmp, ignore_errors=True)
321
+ passed = sum(d["passed"] for d in details)
322
+ total = len(details)
323
+ reward = 1 if total and passed == total else 0
324
+ (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1))
325
+ reward_path.write_text(f"{reward}\n")
326
+ print(f"{passed}/{total} checks passed; reward {reward}")
327
+
328
+
329
+ if __name__ == "__main__":
330
+ sys.exit(main())
tasks/service-hr-certifications-41837/tests/replay.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline business-app client. Print usage with --help."""
2
+ import argparse
3
+ import copy
4
+ import fcntl
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+
10
+ def same(left, right):
11
+ return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False)
12
+
13
+
14
+ def apply(world, action):
15
+ if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}:
16
+ raise ValueError('expected op, app, id, fields')
17
+ op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields'))
18
+ if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields:
19
+ raise ValueError('unknown app, invalid id or empty fields')
20
+ collection = world[app]
21
+ if op == 'update' and key in collection:
22
+ collection[key].update(copy.deepcopy(fields))
23
+ elif op == 'create' and key not in collection:
24
+ collection[key] = copy.deepcopy(fields)
25
+ else:
26
+ raise ValueError(f'invalid {op} for {app}/{key}')
27
+
28
+
29
+ def load_actions(path):
30
+ if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000):
31
+ raise ValueError('invalid action log')
32
+ if not path.exists():
33
+ return []
34
+ return [json.loads(s) for s in path.read_text().splitlines() if s.strip()]
35
+
36
+
37
+ def main():
38
+ parser = argparse.ArgumentParser(description=__doc__)
39
+ parser.add_argument('op', choices=('apps','list','get','update','create'))
40
+ parser.add_argument('app', nargs='?')
41
+ parser.add_argument('id', nargs='?')
42
+ parser.add_argument('fields', nargs='?', type=json.loads)
43
+ args = parser.parse_args()
44
+ world = json.loads(Path(__file__).with_name('world.json').read_text())
45
+ out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs'))
46
+ out.mkdir(parents=True, exist_ok=True)
47
+ log = out/'actions.jsonl'
48
+ with (out/'.actions.lock').open('a') as lock:
49
+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
50
+ for event in load_actions(log):
51
+ apply(world,event)
52
+ if args.op=='apps':
53
+ value=sorted(world)
54
+ elif args.op=='list':
55
+ value=world[args.app]
56
+ elif args.op=='get':
57
+ value=world[args.app][args.id]
58
+ else:
59
+ event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields}
60
+ apply(world,event)
61
+ with log.open('a') as handle:
62
+ handle.write(json.dumps(event,allow_nan=False)+'\n')
63
+ value=world[args.app][args.id]
64
+ print(json.dumps(value,sort_keys=True,allow_nan=False))
65
+
66
+
67
+ if __name__=='__main__':
68
+ main()
tasks/service-hr-certifications-41837/tests/target.json ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "certs": {
3
+ "R11647": {
4
+ "course": "privacy",
5
+ "expires_day": 418,
6
+ "person": "S62317",
7
+ "state": "active"
8
+ },
9
+ "R21370": {
10
+ "course": "privacy",
11
+ "expires_day": 396,
12
+ "person": "S26846",
13
+ "state": "retired"
14
+ },
15
+ "R27606": {
16
+ "course": "privacy",
17
+ "expires_day": 399,
18
+ "person": "S62428",
19
+ "state": "deferred"
20
+ },
21
+ "R35407": {
22
+ "course": "privacy",
23
+ "expires_day": 415,
24
+ "person": "S31028",
25
+ "state": "deferred"
26
+ },
27
+ "R39621": {
28
+ "course": "privacy",
29
+ "expires_day": 386,
30
+ "person": "S48952",
31
+ "state": "enrolled"
32
+ },
33
+ "R40742": {
34
+ "course": "records",
35
+ "expires_day": 386,
36
+ "person": "S57195",
37
+ "state": "enrolled"
38
+ },
39
+ "R77131": {
40
+ "course": "privacy",
41
+ "expires_day": 404,
42
+ "person": "S67523",
43
+ "state": "deferred"
44
+ }
45
+ },
46
+ "leave": {
47
+ "S26846": {
48
+ "available_day": 406
49
+ },
50
+ "S31028": {
51
+ "available_day": 420
52
+ },
53
+ "S48952": {
54
+ "available_day": 390
55
+ },
56
+ "S57195": {
57
+ "available_day": 390
58
+ },
59
+ "S62317": {
60
+ "available_day": 413
61
+ },
62
+ "S62428": {
63
+ "available_day": 420
64
+ },
65
+ "S67523": {
66
+ "available_day": 420
67
+ }
68
+ },
69
+ "renewals": {
70
+ "renew-R39621": {
71
+ "course": "privacy",
72
+ "person": "S48952",
73
+ "session": "renewal"
74
+ },
75
+ "renew-R40742": {
76
+ "course": "records",
77
+ "person": "S57195",
78
+ "session": "renewal"
79
+ }
80
+ },
81
+ "sessions": {
82
+ "renewal": {
83
+ "seats": 2,
84
+ "start_day": 416
85
+ }
86
+ }
87
+ }
tasks/service-hr-certifications-41837/tests/test.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ mkdir -p /logs/verifier /workspace/outputs
4
+ exec python3 -B -I /tests/grade.py
tasks/service-hr-certifications-41837/tests/world.json ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "certs": {
3
+ "R11647": {
4
+ "course": "privacy",
5
+ "expires_day": 418,
6
+ "person": "S62317",
7
+ "state": "active"
8
+ },
9
+ "R21370": {
10
+ "course": "privacy",
11
+ "expires_day": 396,
12
+ "person": "S26846",
13
+ "state": "retired"
14
+ },
15
+ "R27606": {
16
+ "course": "privacy",
17
+ "expires_day": 399,
18
+ "person": "S62428",
19
+ "state": "active"
20
+ },
21
+ "R35407": {
22
+ "course": "privacy",
23
+ "expires_day": 415,
24
+ "person": "S31028",
25
+ "state": "active"
26
+ },
27
+ "R39621": {
28
+ "course": "privacy",
29
+ "expires_day": 386,
30
+ "person": "S48952",
31
+ "state": "active"
32
+ },
33
+ "R40742": {
34
+ "course": "records",
35
+ "expires_day": 386,
36
+ "person": "S57195",
37
+ "state": "active"
38
+ },
39
+ "R77131": {
40
+ "course": "privacy",
41
+ "expires_day": 404,
42
+ "person": "S67523",
43
+ "state": "active"
44
+ }
45
+ },
46
+ "leave": {
47
+ "S26846": {
48
+ "available_day": 406
49
+ },
50
+ "S31028": {
51
+ "available_day": 420
52
+ },
53
+ "S48952": {
54
+ "available_day": 390
55
+ },
56
+ "S57195": {
57
+ "available_day": 390
58
+ },
59
+ "S62317": {
60
+ "available_day": 413
61
+ },
62
+ "S62428": {
63
+ "available_day": 420
64
+ },
65
+ "S67523": {
66
+ "available_day": 420
67
+ }
68
+ },
69
+ "renewals": {},
70
+ "sessions": {
71
+ "renewal": {
72
+ "seats": 4,
73
+ "start_day": 416
74
+ }
75
+ }
76
+ }
tasks/service-hr-certifications-41837/tests/world_check.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay submitted mutations from the private verifier's initial state."""
2
+ from types import ModuleType
3
+ import json
4
+
5
+
6
+ def check(spec, outputs, tests):
7
+ replay = ModuleType('workflow_replay')
8
+ exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__)
9
+ world = json.loads((tests/'world.json').read_text())
10
+ target = json.loads((tests/'target.json').read_text())
11
+ # Only fields whose starting and expected values differ may be changed. Attempts
12
+ # to temporarily alter a protected field fail even when a later write restores it.
13
+ allowed = {
14
+ (app,key): {field for field,value in doc.items()
15
+ if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)}
16
+ for app,records in target.items() for key,doc in records.items()
17
+ }
18
+ actions = replay.load_actions(outputs/'actions.jsonl')
19
+ for event in actions:
20
+ replay.apply(world,event)
21
+ touched = set(event['fields'])
22
+ if not touched <= allowed.get((event['app'],event['id']),set()):
23
+ return False,'protected field or record write'
24
+ if not replay.same(world,target):
25
+ return False,'required business outcomes incomplete'
26
+ return True,''
tasks/service-hr-certifications-41837/validation/openenv.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "profile": "harbor-semantic-v1",
3
+ "reward_key": "reward",
4
+ "reward": {
5
+ "range": [
6
+ 0,
7
+ 1
8
+ ],
9
+ "oracle_tolerance": 0,
10
+ "floor_margin": 0.1
11
+ },
12
+ "resources": {
13
+ "cpu": 1,
14
+ "memory_mb": 4096,
15
+ "disk_mb": 10240,
16
+ "episode_timeout_s": 1800
17
+ },
18
+ "types": {
19
+ "tags": [
20
+ "knowledge-work",
21
+ "cross-app-workflows",
22
+ "conditional-execution",
23
+ "protected-state",
24
+ "hr"
25
+ ]
26
+ },
27
+ "requires_credentials": false
28
+ }
tasks/service-hr-certifications-41840/environment/inputs/apps.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline business-app client. Print usage with --help."""
2
+ import argparse
3
+ import copy
4
+ import fcntl
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+
10
+ def same(left, right):
11
+ return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False)
12
+
13
+
14
+ def apply(world, action):
15
+ if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}:
16
+ raise ValueError('expected op, app, id, fields')
17
+ op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields'))
18
+ if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields:
19
+ raise ValueError('unknown app, invalid id or empty fields')
20
+ collection = world[app]
21
+ if op == 'update' and key in collection:
22
+ collection[key].update(copy.deepcopy(fields))
23
+ elif op == 'create' and key not in collection:
24
+ collection[key] = copy.deepcopy(fields)
25
+ else:
26
+ raise ValueError(f'invalid {op} for {app}/{key}')
27
+
28
+
29
+ def load_actions(path):
30
+ if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000):
31
+ raise ValueError('invalid action log')
32
+ if not path.exists():
33
+ return []
34
+ return [json.loads(s) for s in path.read_text().splitlines() if s.strip()]
35
+
36
+
37
+ def main():
38
+ parser = argparse.ArgumentParser(description=__doc__)
39
+ parser.add_argument('op', choices=('apps','list','get','update','create'))
40
+ parser.add_argument('app', nargs='?')
41
+ parser.add_argument('id', nargs='?')
42
+ parser.add_argument('fields', nargs='?', type=json.loads)
43
+ args = parser.parse_args()
44
+ world = json.loads(Path(__file__).with_name('world.json').read_text())
45
+ out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs'))
46
+ out.mkdir(parents=True, exist_ok=True)
47
+ log = out/'actions.jsonl'
48
+ with (out/'.actions.lock').open('a') as lock:
49
+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
50
+ for event in load_actions(log):
51
+ apply(world,event)
52
+ if args.op=='apps':
53
+ value=sorted(world)
54
+ elif args.op=='list':
55
+ value=world[args.app]
56
+ elif args.op=='get':
57
+ value=world[args.app][args.id]
58
+ else:
59
+ event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields}
60
+ apply(world,event)
61
+ with log.open('a') as handle:
62
+ handle.write(json.dumps(event,allow_nan=False)+'\n')
63
+ value=world[args.app][args.id]
64
+ print(json.dumps(value,sort_keys=True,allow_nan=False))
65
+
66
+
67
+ if __name__=='__main__':
68
+ main()
tasks/service-hr-certifications-41840/environment/inputs/world.json ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "certs": {
3
+ "R14020": {
4
+ "course": "induction",
5
+ "expires_day": 398,
6
+ "person": "S37318",
7
+ "state": "active"
8
+ },
9
+ "R14981": {
10
+ "course": "induction",
11
+ "expires_day": 411,
12
+ "person": "S83572",
13
+ "state": "active"
14
+ },
15
+ "R21547": {
16
+ "course": "induction",
17
+ "expires_day": 424,
18
+ "person": "S37724",
19
+ "state": "active"
20
+ },
21
+ "R34688": {
22
+ "course": "records",
23
+ "expires_day": 397,
24
+ "person": "S29462",
25
+ "state": "active"
26
+ },
27
+ "R35432": {
28
+ "course": "records",
29
+ "expires_day": 395,
30
+ "person": "S18548",
31
+ "state": "active"
32
+ },
33
+ "R69002": {
34
+ "course": "induction",
35
+ "expires_day": 422,
36
+ "person": "S78988",
37
+ "state": "active"
38
+ },
39
+ "R79833": {
40
+ "course": "records",
41
+ "expires_day": 430,
42
+ "person": "S98094",
43
+ "state": "retired"
44
+ },
45
+ "R83170": {
46
+ "course": "privacy",
47
+ "expires_day": 420,
48
+ "person": "S63123",
49
+ "state": "active"
50
+ }
51
+ },
52
+ "leave": {
53
+ "S18548": {
54
+ "available_day": 419
55
+ },
56
+ "S29462": {
57
+ "available_day": 400
58
+ },
59
+ "S37318": {
60
+ "available_day": 400
61
+ },
62
+ "S37724": {
63
+ "available_day": 419
64
+ },
65
+ "S63123": {
66
+ "available_day": 424
67
+ },
68
+ "S78988": {
69
+ "available_day": 417
70
+ },
71
+ "S83572": {
72
+ "available_day": 424
73
+ },
74
+ "S98094": {
75
+ "available_day": 417
76
+ }
77
+ },
78
+ "renewals": {},
79
+ "sessions": {
80
+ "renewal": {
81
+ "seats": 3,
82
+ "start_day": 420
83
+ }
84
+ }
85
+ }
tasks/service-hr-certifications-41840/instruction.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew-<cert ID> in renewals with person, course and session set to renewal. Update the session's remaining seats.
2
+
3
+ Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run
4
+ `apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record.
5
+ Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`.
6
+ The client records successful writes in `/workspace/outputs/actions.jsonl`.
7
+ Apply exactly the required changes. Other records and fields must remain untouched,
8
+ including temporary changes. Actions take effect in the local simulation only.
9
+
10
+ ## Deliverable
11
+
12
+ Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in
13
+ `/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory.
tasks/service-hr-certifications-41840/solution/files/actions.jsonl ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {"app": "certs", "fields": {"state": "enrolled"}, "id": "R14020", "op": "update"}
2
+ {"app": "certs", "fields": {"state": "enrolled"}, "id": "R34688", "op": "update"}
3
+ {"app": "certs", "fields": {"state": "enrolled"}, "id": "R35432", "op": "update"}
4
+ {"app": "certs", "fields": {"state": "deferred"}, "id": "R83170", "op": "update"}
5
+ {"app": "certs", "fields": {"state": "deferred"}, "id": "R14981", "op": "update"}
6
+ {"app": "renewals", "fields": {"course": "records", "person": "S18548", "session": "renewal"}, "id": "renew-R35432", "op": "create"}
7
+ {"app": "renewals", "fields": {"course": "records", "person": "S29462", "session": "renewal"}, "id": "renew-R34688", "op": "create"}
8
+ {"app": "renewals", "fields": {"course": "induction", "person": "S37318", "session": "renewal"}, "id": "renew-R14020", "op": "create"}
9
+ {"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"}
tasks/service-hr-certifications-41840/solution/solve.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ mkdir -p /workspace/outputs
4
+ cp -R /solution/files/. /workspace/outputs/
tasks/service-hr-certifications-41840/task.toml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.3"
2
+
3
+ [task]
4
+ name = "apex-gap/service-hr-certifications-41840"
5
+
6
+ [metadata.apex_gap]
7
+ capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"]
8
+ dataset = "Original simulated workflows"
9
+ job = "hr"
10
+ seed = 41840
11
+ source = "local/original-automation-workflows"
12
+ source_revision = "1"
13
+ source_split = "synthetic"
14
+ source_task_id = "service-hr-certifications-41840"
15
+ template_family = "automation:service-hr-certifications"
16
+ workflow_template = "service-hr-certifications"
17
+
18
+ [metadata.openenv_hf_sandbox]
19
+ variant = "apex-gap-hfsandbox-v1"
20
+ task_modified_for_hf_sandbox = true
21
+ network_enabled = true
22
+
23
+ [environment]
24
+ docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf"
25
+ workdir = "/workspace"
26
+ cpus = 1
27
+ memory_mb = 4096
28
+ build_timeout_sec = 600
29
+ network_mode = "public"
30
+
31
+ [agent]
32
+ timeout_sec = 1800
33
+ network_mode = "public"
34
+
35
+ [verifier]
36
+ timeout_sec = 600
37
+ network_mode = "public"
38
+ environment_mode = "separate"
39
+
40
+ [verifier.environment]
41
+ network_mode = "public"
42
+ cpus = 1
43
+ memory_mb = 4096
44
+
45
+ [[artifacts]]
46
+ source = "/workspace/outputs"
tasks/service-hr-certifications-41840/tests/expected.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "checks": [
3
+ {
4
+ "id": "business-outcomes",
5
+ "type": "custom",
6
+ "module": "world_check"
7
+ }
8
+ ]
9
+ }
tasks/service-hr-certifications-41840/tests/grade.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic grader shared by converted knowledge-work tasks.
2
+
3
+ Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the
4
+ submitted /workspace/outputs tree and writes a binary reward plus per-check details.
5
+ No model calls and no network.
6
+
7
+ expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]}
8
+ Check types:
9
+ answer field of outputs/answer.json; kind = number|text|choice|date|bool|list
10
+ xlsx_range recalculated outputs/<file> vs tests/<target> over sheet!range (SpreadsheetBench rules)
11
+ xlsx_cell recalculated outputs/<file> sheet!cell vs value with tolerance (optional alt_values)
12
+ file_contains outputs/<file> text (docx/pdf/ics/eml/txt) must contain every needle
13
+ custom tests/<module>.py defines check(spec, outputs_dir, tests_dir) -> (bool, str)
14
+ """
15
+
16
+ import datetime as dt
17
+ import json
18
+ import re
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ import tempfile
23
+ import unicodedata
24
+ from pathlib import Path
25
+
26
+ OUT = Path("/workspace/outputs")
27
+ TESTS = Path("/tests")
28
+ LOGS = Path("/logs/verifier")
29
+
30
+
31
+ def norm_text(v):
32
+ v = unicodedata.normalize("NFKC", str(v)).casefold()
33
+ v = re.sub(r"[‘’“”]", "'", v)
34
+ v = re.sub(r"[^\w%.$/-]+", " ", v)
35
+ return " ".join(v.split()).strip(" .")
36
+
37
+
38
+ def to_number(v):
39
+ if isinstance(v, bool):
40
+ raise ValueError("bool")
41
+ if isinstance(v, (int, float)):
42
+ return float(v)
43
+ s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-")
44
+ neg = s.startswith("(") and s.endswith(")")
45
+ s = s.strip("()").strip()
46
+ pct = s.endswith("%")
47
+ s = s.rstrip("%").strip()
48
+ s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I)
49
+ x = float(s)
50
+ x = -x if neg else x
51
+ return x / 100 if pct else x
52
+
53
+
54
+ def number_ok(got, want, rel, abs_):
55
+ try:
56
+ g = to_number(got)
57
+ except (TypeError, ValueError):
58
+ return False
59
+ w = float(want)
60
+ tol = max(abs_, rel * abs(w))
61
+ # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which.
62
+ candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g]
63
+ return any(abs(c - w) <= tol for c in candidates)
64
+
65
+
66
+ def parse_date(v):
67
+ if isinstance(v, (dt.date, dt.datetime)):
68
+ return v if isinstance(v, dt.date) else v.date()
69
+ s = str(v).strip()
70
+ for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"):
71
+ try:
72
+ return dt.datetime.strptime(s, fmt).date()
73
+ except ValueError:
74
+ continue
75
+ raise ValueError(s)
76
+
77
+
78
+ def check_answer(check, answers):
79
+ key = check["field"]
80
+ if key not in answers:
81
+ return False, f"missing field {key!r}"
82
+ got, want, kind = answers[key], check["value"], check.get("kind", "text")
83
+ if kind == "number":
84
+ ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01))
85
+ if not ok and check.get("percent_either"):
86
+ ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or (
87
+ number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100)
88
+ )
89
+ elif kind == "date":
90
+ try:
91
+ ok = parse_date(got) == parse_date(want)
92
+ except ValueError:
93
+ ok = False
94
+ elif kind == "bool":
95
+ g = norm_text(got)
96
+ ok = g in {"yes", "true"} if want else g in {"no", "false"}
97
+ elif kind == "choice":
98
+ ok = norm_text(got) == norm_text(want)
99
+ elif kind == "list":
100
+ if not isinstance(got, list):
101
+ return False, f"{key}: expected a JSON list"
102
+ # Filenames may be given with a directory prefix; compare base names.
103
+ base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1])
104
+ ok = sorted(base(x) for x in got) == sorted(base(x) for x in want)
105
+ else:
106
+ accepted = check.get("accept", [want])
107
+ ok = norm_text(got) in {norm_text(a) for a in accepted}
108
+ return ok, "" if ok else f"{key}: got {got!r}"
109
+
110
+
111
+ # LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation.
112
+ RECALC_PROFILE = """<?xml version="1.0" encoding="UTF-8"?>
113
+ <oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema">
114
+ <item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="OOXMLRecalcMode" oor:op="fuse"><value>0</value></prop></item>
115
+ <item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="ODFRecalcMode" oor:op="fuse"><value>0</value></prop></item>
116
+ </oor:items>
117
+ """
118
+
119
+
120
+ def recalc(path, tmp):
121
+ dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}"
122
+ dest.mkdir()
123
+ profile = Path(tmp) / "lo-profile"
124
+ if not profile.exists():
125
+ (profile / "user").mkdir(parents=True)
126
+ (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE)
127
+ subprocess.run(
128
+ ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to",
129
+ "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)],
130
+ stdout=subprocess.DEVNULL,
131
+ stderr=subprocess.DEVNULL,
132
+ timeout=180,
133
+ check=False,
134
+ )
135
+ out = dest / (Path(path).stem + ".xlsx")
136
+ return out if out.exists() else Path(path)
137
+
138
+
139
+ def cell_value(v):
140
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
141
+ return round(float(v), 2)
142
+ if isinstance(v, dt.datetime):
143
+ return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0)
144
+ if isinstance(v, dt.time):
145
+ return v.strftime("%H:%M")
146
+ if isinstance(v, str):
147
+ try:
148
+ return round(float(v), 2)
149
+ except ValueError:
150
+ return v.strip()
151
+ return v
152
+
153
+
154
+ def time_of(v):
155
+ """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and
156
+ Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells."""
157
+ if isinstance(v, dt.time):
158
+ v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400
159
+ if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1:
160
+ return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M")
161
+ return None
162
+
163
+
164
+ def same_cell(a, b):
165
+ if isinstance(a, dt.time) is not isinstance(b, dt.time):
166
+ n = b if isinstance(a, dt.time) else a
167
+ if time_of(n) is not None: # a time against a plain day fraction
168
+ return time_of(a) == time_of(b)
169
+ a, b = cell_value(a), cell_value(b)
170
+ if a in (None, "") and b in (None, ""):
171
+ return True
172
+ return type(a) is type(b) and a == b
173
+
174
+
175
+ ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"}
176
+
177
+
178
+ def is_error(v):
179
+ return isinstance(v, str) and (v in ERRORS or v.startswith("Err:"))
180
+
181
+
182
+ def cells(rng):
183
+ if ":" not in rng:
184
+ return [rng]
185
+ from openpyxl.utils import range_boundaries, get_column_letter
186
+
187
+ c1, r1, c2, r2 = range_boundaries(rng)
188
+ return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)]
189
+
190
+
191
+ def load(path, tmp):
192
+ import openpyxl
193
+
194
+ return openpyxl.load_workbook(recalc(path, tmp), data_only=True)
195
+
196
+
197
+ def check_xlsx_range(check, tmp, cache):
198
+ sub = OUT / check["file"]
199
+ if not sub.is_file():
200
+ return False, f"missing output {check['file']}"
201
+ if sub not in cache:
202
+ cache[sub] = load(sub, tmp)
203
+ tgt = TESTS / check["target"]
204
+ if tgt not in cache:
205
+ cache[tgt] = load(tgt, tmp)
206
+ got, want = cache[sub], cache[tgt]
207
+ cached = None # the target's stored (Excel-computed) values, read only when Calc errs
208
+ for sheet, rng in check["ranges"]:
209
+ sheet = sheet or want.sheetnames[0]
210
+ if sheet not in got.sheetnames:
211
+ return False, f"sheet {sheet!r} missing"
212
+ for name in cells(rng):
213
+ w = want[sheet][name].value
214
+ if is_error(w):
215
+ # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4).
216
+ # The value Excel stored is the intended answer.
217
+ if cached is None:
218
+ import openpyxl
219
+
220
+ cached = openpyxl.load_workbook(tgt, data_only=True)
221
+ c = cached[sheet][name].value if sheet in cached.sheetnames else None
222
+ if c is not None and not is_error(c):
223
+ w = c
224
+ if not same_cell(w, got[sheet][name].value):
225
+ return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}"
226
+ return True, ""
227
+
228
+
229
+ def check_xlsx_cell(check, tmp, cache):
230
+ sub = OUT / check["file"]
231
+ if not sub.is_file():
232
+ return False, f"missing output {check['file']}"
233
+ if sub not in cache:
234
+ cache[sub] = load(sub, tmp)
235
+ wb = cache[sub]
236
+ if check["sheet"] not in wb.sheetnames:
237
+ return False, f"sheet {check['sheet']!r} missing"
238
+ got = wb[check["sheet"]][check["cell"]].value
239
+ want = check["value"]
240
+ if isinstance(want, (int, float)):
241
+ # alt_values: other accepted golds where the source admits more than one reading.
242
+ ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01))
243
+ for w in [want, *check.get("alt_values", [])])
244
+ else:
245
+ ok = norm_text(got) == norm_text(want)
246
+ return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}"
247
+
248
+
249
+ def text_of(path):
250
+ suffix = path.suffix.lower()
251
+ if suffix == ".docx":
252
+ import docx
253
+
254
+ d = docx.Document(path)
255
+ parts = [p.text for p in d.paragraphs]
256
+ for t in d.tables:
257
+ parts += [c.text for row in t.rows for c in row.cells]
258
+ return "\n".join(parts)
259
+ if suffix == ".pdf":
260
+ import pdfplumber
261
+
262
+ with pdfplumber.open(path) as pdf:
263
+ return "\n".join(page.extract_text() or "" for page in pdf.pages)
264
+ return path.read_text(errors="replace")
265
+
266
+
267
+ def check_file_contains(check, tmp, cache):
268
+ sub = OUT / check["file"]
269
+ if not sub.is_file():
270
+ return False, f"missing output {check['file']}"
271
+ text = text_of(sub)
272
+ hay = text if check.get("case_sensitive") else text.casefold()
273
+ for needle in check["needles"]:
274
+ n = needle if check.get("case_sensitive") else needle.casefold()
275
+ if n not in hay:
276
+ return False, f"{check['file']} lacks {needle!r}"
277
+ return True, ""
278
+
279
+
280
+ def main():
281
+ LOGS.mkdir(parents=True, exist_ok=True)
282
+ reward_path = LOGS / "reward.txt"
283
+ reward_path.write_text("0\n")
284
+ spec = json.loads((TESTS / "expected.json").read_text())
285
+ answers, details = {}, []
286
+ answer_file = OUT / "answer.json"
287
+ if answer_file.is_file():
288
+ try:
289
+ answers = json.loads(answer_file.read_text())
290
+ if not isinstance(answers, dict):
291
+ answers = {}
292
+ except json.JSONDecodeError:
293
+ answers = {}
294
+ tmp = tempfile.mkdtemp()
295
+ cache = {}
296
+ try:
297
+ for check in spec["checks"]:
298
+ try:
299
+ if check["type"] == "answer":
300
+ ok, why = check_answer(check, answers)
301
+ elif check["type"] == "xlsx_range":
302
+ ok, why = check_xlsx_range(check, tmp, cache)
303
+ elif check["type"] == "xlsx_cell":
304
+ ok, why = check_xlsx_cell(check, tmp, cache)
305
+ elif check["type"] == "file_contains":
306
+ ok, why = check_file_contains(check, tmp, cache)
307
+ elif check["type"] == "custom":
308
+ import importlib.util
309
+
310
+ spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py")
311
+ mod = importlib.util.module_from_spec(spec_)
312
+ spec_.loader.exec_module(mod)
313
+ ok, why = mod.check(check, OUT, TESTS)
314
+ else:
315
+ ok, why = False, f"unknown check type {check['type']}"
316
+ except Exception as exc: # a malformed submission fails the check, not the grader
317
+ ok, why = False, f"{type(exc).__name__}: {exc}"
318
+ details.append({"id": check["id"], "passed": ok, "detail": why})
319
+ finally:
320
+ shutil.rmtree(tmp, ignore_errors=True)
321
+ passed = sum(d["passed"] for d in details)
322
+ total = len(details)
323
+ reward = 1 if total and passed == total else 0
324
+ (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1))
325
+ reward_path.write_text(f"{reward}\n")
326
+ print(f"{passed}/{total} checks passed; reward {reward}")
327
+
328
+
329
+ if __name__ == "__main__":
330
+ sys.exit(main())
tasks/service-hr-certifications-41840/tests/replay.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline business-app client. Print usage with --help."""
2
+ import argparse
3
+ import copy
4
+ import fcntl
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+
10
+ def same(left, right):
11
+ return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False)
12
+
13
+
14
+ def apply(world, action):
15
+ if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}:
16
+ raise ValueError('expected op, app, id, fields')
17
+ op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields'))
18
+ if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields:
19
+ raise ValueError('unknown app, invalid id or empty fields')
20
+ collection = world[app]
21
+ if op == 'update' and key in collection:
22
+ collection[key].update(copy.deepcopy(fields))
23
+ elif op == 'create' and key not in collection:
24
+ collection[key] = copy.deepcopy(fields)
25
+ else:
26
+ raise ValueError(f'invalid {op} for {app}/{key}')
27
+
28
+
29
+ def load_actions(path):
30
+ if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000):
31
+ raise ValueError('invalid action log')
32
+ if not path.exists():
33
+ return []
34
+ return [json.loads(s) for s in path.read_text().splitlines() if s.strip()]
35
+
36
+
37
+ def main():
38
+ parser = argparse.ArgumentParser(description=__doc__)
39
+ parser.add_argument('op', choices=('apps','list','get','update','create'))
40
+ parser.add_argument('app', nargs='?')
41
+ parser.add_argument('id', nargs='?')
42
+ parser.add_argument('fields', nargs='?', type=json.loads)
43
+ args = parser.parse_args()
44
+ world = json.loads(Path(__file__).with_name('world.json').read_text())
45
+ out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs'))
46
+ out.mkdir(parents=True, exist_ok=True)
47
+ log = out/'actions.jsonl'
48
+ with (out/'.actions.lock').open('a') as lock:
49
+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
50
+ for event in load_actions(log):
51
+ apply(world,event)
52
+ if args.op=='apps':
53
+ value=sorted(world)
54
+ elif args.op=='list':
55
+ value=world[args.app]
56
+ elif args.op=='get':
57
+ value=world[args.app][args.id]
58
+ else:
59
+ event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields}
60
+ apply(world,event)
61
+ with log.open('a') as handle:
62
+ handle.write(json.dumps(event,allow_nan=False)+'\n')
63
+ value=world[args.app][args.id]
64
+ print(json.dumps(value,sort_keys=True,allow_nan=False))
65
+
66
+
67
+ if __name__=='__main__':
68
+ main()
tasks/service-hr-certifications-41840/tests/target.json ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "certs": {
3
+ "R14020": {
4
+ "course": "induction",
5
+ "expires_day": 398,
6
+ "person": "S37318",
7
+ "state": "enrolled"
8
+ },
9
+ "R14981": {
10
+ "course": "induction",
11
+ "expires_day": 411,
12
+ "person": "S83572",
13
+ "state": "deferred"
14
+ },
15
+ "R21547": {
16
+ "course": "induction",
17
+ "expires_day": 424,
18
+ "person": "S37724",
19
+ "state": "active"
20
+ },
21
+ "R34688": {
22
+ "course": "records",
23
+ "expires_day": 397,
24
+ "person": "S29462",
25
+ "state": "enrolled"
26
+ },
27
+ "R35432": {
28
+ "course": "records",
29
+ "expires_day": 395,
30
+ "person": "S18548",
31
+ "state": "enrolled"
32
+ },
33
+ "R69002": {
34
+ "course": "induction",
35
+ "expires_day": 422,
36
+ "person": "S78988",
37
+ "state": "active"
38
+ },
39
+ "R79833": {
40
+ "course": "records",
41
+ "expires_day": 430,
42
+ "person": "S98094",
43
+ "state": "retired"
44
+ },
45
+ "R83170": {
46
+ "course": "privacy",
47
+ "expires_day": 420,
48
+ "person": "S63123",
49
+ "state": "deferred"
50
+ }
51
+ },
52
+ "leave": {
53
+ "S18548": {
54
+ "available_day": 419
55
+ },
56
+ "S29462": {
57
+ "available_day": 400
58
+ },
59
+ "S37318": {
60
+ "available_day": 400
61
+ },
62
+ "S37724": {
63
+ "available_day": 419
64
+ },
65
+ "S63123": {
66
+ "available_day": 424
67
+ },
68
+ "S78988": {
69
+ "available_day": 417
70
+ },
71
+ "S83572": {
72
+ "available_day": 424
73
+ },
74
+ "S98094": {
75
+ "available_day": 417
76
+ }
77
+ },
78
+ "renewals": {
79
+ "renew-R14020": {
80
+ "course": "induction",
81
+ "person": "S37318",
82
+ "session": "renewal"
83
+ },
84
+ "renew-R34688": {
85
+ "course": "records",
86
+ "person": "S29462",
87
+ "session": "renewal"
88
+ },
89
+ "renew-R35432": {
90
+ "course": "records",
91
+ "person": "S18548",
92
+ "session": "renewal"
93
+ }
94
+ },
95
+ "sessions": {
96
+ "renewal": {
97
+ "seats": 0,
98
+ "start_day": 420
99
+ }
100
+ }
101
+ }
tasks/service-hr-certifications-41840/tests/test.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ mkdir -p /logs/verifier /workspace/outputs
4
+ exec python3 -B -I /tests/grade.py
tasks/service-hr-certifications-41840/tests/world.json ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "certs": {
3
+ "R14020": {
4
+ "course": "induction",
5
+ "expires_day": 398,
6
+ "person": "S37318",
7
+ "state": "active"
8
+ },
9
+ "R14981": {
10
+ "course": "induction",
11
+ "expires_day": 411,
12
+ "person": "S83572",
13
+ "state": "active"
14
+ },
15
+ "R21547": {
16
+ "course": "induction",
17
+ "expires_day": 424,
18
+ "person": "S37724",
19
+ "state": "active"
20
+ },
21
+ "R34688": {
22
+ "course": "records",
23
+ "expires_day": 397,
24
+ "person": "S29462",
25
+ "state": "active"
26
+ },
27
+ "R35432": {
28
+ "course": "records",
29
+ "expires_day": 395,
30
+ "person": "S18548",
31
+ "state": "active"
32
+ },
33
+ "R69002": {
34
+ "course": "induction",
35
+ "expires_day": 422,
36
+ "person": "S78988",
37
+ "state": "active"
38
+ },
39
+ "R79833": {
40
+ "course": "records",
41
+ "expires_day": 430,
42
+ "person": "S98094",
43
+ "state": "retired"
44
+ },
45
+ "R83170": {
46
+ "course": "privacy",
47
+ "expires_day": 420,
48
+ "person": "S63123",
49
+ "state": "active"
50
+ }
51
+ },
52
+ "leave": {
53
+ "S18548": {
54
+ "available_day": 419
55
+ },
56
+ "S29462": {
57
+ "available_day": 400
58
+ },
59
+ "S37318": {
60
+ "available_day": 400
61
+ },
62
+ "S37724": {
63
+ "available_day": 419
64
+ },
65
+ "S63123": {
66
+ "available_day": 424
67
+ },
68
+ "S78988": {
69
+ "available_day": 417
70
+ },
71
+ "S83572": {
72
+ "available_day": 424
73
+ },
74
+ "S98094": {
75
+ "available_day": 417
76
+ }
77
+ },
78
+ "renewals": {},
79
+ "sessions": {
80
+ "renewal": {
81
+ "seats": 3,
82
+ "start_day": 420
83
+ }
84
+ }
85
+ }
tasks/service-hr-certifications-41840/tests/world_check.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay submitted mutations from the private verifier's initial state."""
2
+ from types import ModuleType
3
+ import json
4
+
5
+
6
+ def check(spec, outputs, tests):
7
+ replay = ModuleType('workflow_replay')
8
+ exec(compile((tests/'replay.py').read_bytes(), 'replay.py', 'exec'), replay.__dict__)
9
+ world = json.loads((tests/'world.json').read_text())
10
+ target = json.loads((tests/'target.json').read_text())
11
+ # Only fields whose starting and expected values differ may be changed. Attempts
12
+ # to temporarily alter a protected field fail even when a later write restores it.
13
+ allowed = {
14
+ (app,key): {field for field,value in doc.items()
15
+ if field not in world[app].get(key,{}) or not replay.same(world[app][key][field],value)}
16
+ for app,records in target.items() for key,doc in records.items()
17
+ }
18
+ actions = replay.load_actions(outputs/'actions.jsonl')
19
+ for event in actions:
20
+ replay.apply(world,event)
21
+ touched = set(event['fields'])
22
+ if not touched <= allowed.get((event['app'],event['id']),set()):
23
+ return False,'protected field or record write'
24
+ if not replay.same(world,target):
25
+ return False,'required business outcomes incomplete'
26
+ return True,''
tasks/service-hr-certifications-41840/validation/openenv.json ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "profile": "harbor-semantic-v1",
3
+ "reward_key": "reward",
4
+ "reward": {
5
+ "range": [
6
+ 0,
7
+ 1
8
+ ],
9
+ "oracle_tolerance": 0,
10
+ "floor_margin": 0.1
11
+ },
12
+ "resources": {
13
+ "cpu": 1,
14
+ "memory_mb": 4096,
15
+ "disk_mb": 10240,
16
+ "episode_timeout_s": 1800
17
+ },
18
+ "types": {
19
+ "tags": [
20
+ "knowledge-work",
21
+ "cross-app-workflows",
22
+ "conditional-execution",
23
+ "protected-state",
24
+ "hr"
25
+ ]
26
+ },
27
+ "requires_credentials": false
28
+ }
tasks/service-hr-certifications-41843/environment/inputs/apps.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline business-app client. Print usage with --help."""
2
+ import argparse
3
+ import copy
4
+ import fcntl
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+
10
+ def same(left, right):
11
+ return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False)
12
+
13
+
14
+ def apply(world, action):
15
+ if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}:
16
+ raise ValueError('expected op, app, id, fields')
17
+ op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields'))
18
+ if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields:
19
+ raise ValueError('unknown app, invalid id or empty fields')
20
+ collection = world[app]
21
+ if op == 'update' and key in collection:
22
+ collection[key].update(copy.deepcopy(fields))
23
+ elif op == 'create' and key not in collection:
24
+ collection[key] = copy.deepcopy(fields)
25
+ else:
26
+ raise ValueError(f'invalid {op} for {app}/{key}')
27
+
28
+
29
+ def load_actions(path):
30
+ if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000):
31
+ raise ValueError('invalid action log')
32
+ if not path.exists():
33
+ return []
34
+ return [json.loads(s) for s in path.read_text().splitlines() if s.strip()]
35
+
36
+
37
+ def main():
38
+ parser = argparse.ArgumentParser(description=__doc__)
39
+ parser.add_argument('op', choices=('apps','list','get','update','create'))
40
+ parser.add_argument('app', nargs='?')
41
+ parser.add_argument('id', nargs='?')
42
+ parser.add_argument('fields', nargs='?', type=json.loads)
43
+ args = parser.parse_args()
44
+ world = json.loads(Path(__file__).with_name('world.json').read_text())
45
+ out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs'))
46
+ out.mkdir(parents=True, exist_ok=True)
47
+ log = out/'actions.jsonl'
48
+ with (out/'.actions.lock').open('a') as lock:
49
+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
50
+ for event in load_actions(log):
51
+ apply(world,event)
52
+ if args.op=='apps':
53
+ value=sorted(world)
54
+ elif args.op=='list':
55
+ value=world[args.app]
56
+ elif args.op=='get':
57
+ value=world[args.app][args.id]
58
+ else:
59
+ event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields}
60
+ apply(world,event)
61
+ with log.open('a') as handle:
62
+ handle.write(json.dumps(event,allow_nan=False)+'\n')
63
+ value=world[args.app][args.id]
64
+ print(json.dumps(value,sort_keys=True,allow_nan=False))
65
+
66
+
67
+ if __name__=='__main__':
68
+ main()
tasks/service-hr-certifications-41843/environment/inputs/world.json ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "certs": {
3
+ "R16980": {
4
+ "course": "privacy",
5
+ "expires_day": 293,
6
+ "person": "S63970",
7
+ "state": "active"
8
+ },
9
+ "R30399": {
10
+ "course": "privacy",
11
+ "expires_day": 269,
12
+ "person": "S56563",
13
+ "state": "active"
14
+ },
15
+ "R33656": {
16
+ "course": "induction",
17
+ "expires_day": 304,
18
+ "person": "S41205",
19
+ "state": "active"
20
+ },
21
+ "R35602": {
22
+ "course": "privacy",
23
+ "expires_day": 279,
24
+ "person": "S40135",
25
+ "state": "active"
26
+ },
27
+ "R35640": {
28
+ "course": "records",
29
+ "expires_day": 275,
30
+ "person": "S92541",
31
+ "state": "active"
32
+ },
33
+ "R46749": {
34
+ "course": "privacy",
35
+ "expires_day": 293,
36
+ "person": "S96230",
37
+ "state": "active"
38
+ },
39
+ "R47822": {
40
+ "course": "induction",
41
+ "expires_day": 274,
42
+ "person": "S83162",
43
+ "state": "active"
44
+ },
45
+ "R59901": {
46
+ "course": "privacy",
47
+ "expires_day": 295,
48
+ "person": "S73569",
49
+ "state": "active"
50
+ },
51
+ "R66677": {
52
+ "course": "records",
53
+ "expires_day": 286,
54
+ "person": "S93638",
55
+ "state": "retired"
56
+ },
57
+ "R69349": {
58
+ "course": "records",
59
+ "expires_day": 274,
60
+ "person": "S96936",
61
+ "state": "active"
62
+ }
63
+ },
64
+ "leave": {
65
+ "S40135": {
66
+ "available_day": 300
67
+ },
68
+ "S41205": {
69
+ "available_day": 286
70
+ },
71
+ "S56563": {
72
+ "available_day": 295
73
+ },
74
+ "S63970": {
75
+ "available_day": 286
76
+ },
77
+ "S73569": {
78
+ "available_day": 300
79
+ },
80
+ "S83162": {
81
+ "available_day": 295
82
+ },
83
+ "S92541": {
84
+ "available_day": 278
85
+ },
86
+ "S93638": {
87
+ "available_day": 300
88
+ },
89
+ "S96230": {
90
+ "available_day": 293
91
+ },
92
+ "S96936": {
93
+ "available_day": 278
94
+ }
95
+ },
96
+ "renewals": {},
97
+ "sessions": {
98
+ "renewal": {
99
+ "seats": 3,
100
+ "start_day": 296
101
+ }
102
+ }
103
+ }
tasks/service-hr-certifications-41843/instruction.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Allocate remaining places in the renewal session. Process active certs expiring on or before the session start day in ascending expires_day order, breaking ties by ascending cert ID. If the person's available_day is after the session starts, set state to deferred. Otherwise consume one available seat and mark enrolled, or mark waitlisted if no seats remain. For each enrolment create renew-<cert ID> in renewals with person, course and session set to renewal. Update the session's remaining seats.
2
+
3
+ Use the offline app client at `/workspace/inputs/apps.py`. Call it with python3. Run
4
+ `apps` to discover apps, `list APP` to see its records, or `get APP ID` for one record.
5
+ Write with `update APP ID '{"field":"value"}'` or `create APP ID '{"field":"value"}'`.
6
+ The client records successful writes in `/workspace/outputs/actions.jsonl`.
7
+ Apply exactly the required changes. Other records and fields must remain untouched,
8
+ including temporary changes. Actions take effect in the local simulation only.
9
+
10
+ ## Deliverable
11
+
12
+ Work in `/workspace`. Input files are under `/workspace/inputs/`. Put every deliverable in
13
+ `/workspace/outputs/`; only that directory is graded. Leave the app action log in the outputs directory.
tasks/service-hr-certifications-41843/solution/files/actions.jsonl ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"app": "certs", "fields": {"state": "enrolled"}, "id": "R69349", "op": "update"}
2
+ {"app": "certs", "fields": {"state": "waitlisted"}, "id": "R35640", "op": "update"}
3
+ {"app": "certs", "fields": {"state": "deferred"}, "id": "R59901", "op": "update"}
4
+ {"app": "certs", "fields": {"state": "waitlisted"}, "id": "R46749", "op": "update"}
5
+ {"app": "certs", "fields": {"state": "deferred"}, "id": "R35602", "op": "update"}
6
+ {"app": "certs", "fields": {"state": "enrolled"}, "id": "R47822", "op": "update"}
7
+ {"app": "certs", "fields": {"state": "enrolled"}, "id": "R30399", "op": "update"}
8
+ {"app": "certs", "fields": {"state": "waitlisted"}, "id": "R16980", "op": "update"}
9
+ {"app": "renewals", "fields": {"course": "privacy", "person": "S56563", "session": "renewal"}, "id": "renew-R30399", "op": "create"}
10
+ {"app": "renewals", "fields": {"course": "induction", "person": "S83162", "session": "renewal"}, "id": "renew-R47822", "op": "create"}
11
+ {"app": "renewals", "fields": {"course": "records", "person": "S96936", "session": "renewal"}, "id": "renew-R69349", "op": "create"}
12
+ {"app": "sessions", "fields": {"seats": 0}, "id": "renewal", "op": "update"}
tasks/service-hr-certifications-41843/solution/solve.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ mkdir -p /workspace/outputs
4
+ cp -R /solution/files/. /workspace/outputs/
tasks/service-hr-certifications-41843/task.toml ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.3"
2
+
3
+ [task]
4
+ name = "apex-gap/service-hr-certifications-41843"
5
+
6
+ [metadata.apex_gap]
7
+ capability_tags = ["cross-app-workflows", "conditional-execution", "protected-state", "hr"]
8
+ dataset = "Original simulated workflows"
9
+ job = "hr"
10
+ seed = 41843
11
+ source = "local/original-automation-workflows"
12
+ source_revision = "1"
13
+ source_split = "synthetic"
14
+ source_task_id = "service-hr-certifications-41843"
15
+ template_family = "automation:service-hr-certifications"
16
+ workflow_template = "service-hr-certifications"
17
+
18
+ [metadata.openenv_hf_sandbox]
19
+ variant = "apex-gap-hfsandbox-v1"
20
+ task_modified_for_hf_sandbox = true
21
+ network_enabled = true
22
+
23
+ [environment]
24
+ docker_image = "ghcr.io/younesbelkada/apex@sha256:24969c952247033023872f87161a16e067003469506be63783bbaa5d96926bdf"
25
+ workdir = "/workspace"
26
+ cpus = 1
27
+ memory_mb = 4096
28
+ build_timeout_sec = 600
29
+ network_mode = "public"
30
+
31
+ [agent]
32
+ timeout_sec = 1800
33
+ network_mode = "public"
34
+
35
+ [verifier]
36
+ timeout_sec = 600
37
+ network_mode = "public"
38
+ environment_mode = "separate"
39
+
40
+ [verifier.environment]
41
+ network_mode = "public"
42
+ cpus = 1
43
+ memory_mb = 4096
44
+
45
+ [[artifacts]]
46
+ source = "/workspace/outputs"
tasks/service-hr-certifications-41843/tests/expected.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "checks": [
3
+ {
4
+ "id": "business-outcomes",
5
+ "type": "custom",
6
+ "module": "world_check"
7
+ }
8
+ ]
9
+ }
tasks/service-hr-certifications-41843/tests/grade.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic grader shared by converted knowledge-work tasks.
2
+
3
+ Runs inside the separate verifier sandbox. Reads /tests/expected.json, inspects the
4
+ submitted /workspace/outputs tree and writes a binary reward plus per-check details.
5
+ No model calls and no network.
6
+
7
+ expected.json: {"checks": [{"id": ..., "type": ..., ...}, ...]}
8
+ Check types:
9
+ answer field of outputs/answer.json; kind = number|text|choice|date|bool|list
10
+ xlsx_range recalculated outputs/<file> vs tests/<target> over sheet!range (SpreadsheetBench rules)
11
+ xlsx_cell recalculated outputs/<file> sheet!cell vs value with tolerance (optional alt_values)
12
+ file_contains outputs/<file> text (docx/pdf/ics/eml/txt) must contain every needle
13
+ custom tests/<module>.py defines check(spec, outputs_dir, tests_dir) -> (bool, str)
14
+ """
15
+
16
+ import datetime as dt
17
+ import json
18
+ import re
19
+ import shutil
20
+ import subprocess
21
+ import sys
22
+ import tempfile
23
+ import unicodedata
24
+ from pathlib import Path
25
+
26
+ OUT = Path("/workspace/outputs")
27
+ TESTS = Path("/tests")
28
+ LOGS = Path("/logs/verifier")
29
+
30
+
31
+ def norm_text(v):
32
+ v = unicodedata.normalize("NFKC", str(v)).casefold()
33
+ v = re.sub(r"[‘’“”]", "'", v)
34
+ v = re.sub(r"[^\w%.$/-]+", " ", v)
35
+ return " ".join(v.split()).strip(" .")
36
+
37
+
38
+ def to_number(v):
39
+ if isinstance(v, bool):
40
+ raise ValueError("bool")
41
+ if isinstance(v, (int, float)):
42
+ return float(v)
43
+ s = str(v).strip().replace(",", "").replace("$", "").replace("−", "-")
44
+ neg = s.startswith("(") and s.endswith(")")
45
+ s = s.strip("()").strip()
46
+ pct = s.endswith("%")
47
+ s = s.rstrip("%").strip()
48
+ s = re.sub(r"\s*(usd|dollars|million|billion|thousand|m|bn|k)$", "", s, flags=re.I)
49
+ x = float(s)
50
+ x = -x if neg else x
51
+ return x / 100 if pct else x
52
+
53
+
54
+ def number_ok(got, want, rel, abs_):
55
+ try:
56
+ g = to_number(got)
57
+ except (TypeError, ValueError):
58
+ return False
59
+ w = float(want)
60
+ tol = max(abs_, rel * abs(w))
61
+ # "12.5%" may mean the ratio 0.125 or the percent number 12.5; the gold fixes which.
62
+ candidates = [g, g * 100] if isinstance(got, str) and got.strip().endswith("%") else [g]
63
+ return any(abs(c - w) <= tol for c in candidates)
64
+
65
+
66
+ def parse_date(v):
67
+ if isinstance(v, (dt.date, dt.datetime)):
68
+ return v if isinstance(v, dt.date) else v.date()
69
+ s = str(v).strip()
70
+ for fmt in ("%Y-%m-%d", "%m/%d/%Y", "%m/%d/%y", "%d %B %Y", "%B %d, %Y", "%b %d, %Y", "%Y/%m/%d"):
71
+ try:
72
+ return dt.datetime.strptime(s, fmt).date()
73
+ except ValueError:
74
+ continue
75
+ raise ValueError(s)
76
+
77
+
78
+ def check_answer(check, answers):
79
+ key = check["field"]
80
+ if key not in answers:
81
+ return False, f"missing field {key!r}"
82
+ got, want, kind = answers[key], check["value"], check.get("kind", "text")
83
+ if kind == "number":
84
+ ok = number_ok(got, want, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01))
85
+ if not ok and check.get("percent_either"):
86
+ ok = number_ok(got, want * 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) * 100) or (
87
+ number_ok(got, want / 100, check.get("rel_tol", 0.005), check.get("abs_tol", 0.01) / 100)
88
+ )
89
+ elif kind == "date":
90
+ try:
91
+ ok = parse_date(got) == parse_date(want)
92
+ except ValueError:
93
+ ok = False
94
+ elif kind == "bool":
95
+ g = norm_text(got)
96
+ ok = g in {"yes", "true"} if want else g in {"no", "false"}
97
+ elif kind == "choice":
98
+ ok = norm_text(got) == norm_text(want)
99
+ elif kind == "list":
100
+ if not isinstance(got, list):
101
+ return False, f"{key}: expected a JSON list"
102
+ # Filenames may be given with a directory prefix; compare base names.
103
+ base = lambda x: norm_text(str(x).replace("\\", "/").rsplit("/", 1)[-1])
104
+ ok = sorted(base(x) for x in got) == sorted(base(x) for x in want)
105
+ else:
106
+ accepted = check.get("accept", [want])
107
+ ok = norm_text(got) in {norm_text(a) for a in accepted}
108
+ return ok, "" if ok else f"{key}: got {got!r}"
109
+
110
+
111
+ # LibreOffice keeps cached formula values on load unless told otherwise; force a full recalculation.
112
+ RECALC_PROFILE = """<?xml version="1.0" encoding="UTF-8"?>
113
+ <oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema">
114
+ <item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="OOXMLRecalcMode" oor:op="fuse"><value>0</value></prop></item>
115
+ <item oor:path="/org.openoffice.Office.Calc/Formula/Load"><prop oor:name="ODFRecalcMode" oor:op="fuse"><value>0</value></prop></item>
116
+ </oor:items>
117
+ """
118
+
119
+
120
+ def recalc(path, tmp):
121
+ dest = Path(tmp) / f"recalc-{len(list(Path(tmp).glob('recalc-*')))}"
122
+ dest.mkdir()
123
+ profile = Path(tmp) / "lo-profile"
124
+ if not profile.exists():
125
+ (profile / "user").mkdir(parents=True)
126
+ (profile / "user" / "registrymodifications.xcu").write_text(RECALC_PROFILE)
127
+ subprocess.run(
128
+ ["soffice", f"-env:UserInstallation=file://{profile}", "--headless", "--calc", "--convert-to",
129
+ "xlsx:Calc MS Excel 2007 XML", "--outdir", str(dest), str(path)],
130
+ stdout=subprocess.DEVNULL,
131
+ stderr=subprocess.DEVNULL,
132
+ timeout=180,
133
+ check=False,
134
+ )
135
+ out = dest / (Path(path).stem + ".xlsx")
136
+ return out if out.exists() else Path(path)
137
+
138
+
139
+ def cell_value(v):
140
+ if isinstance(v, (int, float)) and not isinstance(v, bool):
141
+ return round(float(v), 2)
142
+ if isinstance(v, dt.datetime):
143
+ return round((v - dt.datetime(1899, 12, 30)).total_seconds() / 86400.0, 0)
144
+ if isinstance(v, dt.time):
145
+ return v.strftime("%H:%M")
146
+ if isinstance(v, str):
147
+ try:
148
+ return round(float(v), 2)
149
+ except ValueError:
150
+ return v.strip()
151
+ return v
152
+
153
+
154
+ def time_of(v):
155
+ """A time or a day fraction in [0, 1) as HH:MM, rounded to the nearest second first. Calc and
156
+ Excel store a time as that fraction; openpyxl returns a time only for time-formatted cells."""
157
+ if isinstance(v, dt.time):
158
+ v = (v.hour * 3600 + v.minute * 60 + v.second + v.microsecond / 1e6) / 86400
159
+ if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= v < 1:
160
+ return (dt.datetime(1899, 12, 30) + dt.timedelta(seconds=round(v * 86400))).strftime("%H:%M")
161
+ return None
162
+
163
+
164
+ def same_cell(a, b):
165
+ if isinstance(a, dt.time) is not isinstance(b, dt.time):
166
+ n = b if isinstance(a, dt.time) else a
167
+ if time_of(n) is not None: # a time against a plain day fraction
168
+ return time_of(a) == time_of(b)
169
+ a, b = cell_value(a), cell_value(b)
170
+ if a in (None, "") and b in (None, ""):
171
+ return True
172
+ return type(a) is type(b) and a == b
173
+
174
+
175
+ ERRORS = {"#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"}
176
+
177
+
178
+ def is_error(v):
179
+ return isinstance(v, str) and (v in ERRORS or v.startswith("Err:"))
180
+
181
+
182
+ def cells(rng):
183
+ if ":" not in rng:
184
+ return [rng]
185
+ from openpyxl.utils import range_boundaries, get_column_letter
186
+
187
+ c1, r1, c2, r2 = range_boundaries(rng)
188
+ return [f"{get_column_letter(c)}{r}" for r in range(r1, r2 + 1) for c in range(c1, c2 + 1)]
189
+
190
+
191
+ def load(path, tmp):
192
+ import openpyxl
193
+
194
+ return openpyxl.load_workbook(recalc(path, tmp), data_only=True)
195
+
196
+
197
+ def check_xlsx_range(check, tmp, cache):
198
+ sub = OUT / check["file"]
199
+ if not sub.is_file():
200
+ return False, f"missing output {check['file']}"
201
+ if sub not in cache:
202
+ cache[sub] = load(sub, tmp)
203
+ tgt = TESTS / check["target"]
204
+ if tgt not in cache:
205
+ cache[tgt] = load(tgt, tmp)
206
+ got, want = cache[sub], cache[tgt]
207
+ cached = None # the target's stored (Excel-computed) values, read only when Calc errs
208
+ for sheet, rng in check["ranges"]:
209
+ sheet = sheet or want.sheetnames[0]
210
+ if sheet not in got.sheetnames:
211
+ return False, f"sheet {sheet!r} missing"
212
+ for name in cells(rng):
213
+ w = want[sheet][name].value
214
+ if is_error(w):
215
+ # LibreOffice could not evaluate the gold formula (e.g. XLOOKUP, FILTER in Calc 7.4).
216
+ # The value Excel stored is the intended answer.
217
+ if cached is None:
218
+ import openpyxl
219
+
220
+ cached = openpyxl.load_workbook(tgt, data_only=True)
221
+ c = cached[sheet][name].value if sheet in cached.sheetnames else None
222
+ if c is not None and not is_error(c):
223
+ w = c
224
+ if not same_cell(w, got[sheet][name].value):
225
+ return False, f"{sheet}!{name}: want {w!r} got {got[sheet][name].value!r}"
226
+ return True, ""
227
+
228
+
229
+ def check_xlsx_cell(check, tmp, cache):
230
+ sub = OUT / check["file"]
231
+ if not sub.is_file():
232
+ return False, f"missing output {check['file']}"
233
+ if sub not in cache:
234
+ cache[sub] = load(sub, tmp)
235
+ wb = cache[sub]
236
+ if check["sheet"] not in wb.sheetnames:
237
+ return False, f"sheet {check['sheet']!r} missing"
238
+ got = wb[check["sheet"]][check["cell"]].value
239
+ want = check["value"]
240
+ if isinstance(want, (int, float)):
241
+ # alt_values: other accepted golds where the source admits more than one reading.
242
+ ok = got is not None and any(number_ok(got, w, check.get("rel_tol", 0.0), check.get("abs_tol", 0.01))
243
+ for w in [want, *check.get("alt_values", [])])
244
+ else:
245
+ ok = norm_text(got) == norm_text(want)
246
+ return ok, "" if ok else f"{check['sheet']}!{check['cell']}: want {want!r} got {got!r}"
247
+
248
+
249
+ def text_of(path):
250
+ suffix = path.suffix.lower()
251
+ if suffix == ".docx":
252
+ import docx
253
+
254
+ d = docx.Document(path)
255
+ parts = [p.text for p in d.paragraphs]
256
+ for t in d.tables:
257
+ parts += [c.text for row in t.rows for c in row.cells]
258
+ return "\n".join(parts)
259
+ if suffix == ".pdf":
260
+ import pdfplumber
261
+
262
+ with pdfplumber.open(path) as pdf:
263
+ return "\n".join(page.extract_text() or "" for page in pdf.pages)
264
+ return path.read_text(errors="replace")
265
+
266
+
267
+ def check_file_contains(check, tmp, cache):
268
+ sub = OUT / check["file"]
269
+ if not sub.is_file():
270
+ return False, f"missing output {check['file']}"
271
+ text = text_of(sub)
272
+ hay = text if check.get("case_sensitive") else text.casefold()
273
+ for needle in check["needles"]:
274
+ n = needle if check.get("case_sensitive") else needle.casefold()
275
+ if n not in hay:
276
+ return False, f"{check['file']} lacks {needle!r}"
277
+ return True, ""
278
+
279
+
280
+ def main():
281
+ LOGS.mkdir(parents=True, exist_ok=True)
282
+ reward_path = LOGS / "reward.txt"
283
+ reward_path.write_text("0\n")
284
+ spec = json.loads((TESTS / "expected.json").read_text())
285
+ answers, details = {}, []
286
+ answer_file = OUT / "answer.json"
287
+ if answer_file.is_file():
288
+ try:
289
+ answers = json.loads(answer_file.read_text())
290
+ if not isinstance(answers, dict):
291
+ answers = {}
292
+ except json.JSONDecodeError:
293
+ answers = {}
294
+ tmp = tempfile.mkdtemp()
295
+ cache = {}
296
+ try:
297
+ for check in spec["checks"]:
298
+ try:
299
+ if check["type"] == "answer":
300
+ ok, why = check_answer(check, answers)
301
+ elif check["type"] == "xlsx_range":
302
+ ok, why = check_xlsx_range(check, tmp, cache)
303
+ elif check["type"] == "xlsx_cell":
304
+ ok, why = check_xlsx_cell(check, tmp, cache)
305
+ elif check["type"] == "file_contains":
306
+ ok, why = check_file_contains(check, tmp, cache)
307
+ elif check["type"] == "custom":
308
+ import importlib.util
309
+
310
+ spec_ = importlib.util.spec_from_file_location("custom_check", TESTS / f"{check['module']}.py")
311
+ mod = importlib.util.module_from_spec(spec_)
312
+ spec_.loader.exec_module(mod)
313
+ ok, why = mod.check(check, OUT, TESTS)
314
+ else:
315
+ ok, why = False, f"unknown check type {check['type']}"
316
+ except Exception as exc: # a malformed submission fails the check, not the grader
317
+ ok, why = False, f"{type(exc).__name__}: {exc}"
318
+ details.append({"id": check["id"], "passed": ok, "detail": why})
319
+ finally:
320
+ shutil.rmtree(tmp, ignore_errors=True)
321
+ passed = sum(d["passed"] for d in details)
322
+ total = len(details)
323
+ reward = 1 if total and passed == total else 0
324
+ (LOGS / "details.json").write_text(json.dumps({"passed": passed, "total": total, "checks": details}, indent=1))
325
+ reward_path.write_text(f"{reward}\n")
326
+ print(f"{passed}/{total} checks passed; reward {reward}")
327
+
328
+
329
+ if __name__ == "__main__":
330
+ sys.exit(main())
tasks/service-hr-certifications-41843/tests/replay.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline business-app client. Print usage with --help."""
2
+ import argparse
3
+ import copy
4
+ import fcntl
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+
10
+ def same(left, right):
11
+ return json.dumps(left, sort_keys=True, allow_nan=False) == json.dumps(right, sort_keys=True, allow_nan=False)
12
+
13
+
14
+ def apply(world, action):
15
+ if not isinstance(action, dict) or action.keys() != {'op', 'app', 'id', 'fields'}:
16
+ raise ValueError('expected op, app, id, fields')
17
+ op, app, key, fields = (action[k] for k in ('op', 'app', 'id', 'fields'))
18
+ if app not in world or not isinstance(key, str) or not key or not isinstance(fields, dict) or not fields:
19
+ raise ValueError('unknown app, invalid id or empty fields')
20
+ collection = world[app]
21
+ if op == 'update' and key in collection:
22
+ collection[key].update(copy.deepcopy(fields))
23
+ elif op == 'create' and key not in collection:
24
+ collection[key] = copy.deepcopy(fields)
25
+ else:
26
+ raise ValueError(f'invalid {op} for {app}/{key}')
27
+
28
+
29
+ def load_actions(path):
30
+ if path.is_symlink() or (path.is_file() and path.stat().st_size > 2_000_000):
31
+ raise ValueError('invalid action log')
32
+ if not path.exists():
33
+ return []
34
+ return [json.loads(s) for s in path.read_text().splitlines() if s.strip()]
35
+
36
+
37
+ def main():
38
+ parser = argparse.ArgumentParser(description=__doc__)
39
+ parser.add_argument('op', choices=('apps','list','get','update','create'))
40
+ parser.add_argument('app', nargs='?')
41
+ parser.add_argument('id', nargs='?')
42
+ parser.add_argument('fields', nargs='?', type=json.loads)
43
+ args = parser.parse_args()
44
+ world = json.loads(Path(__file__).with_name('world.json').read_text())
45
+ out = Path(os.environ.get('WORKFLOW_OUTPUT_DIR', '/workspace/outputs'))
46
+ out.mkdir(parents=True, exist_ok=True)
47
+ log = out/'actions.jsonl'
48
+ with (out/'.actions.lock').open('a') as lock:
49
+ fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
50
+ for event in load_actions(log):
51
+ apply(world,event)
52
+ if args.op=='apps':
53
+ value=sorted(world)
54
+ elif args.op=='list':
55
+ value=world[args.app]
56
+ elif args.op=='get':
57
+ value=world[args.app][args.id]
58
+ else:
59
+ event={'op':args.op, 'app':args.app, 'id':args.id, 'fields':args.fields}
60
+ apply(world,event)
61
+ with log.open('a') as handle:
62
+ handle.write(json.dumps(event,allow_nan=False)+'\n')
63
+ value=world[args.app][args.id]
64
+ print(json.dumps(value,sort_keys=True,allow_nan=False))
65
+
66
+
67
+ if __name__=='__main__':
68
+ main()
tasks/service-hr-certifications-41843/tests/target.json ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "certs": {
3
+ "R16980": {
4
+ "course": "privacy",
5
+ "expires_day": 293,
6
+ "person": "S63970",
7
+ "state": "waitlisted"
8
+ },
9
+ "R30399": {
10
+ "course": "privacy",
11
+ "expires_day": 269,
12
+ "person": "S56563",
13
+ "state": "enrolled"
14
+ },
15
+ "R33656": {
16
+ "course": "induction",
17
+ "expires_day": 304,
18
+ "person": "S41205",
19
+ "state": "active"
20
+ },
21
+ "R35602": {
22
+ "course": "privacy",
23
+ "expires_day": 279,
24
+ "person": "S40135",
25
+ "state": "deferred"
26
+ },
27
+ "R35640": {
28
+ "course": "records",
29
+ "expires_day": 275,
30
+ "person": "S92541",
31
+ "state": "waitlisted"
32
+ },
33
+ "R46749": {
34
+ "course": "privacy",
35
+ "expires_day": 293,
36
+ "person": "S96230",
37
+ "state": "waitlisted"
38
+ },
39
+ "R47822": {
40
+ "course": "induction",
41
+ "expires_day": 274,
42
+ "person": "S83162",
43
+ "state": "enrolled"
44
+ },
45
+ "R59901": {
46
+ "course": "privacy",
47
+ "expires_day": 295,
48
+ "person": "S73569",
49
+ "state": "deferred"
50
+ },
51
+ "R66677": {
52
+ "course": "records",
53
+ "expires_day": 286,
54
+ "person": "S93638",
55
+ "state": "retired"
56
+ },
57
+ "R69349": {
58
+ "course": "records",
59
+ "expires_day": 274,
60
+ "person": "S96936",
61
+ "state": "enrolled"
62
+ }
63
+ },
64
+ "leave": {
65
+ "S40135": {
66
+ "available_day": 300
67
+ },
68
+ "S41205": {
69
+ "available_day": 286
70
+ },
71
+ "S56563": {
72
+ "available_day": 295
73
+ },
74
+ "S63970": {
75
+ "available_day": 286
76
+ },
77
+ "S73569": {
78
+ "available_day": 300
79
+ },
80
+ "S83162": {
81
+ "available_day": 295
82
+ },
83
+ "S92541": {
84
+ "available_day": 278
85
+ },
86
+ "S93638": {
87
+ "available_day": 300
88
+ },
89
+ "S96230": {
90
+ "available_day": 293
91
+ },
92
+ "S96936": {
93
+ "available_day": 278
94
+ }
95
+ },
96
+ "renewals": {
97
+ "renew-R30399": {
98
+ "course": "privacy",
99
+ "person": "S56563",
100
+ "session": "renewal"
101
+ },
102
+ "renew-R47822": {
103
+ "course": "induction",
104
+ "person": "S83162",
105
+ "session": "renewal"
106
+ },
107
+ "renew-R69349": {
108
+ "course": "records",
109
+ "person": "S96936",
110
+ "session": "renewal"
111
+ }
112
+ },
113
+ "sessions": {
114
+ "renewal": {
115
+ "seats": 0,
116
+ "start_day": 296
117
+ }
118
+ }
119
+ }
tasks/service-hr-certifications-41843/tests/test.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/sh
2
+ set -eu
3
+ mkdir -p /logs/verifier /workspace/outputs
4
+ exec python3 -B -I /tests/grade.py
tasks/service-hr-certifications-41843/tests/world.json ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "certs": {
3
+ "R16980": {
4
+ "course": "privacy",
5
+ "expires_day": 293,
6
+ "person": "S63970",
7
+ "state": "active"
8
+ },
9
+ "R30399": {
10
+ "course": "privacy",
11
+ "expires_day": 269,
12
+ "person": "S56563",
13
+ "state": "active"
14
+ },
15
+ "R33656": {
16
+ "course": "induction",
17
+ "expires_day": 304,
18
+ "person": "S41205",
19
+ "state": "active"
20
+ },
21
+ "R35602": {
22
+ "course": "privacy",
23
+ "expires_day": 279,
24
+ "person": "S40135",
25
+ "state": "active"
26
+ },
27
+ "R35640": {
28
+ "course": "records",
29
+ "expires_day": 275,
30
+ "person": "S92541",
31
+ "state": "active"
32
+ },
33
+ "R46749": {
34
+ "course": "privacy",
35
+ "expires_day": 293,
36
+ "person": "S96230",
37
+ "state": "active"
38
+ },
39
+ "R47822": {
40
+ "course": "induction",
41
+ "expires_day": 274,
42
+ "person": "S83162",
43
+ "state": "active"
44
+ },
45
+ "R59901": {
46
+ "course": "privacy",
47
+ "expires_day": 295,
48
+ "person": "S73569",
49
+ "state": "active"
50
+ },
51
+ "R66677": {
52
+ "course": "records",
53
+ "expires_day": 286,
54
+ "person": "S93638",
55
+ "state": "retired"
56
+ },
57
+ "R69349": {
58
+ "course": "records",
59
+ "expires_day": 274,
60
+ "person": "S96936",
61
+ "state": "active"
62
+ }
63
+ },
64
+ "leave": {
65
+ "S40135": {
66
+ "available_day": 300
67
+ },
68
+ "S41205": {
69
+ "available_day": 286
70
+ },
71
+ "S56563": {
72
+ "available_day": 295
73
+ },
74
+ "S63970": {
75
+ "available_day": 286
76
+ },
77
+ "S73569": {
78
+ "available_day": 300
79
+ },
80
+ "S83162": {
81
+ "available_day": 295
82
+ },
83
+ "S92541": {
84
+ "available_day": 278
85
+ },
86
+ "S93638": {
87
+ "available_day": 300
88
+ },
89
+ "S96230": {
90
+ "available_day": 293
91
+ },
92
+ "S96936": {
93
+ "available_day": 278
94
+ }
95
+ },
96
+ "renewals": {},
97
+ "sessions": {
98
+ "renewal": {
99
+ "seats": 3,
100
+ "start_day": 296
101
+ }
102
+ }
103
+ }