File size: 30,638 Bytes
5eec1f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""T23 v2 task-based, staged RLVR checks. No facial/reference-mask matching.
Only stdlib and ffmpeg; native inspection is performed by the real Friction loader.
"""
import colorsys
import hashlib
import json
import math
import os
import pathlib
import shutil
import statistics as st
import subprocess
from reference_viewing import verify_viewing

VERSION = 't23-task-v3-reference-viewing'
SIZE = 200
FPS = 30
HERE = pathlib.Path(__file__).resolve().parent


class VerifierError(RuntimeError):
    pass


def mean(values):
    values = list(values)
    return st.mean(values) if values else 0.0


def sha(path):
    return hashlib.sha256(pathlib.Path(path).read_bytes()).hexdigest()


def command(args, timeout=120):
    try:
        return subprocess.run(args, capture_output=True, timeout=timeout)
    except (OSError, subprocess.TimeoutExpired) as exc:
        raise VerifierError(f'Verifier dependency failed: {args[0]}: {exc}') from exc


def probe(video):
    if not pathlib.Path(video).is_file():
        return None
    process = command(['ffprobe', '-v', 'error', '-show_streams', '-show_format', '-of', 'json', str(video)])
    if process.returncode:
        return None  # Invalid learner file; tool failures are checked by preflight.
    try:
        return json.loads(process.stdout)
    except ValueError as exc:
        raise VerifierError('ffprobe returned invalid JSON') from exc


def decode(video):
    process = command(['ffmpeg', '-nostdin', '-v', 'error', '-i', str(video), '-vf', f'fps={FPS},scale={SIZE}:{SIZE}',
                       '-frames:v', '240', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], timeout=180)
    if process.returncode:
        return []
    stride = SIZE * SIZE * 3
    if len(process.stdout) % stride:
        raise VerifierError('Partial raw frame returned')
    return [process.stdout[i:i + stride] for i in range(0, len(process.stdout), stride)]


def components(points):
    """8-connected components; diagonal antialiasing does not split a smile."""
    points = set(points)
    result = []
    while points:
        seed = points.pop()
        component, pending = [seed], [seed]
        while pending:
            x, y = pending.pop()
            for dx in (-1, 0, 1):
                for dy in (-1, 0, 1):
                    next_point = x + dx, y + dy
                    if next_point in points:
                        points.remove(next_point)
                        pending.append(next_point)
                        component.append(next_point)
        if len(component) >= 2:
            result.append(component)
    return result


def face_geometry(dark, box):
    x0, x1, top, bottom = box
    w, h = x1 - x0 + 1, bottom - top + 1
    # Eyes may touch the smile in legitimate drawings. Split at the eye row
    # rather than requiring three disconnected dark components.
    if dark:
        min_y = min(y for _, y in dark)
        split = min_y + max(2, round(h * .12))
        comps = components([(x, y) for x, y in dark if y < split]) + components([(x, y) for x, y in dark if y >= split])
    else:
        comps = []
    candidates = []
    for part in comps:
        xs, ys = zip(*part)
        candidates.append({'x': mean(xs), 'y': mean(ys), 'w': max(xs) - min(xs) + 1,
                           'h': max(ys) - min(ys) + 1, 'area': len(part), 'points': part})
    # Any valid eye pair/mouth combination can pass, independently of layer count.
    for mouth in candidates:
        if not .12 * w <= mouth['w'] <= .60 * w:
            continue
        eyes = [c for c in candidates if c is not mouth and .015 * w <= c['w'] <= .18 * w
                and c['y'] < mouth['y'] and abs(c['y'] - mouth['y']) < .40 * h]
        for left in eyes:
            for right in eyes:
                if not .12 * w <= right['x'] - left['x'] <= .65 * w or abs(left['y'] - right['y']) > .15 * h:
                    continue
                # Smile centre is below its ends (image y grows down).
                pts = mouth['points']
                minx, maxx = min(x for x, _ in pts), max(x for x, _ in pts)
                span = max(1, maxx - minx)
                middle = [y for x, y in pts if .3 <= (x - minx) / span <= .7]
                edges = [y for x, y in pts if (x - minx) / span < .2 or (x - minx) / span > .8]
                smile = bool(middle and edges and mean(middle) >= mean(edges) + .015 * h)
                lower = min(left['y'], right['y'], mouth['y']) >= top + .45 * h
                if smile:
                    return True, lower
    return False, False


def analyse(frame):
    fills = []
    cols = [0] * SIZE
    top, bottom = [SIZE] * SIZE, [-1] * SIZE
    for y in range(SIZE):
        for x in range(SIZE):
            offset = 3 * (y * SIZE + x)
            rgb = frame[offset:offset + 3]
            # Wide pastel tolerance; dark facial ink is measured separately.
            if max(rgb) - min(rgb) >= 30 and max(rgb) >= 100:
                fills.append((x, y))
                cols[x] += 1
                top[x] = min(top[x], y)
                bottom[x] = max(bottom[x], y)
    runs, start = [], None
    for x in range(SIZE + 1):
        on = x < SIZE and cols[x] >= 3
        if on and start is None:
            start = x
        elif not on and start is not None:
            if x - start >= 8:
                runs.append((start, x - 1))
            start = None
    blobs = []
    for x0, x1 in runs:
        t, b = min(top[x0:x1 + 1]), max(bottom[x0:x1 + 1])
        w, h = x1 - x0 + 1, b - t + 1
        if h < 8:
            continue
        dark, widths, hue, saturation, value = [], [], [], [], []
        nonwhite = []
        for y in range(t, b + 1):
            row_ink = []
            for x in range(x0, x1 + 1):
                i = 3 * (y * SIZE + x)
                rgb = frame[i:i + 3]
                if min(rgb) < 235:
                    row_ink.append(x)
                    nonwhite.append((x, y))
                if max(rgb) < 130:
                    dark.append((x, y))
                if max(rgb) - min(rgb) >= 30:
                    hh, ss, vv = colorsys.rgb_to_hsv(*(c / 255 for c in rgb))
                    hue.append(hh * 2 * math.pi)
                    saturation.append(ss)
                    value.append(vv)
            widths.append(max(row_ink) - min(row_ink) + 1 if row_ink else 0)
        facial, lower = face_geometry(dark, (x0, x1, t, b))
        # Rounded shoulders, substantial lower body, narrow upper tip, flat feet.
        upper = mean(widths[:max(1, int(h * .12))]) / w
        shoulder = mean(widths[int(h * .3):int(h * .6)]) / w
        base = mean(widths[int(h * .7):max(int(h * .7) + 1, int(h * .9))]) / w
        central_bottoms = [bottom[x] for x in range(x0 + int(w * .2), x1 - int(w * .2) + 1)]
        dome = upper <= .70 and shoulder >= .55 and base >= .70 and st.pstdev(central_bottoms) <= max(1.5, .06 * h)
        blobs.append({'x': (x0 + x1) / 2, 'x0': x0, 'x1': x1, 'top': t, 'bottom': b, 'w': w, 'h': h,
                      'full': x0 > 1 and x1 < SIZE - 2, 'dome': dome, 'face': facial, 'lower_face': lower,
                      'hue': math.atan2(mean([math.sin(a) for a in hue]), mean([math.cos(a) for a in hue])),
                      'saturation': mean(saturation), 'brightness': mean(value)})
    # Inspect every background pixel; foreground includes coloured fill and dark
    # marks inside a detected character. Stray dark objects elsewhere remain visible.
    offwhite = background = 0
    for y in range(SIZE):
        for x in range(SIZE):
            if any(blob['x0'] <= x <= blob['x1'] and blob['top'] <= y <= blob['bottom'] for blob in blobs):
                continue
            background += 1
            i = 3 * (y * SIZE + x)
            if min(frame[i:i + 3]) < 240:
                offwhite += 1
    full = [b for b in blobs if b['full']]
    return {'blobs': blobs, 'full': full, 'background_white': 1 - offwhite / max(1, background),
            'h': st.median(b['h'] for b in full) if full else None,
            'w': st.median(b['w'] for b in full) if full else None,
            'floor': st.median(b['bottom'] for b in full) if full else None}


def peaks(values):
    """Local maxima, with plateaus represented once; no fixed phase or exact curve."""
    extrema = []
    direction = 0
    for i in range(1, len(values)):
        delta = values[i] - values[i - 1]
        new = 1 if delta > .25 else -1 if delta < -.25 else 0
        if new and direction == 1 and new == -1:
            if not extrema or i - 1 - extrema[-1] >= 8:
                extrema.append(i - 1)
        if new:
            direction = new
    if values and values[0] >= max(values[:min(5, len(values))]) - .25:
        extrema.insert(0, 0)
    return extrema


def measure(frames):
    analysed = [analyse(frame) for frame in frames]
    valid = [a for a in analysed if len(a['full']) >= 2]
    if len(valid) < .90 * len(frames) or not frames:
        return {'visible': False, 'frame_count': len(frames), 'analysed': analysed}
    hs = [a['h'] if a['h'] is not None else 0 for a in analysed]
    full = [b for a in analysed for b in a['full']]
    spacings = [right['x'] - left['x'] for a in analysed for left, right in zip(a['full'], a['full'][1:])]
    spacing = st.median(spacings)
    locations = []
    for a in analysed:
        angles = [2 * math.pi * b['x'] / spacing for b in a['full']]
        locations.append(math.atan2(mean([math.sin(x) for x in angles]), mean([math.cos(x) for x in angles])) * spacing / (2 * math.pi))
    shifts = [(right - left + spacing / 2) % spacing - spacing / 2 for left, right in zip(locations, locations[1:])]
    hues = []
    for a in analysed:
        angles = [b['hue'] for b in a['full']]
        hues.append(math.atan2(mean([math.sin(v) for v in angles]), mean([math.cos(v) for v in angles])))
    hue_steps = [(b - a + math.pi) % (2 * math.pi) - math.pi for a, b in zip(hues, hues[1:])]
    rests = peaks(hs)
    hops = []
    for start, end in zip(rests, rests[1:]):
        if not 9 <= end - start <= 21:
            continue
        minimum = min(hs[start:end + 1])
        minima = [i for i in range(start, end + 1) if hs[i] == minimum]
        trough = round(mean(minima))
        amplitude = max(hs[start], hs[end]) - hs[trough]
        if amplitude < 3:
            continue
        move = shifts[start:end]
        total = sum(move)
        spring_move = sum(shifts[trough:end])
        height_steps = [abs(hs[i + 1] - hs[i]) for i in range(start, end)]
        down = [abs(hs[i + 1] - hs[i]) for i in range(start, trough)]
        up = [abs(hs[i + 1] - hs[i]) for i in range(trough, end)]
        def eased(slopes):
            return len(slopes) >= 3 and max(slopes) > 0 and min(slopes[0], slopes[-1]) <= .65 * max(slopes)
        hops.append({'eased_height': eased(down) and eased(up), 'start_frame' : start, 'minimum_frame': trough, 'end_frame': end,
                     'period': (end - start) / FPS, 'squash_ratio': hs[trough] / max(hs[start], hs[end]),
                     'squash_duration': trough - start, 'spring_duration': end - trough,
                     'step_spacing': total / spacing, 'spring_fraction': spring_move / total if total > 1 else 0,
                     'backward_fraction': sum(max(0, -v) for v in move) / max(1, sum(abs(v) for v in move)),
                     'largest_move_spacing': max(map(abs, move), default=0) / spacing,
                     'largest_height_step': max(height_steps, default=0) / amplitude, 'height_quantization': 1 / amplitude,
                     'hue_turns': sum(hue_steps[start:end]) / (2 * math.pi),
                     'largest_hue_step': max(map(abs, hue_steps[start:end]), default=0) / (2 * math.pi)})
    shared = []
    for a in analysed:
        angles = [b['hue'] for b in a['full']]
        shared.append(all(abs((v - hues[len(shared)] + math.pi) % (2 * math.pi) - math.pi) <= math.radians(20) for v in angles))
    rest_height = max(hs)
    rest_blobs = [b for a in analysed if a['h'] >= rest_height - 1 for b in a['full']]
    return {'visible': True, 'frame_count': len(frames), 'analysed': analysed, 'hops': hops,
            'width': st.median(b['w'] for b in full) * 4, 'rest_height': rest_height * 4,
            'floor': st.median(a['floor'] for a in valid) * 4,
            'floor_std': st.pstdev(a['floor'] for a in valid) * 4,
            'width_ratio': max(b['w'] for b in full) / min(b['w'] for b in full),
            'spacing': spacing * 4, 'spacing_cv': st.pstdev(spacings) / spacing,
            'common_floor_fraction': mean(max(b['bottom'] for b in a['full']) - min(b['bottom'] for b in a['full']) <= 1 for a in valid),
            'row_coverage': mean(3 <= len(a['blobs']) <= 6 and len(a['full']) >= 2 for a in analysed),
            'dome_fraction': mean(b['dome'] for b in rest_blobs),
            'face_fraction': mean(b['face'] for b in full), 'lower_face_fraction': mean(b['lower_face'] for b in full),
            'background_fraction': mean(a['background_white'] >= .995 for a in analysed),
            'shared_colour_fraction': mean(shared), 'saturation': st.median(b['saturation'] for b in full),
            'brightness': st.median(b['brightness'] for b in full), 'hue_bins': len({int((h % (2 * math.pi)) / (math.pi / 6)) for h in hues})}


def assess(metrics):
    checks = []
    def add(stage, name, weight, measured, passed, target, feedback):
        checks.append({'stage': stage, 'id': name, 'weight': weight, 'measured': measured,
                       'passed': bool(passed), 'target': target, 'feedback': None if passed else feedback})
    visible = metrics.get('visible', False)
    def get(key):
        return metrics.get(key, 0)
    add('scene', 'dome_body', .05, get('dome_fraction'), visible and get('dome_fraction') >= .90,
        'Rounded top, broad lower body, flatter feet on >=90% rest observations', 'Round the upper body and keep the bottom flatter.')
    add('scene', 'face_structure', .05, get('face_fraction'), visible and get('face_fraction') >= .85,
        'Two separated eyes and an upward smile on >=85% full blobs', 'Give every blob two eyes and a curved smile.')
    add('scene', 'face_lower_half', .02, get('lower_face_fraction'), visible and get('lower_face_fraction') >= .85,
        'Eye/mouth centres in lower half, with 5% drawing tolerance', 'Move the face into the lower half of the body.')
    add('scene', 'proportions', .04, [get('width'), get('rest_height')], visible and 165 <= get('width') <= 212 and 137 <= get('rest_height') <= 177
        and 1.02 <= get('width') / max(1, get('rest_height')) <= 1.55, 'Reference proportions with broad +/-13% bands', 'Keep the body slightly wider than tall and close to reference size.')
    add('scene', 'row_layout', .04, [get('spacing'), get('spacing_cv'), get('row_coverage')], visible and 176 <= get('spacing') <= 224
        and get('spacing_cv') <= .08 and get('row_coverage') >= .90, 'Even spacing near 200px; about four whole/partial characters', 'Space identical characters evenly across both edges.')
    add('scene', 'floor_layout', .02, get('floor'), visible and 455 <= get('floor') <= 487 and metrics.get('common_floor_fraction', 1) >= .95,
        'Common floor near y=471, +/-16px', 'Align the feet slightly below the middle of the scene.')
    add('scene', 'white_background', .03, get('background_fraction'), visible and get('background_fraction') >= .95,
        '>=99.5% white background pixels on >=95% frames', 'Remove marks or coloured content from the full background.')
    hops = metrics.get('hops', [])
    coverage = sum(h['end_frame'] - h['start_frame'] for h in hops) / max(1, metrics.get('frame_count', 0) - 1)
    def hopcheck(name, weight, test, target, feedback, stage='vertical'):
        fraction = mean(test(h) for h in hops)
        add(stage, name, weight, {'fraction': fraction, 'observed_hops': len(hops), 'coverage': coverage},
            visible and len(hops) >= 8 and coverage >= .80 and fraction >= .90 and (name != 'colour_per_hop' or metrics.get('hue_bins', 0) >= 6), target, feedback)
    hopcheck('hop_cadence', .05, lambda h: .40 <= h['period'] <= .60, 'Hop every 0.4-0.6s across >=90% hops', 'Repeat the squash and spring about twice a second.')
    hopcheck('squash_depth', .05, lambda h: .60 <= h['squash_ratio'] <= .76, 'Minimum height 60-76% of resting height', 'Squash to roughly two-thirds of resting height.')
    add('vertical', 'pinned_feet', .04, get('floor_std'), visible and get('floor_std') <= 4,
        'Floor standard deviation <=4px', 'Keep the feet pinned while changing body height.')
    add('vertical', 'stable_width', .03, get('width_ratio'), visible and get('width_ratio') <= 1.08,
        'Width max/min <=1.08', 'Squash vertically without widening the body significantly.')
    hopcheck('smooth_asymmetric_dance', .08, lambda h: h['squash_duration'] > h['spring_duration'] and h['largest_height_step'] <= .30 + h.get('height_quantization', 0) and h['eased_height'],
        'Squash lasts longer than spring; smaller endpoint slopes; no height jump >30% amplitude', 'Make the squash slower than the spring and remove sudden height jumps.')
    hopcheck('half_spacing_right', .10, lambda h: .40 <= h['step_spacing'] <= .60 and h['backward_fraction'] <= .10,
        'Each hop moves 40-60% spacing right, with <=10% backward movement', 'Move the entire row half a spacing to the right on each hop.', stage='sideways')
    hopcheck('move_during_spring', .06, lambda h: h['spring_fraction'] >= .75 and h['step_spacing'] > .1,
        '>=75% rightward displacement occurs during spring-back', 'Keep the row still while squashing; move it during spring-back.', stage='sideways')
    hopcheck('smooth_sideways', .04, lambda h: h['largest_move_spacing'] <= .20 and .40 <= h['step_spacing'] <= .60,
        'No single-frame movement >20% spacing', 'Ease the sideways movement rather than jumping between positions.', stage='sideways')
    add('colour', 'shared_palette', .04, [get('shared_colour_fraction'), get('saturation'), get('brightness')], visible
        and get('shared_colour_fraction') >= .95 and .25 <= get('saturation') <= .80 and .75 <= get('brightness') <= 1,
        'Shared hue >=95%; broad pastel saturation/brightness bands', 'Use the same clear pastel fill colour on every character.')
    hopcheck('colour_per_hop', .06, lambda h: .75 <= h['hue_turns'] <= 1.25 and h['largest_hue_step'] <= .20,
        'One continuous forward hue turn per hop, +/-25%', 'Cycle continuously around the colour wheel once per hop.', stage='colour')
    return checks


def walk(node):
    if isinstance(node, dict):
        yield node
        for value in node.values():
            yield from walk(value)
    elif isinstance(node, list):
        for value in node:
            yield from walk(value)


def native_check(project, work):
    if not pathlib.Path(project).is_file():
        return {'status': 'missing', 'loaded': False}, None
    output = pathlib.Path(work) / 'native.json'
    output.unlink(missing_ok=True)
    override = os.environ.get('T23_NATIVE_COMMAND')
    args = json.loads(override) if override else ['bash', str(HERE / 'native/runtime-launch.sh')]
    if override:
        args += ['--project', str(project), '--output', str(output), '--max-frames', '180']
    else:
        if not pathlib.Path('/opt/friction-audit/bin/friction').is_file():
            raise VerifierError('Pinned native Friction inspector not installed; rebuild task image')
        binary = pathlib.Path('/opt/friction-audit/bin/friction')
        expected = json.loads((HERE / 'native/runtime-lock.json').read_text())['audit_binary_sha256']
        if sha(binary) != expected:
            raise VerifierError('Native inspector binary hash does not match pinned runtime')
        args += [str(project), '--audit-output', str(output), '--audit-max-frames', '180']
    process = command(args, timeout=300)
    if not output.is_file():
        raise VerifierError('Native inspector produced no report: ' + process.stderr.decode(errors='replace')[-1000:])
    data = json.loads(output.read_text())
    if data.get('infrastructure_failure') or process.returncode not in (0, 4):
        raise VerifierError('Native inspection failed or timed out')
    if process.returncode == 4 or not data.get('loaded'):
        return {'status': 'invalid_project', 'loaded': False, 'error': data.get('error')}, None
    if not data.get('evaluation_completed') or not data.get('scenes'):
        raise VerifierError('Native inspection incomplete')
    # Inspector reports the whole object tree, including other scenes. No imported
    # images, footage, linked canvases or shaders are eligible for this vector task.
    objects = [n for scene in data['scenes'] for n in walk(scene.get('structure', {})) if 'objects' in n or 'type_id' in n]
    disallowed = [n for scene in data['scenes'] for n in walk(scene.get('structure', {}))
                  if any(word in n.get('type', '').lower() for word in ('videobox', 'imagebox', 'imagepaint', 'shader', 'linkedbox', 'linkcanvas', 'internallink', 'animationbox'))]
    vector_types = ('SmartVectorPath', 'Circle', 'Rectangle', 'VectorPath', 'Ellipse')
    vectors = [n for scene in data['scenes'] for n in walk(scene.get('structure', {})) if n.get('type') in vector_types]
    keys = [n for scene in data['scenes'] for n in walk(scene.get('structure', {})) if n.get('keys') or n.get('has_expression') and n.get('expression_valid')]
    scene = data['scenes'][0]
    if not scene.get('frames_complete'):
        raise VerifierError('Independent render did not cover all native frames')
    frames = scene.get('frames', [])
    preview = pathlib.Path(work) / 'native-preview.mp4'
    if frames:
        # Filenames produced by native runner are a continuous zero-based sequence.
        first = pathlib.Path(frames[0]['image'])
        image_pattern = pathlib.Path(work) / first.parent / (first.name[:-10] + '%06d.png')
        process = command(['ffmpeg', '-nostdin', '-v', 'error', '-y', '-framerate', str(scene['fps']), '-i', str(image_pattern),
                           '-c:v', 'libx264', '-crf', '10', '-pix_fmt', 'yuv420p', str(preview)], timeout=180)
        if process.returncode:
            raise VerifierError('Could not encode independent native render: ' + process.stderr.decode(errors='replace')[-500:])
    else:
        raise VerifierError('Native renderer produced no frame index')
    summary = {'status': 'loaded', 'loaded': True, 'editable': data.get('editable'), 'assets_resolved': data.get('assets_resolved'),
               'single_scene': len(data['scenes']) == 1, 'vector_objects': len(vectors), 'animated_properties': len(keys),
               'forbidden_types': sorted({n.get('type') for n in disallowed}), 'metadata': {k: scene.get(k) for k in ('width', 'height', 'fps', 'frame_range')},
               'inspector': data.get('inspector'), 'runtime_image': data.get('runtime_image'), 'report_sha256': sha(output)}
    return summary, preview


def action_audit(log):
    if not pathlib.Path(log).is_file():
        return {'status': 'unknown', 'violations': [], 'reason': 'Required action log missing'}
    violations, uncertain = [], []
    initialized = False
    for line in pathlib.Path(log).read_text().splitlines():
        if not line.strip():
            continue
        try:
            event = json.loads(line)
        except ValueError:
            # Historical appfinder stubs do not establish shell intent.
            import re
            match = re.search(r'\b(xterm|uxterm|lxterm|xfce4-terminal|x-terminal-emulator)\b', line)
            if match:
                violations.append({'event': 'explicit_terminal_request', 'raw': line})
            else:
                uncertain.append(line)
            continue
        if event.get('event') == 'audit_start':
            initialized = True
        elif event.get('event') in ('explicit_terminal_request', 'shell_execution'):
            violations.append(event)
        elif event.get('event') not in ('application_launcher', 'audit_start', 'denied_ambiguous_launcher'):
            uncertain.append(event)
    if not initialized:
        uncertain.append('Required audit_start marker missing')
    return {'status': 'unknown' if uncertain else 'complete', 'violations': violations, 'uncertain': uncertain}


def correspondence(candidate, native):
    if len(candidate) != len(native):
        return {'matched': False, 'reason': 'frame count mismatch'}
    errors = []
    for a, b in zip(candidate, native):
        foreground = [i for i in range(0, len(a), 3) if min(a[i:i + 3]) < 230 or min(b[i:i + 3]) < 230]
        errors.append(mean(abs(a[i + c] - b[i + c]) / 255 for i in foreground for c in range(3)))
    return {'matched': bool(errors) and max(errors) <= .08, 'maximum_foreground_error': max(errors, default=1), 'mean_foreground_error': mean(errors)}


def evaluate(video, project, terminal_log, work, viewing_log=None, reference=None):
    work = pathlib.Path(work)
    work.mkdir(parents=True, exist_ok=True)
    for tool in ('ffmpeg', 'ffprobe'):
        if not shutil.which(tool):
            raise VerifierError(f'{tool} missing')
        if command([tool, '-version']).returncode:
            raise VerifierError(f'{tool} unavailable')
    meta = probe(video)
    frames = decode(video) if meta else []
    metrics = measure(frames) if frames else {'visible': False}
    checks = assess(metrics)
    native, preview = native_check(project, work)
    if native.get('loaded') and native.get('assets_resolved') is None and not native.get('forbidden_types'):
        raise VerifierError('Native dependency scope unsupported; review rather than penalize learner')
    authored = native.get('loaded') and native.get('editable') and native.get('single_scene') and native.get('vector_objects', 0) >= 1 and not native.get('forbidden_types') and native.get('assets_resolved') is True
    native_frames = decode(preview) if preview else []
    match = correspondence(frames, native_frames) if frames and native_frames else {'matched': False}
    actions = action_audit(terminal_log)
    if actions['status'] == 'unknown':
        raise VerifierError('Action audit is incomplete or ambiguous; review before training')
    if authored and not match['matched']:
        # A different export is a learner delivery failure; preserve separate native
        # progress by measuring the independent render, never the unrelated MP4.
        native_metrics = measure(native_frames)
        checks = assess(native_metrics)
        metrics = native_metrics
    for name, weight, passed, measured, feedback in [
        ('native_vector_scene', .05, authored, native, 'Save one editable scene containing your own vector shapes; remove imported footage.'),
        ('native_animation', .04, authored and native.get('animated_properties', 0) > 0, native.get('animated_properties', 0), 'Animate the native scene using keyframes or in-app expressions.'),
        ('export_matches_project', .04, authored and match['matched'], match, 'Render the saved native scene and submit that render.')]:
        checks.append({'stage': 'delivery' if name == 'export_matches_project' else 'scene', 'id': name, 'weight': weight, 'passed': bool(passed), 'measured': measured, 'feedback': None if passed else feedback})
    streams = meta.get('streams', []) if meta else []
    stream = next((s for s in streams if s.get('codec_type') == 'video'), {})
    duration = float(meta.get('format', {}).get('duration', 0)) if meta else 0
    exports = [('dimensions', .02, stream.get('width') == 800 and stream.get('height') == 800),
               ('fps', .01, stream.get('avg_frame_rate') in ('30/1', '60/2')),
               ('duration', .02, abs(duration - 6) <= 1 / FPS + .001 and len(frames) in (179, 180, 181)),
               ('codec', .01, stream.get('codec_name') == 'h264'),
               ('no_audio', .01, bool(meta) and not any(s.get('codec_type') == 'audio' for s in streams))]
    for name, weight, passed in exports:
        checks.append({'stage': 'delivery', 'id': name, 'weight': weight, 'passed': bool(passed), 'measured': duration if name == 'duration' else stream.get(name), 'feedback': None if passed else f'Correct the exported {name}.'})
    assert abs(sum(c['weight'] for c in checks) - 1) < 1e-8
    # Native ownership/authorship failures invalidate render-derived creative credit.
    # Missing project earns only genuine format delivery credit; no spoofed visual progress.
    if not authored:
        for c in checks:
            if c['stage'] != 'delivery':
                c['passed'] = False
                c['feedback'] = 'Native scene must load and contain eligible vector artwork before creative reward can be verified.'
    viewing = verify_viewing(viewing_log or os.environ.get('T23_VIEWING_LOG', '/logs/artifacts/reference-viewing.jsonl'),
                             reference or os.environ.get('T23_REFERENCE', '/root/media/reference.mp4'))
    # Preserve existing rubric points, adding five independent process points.
    for c in checks:
        c['weight'] *= 100 / 105
    checks.append({'stage': 'reference', 'id': 'watched_reference', 'weight': 5 / 105,
                   'passed': viewing['passed'], 'measured': viewing,
                   'feedback': None if viewing['passed'] else
                   'Use Watch Dance Blob Reference; view for 3 seconds and inspect at least 10 frames spanning 0.5 seconds.'})
    progress = round(sum(c['weight'] for c in checks if c['passed']), 4)
    reward = 0.0 if actions['violations'] else progress
    stages = {}
    for stage in ('reference', 'scene', 'vertical', 'sideways', 'colour', 'delivery'):
        subset = [c for c in checks if c['stage'] == stage]
        stages[stage] = {'earned': round(sum(c['weight'] for c in subset if c['passed']), 4), 'available': round(sum(c['weight'] for c in subset), 4),
                         'feedback': [c['feedback'] for c in subset if not c['passed']]}
    return {'version': VERSION, 'status': 'complete', 'reward': reward, 'progress_reward': progress, 'checks': checks, 'stages': stages,
            'actions': actions, 'native': native, 'correspondence': match, 'hops': metrics.get('hops', []),
            'provenance': {'video_sha256': sha(video) if pathlib.Path(video).is_file() else None, 'project_sha256': sha(project) if pathlib.Path(project).is_file() else None,
                           'scorer_sha256': sha(__file__), 'action_log_sha256': sha(terminal_log),
                           'viewing_log_sha256': sha(viewing_log or os.environ.get('T23_VIEWING_LOG', '/logs/artifacts/reference-viewing.jsonl'))}}