hf2q 0.1.33

Pure Rust CLI for converting HuggingFace models to hardware-optimized formats and serving them over an OpenAI-compatible API on Apple Silicon
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
#!/usr/bin/env python3
"""Execute/reduce an existing frozen finite peer selector through canonical Q5.

Only the original rank, configuration reduction and final selection AST are
retained. No historical executor imports, controller, guard or observer runs.
Preparation and replay never load models. A prepared namespace is single-use;
parent owns host admission, fresh source-matched negative control and dispatch.
"""
import argparse
import ast
import copy
import json
import os
from pathlib import Path
import shutil
import statistics
import subprocess
import sys
import time

import family_peer
import q2_run_audit
import q3_metrics
import q3_stats
import q5_artifacts
import q5_calibration as q5
import q5_case
import q5_policy
import q5_runtime
import quality_campaign
import quality_launch

HERE = Path(__file__).resolve().parent
POLICY = {'normal_pressure_only': True, 'swap_growth_tolerance_bytes': 0}


def require(ok, reason):
    if not ok:
        raise ValueError(reason)


def load(path):
    return q5_case.loads(Path(path).read_bytes())


def digest(path):
    return q5_artifacts.sha256(path)


def reference(path):
    path = Path(path).resolve(strict=True)
    return {'path': str(path), 'sha256': digest(path)}


def checked(ref):
    require(digest(ref['path']) == ref['sha256'], 'bound input changed: ' + ref['path'])
    return load(ref['path'])


def save(path, value):
    with Path(path).open('x') as stream:
        json.dump(value, stream, indent=2, allow_nan=False)
        stream.write('\n')
        stream.flush()
        os.fsync(stream.fileno())


def fresh(path):
    path = Path(path).absolute()
    require(not path.exists() and not q5.inside_git(path.parent.resolve()), 'fresh namespace outside Git required')
    path.mkdir(mode=0o700)
    return path


def snapshots(registration):
    for artifact in registration['artifacts']:
        stat = os.stat(artifact['path'], follow_symlinks=False)
        actual = dict(device=stat.st_dev, inode=stat.st_ino, bytes=stat.st_size,
                      mtime_ns=stat.st_mtime_ns, ctime_ns=stat.st_ctime_ns)
        require(actual == artifact['snapshot'], 'retained full-hash/stat witness changed: ' + artifact['path'])


def canonical_sources():
    bindings = q5.source_bindings()
    # The adapter, quality/metric audit and all coding-client sources/fixtures are
    # independent pins in addition to the complete canonical Native9 closure.
    bindings.update({str(path): digest(path) for path in HERE.glob('*.py')})
    bindings.update({str(path): digest(path) for path in (HERE / 'fixtures').rglob('*') if path.is_file()})
    return bindings


def registered_runtime(source_plan, source_selector, family):
    if family == 'qwen38':
        return Path(load(source_plan.parent / 'recipe.json')['runtime'])
    assignments = {node.targets[0].id: node.value for node in ast.parse(source_selector.read_text()).body
                   if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name)}
    base, suffix = assignments['V0'], assignments['V']
    require(isinstance(base, ast.Call) and isinstance(base.func, ast.Name) and base.func.id == 'Path' and
            len(base.args) == 1 and not base.keywords and isinstance(suffix, ast.BinOp) and
            isinstance(suffix.op, ast.Div) and isinstance(suffix.left, ast.Name) and suffix.left.id == 'V0',
            'original runtime binding cannot be derived without executing private code')
    return Path(ast.literal_eval(base.args[0])) / ast.literal_eval(suffix.right)


def bound_inputs(binding, source_case, case, effective, output):
    """Keep original expectations; only the approved client toolchain/proof may move."""
    original = binding['inputs']
    require(isinstance(original, dict) and original, 'frozen input hash bindings missing')
    replaced = {source_case['variables'][key] for key in ('CARGO', 'SANDBOX_PROOF')}
    immutable = {path: expected for path, expected in original.items() if path not in replaced}
    for path, expected in immutable.items():
        require(digest(path) == expected, 'original immutable input changed: ' + path)
    for key in ('CHAT_TEMPLATE', 'CLIENT_APPROVAL_TEMPLATE', 'PEER_BIN'):
        path = source_case['variables'][key]
        require(path in immutable and case['variables'][key] == path, 'frozen input identity missing: ' + key)
    values = case['variables']
    proof = checked({'path': values['SANDBOX_PROOF'], 'sha256': values['SANDBOX_PROOF_SHA256']})
    cargo = Path(values['CARGO']).resolve(strict=True)
    toolchain = Path(proof['toolchain_root']).resolve(strict=True)
    require(cargo == toolchain / 'bin/cargo' and toolchain.name == values['TOOLCHAIN'] and
            digest(cargo) == proof['cargo_sha256'], 'replacement client toolchain differs from sandbox proof')
    current = q5_artifacts.input_hashes(effective, output)
    require(all(path not in immutable or immutable[path] == expected for path, expected in current.items()),
            'effective input rebases an immutable original hash')
    return {**immutable, **current, values['SANDBOX_PROOF']: values['SANDBOX_PROOF_SHA256'],
            values['CARGO']: proof['cargo_sha256']}


def prepare(args):
    original = load(args.source_plan)
    parent = load(args.parent_inputs)
    family = args.family
    expected_screens = 28 if family == 'qwen38' else 18
    incumbent = original.get('incumbent_name', original.get('incumbent'))
    require(len(original['screen_order']) == expected_screens and
            len(set(original['screen_order'])) == expected_screens and
            original['positions'] == ['warmup', 'p1', 'p2', 'p3'] and
            set(original['bindings']) == set(original['screen_order']) | {incumbent}, 'registered roster changed')
    require(not original['blockers'] and not original['unresolved_mandatory_arms'], 'mandatory input unresolved')
    require(original['strict_seconds'] == 360 and original['outer_seconds'] == 450 and
            original['outside_lease_spacing_seconds'] == 65, 'registered limits changed')
    require(original['comparison_failure_policy'] == {'version': 1, 'reruns_per_position': 2,
            'rerun_failure_kinds': ['task'], 'arms': ['peer']}, 'reference retry policy changed')
    require(args.previous_runtime.resolve() == registered_runtime(args.source_plan, args.source_selector, family).resolve(),
            'previous extension runtime differs from original frozen declaration')
    require(not (args.previous_runtime / 'RUN-CLAIM').exists(), 'previous extension already claimed; spend must not reset')
    if (args.previous_runtime / 'campaign.json').exists():
        require(not load(args.previous_runtime / 'campaign.json').get('attempts'),
                'previous extension has attempts; importing its spent positions is required, never restart')
    values = parent['family_overrides'][family]
    root = fresh(args.output)
    (root / 'cases').mkdir()
    registration = copy.deepcopy(original)
    pins = canonical_sources()
    refs = {'source_plan': reference(args.source_plan), 'source_selector': reference(args.source_selector),
            'parent_inputs': reference(args.parent_inputs),
            'source_prepared': reference(Path(args.source_plan).parent / 'prepared.json')}
    prepared = checked(refs['source_prepared'])
    require(prepared['plan_sha256'] == refs['source_plan']['sha256'], 'frozen preparation changed')
    if family == 'qwen38':
        refs['source_recipe'] = reference(args.source_plan.parent / 'recipe.json')
        require(checked(refs['source_recipe'])['upstream_executor'] == refs['source_selector'],
                'Qwen38 reduction must be the exact registered upstream selector')
    else:
        require(prepared['executor_sha256'] == refs['source_selector']['sha256'],
                'Qwen36 reduction must be the exact prepared selector')
    for key in ('old_reference', 'old_population'):
        if key in original:
            checked(original[key])
            pins[original[key]['path']] = original[key]['sha256']
    identity = checked(original['peer_identity'])
    pins[original['peer_identity']['path']] = original['peer_identity']['sha256']
    pins[original['peer_binary']['path']] = original['peer_binary']['sha256']
    for key in ('libraries_and_binary_sha256', 'external_dylibs_sha256', 'source_sha256'):
        pins.update(identity[key])
    bindings = {}
    for name, binding in original['bindings'].items():
        source_case = checked({'path': binding['case'], 'sha256': binding['sha256']})
        require(source_case['family'] == family and '--engine-kind' in source_case['client']['argv'] and
                source_case['client']['argv'][source_case['client']['argv'].index('--engine-kind') + 1] == 'peer',
                'only the exact registered peer cases are admitted')
        case = copy.deepcopy(source_case)
        # Candidate-side HF2Q_BIN/approval never replaces the peer engine approval.
        # Transport port and original peer launch argv are retained, not a sweep.
        for key in ('MODEL', 'MODEL_SHA256', 'MODEL_ID'):
            require(case['variables'][key] == values[key], 'parent original target identity differs: ' + key)
        for key in ('CARGO', 'TOOLCHAIN', 'SANDBOX_PROOF', 'SANDBOX_PROOF_SHA256'):
            case['variables'][key] = values[key]
        approval = load(case['variables']['CLIENT_APPROVAL_TEMPLATE'])
        require(approval.get('engine_kind') == 'peer' and approval['agent_template']['engine_kind'] == 'peer',
                'hf2q approval cannot authorize peer execution')
        require(approval['agent_template']['sandbox_proof_sha256'] ==
                source_case['variables']['SANDBOX_PROOF_SHA256'], 'original peer sandbox approval differs')
        proof = checked({'path': values['SANDBOX_PROOF'], 'sha256': values['SANDBOX_PROOF_SHA256']})
        require('agent_template' not in case['client']['approval']['set'],
                'original peer approval already overrides agent_template')
        # Preserve the immutable approval input; render only the sanctioned
        # client toolchain/proof substitutions into the actual launch approval.
        case['client']['approval']['set']['agent_template'] = {
            **approval['agent_template'], 'sandbox_proof_sha256': values['SANDBOX_PROOF_SHA256'],
            'cargo_sha256': proof['cargo_sha256'], 'toolchain': values['TOOLCHAIN']}
        case['policy'] = {**case.get('policy', {}), **POLICY}
        q5_case.validate(case)
        path = root / 'cases' / (name + '.json')
        save(path, case)
        effective = q5_case.build_plan(case, q5.builtins(root / 'unexecuted' / name), {})
        require(effective['complete'] and all(q5_artifacts.file_checks(effective).values()), 'case input unavailable: ' + name)
        require(case['serve'] == source_case['serve'] and case['workload'] == source_case['workload'] and
                case['readiness'] == source_case['readiness'] and case['artifact'] == source_case['artifact'],
                'frozen runtime settings changed')
        inputs = bound_inputs(binding, source_case, case, effective, root / 'unexecuted' / name)
        pins.update(inputs)
        pins[binding['case']] = binding['sha256']
        bindings[name] = {**binding, 'case': str(path), 'sha256': digest(path),
                          'original_case': {'path': binding['case'], 'sha256': binding['sha256']},
                          'effective_inputs': inputs}
        # Old private guards/prebindings remain in the original plan as evidence,
        # not as operating instructions in the successor binding.
        for key in ('guard', 'guard_sha256', 'prebinding'):
            bindings[name].pop(key, None)
        pins[str(path)] = digest(path)
    registration['bindings'] = bindings
    registration['cases'] = bindings
    plan = {'schema': 'hf2q.peer-existing-selector-canonical.v1', 'family': family, 'original': refs,
            'registration': registration, 'file_sha256': pins,
            'supervisor_source_bindings': q5.source_bindings(), 'supervisor_sources': q5.supervisor_sources(),
            'native_ownership_sources': q5_runtime.source_bindings(),
            'parent_family_values': values, 'strict_policy': POLICY, 'inner_seconds': 360, 'outer_seconds': 450,
            'required_volume': str(next(path for path in args.source_plan.resolve().parents if os.path.ismount(path))),
            'previous_runtime': str(args.previous_runtime.absolute()),
            'cooldown_seconds': 65, 'runtime_qualified': False, 'release_qualified': False}
    hostq = args.previous_runtime.parent.parent / 'hostq.sh'
    plan['hostq'] = reference(hostq)
    pins[str(hostq.resolve())] = digest(hostq)
    plan['power_helper'] = reference(HERE.parent / 'qwen36_watchdog_validate.sh')
    pins[plan['power_helper']['path']] = plan['power_helper']['sha256']
    for ref in refs.values():
        pins[ref['path']] = ref['sha256']
    save(root / 'plan.json', plan)
    print(json.dumps({'prepared': str(root / 'plan.json'), 'models_loaded': 0, 'readiness': False,
                      'fresh_source_matched_negative_control_required_at_dispatch': True}))


def frozen(path):
    plan = load(path)
    for name, expected in plan['file_sha256'].items():
        require(digest(name) == expected, 'source/input drift: ' + name)
    require(plan['supervisor_source_bindings'] == q5.source_bindings(), 'canonical source closure changed')
    require(plan['strict_policy'] == POLICY and plan['inner_seconds'] == 360 and
            plan['outer_seconds'] == 450 and plan['cooldown_seconds'] == 65, 'registered safety limits changed')
    snapshots(plan['registration'])
    identity = checked(plan['registration']['peer_identity'])
    for alias, binding in identity['dylib_alias_resolution'].items():
        require(str(Path(alias).resolve()) == binding['resolved'], 'peer dylib alias resolution changed')
        for link, target in binding['symlink_components'].items():
            require(os.readlink(link) == target, 'peer dylib alias changed')
    previous = Path(plan['previous_runtime'])
    require(previous.resolve() == registered_runtime(Path(plan['original']['source_plan']['path']),
            Path(plan['original']['source_selector']['path']), plan['family']).resolve(),
            'successor runtime differs from original frozen selector identity')
    require(not (previous / 'campaign.json').exists() or not load(previous / 'campaign.json').get('attempts'),
            'previous extension has historical spend; importing/refunding attempts is forbidden')
    if (previous / 'RUN-CLAIM').exists():
        claim = load(previous / 'RUN-CLAIM')
        require(claim.get('schema') == 'hf2q.peer-selector-claim.v1' and
                claim.get('plan') == reference(path) and claim.get('original') == plan['original'] and
                claim.get('previous_runtime') == str(previous.resolve()),
                'original selector already claimed by another owner; spend must not reset')
    require(not any(name.startswith(('HF2Q_Q5_', 'LLAMA_', 'MLX_')) for name in os.environ), 'ambient overrides forbidden')
    return plan


def original_reduction(plan, namespace):
    """Keep the original reducer/control flow, with only its attempt callback replaced."""
    ref = plan['original']['source_selector']
    require(digest(ref['path']) == ref['sha256'], 'original selector source changed')
    tree = ast.parse(Path(ref['path']).read_text())
    functions = {node.name: node for node in tree.body if isinstance(node, ast.FunctionDef)}
    run = functions['run']
    index = next(i for i, node in enumerate(run.body) if isinstance(node, ast.FunctionDef) and node.name == 'configuration')
    require(len(run.body[index:]) == 2 and isinstance(run.body[index + 1], ast.Try), 'original selector reduction boundary differs')
    select = ast.FunctionDef(name='select', args=ast.arguments(posonlyargs=[], args=[], vararg=None, kwarg=None,
                            kwonlyargs=[], kw_defaults=[], defaults=[]), body=run.body[index:],
                            decorator_list=[], returns=None, type_comment=None)
    nodes = [functions['rank']]
    if 'old_incumbent' in functions:
        nodes.append(functions['old_incumbent'])
    nodes.append(select)
    module = ast.fix_missing_locations(ast.Module(body=nodes, type_ignores=[]))
    exec(compile(module, ref['path'], 'exec'), namespace)
    return namespace


def storage(root, internal, volume):
    volume = Path(volume)
    require(os.path.ismount(volume) and root.resolve().is_relative_to(volume.resolve()) and
            os.stat(root).st_dev == os.stat(volume).st_dev, 'required external output volume unavailable')
    record = {'internal_free_bytes': shutil.disk_usage(internal).free, 'output_free_bytes': shutil.disk_usage(root).free,
              'internal_floor_bytes': 25 << 30, 'output_floor_bytes': 12 << 30, 'estimated_output_bytes': 8 << 30}
    record['passed'] = record['internal_free_bytes'] >= (25 << 30) and record['output_free_bytes'] >= (20 << 30)
    save(root / 'storage.json', record)
    require(record['passed'], 'original storage headroom gate refused')


def launch_claim(plan, plan_path, output, previous, control):
    runtime = Path(plan['previous_runtime']).resolve(strict=True)
    require(not (runtime / 'campaign.json').exists() or not load(runtime / 'campaign.json').get('attempts'),
            'original selector already has historical spend')
    claim = {'schema': 'hf2q.peer-selector-claim.v1', 'plan': reference(plan_path),
             'original': plan['original'], 'previous_runtime': str(runtime), 'output': str(output.resolve()),
             'last_completion': previous, 'negative_control': control}
    save(runtime / 'RUN-CLAIM', claim)  # Exclusive and permanent, including interrupted/failed launches.
    return reference(runtime / 'RUN-CLAIM')


def claimed_launch(plan, record):
    """Authenticate scheduled metadata against the owner's immutable pre-launch ledger."""
    claim_path = Path(plan['previous_runtime']).resolve() / 'RUN-CLAIM'
    require(record.get('launch_claim') == reference(claim_path), 'attempt has no original selector spend claim')
    claim = checked(record['launch_claim'])
    require(claim.get('schema') == 'hf2q.peer-selector-claim.v1' and claim['original'] == plan['original'] and
            claim['previous_runtime'] == str(Path(plan['previous_runtime']).resolve()) and
            checked(claim['plan']) == plan, 'attempt claim owner differs')
    unit = f"{record['phase']}-{record['case_name']}-{record['position']}-a{record['repeat']}"
    require(record['name'] == unit and Path(record['output']) == Path(claim['output']) / unit / 'q5',
            'attempt phase/position/retry differs from its captured unit/output')
    ledger = record['attempt_ledger']
    require(Path(ledger['path']) == Path(claim['output']) / 'launched' /
            f"{record['launch_index']:06d}-{unit}.json", 'attempt ledger is outside claimed sequence')
    scheduled = checked(ledger)
    require(all(record.get(key) == value for key, value in scheduled.items() if key != 'outcome'),
            'attempt differs from durable launched metadata')
    packet = load(Path(record['output']).parent / 'execution.json')
    require(packet['record'] == {**scheduled, 'attempt_ledger': ledger} and packet['plan'] == claim['plan'] and
            packet['negative_control'] == claim['negative_control'],
            'attempt packet differs from durable launched metadata')
    return scheduled


def replay_samples(receipt, output):
    def expanded(row):
        host = row.get('host')
        if host is None:
            return row
        vm = {key: host[key] for key in ('free_plus_cached_bytes', 'compressor_bytes', 'wired_bytes',
              'anonymous_bytes', 'file_backed_bytes', 'free_bytes', 'speculative_bytes')}
        return {**row, 'host': {**host, 'vm': vm, 'swap': {'used_bytes': host['swap_used_bytes']}}}
    baseline = [expanded(row) for row in receipt['preflight']['baseline_samples']]
    policy = q5_policy.effective_policy(receipt['policy'])
    actual, reason = q5_policy.baseline_from(baseline, policy)
    require(reason is None and actual == receipt['baseline'], 'strict baseline replay differs')
    inputs = receipt['floor_inputs']
    monitor = q5_policy.Monitor(actual, policy, inputs['latency_ns'], inputs['latency_source'],
                                inputs['seed_rate_bytes_per_s'])
    declared_ready = (receipt.get('readiness') or {}).get('ready_ns')
    allowed_ready = declared_ready if declared_ready is not None else (receipt.get('server') or {}).get('launch_ns')
    require(allowed_ready is None or (type(allowed_ready) is int and allowed_ready >= 0),
            'captured monitor activation clock invalid')
    def feed(row):
        require('monitor_ready_ns' in row, 'sample monitor_ready_ns capture missing')
        ready = row['monitor_ready_ns']
        require(ready is None or (type(ready) is int and ready >= 0 and ready == allowed_ready),
                'sample monitor readiness contradicts captured activation')
        require(monitor.ready_ns is None or ready == monitor.ready_ns, 'sample monitor readiness reset')
        monitor.ready_ns = ready
        monitor.feed(expanded(row))
    samples_path = Path(receipt['samples']['file'])
    with (samples_path if samples_path.is_absolute() else output / samples_path).open() as stream:
        for line in stream:
            feed(q5_case.loads(line))
    feed(receipt['post_cleanup_observation'])
    require(declared_ready is None or monitor.ready_ns == declared_ready,
            'final monitor readiness contradicts captured activation')
    require(monitor.summary() == {key: value for key, value in receipt['samples'].items() if key != 'file'},
            'raw strict sampler reduction differs')
    return monitor


def settle(plan, record):
    """Canonical launch/quality/ownership replay, also used without execution."""
    claimed_launch(plan, record)
    binding = plan['registration']['bindings'][record['case_name']]
    case = checked({'path': binding['case'], 'sha256': binding['sha256']})
    output = Path(record['output'])
    require(record['case'] == binding['case'] and record['case_sha256'] == binding['sha256'],
            'attempt case differs from registered configuration')
    outer = checked(record['runner_ownership'])
    require(outer.get('runner_sha256') == digest(quality_campaign.__file__) and
            outer['deadline']['seconds'] == 450 and not outer['deadline']['exceeded'], 'outer source/deadline differs')
    quality_launch.validate_runner(record, plan['supervisor_source_bindings'], allow_memory_stop=True)
    strict = outer['strict']
    control = checked(strict['negative_control'])
    require(control.get('supervisor_source_bindings') == plan['supervisor_source_bindings'] and
            control.get('supervisor_sources') == plan['supervisor_sources'] and
            q5.q5_admission.negative_control_latency(control) == strict['floor_inputs']['latency_ns'],
            'strict envelope control source/latency differs')
    expected_argv = quality_campaign.q5_argv(binding['case'], output, strict['negative_control']['path']) + [
        '--deadline-seconds', '360']
    require(record['argv'] == expected_argv, 'actual canonical invocation differs from registered configuration')
    require(strict['policy']['normal_pressure_only'] is True and strict['policy']['swap_growth_tolerance_bytes'] == 0 and
            strict['deadline']['seconds'] == 360 and outer['deadline']['started_ns'] <= strict['deadline']['started_ns'] <=
            outer['launch']['registered_ns'] and
            not strict['deadline']['exceeded'] and strict['sampler_alive'] is False and strict['sampler_error'] is None,
            'outer strict policy/deadline/observer differs')
    power = outer['power']
    require(power['helper'] == plan['power_helper'] and not power['errors'] and
            power['before']['mode'] == power['after']['mode'] and power['before']['mode'] in ('ac:0', 'ac:2', 'battery:2') and
            all(type(power[phase]['thermal']) is int and power[phase]['thermal'] in (0, 1) for phase in ('before', 'after')),
            'retained release power/thermal gate differs')
    strict_monitor = replay_samples(strict, output)
    stop = outer.get('stop')
    if stop is not None:
        require(strict_monitor.stop is not None and strict_monitor.stop['reason'] == stop['reason'] and
                stop['reason'] in q5_policy.MEMORY_STOPS, 'outer stop has no matching strict sample')
        return {**record, 'q5': str(output), 'outcome': 'Fail', 'failure_kind': 'memory_stop',
                'reason': stop['reason'], 'timing_used_for_selection': False,
                'cleanup_empty_ns': outer['cleanup']['empty_ns'], 'launch_ns': outer['launch']['registered_ns']}
    require(strict_monitor.stop is None and strict_monitor.max_blind_run == 0 and
            strict_monitor.sample_error_count == 0, 'strict outer observations invalid')
    receipt = load(output / 'receipt.json')
    deadline = receipt.get('deadline') or {}
    require(deadline.get('seconds') == 360 and deadline.get('origin') == 'main entry, never reset' and
            deadline.get('exceeded') is False and receipt.get('policy', {}).get('normal_pressure_only') is True and
            receipt.get('policy', {}).get('swap_growth_tolerance_bytes') == 0, 'inner strict policy/deadline differs')
    require(receipt.get('cleanup_proven') is True and receipt['cleanup']['proven'] is True and
            receipt.get('sampler_alive') is False and receipt.get('sampler_error') is None and
            receipt.get('listener_after_cleanup', {}).get('clear') is True, 'inner cleanup/sampler/listener unproven')
    monitor = replay_samples(receipt, output)
    if receipt.get('stop') is None:
        require(monitor.stop is None, 'unreported strict memory/observation stop')
    summary_path = output / 'client/summary.json'
    summary = q3_metrics.load_json(summary_path)
    outcome, kind, reason = q3_metrics.classify(receipt, summary, q3_metrics.has_oom_marker(output / 'server.stderr'))
    if outcome == 'Pass' or (summary is not None and receipt.get('client_native_launch') is not None):
        require(summary is not None and receipt.get('client_native_launch') is not None and
                (receipt.get('server') or {}).get('native_launch') is not None,
                'quality evidence requires actual server/client Native9 launches')
        quality_launch.validate(case, {}, record, receipt, summary, summary_path, plan)
        q2_run_audit.audit_quality_agents(receipt, summary_path.parent, summary, 'peer')
    thermal = record['post_thermal']
    require(type(thermal) is int and 0 <= thermal <= 3, 'captured post-run thermal observation required')
    require(thermal == power['after']['thermal'], 'post-run thermal differs from owned final observation')
    metrics = q3_metrics.run_metrics(output, receipt, summary, 4, thermal)
    if outcome == 'Pass':
        require(receipt['verdict']['verdict'] == 'CalibrationPass' and metrics['thermal']['valid'] is True and
                metrics['tasks_passed'] == 4 and metrics['makespan_s'] > 0 and len(summary['agents']) == 4,
                'actual CalibrationPass/thermal/four-task quality required')
        for agent in summary['agents'].values():
            tests = [tool for tool in agent['tools'] if tool.get('name') == 'run_tests' and tool.get('target') == 'all']
            require(tests and tests[-1].get('passed') is True, 'final own-output oracle missing')
        actual = family_peer.validate_speculation_proof(output / 'client', load(output / 'client-approval.json'))
        require(actual == summary.get('peer_speculation_proof'), 'actual speculation proof differs')
        if binding['trained']:
            require(all(actual['transports'][transport]['drafted_tokens'] > 0 and
                        actual['transports'][transport]['accepted_tokens'] > 0 for transport in ('unary', 'sse')),
                    'trained unary/SSE speculation not exercised')
    return {**record, 'q5': str(output), 'outcome': outcome, 'failure_kind': kind, 'reason': reason,
            'metrics': metrics, 'cleanup_empty_ns': max(outer['cleanup']['empty_ns'], receipt['cleanup']['empty_ns']),
            'launch_ns': outer['launch']['registered_ns']}


def completion_empty(plan, prior):
    if prior.get('launch') is not None:
        require(prior.get('source_bindings') == plan['supervisor_source_bindings'] and
                (prior.get('stop') is None or prior['stop'].get('reason') in q5_policy.MEMORY_STOPS),
                'previous outer completion source/stop differs')
        launches = [prior['launch']]
    else:
        require(prior.get('supervisor_source_bindings') == plan['supervisor_source_bindings'] and
                prior.get('cleanup_proven') is True, 'previous Q5 cleanup/source closure differs')
        launches = [prior['server']['native_launch']]
        if prior.get('client_native_launch') is not None:
            launches.append(prior['client_native_launch'])
        require(prior.get('stop') is None or prior.get('verdict', {}).get('verdict') == 'NegativeControlPass',
                'previous Q5 runtime did not complete normally')
    quality_launch.validate_cleanup(prior['cleanup'], launches)
    return prior['cleanup']['empty_ns']


def execute(args):
    """One existing hostq lease; only the canonical callback owns model processes."""
    packet = load(args.attempt)
    checked(packet['plan'])
    plan = frozen(Path(packet['plan']['path']))
    hostq = Path(plan['hostq']['path'])
    require(os.environ.get('HOSTQ_STATE_DIR') is None and
            (hostq.parent / 'HOST-LOCK').read_text().strip() == packet['lease_name'],
            'actual shared per-attempt hostq measurement lease required')
    record = packet['record']
    claimed_launch(plan, record)
    binding = plan['registration']['bindings'][record['case_name']]
    require(record['case'] == binding['case'] and record['case_sha256'] == binding['sha256'],
            'queued case binding changed')
    control = packet['negative_control']
    checked(control)
    root = Path(record['output']).parent
    expected = quality_campaign.q5_argv(binding['case'], root / 'q5', control['path']) + ['--deadline-seconds', '360']
    require(record['argv'] == expected and not Path(record['output']).exists(), 'queued canonical invocation changed')
    error = None
    with (root / 'stdout').open('xb') as stdout, (root / 'stderr').open('xb') as stderr:
        try:
            record['q5_exit'] = quality_campaign.subprocess_runner(
                expected, dict(os.environ), stdout, stderr, deadline_seconds=450,
                strict_policy=POLICY, strict_deadline_seconds=360, negative_control_receipt=control['path'],
                power_helper=plan['power_helper']['path'])
        except BaseException as exception:
            error = exception
            record['execution_error'] = repr(exception)
    proof_path = root / 'stdout.ownership.json'
    if proof_path.exists():
        record['runner_ownership'] = reference(proof_path)
    outer = load(proof_path) if proof_path.exists() else {}
    record['post_thermal'] = ((outer.get('power') or {}).get('after') or {}).get('thermal')
    inner = q3_metrics.load_json(root / 'q5/receipt.json') or {}
    post_source_error = None
    try:
        frozen(Path(packet['plan']['path']))
    except BaseException as exception:
        post_source_error = repr(exception)
        record['post_source_error'] = post_source_error
    retained = (not (outer.get('cleanup') or {}).get('proven') or
                (inner and not inner.get('cleanup_proven')) or
                (outer.get('strict') or {}).get('sampler_alive') or inner.get('sampler_alive') or post_source_error)
    record['retain_lease'] = bool(retained)
    save(root / 'execution-result.json', record)
    if retained:
        save(root / 'STOP', {'reason': 'Native9 cleanup or sampler shutdown unproven', 'parent_recovery_required': True})
        while True:
            time.sleep(3600)
    return 1 if error is not None else 0


def operate(args, replay=False):
    plan = frozen(args.plan)
    output = fresh(args.output)
    registration = plan['registration']
    replay_rows = checked(reference(args.attempts)) if replay else None
    if replay:
        require(isinstance(replay_rows, list), 'attempts must be the complete ordered JSON array')
        claim = load(Path(plan['previous_runtime']) / 'RUN-CLAIM')
        require(claim['plan'] == reference(args.plan), 'reduction must use the actual claimed plan')
        ledger = sorted((Path(claim['output']) / 'launched').iterdir())
        require(all(load(path)['launch_index'] == index for index, path in enumerate(ledger)),
                'durable launched ledger has missing/reordered attempts')
        if args.configuration is not None:
            ledger = [path for path in ledger if
                      (load(path)['case_name'], load(path)['phase']) == (args.configuration, args.phase)]
        require([row.get('attempt_ledger') for row in replay_rows] == [reference(path) for path in ledger],
                'replay must include the complete durable launched attempt sequence')
        previous_ref = claim['last_completion']
        previous_empty = None
    else:
        require(not (Path(plan['previous_runtime']) / 'RUN-CLAIM').exists(),
                'original selector already claimed; no retry/reset')
        previous_ref = {'path': str(args.last_completion), 'sha256': args.last_completion_sha256}
        previous_empty = completion_empty(plan, checked(previous_ref))
        control = checked(reference(args.negative_control_receipt))
        require(control.get('supervisor_sources') == plan['supervisor_sources'] and
                control.get('supervisor_source_bindings') == plan['supervisor_source_bindings'], 'fresh source-matched NC required')
        q5.q5_admission.negative_control_latency(control)
        (output / 'launched').mkdir()
        claim_ref = launch_claim(plan, args.plan, output, previous_ref, reference(args.negative_control_receipt))
    state = {'status': 'Running', 'attempts': [], 'release_qualified': False}
    save(output / 'plan.json', plan)
    cursor = 0
    seen_outputs = set()
    def persist():
        quality_campaign.save(output / 'campaign.json', state)
    persist()
    def attempt(name, phase, position, repeat):
        nonlocal cursor, previous_empty, previous_ref
        frozen(args.plan)
        unit = f'{phase}-{name}-{position}-a{repeat}'
        if replay:
            require(cursor < len(replay_rows), 'unexecuted mandatory position; selection forbidden')
            record = replay_rows[cursor]
            cursor += 1
            require((record['case_name'], record['phase'], record['position'], record['repeat']) ==
                    (name, phase, position, repeat), 'attempt order/retry/confirmation differs from original selector')
        else:
            root = output / unit
            root.mkdir()
            storage(root, Path.home(), plan['required_volume'])
            remaining = 65 - (time.monotonic_ns() - previous_empty) / 1e9
            if remaining > 0:
                time.sleep(remaining)
            frozen(args.plan)
            binding = registration['bindings'][name]
            argv = quality_campaign.q5_argv(binding['case'], root / 'q5', str(args.negative_control_receipt)) + ['--deadline-seconds', '360']
            record = {'name': unit, 'case_name': name, 'phase': phase, 'position': position, 'repeat': repeat,
                      'case': binding['case'], 'case_sha256': binding['sha256'], 'output': str(root / 'q5'),
                      'argv': argv, 'outcome': 'Launched', 'previous_completion': previous_ref,
                      'launch_claim': claim_ref, 'launch_index': len(state['attempts'])}
            ledger_path = output / 'launched' / f"{record['launch_index']:06d}-{unit}.json"
            save(ledger_path, record)
            record['attempt_ledger'] = reference(ledger_path)
            state['attempts'].append(record)
            persist()  # Spend is durable before the canonical owned launch.
            packet = root / 'execution.json'
            lease_name = 'canonical-' + plan['family'] + '-' + unit
            save(packet, {'plan': reference(args.plan), 'record': record, 'lease_name': lease_name,
                          'negative_control': reference(args.negative_control_receipt)})
            queue_argv = ['/bin/bash', plan['hostq']['path'], lease_name, 'measure', '--', sys.executable,
                          '-B', str(Path(__file__).resolve()), 'execute', '--attempt', str(packet)]
            with (root / 'hostq.stdout').open('xb') as stdout, (root / 'hostq.stderr').open('xb') as stderr:
                code = subprocess.run(queue_argv, stdin=subprocess.DEVNULL, stdout=stdout, stderr=stderr).returncode
            require((root / 'execution-result.json').is_file(), 'queued owner exited without a cleanup result')
            record.update(load(root / 'execution-result.json'))
            persist()
            require(not record.get('retain_lease'), 'queued owner retained the model lease')
            if code != 0:
                outer = checked(record['runner_ownership'])
                require((outer.get('stop') or {}).get('reason') in q5_policy.MEMORY_STOPS,
                        'queued canonical execution failed: ' + record.get('execution_error', str(code)))
        frozen(args.plan)
        identity = str(Path(record['output']).resolve())
        require(identity not in seen_outputs, 'canonical receipt reused across positions')
        seen_outputs.add(identity)
        if previous_empty is None:
            previous_empty = completion_empty(plan, checked(record['previous_completion']))
        row = settle(plan, record)
        if previous_empty is not None:
            require(row['launch_ns'] - previous_empty >= 65_000_000_000, 'original post-cleanup cooldown violated')
        previous_empty = row['cleanup_empty_ns']
        previous_ref = record['runner_ownership']
        if replay:
            state['attempts'].append(row)
        else:
            record.update(row)
        persist()
        return row
    def result_save(path, value):
        if replay and Path(path).name == 'confirmed-reference.json':
            require(cursor == len(replay_rows), 'extra attempts forbid a complete selection')
        save(path, value)
    namespace = dict(require=require, load=load, save=result_save, digest=digest, Path=Path, statistics=statistics,
                     q3_stats=q3_stats, p=registration, prepared={'bindings': registration['bindings']}, E=output,
                     state=state, persist=persist, attempt=attempt)
    try:
        original = original_reduction(plan, namespace)
        if replay and args.configuration is not None:
            configuration = next(node for node in ast.parse(Path(plan['original']['source_selector']['path']).read_text()).body
                                 if isinstance(node, ast.FunctionDef) and node.name == 'run')
            configuration = next(node for node in configuration.body if isinstance(node, ast.FunctionDef) and node.name == 'configuration')
            exec(compile(ast.fix_missing_locations(ast.Module(body=[configuration], type_ignores=[])),
                         plan['original']['source_selector']['path'], 'exec'), original)
            require(args.configuration in registration['bindings'], 'unregistered configuration')
            score = original['configuration'](args.configuration, args.phase)
            require(cursor == len(replay_rows), 'extra attempts cannot be dropped')
            save(output / 'configuration-score.json', {'case': args.configuration, 'rank': score,
                 'complete_selection': False, 'release_qualified': False})
            return 0 if score is not None else 3
        result = original['select']()
        if replay:
            require(cursor == len(replay_rows), 'extra attempts cannot be dropped')
        return result
    except BaseException as error:
        state.update(status='Halted', reason=repr(error))
        persist()
        raise


def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    sub = parser.add_subparsers(dest='command', required=True)
    preparation = sub.add_parser('prepare')
    preparation.add_argument('--family', choices=('qwen38', 'qwen36'), required=True)
    preparation.add_argument('--previous-runtime', type=Path, required=True)
    for name in ('source-plan', 'source-selector', 'parent-inputs', 'output'):
        preparation.add_argument('--' + name, type=Path, required=True)
    for command in ('run', 'reduce'):
        child = sub.add_parser(command)
        child.add_argument('--plan', type=Path, required=True)
        child.add_argument('--output', type=Path, required=True)
        if command == 'run':
            child.add_argument('--negative-control-receipt', type=Path, required=True)
            child.add_argument('--last-completion', type=Path, required=True)
            child.add_argument('--last-completion-sha256', required=True)
        else:
            child.add_argument('--attempts', type=Path, required=True)
            child.add_argument('--configuration')
            child.add_argument('--phase', choices=('screen', 'confirm'), default='screen')
    execution = sub.add_parser('execute')
    execution.add_argument('--attempt', type=Path, required=True)
    args = parser.parse_args(argv)
    if args.command == 'prepare':
        return prepare(args)
    if args.command == 'execute':
        return execute(args)
    return operate(args, replay=args.command == 'reduce')


if __name__ == '__main__':
    try:
        raise SystemExit(main())
    except (ValueError, OSError, KeyError, TypeError) as error:
        print(json.dumps({'valid': False, 'error': str(error), 'release_qualified': False}), file=sys.stderr)
        raise SystemExit(2)