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
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
"""Light machines: learn an unknown device by experiment, then plan or predict.

Two families share one machine model.

``light_machine`` (interactive)
    N lights and B buttons.  The model is told the current pattern, the target
    pattern and the allowed *kinds* of button behaviour, but not which button
    does what.  It must experiment (each press costs a step) and then reach the
    target.  The oracle is a BFS shortest path; targets are chosen far from the
    start so a random policy almost never wins.

``light_machine_log`` (single turn)
    A log of presses from a start pattern is given.  Two questions follow from
    a new pattern: the pattern after a short button sequence, and the minimum
    number of presses needed to reach a target.  The log is built by an active
    probe phase (every pure toggle is tested in the all-off state, the
    conditional is only ever pressed while its condition light is on) so the
    hidden machine is identifiable.  The queried sequence deliberately presses
    the conditional in the opposite condition: a "last logged toggle set"
    pattern matcher gets it wrong, while the inferred rule gets it right.

Hypothesis language (both modes)
    Each button has exactly one fixed behaviour from:
      * toggle a non-empty fixed set of lights;
      * conditional: toggle a non-empty fixed set only while a given light is
        on (otherwise nothing happens);
      * rotate the whole pattern one place to the left;
      * branch: while a given light is on toggle one non-empty set, otherwise
        toggle a different non-empty set.
    The log mode additionally states the multiset of behaviour kinds (e.g.
    "two toggles, one conditional"), so the only hidden facts are which button
    has which kind and the sets/condition lights.  The interactive mode does
    not state the multiset: it must be discovered by pressing buttons.
"""
from __future__ import annotations

import itertools
import random
from collections import deque

from ..core import ANSWER_INSTRUCTION, Ambiguous, Env, InteractiveFamily, Task, TaskFamily, pseudo_words, sub_rng

# ---------------------------------------------------------------------------
# machine primitives
# ---------------------------------------------------------------------------

KINDS = ("toggle", "cond", "rot", "branch")
KIND_WORDS = {
    "toggle": "toggle a fixed non-empty set of lights",
    "cond": "toggle its fixed non-empty set only while a particular light is on (otherwise nothing happens)",
    "rot": "rotate the whole pattern one place to the left (the leftmost light moves to the right end)",
    "branch": "while a particular light is on toggle one fixed non-empty set, otherwise toggle a different fixed non-empty set",
}


def _rot(mask: int, n: int) -> int:
    """Rotate the displayed pattern one place left (position 0 -> position n-1)."""
    return ((mask >> 1) | ((mask & 1) << (n - 1))) & ((1 << n) - 1)


def _apply(beh, mask: int, n: int) -> int:
    """Apply one button behaviour to a light pattern."""
    kind = beh[0]
    if kind == "toggle":
        return mask ^ beh[1]
    if kind == "cond":
        return mask ^ beh[2] if (mask >> beh[1]) & 1 else mask
    if kind == "rot":
        return _rot(mask, n)
    if kind == "branch":
        _, k, s_on, s_off = beh
        return mask ^ (s_on if (mask >> k) & 1 else s_off)
    raise ValueError(kind)


def _pattern(mask: int, n: int) -> str:
    return "".join("#" if (mask >> i) & 1 else "." for i in range(n))


def _mask(text: str) -> int:
    m = 0
    for i, ch in enumerate(text.strip()):
        if ch == "#":
            m |= 1 << i
    return m


def _all_states(n: int):
    return range(1 << n)


def _reachable(n: int, buttons, start: int) -> dict[int, int]:
    """BFS distances from start under a full machine (list of behaviours)."""
    dist = {start: 0}
    q = deque([start])
    while q:
        m = q.popleft()
        d = dist[m]
        for beh in buttons:
            nm = _apply(beh, m, n)
            if nm not in dist:
                dist[nm] = d + 1
                q.append(nm)
    return dist


def _shortest_path(n: int, buttons, start: int, target: int) -> list[int] | None:
    """BFS shortest button-index path, deterministic in button order."""
    if start == target:
        return []
    prev: dict[int, tuple[int, int] | None] = {start: None}
    q = deque([start])
    while q:
        m = q.popleft()
        for i, beh in enumerate(buttons):
            nm = _apply(beh, m, n)
            if nm not in prev:
                prev[nm] = (m, i)
                if nm == target:
                    path = []
                    cur = nm
                    while prev[cur] is not None:
                        p, bi = prev[cur]
                        path.append(bi)
                        cur = p
                    return list(reversed(path))
                q.append(nm)
    return None


def _random_policy_hit_prob(n: int, buttons, start: int, target: int, max_steps: int) -> float:
    """Exact probability that a uniform-random button policy reaches target in time."""
    b = len(buttons)
    if start == target:
        return 1.0
    dist = {start: 1.0}
    hit = 0.0
    for _ in range(max_steps):
        nd: dict[int, float] = {}
        for m, pr in dist.items():
            for beh in buttons:
                nm = _apply(beh, m, n)
                nd[nm] = nd.get(nm, 0.0) + pr / b
        dist = nd
        hit += dist.get(target, 0.0)
    return hit


def _predict(obs: list[tuple[int, int]], m: int, n: int, kinds) -> int | None:
    """Prediction of an honest agent for one button at pattern m, from that button's
    observed (before, after) pairs only. Occam order: toggle > rotate > conditional >
    branch. Returns None when the observations do not determine the outcome."""
    if not obs:
        return None
    diffs = {b ^ a for b, a in obs}
    if "toggle" in kinds and len(diffs) == 1 and 0 not in diffs:
        return m ^ next(iter(diffs))
    if "rot" in kinds and all(a == _rot(b, n) for b, a in obs):
        return _rot(m, n)
    outcomes = set()
    if "cond" in kinds:
        acting = {b ^ a for b, a in obs if a != b}
        if len(acting) <= 1:
            s = next(iter(acting), None)
            for k in range(n):
                if all(((b >> k) & 1) == (a != b) for b, a in obs):
                    on = (m >> k) & 1
                    outcomes.add(None if on and s is None else (m ^ s if on else m))
    if "branch" in kinds:
        for k in range(n):
            side = {0: set(), 1: set()}
            for b, a in obs:
                side[(b >> k) & 1].add(b ^ a)
            if all(len(v) <= 1 and 0 not in v for v in side.values()):
                if side[0] and side[0] == side[1]:
                    continue  # the two sets must differ
                d = side[(m >> k) & 1]
                outcomes.add(m ^ next(iter(d)) if d else None)
    if len(outcomes) == 1:
        return next(iter(outcomes))
    return None


def _honest_explorer_steps(n: int, buttons, start: int, target: int, kinds, cap: int) -> int | None:
    """Steps a knowledge-free explore-then-plan agent needs to reach the target, or None.

    The agent sees only patterns. Each step it plans a shortest path using the buttons
    whose effect it can predict (see `_predict`); if a plan exists it takes the first
    press and re-plans (so wrong guesses get corrected), otherwise it explores by pressing
    the least-observed button whose effect here is still unknown. This is the fairness
    yardstick for the step budget: a careful player is never asked to be luckier than it.
    """
    obs: list[list[tuple[int, int]]] = [[] for _ in buttons]
    m = start
    for step in range(cap):
        if m == target:
            return step
        prev = {m: None}
        q = deque([m])
        first = None
        while q and first is None:
            cur = q.popleft()
            for i in range(len(buttons)):
                nxt = _predict(obs[i], cur, n, kinds)
                if nxt is None or nxt in prev:
                    continue
                prev[nxt] = (cur, i)
                if nxt == target:
                    while prev[nxt][0] != m:
                        nxt = prev[nxt][0]
                    first = prev[nxt][1]
                    break
                q.append(nxt)
        if first is None:
            unknown = [i for i in range(len(buttons)) if _predict(obs[i], m, n, kinds) is None]
            if not unknown:
                return None  # everything predictable here, yet no route: the agent is stuck
            first = min(unknown, key=lambda i: (len(obs[i]), i))
        after = _apply(buttons[first], m, n)
        obs[first].append((m, after))
        m = after
    return cap if m == target else None


# ---------------------------------------------------------------------------
# interactive family
# ---------------------------------------------------------------------------

# The validator also runs a uniform-random policy.  In a tiny toggle-only state
# space that policy reaches almost every target, so the interactive machine uses
# seven buttons on seven lights, and the generator rejects targets whose exact
# random-policy hit probability exceeds 5%.  The step budget comes from an honest
# explorer (`_honest_explorer_steps`) plus FAIR_SLACK presses.
FAIR_SLACK = 3
INTERACTIVE = {
    1: dict(n=7, b=7, kinds=("toggle",), min_len=4),
    2: dict(n=7, b=7, kinds=("toggle",), min_len=4),
    3: dict(n=7, b=7, kinds=("toggle", "cond"), min_len=5),
    4: dict(n=7, b=7, kinds=("toggle", "cond", "rot"), min_len=5),
    5: dict(n=7, b=7, kinds=("toggle", "cond", "rot", "branch"), min_len=5),
}

# Kind counts used by the interactive sampler (sums to b=7).
INTERACTIVE_MIX = {
    1: ("toggle",) * 7,
    2: ("toggle",) * 7,
    3: ("toggle",) * 5 + ("cond",) * 2,
    4: ("toggle",) * 4 + ("cond",) * 2 + ("rot",),
    5: ("toggle",) * 3 + ("cond",) + ("rot",) + ("branch",) * 2,
}


def _sample_behavior(rng: random.Random, kind: str, n: int):
    if kind == "toggle":
        return ("toggle", rng.randrange(1, 1 << n))
    if kind == "cond":
        return ("cond", rng.randrange(n), rng.randrange(1, 1 << n))
    if kind == "rot":
        return ("rot",)
    if kind == "branch":
        while True:
            k = rng.randrange(n)
            s = rng.randrange(1, 1 << n)
            t = rng.randrange(1, 1 << n)
            if s != t:
                return ("branch", k, s, t)
    raise ValueError(kind)


def _build_interactive(seed: int, difficulty: int):
    """Deterministically build (n, names, buttons, start, target, max_steps)."""
    P = INTERACTIVE[difficulty]
    rng = sub_rng(seed, difficulty, "machine")
    srng = sub_rng(seed, difficulty, "surface")
    n, b = P["n"], P["b"]
    mix = list(INTERACTIVE_MIX[difficulty])

    for _ in range(400):
        rng.shuffle(mix)
        buttons = [_sample_behavior(rng, kind, n) for kind in mix]
        start = rng.randrange(1 << n)
        reach = _reachable(n, buttons, start)
        # every button must matter for some reachable state
        if any(not any(_apply(beh, m, n) != m for m in reach) for beh in buttons):
            continue
        # target at a controlled distance, reachable, and not the start
        far = [m for m, d in reach.items() if P["min_len"] <= d <= P["min_len"] + 1]
        if not far:
            continue
        rng.shuffle(far)
        for target in far:
            dist = reach[target]
            # budget = what an honest explorer needs + slack; episodes the explorer
            # cannot finish (they would need luck) are rejected
            honest = _honest_explorer_steps(n, buttons, start, target, P["kinds"], cap=dist + 3 * b)
            if honest is None:
                continue
            max_steps = honest + FAIR_SLACK
            # exact random-policy probability must be far below the 10% limit:
            # random button mashing should almost never earn reward
            if _random_policy_hit_prob(n, buttons, start, target, max_steps) > 0.05:
                continue
            names = pseudo_words(srng, b, syllables=(2, 2))
            return n, names, buttons, start, target, max_steps
    raise RuntimeError(f"light_machine: no interactive machine for seed={seed} d={difficulty}")


class LightMachine(InteractiveFamily):
    name = "light_machine"
    skills = ("experiment design", "learning device mechanics", "planning", "state-space search")

    def make_env(self, seed: int, difficulty: int) -> Env:
        n, names, buttons, start, target, max_steps = _build_interactive(seed, difficulty)
        return _LightEnv(n, names, buttons, start, target, max_steps, seed, difficulty)

    def oracle_actions(self, seed: int, difficulty: int) -> list[str]:
        n, names, buttons, start, target, _ = _build_interactive(seed, difficulty)
        path = _shortest_path(n, buttons, start, target)
        if path is None:
            raise RuntimeError("light_machine: oracle target unreachable")
        return [f"PRESS {names[i]}" for i in path]


class _LightEnv(Env):
    def __init__(self, n, names, buttons, start, target, max_steps, seed, difficulty):
        self.n = n
        self.names = names
        self.buttons = buttons
        self.start = start
        self.state = start
        self.target = target
        self.max_steps = max_steps
        self.left = max_steps
        self._done = False
        self._success = False
        self.intro = _render_interactive_intro(seed, difficulty, n, names, start, target, max_steps)

    def legal_actions(self) -> list[str]:
        return [f"PRESS {name}" for name in self.names]

    def step(self, action: str) -> str:
        if self._done:
            return "The episode is already over."
        text = (action or "").strip()
        parts = text.split()
        if len(parts) != 2 or parts[0].upper() != "PRESS":
            self.left -= 1
            if self.left <= 0:
                self._done = True
            return f"That is not a valid action. Use exactly 'PRESS <button>'. Steps left: {self.left}."
        name = parts[1]
        if name not in self.names:
            self.left -= 1
            if self.left <= 0:
                self._done = True
            return f"There is no button called {name}. Steps left: {self.left}."
        i = self.names.index(name)
        self.state = _apply(self.buttons[i], self.state, self.n)
        self.left -= 1
        if self.state == self.target:
            self._done = True
            self._success = True
            return f"Pattern: {_pattern(self.state, self.n)}. Target reached! Steps left: {self.left}."
        if self.left <= 0:
            self._done = True
            return f"Pattern: {_pattern(self.state, self.n)}. No steps left."
        return f"Pattern: {_pattern(self.state, self.n)}. Steps left: {self.left}."

    @property
    def done(self) -> bool:
        return self._done

    @property
    def success(self) -> bool:
        return self._success


def _render_interactive_intro(seed, difficulty, n, names, start, target, max_steps) -> str:
    rng = sub_rng(seed, difficulty, "intro")
    styles = [
        ("device", "You have found an unfamiliar device."),
        ("console", "A sealed console stands in front of you."),
        ("machine", "A machine with a row of lights is humming quietly."),
    ]
    noun, intro = rng.choice(styles)
    lines = [
        intro,
        f"The {noun} has {n} lights. '#' means a light is on and '.' means it is off.",
        f"Current pattern: {_pattern(start, n)}",
        f"Target pattern:  {_pattern(target, n)}",
        "",
        "There are buttons named: " + ", ".join(names) + ".",
        "The only action you may take is: PRESS <button>. Each press costs one step.",
        "Malformed actions also cost one step. You may press any button as often as you like,",
        "and a press may leave the pattern unchanged.",
        "",
        "Each button has exactly one fixed kind of behaviour, chosen from this list:",
    ]
    for kind in INTERACTIVE[difficulty]["kinds"]:
        lines.append(f"- {KIND_WORDS[kind]}")
    lines += [
        "",
        "You do not know which button has which behaviour. Press buttons to learn what they do,",
        "then use that knowledge to reach the target. The target is reachable from the current pattern.",
        f"You have {max_steps} steps in total.",
    ]
    return "\n".join(lines)


# ---------------------------------------------------------------------------
# log family
# ---------------------------------------------------------------------------

# Log mode follows the brief's sizes more closely, but every difficulty includes
# at least one conditional: without a state-dependent button the "replay the
# last logged toggle set" shortcut would be exactly correct for pure toggles.
LOG_PARAMS = {
    1: dict(n=3, b=2, kinds=("toggle", "cond"), seq=(2, 2), log=(4, 9)),
    2: dict(n=4, b=3, kinds=("toggle", "toggle", "cond"), seq=(2, 3), log=(5, 10)),
    3: dict(n=5, b=3, kinds=("toggle", "toggle", "cond"), seq=(2, 3), log=(6, 11)),
    4: dict(n=6, b=4, kinds=("toggle", "toggle", "cond", "rot"), seq=(3, 4), log=(7, 12)),
    5: dict(n=7, b=4, kinds=("toggle", "cond", "rot", "branch"), seq=(3, 4), log=(8, 12)),
}


def _kind_counts(kinds) -> dict[str, int]:
    out = {k: 0 for k in KINDS}
    for k in kinds:
        out[k] += 1
    return {k: v for k, v in out.items() if v}


def _type_assignments(kinds):
    """All distinct assignments of the multiset `kinds` to button positions."""
    return list(dict.fromkeys(itertools.permutations(kinds)))


def _consistent_behaviors(n: int, kind: str, obs: list[tuple[int, int]]) -> list[tuple]:
    """All behaviours of `kind` that explain every observed (before, after) press."""
    if kind == "toggle":
        if not obs:
            return [("toggle", s) for s in range(1, 1 << n)]
        s = obs[0][0] ^ obs[0][1]
        if s == 0 or any((b ^ a) != s for b, a in obs):
            return []
        return [("toggle", s)]

    if kind == "cond":
        out = []
        for k in range(n):
            on = [(b, a) for b, a in obs if (b >> k) & 1]
            off = [(b, a) for b, a in obs if not ((b >> k) & 1)]
            if any(a != b for b, a in off):
                continue
            if on:
                s = on[0][0] ^ on[0][1]
                if s == 0 or any((b ^ a) != s for b, a in on):
                    continue
                out.append(("cond", k, s))
            else:
                for s in range(1, 1 << n):
                    out.append(("cond", k, s))
        return out

    if kind == "rot":
        if all(a == _rot(b, n) for b, a in obs):
            return [("rot",)]
        return []

    if kind == "branch":
        out = []
        for k in range(n):
            on = [(b, a) for b, a in obs if (b >> k) & 1]
            off = [(b, a) for b, a in obs if not ((b >> k) & 1)]
            if on:
                s = on[0][0] ^ on[0][1]
                if s == 0 or any((b ^ a) != s for b, a in on):
                    continue
                ss = [s]
            else:
                ss = list(range(1, 1 << n))
            if off:
                t = off[0][0] ^ off[0][1]
                if t == 0 or any((b ^ a) != t for b, a in off):
                    continue
                tt = [t]
            else:
                tt = list(range(1, 1 << n))
            for s in ss:
                for t in tt:
                    if s != t:
                        out.append(("branch", k, s, t))
        return out

    raise ValueError(kind)


def _behavior_key(beh, n: int) -> tuple[int, ...]:
    """Full transition table, used to collapse behaviourally identical candidates."""
    return tuple(_apply(beh, m, n) for m in range(1 << n))


def _decode_evidence(evidence, query):
    n = evidence["lights"]
    names = evidence["buttons"]
    idx = {name: i for i, name in enumerate(names)}
    obs = [[] for _ in names]
    for rec in evidence["log"]:
        obs[idx[rec["button"]]].append((_mask(rec["before"]), _mask(rec["after"])))
    qstart = _mask(query["start"])
    qseq = [idx[name] for name in query["sequence"]]
    qtarget = _mask(query["target"])
    kinds = evidence["kinds"]
    return n, names, obs, qstart, qseq, qtarget, kinds


def _machine_answers(n, buttons, qstart, qseq, qtarget):
    """(pattern-after-sequence, shortest-distance) for one fully specified machine."""
    m = qstart
    for i in qseq:
        m = _apply(buttons[i], m, n)
    after = m
    dist = _reachable(n, buttons, qstart)
    if qtarget not in dist:
        return None
    return after, dist[qtarget]


def _solve_log(evidence, query):
    n, names, obs, qstart, qseq, qtarget, kinds = _decode_evidence(evidence, query)
    answers: set[tuple[int, int]] = set()
    seen_machines = set()

    for assign in _type_assignments(kinds):
        per_button = []
        ok = True
        for i, kind in enumerate(assign):
            cands = _consistent_behaviors(n, kind, obs[i])
            if not cands:
                ok = False
                break
            # collapse behaviourally identical candidates
            uniq = {}
            for beh in cands:
                uniq.setdefault(_behavior_key(beh, n), beh)
            per_button.append(list(uniq.values()))
        if not ok:
            continue
        # product size guard: generated logs keep this tiny
        total = 1
        for c in per_button:
            total *= len(c)
        if total > 20000:
            # too many observationally distinct machines: treat as ambiguous
            return None
        for combo in itertools.product(*per_button):
            key = tuple(_behavior_key(b, n) for b in combo)
            if key in seen_machines:
                continue
            seen_machines.add(key)
            ans = _machine_answers(n, list(combo), qstart, qseq, qtarget)
            if ans is None:
                continue
            answers.add(ans)
            if len(answers) >= 2:
                return answers
    return answers


def _answers_to_strings(answers, n):
    return {f"{_pattern(a, n)}, {d}" for a, d in answers}


class LightMachineLog(TaskFamily):
    name = "light_machine_log"
    skills = ("learning device mechanics from a log", "rule induction", "state-space search",
              "counterfactual prediction")

    # ---- generation --------------------------------------------------------
    def _build_log(self, rng, n, b, kinds, machine, names, max_len):
        """Search for a short log that identifies every button.

        The search starts from the all-off pattern and first presses every pure
        toggle twice.  That both reveals the toggle set and proves the button
        is unconditional (a conditional with any condition light does nothing
        in the all-off state).  A depth-first search then adds presses until:

        * the conditional has been pressed at least twice, always while its
          condition light is on, and the intersection of the on-lights of those
          before-states is exactly its condition light (so the condition is
          uniquely inferable without ever observing the off behaviour);
        * the branch button has been seen in both condition states and its
          condition light is the unique light that predicts which set it used;
        * the rotate button has been seen in a non-uniform state;
        * every button appears at least once.

        Returns a list of (button_index, before_mask, after_mask) or None.
        """
        toggle_ids = [i for i, k in enumerate(kinds) if k == "toggle"]
        cond_ids = [i for i, k in enumerate(kinds) if k == "cond"]
        rot_ids = [i for i, k in enumerate(kinds) if k == "rot"]
        branch_ids = [i for i, k in enumerate(kinds) if k == "branch"]

        state = 0
        prefix: list[tuple[int, int, int]] = []
        for i in toggle_ids:
            for _ in range(2):
                ns = _apply(machine[i], state, n)
                prefix.append((i, state, ns))
                state = ns

        nodes = 0
        node_limit = 200000

        def branch_predictor(recs, k):
            good = []
            for j in range(n):
                groups = {}
                valid = True
                for bef, aft in recs:
                    eff = bef ^ aft
                    val = (bef >> j) & 1
                    if val in groups and groups[val] != eff:
                        valid = False
                        break
                    groups[val] = eff
                if valid and len(groups) == 2 and groups[0] != groups[1]:
                    good.append(j)
            return good == [k]

        def goal(seq):
            if len(seq) < 4 or len(seq) > max_len:
                return False
            used = {i for i, _, _ in seq}
            if any(i not in used for i in range(b)):
                return False
            for ci in cond_ids:
                _, k, _ = machine[ci]
                recs = [(bef, aft) for i, bef, aft in seq if i == ci]
                if len(recs) < 2 or any(not ((bef >> k) & 1) for bef, _ in recs):
                    return False
                inter = None
                for bef, _ in recs:
                    on = {j for j in range(n) if (bef >> j) & 1}
                    inter = on if inter is None else inter & on
                if inter != {k}:
                    return False
            for bi in branch_ids:
                _, k, _, _ = machine[bi]
                recs = [(bef, aft) for i, bef, aft in seq if i == bi]
                onc = sum((bef >> k) & 1 for bef, _ in recs)
                offc = sum(not ((bef >> k) & 1) for bef, _ in recs)
                if not ((onc >= 1 and offc >= 2) or (onc >= 2 and offc >= 1)):
                    return False
                if not branch_predictor(recs, k):
                    return False
            for ri in rot_ids:
                recs = [(bef, aft) for i, bef, aft in seq if i == ri]
                if sum(bef not in (0, (1 << n) - 1) for bef, _ in recs) < 1:
                    return False
            return True

        def dfs(cur, seq):
            nonlocal nodes
            nodes += 1
            if nodes > node_limit:
                return None
            if len(seq) >= max_len:
                return seq if goal(seq) else None

            # Exact lower bound on the presses still needed; without this the
            # search wanders when one branch side is already complete.
            used = {i for i, _, _ in seq}
            need = sum(1 for i in range(b) if i not in used)
            for ci in cond_ids:
                c = sum(1 for i, _, _ in seq if i == ci)
                need += max(0, 2 - c)
            for bi in branch_ids:
                _, k, _, _ = machine[bi]
                onc = sum(1 for i, bef, _ in seq if i == bi and ((bef >> k) & 1))
                offc = sum(1 for i, bef, _ in seq if i == bi and not ((bef >> k) & 1))
                need += min(max(0, 1 - onc) + max(0, 2 - offc),
                            max(0, 2 - onc) + max(0, 1 - offc))
            for ri in rot_ids:
                c = sum(1 for i, bef, _ in seq if i == ri and bef not in (0, (1 << n) - 1))
                need += max(0, 1 - c)
            if need > max_len - len(seq):
                return None

            moves = []
            for i in range(b):
                kind = kinds[i]
                if kind == "cond":
                    _, k, _ = machine[i]
                    if not ((cur >> k) & 1):
                        continue  # never reveal the off-condition behaviour
                    c = sum(1 for j, _, _ in seq if j == i)
                    score = 10 if c < 2 else 0
                elif kind == "branch":
                    _, k, _, _ = machine[i]
                    on = (cur >> k) & 1
                    onc = sum(1 for j, bef, _ in seq if j == i and ((bef >> k) & 1))
                    offc = sum(1 for j, bef, _ in seq if j == i and not ((bef >> k) & 1))
                    score = 10 if (on and onc < 2) or (not on and offc < 2) else 0
                elif kind == "rot":
                    if cur in (0, (1 << n) - 1):
                        continue  # rotating a uniform pattern is a wasted no-op
                    c = sum(1 for j, bef, _ in seq if j == i and bef not in (0, (1 << n) - 1))
                    score = 10 if c < 1 else 0
                else:
                    score = 10 if i not in used else 0
                moves.append((-score, i))
            moves.sort()
            for _, i in moves:
                ns = _apply(machine[i], cur, n)
                res = dfs(ns, seq + [(i, cur, ns)])
                if res is not None:
                    return res
            return None

        return dfs(state, prefix)

    def _make_query(self, rng, n, b, kinds, machine, log, names, max_len):
        """Choose a new start, a sequence, and a target for the two questions."""
        cond_ids = [i for i, k in enumerate(kinds) if k == "cond"]
        log_starts = {bef for _, bef, _ in log}
        # New pattern: not the log's start and preferably not any logged state.
        for _ in range(200):
            qstart = rng.randrange(1 << n)
            if qstart == log[0][1]:
                continue
            if qstart in log_starts and rng.random() < 0.7:
                continue
            break
        else:
            qstart = rng.randrange(1 << n)

        seq_len = rng.randint(2, min(4, b + 1))
        seq = [rng.randrange(b) for _ in range(seq_len)]
        if cond_ids:
            # Put exactly one press of a conditional into the queried sequence,
            # at a state where its condition light is OFF.  Every logged press
            # of that button had the light on, so this is the generalisation
            # step.  Keeping it to a single press also stops the "assume it is
            # an unconditional toggle" mistake from cancelling out.
            ci = rng.choice(cond_ids)
            _, k, _ = machine[ci]
            others = [i for i in range(b) if i != ci]
            seq = [i for i in seq if i != ci]
            while len(seq) < seq_len - 1:
                seq.insert(rng.randrange(len(seq) + 1), rng.choice(others))
            m = qstart
            positions = []
            for pos in range(len(seq) + 1):
                if not ((m >> k) & 1):
                    positions.append(pos)
                if pos < len(seq):
                    m = _apply(machine[seq[pos]], m, n)
            if not positions:
                return None
            seq.insert(rng.choice(positions), ci)

        m = qstart
        for i in seq:
            m = _apply(machine[i], m, n)
        after = m
        if after == qstart:
            return None  # keep the pattern question non-trivial

        # The answer must really depend on the conditional's off behaviour:
        # compare with a variant in which every conditional is an unconditional
        # toggle of the same set.  If the final patterns agree, the query is not
        # testing the generalisation, so choose another one.
        if cond_ids:
            variant = [("toggle", beh[2]) if kinds[i] == "cond" else beh
                       for i, beh in enumerate(machine)]
            mv = qstart
            for i in seq:
                mv = _apply(variant[i], mv, n)
            if mv == after:
                return None
        dist = _reachable(n, machine, qstart)
        # Target at a distance different from the given sequence length, so the
        # "count = length of the sequence" shortcut is wrong.
        candidates = [st for st, d in dist.items() if st != qstart and d != len(seq)]
        if not candidates:
            return None
        target = rng.choice(candidates)
        if target == after and rng.random() < 0.5:
            return None
        return qstart, seq, target

    def generate(self, seed: int, difficulty: int) -> Task:
        P = LOG_PARAMS[difficulty]
        rng = sub_rng(seed, difficulty, "machine")
        srng = sub_rng(seed, difficulty, "surface")
        n, b = P["n"], P["b"]

        for _ in range(300):
            kinds = list(P["kinds"])
            rng.shuffle(kinds)
            machine = [_sample_behavior(rng, kind, n) for kind in kinds]
            names = pseudo_words(srng, b, syllables=(2, 2))

            # A log start at all-off makes the probe phase meaningful.
            log = self._build_log(rng, n, b, kinds, machine, names, P["log"][1])
            if log is None:
                continue

            q = self._make_query(rng, n, b, kinds, machine, log, names, P["log"][1])
            if q is None:
                continue
            qstart, qseq, qtarget = q

            # Try the query; extend the log with distinguishing presses if the
            # current evidence leaves two possible answers.
            for _extend in range(8):
                evidence = {
                    "lights": n,
                    "buttons": names,
                    "kinds": list(P["kinds"]),
                    "start": _pattern(log[0][1], n),
                    "log": [
                        {"button": names[i], "before": _pattern(bef, n), "after": _pattern(aft, n)}
                        for i, bef, aft in log
                    ],
                }
                query = {
                    "start": _pattern(qstart, n),
                    "sequence": [names[i] for i in qseq],
                    "target": _pattern(qtarget, n),
                }
                sols = _solve_log(evidence, query)
                if sols is not None and len(sols) == 1:
                    after, dist = next(iter(sols))
                    answer = f"{_pattern(after, n)}, {dist}"
                    hidden = {
                        "kinds": {names[i]: kinds[i] for i in range(b)},
                        "machine": [[names[i]] + list(machine[i]) for i in range(b)],
                        "start": _pattern(log[0][1], n),
                        "target": _pattern(qtarget, n),
                    }
                    prompt = self._render(srng, evidence, query, difficulty)
                    return Task(self.name, seed, difficulty, evidence, query, prompt, answer, hidden)
                # Counterexample extension: try a press from the current end
                # state that reduces the answer set, without violating the
                # conditional generalisation.
                if len(log) >= P["log"][1]:
                    break
                state = log[-1][2]
                best = None
                for i in range(b):
                    if kinds[i] == "cond":
                        _, k, _ = machine[i]
                        if not ((state >> k) & 1):
                            continue  # would reveal the off behaviour
                    trial = log + [(i, state, _apply(machine[i], state, n))]
                    ev2 = dict(evidence)
                    ev2["log"] = [
                        {"button": names[j], "before": _pattern(bef, n), "after": _pattern(aft, n)}
                        for j, bef, aft in trial
                    ]
                    s2 = _solve_log(ev2, query)
                    score = 99 if s2 is None else len(s2)
                    if best is None or score < best[0]:
                        best = (score, trial)
                if best is None:
                    break
                log = best[1]
        raise RuntimeError(f"light_machine_log: no identifiable task for seed={seed} d={difficulty}")

    # ---- rendering ---------------------------------------------------------
    def _render(self, rng, ev, q, difficulty) -> str:
        n = ev["lights"]
        names = ev["buttons"]
        counts = _kind_counts(ev["kinds"])
        parts = []
        for kind in KINDS:
            c = counts.get(kind, 0)
            if not c:
                continue
            noun = {"toggle": "pure toggle", "cond": "conditional button",
                    "rot": "rotate button", "branch": "branch button"}[kind]
            if c > 1:
                noun = {"toggle": "pure toggles", "cond": "conditional buttons",
                        "rot": "rotate buttons", "branch": "branch buttons"}[kind]
            parts.append(f"{c} {noun}")
        type_text = ", ".join(parts)
        intro = rng.choice([
            "A log from an unfamiliar light machine has been recovered.",
            "An engineer left notes from experiments on a strange console.",
            "You found a recorded session with a machine whose buttons are unlabelled.",
        ])
        lines = [
            intro,
            f"It has {n} lights ('#' on, '.' off) and {len(names)} buttons named "
            + ", ".join(names) + ".",
            "",
            f"Each button has exactly one fixed kind of behaviour. This machine has {type_text}.",
            "The allowed kinds are:",
        ]
        for kind in KINDS:
            if counts.get(kind, 0):
                lines.append(f"- {KIND_WORDS[kind]}")
        lines += [
            "",
            "The log starts from the start pattern; each numbered line (or table row) is one press.",
            "A press may leave the pattern unchanged.",
        ]
        style = rng.choice(["list", "table"])
        if style == "list":
            lines.append(f"Start: {ev['start']}")
            for i, rec in enumerate(ev["log"], 1):
                lines.append(f"{i}. PRESS {rec['button']} -> {rec['after']}")
        else:
            lines.append("| step | action | resulting pattern |")
            lines.append("|---|---|---|")
            lines.append(f"| 0 | (start) | {ev['start']} |")
            for i, rec in enumerate(ev["log"], 1):
                lines.append(f"| {i} | PRESS {rec['button']} | {rec['after']} |")
        lines += [
            "",
            "A new experiment starts from a different pattern.",
            f"New start: {q['start']}",
            "Question 1: what is the pattern after pressing this sequence? "
            + ", ".join(f"PRESS {name}" for name in q["sequence"]),
            f"Question 2: from the same new start, what is the minimum number of presses needed to reach {q['target']}? "
            "You may press any buttons in any order.",
            "",
            "The queried sequence may press a button in a situation that never occurred in the log;",
            "use the inferred rule rather than replaying the last observed effect.",
            "",
            ANSWER_INSTRUCTION.format(fmt="<pattern>, <minimum number of presses>"),
        ]
        return "\n".join(lines)

    # ---- solver & shortcuts ------------------------------------------------
    def solve(self, evidence, query) -> set[str]:
        n = evidence["lights"]
        res = _solve_log(evidence, query)
        if res is None:
            return set()
        return _answers_to_strings(res, n)

    def shortcuts(self, evidence, query) -> dict[str, str]:
        n, names, obs, qstart, qseq, qtarget, kinds = _decode_evidence(evidence, query)
        # no_change: pretend buttons do nothing
        no_change = f"{_pattern(qstart, n)}, {len(qseq)}"
        # last_logged_effect: replay each button's last observed toggle set,
        # ignoring conditions.
        last = {}
        for i, recs in enumerate(obs):
            if recs:
                b, a = recs[-1]
                last[i] = b ^ a
        m = qstart
        for i in qseq:
            m ^= last.get(i, 0)
        last_effect = f"{_pattern(m, n)}, {len(qseq)}"
        # sequence_length: the lazy count is just the length of the given sequence
        seq_len = f"{_pattern(qstart, n)}, {len(qseq)}"
        # copy_first_logged_after: copy the pattern after the first logged press
        first_after = _pattern(_mask(evidence["log"][0]["after"]), n) if evidence["log"] else _pattern(qstart, n)
        copy_first = f"{first_after}, {len(qseq)}"
        return {
            "no_change": no_change,
            "last_logged_effect": last_effect,
            "sequence_length": seq_len,
            "copy_first_logged_after": copy_first,
        }