main
John Lauer Document silkscreen export warning isolation and prepare narrated results review 46fcaab
"""Review a bench thermal capture without changing AIFlow acceptance or hardware state.

CSV columns: time_s, case_c, ambient_c, current_a, load_enabled, fan_rpm.
This checks recorded samples only; sampling gaps, sensor placement and calibration
remain part of the reviewed acquisition plan. It cannot certify between-sample peaks.
"""
import argparse
import csv
import hashlib
import json
import math
from pathlib import Path


def finite(value, name):
    if isinstance(value, bool):
        raise ValueError(f'{name}: boolean is not a measurement')
    v = float(value)
    if not math.isfinite(v):
        raise ValueError(f'{name}: non-finite value')
    return v


def review(manifest_path):
    manifest_path = Path(manifest_path)
    m = json.loads(manifest_path.read_text())
    required = ['capture', 'origin', 'board_sha256', 'firmware_sha256',
                'assembly_id', 'acquisition_plan', 'calibration_evidence',
                'case_uncertainty_c', 'current_uncertainty_a',
                'time_uncertainty_s', 'maximum_sample_gap_s',
                'fault_time_s', 'required_observation_end_s',
                'shutdown_deadline_s', 'off_current_limit_a']
    missing = [k for k in required if m.get(k) is None or m.get(k) == '']
    if missing:
        return {'status': 'blocked', 'eligibleHardwareEvidence': False,
                'issues': ['Missing acquisition input: ' + k for k in missing]}
    issues = []
    if m['origin'] != 'measured-hardware':
        issues.append('Synthetic or unknown origin: not hardware qualification evidence')
    for name in ['board_sha256', 'firmware_sha256']:
        h = m[name]
        if not isinstance(h, str) or len(h) != 64 or any(c not in '0123456789abcdef' for c in h):
            issues.append('Invalid identity: ' + name)
    evidence_hashes = {}
    for key in ['acquisition_plan', 'calibration_evidence']:
        p = manifest_path.parent / m[key]
        if not p.is_file() or not p.stat().st_size:
            issues.append('Missing evidence file: ' + key)
        else:
            evidence_hashes[key] = hashlib.sha256(p.read_bytes()).hexdigest()
    values = {k: finite(m[k], k) for k in required if k.endswith(('_c', '_a', '_s'))}
    for k in ['case_uncertainty_c', 'current_uncertainty_a', 'time_uncertainty_s']:
        if values[k] < 0:
            raise ValueError(k + ' must be nonnegative')
    for k in ['maximum_sample_gap_s', 'shutdown_deadline_s', 'off_current_limit_a']:
        if values[k] <= 0:
            raise ValueError(k + ' must be positive')
    capture = manifest_path.parent / m['capture']
    if not capture.is_file():
        return {'status': 'blocked', 'eligibleHardwareEvidence': False,
                'issues': issues + ['Capture file does not exist']}
    rows = []
    with capture.open(newline='') as f:
        for row in csv.DictReader(f):
            r = {k: finite(row[k], k) for k in ['time_s', 'case_c', 'ambient_c', 'current_a', 'load_enabled', 'fan_rpm']}
            if r['load_enabled'] not in [0, 1] or r['fan_rpm'] < 0:
                raise ValueError('Invalid enable/RPM sample')
            rows.append(r)
    if len(rows) < 2:
        raise ValueError('At least two samples required')
    gaps = [b['time_s'] - a['time_s'] for a, b in zip(rows, rows[1:])]
    if min(gaps) <= 0:
        raise ValueError('Sample times must be strictly increasing')
    if max(gaps) > values['maximum_sample_gap_s'] + 1e-12:
        issues.append('Acquisition contains excessive sample gaps')
    fault = values['fault_time_s']
    end = values['required_observation_end_s']
    deadline = fault + values['shutdown_deadline_s']
    if end <= deadline:
        raise ValueError('Observation end must be after the shutdown deadline')
    if rows[0]['time_s'] >= fault or rows[-1]['time_s'] < end:
        issues.append('Capture does not cover pre-fault and required post-fault window')
    pre = [r for r in rows if r['time_s'] < fault]
    if not any(r['load_enabled'] == 1 and r['current_a'] - values['current_uncertainty_a'] > values['off_current_limit_a'] for r in pre):
        issues.append('No loaded pre-fault sample; shutdown was not exercised')
    peak = max(r['case_c'] for r in rows) + values['case_uncertainty_c']
    if peak > 55:
        issues.append('Recorded case temperature plus stated uncertainty exceeds unchanged 55 C ceiling')
    def off(r):
        return r['load_enabled'] == 0 and abs(r['current_a']) + values['current_uncertainty_a'] <= values['off_current_limit_a']
    # Accept only a sustained observed off state, including timestamp uncertainty.
    last_on = max((i for i, r in enumerate(rows) if not off(r)), default=-1)
    first = rows[last_on + 1] if last_on + 1 < len(rows) else None
    latency = None
    if first is None:
        issues.append('No sustained observed off state')
    else:
        latency = first['time_s'] - fault + 2 * values['time_uncertainty_s']
        if first['time_s'] < fault:
            issues.append('Sustained off state predates the fault')
        if latency > values['shutdown_deadline_s'] + 1e-12:
            issues.append('Observed shutdown exceeds supplied test-plan deadline including timing uncertainty')
    return {'status': 'fail' if issues else 'sample-check-pass',
            'eligibleHardwareEvidence': not issues and m['origin'] == 'measured-hardware',
            'issues': issues, 'sampleCount': len(rows),
            'maximumSampleGapS': max(gaps), 'peakCaseUpperBoundC': peak,
            'observedShutdownUpperLatencyS': latency,
            'captureSha256': hashlib.sha256(capture.read_bytes()).hexdigest(),
            'manifestSha256': hashlib.sha256(manifest_path.read_bytes()).hexdigest(),
            'evidenceHashes': evidence_hashes,
            'limits': 'Recorded-sample review only. Does not verify sensor placement, uncertainty validity, test severity, between-sample behavior, airflow, calibration contents or reviewer approval. Does not pass AIFlow or unlock firmware.'}


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('manifest');p.add_argument('--out')
    args = p.parse_args()
    try:
        result = review(args.manifest)
    except (ValueError, KeyError, OSError, TypeError) as e:
        result = {'status': 'invalid', 'eligibleHardwareEvidence': False, 'issues': [str(e)]}
    text = json.dumps(result, indent=2) + '\n'
    if args.out:
        Path(args.out).write_text(text)
    print(text, end='')
    return 0 if result['status'] == 'sample-check-pass' else 2

if __name__ == '__main__':
    raise SystemExit(main())