File size: 26,210 Bytes
7c188b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Task families for MAUI-Bench.

Each family provides:
  generate(rng, cfg)  -> Instance (fully declarative, JSON-serializable)
  cost(inst, action)  -> expected cost in ms (or negative utility for T4)
  oracle(inst)        -> (a_star, c_star, c_rand) computed exactly, never by LLM
  parse(inst, text)   -> action or None (strict JSON extraction with light repair)
  penalized(inst, a)  -> action with constraint violations mapped to penalty cost

Cost model provenance (report these in the paper):
  T1 menu:   linear-scan search term per slot (Cockburn/Gutwin/Greenberg 2007 family)
             plus Fitts pointing to the slot, MacKenzie formulation.
  T2 layout: Fitts MT = a + b * log2(D/W + 1), a=0 ms, b=150 ms/bit defaults
             (Soukoreff/MacKenzie 2004 ranges); zero-order (from origin) or
             first-order (transition-weighted) variants.
  T3 klm:    canonical KLM operator times (Card/Moran/Newell 1980), M-placement
             simplified to one M per chunk boundary.
  T4 intervention: declared MDP; optimum by value iteration, so Delta-EU is exact.
"""
from __future__ import annotations

import itertools
import json
import math
import re
from dataclasses import dataclass, field
from typing import Any, Optional

import numpy as np

WORD_BANK = [
    "Open", "Save", "Export", "Import", "Print", "Share", "Rename", "Duplicate",
    "Archive", "Restore", "Search", "Filter", "Sort", "Group", "Annotate",
    "Highlight", "Translate", "Summarize", "Compare", "Merge", "Split", "Align",
    "Publish", "Schedule", "Notify", "Sync", "Backup", "Preview", "Insert",
    "Format", "Validate", "Delete",
]

DESTRUCTIVE = {"Delete", "Archive"}


def fitts_ms(D: float, W: float, a: float = 0.0, b: float = 150.0) -> float:
    return a + b * math.log2(D / max(W, 1e-9) + 1.0)


def zipf_probs(n: int, s: float, rng: np.random.Generator) -> np.ndarray:
    ranks = np.arange(1, n + 1, dtype=float)
    p = ranks ** (-s)
    p = p / p.sum()
    rng.shuffle(p)  # decouple frequency rank from label order shown to the model
    return p


def _extract_json(text: str) -> Optional[dict]:
    """Strict-ish JSON extraction: fenced block first, then first balanced object."""
    m = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.DOTALL)
    candidates = [m.group(1)] if m else []
    # fall back to the largest brace-balanced span
    start = text.find("{")
    if start != -1:
        depth = 0
        for i, ch in enumerate(text[start:], start):
            if ch == "{":
                depth += 1
            elif ch == "}":
                depth -= 1
                if depth == 0:
                    candidates.append(text[start : i + 1])
                    break
    for c in candidates:
        try:
            return json.loads(c)
        except Exception:
            try:
                return json.loads(c.replace("'", '"'))
            except Exception:
                continue
    return None


@dataclass
class Instance:
    family: str
    seed: int
    data: dict[str, Any]
    paraphrases: list[str] = field(default_factory=list)

    def to_json(self) -> str:
        return json.dumps(
            {"family": self.family, "seed": self.seed, "data": self.data,
             "paraphrases": self.paraphrases},
            sort_keys=True,
        )


# ======================================================================= T1
class MenuTask:
    family = "menu"

    @staticmethod
    def generate(rng: np.random.Generator, cfg: dict) -> Instance:
        n = int(rng.choice(cfg["sizes"]))
        s = float(rng.choice(cfg["zipf_exponents"]))
        labels = [str(x) for x in rng.choice(WORD_BANK, size=n, replace=False)]
        probs = zipf_probs(n, s, rng)
        pinned_last = None
        if rng.random() < cfg["pin_last_fraction"]:
            dest = [w for w in labels if w in DESTRUCTIVE]
            if dest:
                pinned_last = dest[0]
        data = {
            "n": n,
            "labels": labels,
            "usage": {lab: float(p) for lab, p in zip(labels, probs)},
            "pinned_last": pinned_last,
            "slot_height_px": 24,
            "slot_width_px": 160,
            "search_ms_per_slot": cfg["search_time_per_slot_ms"],
            "fitts_b": 150.0,
        }
        base = (
            "Reorder the menu so that expected selection time is minimized for the "
            "given click-frequency distribution."
        )
        paras = [
            "Arrange these menu items to make the average selection as fast as "
            "possible under the stated usage frequencies.",
            "Given how often each command is used, produce the item ordering with "
            "the lowest expected time to select.",
            "Optimize the order of this menu for the provided click probabilities "
            "so users reach frequent items quickest.",
            "Sort the menu entries to minimize mean selection cost given the usage "
            "statistics below.",
        ]
        data["description"] = base
        return Instance("menu", int(rng.integers(0, 2**31)), data, paras)

    @staticmethod
    def cost(inst: Instance, order: list[str]) -> float:
        d = inst.data
        h, w, b = d["slot_height_px"], d["slot_width_px"], d["fitts_b"]
        total = 0.0
        for slot, lab in enumerate(order):
            D = (slot + 0.5) * h  # from menu origin to slot center
            mt = fitts_ms(D, h, b=b)
            scan = d["search_ms_per_slot"] * (slot + 1)
            total += d["usage"][lab] * (mt + scan)
        return total

    PENALTY_MS = 5000.0

    @classmethod
    def penalized(cls, inst: Instance, order: Optional[list[str]]) -> tuple[list[str], float]:
        """Return a valid order plus additive penalty for violations."""
        d = inst.data
        labels = d["labels"]
        penalty = 0.0
        if order is None:
            return list(labels), cls.PENALTY_MS  # unparseable = worst-case-ish
        clean = [x for x in order if x in labels]
        missing = [x for x in labels if x not in clean]
        penalty += cls.PENALTY_MS * 0.2 * (len(order) - len(clean))  # hallucinated
        penalty += cls.PENALTY_MS * 0.2 * len(missing)               # dropped
        clean = clean + missing
        # de-duplicate preserving first occurrence
        seen: set[str] = set()
        clean = [x for x in clean if not (x in seen or seen.add(x))]
        if d["pinned_last"] and clean[-1] != d["pinned_last"]:
            penalty += cls.PENALTY_MS * 0.5
            clean = [x for x in clean if x != d["pinned_last"]] + [d["pinned_last"]]
        return clean, penalty

    @classmethod
    def oracle(cls, inst: Instance) -> tuple[list[str], float, float]:
        d = inst.data
        labels = sorted(d["labels"], key=lambda l: -d["usage"][l])
        if d["pinned_last"]:
            labels = [x for x in labels if x != d["pinned_last"]] + [d["pinned_last"]]
        # slot cost is monotone in slot index, so frequency-sorted is exactly optimal
        # under the pin constraint; verify by local exchange as a safety certificate.
        c_star = cls.cost(inst, labels)
        for i in range(len(labels) - 1):
            swapped = labels[:]
            swapped[i], swapped[i + 1] = swapped[i + 1], swapped[i]
            v, p = cls.penalized(inst, swapped)
            assert cls.cost(inst, v) + p >= c_star - 1e-6, "oracle certificate failed"
        # expected cost of a uniformly random valid order (exact by symmetry:
        # every label occupies every slot with equal probability)
        n = d["n"]
        slot_costs = [
            fitts_ms((s + 0.5) * d["slot_height_px"], d["slot_height_px"], b=d["fitts_b"])
            + d["search_ms_per_slot"] * (s + 1)
            for s in range(n)
        ]
        c_rand = float(np.mean(slot_costs))  # since usage sums to 1
        return labels, c_star, c_rand

    @staticmethod
    def parse(inst: Instance, text: str) -> Optional[list[str]]:
        obj = _extract_json(text)
        if not obj:
            return None
        order = obj.get("order")
        return order if isinstance(order, list) else None


# ======================================================================= T2
class LayoutTask:
    family = "layout"

    @staticmethod
    def generate(rng: np.random.Generator, cfg: dict) -> Instance:
        m = int(rng.choice(cfg["n_controls"]))
        rows, cols = map(int, rng.choice(np.array(cfg["grid_shapes"], dtype=object)))
        while rows * cols < m:
            rows, cols = rows + 1, cols
        labels = [str(x) for x in rng.choice(WORD_BANK, size=m, replace=False)]
        probs = zipf_probs(m, 1.1, rng)
        first_order = bool(rng.random() < cfg["first_order_fraction"])
        trans = None
        if first_order:
            T = rng.dirichlet(np.ones(m), size=m)
            trans = T.tolist()
        cell_w, cell_h = 96.0, 48.0
        slots = []
        for r in range(rows):
            for c in range(cols):
                slots.append({"x": (c + 0.5) * cell_w, "y": (r + 0.5) * cell_h,
                              "w": cell_w})
        data = {
            "m": m, "rows": rows, "cols": cols,
            "labels": labels,
            "usage": {lab: float(p) for lab, p in zip(labels, probs)},
            "transitions": trans,
            "slots": slots,
            "origin": {"x": 0.0, "y": 0.0},
            "fitts_a": cfg["fitts_a_ms"], "fitts_b": cfg["fitts_b_ms_per_bit"],
            "description": (
                "Assign each control to one grid slot to minimize expected Fitts-law "
                "movement time, given the usage frequencies"
                + (" and the first-order transition matrix." if first_order else
                   " measured from the screen origin.")
            ),
        }
        paras = [
            "Place the controls on the grid so total predicted pointing time is lowest.",
            "Choose a slot for every control minimizing expected movement time under "
            "Fitts' law for the given frequencies.",
            "Lay out these controls on the grid for minimum expected acquisition time.",
            "Map controls to grid positions to optimize aggregate Fitts-law cost.",
        ]
        return Instance("layout", int(rng.integers(0, 2**31)), data, paras)

    @staticmethod
    def _dist(p: dict, q: dict) -> float:
        return math.hypot(p["x"] - q["x"], p["y"] - q["y"])

    _mat_cache: dict = {}

    @classmethod
    def _matrices(cls, inst: Instance):
        """Precompute per-instance cost matrices for fast evaluation.
        Returns (origin_cost[nslots], pair_cost[nslots, nslots], W[m, m] or None)."""
        key = (inst.family, inst.seed)
        hit = cls._mat_cache.get(key)
        if hit is not None:
            return hit
        d = inst.data
        slots = d["slots"]
        ns = len(slots)
        xs = np.array([s["x"] for s in slots])
        ys = np.array([s["y"] for s in slots])
        ws = np.array([s["w"] for s in slots])
        ox, oy = d["origin"]["x"], d["origin"]["y"]
        a, b = d["fitts_a"], d["fitts_b"]
        D0 = np.maximum(np.hypot(xs - ox, ys - oy), 1.0)
        origin_cost = a + b * np.log2(D0 / ws + 1.0)
        DX = xs[:, None] - xs[None, :]
        DY = ys[:, None] - ys[None, :]
        Dp = np.maximum(np.hypot(DX, DY), 1.0)
        pair_cost = a + b * np.log2(Dp / ws[None, :] + 1.0)
        W = None
        if d["transitions"] is not None:
            labels = d["labels"]
            T = np.array(d["transitions"])
            u = np.array([d["usage"][l] for l in labels])
            W = u[:, None] * T
        cls._mat_cache[key] = (origin_cost, pair_cost, W)
        return cls._mat_cache[key]

    @classmethod
    def cost(cls, inst: Instance, assign: dict[str, int]) -> float:
        d = inst.data
        labels = d["labels"]
        origin_cost, pair_cost, W = cls._matrices(inst)
        perm = np.array([assign[l] for l in labels], dtype=int)
        if W is None:
            u = np.array([d["usage"][l] for l in labels])
            return float(np.dot(u, origin_cost[perm]))
        return float(np.sum(W * pair_cost[np.ix_(perm, perm)]))

    PENALTY_MS = 5000.0

    @classmethod
    def penalized(cls, inst: Instance, assign: Optional[dict[str, int]]
                  ) -> tuple[dict[str, int], float]:
        d = inst.data
        labels, nslots = d["labels"], len(d["slots"])
        if assign is None:
            return {l: i for i, l in enumerate(labels)}, cls.PENALTY_MS
        penalty = 0.0
        clean: dict[str, int] = {}
        used: set[int] = set()
        for lab in labels:
            si = assign.get(lab)
            if isinstance(si, int) and 0 <= si < nslots and si not in used:
                clean[lab] = si
                used.add(si)
            else:
                penalty += cls.PENALTY_MS * 0.2
        free = [i for i in range(nslots) if i not in used]
        for lab in labels:
            if lab not in clean:
                clean[lab] = free.pop(0)
        return clean, penalty

    @classmethod
    def oracle(cls, inst: Instance) -> tuple[dict[str, int], float, float]:
        d = inst.data
        labels, slots = d["labels"], d["slots"]
        m = len(labels)
        if d["transitions"] is None:
            # zero-order: linear assignment, exact via Hungarian
            from scipy.optimize import linear_sum_assignment
            C = np.zeros((m, len(slots)))
            for i, lab in enumerate(labels):
                for j, s in enumerate(slots):
                    D = max(cls._dist(d["origin"], s), 1.0)
                    C[i, j] = d["usage"][lab] * fitts_ms(D, s["w"], d["fitts_a"], d["fitts_b"])
            ri, ci = linear_sum_assignment(C)
            a_star = {labels[i]: int(j) for i, j in zip(ri, ci)}
        else:
            # first-order: QAP-like. Exact enumeration (vectorized) for m<=6;
            # otherwise best of 60 seeded restarts of full 2-exchange descent.
            # The descent uses the vectorized cost; each restart terminates at a
            # local optimum of the 2-exchange neighborhood (certificate logged).
            _, pair_cost, W = cls._matrices(inst)

            def perm_cost(perm_arr):
                return float(np.sum(W * pair_cost[np.ix_(perm_arr, perm_arr)]))

            if m <= 6:
                best, best_c = None, float("inf")
                for perm in itertools.permutations(range(len(slots)), m):
                    pa = np.array(perm, dtype=int)
                    c = perm_cost(pa)
                    if c < best_c:
                        best, best_c = pa, c
                a_star = {lab: int(best[i]) for i, lab in enumerate(labels)}
            else:
                rng = np.random.default_rng(inst.seed)
                nslots = len(slots)
                best, best_c = None, float("inf")
                for _ in range(60):
                    pa = np.array(rng.permutation(nslots)[:m], dtype=int)
                    unused = [x for x in range(nslots) if x not in set(pa.tolist())]
                    c0 = perm_cost(pa)
                    improved = True
                    while improved:
                        improved = False
                        for i in range(m):
                            for j in range(i + 1, m):
                                pa[i], pa[j] = pa[j], pa[i]
                                c1 = perm_cost(pa)
                                if c1 < c0 - 1e-9:
                                    c0, improved = c1, True
                                else:
                                    pa[i], pa[j] = pa[j], pa[i]
                        for i in range(m):        # relocation moves to unused slots
                            for uix, uslot in enumerate(unused):
                                old = pa[i]
                                pa[i] = uslot
                                c1 = perm_cost(pa)
                                if c1 < c0 - 1e-9:
                                    unused[uix] = int(old)
                                    c0, improved = c1, True
                                else:
                                    pa[i] = old
                    if c0 < best_c:
                        best, best_c = pa.copy(), c0
                a_star = {lab: int(best[i]) for i, lab in enumerate(labels)}
        c_star = cls.cost(inst, a_star)
        # random baseline: Monte Carlo over 500 uniform valid assignments (seeded)
        rng = np.random.default_rng(inst.seed + 1)
        cs = []
        for _ in range(500):
            perm = rng.permutation(len(slots))[:m]
            cs.append(cls.cost(inst, {lab: int(perm[i]) for i, lab in enumerate(labels)}))
        return a_star, c_star, float(np.mean(cs))

    @staticmethod
    def parse(inst: Instance, text: str) -> Optional[dict[str, int]]:
        obj = _extract_json(text)
        if not obj:
            return None
        a = obj.get("assignment")
        if isinstance(a, dict):
            try:
                return {str(k): int(v) for k, v in a.items()}
            except Exception:
                return None
        return None


# ======================================================================= T3
class KLMTask:
    family = "klm"

    # widget library: name -> KLM operator string to complete one field with it
    LIBRARY = {
        "free_text":       "HMKKKKKKKK",       # home hands, think, ~8 keystrokes
        "masked_text":     "HMKKKKKKKKKK",
        "dropdown":        "PBMPB",             # point, click, scan, point, click
        "searchable_dropdown": "PBMKKKPB",
        "date_picker":     "PBMPBPB",
        "date_text":       "HMKKKKKKKK",
        "stepper":         "PBBBB",
        "slider":          "PMB",
        "radio_group":     "MPB",
        "checkbox":        "PB",
        "toggle":          "PB",
        "segmented":       "MPB",
    }
    FIELD_KINDS = {
        "date":       ["date_picker", "date_text"],
        "small_int":  ["stepper", "slider", "free_text", "dropdown"],
        "choice_3":   ["radio_group", "dropdown", "segmented"],
        "choice_12":  ["dropdown", "searchable_dropdown", "radio_group"],
        "boolean":    ["checkbox", "toggle", "dropdown"],
        "short_text": ["free_text", "masked_text"],
    }

    @staticmethod
    def _klm_ms(ops: str, cfg_ops: dict[str, int]) -> float:
        return float(sum(cfg_ops[o] for o in ops))

    @classmethod
    def generate(cls, rng: np.random.Generator, cfg: dict) -> Instance:
        n_fields = int(rng.integers(3, 7))
        kinds = [str(x) for x in rng.choice(list(cls.FIELD_KINDS), size=n_fields, replace=True)]
        fields = [{"name": f"field_{i+1}", "kind": k} for i, k in enumerate(kinds)]
        data = {
            "fields": fields,
            "allowed": {k: cls.FIELD_KINDS[k] for k in set(kinds)},
            "library_klm": {w: cls.LIBRARY[w] for w in cls.LIBRARY},
            "operators_ms": cfg["operators_ms"],
            "description": (
                "For each form field, choose one widget from the allowed set for its "
                "kind so that total Keystroke-Level-Model completion time is minimal."
            ),
        }
        paras = [
            "Select widgets for every field minimizing the summed KLM time.",
            "Pick the widget per field that yields the fastest KLM-predicted completion.",
            "Compose the form from allowed widgets to minimize total predicted time.",
            "Choose, per field, the allowed widget with lowest KLM completion cost.",
        ]
        return Instance("klm", int(rng.integers(0, 2**31)), data, paras)

    @classmethod
    def cost(cls, inst: Instance, choice: dict[str, str]) -> float:
        d = inst.data
        return sum(
            cls._klm_ms(d["library_klm"][choice[f["name"]]], d["operators_ms"])
            for f in d["fields"]
        )

    PENALTY_MS = 5000.0

    @classmethod
    def penalized(cls, inst: Instance, choice: Optional[dict[str, str]]
                  ) -> tuple[dict[str, str], float]:
        d = inst.data
        penalty = 0.0
        clean: dict[str, str] = {}
        for f in d["fields"]:
            allowed = d["allowed"][f["kind"]]
            w = (choice or {}).get(f["name"])
            if w in allowed:
                clean[f["name"]] = w
            else:
                penalty += cls.PENALTY_MS * (0.5 if w else 0.2)
                clean[f["name"]] = allowed[0]
        return clean, penalty

    @classmethod
    def oracle(cls, inst: Instance) -> tuple[dict[str, str], float, float]:
        d = inst.data
        a_star, per_field_rand = {}, []
        for f in d["fields"]:
            allowed = d["allowed"][f["kind"]]
            costs = {w: cls._klm_ms(d["library_klm"][w], d["operators_ms"]) for w in allowed}
            a_star[f["name"]] = min(costs, key=costs.get)
            per_field_rand.append(float(np.mean(list(costs.values()))))
        return a_star, cls.cost(inst, a_star), float(sum(per_field_rand))

    @staticmethod
    def parse(inst: Instance, text: str) -> Optional[dict[str, str]]:
        obj = _extract_json(text)
        if not obj:
            return None
        c = obj.get("widgets")
        return {str(k): str(v) for k, v in c.items()} if isinstance(c, dict) else None


# ======================================================================= T4
class InterventionTask:
    """Declared-MDP intervention timing. States: user attention in
    {focused, receptive, idle}; actions: {wait, ask, act}. Optimal policy by
    value iteration on the declared dynamics, so Delta-EU is exact."""
    family = "intervention"
    STATES = ["focused", "receptive", "idle"]
    ACTIONS = ["wait", "ask", "act"]

    @classmethod
    def generate(cls, rng: np.random.Generator, cfg: dict) -> Instance:
        P = rng.dirichlet(np.ones(3) * 2.0, size=3)  # row-stochastic attention dynamics
        # declared reward matrix R[state][action]; interruption costly when focused,
        # missed assistance costly when receptive
        interruption = float(rng.uniform(3.0, 8.0))
        missed = float(rng.uniform(1.0, 5.0))
        dialog = float(rng.uniform(0.5, 2.0))
        assist_value = float(rng.uniform(4.0, 9.0))
        R = {
            "focused":   {"wait": 0.0,           "ask": -dialog - interruption,
                          "act": assist_value - interruption},
            "receptive": {"wait": -missed,       "ask": assist_value - dialog,
                          "act": assist_value},
            "idle":      {"wait": 0.0,           "ask": -dialog,
                          "act": assist_value * 0.3},
        }
        horizon = cfg["horizon"]
        data = {
            "P": P.tolist(), "R": R, "horizon": horizon,
            "start_state_probs": [0.5, 0.3, 0.2],
            "description": (
                "At each of H steps decide wait, ask, or act, to maximize total "
                "declared utility given the attention dynamics and reward matrix. "
                "Output a policy mapping each (step, state) to an action."
            ),
        }
        paras = [
            "Produce the per-step, per-state action policy maximizing expected total reward.",
            "For every step and attention state choose wait, ask, or act to maximize utility.",
            "Give the utility-maximizing intervention policy over the horizon.",
            "Return the optimal action for each state at each step under the declared rewards.",
        ]
        return Instance("intervention", int(rng.integers(0, 2**31)), data, paras)

    @classmethod
    def _value(cls, inst: Instance, policy: dict[str, str]) -> float:
        d = inst.data
        P = np.array(d["P"])
        H = d["horizon"]
        V = np.zeros(3)
        for t in range(H - 1, -1, -1):
            V_new = np.zeros(3)
            for si, s in enumerate(cls.STATES):
                a = policy.get(f"{t}:{s}", "wait")
                r = d["R"][s].get(a, -10.0)
                V_new[si] = r + P[si] @ V
            V = V_new
        return float(np.array(d["start_state_probs"]) @ V)

    @classmethod
    def cost(cls, inst: Instance, policy: dict[str, str]) -> float:
        # negated utility so "lower is better" matches other families
        return -cls._value(inst, policy)

    PENALTY = 20.0

    @classmethod
    def penalized(cls, inst: Instance, policy: Optional[dict[str, str]]
                  ) -> tuple[dict[str, str], float]:
        d = inst.data
        penalty = 0.0
        clean: dict[str, str] = {}
        for t in range(d["horizon"]):
            for s in cls.STATES:
                key = f"{t}:{s}"
                a = (policy or {}).get(key)
                if a in cls.ACTIONS:
                    clean[key] = a
                else:
                    penalty += 0.05 * cls.PENALTY
                    clean[key] = "wait"
        return clean, penalty

    @classmethod
    def oracle(cls, inst: Instance) -> tuple[dict[str, str], float, float]:
        d = inst.data
        P = np.array(d["P"])
        H = d["horizon"]
        V = np.zeros(3)
        pol: dict[str, str] = {}
        for t in range(H - 1, -1, -1):
            V_new = np.zeros(3)
            for si, s in enumerate(cls.STATES):
                q = {a: d["R"][s][a] + float(P[si] @ V) for a in cls.ACTIONS}
                best = max(q, key=q.get)
                pol[f"{t}:{s}"] = best
                V_new[si] = q[best]
            V = V_new
        c_star = cls.cost(inst, pol)
        rng = np.random.default_rng(inst.seed + 2)
        cs = []
        for _ in range(500):
            rp = {f"{t}:{s}": cls.ACTIONS[int(rng.integers(3))]
                  for t in range(H) for s in cls.STATES}
            cs.append(cls.cost(inst, rp))
        return pol, c_star, float(np.mean(cs))

    @staticmethod
    def parse(inst: Instance, text: str) -> Optional[dict[str, str]]:
        obj = _extract_json(text)
        if not obj:
            return None
        p = obj.get("policy")
        return {str(k): str(v) for k, v in p.items()} if isinstance(p, dict) else None


FAMILIES = {
    "menu": MenuTask,
    "layout": LayoutTask,
    "klm": KLMTask,
    "intervention": InterventionTask,
}