File size: 24,458 Bytes
09c6e66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Deterministic video verifier for the t50–t53 Friction tutorial tasks.

The source composition and measured visual gates are in rubric.json. This
script only scores rendered pixels and harvested artifacts; it does not infer
success from the agent's narration or editor state.
"""
import argparse
from collections import deque
import json
import math
import os
from pathlib import Path
import shutil
import signal
import subprocess
import time

SPEC = json.loads((Path(__file__).parent / 'rubric.json').read_text())
TASK = SPEC['task_id']
W, H = SPEC['analysis_size']
N = W * H


def command(args):
    return subprocess.run(args, capture_output=True, check=True).stdout


def probe(path):
    data = json.loads(command(['ffprobe', '-v', 'error', '-show_streams',
                               '-show_format', '-of', 'json', str(path)]))
    stream = next(s for s in data['streams'] if s.get('codec_type') == 'video')
    a, b = stream['avg_frame_rate'].split('/')
    return {'width': stream['width'], 'height': stream['height'],
            'fps': float(a) / float(b),
            'duration': float(data['format']['duration'])}


def decode(path):
    raw = command(['ffmpeg', '-v', 'error', '-i', str(path), '-vf',
                   f'fps=8,scale={W}:{H}:flags=area', '-f', 'rawvideo',
                   '-pix_fmt', 'rgb24', '-'])
    size = N * 3
    if not raw or len(raw) % size:
        raise RuntimeError(f'Incomplete decode: {path}')
    return [raw[i:i+size] for i in range(0, len(raw), size)]


def mask(frame, color):
    result = bytearray(N)
    for p in range(N):
        r, g, b = frame[p*3:p*3+3]
        if color == 'blue':
            hit = b > 95 and b > r*1.25 and b >= g*.83
        elif color == 'green':
            hit = g > 95 and g > r*1.35 and g > b*1.03
        elif color == 'teal':
            hit = g > 85 and b > 85 and g > r*1.17 and b > r*1.17
        elif color == 'white':
            hit = min(r, g, b) > 180
        elif color == 'light':
            hit = min(r, g, b) > 55
        else:
            raise ValueError(color)
        result[p] = int(hit)
    return result


def components(bitmap, min_area=3):
    seen = bytearray(N)
    found = []
    for seed in range(N):
        if not bitmap[seed] or seen[seed]:
            continue
        q = deque([seed]); seen[seed] = 1
        count = sx = sy = 0
        x0 = W; y0 = H; x1 = y1 = 0
        while q:
            p = q.popleft(); x = p % W; y = p // W
            count += 1; sx += x; sy += y
            x0 = min(x0, x); x1 = max(x1, x)
            y0 = min(y0, y); y1 = max(y1, y)
            for other in (p-1 if x else -1, p+1 if x<W-1 else -1,
                          p-W if y else -1, p+W if y<H-1 else -1):
                if other >= 0 and bitmap[other] and not seen[other]:
                    seen[other] = 1; q.append(other)
        if count >= min_area:
            found.append({'area': count, 'cx': sx/count, 'cy': sy/count,
                          'bbox': [x0, y0, x1, y1]})
    return sorted(found, key=lambda c: c['area'], reverse=True)


def dark_fraction(frame):
    return sum(max(frame[p*3:p*3+3]) < 45 for p in range(N)) / N


def range_of(values):
    return max(values)-min(values) if values else 0


def native_project(path):
    if not path.exists() or path.stat().st_size < 1024:
        return False, 'Missing or undersized project'
    if not shutil.which('friction') or not shutil.which('Xvfb'):
        return False, 'Friction or Xvfb unavailable; native reopen not verified'
    display = f':{100 + os.getpid() % 10000}'
    server = subprocess.Popen(['Xvfb', display, '-screen', '0', '1280x800x24',
                               '-nolisten', 'tcp'], stdout=subprocess.DEVNULL,
                              stderr=subprocess.DEVNULL, start_new_session=True)
    time.sleep(.5)
    if server.poll() is not None:
        return False, 'Could not start isolated X display'
    env = os.environ.copy()
    env['DISPLAY'] = display
    process = subprocess.Popen(['friction', str(path)], env=env,
                               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                               start_new_session=True)
    try:
        time.sleep(4)
        running = process.poll() is None
        if running:
            os.killpg(process.pid, signal.SIGTERM)
    except ProcessLookupError:
        running = False
    try:
        output = process.communicate(timeout=5)[0].decode(errors='replace')
    except subprocess.TimeoutExpired:
        os.killpg(process.pid, signal.SIGKILL)
        output = process.communicate()[0].decode(errors='replace')
    try:
        os.killpg(server.pid, signal.SIGTERM)
    except ProcessLookupError:
        pass
    server.wait(timeout=5)
    opened = (running and 'Friction 1.' in output and
              'Error while reading' not in output and
              'Incompatible or incomplete data' not in output and
              'No such file' not in output)
    return opened, output[-1000:]


def contour_profile(bitmap):
    columns = []
    for x in range(W):
        rows = [y for y in range(H) if bitmap[y*W+x]]
        if rows:
            columns.append((x, sum(rows)/len(rows)))
    if len(columns) < 4:
        return [], None
    start, end = columns[0][0], columns[-1][0]
    low = min(y for _, y in columns)
    height = max(y for _, y in columns)-low
    if not height or end == start:
        return [], None
    profile = []
    for fraction in (0, .1, .2, .3, .4, .5, .6, .7, .8, .9, 1):
        target = start + fraction*(end-start)
        nearest = min(columns, key=lambda item: abs(item[0]-target))
        profile.append((nearest[1]-low)/height)
    return profile, len(columns)/(end-start+1)


def add(report, name, points, passed, detail, missing=False):
    status = 'missing' if missing else ('pass' if passed else 'fail')
    report['checks'].append({'name': name, 'points': points, 'status': status,
                             'earned': points if passed else 0, 'detail': detail})


def media(report, path, points_video=5, points_format=10):
    if not path.exists() or not path.stat().st_size:
        meta, frames = None, []
    else:
        try:
            meta, frames = probe(path), decode(path)
        except (subprocess.CalledProcessError, KeyError, StopIteration, ValueError,
                RuntimeError):
            meta, frames = None, []
    add(report, f'{path.name}: readable export', points_video, bool(meta and frames),
        meta, missing=not path.exists())
    fmt = bool(meta and meta['width'] == SPEC['output_size'][0]
               and meta['height'] == SPEC['output_size'][1]
               and abs(meta['fps']-SPEC['output_fps']) < .05
               and abs(meta['duration']-SPEC['output_duration_sec'])
               <= max(.09, 2/SPEC['output_fps']))
    add(report, f'{path.name}: source composition format', points_format, fmt,
        {'expected': [SPEC['output_size'], SPEC['output_fps'],
                      SPEC['output_duration_sec']], 'actual': meta}, missing=not meta)
    return frames


def grade_t50(report, frames):
    if not frames:
        for name, pts in [('Blue center, green satellites on black',20),
                          ('Orbital motion',25),('Satellite count and phase',15),
                          ('Depth and occlusion',10),('Loop seam',10)]:
            add(report,name,pts,False,'No decoded frames',True)
        return
    rows=[]
    for frame in frames:
        blue=components(mask(frame,'blue'),20)
        green=components(mask(frame,'green'),4)
        rows.append({'blue':blue[0] if blue else None,'green':green[:6],
                     'dark':dark_fraction(frame)})
    centers=[r['blue'] for r in rows if r['blue']]
    center=centers[len(centers)//2] if centers else None
    comp=bool(center and center['area']>100 and abs(center['cx']-W/2)<W*.2
              and abs(center['cy']-H/2)<H*.2 and
              sum(r['dark']>.72 and len(r['green'])>=2 for r in rows)>=len(rows)*.45)
    add(report,'Blue center, green satellites on black',20,comp,
        {'center':center,'dark_range':[min(r['dark'] for r in rows),
                                     max(r['dark'] for r in rows)],
         'frames_with_two_satellites':sum(len(r['green'])>=2 for r in rows)})
    angles=[]; distances=[]; green_x=[];green_y=[]; phase=[];near=far=0
    if center:
        for row in rows:
            satellites=row['green']
            for c in satellites:
                dx=c['cx']-center['cx'];dy=c['cy']-center['cy']
                dist=math.hypot(dx,dy)
                if dist<4:continue
                angles.append(math.atan2(dy,dx));distances.append(dist)
                green_x.append(c['cx']);green_y.append(c['cy'])
                radius=math.sqrt(center['area']/math.pi)
                near+=dist<radius*1.4;far+=dist>radius*1.7
            if len(satellites)>=2:
                a=math.atan2(satellites[0]['cy']-center['cy'],satellites[0]['cx']-center['cx'])
                b=math.atan2(satellites[1]['cy']-center['cy'],satellites[1]['cx']-center['cx'])
                phase.append(abs((a-b+math.pi)%(2*math.pi)-math.pi))
    bins={int((a+math.pi)/(2*math.pi)*8)%8 for a in angles}
    orbital=len(bins)>=6 and range_of(green_x)>W*.20 and range_of(green_y)>H*.20
    add(report,'Orbital motion',25,orbital,
        {'occupied_angle_bins':sorted(bins),'x_range':range_of(green_x),
         'y_range':range_of(green_y),'satellite_samples':len(angles)})
    phase_ok=bool(orbital and len(phase)>=len(rows)*.45 and
                  sum(.35<p<math.pi-.15 for p in phase)/len(phase)>.65)
    add(report,'Satellite count and phase',15,phase_ok,
        {'two_satellite_frames':len(phase),'phase_range':
         [min(phase),max(phase)] if phase else None})
    depth=orbital and near>=2 and far>=2
    add(report,'Depth and occlusion',10,depth,
        {'near_center_samples':near,'far_samples':far,
         'reference_note':'satellite passes beside/behind the blue center'})
    a=frames[0];b=frames[-1]
    mismatch=sum(abs(a[i]-b[i])>45 for i in range(0,len(a),3))/N
    add(report,'Loop seam',10,mismatch<.08,
        {'first_last_changed_pixel_fraction':mismatch})
    report['trace']=[{'frame':i,'blue':r['blue'],'green':r['green']}
                     for i,r in enumerate(rows)]


def grade_t51(report, frames):
    if not frames:
        for name,pts in [('Black and teal line design',20),('Final path contour',20),
                         ('Sequential path reveal',25),('Moving tip',10),
                         ('Final hold',5)]:
            add(report,name,pts,False,'No decoded frames',True)
        return
    masks=[mask(f,'teal') for f in frames]
    areas=[sum(m) for m in masks]
    boxes=[]
    for m in masks:
        pts=[p for p,v in enumerate(m) if v]
        boxes.append([min(p%W for p in pts),min(p//W for p in pts),
                      max(p%W for p in pts),max(p//W for p in pts)] if pts else None)
    peak=max(areas); end=areas[-1];dark=sum(dark_fraction(f) for f in frames[-5:])/min(5,len(frames))
    design=peak>70 and dark>.8 and end>peak*.6
    add(report,'Black and teal line design',20,design,
        {'peak_line_pixels':peak,'end_pixels':end,'end_dark_fraction':dark})
    final=masks[-1]
    profile, coverage=contour_profile(final)
    reference=[1,.73,.46,.19,.15,.47,.81,.9,.54,.45,.7]
    error=sum(abs(actual-expected) for actual,expected in zip(profile,reference))/len(reference) if profile else None
    contour=bool(boxes[-1] and boxes[-1][2]-boxes[-1][0]>W*.38 and
                 boxes[-1][3]-boxes[-1][1]>H*.18 and coverage>.85 and
                 error<.18 and profile[0]>profile[3]+.4 and
                 profile[6]>profile[4]+.35 and
                 profile[6]>min(profile[8:10])+.2 and
                 profile[10]>min(profile[8:10])+.1)
    add(report,'Final path contour',20,contour,
        {'final_bbox':boxes[-1],'normalized_profile':profile,
         'reference_error':error,'column_coverage':coverage})
    first=min(areas[:max(1,len(areas)//5)]);last=sum(areas[-5:])/min(5,len(areas))
    rises=sum(b>=a-peak*.08 for a,b in zip(areas,areas[1:]))
    line_overlap=[]
    for current,area in zip(masks,areas):
        if area>peak*.1:
            matches=sum(current[p] and any(final[q] for q in
                        (p, p-1 if p%W else p, p+1 if p%W<W-1 else p,
                         p-W if p>=W else p, p+W if p<N-W else p))
                        for p in range(N))
            line_overlap.append(matches/area)
    reveal=(contour and peak>70 and first<peak*.3 and last>peak*.7 and
            rises>=.7*(len(areas)-1) and
            bool(line_overlap) and min(line_overlap)>.65)
    add(report,'Sequential path reveal',25,reveal,
        {'first_min':first,'peak':peak,'last_mean':last,
         'nondecreasing_steps':rises,'min_final_path_overlap':
         min(line_overlap) if line_overlap else None})
    left=[b[0] if b else None for b in boxes];right=[b[2] if b else None for b in boxes]
    active=[i for i,a in enumerate(areas) if a>peak*.10]
    tip=bool(active and range_of([right[i] for i in active if right[i] is not None])>W*.3
             and range_of([left[i] for i in active if left[i] is not None])<W*.12)
    add(report,'Moving tip',10,tip,
        {'left_range':range_of([left[i] for i in active if left[i] is not None]),
         'right_range':range_of([right[i] for i in active if right[i] is not None])})
    hold=peak>70 and min(areas[-max(2,len(areas)//8):])>peak*.72
    add(report,'Final hold',5,hold,{'last_areas':areas[-10:]})
    report['trace']=[{'frame':i,'line_pixels':areas[i],'bbox':boxes[i]}
                     for i in range(len(frames))]


def t52_bins(frame):
    bins=[0]*8
    cx=W/2;cy=H/2
    for p in range(N):
        x=p%W-cx;y=p//W-cy;d=math.hypot(x,y)
        if not 5<d<26:continue
        r,g,b=frame[p*3:p*3+3]
        light=max(0,min(r,g,b)-35)
        angle=(math.atan2(y,x)+math.pi)/(2*math.pi)
        bins[int(angle*8)%8]+=light
    return bins


def grade_t52(report, frames):
    if not frames:
        for name,pts in [('Eight-dot loader design',20),('Rotating phase order',25),
                         ('Repeated cycle',20),('Staggered brightness',10),
                         ('Loop seam',5)]:
            add(report,name,pts,False,'No decoded frames',True)
        return
    comps=[];bins=[];darks=[]
    for frame in frames:
        # Dim dots remain present while the highlighted dot travels.
        comps.append(components(mask(frame,'light'),3))
        bins.append(t52_bins(frame));darks.append(dark_fraction(frame))
    ring=[]
    for cs in comps:
        good=[c for c in cs if 5<math.hypot(c['cx']-W/2,c['cy']-H/2)<26
              and 3<=c['area']<=180]
        ring.append(good)
    design=max(len(x) for x in ring)>=6 and sum(d>.83 for d in darks)>=len(darks)*.7
    add(report,'Eight-dot loader design',20,design,
        {'max_ring_dots':max(len(x) for x in ring),
         'frames_with_six_or_more':sum(len(x)>=6 for x in ring),
         'dark_range':[min(darks),max(darks)]})
    brightest=[max(range(8),key=lambda j:row[j]) for row in bins]
    unique=len(set(brightest))
    steps=[(b-a)%8 for a,b in zip(brightest,brightest[1:])]
    forward=sum(1<=s<=3 for s in steps);reverse=sum(5<=s<=7 for s in steps)
    phase=unique>=5 and max(forward,reverse)>=max(4,len(steps)*.18)
    add(report,'Rotating phase order',25,phase,
        {'visited_bins':sorted(set(brightest)),'forward_steps':forward,
         'reverse_steps':reverse,'sequence':brightest})
    # Compare brightness patterns at lags: a repeated phase cycle should
    # produce several near matches separated by a stable nonzero interval.
    period=None;score=1e9
    for lag in range(max(4,len(bins)//10),max(5,len(bins)//2)):
        pairs=[(bins[i],bins[i+lag]) for i in range(len(bins)-lag)]
        errors=[sum(abs(a-b) for a,b in zip(x,y))/max(1,sum(x)+sum(y)) for x,y in pairs]
        mean=sum(errors)/len(errors)
        if mean<score:score=mean;period=lag
    cycle=period is not None and score<.32 and unique>=5
    add(report,'Repeated cycle',20,cycle,
        {'best_lag_samples':period,'relative_brightness_error':score})
    contrast=[(max(x)-min(x))/max(1,max(x)) for x in bins]
    stagger=sum(v>.35 for v in contrast)>=len(contrast)*.55
    add(report,'Staggered brightness',10,stagger,
        {'contrast_mean':sum(contrast)/len(contrast)})
    a=frames[0];b=frames[-1]
    mismatch=sum(abs(a[i]-b[i])>55 for i in range(0,len(a),3))/N
    add(report,'Loop seam',5,mismatch<.055,
        {'first_last_changed_pixel_fraction':mismatch})
    report['trace']=[{'frame':i,'ring_dots':len(ring[i]),'bins':bins[i]}
                     for i in range(len(frames))]


def boundary_uneven(bitmap,orientation):
    positions=[]
    if orientation=='top':
        for x in range(2,W-2,3):
            rows=[y for y in range(H) if bitmap[y*W+x]]
            if rows:positions.append(max(rows))
    elif orientation=='left':
        for y in range(2,H-2,3):
            cols=[x for x in range(W) if bitmap[y*W+x]]
            if cols:positions.append(max(cols))
    else:
        for sector in range(24):
            angle=2*math.pi*sector/24
            radii=[];furthest_inside=0
            for r in range(1,round(math.hypot(W/2,H/2))+1):
                x=round(W/2+math.cos(angle)*r);y=round(H/2+math.sin(angle)*r)
                if not (0<=x<W and 0<=y<H):break
                furthest_inside=r
                if bitmap[y*W+x]:radii.append(r)
            # Ignore rays clipped by the rectangular canvas. A perfectly
            # circular edge must not appear liquid only because it hits a side.
            if radii and max(radii)<furthest_inside-1:
                positions.append(max(radii))
    return range_of(positions),positions


def grade_t53_method(report,frames,method):
    label=method.replace('_',' ')
    if not frames:
        for name,points in (('Black and white scenes',3),('Wipe progression',3),
                            ('Liquid boundary',10),('Full transition and settle',4)):
            add(report,f'{label}: {name}',points,False,'No decoded frames',True)
        return None
    bitmaps=[mask(f,'white') for f in frames]
    coverage=[sum(m)/N for m in bitmaps]
    scenes=min(coverage)<.08 and max(coverage)>.90
    add(report,f'{label}: Black and white scenes',3,scenes,
        {'min_white':min(coverage),'max_white':max(coverage)})
    peak=max(range(len(coverage)),key=lambda i:coverage[i])
    rise=sum(b>=a-.08 for a,b in zip(coverage[:peak],coverage[1:peak+1]))
    fall=sum(b<=a+.08 for a,b in zip(coverage[peak:],coverage[peak+1:]))
    progressing=(peak>=2 and peak<len(coverage)-2 and
                 rise>=peak*.65 and fall>=(len(coverage)-peak-1)*.65 and
                 min(coverage[peak:])<.12)
    add(report,f'{label}: Wipe progression',3,progressing,
        {'peak_frame':peak,'rise_steps':rise,'fall_steps':fall,
         'coverage':coverage})
    candidates=[i for i in range(peak+1) if .22<coverage[i]<.78]
    mid=min(candidates,key=lambda i:abs(coverage[i]-.5)) if candidates else None
    if mid is None:
        oriented=False;uneven=0;profile=[]
    else:
        m=bitmaps[mid]
        if method=='top_to_bottom':
            top=sum(m[y*W+x] for y in range(H//3) for x in range(W))/(N/3)
            bottom=sum(m[y*W+x] for y in range(2*H//3,H) for x in range(W))/(N/3)
            oriented=top>bottom+.25
            uneven,profile=boundary_uneven(m,'top')
        elif method=='left_to_right':
            left=sum(m[y*W+x] for y in range(H) for x in range(W//3))/(N/3)
            right=sum(m[y*W+x] for y in range(H) for x in range(2*W//3,W))/(N/3)
            oriented=left>right+.25
            uneven,profile=boundary_uneven(m,'left')
        else:
            center=sum(m[y*W+x] for y in range(H//3,2*H//3)
                       for x in range(W//3,2*W//3))/max(1,(H//3)*(W//3))
            corners=sum(m[y*W+x] for y in list(range(H//5))+list(range(4*H//5,H))
                        for x in list(range(W//5))+list(range(4*W//5,W)))
            corners/=max(1,(2*(H//5))*(2*(W//5)))
            oriented=center>corners+.22
            uneven,profile=boundary_uneven(m,'center')
    liquid=oriented and uneven>=3
    add(report,f'{label}: Liquid boundary',10,liquid,
        {'mid_frame':mid,'oriented':oriented,'boundary_range':uneven,
         'sampled_boundary':profile[:40]})
    settled=coverage[0]<.12 and coverage[-1]<.12 and max(coverage)>.9
    add(report,f'{label}: Full transition and settle',4,settled,
        {'first':coverage[0],'last':coverage[-1],'peak':max(coverage)})
    report.setdefault('trace',{})[method]=[{'frame':i,'white_fraction':v}
                                         for i,v in enumerate(coverage)]
    return bitmaps[mid] if mid is not None else None


def grade(desktop,project,terminal_log):
    report={'task':TASK,'rubric_version':SPEC['rubric_version'],
            'source_video_sha256':SPEC['source_video_sha256'],
            'checks':[],'outputs':{},'terminal_attempts':[]}
    if terminal_log.exists() and terminal_log.stat().st_size:
        report['terminal_attempts']=terminal_log.read_text(errors='replace').splitlines()
    clips={}
    for filename in SPEC['outputs']:
        path=desktop/filename
        clips[filename]=media(report,path,5,5 if TASK=='t53' else 10)
        report['outputs'][filename]=str(path)
    saved, reopen_detail=native_project(project) if TASK=='t51' else (
        project.exists() and project.stat().st_size>=1024, 'Size check only')
    add(report,'Native editable Friction project',5,saved,
        {'path':str(project),'bytes':project.stat().st_size if project.exists() else 0,
         'reopen':reopen_detail},
        missing=not project.exists())
    if TASK=='t50':grade_t50(report,clips['final.mp4'])
    elif TASK=='t51':grade_t51(report,clips['final.mp4'])
    elif TASK=='t52':grade_t52(report,clips['final.mp4'])
    elif TASK=='t53':
        mids={}
        for method in ('top_to_bottom','left_to_right','center'):
            mids[method]=grade_t53_method(report,clips[method+'.mp4'],method)
        pairs=[(a,b) for a,b in (('top_to_bottom','left_to_right'),
                                  ('top_to_bottom','center'),
                                  ('left_to_right','center'))
               if mids[a] is not None and mids[b] is not None]
        ious=[]
        for a,b in pairs:
            x,y=mids[a],mids[b]
            inter=sum(bool(u and v) for u,v in zip(x,y))
            union=sum(bool(u or v) for u,v in zip(x,y))
            ious.append(inter/union if union else 1)
        distinct=len(ious)==3 and max(ious)<.80
        add(report,'Three distinct transition methods',5,distinct,
            {'pairwise_midframe_iou':ious},missing=len(ious)<3)
    else:raise ValueError(TASK)
    possible=sum(c['points'] for c in report['checks'])
    if possible!=100:
        raise RuntimeError(f'Rubric totals {possible}, expected 100')
    earned=sum(c['earned'] for c in report['checks'])
    report['earned_points']=earned
    report['raw_score']=earned/100
    report['native_project_gate']=(('clear' if saved else 'capped-at-0.5')
                                   if TASK=='t51' else 'not-applicable')
    report['ungated_score']=min(earned/100,.5) if TASK=='t51' and not saved else earned/100
    report['code_access_gate']='terminal-attempt' if report['terminal_attempts'] else 'clear'
    report['score']=0 if report['terminal_attempts'] else report['ungated_score']
    return report


def main():
    parser=argparse.ArgumentParser()
    parser.add_argument('--desktop',default='/root/Desktop')
    parser.add_argument('--project',default='/root/edit/project.friction')
    parser.add_argument('--terminal-log',default='/logs/artifacts/terminal-attempts.log')
    parser.add_argument('--reward',default='/logs/verifier/reward.txt')
    parser.add_argument('--report',default='/logs/verifier/score.json')
    args=parser.parse_args()
    result=grade(Path(args.desktop),Path(args.project),Path(args.terminal_log))
    report=Path(args.report);reward=Path(args.reward)
    report.parent.mkdir(parents=True,exist_ok=True)
    reward.parent.mkdir(parents=True,exist_ok=True)
    report.write_text(json.dumps(result,indent=2)+'\n')
    reward.write_text(f"{result['score']:.6f}\n")
    print(json.dumps({'score':result['score'],'checks':result['checks']},indent=2))


if __name__=='__main__':main()