File size: 33,274 Bytes
232313d
 
 
d25cd8a
232313d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d25cd8a
 
 
232313d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d25cd8a
232313d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d25cd8a
232313d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d25cd8a
232313d
 
 
 
 
 
 
 
 
 
 
 
d25cd8a
232313d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d25cd8a
232313d
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
"""Jev Rules-7: rule and policy decision tasks (evaluation only). Facts in the state, the policy RULE IN THE QUESTION,
gold computed exactly by code for the generated tasks; ShARC dev and the patent phrase test split are pinned public
sets. Skills: admission, rental, agent_rules, authority, fraud_points, sharc, patent_phrases, missing_facts (paired
complete / one-fact-removed records for the AUROC of the model's confidence).
"""

import gzip
import hashlib
import json
import random

import bench_common as X
from bench_common import choice, noul, noul_target, onehot, score as score_q

VERSION = "v1"
BENCH = "Rules7"
SKILLS = ("admission", "rental", "agent_rules", "authority", "fraud_points", "sharc", "patent_phrases", "missing_facts")
SIZES = {"admission": 400, "rental": 400, "agent_rules": 400, "authority": 400, "fraud_points": 400, "sharc": 400,
         "patent_phrases": 400, "missing_facts": 160}  # missing_facts: pairs per task (two tasks, two items per pair)
LICENSE = "CC0-1.0"
SHARC = ("tasksource/sharc", "fa4605de8281290c69af9dea6118b37d072c2b59", "data/validation-00000-of-00001.parquet")
PATENT = ("tasksource/patent-phrase-similarity", "ff1868796e44ac9ec02e870b447fde6c5bf2d6e4",
          "data/test-00000-of-00001-c5556affccbcc71f.parquet")

NAMES = ["Alex Moreno", "Priya Raman", "Chen Wei", "Sara Lindqvist", "Tomasz Nowak", "Amara Okafor", "Lucas Ferreira",
         "Yuki Tanaka", "Fatima Zahra", "Noah Becker", "Elena Petrova", "Diego Salazar", "Ines Costa", "Omar Haddad"]


def _item(id, skill, source, state, questions, targets, license=LICENSE, split="generated", **extra):
    st = state if isinstance(state, str) else json.dumps(state, ensure_ascii=False)
    key = st + " " + " ".join(q["instructions"] for q in questions.values())
    it = X._item(id, skill, source, st, questions, targets, license, key)
    it.update(bench=BENCH, split=split, **extra)
    return it


# ===================================================================== a small rule engine with missing facts
class Cond:
    """One condition on one fact: kind ge / le (numeric threshold t), bool, notbool, in (value in `opts`)."""

    def __init__(s, spec: dict, rng: random.Random):
        s.key, s.kind = spec["key"], spec["kind"]
        s.spec = spec
        s.t = rng.choice(spec["ts"]) if "ts" in spec else None
        s.opts = spec.get("opts")
        s.phrase = spec["phrase"].format(t=s.t) if "phrase" in spec else None
        s.exc = spec.get("exc")

    def test(s, v):
        if s.kind == "ge":
            return v >= s.t
        if s.kind == "le":
            return v <= s.t
        if s.kind == "lt":
            return v < s.t
        if s.kind == "bool":
            return bool(v)
        if s.kind == "notbool":
            return not v
        return v in s.opts

    def sample(s, rng: random.Random, truth: bool):
        sp = s.spec
        if s.kind in ("bool", "notbool"):
            return truth if s.kind == "bool" else (not truth)
        if s.kind == "in":
            return rng.choice(s.opts if truth else sp["other"])
        if s.kind == "lt":
            return max(sp["lo"], s.t - 1 - rng.choice([0, 0, 1, 2, 5])) if truth else s.t + rng.choice([0, 1, 3, 10, 60])
        step, dec = sp.get("step", 1), sp.get("dec", 0)
        d = rng.choice([0, 1, 1, 2, 3, 5, 9]) * step
        up = (s.kind == "ge") == truth  # value above the threshold
        if not truth:
            d = max(d, step)
        v = s.t + d if up else s.t - d
        v = min(sp["hi"], max(sp["lo"], v))
        v = round(v, dec) if dec else int(round(v))
        if s.test(v) != truth:  # clipped into the wrong side: fall back to the boundary
            v = s.t if truth else (s.t - step if s.kind == "ge" else s.t + step)
            v = round(v, dec) if dec else int(round(v))
        return v


def ev3(node, facts):
    """Kleene evaluation: True / False / None (a needed fact is missing)."""
    t = node[0]
    if t == "c":
        c = node[1]
        return None if c.key not in facts else bool(c.test(facts[c.key]))
    if t == "not":
        v = ev3(node[1], facts)
        return None if v is None else (not v)
    vals = [ev3(n, facts) for n in node[1]]
    if t == "and":
        return False if False in vals else (None if None in vals else True)
    return True if True in vals else (None if None in vals else False)


def conds_of(node):
    if node[0] == "c":
        return [node[1]]
    if node[0] == "not":
        return conds_of(node[1])
    return [c for n in node[1] for c in conds_of(n)]


def build_tree(rng: random.Random, pool: list, exc_pool: list, n: int = 3, allow_exc: bool = True):
    specs = rng.sample(pool, n)
    cs = [("c", Cond(sp, rng)) for sp in specs]
    form = rng.choice(["and", "and", "or_in", "or_out"])
    if form == "and" or n < 3:
        node = ("and", cs)
    elif form == "or_in":
        node = ("and", [cs[0], ("or", cs[1:])])
    else:
        node = ("or", [("and", cs[:2]), cs[2]])
    if allow_exc and exc_pool and rng.random() < 0.4:
        e = ("not", ("c", Cond(rng.choice(exc_pool), rng)))
        node = ("and", [node, e]) if node[0] != "and" else ("and", node[1] + [e])
    return node


def render_tree(node):
    """The tree as a phrase for a sentence; a nested or reads "either ... or ..."."""
    if node[0] == "c":
        return node[1].phrase
    if node[0] == "or":
        sep = ", or " if any(m[0] != "c" for m in node[1]) else " or "
        return "either " + sep.join(render_tree(m) for m in node[1])
    parts = [render_tree(n) for n in node[1] if n[0] != "not"]
    exc = [n[1][1].exc for n in node[1] if n[0] == "not"]
    s = parts[0] if len(parts) == 1 else ", ".join(parts[:-1]) + " and " + parts[-1]
    return s + (", unless the applicant " + " or ".join(exc) if exc else "")


def sample_facts(rng: random.Random, node, target: bool, tries: int = 300):
    cs = conds_of(node)
    for _ in range(tries):
        p = rng.choice([0.3, 0.5, 0.7, 0.9])
        facts = {}
        for c in cs:
            if c.key in facts:
                continue
            facts[c.key] = c.sample(rng, rng.random() < (1 - p if c.exc else p))
        if ev3(node, facts) == target:
            return facts
    return None


def pivots(node, facts):
    """Facts whose removal leaves the outcome undecided."""
    return [k for k in facts if ev3(node, {a: b for a, b in facts.items() if a != k}) is None]


# ===================================================================== admission
ADM_POOL = [
    dict(key="gpa", kind="ge", ts=[2.8, 3.0, 3.2, 3.4, 3.6], lo=2.0, hi=4.0, step=0.1, dec=1, phrase="has a GPA of at least {t}"),
    dict(key="entrance_exam_score", kind="ge", ts=[60, 65, 70, 75, 80], lo=30, hi=100, phrase="scored at least {t} on the entrance exam"),
    dict(key="recommendation_letters", kind="ge", ts=[2, 3, 4], lo=0, hi=6, phrase="has at least {t} recommendation letters"),
    dict(key="years_of_work_experience", kind="ge", ts=[2, 3, 5, 8], lo=0, hi=20, phrase="has at least {t} years of work experience"),
    dict(key="age", kind="le", ts=[28, 30, 35, 40], lo=17, hi=55, phrase="is at most {t} years old"),
    dict(key="submitted_before_deadline", kind="bool", phrase="submitted the application before the deadline"),
    dict(key="portfolio_included", kind="bool", phrase="included a portfolio"),
    dict(key="application_fee_paid", kind="bool", phrase="paid the application fee"),
    dict(key="highest_degree", kind="in", opts=["bachelor's degree", "master's degree", "doctorate"],
         other=["high school diploma", "associate degree", "none"], phrase="holds a bachelor's degree or higher"),
]
ADM_EXC = [
    dict(key="disciplinary_record", kind="bool", exc="has a disciplinary record"),
    dict(key="plagiarism_flag", kind="bool", exc="has a plagiarism flag on file"),
    dict(key="unpaid_tuition", kind="bool", exc="owes unpaid tuition from an earlier enrolment"),
]
ADM_EXTRA = {"applicant": lambda r: r.choice(NAMES), "intended_program": lambda r: r.choice(
    ["Chemistry", "Economics", "Computer Science", "History", "Nursing", "Design", "Physics"]),
    "country": lambda r: r.choice(["Poland", "Brazil", "Japan", "Kenya", "Canada", "Germany", "India"])}
ADM_LEADS = ("Our admissions policy accepts an applicant who {r}. Should this applicant be admitted?",
             "Policy: an applicant is admitted if the applicant {r}. Should this applicant be admitted?",
             "The programme admits an applicant who {r}. Based on the record, should this applicant be admitted?")


def gen_admission(rng: random.Random, target: bool):
    for _ in range(100):
        node = build_tree(rng, ADM_POOL, ADM_EXC, n=rng.choice([2, 3, 3, 4]))
        facts = sample_facts(rng, node, target)
        if facts is None:
            continue
        text = rng.choice(ADM_LEADS).format(r=render_tree(node))
        state = {k: f(rng) for k, f in ADM_EXTRA.items()}
        items = list(facts.items())
        rng.shuffle(items)
        state.update(dict(items))
        return node, state, facts, text
    raise RuntimeError("admission generator failed")


def admission(n: int, rng: random.Random) -> list:
    out = []
    for i in range(n):
        target = i % 2 == 0
        node, state, facts, text = gen_admission(rng, target)
        assert ev3(node, facts) == target
        out.append(_item(f"rules7-admission-{i:04d}", "admission", "rules7:admission", state, {"admit": noul(text)},
                         {"admit": noul_target(target)}))
    return out


# ===================================================================== agent_rules
AGENT = {
    "spend money": dict(
        pool=[dict(key="amount_usd", kind="le", ts=[50, 100, 250, 500, 1000], lo=1, hi=3000, step=10, phrase="the amount is at most ${t}"),
              dict(key="vendor_on_approved_list", kind="bool", phrase="the vendor is on the approved list"),
              dict(key="manager_approved", kind="bool", phrase="a manager has approved it"),
              dict(key="budget_remaining_usd", kind="ge", ts=[500, 1000, 2000], lo=0, hi=6000, step=50, phrase="the remaining budget is at least ${t}")],
        exc=[dict(key="purchase_is_recurring", kind="bool", exc="is a recurring subscription")],
        stem="Spending money", extra={"description": ["software licence", "conference ticket", "cloud credits", "office supplies"]}),
    "send an email": dict(
        pool=[dict(key="recipient_is_internal", kind="bool", phrase="the recipient is inside the company"),
              dict(key="contains_customer_data", kind="notbool", phrase="the message contains no customer data"),
              dict(key="manager_approved", kind="bool", phrase="a manager has approved it"),
              dict(key="recipient_count", kind="le", ts=[1, 3, 5, 10], lo=1, hi=30, phrase="it goes to at most {t} recipients")],
        exc=[dict(key="marketing_content", kind="bool", exc="is marketing content")],
        stem="Sending an email", extra={"subject": ["Quarterly numbers", "Meeting notes", "Invoice question", "Launch update"]}),
    "delete a file": dict(
        pool=[dict(key="location", kind="in", opts=["sandbox"], other=["staging", "production", "shared drive"], phrase="the file is in the sandbox"),
              dict(key="backup_exists", kind="bool", phrase="a backup exists"),
              dict(key="file_age_days", kind="ge", ts=[30, 90, 180, 365], lo=0, hi=900, step=10, phrase="the file is at least {t} days old"),
              dict(key="created_by_agent", kind="bool", phrase="the agent created the file")],
        exc=[dict(key="under_legal_hold", kind="bool", exc="is under legal hold")],
        stem="Deleting a file", extra={"file": ["report_q3.csv", "tmp_export.json", "notes.txt", "build.log"]}),
    "deploy code": dict(
        pool=[dict(key="tests_passed", kind="bool", phrase="all tests passed"),
              dict(key="reviewer_approvals", kind="ge", ts=[1, 2, 3], lo=0, hi=5, phrase="at least {t} reviewers approved it"),
              dict(key="lines_changed", kind="le", ts=[100, 300, 500, 1000], lo=1, hi=2500, step=20, phrase="the change touches at most {t} lines"),
              dict(key="rollback_plan", kind="bool", phrase="a rollback plan is attached")],
        exc=[dict(key="change_freeze", kind="bool", exc="is during a change freeze")],
        stem="Deploying code", extra={"service": ["billing-api", "web-frontend", "search-index", "auth"]}),
    "read data": dict(
        pool=[dict(key="data_sensitivity_level", kind="le", ts=[1, 2, 3], lo=1, hi=5, phrase="the data sensitivity level is at most {t}"),
              dict(key="purpose_logged", kind="bool", phrase="the purpose is logged"),
              dict(key="user_consented", kind="bool", phrase="the user consented"),
              dict(key="requester_in_team", kind="bool", phrase="the requester is in the owning team")],
        exc=[dict(key="subject_is_minor", kind="bool", exc="involves a minor's data")],
        stem="Reading data", extra={"dataset": ["orders", "support tickets", "telemetry", "payroll"]}),
}
AGENT_LEADS = ("Rules for the agent: ", "The agent works under these rules. ", "Agent policy: ")


def agent_rules(n: int, rng: random.Random, with_missing: bool = False) -> list:
    out = []
    for i in range(n):
        target = i % 2 == 0
        for _ in range(100):
            kinds = rng.sample(list(AGENT), 3)
            trees = {k: build_tree(rng, AGENT[k]["pool"], AGENT[k]["exc"], n=3) for k in kinds}
            act = rng.choice(kinds)
            facts = sample_facts(rng, trees[act], target)
            if facts is not None:
                break
        rules = []
        for k in kinds:
            nd = trees[k]
            body = render_tree(nd).replace(", unless the applicant", ", unless the action")
            rules.append(f"{AGENT[k]['stem']} is allowed only if {body}.")
        state = {"requested action": act, **{kk: rng.choice(vv) for kk, vv in AGENT[act]["extra"].items()}, **facts}
        text = rng.choice(AGENT_LEADS) + " ".join(f"({j + 1}) {r}" for j, r in enumerate(rules)) + \
            " May the agent take the requested action?"
        out.append(_item(f"rules7-agent_rules-{i:04d}", "agent_rules", "rules7:agent_rules", state,
                         {"allowed": noul(text)}, {"allowed": noul_target(ev3(trees[act], facts))}))
        assert ev3(trees[act], facts) == target
    return out


# ===================================================================== rental
RENT_OPTS = {"decline": "the rental is refused", "approve": "the rental is approved at the standard terms",
             "approve_with_surcharge": "approved with a young-driver surcharge",
             "require_deposit": "approved but a security deposit is required",
             "surcharge_and_deposit": "approved with both a surcharge and a deposit"}


def gen_rental(rng: random.Random, want: str):
    for _ in range(500):
        min_age = rng.choice([21, 23, 25])
        young = rng.choice([25, 27, 30])
        lic = rng.choice([1, 2, 3])
        dep_rule = rng.choice(["luxury", "debit", "either"])
        dui = rng.choice([3, 5])
        facts = {"renter_age": rng.randint(min_age - 3, 45), "licence_years": rng.randint(0, 8),
                 "vehicle_class": rng.choice(["economy", "compact", "suv", "luxury"]),
                 "payment_method": rng.choice(["credit card", "debit card"]),
                 "dui_conviction_years_ago": rng.choice([None, None, 1, 2, 4, 6, 10]),
                 "rental_days": rng.randint(1, 21)}
        decline = facts["renter_age"] < min_age or facts["licence_years"] < lic or \
            (facts["dui_conviction_years_ago"] is not None and facts["dui_conviction_years_ago"] < dui)
        sur = facts["renter_age"] < young
        dep = {"luxury": facts["vehicle_class"] == "luxury", "debit": facts["payment_method"] == "debit card",
               "either": facts["vehicle_class"] == "luxury" or facts["payment_method"] == "debit card"}[dep_rule]
        gold = "decline" if decline else ("surcharge_and_deposit" if sur and dep else "approve_with_surcharge" if sur
                                           else "require_deposit" if dep else "approve")
        if gold != want:
            continue
        dep_txt = {"luxury": "the vehicle is in the luxury class", "debit": "the renter pays by debit card",
                   "either": "the vehicle is in the luxury class or the renter pays by debit card"}[dep_rule]
        text = (f"Rental policy: refuse the rental if the renter is under {min_age}, has held a licence for less than "
                f"{lic} year{'s' if lic > 1 else ''}, or has a DUI conviction within the last {dui} years. "
                f"Otherwise approve it, adding a young-driver surcharge if the renter is under {young}, and requiring a "
                f"security deposit if {dep_txt}. What should we do with this rental request?")
        return facts, text, gold
    raise RuntimeError("rental generator failed")


def rental(n: int, rng: random.Random) -> list:
    order = list(RENT_OPTS)
    out = []
    for i in range(n):
        facts, text, gold = gen_rental(rng, order[i % len(order)])
        state = {"renter": rng.choice(NAMES), **{k: v for k, v in facts.items() if v is not None}}
        if facts["dui_conviction_years_ago"] is None:
            state["dui_conviction"] = "none on record"
        opts = list(RENT_OPTS)
        rng.shuffle(opts)
        out.append(_item(f"rules7-rental-{i:04d}", "rental", "rules7:rental", state,
                         {"decision": choice(text, {o: RENT_OPTS[o] for o in opts})}, {"decision": onehot(opts, gold)}))
    return out


# ===================================================================== authority
ROLES = {"team_lead": "a team lead", "department_head": "a department head", "cfo": "the CFO",
         "general_counsel": "the general counsel", "hr_director": "the HR director"}


def gen_authority(rng: random.Random, want: str):
    for _ in range(500):
        t1 = rng.choice([200, 500, 1000, 2000])
        t2 = t1 * rng.choice([5, 10])
        rtype = rng.choice(["purchase", "purchase", "contract", "hire", "travel", "software licence"])
        amount = int(rng.choice([t1 * 0.3, t1 * 0.9, t1, t1 * 1.1, t2 * 0.5, t2, t2 * 1.2, t2 * 3]))
        salary_cap = rng.choice([60000, 80000, 100000])
        salary = rng.choice([salary_cap - 10000, salary_cap, salary_cap + 5000, salary_cap + 30000])
        facts = {"request_type": rtype, "requested_by": rng.choice(NAMES)}
        if rtype == "hire":
            facts["annual_salary_usd"] = salary
            gold = "department_head" if salary <= salary_cap else "hr_director"
        else:
            facts["amount_usd"] = amount
            if rtype == "contract":
                gold = "general_counsel"
            elif rtype == "software licence":
                gold = "department_head" if amount <= t2 else "cfo"
            elif rtype == "travel":
                gold = "team_lead" if amount <= t2 // 4 else "department_head"
            else:
                gold = "team_lead" if amount <= t1 else ("department_head" if amount <= t2 else "cfo")
        if gold != want:
            continue
        text = (f"Approval rules: purchases up to ${t1} can be approved by a team lead, up to ${t2} by a department head, "
                f"and anything above that by the CFO. Travel up to ${t2 // 4} can be approved by a team lead, above that "
                f"by a department head. Software licences up to ${t2} go to a department head, above that to the CFO. "
                f"Every contract, whatever its value, goes to the general counsel. A hire with an annual salary up to "
                f"${salary_cap} is approved by a department head, a higher salary by the HR director. "
                f"Who may approve this request?")
        return facts, text, gold
    raise RuntimeError("authority generator failed")


def authority(n: int, rng: random.Random) -> list:
    order = list(ROLES)
    out = []
    for i in range(n):
        facts, text, gold = gen_authority(rng, order[i % len(order)])
        opts = list(ROLES)
        rng.shuffle(opts)
        out.append(_item(f"rules7-authority-{i:04d}", "authority", "rules7:authority", facts,
                         {"approver": choice(text, {o: ROLES[o] for o in opts})}, {"approver": onehot(opts, gold)}))
    return out


# ===================================================================== fraud_points
FRAUD_RULES = [
    dict(key="account_age_days", kind="lt", ts=[7, 14, 30], lo=0, hi=900, step=1, ph="the account is less than {t} days old"),
    dict(key="billing_shipping_countries_differ", kind="bool", ph="the billing and shipping countries differ"),
    dict(key="order_total_usd", kind="ge", ts=[300, 500, 1000, 2000], lo=10, hi=4000, step=25, ph="the order total is at least ${t}"),
    dict(key="failed_payment_attempts", kind="ge", ts=[2, 3, 4], lo=0, hi=8, step=1, ph="there were at least {t} failed payment attempts"),
    dict(key="new_device", kind="bool", ph="the order comes from a device not seen before"),
    dict(key="vpn_or_proxy", kind="bool", ph="the connection uses a VPN or proxy"),
    dict(key="local_hour", kind="in", opts=[1, 2, 3, 4], other=[8, 9, 10, 12, 14, 16, 19, 21], ph="the order was placed between 01:00 and 04:59 local time"),
    dict(key="previous_chargebacks", kind="ge", ts=[1, 2], lo=0, hi=5, step=1, ph="the customer has at least {t} earlier chargebacks"),
    dict(key="disposable_email", kind="bool", ph="the email address is from a disposable-email provider"),
    dict(key="freight_forwarder_address", kind="bool", ph="the shipping address is a freight forwarder"),
]
LEVELS = ["low", "medium", "high", "critical"]


def gen_fraud(rng: random.Random, want: int):
    for _ in range(2000):
        specs = rng.sample(FRAUD_RULES, 6)
        rules = []
        for sp in specs:
            c = Cond({**sp, "phrase": sp["ph"]}, rng)
            rules.append((c, rng.choice([1, 2, 2, 3, 3, 4])))
        a = rng.choice([2, 3, 4])
        b = a + rng.choice([2, 3])
        d = b + rng.choice([2, 3])
        cut = (a, b, d)
        p = rng.choice([0.2, 0.35, 0.5, 0.7])
        facts = {c.key: c.sample(rng, rng.random() < p) for c, _ in rules}
        total = sum(pts for c, pts in rules if c.test(facts[c.key]))
        lvl = sum(total >= x for x in cut)
        if lvl != want:
            continue
        pts_txt = "; ".join(f"+{pts} if {c.phrase}" for c, pts in rules)
        text = (f"Fraud score: add up the points: {pts_txt}. Risk level: below {cut[0]} points is low, {cut[0]} to "
                f"{cut[1] - 1} is medium, {cut[1]} to {cut[2] - 1} is high, {cut[2]} or more is critical. "
                f"What risk level does this order get?")
        return rules, cut, facts, text, lvl
    raise RuntimeError("fraud generator failed")


def fraud_level(rules, cut, facts):
    total = sum(pts for c, pts in rules if c.key in facts and c.test(facts[c.key]))
    return sum(total >= x for x in cut)


def fraud_pivots(rules, cut, facts):
    """Facts whose removal leaves the level undecided (it differs with and without that rule's points)."""
    out = []
    for c, pts in rules:
        rest = sum(p for c2, p in rules if c2.key != c.key and c2.test(facts[c2.key]))
        if sum(rest >= x for x in cut) != sum(rest + pts >= x for x in cut):
            out.append(c.key)
    return out


def fraud_state(rng, facts):
    items = list(facts.items())
    rng.shuffle(items)
    return {"order_id": f"ORD-{rng.randint(10000, 99999)}", "customer": rng.choice(NAMES), **dict(items)}


def fraud_points(n: int, rng: random.Random) -> list:
    out = []
    for i in range(n):
        rules, cut, facts, text, lvl = gen_fraud(rng, i % 4)
        out.append(_item(f"rules7-fraud_points-{i:04d}", "fraud_points", "rules7:fraud_points", fraud_state(rng, facts),
                         {"risk": score_q(text, LEVELS)}, {"risk": {str(j): float(j == lvl) for j in range(4)}}))
    return out


# ===================================================================== missing facts
def missing_facts(pairs: int, rng: random.Random) -> list:
    out = []
    i = 0
    while i < pairs:  # admission
        node, state, facts, text = gen_admission(rng, i % 2 == 0)
        pv = pivots(node, facts)
        if not pv:
            continue
        gone = rng.choice(pv)
        gold = ev3(node, facts)
        full = _item(f"rules7-missing_facts-admission-{i:04d}-complete", "missing_facts", "missing:admission:complete",
                     state, {"admit": noul(text)}, {"admit": noul_target(gold)}, variant="complete", pair=i, task="admission")
        miss = {k: v for k, v in state.items() if k != gone}
        part = _item(f"rules7-missing_facts-admission-{i:04d}-missing", "missing_facts", "missing:admission:missing", miss,
                     {"admit": noul(text)}, {}, variant="missing", pair=i, task="admission", removed=gone)
        out += [full, part]
        i += 1
    i = 0
    while i < pairs:  # fraud points
        rules, cut, facts, text, lvl = gen_fraud(rng, i % 4)
        pv = fraud_pivots(rules, cut, facts)
        if not pv:
            continue
        gone = rng.choice(pv)
        state = fraud_state(rng, facts)
        full = _item(f"rules7-missing_facts-fraud_points-{i:04d}-complete", "missing_facts", "missing:fraud_points:complete",
                     state, {"risk": score_q(text, LEVELS)}, {"risk": {str(j): float(j == lvl) for j in range(4)}},
                     variant="complete", pair=i, task="fraud_points")
        part = _item(f"rules7-missing_facts-fraud_points-{i:04d}-missing", "missing_facts", "missing:fraud_points:missing",
                     {k: v for k, v in state.items() if k != gone}, {"risk": score_q(text, LEVELS)}, {},
                     variant="missing", pair=i, task="fraud_points", removed=gone)
        out += [full, part]
        i += 1
    return out


# ===================================================================== public sets
def _clean(t) -> str:
    return " ".join(str(t).split()) if t is not None else ""


def _norm(t) -> str:
    import re

    return re.sub(r"\W+", " ", str(t).lower()).strip()


def load_exclusions() -> dict:
    """Rule texts excluded from the ShARC selection (duplicated rule texts; normalised, first 200 chars): drop_keys.json,
    2 rule texts, 36 dev rows. Nothing is excluded from the patent phrases."""
    import os

    p = os.path.join(os.path.dirname(os.path.abspath(__file__)), "drop_keys.json")
    return {"sharc_drop": set(json.load(open(p))), "pairs": set(), "anchors": set()}


def sharc(n: int, rng: random.Random, pools: dict | None = None) -> tuple[list, dict]:
    """ShARC dev (CC BY-SA 3.0), the rows whose answer is yes or no (no follow-up question needed), balanced; at most
    eight utterances per rule text (the dev split has only 56 rule texts with yes / no answers)."""
    import pandas as pd
    from huggingface_hub import hf_hub_download

    repo, rev, f = SHARC
    df = pd.read_parquet(hf_hub_download(repo, f, repo_type="dataset", revision=rev))
    df = df[df.label.isin([0, 1])]
    rows = df.to_dict("records")
    dropped = 0
    if pools:  # rule texts listed in drop_keys.json are excluded (duplicated rule texts)
        bad = {}
        keep = []
        for r in rows:
            k = _norm(r["snippet"])[:200]
            if k not in bad:
                bad[k] = k in pools["sharc_drop"]
            if bad[k]:
                dropped += 1
            else:
                keep.append(r)
        rows = keep
    rng.shuffle(rows)
    per_tree, picked = {}, {True: [], False: []}
    for r in rows:
        yes = int(r["label"]) == 0
        if per_tree.get(r["tree_id"], 0) >= 8 or len(picked[yes]) >= n // 2:
            continue
        per_tree[r["tree_id"]] = per_tree.get(r["tree_id"], 0) + 1
        picked[yes].append(r)
    out = []
    for j, r in enumerate(sorted(picked[True] + picked[False], key=lambda r: r["utterance_id"])):
        state = {"rule text": _clean(r["snippet"]), "scenario": _clean(r["scenario"]) or "(none given)",
                 "conversation so far": _clean(r["history"]).replace(" Q:", "\nQ:").replace(" A:", "\nA:") or "(none)",
                 "user question": _clean(r["question"])}
        q = noul("Using only the rule text, the scenario and the conversation so far, do the rules say that the answer to "
                 "the user's question is yes?")
        out.append(_item(f"rules7-sharc-{r['utterance_id'][:12]}", "sharc", "sharc:dev", state, {"answer": q},
                         {"answer": noul_target(int(r["label"]) == 0)}, license="CC-BY-SA-3.0", split="public"))
    info = {"dataset": f"{SHARC[0]}@{SHARC[1]}", "file": SHARC[2], "dev_rows": int(len(pd.read_parquet(hf_hub_download(
        repo, f, repo_type="dataset", revision=rev)))), "yes_no_rows": int(len(df)),
            "excluded_rule_texts": dropped}
    return out, info


PATENT_LEVELS = ["not related (0)", "somewhat related (0.25)", "synonym with a different breadth, e.g. hypernym or "
                 "hyponym (0.5)", "close synonym (0.75)", "very close match (1.0)"]


def patent_phrases(n: int, rng: random.Random, pools: dict | None = None) -> tuple[list, dict]:
    """US Patent Phrase-to-Phrase Matching, the held-out (test) split of tasksource/patent-phrase-similarity with the
    expert scores 0 / 0.25 / 0.5 / 0.75 / 1; balanced over the five levels."""
    import pandas as pd
    from huggingface_hub import hf_hub_download

    repo, rev, f = PATENT
    df = pd.read_parquet(hf_hub_download(repo, f, repo_type="dataset", revision=rev))
    df = df.drop_duplicates(["anchor", "target", "context"])
    dropped = 0
    if pools:
        mask = [(_norm(a), _norm(t)) in pools["pairs"] or _norm(a) in pools["anchors"]
                for a, t in zip(df.anchor, df.target, strict=True)]
        dropped = int(sum(mask))
        df = df[[not m for m in mask]]
    by = {j: [r for r in df.to_dict("records") if abs(float(r["score"]) - j / 4) < 1e-6] for j in range(5)}
    out = []
    for j in range(5):
        rng.shuffle(by[j])
        for r in by[j][:n // 5]:
            state = {"phrase A": r["anchor"], "phrase B": r["target"], "technical field (CPC class)": r["context"]}
            q = score_q("In patent language, how similar in meaning is phrase B to phrase A, in the given technical "
                        "field?", PATENT_LEVELS)
            out.append(_item(f"rules7-patent-{hashlib.sha1((r['anchor'] + '|' + r['target'] + '|' + r['context']).encode()).hexdigest()[:12]}",
                             "patent_phrases", "patent_phrases:test", state, {"similarity": q},
                             {"similarity": {str(k): float(k == j) for k in range(5)}}, license="CC-BY-4.0",
                             split="public"))
    rng.shuffle(out)
    return out, {"dataset": f"{PATENT[0]}@{PATENT[1]}", "file": PATENT[2], "rows": int(len(df)),
                                                   "excluded_pairs": dropped}


# ===================================================================== build
def build(seed: int = 0, sizes: dict | None = None, public: bool = True, screen: bool = True) -> tuple[list, dict]:
    sz = {**SIZES, **(sizes or {})}
    items, info = [], {"version": VERSION, "seed": seed}
    items += admission(sz["admission"], random.Random(f"{seed}:admission"))
    items += rental(sz["rental"], random.Random(f"{seed}:rental"))
    items += agent_rules(sz["agent_rules"], random.Random(f"{seed}:agent"))
    items += authority(sz["authority"], random.Random(f"{seed}:authority"))
    items += fraud_points(sz["fraud_points"], random.Random(f"{seed}:fraud"))
    if public:
        pools = load_exclusions() if screen else None
        its, info["sharc"] = sharc(sz["sharc"], random.Random(f"{seed}:sharc"), pools)
        items += its
        its, info["patent"] = patent_phrases(sz["patent_phrases"], random.Random(f"{seed}:patent"), pools)
        items += its
    items += missing_facts(sz["missing_facts"], random.Random(f"{seed}:missing"))
    ids = set()
    for x in items:
        assert x["id"] not in ids, x["id"]
        ids.add(x["id"])
    info["counts"] = {s: sum(x["skill"] == s for x in items) for s in SKILLS}
    info["gold"] = {}
    for s in SKILLS:
        c = {}
        for x in items:
            if x["skill"] == s:
                for k, t in x["targets"].items():
                    g = max(t, key=t.get)
                    c[g] = c.get(g, 0) + 1
        info["gold"][s] = dict(sorted(c.items()))
    return items, info


def state_hashes(items: list) -> list:
    return sorted({hashlib.sha1(x["state"].encode()).hexdigest() for x in items})


def write(items: list, info: dict, outdir: str = ".") -> list:
    import os

    p = os.path.join(outdir, "rules7_v1_items.json.gz")
    with gzip.open(p, "wt") as fh:
        json.dump(items, fh, ensure_ascii=False)
    return [p]


if __name__ == "__main__":
    import argparse

    ap = argparse.ArgumentParser(description="build Rules7 v1 items")
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--out", default=".")
    a = ap.parse_args()
    its, inf = build(a.seed)
    print(json.dumps(inf, indent=1))
    print(write(its, inf, a.out))