File size: 35,545 Bytes
d9c109c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
"""ARC-style grid transformations with an invented operation language.

A hidden program of 1..D operations (geometry, recolouring, gravity, extension,
cropping, filling, scaling, mirror completion) turns each example input grid into
its output.  The model must induce the program from a handful of pairs and apply
it to a new grid.

Design points:
  * The operation language, its parameter ranges, the depth budget and the
    "no hidden no-op" rule are stated in the prompt; only the program is hidden.
  * Identifiability is checked by an independent BFS over *joint states* (all
    example grids plus the query grid), with states deduplicated by value.  Any
    operation that fails to change every example grid is excluded by the stated
    rule, which keeps the search tiny.
  * Counterexamples are added by CEGIS: an alternative consistent program is
    reconstructed and a new input that separates it from the truth is appended.
  * The query always has a size no example input has, so "copy the nearest
    example output", identity and majority-output shortcuts cannot work.
  * Semantics (program/pairs) and surface (wording/layout) use separate RNG
    streams; examples are shuffled before rendering.

Generalisation axes (each query exercises at least one):
  * unseen grid size (query size differs from every example input size);
  * unseen arrangement of colours / objects (random independent grid);
  * operations composed into a longer pipeline than any single example reveals
    (depth at the difficulty's budget).
"""
from __future__ import annotations

import itertools
from collections import Counter

from ..core import ANSWER_INSTRUCTION, MAX_PROMPT_CHARS, Task, TaskFamily, sub_rng

Grid = tuple[tuple[int, ...], ...]
MAX_DIM = 14  # stated in the prompt: no intermediate grid is larger than this

PARAMS = {
    1: dict(D=1, sizes=(3, 4), ncol=(2, 3), nex=2, max_ex=5, max_recol=1,
            groups=("geometry", "recolour", "gravity")),
    2: dict(D=1, sizes=(3, 5), ncol=(2, 4), nex=3, max_ex=5, max_recol=1,
            groups=("geometry", "recolour", "gravity", "extend", "crop",
                    "fill", "scale", "mirror")),
    3: dict(D=2, sizes=(4, 6), ncol=(3, 4), nex=3, max_ex=5, max_recol=2,
            groups=("geometry", "recolour", "gravity", "extend", "crop",
                    "fill", "scale", "mirror")),
    4: dict(D=2, sizes=(4, 7), ncol=(3, 5), nex=3, max_ex=5, max_recol=2,
            groups=("geometry", "recolour", "gravity", "extend", "crop",
                    "fill", "scale", "mirror")),
    5: dict(D=3, sizes=(5, 7), ncol=(3, 5), nex=4, max_ex=5, max_recol=2,
            groups=("geometry", "recolour", "gravity", "extend", "crop",
                    "fill", "scale", "mirror")),
}

DIRS = ("up", "down", "left", "right")
GEOMETRY = ("rot", "flip", "transpose")


# ---- primitive grid operations ------------------------------------------------
def _grid(g: Grid) -> Grid:
    return tuple(tuple(int(v) for v in row) for row in g)


def _rot90(g: Grid) -> Grid:
    return tuple(zip(*g[::-1]))


def _rot180(g: Grid) -> Grid:
    return _rot90(_rot90(g))


def _rot270(g: Grid) -> Grid:
    return _rot90(_rot180(g))


def _flip_lr(g: Grid) -> Grid:
    return tuple(tuple(row[::-1]) for row in g)


def _flip_tb(g: Grid) -> Grid:
    return tuple(reversed(g))


def _transpose(g: Grid) -> Grid:
    return tuple(zip(*g))


def _gravity(g: Grid, direction: str) -> Grid:
    h, w = len(g), len(g[0])
    out = [[0] * w for _ in range(h)]
    if direction in ("up", "down"):
        for c in range(w):
            vals = [g[r][c] for r in range(h) if g[r][c] != 0]
            start = 0 if direction == "up" else h - len(vals)
            for i, v in enumerate(vals):
                out[start + i][c] = v
    else:
        for r in range(h):
            vals = [v for v in g[r] if v != 0]
            start = 0 if direction == "left" else w - len(vals)
            for i, v in enumerate(vals):
                out[r][start + i] = v
    return tuple(tuple(row) for row in out)


def _extend(g: Grid, colour: int, direction: str) -> Grid:
    h, w = len(g), len(g[0])
    out = [list(row) for row in g]
    dr = {"up": -1, "down": 1, "left": 0, "right": 0}[direction]
    dc = {"up": 0, "down": 0, "left": -1, "right": 1}[direction]
    for r in range(h):
        for c in range(w):
            if g[r][c] != colour:
                continue
            rr, cc = r + dr, c + dc
            # stop at the first cell that was non-empty in the original grid
            while 0 <= rr < h and 0 <= cc < w and g[rr][cc] == 0:
                out[rr][cc] = colour
                rr += dr
                cc += dc
    return tuple(tuple(row) for row in out)


def _crop(g: Grid) -> Grid:
    cells = [(r, c) for r in range(len(g)) for c in range(len(g[0])) if g[r][c] != 0]
    if not cells:
        return g
    r0 = min(r for r, _ in cells)
    r1 = max(r for r, _ in cells)
    c0 = min(c for _, c in cells)
    c1 = max(c for _, c in cells)
    return tuple(tuple(g[r][c0:c1 + 1]) for r in range(r0, r1 + 1))


def _fill(g: Grid, colour: int) -> Grid:
    h, w = len(g), len(g[0])
    seen = [[False] * w for _ in range(h)]
    stack = []
    for r in range(h):
        for c in (0, w - 1):
            if g[r][c] == 0 and not seen[r][c]:
                seen[r][c] = True
                stack.append((r, c))
    for c in range(w):
        for r in (0, h - 1):
            if g[r][c] == 0 and not seen[r][c]:
                seen[r][c] = True
                stack.append((r, c))
    while stack:
        r, c = stack.pop()
        for nr, nc in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
            if 0 <= nr < h and 0 <= nc < w and g[nr][nc] == 0 and not seen[nr][nc]:
                seen[nr][nc] = True
                stack.append((nr, nc))
    out = [list(row) for row in g]
    for r in range(h):
        for c in range(w):
            if g[r][c] == 0 and not seen[r][c]:
                out[r][c] = colour
    return tuple(tuple(row) for row in out)


def _scale(g: Grid) -> Grid:
    out = []
    for row in g:
        doubled = []
        for v in row:
            doubled.extend((v, v))
        out.append(tuple(doubled))
        out.append(tuple(doubled))
    return tuple(out)


def _mirror(g: Grid, axis: str) -> Grid:
    h, w = len(g), len(g[0])
    out = [list(row) for row in g]
    if axis == "lr":
        for r in range(h):
            for c in range(w // 2):
                out[r][w - 1 - c] = out[r][c]
    else:
        for r in range(h // 2):
            for c in range(w):
                out[h - 1 - r][c] = out[r][c]
    return tuple(tuple(row) for row in out)


def _recolour(g: Grid, pairs) -> Grid:
    # Simultaneous: look up the *original* value, so swaps are well defined.
    # Small fixed-size table avoids a dict lookup per cell (this is the hottest
    # primitive during the brute-force search).
    mp = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
    if len(pairs) == 1:
        a, b = pairs[0]
        if a == b:
            return g
        return tuple(tuple(b if v == a else v for v in row) for row in g)
    mp = list(mp)
    for a, b in pairs:
        mp[a] = b
    return tuple(tuple(mp[v] for v in row) for row in g)


def _apply(op, g: Grid) -> Grid:
    kind = op[0]
    if kind == "rot":
        return {90: _rot90, 180: _rot180, 270: _rot270}[op[1]](g)
    if kind == "flip":
        return _flip_lr(g) if op[1] == "lr" else _flip_tb(g)
    if kind == "transpose":
        return _transpose(g)
    if kind == "recolour":
        return _recolour(g, op[1])
    if kind == "gravity":
        return _gravity(g, op[1])
    if kind == "extend":
        return _extend(g, op[1], op[2])
    if kind == "crop":
        return _crop(g)
    if kind == "fill":
        return _fill(g, op[1])
    if kind == "scale":
        return _scale(g)
    if kind == "mirror":
        return _mirror(g, op[1])
    raise ValueError(f"unknown op {op!r}")


def _run(prog, g: Grid) -> Grid:
    cur = g
    for op in prog:
        cur = _apply(op, cur)
    return cur


def _valid_trace(prog, g: Grid) -> bool:
    """The stated no-hidden-no-op rule, plus the stated size/non-empty bounds."""
    cur = g
    for op in prog:
        nxt = _apply(op, cur)
        if nxt == cur:                     # hidden no-op -> not a legal program
            return False
        if not nxt or not nxt[0]:          # empty grid
            return False
        if len(nxt) > MAX_DIM or len(nxt[0]) > MAX_DIM:
            return False
        if not any(v != 0 for row in nxt for v in row):
            return False
        cur = nxt
    return True


def _grid_str(g: Grid) -> str:
    return "/".join("".join(str(v) for v in row) for row in g)


def _grid_list(g: Grid):
    return [[int(v) for v in row] for row in g]


def _grid_dim(g) -> tuple[int, int]:
    return len(g), len(g[0])


def _op_dims(op, dims):
    """Shape effect of an operation, or None when it depends on the contents
    (crop). Used only as a sound prefilter."""
    h, w = dims
    kind = op[0]
    if kind == "transpose" or (kind == "rot" and op[1] in (90, 270)):
        return w, h
    if kind in ("rot", "flip", "gravity", "recolour", "extend", "fill", "mirror"):
        return h, w
    if kind == "scale":
        return 2 * h, 2 * w
    return None  # crop


# ---- operation enumeration for the brute-force solver -------------------------
def _allowed_kinds(groups) -> set[str]:
    out = set()
    for grp in groups:
        if grp == "geometry":
            out.update(GEOMETRY)
        else:
            out.add(grp)
    return out


def _ops_for_state(state, n_ex, palette, allowed, max_recol):
    """Every operation that could change *every* example grid in this state.

    Parameters range over the palette exactly as the prompt states; sources are
    restricted to colours present in the examples, because an operation whose
    source is absent cannot change them.
    """
    present = sorted({v for g in state[:n_ex] for row in g for v in row})
    ops = []
    if "rot" in allowed:
        ops += [("rot", 90), ("rot", 180), ("rot", 270)]
    if "flip" in allowed:
        ops += [("flip", "lr"), ("flip", "tb")]
    if "transpose" in allowed:
        ops.append(("transpose",))
    if "recolour" in allowed:
        for a in present:
            for b in palette:
                if a != b:
                    ops.append(("recolour", ((a, b),)))
        if max_recol >= 2:  # a swap uses two simultaneous mappings
            for a, b in itertools.combinations(present, 2):
                ops.append(("recolour", ((a, b), (b, a))))
    if "gravity" in allowed:
        ops += [("gravity", d) for d in DIRS]
    if "extend" in allowed:
        for c in present:
            if c != 0:
                ops += [("extend", c, d) for d in DIRS]
    if "crop" in allowed:
        ops.append(("crop",))
    if "fill" in allowed:
        ops += [("fill", c) for c in palette if c != 0]
    if "scale" in allowed:
        ops.append(("scale",))
    if "mirror" in allowed:
        ops += [("mirror", "lr"), ("mirror", "tb")]
    return ops


def _reachable_dims(target, allowed, steps):
    """Dimension abstraction used for a sound prune: which (h, w) can still be
    turned into `target` by at most `steps` legal operations?  The abstraction
    over-approximates (it ignores cell contents), so pruning with it is sound."""
    th, tw = target
    cur = {(th, tw)}          # r = 0
    levels = [set(cur)]
    for _ in range(steps):
        pre = set(cur)        # shape-preserving operations
        if "rot" in allowed or "transpose" in allowed:
            pre.update((w, h) for h, w in cur)   # a rotation/transpose can swap
        if "scale" in allowed:
            pre.update((h // 2, w // 2) for h, w in cur if h % 2 == 0 and w % 2 == 0)
        if "crop" in allowed:
            for h, w in cur:
                for H in range(h, MAX_DIM + 1):
                    for W in range(w, MAX_DIM + 1):
                        pre.add((H, W))
        cur = pre
        levels.append(set(cur))
    return levels          # levels[r] = dims that can reach target in <= r steps


def _search(ex_in, ex_out, q_in, D, palette, groups, max_recol, limit=2):
    """BFS over joint states. Returns {answer: program path} for every consistent
    program of length <= D, stopping once `limit` different answers exist."""
    allowed = _allowed_kinds(groups)
    n_ex = len(ex_in)
    start = tuple(ex_in) + (q_in,)
    seen = {start}
    parent = {}
    frontier = [start]
    answers: dict[str, tuple] = {}
    cache: dict[tuple, Grid] = {}
    dim_ok = [_reachable_dims(_grid_dim(t), allowed, D) for t in ex_out]
    # which target dims are possible on the query side is unconstrained (there is
    # no labelled output for the query), so it never prunes.

    def app(op, g):
        key = (op, g)
        if key not in cache:
            cache[key] = _apply(op, g)
        return cache[key]

    def path_of(state):
        path = []
        cur = state
        while cur != start:
            prev, op = parent[cur]
            path.append(op)
            cur = prev
        path.reverse()
        return tuple(path)

    for depth in range(1, D + 1):
        remaining = D - depth
        nxt_front = []
        for state in frontier:
            sdims = [_grid_dim(g) for g in state]
            for op in _ops_for_state(state, n_ex, palette, allowed, max_recol):
                # cheap dimension prefilter: skip an operation whose (known)
                # shape effect cannot reach the target within the budget
                bad = False
                for i in range(n_ex):
                    d = _op_dims(op, sdims[i])
                    if d is not None and d not in dim_ok[i][remaining]:
                        bad = True
                        break
                if bad:
                    continue
                nxt = tuple(app(op, g) for g in state)
                # the prompt says every operation changes every example grid
                if any(nxt[i] == state[i] for i in range(n_ex)):
                    continue
                ok = True
                for i in range(n_ex):
                    g = nxt[i]
                    if not g or not g[0] or len(g) > MAX_DIM or len(g[0]) > MAX_DIM:
                        ok = False
                        break
                    if _grid_dim(g) not in dim_ok[i][remaining]:
                        ok = False
                        break
                if not ok:
                    continue
                if any(not any(v != 0 for row in g for v in row) for g in nxt):
                    continue
                hit = all(nxt[i] == ex_out[i] for i in range(n_ex))
                if hit:
                    ans = _grid_str(nxt[-1])
                    if ans not in answers:
                        answers[ans] = path_of(state) + (op,)
                        if len(answers) >= limit:
                            return answers
                if remaining == 0:
                    continue          # nothing can be extended further
                if nxt in seen:
                    continue
                seen.add(nxt)
                parent[nxt] = (state, op)
                nxt_front.append(nxt)
        frontier = nxt_front
        if not frontier:
            break
    return answers


# ---- random grid generation ---------------------------------------------------
def _inside_hole(r, c, hole) -> bool:
    if hole is None:
        return False
    r0, c0, h, w = hole
    return r0 < r < r0 + h - 1 and c0 < c < c0 + w - 1


def _place_object(g, rng, size, colour, off, work, hole) -> None:
    kind = rng.choices(("single", "box", "line", "blob"),
                       weights=(2, 3, 3, 3), k=1)[0]
    cells = set()
    if kind == "single":
        cells.add((off + rng.randrange(work), off + rng.randrange(work)))
    elif kind == "line":
        length = rng.randint(2, max(2, min(work, 4)))
        if rng.random() < 0.5:
            r0 = off + rng.randrange(work)
            c0 = off + rng.randrange(max(1, work - length + 1))
            cells.update((r0, c0 + i) for i in range(length))
        else:
            r0 = off + rng.randrange(max(1, work - length + 1))
            c0 = off + rng.randrange(work)
            cells.update((r0 + i, c0) for i in range(length))
    elif kind == "box":
        h = rng.randint(1, min(3, work))
        w = rng.randint(1, min(3, work))
        r0 = off + rng.randrange(work - h + 1)
        c0 = off + rng.randrange(work - w + 1)
        cells.update((r, c) for r in range(r0, r0 + h) for c in range(c0, c0 + w))
    else:  # connected random walk
        r = off + rng.randrange(work)
        c = off + rng.randrange(work)
        for _ in range(rng.randint(2, max(2, min(work * work, 6)))):
            cells.add((r, c))
            dr, dc = rng.choice(((0, 1), (0, -1), (1, 0), (-1, 0)))
            r = min(max(r + dr, off), off + work - 1)
            c = min(max(c + dc, off), off + work - 1)
    for r, c in cells:
        if not _inside_hole(r, c, hole):
            g[r][c] = colour


def _random_grid(rng, size, palette):
    """Sparse objects (20-45% non-zero), every palette colour present, sometimes
    an enclosed hole so that `fill enclosed` is usable."""
    colours = [c for c in palette if c != 0]
    for _ in range(250):
        g = [[0] * size for _ in range(size)]
        margin = rng.choice((0, 0, 0, 1, 1, 2)) if size >= 4 else 0
        work = max(1, size - margin)
        off = rng.randint(0, size - work)

        hole = None
        if size >= 5 and rng.random() < 0.5:
            h = rng.randint(3, min(4, work))
            w = rng.randint(3, min(4, work))
            r0 = off + rng.randint(0, work - h)
            c0 = off + rng.randint(0, work - w)
            colour = rng.choice(colours)
            for c in range(c0, c0 + w):
                g[r0][c] = colour
                g[r0 + h - 1][c] = colour
            for r in range(r0, r0 + h):
                g[r][c0] = colour
                g[r][c0 + w - 1] = colour
            hole = (r0, c0, h, w)

        for _ in range(rng.randint(1, 3)):
            _place_object(g, rng, size, rng.choice(colours), off, work, hole)

        # all palette colours must appear (keeps recolouring meaningful)
        for colour in colours:
            if not any(colour in row for row in g):
                for _ in range(80):
                    r = off + rng.randrange(work)
                    c = off + rng.randrange(work)
                    if not _inside_hole(r, c, hole):
                        g[r][c] = colour
                        break

        density = sum(v != 0 for row in g for v in row) / (size * size)
        if 0.20 <= density <= 0.45:
            return tuple(tuple(row) for row in g)
    return None


def _make_pool(rng, P, palette, n=700):
    lo, hi = P["sizes"]
    sizes = list(range(lo, hi + 1))
    pool = []
    for _ in range(n):
        size = rng.choice(sizes)
        g = _random_grid(rng, size, palette)
        if g is not None:
            pool.append(g)
    return pool


# ---- program sampling ---------------------------------------------------------
def _sample_op(rng, kind, palette, max_recol):
    if kind == "rot":
        return ("rot", rng.choice((90, 180, 270)))
    if kind == "flip":
        return ("flip", rng.choice(("lr", "tb")))
    if kind == "transpose":
        return ("transpose",)
    if kind == "recolour":
        if max_recol >= 2 and rng.random() < 0.35:
            a, b = rng.sample(palette, 2)
            return ("recolour", ((a, b), (b, a)))
        a = rng.choice(palette)
        b = rng.choice([c for c in palette if c != a])
        return ("recolour", ((a, b),))
    if kind == "gravity":
        return ("gravity", rng.choice(DIRS))
    if kind == "extend":
        colour = rng.choice([c for c in palette if c != 0])
        return ("extend", colour, rng.choice(DIRS))
    if kind == "crop":
        return ("crop",)
    if kind == "fill":
        return ("fill", rng.choice([c for c in palette if c != 0]))
    if kind == "scale":
        return ("scale",)
    if kind == "mirror":
        return ("mirror", rng.choice(("lr", "tb")))
    raise ValueError(kind)


def _sample_program(rng, palette, P):
    kinds = sorted(_allowed_kinds(P["groups"]))
    prog = []
    for _ in range(P["D"]):
        for _ in range(30):
            op = _sample_op(rng, rng.choice(kinds), palette, P["max_recol"])
            if prog and op == prog[-1]:
                continue
            break
        else:
            return None
        prog.append(op)
    return tuple(prog)


# ---- solver for the counterexample loop ---------------------------------------
def _separates(alt_prog, true_prog, g) -> bool:
    """True if `g` rules the alternative program out under the stated language."""
    cur = g
    for op in alt_prog:
        nxt = _apply(op, cur)
        if nxt == cur:                       # illegal no-op on this example
            return True
        if not nxt or not nxt[0] or len(nxt) > MAX_DIM or len(nxt[0]) > MAX_DIM:
            return True
        if not any(v != 0 for row in nxt for v in row):
            return True
        cur = nxt
    return cur != _run(true_prog, g)


class GridRules(TaskFamily):
    name = "grid_rules"
    skills = ("grid transformations", "program induction", "spatial reasoning",
              "composition", "counterexample reasoning")

    # ---- task construction -------------------------------------------------
    def _try_build(self, rng, prog, palette, P, pool):
        valid = [g for g in pool if _valid_trace(prog, g)]
        if len(valid) < P["nex"] + 1:
            return None

        lo, hi = P["sizes"]
        qsizes = list(range(lo, hi + 1))
        rng.shuffle(qsizes)
        qsize = ex_size = None
        candidates = []
        for qs in qsizes:
            others = [g for g in valid if len(g) != qs]
            any_of_size = [g for g in pool if len(g) == qs]
            if len(others) >= P["nex"] and any_of_size:
                qsize = qs
                candidates = others
                break
        if qsize is None:
            return None

        # query: fresh grid of an unseen size (need not be a valid trace; the
        # no-op rule only constrains the labelled examples)
        query = rng.choice([g for g in pool if len(g) == qsize])
        truth_ans = _grid_str(_run(prog, query))
        if _run(prog, query) == query:
            return None

        # initial examples, preferring different sizes and different grids
        by_size = {}
        for g in candidates:
            by_size.setdefault(len(g), []).append(g)
        for v in by_size.values():
            rng.shuffle(v)
        order_sizes = sorted(by_size)
        rng.shuffle(order_sizes)
        examples = []
        for s in order_sizes:
            if len(examples) >= P["nex"]:
                break
            examples.append(by_size[s].pop())
        remaining = [g for s in order_sizes for g in by_size[s]]
        rng.shuffle(remaining)
        while len(examples) < P["nex"] and remaining:
            examples.append(remaining.pop())
        if len(examples) < P["nex"]:
            return None
        rng.shuffle(examples)

        used = set(examples) | {query}
        extra_pool = [g for g in pool if g not in used]

        for _ in range(14):
            ex_out = [_run(prog, g) for g in examples]
            res = _search(examples, ex_out, query, P["D"], palette, P["groups"],
                          P["max_recol"], limit=2)
            if len(res) == 1:
                only = next(iter(res))
                if only != truth_ans:
                    return None
                break
            if not res:
                return None
            alt_ans = next(a for a in res if a != truth_ans)
            alt_prog = res[alt_ans]
            if len(examples) >= P["max_ex"]:
                return None

            pick = None
            for g in extra_pool:
                if g in used:
                    continue
                if _separates(alt_prog, prog, g):
                    pick = g
                    break
            if pick is None:
                # random search for a counterexample
                for _ in range(400):
                    g = _random_grid(rng, rng.choice(list(range(lo, hi + 1))), palette)
                    if g is None or g in used:
                        continue
                    if not _valid_trace(prog, g):
                        continue
                    extra_pool.append(g)
                    if _separates(alt_prog, prog, g):
                        pick = g
                        break
            if pick is None:
                return None
            examples.append(pick)
            used.add(pick)
        else:
            return None

        # anti-shortcut check: no lazy answer may equal the truth on this query
        out_now = [_run(prog, g) for g in examples]
        if truth_ans in self._lazy_answers(examples, out_now, query):
            return None
        return examples, query, truth_ans

    @staticmethod
    def _ex_out(examples, prog):
        return [{"input": _grid_list(g), "output": _grid_list(_run(prog, g))}
                for g in examples]

    # ---- generation --------------------------------------------------------
    def generate(self, seed: int, difficulty: int) -> Task:
        P = PARAMS[difficulty]
        rng = sub_rng(seed, difficulty, "program")
        srng = sub_rng(seed, difficulty, "surface")
        built = None
        for _palette_try in range(30):
            ncol = rng.randint(*P["ncol"])
            palette = [0] + sorted(rng.sample(range(1, 10), ncol))
            pool = _make_pool(rng, P, palette)
            for _ in range(120):
                prog = _sample_program(rng, palette, P)
                if prog is None:
                    continue
                got = self._try_build(rng, prog, palette, P, pool)
                if got is not None:
                    examples, query, answer = got
                    built = (prog, palette, examples, query, answer)
                    break
            if built is not None:
                break
        if built is None:
            raise RuntimeError(f"grid_rules: no identifiable task for seed={seed} d={difficulty}")

        prog, palette, examples, query, answer = built
        ev_examples = self._ex_out(examples, prog)
        evidence = {
            "max_depth": P["D"],
            "max_recolour": P["max_recol"],
            "max_dim": MAX_DIM,
            "palette": palette,
            "groups": list(P["groups"]),
            "examples": ev_examples,
        }
        query_ev = {"input": _grid_list(query)}
        prompt = self._render(srng, evidence, query_ev)
        if len(prompt) > MAX_PROMPT_CHARS[difficulty]:
            # extremely rare (only very large scaled grids); re-roll surface is
            # not enough, so rebuild with a fresh program stream.
            return self.generate(seed + 7919, difficulty)

        hidden = {
            "program": [[op[0]] + [list(x) if isinstance(x, tuple) else x for x in op[1:]]
                        for op in prog],
            "palette": palette,
        }
        return Task(self.name, seed, difficulty, evidence, query_ev, prompt, answer, hidden)

    # ---- rendering ---------------------------------------------------------
    def _render(self, rng, ev, q) -> str:
        D = ev["max_depth"]
        palette = ev["palette"]
        groups = set(ev["groups"])
        intro = rng.choice([
            "An unknown machine rewrites grids of coloured digits.",
            "A hidden procedure maps each input grid to an output grid.",
            "Each grid below is transformed by the same hidden sequence of operations.",
        ])
        steps = "exactly one operation" if D == 1 else f"a sequence of 1 to {D} operations"
        lines = [intro, ""]
        lines.append("Digits are colours; 0 is the empty background. The transformation is "
                     f"{steps}. Operations are applied in order, and each operation changes at "
                     "least one cell in every example grid at the moment it is applied (no hidden "
                     "no-op steps).")
        lines.append("")
        lines.append("The operations are:")
        if "geometry" in groups:
            lines.append("- rotate 90, 180 or 270 degrees clockwise")
            lines.append("- flip the grid left-right")
            lines.append("- flip the grid top-bottom")
            lines.append("- transpose (swap rows and columns)")
        if "recolour" in groups:
            extra = (" At this difficulty a recolour may instead swap two colours: x -> y and "
                     "y -> x at the same time.") if ev["max_recolour"] >= 2 else ""
            lines.append("- recolour x -> y: every cell of colour x becomes y. Here x and y are "
                         "any palette digits (x may be 0, the background)." + extra)
        if "gravity" in groups:
            lines.append("- gravity up/down/left/right: every non-zero cell slides as far as possible "
                         "in that direction; cells in the same column (for up/down) or row (for "
                         "left/right) keep their relative order")
        if "extend" in groups:
            lines.append("- extend c up/down/left/right: every cell that already has the non-zero "
                         "colour c paints empty cells toward that border, stopping at the first cell "
                         "that is non-empty in the original grid")
        if "crop" in groups:
            lines.append("- crop: cut the grid down to the bounding box of all non-zero cells")
        if "fill" in groups:
            lines.append("- fill enclosed with c: every empty cell that is not connected to the border "
                         "through empty cells (4-connected: up, down, left, right) becomes the "
                         "non-zero colour c")
        if "scale" in groups:
            lines.append("- scale x2: each cell becomes a 2x2 block of the same colour")
        if "mirror" in groups:
            lines.append("- mirror-complete left-right: copy the left half onto the right half; "
                         "mirror-complete top-bottom: copy the top half onto the bottom half. When "
                         "there is an odd number of columns (or rows), the middle column (or row) "
                         "stays unchanged")
        lines.append("")
        lines.append(f"All colours are digits from this palette: {', '.join(str(x) for x in palette)} "
                     f"(0 is empty). No grid at any stage has more than {ev['max_dim']} rows or "
                     f"{ev['max_dim']} columns, and no grid becomes empty.")
        lines.append("")

        order = list(range(len(ev["examples"])))
        rng.shuffle(order)
        style = rng.choice(("blocks", "framed"))
        for k, i in enumerate(order, 1):
            ex = ev["examples"][i]
            lines.append(f"Example {k}:")
            if style == "blocks":
                lines.append("  input:")
                lines.extend("    " + "".join(str(v) for v in row) for row in ex["input"])
                lines.append("  output:")
                lines.extend("    " + "".join(str(v) for v in row) for row in ex["output"])
            else:
                lines.append("  before -> after")
                lines.extend("  | " + "".join(str(v) for v in row) for row in ex["input"])
                lines.append("  ----")
                lines.extend("  | " + "".join(str(v) for v in row) for row in ex["output"])
            lines.append("")

        lines.append("New input grid:")
        lines.append("")
        lines.extend("  " + "".join(str(v) for v in row) for row in q["input"])
        lines.append("")
        lines.append("Apply the same hidden sequence to this new input and give the resulting grid.")
        lines.append("Write the output rows joined by '/', with one digit per cell and no spaces.")
        lines.append("")
        lines.append(ANSWER_INSTRUCTION.format(fmt="<the output rows joined by />"))
        return "\n".join(lines)

    # ---- independent solver & shortcuts -----------------------------------
    def _decode(self, evidence, query):
        pal = [int(x) for x in evidence["palette"]]
        ex_in = [_grid(x["input"]) for x in evidence["examples"]]
        ex_out = [_grid(x["output"]) for x in evidence["examples"]]
        q_in = _grid(query["input"])
        return ex_in, ex_out, q_in

    def solve(self, evidence, query) -> set[str]:
        ex_in, ex_out, q_in = self._decode(evidence, query)
        res = _search(ex_in, ex_out, q_in, int(evidence["max_depth"]),
                      [int(x) for x in evidence["palette"]], evidence["groups"],
                      int(evidence["max_recolour"]), limit=2)
        return set(res)

    @staticmethod
    def _lazy_answers(ex_in, ex_out, q_in) -> set[str]:
        def similarity(a, b):
            if _grid_dim(a) != _grid_dim(b):
                return abs(len(a) - len(b)) + abs(len(a[0]) - len(b[0])) + 10
            return sum(x != y for ra, rb in zip(a, b) for x, y in zip(ra, rb))

        nearest = min(range(len(ex_in)), key=lambda i: (similarity(ex_in[i], q_in), i))
        counts = Counter(_grid_str(g) for g in ex_out)
        most = counts.most_common(1)[0][0]
        return {_grid_str(q_in), _grid_str(ex_out[nearest]), most}

    def shortcuts(self, evidence, query) -> dict[str, str]:
        ex_in = [_grid(x["input"]) for x in evidence["examples"]]
        ex_out = [_grid(x["output"]) for x in evidence["examples"]]
        q_in = _grid(query["input"])
        lazy = self._lazy_answers(ex_in, ex_out, q_in)
        # stable order for reporting
        ident = _grid_str(q_in)

        def similarity(a, b):
            if _grid_dim(a) != _grid_dim(b):
                return abs(len(a) - len(b)) + abs(len(a[0]) - len(b[0])) + 10
            return sum(x != y for ra, rb in zip(a, b) for x, y in zip(ra, rb))

        nearest = min(range(len(ex_in)), key=lambda i: (similarity(ex_in[i], q_in), i))
        counts = Counter(_grid_str(g) for g in ex_out)
        most = counts.most_common(1)[0][0]
        assert lazy == {ident, _grid_str(ex_out[nearest]), most}
        return {
            "identity": ident,
            "copy_nearest_output": _grid_str(ex_out[nearest]),
            "most_common_output": most,
        }

    # ---- scoring -----------------------------------------------------------
    def split_items(self, answer: str) -> list[str]:
        return [x for x in answer.strip().split("/") if x != ""]

    def normalize_item(self, item: str) -> str:
        return "".join(item.split())

    def score(self, task: Task, response: str) -> float:
        from ..core import extract_answer
        pred = extract_answer(response)
        if pred is None:
            return 0.0
        gold = [self.normalize_item(x) for x in self.split_items(task.answer)]
        got = [self.normalize_item(x) for x in self.split_items(pred)]
        if len(gold) != len(got) or any(len(a) != len(b) for a, b in zip(gold, got)):
            return 0.0
        total = sum(len(r) for r in gold)
        if total == 0:
            return 0.0
        correct = sum(a == b for ga, gb in zip(gold, got) for a, b in zip(ga, gb))
        return 1.0 if correct == total else correct / total