| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527 |
- #!/usr/bin/env python3
- """UART/RS232 receipt builders and validators that do not depend on ChipWatcher."""
- from __future__ import annotations
- import argparse
- import copy
- import hashlib
- import importlib.util
- import json
- import os
- import re
- import subprocess
- import sys
- from datetime import datetime, timezone
- from pathlib import Path
- from typing import Any
- ROOT = Path(__file__).resolve().parents[1]
- FORBIDDEN_ACTION_MARKERS = [
- "PROGRAM_FLASH",
- "ERASE_FLASH",
- "PROGRAM_SPIBIN",
- "DIRECT_FLASH_WRITE",
- "DRIVER_INSTALL",
- "DRIVER_REINSTALL",
- "REAL_PTC",
- "REAL_FAN",
- "REAL_BMC",
- ]
- REAL_BMC_J6_FORBIDDEN_ACTION_MARKERS = [
- marker for marker in FORBIDDEN_ACTION_MARKERS if marker != "REAL_BMC"
- ]
- REAL_BMC_J6_FORBIDDEN_ACTION_MARKERS.extend(
- [
- "DRIVER_INSTALL",
- "DRIVER_REINSTALL",
- "PROGRAM_DEVICE",
- "DOWNLOAD",
- "CONNECT_CABLE",
- "OPEN_COM",
- "COM_OPEN",
- "TOGGLE_DTR",
- "TOGGLE_RTS",
- "READ_DEVICE_ID",
- ]
- )
- REAL_BMC_J6_WINDOWS_FORBIDDEN_ACTION_MARKERS = [
- marker
- for marker in REAL_BMC_J6_FORBIDDEN_ACTION_MARKERS
- if marker not in {"OPEN_COM", "COM_OPEN"}
- ]
- OFFLINE_FIDELITY_FORBIDDEN_ACTION_MARKERS = [
- *FORBIDDEN_ACTION_MARKERS,
- "PROGRAM_SRAM",
- "OPEN_COM",
- "COM_OPEN",
- "TOGGLE_DTR",
- "TOGGLE_RTS",
- "DTR",
- "RTS",
- "CONNECT_CABLE",
- "DOWNLOAD",
- "PROGRAM_DEVICE",
- "READ_DEVICE_ID",
- ]
- UART_SCHEMAS = {
- "uart-preflight-receipt-v1": "uart-preflight-validation-v1",
- "bmc-uart-protocol-receipt-v1": "bmc-uart-protocol-validation-v1",
- "uart-loopback-receipt-v1": "uart-loopback-validation-v1",
- "uart-board-sram-receipt-v1": "uart-board-sram-validation-v1",
- "uart-soak-receipt-v1": "uart-soak-validation-v1",
- }
- FINAL_GATE_REQUIRED_LAYERS = [
- "static",
- "model",
- "replay",
- "rtl_sim",
- "formal",
- "detector_selftest",
- "td_build",
- "uart_strict",
- ]
- OFFLINE_FIDELITY_REQUIRED_LAYERS = [
- "static",
- "model",
- "replay",
- "protocol_fuzz",
- "hdl_sim",
- "cocotb_virtual_lab",
- "virtual_driver_lab",
- "formal",
- "detector_selftest",
- "mutation",
- "thermal_digital_twin",
- "coverage_matrix",
- "td_build",
- "debug_bundle",
- ]
- OFFLINE_FIDELITY_FORBIDDEN_LAYERS = {
- "hardware",
- "board",
- "uart_strict",
- "chipwatcher",
- "thermal_performance_pass",
- }
- OFFLINE_FIDELITY_LAYER_EVIDENCE = {
- "static": ["returncode"],
- "model": ["tests"],
- "replay": ["sample_count"],
- "protocol_fuzz": ["scenarios"],
- "hdl_sim": ["tests", "backend_results"],
- "cocotb_virtual_lab": ["sim"],
- "virtual_driver_lab": ["user_mode_shims", "trace_hash"],
- "formal": ["targets"],
- "detector_selftest": ["results"],
- "mutation": ["mutants"],
- "thermal_digital_twin": ["models"],
- "coverage_matrix": ["items"],
- "td_build": ["elaboration"],
- "debug_bundle": ["path", "bundle_dir"],
- }
- OFFLINE_FIDELITY_REQUIRED_COVERAGE_CATEGORIES = {
- "protocol",
- "uart_bit",
- "control",
- "safety",
- "debug",
- "virtual_driver_lab",
- "thermal",
- "fault_injection",
- "cocotb_virtual_lab",
- "formal",
- "mutation",
- "td_toolchain",
- }
- OFFLINE_FIDELITY_REQUIRED_VIRTUAL_SHIMS = {
- "pyserial_loopback_url",
- "socket_pipe_transport",
- "bmc_text_driver",
- "host_register_plane",
- "debug_uart_decoder",
- "fault_injection_facade",
- }
- OFFLINE_FIDELITY_REQUIRED_VIRTUAL_FAULTS = {
- "timeout",
- "disconnect",
- "partial_read",
- "partial_write",
- "permission_denied",
- "buffer_overflow",
- "tx_backpressure",
- "rx_overflow",
- }
- OFFLINE_FIDELITY_REQUIRED_THERMAL_SCENARIOS = {
- "conservative",
- "optimistic",
- "extreme",
- "random_perturbation",
- "sensor_drift",
- "sensor_delay",
- "crosstalk",
- "fan_degradation",
- "ptc_thermal_inertia",
- }
- OFFLINE_FIDELITY_REQUIRED_MUTANTS = {
- "invert_fault_condition",
- "remove_force_off",
- "break_channel_compare",
- "drop_debug_event",
- "break_debug_checksum",
- "bad_formal_property",
- }
- OFFLINE_FIDELITY_REQUIRED_TOOLCHAIN_TOOLS = {
- "python",
- "iverilog",
- "vvp",
- "verilator",
- "yosys",
- "sby",
- "cocotb",
- "td_cli",
- }
- REAL_BMC_J6_WINDOWS_REQUIRED_LAYERS = [
- "td_bitstream",
- "manual_sram_programming",
- "windows_serial_capture",
- "real_bmc_protocol",
- "safety_contract",
- "artifact_hashes",
- ]
- REAL_BMC_J6_WINDOWS_ALLOWED_LAYER_SET = set(REAL_BMC_J6_WINDOWS_REQUIRED_LAYERS)
- REAL_BMC_J6_WINDOWS_ALLOWED_PIN_PROFILES = {
- "primary": {"tx_ball": "T4", "rx_ball": "R5", "debug_rx_ball": "P10", "debug_tx_ball": "R10"},
- "swapped": {"tx_ball": "R5", "rx_ball": "T4", "debug_rx_ball": "P10", "debug_tx_ball": "R10"},
- }
- REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_REQUIRED_LAYERS = [
- "td_bitstream",
- "manual_sram_programming",
- "host_command_sequence",
- "host_control_transcript",
- "host_sensor_reports",
- "debug_frame_capture",
- "bmc_raw_sampling",
- "pid_boundary",
- "timeout_evidence",
- "pin_map",
- "safety_contract",
- "real_fan_ptc_hardware_status",
- "artifact_hashes",
- ]
- REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_LAYER_SET = set(
- REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_REQUIRED_LAYERS
- )
- REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_TOP_MODULE = (
- "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921_top"
- )
- REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_TOP_MODULES_BY_PIN_PROFILE = {
- "temp-uart-ptc-remap": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921_top",
- "formal-uart": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921_top",
- }
- REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_PIN_PROFILES = {
- "temp-uart-ptc-remap": {
- "tx_ball": "T4",
- "rx_ball": "R5",
- "bmc_tx_ball": "T4",
- "bmc_rx_ball": "R5",
- "host_tx_ball": "P7",
- "host_rx_ball": "P8",
- "debug_rx_ball": "P10",
- "debug_tx_ball": "R10",
- },
- "formal-uart": {
- "tx_ball": "P5",
- "rx_ball": "T8",
- "bmc_tx_ball": "P5",
- "bmc_rx_ball": "T8",
- "host_tx_ball": "M14",
- "host_rx_ball": "M15",
- "debug_rx_ball": "P15",
- "debug_tx_ball": "N14",
- },
- }
- REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_COMMANDS = [
- "SET PTC 01 10",
- "SET PTC 24 20",
- "SET FAN 01 40",
- "SET FAN 04 30",
- "SET PID ENABLE",
- "GET STATUS",
- "GET MAP",
- "GET SENSOR",
- "GET SENSOR",
- "GET SENSOR",
- "SET PID DISABLE",
- "DISABLE",
- ]
- REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_ACK_CMDS = {
- "SET PTC 01 10": "PTCCH",
- "SET PTC 24 20": "PTCCH",
- "SET FAN 01 40": "FANCH",
- "SET FAN 04 30": "FANCH",
- "SET PID ENABLE": "PID_EN",
- "GET STATUS": "STATUS",
- "GET MAP": "MAP___",
- "GET SENSOR": "SENSOR",
- "SET PID DISABLE": "PID_DI",
- "DISABLE": "DISABL",
- }
- REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_COMMAND_RE = re.compile(
- r"^(?:"
- r"SET PTC (?:0[1-9]|1[0-9]|2[0-4]) (?:0|[1-9][0-9]?|100)|"
- r"SET FAN (?:0[1-4]) (?:0|[1-9][0-9]?|100)|"
- r"SET PID ENABLE|"
- r"SET PID DISABLE|"
- r"GET STATUS|"
- r"GET MAP|"
- r"GET SENSOR|"
- r"DISABLE"
- r")$"
- )
- REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_FORBIDDEN_ACTION_MARKERS = [
- marker
- for marker in REAL_BMC_J6_WINDOWS_FORBIDDEN_ACTION_MARKERS
- if marker not in {"REAL_FAN", "REAL_PTC"}
- ]
- REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_REQUIRED_SAFETY_FALSE_FIELDS = [
- "flash_attempted",
- "driver_install_attempted",
- "programs_flash",
- "programs_nonvolatile",
- "opens_unknown_com_ports",
- "enumerates_com_ports",
- "toggles_dtr_rts",
- "debug_port_writes_to_serial",
- "uncontrolled_real_bmc_action_attempted",
- "real_thermal_performance_claimed",
- ]
- REAL_BMC_J6_WINDOWS_REQUIRED_SAFETY_FALSE_FIELDS = [
- "flash_attempted",
- "driver_install_attempted",
- "programs_flash",
- "opens_unknown_com_ports",
- "toggles_dtr_rts",
- "ptc_fan_pins_exported",
- "real_ptc_fan_action_attempted",
- "uncontrolled_real_bmc_action_attempted",
- ]
- REAL_BMC_J6_ACTION_SAFETY_ALIASES = {
- "com_open",
- "connect_cable",
- "connects_cable",
- "download_to_hardware",
- "downloads_to_hardware",
- "driver_install",
- "driver_installed",
- "erase_flash",
- "install_driver",
- "installs_drivers",
- "open_com",
- "opened_com",
- "program_device",
- "program_flash",
- "programs_device",
- "read_device_id",
- "real_bmc_action_attempted",
- "real_fan_action_attempted",
- "real_ptc_action_attempted",
- "real_ptc_fan_bmc_action_attempted",
- "touches_ptc_fan_bmc",
- "toggle_dtr",
- "toggle_rts",
- "toggles_dtr",
- "toggles_rts",
- }
- J6SYS_RE = re.compile(
- r"J6SYS\s+wake=(?P<wake>[0-9A-Fa-f]{8})\s+poll=(?P<poll>[0-9A-Fa-f]{8})"
- r"\s+tx=(?P<tx>[0-9A-Fa-f]{8})\s+rx=(?P<rx>[0-9A-Fa-f]{8})"
- r"\s+uerr=(?P<uerr>[0-9A-Fa-f]{2,8})\s+state=(?P<state>[0-9A-Fa-f]+)"
- r"\s+tok=(?P<tok>[0-9A-Fa-f]{8})\s+seq=(?P<seq>[0-9A-Fa-f]{8})"
- r"\s+valid=(?P<valid>[0-9A-Fa-f]{8})\s+perr=(?P<perr>[0-9A-Fa-f]+)"
- r"\s+stale=(?P<stale>[0-9A-Fa-f]+)\s+frame=(?P<frame>[0-9A-Fa-f]+)"
- r"\s+duovf=(?P<duovf>[0-9A-Fa-f]+)\s+dbg=(?P<dbg>[0-9A-Fa-f]{8})"
- r"\s+derr=(?P<derr>[0-9A-Fa-f]{8})"
- )
- def _parse_j6sys_line(raw: str) -> dict[str, object] | None:
- match = J6SYS_RE.search(raw)
- if not match:
- return None
- return {
- "kind": "j6sys",
- "raw": raw,
- "wake": int(match.group("wake"), 16),
- "poll": int(match.group("poll"), 16),
- "tx": int(match.group("tx"), 16),
- "rx": int(match.group("rx"), 16),
- "uerr": int(match.group("uerr"), 16),
- "state": int(match.group("state"), 16),
- "tok": int(match.group("tok"), 16),
- "seq": int(match.group("seq"), 16),
- "valid": int(match.group("valid"), 16),
- "perr": int(match.group("perr"), 16),
- "stale": int(match.group("stale"), 16),
- "frame": int(match.group("frame"), 16),
- "duovf": int(match.group("duovf"), 16),
- "dbg": int(match.group("dbg"), 16),
- "derr": int(match.group("derr"), 16),
- }
- def utc_now() -> str:
- return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
- def compute_file_hash(path: Path | str) -> str:
- digest = hashlib.sha256()
- with Path(path).open("rb") as handle:
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def read_json(path: Path | str) -> dict[str, Any]:
- return json.loads(Path(path).read_text(encoding="utf-8-sig"))
- def backend_capabilities() -> dict[str, Any]:
- has_pyserial = importlib.util.find_spec("serial") is not None
- has_jsonschema = importlib.util.find_spec("jsonschema") is not None
- return {
- "schema": "uart-tool-backend-capabilities-v1",
- "generated_at": utc_now(),
- "python": sys.executable,
- "serial_backend": "pyserial" if has_pyserial else "powershell_dotnet_limited",
- "schema_backend": "jsonschema" if has_jsonschema else "builtin_limited",
- "pyserial_available": has_pyserial,
- "jsonschema_available": has_jsonschema,
- "strict_gate_requires": [
- "explicit COM allowlist",
- "hashes for transcript and bitstream artifacts",
- "SRAM-only programming evidence",
- "debug UART event stream",
- "register dump snapshot",
- ],
- }
- def _resolve_receipt_path(receipt_path: Path, value: Any) -> Path:
- if isinstance(value, dict):
- value = value.get("path")
- path = Path(str(value))
- if not path.is_absolute():
- path = receipt_path.parent / path
- return path
- def _receipt_path_candidates(receipt_path: Path, value: Any) -> list[tuple[Path, str]]:
- if isinstance(value, dict):
- value = value.get("path")
- raw = str(value)
- path = Path(raw)
- if not path.is_absolute():
- return [(receipt_path.parent / path, "package_relative")]
- candidates: list[tuple[Path, str]] = [(path, "as_recorded")]
- package_dir = receipt_path.parent
- if path.name:
- try:
- if path.parent.name == package_dir.name:
- candidates.append((package_dir / path.name, "package_relative"))
- else:
- candidates.append((package_dir / path.name, "package_basename"))
- except OSError:
- candidates.append((package_dir / path.name, "package_basename"))
- package_name = package_dir.name
- parts = path.parts
- if package_name in parts:
- index = parts.index(package_name)
- suffix = Path(*parts[index + 1 :]) if index + 1 < len(parts) else Path()
- if str(suffix):
- candidates.append((package_dir / suffix, "package_suffix"))
- deduped: list[tuple[Path, str]] = []
- seen: set[str] = set()
- for candidate, resolution in candidates:
- key = str(candidate)
- if key in seen:
- continue
- seen.add(key)
- deduped.append((candidate, resolution))
- return deduped
- def _hash_validation(receipt_path: Path, item: Any, *, required: bool) -> dict[str, Any]:
- if not item:
- return {"status": "missing" if required else "not_provided", "exists": False}
- raw_path = item.get("path") if isinstance(item, dict) else item
- expected = item.get("sha256") if isinstance(item, dict) else None
- if not raw_path:
- return {"status": "missing", "exists": False}
- candidates = _receipt_path_candidates(receipt_path, item)
- path, resolution = candidates[0]
- for candidate, candidate_resolution in candidates:
- if candidate.is_file():
- path = candidate
- resolution = candidate_resolution
- break
- result: dict[str, Any] = {
- "raw_path": str(raw_path),
- "path": str(path),
- "exists": path.is_file(),
- "resolution": resolution,
- "tried": [str(candidate) for candidate, _ in candidates],
- }
- if not path.is_file():
- result["status"] = "missing"
- return result
- actual = compute_file_hash(path)
- result["sha256"] = actual
- if not expected:
- result["status"] = "missing_hash"
- elif str(expected).lower() != actual:
- result["status"] = "hash_mismatch"
- else:
- result["status"] = "pass"
- return result
- def _hash_validation_with_optional_receipt_path(
- receipt_path: Path | None,
- item: Any,
- *,
- required: bool,
- ) -> dict[str, Any]:
- if receipt_path is not None:
- return _hash_validation(receipt_path, item, required=required)
- if not item:
- return {"status": "missing" if required else "not_provided", "exists": False}
- raw_path = item.get("path") if isinstance(item, dict) else item
- expected = item.get("sha256") if isinstance(item, dict) else None
- if not raw_path:
- return {"status": "missing", "exists": False}
- path = Path(str(raw_path))
- result: dict[str, Any] = {
- "raw_path": str(raw_path),
- "path": str(path),
- "exists": path.is_file() if path.is_absolute() else False,
- "resolution": "absolute_direct" if path.is_absolute() else "unresolved_without_receipt_path",
- "tried": [str(path)],
- }
- if not path.is_absolute():
- result["status"] = "relative_without_receipt_path"
- return result
- if not path.is_file():
- result["status"] = "missing"
- return result
- actual = compute_file_hash(path)
- result["sha256"] = actual
- if not expected:
- result["status"] = "missing_hash"
- elif str(expected).lower() != actual:
- result["status"] = "hash_mismatch"
- else:
- result["status"] = "pass"
- return result
- def _safe_int(value: Any, *, default: int | None = None) -> int | None:
- try:
- if isinstance(value, bool):
- return int(value)
- if isinstance(value, str):
- token = value.strip()
- if token.lower().startswith("0x"):
- return int(token[2:], 16)
- if re.fullmatch(r"[0-9A-Fa-f]+", token) and any(ch in "ABCDEFabcdef" for ch in token):
- return int(token, 16)
- return int(value)
- except (TypeError, ValueError):
- return default
- def _safe_fixed_hex_int(value: Any, *, default: int | None = None) -> int | None:
- try:
- if isinstance(value, bool):
- return int(value)
- if isinstance(value, int):
- return value
- if isinstance(value, str):
- token = value.strip()
- if token.lower().startswith("0x"):
- token = token[2:]
- if re.fullmatch(r"[0-9A-Fa-f]+", token):
- return int(token, 16)
- return int(value)
- except (TypeError, ValueError):
- return default
- def _raw_field_token(raw: Any, key: str) -> str | None:
- if not isinstance(raw, str):
- return None
- match = re.search(rf"(?:^|\s){re.escape(key)}=([^ \t\r\n]+)", raw)
- if not match:
- return None
- return match.group(1).rstrip("\\r").rstrip("\\n")
- def _normalize_compact_alias_value(field: str, value: Any) -> Any:
- if not isinstance(value, str):
- return value
- if field in {"source", "pwm_source"} and value == "hm":
- return "host_manual"
- if field == "status" and value == "ok":
- return "valid"
- if field == "status" and value == "v":
- return "valid"
- if field == "status" and value == "a":
- return "all_ff"
- if field == "status" and value == "m":
- return "missing"
- return value
- def _artifact_hash_from_result(result: dict[str, Any] | None) -> str | None:
- if isinstance(result, dict) and result.get("status") in {"pass", "missing_hash"}:
- return str(result.get("sha256") or "")
- return None
- def _iter_string_values(value: Any):
- if isinstance(value, str):
- yield value
- elif isinstance(value, dict):
- for child in value.values():
- yield from _iter_string_values(child)
- elif isinstance(value, list):
- for child in value:
- yield from _iter_string_values(child)
- def _iter_string_keys_and_values(value: Any):
- if isinstance(value, str):
- yield value
- elif isinstance(value, dict):
- for key, child in value.items():
- yield str(key)
- yield from _iter_string_keys_and_values(child)
- elif isinstance(value, list):
- for child in value:
- yield from _iter_string_keys_and_values(child)
- def _contains_forbidden_action(receipt: dict[str, Any]) -> bool:
- text = "\n".join(_iter_string_values(receipt)).upper()
- return any(marker in text for marker in FORBIDDEN_ACTION_MARKERS)
- def _forbidden_action_markers(receipt: dict[str, Any], markers: list[str] | None = None) -> list[str]:
- text = "\n".join(_iter_string_values(receipt)).upper()
- return _forbidden_markers_in_text(text, markers)
- def _forbidden_action_markers_in_keys_and_values(receipt: dict[str, Any], markers: list[str] | None = None) -> list[str]:
- text = "\n".join(_iter_string_keys_and_values(receipt)).upper()
- return _forbidden_markers_in_text(text, markers)
- def _forbidden_markers_in_text(text: str, markers: list[str] | None = None) -> list[str]:
- text = text.upper()
- found: list[str] = []
- for marker in markers or FORBIDDEN_ACTION_MARKERS:
- pattern = rf"(?<![A-Z0-9_\\/]){re.escape(marker.upper())}(?![A-Z0-9_\\/])"
- if re.search(pattern, text):
- found.append(marker)
- return found
- def _validate_json_schema_file(payload: dict[str, Any], schema_file: str, *, required: bool) -> list[str]:
- if importlib.util.find_spec("jsonschema") is None:
- return ["schema_validation_unavailable"] if required else []
- schema_path = ROOT / "schemas" / schema_file
- if not schema_path.is_file():
- return ["schema_file_missing"] if required else []
- try:
- from jsonschema import Draft202012Validator # type: ignore
- schema = read_json(schema_path)
- errors = sorted(
- Draft202012Validator(schema).iter_errors(payload),
- key=lambda error: list(error.absolute_path),
- )
- except Exception as exc: # noqa: BLE001 - schema failures should fail closed.
- return [f"schema_validation_error:{exc.__class__.__name__}"]
- if not errors:
- return []
- failures = ["schema_error"]
- for error in errors[:5]:
- location = "/".join(str(part) for part in error.absolute_path) or "<root>"
- failures.append(f"schema_error:{location}:{error.validator}")
- if len(errors) > 5:
- failures.append(f"schema_error:additional_count:{len(errors) - 5}")
- return failures
- def _has_nonempty_evidence(item: dict[str, Any], keys: list[str]) -> tuple[bool, str]:
- for key in keys:
- value = item.get(key)
- if value is None:
- continue
- if isinstance(value, (list, dict, str)) and not value:
- continue
- return True, key
- return False, keys[0]
- def _set_from_named_items(items: Any, field: str = "name") -> set[str]:
- if not isinstance(items, list):
- return set()
- names: set[str] = set()
- for item in items:
- if isinstance(item, dict) and item.get(field):
- names.add(str(item[field]))
- return names
- def _scenario_covered(model_name: str, required: str) -> bool:
- if model_name == required:
- return True
- if required == "sensor_drift" and "sensor_drift" in model_name:
- return True
- if required == "sensor_delay" and "delay" in model_name:
- return True
- if required == "crosstalk" and "crosstalk" in model_name:
- return True
- if required == "fan_degradation" and "fan_degradation" in model_name:
- return True
- return False
- def _validate_toolchain_evidence(toolchain: dict[str, Any]) -> list[str]:
- failures: list[str] = []
- manifest = toolchain.get("manifest")
- if not isinstance(manifest, dict):
- failures.append("missing_toolchain_manifest")
- manifest = {}
- cleanup_policy = toolchain.get("cleanup_policy")
- if not isinstance(cleanup_policy, dict):
- failures.append("missing_toolchain_cleanup_policy")
- cleanup_policy = {}
- install_roots = manifest.get("install_roots") if isinstance(manifest, dict) else None
- if not isinstance(install_roots, dict) or not install_roots:
- failures.append("missing_toolchain_manifest:install_roots")
- manifest_tools = manifest.get("tools") if isinstance(manifest, dict) else None
- toolchain_tools = (toolchain.get("toolchain") or {}).get("tools") if isinstance(toolchain.get("toolchain"), dict) else None
- seen_tools = _set_from_named_items(manifest_tools)
- if isinstance(toolchain_tools, dict):
- seen_tools.update(str(name) for name, info in toolchain_tools.items() if isinstance(info, dict) and info.get("status") == "present")
- for tool in sorted(OFFLINE_FIDELITY_REQUIRED_TOOLCHAIN_TOOLS - seen_tools):
- failures.append(f"missing_toolchain_tool:{tool}")
- for item in manifest_tools if isinstance(manifest_tools, list) else []:
- if not isinstance(item, dict):
- continue
- if item.get("status") != "present":
- failures.append(f"toolchain_tool_not_present:{item.get('name', 'unknown')}")
- if not (item.get("path") or item.get("python")):
- failures.append(f"missing_toolchain_tool_path:{item.get('name', 'unknown')}")
- if cleanup_policy.get("default") != "dry_run":
- failures.append("toolchain_cleanup_not_dry_run")
- if cleanup_policy.get("requires_owner_marker") is not True:
- failures.append("toolchain_cleanup_missing_owner_marker")
- if not cleanup_policy.get("allowed_root"):
- failures.append("toolchain_cleanup_missing_allowed_root")
- return failures
- def _validate_offline_layer_evidence(layer: str, item: dict[str, Any]) -> list[str]:
- failures: list[str] = []
- keys = OFFLINE_FIDELITY_LAYER_EVIDENCE.get(layer, [])
- ok, representative = _has_nonempty_evidence(item, keys)
- if not ok:
- failures.append(f"missing_layer_evidence:{layer}:{representative}")
- return failures
- if layer == "virtual_driver_lab":
- shims = item.get("user_mode_shims") or []
- if not isinstance(shims, list) or not shims or any(not isinstance(shim, dict) or not shim.get("transcript") for shim in shims):
- failures.append("missing_layer_evidence:virtual_driver_lab:transcript")
- shim_names = _set_from_named_items(shims)
- for name in sorted(OFFLINE_FIDELITY_REQUIRED_VIRTUAL_SHIMS - shim_names):
- failures.append(f"missing_layer_evidence:virtual_driver_lab:{name}")
- for shim in shims if isinstance(shims, list) else []:
- if isinstance(shim, dict) and shim.get("status") != "pass":
- failures.append(f"missing_layer_evidence:virtual_driver_lab:shim_status:{shim.get('name', 'unknown')}")
- faults = set(str(value) for value in item.get("fault_contracts", []) if value) if isinstance(item.get("fault_contracts"), list) else set()
- for fault in sorted(OFFLINE_FIDELITY_REQUIRED_VIRTUAL_FAULTS - faults):
- failures.append(f"missing_layer_evidence:virtual_driver_lab:{fault}")
- if len(str(item.get("trace_hash") or "")) != 64:
- failures.append("missing_layer_evidence:virtual_driver_lab:trace_hash")
- elif layer == "mutation":
- mutants = item.get("mutants") or []
- if not isinstance(mutants, list) or not mutants:
- failures.append("missing_layer_evidence:mutation:mutants")
- mutant_names = _set_from_named_items(mutants)
- for mutant_name in sorted(OFFLINE_FIDELITY_REQUIRED_MUTANTS - mutant_names):
- failures.append(f"missing_layer_evidence:mutation:{mutant_name}")
- for mutant in mutants if isinstance(mutants, list) else []:
- if not isinstance(mutant, dict) or mutant.get("mutation_status") != "killed":
- failures.append("missing_layer_evidence:mutation:killed")
- break
- if len(str(mutant.get("artifact_sha256") or "")) != 64:
- failures.append("missing_layer_evidence:mutation:artifact_sha256")
- break
- elif layer == "thermal_digital_twin":
- models = item.get("models") or []
- model_names = _set_from_named_items(models)
- for required in sorted(OFFLINE_FIDELITY_REQUIRED_THERMAL_SCENARIOS):
- if not any(_scenario_covered(name, required) for name in model_names):
- failures.append(f"missing_layer_evidence:thermal_digital_twin:{required}")
- for model in models if isinstance(models, list) else []:
- if not isinstance(model, dict) or len(str(model.get("trace_hash") or "")) != 64:
- failures.append("missing_layer_evidence:thermal_digital_twin:trace_hash")
- break
- if model.get("status") != "pass":
- failures.append("missing_layer_evidence:thermal_digital_twin:model_status")
- break
- if model.get("violations") not in (None, []):
- failures.append("missing_layer_evidence:thermal_digital_twin:violations")
- break
- elif layer == "coverage_matrix":
- rows = item.get("items") or []
- if not isinstance(rows, list) or not rows or any(not isinstance(row, dict) or row.get("status") != "pass" for row in rows):
- failures.append("missing_layer_evidence:coverage_matrix:covered_items")
- categories = set()
- for row in rows if isinstance(rows, list) else []:
- if isinstance(row, dict) and row.get("category"):
- categories.add(str(row["category"]))
- if isinstance(row, dict) and not row.get("covered_by"):
- failures.append(f"missing_layer_evidence:coverage_matrix:covered_by:{row.get('category', 'unknown')}")
- for category in sorted(OFFLINE_FIDELITY_REQUIRED_COVERAGE_CATEGORIES - categories):
- failures.append(f"missing_layer_evidence:coverage_matrix:{category}")
- elif layer == "td_build":
- elaboration = item.get("elaboration") or {}
- if not isinstance(elaboration, dict) or elaboration.get("status") != "pass":
- failures.append("missing_layer_evidence:td_build:elaboration")
- else:
- database = elaboration.get("database") or {}
- plan = elaboration.get("plan") or {}
- if not isinstance(database, dict) or len(str(database.get("sha256") or "")) != 64:
- failures.append("missing_layer_evidence:td_build:database")
- if not isinstance(plan, dict) or len(str(plan.get("script_sha256") or "")) != 64:
- failures.append("missing_layer_evidence:td_build:script_sha256")
- return failures
- def _validate_safety(receipt: dict[str, Any]) -> list[str]:
- failures: list[str] = []
- safety = receipt.get("safety") or {}
- for field in ["flash_attempted", "real_ptc_fan_bmc_action_attempted", "driver_install_attempted"]:
- if safety.get(field) is not False:
- failures.append(f"safety_flag:{field}")
- if _contains_forbidden_action(receipt):
- failures.append("forbidden_action_marker")
- return failures
- def _validate_real_bmc_artifact(
- receipt_path: Path | None,
- layer: dict[str, Any],
- key: str,
- failure_prefix: str,
- *,
- required: bool = True,
- ) -> tuple[dict[str, Any] | None, list[str]]:
- failures: list[str] = []
- result = _hash_validation_with_optional_receipt_path(receipt_path, layer.get(key), required=required)
- if result["status"] == "missing":
- failures.append(f"missing_{failure_prefix}")
- elif result["status"] == "relative_without_receipt_path":
- failures.append(f"{failure_prefix}_relative_without_receipt_path")
- elif result["status"] == "missing_hash":
- failures.append(f"missing_{failure_prefix}_hash")
- elif result["status"] == "hash_mismatch":
- failures.append(f"{failure_prefix}_hash_mismatch")
- return result, failures
- def _validate_real_bmc_debug_artifact(
- receipt_path: Path | None,
- remote_layer: dict[str, Any],
- field: str,
- ) -> tuple[dict[str, Any] | None, list[str]]:
- debug_evidence = remote_layer.get("debug_evidence") if isinstance(remote_layer, dict) else None
- item = debug_evidence.get(field) if isinstance(debug_evidence, dict) else None
- failure_name = f"debug_{field}"
- if receipt_path is None:
- return None, ([] if item else [f"missing_{failure_name}"])
- result = _hash_validation(receipt_path, item, required=True)
- failures: list[str] = []
- if result["status"] == "missing":
- failures.append(f"missing_{failure_name}")
- elif result["status"] == "missing_hash":
- failures.append(f"missing_{failure_name}_hash")
- elif result["status"] == "hash_mismatch":
- failures.append(f"{failure_name}_hash_mismatch")
- return result, failures
- def _real_bmc_artifact_content_status(result: dict[str, Any] | None, role: str) -> tuple[str, list[str]]:
- if not isinstance(result, dict) or result.get("exists") is not True:
- return "missing", []
- path = Path(str(result.get("path") or ""))
- if not path.is_file():
- return "missing", []
- try:
- data = path.read_bytes()
- except OSError as exc:
- return "fail", [f"{role}_unreadable:{exc.__class__.__name__}"]
- if b"\x00" in data[:4096]:
- return "pass", []
- try:
- text = data.decode("utf-8-sig")
- except UnicodeDecodeError:
- try:
- text = data.decode("utf-16")
- except UnicodeDecodeError:
- return "fail", [f"{role}_unreadable:UnicodeDecodeError"]
- try:
- payload = json.loads(text)
- except json.JSONDecodeError:
- lowered = text.lower()
- if "blocked_pending" in lowered or "blocked_missing" in lowered:
- return "blocked", [f"{role}_status_not_pass:blocked_placeholder"]
- return ("pass", []) if text.strip() else ("blocked", [f"{role}_status_not_pass:empty"])
- if isinstance(payload, dict):
- failures: list[str] = []
- normalized = "pass"
- status = str(payload.get("status") or "pass")
- if status != "pass":
- normalized = "blocked" if status.startswith("blocked_") else "fail"
- failures.append(f"{role}_status_not_pass:{status}")
- if role == "debug_event_stream" and not payload.get("events"):
- normalized = "blocked" if normalized == "pass" else normalized
- failures.append(f"{role}_status_not_pass:empty_events")
- if role == "debug_register_dump" and not payload.get("debug_registers"):
- normalized = "blocked" if normalized == "pass" else normalized
- failures.append(f"{role}_status_not_pass:empty_registers")
- if role == "event_stream" and not payload.get("events"):
- normalized = "blocked" if normalized == "pass" else normalized
- failures.append(f"{role}_status_not_pass:empty_events")
- if role == "register_dump" and not payload.get("debug_registers"):
- normalized = "blocked" if normalized == "pass" else normalized
- failures.append(f"{role}_status_not_pass:empty_registers")
- if failures:
- return normalized, failures
- return "pass", []
- def _validate_real_bmc_j6_windows_safety_block(safety: Any) -> list[str]:
- failures: list[str] = []
- if not isinstance(safety, dict):
- return ["safety_not_object"]
- for field in REAL_BMC_J6_WINDOWS_REQUIRED_SAFETY_FALSE_FIELDS:
- if safety.get(field) is not False:
- failures.append(f"safety_flag:{field}")
- for key, value in safety.items():
- key_text = str(key)
- key_normalized = key_text.lower()
- if key_normalized in REAL_BMC_J6_ACTION_SAFETY_ALIASES and key_normalized not in {"open_com", "opened_com", "com_open"}:
- if value is not False and value not in (None, "", 0):
- failures.append(f"safety_flag:{key_text}")
- for marker in _forbidden_markers_in_text(key_text, REAL_BMC_J6_FORBIDDEN_ACTION_MARKERS):
- if value is not False and value not in (None, "", 0):
- failures.append(f"forbidden_action_marker:{marker}")
- return failures
- def _status_from_layer(layer: Any) -> str:
- if not isinstance(layer, dict):
- return "missing"
- status = str(layer.get("status") or "missing")
- if status == "pass":
- return "pass"
- if status.startswith("blocked_"):
- return "blocked"
- if status == "missing":
- return "missing"
- return "fail"
- def _status_from_artifact(result: dict[str, Any] | None) -> str:
- if not isinstance(result, dict):
- return "missing"
- status = str(result.get("status") or "missing")
- if status == "pass":
- return "pass"
- if status in {"missing", "not_provided"}:
- return "missing"
- if status in {"missing_hash", "hash_mismatch"}:
- return "fail"
- return status
- def _parse_j6sys_transcript(result: dict[str, Any] | None) -> tuple[list[dict[str, object]], list[str]]:
- if not isinstance(result, dict) or result.get("exists") is not True:
- return [], []
- path = Path(str(result.get("path") or ""))
- if not path.is_file():
- return [], []
- lines: list[dict[str, object]] = []
- try:
- for raw in path.read_text(encoding="utf-8-sig", errors="replace").splitlines():
- parsed = _parse_j6sys_line(raw.strip())
- if parsed is not None:
- lines.append(parsed)
- except OSError as exc:
- return [], [f"j6sys_transcript_unreadable:{exc.__class__.__name__}"]
- if not lines:
- return [], ["missing_j6sys_lines"]
- return lines, []
- def _j6sys_threshold_failures(parsed_lines: list[dict[str, object]]) -> tuple[dict[str, object] | None, list[str]]:
- if not parsed_lines:
- return None, ["missing_j6sys_lines"]
- last = parsed_lines[-1]
- failures: list[str] = []
- poll = int(last.get("poll", 0))
- expected_tx = 3 + (43 * poll)
- checks = [
- ("wake", int(last.get("wake", 0)) == 3, "j6sys_wake_not_3"),
- ("poll", poll >= 3, "j6sys_poll_lt_3"),
- ("tx", int(last.get("tx", 0)) >= expected_tx, "j6sys_tx_count_low"),
- ("rx", int(last.get("rx", 0)) > 0, "j6sys_no_bmc_rx"),
- ("uerr", int(last.get("uerr", 0)) == 0, "j6sys_uart_error"),
- ("tok", int(last.get("tok", 0)) > 0, "j6sys_no_tokens"),
- ("seq", int(last.get("seq", 0)) >= 3, "j6sys_seq_lt_3"),
- ("valid", int(last.get("valid", 0)) >= 3, "j6sys_valid_lt_3"),
- ("perr", int(last.get("perr", 0)) == 0, "j6sys_parser_error"),
- ("stale", int(last.get("stale", 0)) == 0, "j6sys_stale"),
- ("frame", int(last.get("frame", 0)) == 0, "j6sys_frame_error"),
- ("duovf", int(last.get("duovf", 0)) == 0, "j6sys_debug_uart_overflow"),
- ("dbg", int(last.get("dbg", 0)) > 0, "j6sys_debug_ping_not_seen"),
- ("derr", int(last.get("derr", 0)) == 0, "j6sys_debug_uart_error"),
- ]
- for _field, passed, failure in checks:
- if not passed:
- failures.append(failure)
- return last, failures
- J6RAW_RE = re.compile(
- r"J6RAW\s+cr=(?P<cr>[0-9A-Fa-f]{8})\s+rx=(?P<rx>[0-9A-Fa-f]{8})"
- r"\s+drop=(?P<drop>[0-9A-Fa-f]{8})\s+berr=(?P<berr>[0-9A-Fa-f]{8})"
- r"\s+derr=(?P<derr>[0-9A-Fa-f]{8})\s+last=(?P<last>[0-9A-Fa-f]{2})"
- r"\s+dbg=(?P<dbg>[0-9A-Fa-f]{8})"
- )
- J6RAW_FRAME_RE = re.compile(
- r"\bJ6RAW\s+seq=(?P<seq>[0-9A-Fa-f]{8})\s+off=(?P<off>[0-9A-Fa-f]{8})"
- r"\s+len=(?P<len>[0-9A-Fa-f]{2})\s+sum=(?P<sum>[0-9A-Fa-f]{4})"
- r"\s+data=(?P<data>[0-9A-Fa-f]*)\b"
- )
- J6RAW_FRAME_COMPACT_RE = re.compile(
- r"\bJ6RAW\s+s=(?P<seq>[0-9A-Fa-f]{1,8})\s+o=(?P<off>[0-9A-Fa-f]{8})"
- r"\s+l=(?P<len>[0-9A-Fa-f]{2})\s+u=(?P<sum>[0-9A-Fa-f]{4})"
- r"\s+d=(?P<data>[0-9A-Fa-f]*)\b"
- )
- LOSSLESS_HEX_FIELDS = {
- "seq",
- "cmd",
- "id",
- "i",
- "s",
- "v",
- "m",
- "tp",
- "t",
- "tx",
- "rx",
- "drop",
- "off",
- "raw_in",
- "ri",
- "raw_out",
- "ro",
- "raw_drop",
- "rd",
- "hd",
- "fifo",
- "fifo_max",
- "bmc_berr",
- "be",
- "host_err",
- "he",
- "e",
- "ty",
- "c",
- "p",
- "p0",
- "p23",
- "f0",
- "f3",
- "f5",
- "to",
- "ts",
- }
- LOSSLESS_STRING_FIELDS = {
- "st",
- "status",
- "src",
- "source",
- "pwm",
- "pwm_source",
- "pid",
- }
- def _parse_lossless_value(key: str, value: str) -> Any:
- token = value.strip()
- while token.endswith("\\r") or token.endswith("\\n"):
- token = token[:-2]
- if key in LOSSLESS_STRING_FIELDS:
- return token
- if key in LOSSLESS_HEX_FIELDS or token.lower().startswith("0x"):
- try:
- return int(token[2:] if token.lower().startswith("0x") else token, 16)
- except ValueError:
- return token
- parsed = _parse_int_token(token)
- return parsed if parsed is not None else token
- def _normalized_transcript_lines(text: str) -> list[str]:
- """Split real or escaped UART line delimiters without changing payload fields."""
- normalized = text.replace("\\r\\n", "\n").replace("\\n", "\n").replace("\\r", "\n")
- return normalized.splitlines()
- def _parse_lossless_key_value_lines(text: str, prefix: str) -> list[dict[str, Any]]:
- lines: list[dict[str, Any]] = []
- pattern = re.compile(rf"\b{re.escape(prefix)}\b(?P<body>[^\r\n]*)")
- for raw in _normalized_transcript_lines(text):
- match = pattern.search(raw)
- if not match:
- continue
- fields: dict[str, Any] = {}
- for key, raw_value in re.findall(r"([A-Za-z0-9_]+)=([^ \t\r\n]+)", match.group("body")):
- fields[key] = _parse_lossless_value(key, raw_value)
- fields["raw"] = raw
- if "host_report_drop" not in fields and "hd" in fields:
- fields["host_report_drop"] = fields["hd"]
- if "raw_in" not in fields and "ri" in fields:
- fields["raw_in"] = fields["ri"]
- if "raw_out" not in fields and "ro" in fields:
- fields["raw_out"] = fields["ro"]
- if "seq" not in fields and "s" in fields:
- fields["seq"] = fields["s"]
- if "id" not in fields and "i" in fields:
- fields["id"] = fields["i"]
- if "temp" not in fields and "tp" in fields:
- fields["temp"] = fields["tp"]
- if "temp" not in fields and "t" in fields:
- fields["temp"] = fields["t"]
- if "raw_drop" not in fields and "rd" in fields:
- fields["raw_drop"] = fields["rd"]
- if "bmc_berr" not in fields and "be" in fields:
- fields["bmc_berr"] = fields["be"]
- if "host_err" not in fields and "he" in fields:
- fields["host_err"] = fields["he"]
- if "err" not in fields and "e" in fields:
- fields["err"] = fields["e"]
- if "type" not in fields and "ty" in fields:
- fields["type"] = fields["ty"]
- if "ch" not in fields and "c" in fields:
- fields["ch"] = fields["c"]
- if "pct" not in fields and "p" in fields:
- fields["pct"] = fields["p"]
- if "status" not in fields and "st" in fields:
- fields["status"] = fields["st"]
- if "valid" not in fields and "v" in fields:
- fields["valid"] = fields["v"]
- if "missing" not in fields and "m" in fields:
- fields["missing"] = fields["m"]
- if "missing" not in fields and "miss" in fields:
- fields["missing"] = fields["miss"]
- if "requested" not in fields and "req" in fields:
- fields["requested"] = fields["req"]
- if "pid_requested" not in fields and "req" in fields:
- fields["pid_requested"] = fields["req"]
- if "active" not in fields and "act" in fields:
- fields["active"] = fields["act"]
- if "pid_active" not in fields and "act" in fields:
- fields["pid_active"] = fields["act"]
- if "source" not in fields and "src" in fields:
- fields["source"] = fields["src"]
- if "pwm_source" not in fields and "src" in fields:
- fields["pwm_source"] = fields["src"]
- if "ptc00" not in fields and "p0" in fields:
- fields["ptc00"] = fields["p0"]
- if "ptc23" not in fields and "p23" in fields:
- fields["ptc23"] = fields["p23"]
- if "fan00" not in fields and "f0" in fields:
- fields["fan00"] = fields["f0"]
- if "fan03" not in fields and "f3" in fields:
- fields["fan03"] = fields["f3"]
- if "fan05" not in fields and "f5" in fields:
- fields["fan05"] = fields["f5"]
- if "timeout" not in fields and "to" in fields:
- fields["timeout"] = fields["to"]
- if "timeout_s" not in fields and "ts" in fields:
- fields["timeout_s"] = fields["ts"]
- if "timeout" not in fields and "to" in fields:
- fields["timeout"] = fields["to"]
- if "timeout_s" not in fields and "ts" in fields:
- fields["timeout_s"] = fields["ts"]
- for alias_field in ("status", "source", "pwm_source"):
- if alias_field in fields:
- fields[alias_field] = _normalize_compact_alias_value(alias_field, fields[alias_field])
- lines.append(fields)
- return lines
- def _host_sensor_row_fields(row: Any) -> dict[str, Any]:
- if not isinstance(row, dict):
- return {}
- fields = row.get("fields") if isinstance(row.get("fields"), dict) else {}
- merged: dict[str, Any] = dict(fields)
- for key in ("seq", "s", "id", "i", "temp", "tp", "t", "missing", "miss", "status", "st", "raw", "fault"):
- if key in row and key not in merged:
- merged[key] = row[key]
- if "seq" not in merged and "s" in merged:
- merged["seq"] = merged["s"]
- if "id" not in merged and "i" in merged:
- raw_i = _raw_field_token(row.get("raw"), "i")
- merged["id"] = _safe_fixed_hex_int(raw_i if raw_i is not None else merged["i"], default=merged["i"])
- elif "id" in merged:
- raw_id = _raw_field_token(row.get("raw"), "id")
- normalized_id = _safe_fixed_hex_int(raw_id if raw_id is not None else merged["id"], default=None)
- if normalized_id is not None:
- merged["id"] = normalized_id
- if "temp" not in merged and "tp" in merged:
- merged["temp"] = merged["tp"]
- if "temp" not in merged and "t" in merged:
- merged["temp"] = merged["t"]
- if "missing" not in merged and "miss" in merged:
- merged["missing"] = merged["miss"]
- if "status" not in merged and "st" in merged:
- merged["status"] = merged["st"]
- if "status" in merged:
- merged["status"] = _normalize_compact_alias_value("status", merged["status"])
- return merged
- def _host_sensor_row_missing(row: Any) -> bool:
- fields = _host_sensor_row_fields(row)
- missing = _safe_int(fields.get("missing"), default=None)
- if missing is not None:
- return missing == 1
- return str(fields.get("status") or "").lower() in {"missing", "no_reading", "na", "disabled"}
- def _parse_j6raw_frames(text: str) -> list[dict[str, Any]]:
- frames: list[dict[str, Any]] = []
- for line_index, raw in enumerate(_normalized_transcript_lines(text)):
- match = J6RAW_FRAME_RE.search(raw) or J6RAW_FRAME_COMPACT_RE.search(raw)
- if not match:
- continue
- data_hex = match.group("data")
- frames.append(
- {
- "kind": "j6raw_frame",
- "raw": raw,
- "line_index": line_index,
- "seq": int(match.group("seq"), 16),
- "off": int(match.group("off"), 16),
- "len": int(match.group("len"), 16),
- "sum": int(match.group("sum"), 16),
- "data_hex": data_hex,
- }
- )
- return frames
- def _post_j6ready_j6raw_frames(text: str, frames: list[dict[str, Any]]) -> list[dict[str, Any]]:
- lines = _normalized_transcript_lines(text)
- j6ready_index = next(
- (index for index, raw in enumerate(lines) if raw.startswith("J6READY")),
- None,
- )
- if j6ready_index is None:
- return frames
- filtered = [frame for frame in frames if int(frame.get("line_index", -1)) > j6ready_index]
- return filtered or frames
- def _validate_j6raw_replay(
- frames: list[dict[str, Any]],
- *,
- last_stat: dict[str, Any] | None,
- replay_result: dict[str, Any] | None,
- ) -> tuple[dict[str, Any], list[str]]:
- failures: list[str] = []
- replay = bytearray()
- first_seq = int(frames[0].get("seq") or 0) if frames else 0
- first_off = int(frames[0].get("off") or 0) if frames else 0
- expected_seq = first_seq
- expected_off = first_off
- if not frames:
- failures.append("missing_j6raw_frames")
- for frame in frames:
- seq = int(frame.get("seq") or 0)
- off = int(frame.get("off") or 0)
- length = int(frame.get("len") or 0)
- checksum = int(frame.get("sum") or 0)
- data_hex = str(frame.get("data_hex") or "")
- if seq != expected_seq:
- failures.append("raw_frame_seq_gap")
- if off != expected_off:
- failures.append("raw_frame_offset_gap")
- if len(data_hex) != length * 2:
- failures.append(f"raw_frame_len_mismatch:{seq}")
- data = b""
- else:
- try:
- data = bytes.fromhex(data_hex)
- except ValueError:
- data = b""
- failures.append(f"raw_frame_hex_malformed:{seq}")
- if len(data) != length:
- failures.append(f"raw_frame_data_len_mismatch:{seq}")
- if (sum(data) & 0xFFFF) != checksum:
- failures.append(f"raw_frame_checksum_mismatch:{seq}")
- replay.extend(data)
- expected_seq = seq + 1
- expected_off = off + length
- raw_in = _safe_int((last_stat or {}).get("raw_in"), default=None)
- raw_out = _safe_int((last_stat or {}).get("raw_out"), default=None)
- raw_drop = _safe_int((last_stat or {}).get("raw_drop"), default=None)
- bmc_berr = _safe_int((last_stat or {}).get("bmc_berr"), default=0) or 0
- host_err = _safe_int((last_stat or {}).get("host_err"), default=0) or 0
- if last_stat is None:
- failures.append("missing_j6stat_lines")
- else:
- if raw_drop not in (0, None):
- failures.append("raw_drop_nonzero")
- if bmc_berr:
- failures.append("bmc_uart_error_nonzero")
- if host_err:
- failures.append("host_uart_error_nonzero")
- expected_replay_len = len(replay) + first_off
- if raw_in is not None and raw_in != expected_replay_len:
- failures.append("raw_in_replay_len_mismatch")
- if raw_out is not None and raw_out != expected_replay_len:
- failures.append("raw_out_replay_len_mismatch")
- replay_artifact_status = "not_provided"
- replay_artifact_sha256 = hashlib.sha256(bytes(replay)).hexdigest()
- if isinstance(replay_result, dict) and replay_result.get("exists") is True:
- replay_path = Path(str(replay_result.get("path") or ""))
- try:
- artifact_bytes = replay_path.read_bytes()
- replay_artifact_status = "pass"
- if artifact_bytes != bytes(replay):
- failures.append("raw_replay_artifact_mismatch")
- replay_artifact_status = "mismatch"
- except OSError as exc:
- replay_artifact_status = f"unreadable:{exc.__class__.__name__}"
- failures.append("raw_replay_artifact_unreadable")
- else:
- failures.append("missing_raw_replay_artifact")
- status = "pass" if not failures else "fail"
- return (
- {
- "status": status,
- "frames": len(frames),
- "bytes": len(replay),
- "first_seq": first_seq,
- "first_off": first_off,
- "baseline_bytes": first_off,
- "sha256": replay_artifact_sha256,
- "artifact_status": replay_artifact_status,
- "raw_in": raw_in,
- "raw_out": raw_out,
- "raw_drop": raw_drop,
- },
- failures,
- )
- def _parse_j6raw_text(text: str) -> list[dict[str, object]]:
- lines: list[dict[str, object]] = []
- for raw in text.splitlines():
- match = J6RAW_RE.search(raw)
- if match:
- lines.append(
- {
- "kind": "j6raw",
- "raw": raw,
- "cr": int(match.group("cr"), 16),
- "rx": int(match.group("rx"), 16),
- "drop": int(match.group("drop"), 16),
- "berr": int(match.group("berr"), 16),
- "derr": int(match.group("derr"), 16),
- "last": int(match.group("last"), 16),
- "dbg": int(match.group("dbg"), 16),
- }
- )
- return lines
- def _read_artifact_text(result: dict[str, Any] | None) -> str:
- if not isinstance(result, dict) or result.get("exists") is not True:
- return ""
- path = Path(str(result.get("path") or ""))
- if not path.is_file():
- return ""
- try:
- data = path.read_bytes()
- except OSError:
- return ""
- return data.decode("utf-8-sig", errors="replace")
- def _artifact_size(result: dict[str, Any] | None) -> int | None:
- if not isinstance(result, dict) or result.get("exists") is not True:
- return None
- path = Path(str(result.get("path") or ""))
- try:
- return path.stat().st_size
- except OSError:
- return None
- def _classify_j6raw_text(text: str, last_j6raw: dict[str, object] | None) -> str:
- lower = text.lower()
- if last_j6raw is not None:
- if int(last_j6raw.get("berr", 0)) > 0 or int(last_j6raw.get("derr", 0)) > 0:
- return "garbled_or_wrong_baud_suspected"
- if int(last_j6raw.get("drop", 0)) > 0:
- return "raw_debug_overflow"
- if int(last_j6raw.get("rx", 0)) <= 0 and not text.strip():
- return "no_bmc_return"
- if re.search(r"login:|password:", lower):
- return "login_or_password_prompt"
- if re.search(r"(^|[\r\n])[^ \r\n].*(#|\$)\s*($|[\r\n])", lower) or re.search(r"root@|admin@|bmc.*[#\$]", lower):
- return "shell_prompt"
- if re.search(r"boot|linux|kernel|uboot|u-boot|init|systemd", lower):
- return "boot_log"
- if re.search(r"not found|permission denied|command not found|usage:|error", lower):
- return "command_or_shell_error"
- if re.search(r"\\x(00|01|02|03|04|05|06|07|08|0b|0c|0e|0f|1[0-9a-f]|7f)", lower):
- return "garbled_or_wrong_baud_suspected"
- if not text.strip():
- return "no_bmc_return"
- return "unclassified_text"
- J6SENS_RE = re.compile(
- r"J6SENS\s+cmd=(?P<cmd>[0-9A-Fa-f]{8})\s+tx=(?P<tx>[0-9A-Fa-f]{8})"
- r"\s+rx=(?P<rx>[0-9A-Fa-f]{8})\s+drop=(?P<drop>[0-9A-Fa-f]{8})"
- r"\s+berr=(?P<berr>[0-9A-Fa-f]{8})\s+derr=(?P<derr>[0-9A-Fa-f]{8})"
- r"\s+phase=(?P<phase>[0-9A-Fa-f]{8})"
- )
- J6CMD_RE = re.compile(
- r"J6CMD\s+seq=(?P<seq>[0-9A-Fa-f]{8})\s+idx=(?P<index>[0-9A-Fa-f]{2})"
- r"\s+name=(?P<name>[A-Za-z0-9_]+)\s+text=(?P<text>[^\r\n]*)"
- )
- HEX48_RE = re.compile(r"(?i)(^|[^0-9a-f])((?:[0-9a-f]{2}\s+){47}[0-9a-f]{2})([^0-9a-f]|$)")
- def _parse_j6sens_text(text: str) -> list[dict[str, object]]:
- lines: list[dict[str, object]] = []
- for raw in text.splitlines():
- match = J6SENS_RE.search(raw)
- if match:
- lines.append(
- {
- "kind": "j6sens",
- "raw": raw,
- "cmd": int(match.group("cmd"), 16),
- "tx": int(match.group("tx"), 16),
- "rx": int(match.group("rx"), 16),
- "drop": int(match.group("drop"), 16),
- "berr": int(match.group("berr"), 16),
- "derr": int(match.group("derr"), 16),
- "phase": int(match.group("phase"), 16),
- }
- )
- return lines
- def _parse_int_token(value: Any) -> int | None:
- if isinstance(value, bool):
- return int(value)
- if isinstance(value, int):
- return value
- if isinstance(value, float):
- return int(value)
- if not isinstance(value, str):
- return None
- token = value.strip()
- if not token:
- return None
- try:
- if token.lower().startswith("0x"):
- return int(token[2:], 16)
- if re.search(r"[A-Fa-f]", token):
- return int(token, 16)
- return int(token, 10)
- except ValueError:
- return None
- def _parse_key_value_status_lines(text: str, prefix: str) -> list[dict[str, Any]]:
- lines: list[dict[str, Any]] = []
- pattern = re.compile(rf"\b{re.escape(prefix)}\b(?P<body>[^\r\n]*)")
- for raw in text.splitlines():
- match = pattern.search(raw)
- if not match:
- continue
- fields: dict[str, Any] = {}
- for key, raw_value in re.findall(r"([A-Za-z0-9_]+)=([A-Za-z0-9_]+)", match.group("body")):
- parsed = _parse_int_token(raw_value)
- fields[key] = parsed if parsed is not None else raw_value
- fields["raw"] = raw
- lines.append(fields)
- return lines
- def _merge_status_events(text_events: list[dict[str, Any]], stream_events: list[dict[str, Any]], kind: str) -> list[dict[str, Any]]:
- merged: list[dict[str, Any]] = []
- seen: set[str] = set()
- for event in text_events:
- raw = str(event.get("raw") or "")
- key = f"text:{raw}"
- if key in seen:
- continue
- seen.add(key)
- event = dict(event)
- event["kind"] = kind
- merged.append(event)
- for event in stream_events:
- if str(event.get("kind") or "") != kind:
- continue
- raw = str(event.get("raw") or "")
- key = f"stream:{raw}:{json.dumps(event, sort_keys=True, default=str)}"
- if raw and any(str(item.get("raw") or "") == raw for item in merged):
- continue
- if key in seen:
- continue
- seen.add(key)
- merged.append(event)
- return merged
- def _parse_modtrace_flags(modtrace: dict[str, Any] | None) -> dict[str, bool]:
- raw = str((modtrace or {}).get("raw") or "")
- lower = raw.lower()
- return {
- "pid_disabled": "pid=disabled" in lower,
- "bmc_observe_only": "bmc=observe_only" in lower,
- "host_slave": "host=slave" in lower,
- "pwm_host_manual": "pwm=host_manual" in lower,
- "timeout_s_5": "timeout_s=5" in lower,
- }
- def _host_sensor_real_fan_ptc_allowed_command(command: str) -> bool:
- return REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_COMMAND_RE.match(command.strip()) is not None
- def _parse_host_sensor_report_text(text: str) -> dict[str, Any]:
- samples: dict[int, dict[str, Any]] = {}
- pwm_events: list[dict[str, Any]] = []
- pid_events: list[dict[str, Any]] = []
- stat_events: list[dict[str, Any]] = []
- current_seq = 0
- for raw in _normalized_transcript_lines(text):
- line = raw.strip()
- if not line:
- continue
- if line.startswith("SENS "):
- fields = _parse_lossless_key_value_lines(line, "SENS")
- parsed = fields[0] if fields else {"raw": line}
- seq = _safe_int(parsed.get("seq"), default=0) or 0
- current_seq = seq
- sample = samples.setdefault(seq, {"seq": seq, "summary": {}, "dimm_rows": []})
- sample["summary"] = parsed
- elif line.startswith("DIMM "):
- fields = _parse_lossless_key_value_lines(line, "DIMM")
- parsed = fields[0] if fields else {"raw": line}
- seq = _safe_int(parsed.get("seq"), default=None)
- if seq is None:
- seq = current_seq
- parsed["seq"] = seq
- sample = samples.setdefault(seq, {"seq": seq, "summary": {}, "dimm_rows": []})
- sample["dimm_rows"].append(parsed)
- elif line.startswith("PWM "):
- pwm_events.extend(_parse_lossless_key_value_lines(line, "PWM"))
- elif line.startswith("PID "):
- pid_events.extend(_parse_lossless_key_value_lines(line, "PID"))
- elif line.startswith("STAT "):
- stat_events.extend(_parse_lossless_key_value_lines(line, "STAT"))
- ordered = [samples[key] for key in sorted(samples)]
- all_ff_samples: list[int] = []
- for sample in ordered:
- summary = sample.get("summary") if isinstance(sample.get("summary"), dict) else {}
- if str(summary.get("status") or "").lower() in {"all_ff", "all_raw_ff"}:
- all_ff_samples.append(_safe_int(sample.get("seq"), default=0) or 0)
- return {
- "samples": ordered,
- "sample_count": len(ordered),
- "dimm_rows_per_sample": [len(sample.get("dimm_rows") or []) for sample in ordered],
- "all_ff_samples": all_ff_samples,
- "pwm_events": pwm_events,
- "pid_events": pid_events,
- "stat_events": stat_events,
- }
- def _read_json_artifact(result: dict[str, Any] | None, role: str) -> tuple[dict[str, Any], list[str]]:
- if not isinstance(result, dict) or result.get("exists") is not True:
- return {}, []
- path = Path(str(result.get("path") or ""))
- try:
- payload = read_json(path)
- except Exception as exc: # noqa: BLE001 - validation reports malformed sidecars as receipt failures.
- return {}, [f"{role}_unreadable:{exc.__class__.__name__}"]
- return (payload if isinstance(payload, dict) else {}), []
- def _validate_layer_statuses(
- *,
- layers: dict[str, Any],
- required_layers: list[str],
- allowed_layers: set[str],
- ) -> list[str]:
- failures: list[str] = []
- for layer in required_layers:
- item = layers.get(layer)
- if item is not None and not isinstance(item, dict):
- failures.append(f"layer_not_object:{layer}")
- item = {}
- status_value = str((item or {}).get("status") or "missing")
- if status_value == "missing":
- failures.append(f"missing_layer:{layer}")
- elif status_value.startswith("blocked_"):
- failures.append(f"blocked_layer:{layer}")
- elif status_value != "pass":
- failures.append(f"fail_layer:{layer}:{status_value}")
- for layer in sorted(set(layers) - allowed_layers):
- failures.append(f"undeclared_layer:{layer}")
- return failures
- def validate_real_bmc_j6_windows_gate_v2_receipt(receipt: dict[str, Any] | Path | str, *, strict: bool = False) -> dict[str, Any]:
- receipt_path: Path | None = None
- if isinstance(receipt, dict):
- payload = receipt
- else:
- receipt_path = Path(receipt)
- payload = read_json(receipt_path)
- failures: list[str] = []
- warnings: list[str] = []
- schema_ok = payload.get("schema") == "real-bmc-j6-windows-gate-v2-receipt-v1"
- if not schema_ok:
- failures.append("fail_schema")
- failures.extend(_validate_json_schema_file(payload, "real_bmc_j6_windows_gate_v2_receipt.schema.json", required=False))
- top_status = str(payload.get("status") or "missing")
- if top_status != "pass":
- failures.append(f"top_status_not_pass:{top_status}")
- if payload.get("counterparty") != "real_bmc":
- failures.append("counterparty_not_real_bmc")
- layers = payload.get("layers") or {}
- if not isinstance(layers, dict):
- failures.append("layers_not_object")
- layers = {}
- failures.extend(
- _validate_layer_statuses(
- layers=layers,
- required_layers=REAL_BMC_J6_WINDOWS_REQUIRED_LAYERS,
- allowed_layers=REAL_BMC_J6_WINDOWS_ALLOWED_LAYER_SET,
- )
- )
- programming = payload.get("programming") or {}
- if not isinstance(programming, dict):
- programming = {}
- failures.append("programming_not_object")
- if programming.get("mode") != "PROGRAM_SRAM":
- failures.append("programming_not_sram")
- if programming.get("manual_programming") is not True:
- failures.append("manual_programming_not_true")
- bitstream_result = None
- if receipt_path is not None:
- bitstream_result = _hash_validation(receipt_path, programming.get("bitstream"), required=True)
- if bitstream_result["status"] in {"missing", "hash_mismatch"}:
- failures.append(f"bitstream_{bitstream_result['status']}")
- elif strict and bitstream_result["status"] == "missing_hash":
- failures.append("missing_bitstream_hash")
- bitstream_sha256 = _artifact_hash_from_result(bitstream_result)
- pin_profile = payload.get("pin_profile") or {}
- if not isinstance(pin_profile, dict):
- pin_profile = {}
- failures.append("pin_profile_not_object")
- profile_name = str(pin_profile.get("name") or "")
- expected_profile = REAL_BMC_J6_WINDOWS_ALLOWED_PIN_PROFILES.get(profile_name)
- if expected_profile is None:
- failures.append("pin_profile_invalid")
- else:
- if pin_profile.get("connector") != "J6":
- failures.append("pin_profile_connector_not_j6")
- for field, expected in expected_profile.items():
- if pin_profile.get(field) != expected:
- failures.append(f"pin_profile_{field}_mismatch")
- td_layer = layers.get("td_bitstream") if isinstance(layers.get("td_bitstream"), dict) else {}
- manual_layer = layers.get("manual_sram_programming") if isinstance(layers.get("manual_sram_programming"), dict) else {}
- capture_layer = layers.get("windows_serial_capture") if isinstance(layers.get("windows_serial_capture"), dict) else {}
- protocol_layer = layers.get("real_bmc_protocol") if isinstance(layers.get("real_bmc_protocol"), dict) else {}
- safety_contract = layers.get("safety_contract") if isinstance(layers.get("safety_contract"), dict) else {}
- artifact_layer = layers.get("artifact_hashes") if isinstance(layers.get("artifact_hashes"), dict) else {}
- td_result, current_failures = _validate_real_bmc_artifact(receipt_path, td_layer, "receipt", "td_receipt")
- failures.extend(current_failures)
- td_sha256 = _artifact_hash_from_result(td_result)
- if isinstance(td_result, dict) and td_result.get("exists"):
- try:
- td_payload = read_json(td_result["path"])
- except Exception as exc: # noqa: BLE001
- failures.append(f"td_receipt_unreadable:{exc.__class__.__name__}")
- td_payload = {}
- if isinstance(td_payload, dict):
- if str(td_payload.get("status") or "missing") != "pass":
- failures.append(f"td_bitstream_receipt_not_pass:{td_payload.get('status', 'missing')}")
- if td_payload.get("mode") != "implementation":
- failures.append("td_bitstream_not_implementation")
- if td_payload.get("top_module") != "uart_rs232_j6_system_debug_top":
- failures.append("td_bitstream_wrong_top_module")
- td_profile = str(td_payload.get("pin_profile") or "")
- if profile_name and td_profile and td_profile != profile_name:
- failures.append("td_bitstream_pin_profile_mismatch")
- td_bitstream = td_payload.get("bitstream") if isinstance(td_payload.get("bitstream"), dict) else {}
- td_bitstream_sha256 = str(td_bitstream.get("sha256") or "")
- if not td_bitstream_sha256:
- failures.append("td_bitstream_missing_hash")
- elif bitstream_sha256 and td_bitstream_sha256.lower() != bitstream_sha256.lower():
- failures.append("td_bitstream_hash_mismatch")
- if manual_layer.get("mode") != "PROGRAM_SRAM":
- failures.append("manual_sram_mode_not_program_sram")
- if manual_layer.get("manual_programming") is not True:
- failures.append("manual_sram_manual_programming_not_true")
- if not manual_layer.get("operator"):
- failures.append("manual_sram_missing_operator")
- if not manual_layer.get("programmed_at"):
- failures.append("manual_sram_missing_programmed_at")
- attestation_result, current_failures = _validate_real_bmc_artifact(
- receipt_path,
- manual_layer,
- "attestation",
- "manual_sram_attestation",
- )
- failures.extend(current_failures)
- attestation_sha256 = _artifact_hash_from_result(attestation_result)
- if isinstance(attestation_result, dict) and attestation_result.get("exists"):
- try:
- attestation_payload = read_json(attestation_result["path"])
- except Exception as exc: # noqa: BLE001
- failures.append(f"manual_sram_attestation_unreadable:{exc.__class__.__name__}")
- attestation_payload = {}
- if isinstance(attestation_payload, dict):
- if str(attestation_payload.get("status") or "missing") != "pass":
- failures.append(f"manual_sram_attestation_not_pass:{attestation_payload.get('status', 'missing')}")
- if attestation_payload.get("mode") != "PROGRAM_SRAM":
- failures.append("manual_sram_attestation_wrong_mode")
- attested_bitstream_sha256 = str(attestation_payload.get("bitstream_sha256") or "")
- if not attested_bitstream_sha256:
- failures.append("manual_sram_attestation_missing_bitstream_hash")
- elif bitstream_sha256 and attested_bitstream_sha256.lower() != bitstream_sha256.lower():
- failures.append("manual_sram_attestation_bitstream_hash_mismatch")
- attested_td_receipt_sha256 = str(attestation_payload.get("td_receipt_sha256") or "")
- if not attested_td_receipt_sha256:
- failures.append("manual_sram_attestation_missing_td_receipt_hash")
- elif td_sha256 and attested_td_receipt_sha256.lower() != td_sha256.lower():
- failures.append("manual_sram_attestation_td_receipt_hash_mismatch")
- if int(capture_layer.get("baud") or 0) != 115200:
- failures.append("serial_baud_not_115200")
- if str(capture_layer.get("format") or "").upper() != "8N1":
- failures.append("serial_format_not_8n1")
- if _safe_int(capture_layer.get("duration_s"), default=0) < 90:
- failures.append("capture_duration_lt_90")
- transcript_result, current_failures = _validate_real_bmc_artifact(receipt_path, capture_layer, "transcript", "transcript")
- failures.extend(current_failures)
- event_stream_result, current_failures = _validate_real_bmc_artifact(receipt_path, capture_layer, "event_stream", "event_stream")
- failures.extend(current_failures)
- register_dump_result, current_failures = _validate_real_bmc_artifact(receipt_path, capture_layer, "register_dump", "register_dump")
- failures.extend(current_failures)
- transcript_sha256 = _artifact_hash_from_result(transcript_result)
- event_stream_sha256 = _artifact_hash_from_result(event_stream_result)
- register_dump_sha256 = _artifact_hash_from_result(register_dump_result)
- event_stream_content_status, current_failures = _real_bmc_artifact_content_status(event_stream_result, "event_stream")
- failures.extend(current_failures)
- register_dump_content_status, current_failures = _real_bmc_artifact_content_status(register_dump_result, "register_dump")
- failures.extend(current_failures)
- for role, artifact_result in [
- ("td_receipt", td_result),
- ("manual_sram_attestation", attestation_result),
- ("transcript", transcript_result),
- ("event_stream", event_stream_result),
- ("register_dump", register_dump_result),
- ]:
- if isinstance(artifact_result, dict) and artifact_result.get("exists") is True:
- path = Path(str(artifact_result.get("path") or ""))
- try:
- data = path.read_bytes()
- if b"\x00" not in data[:4096]:
- text = data.decode("utf-8-sig", errors="ignore")
- for marker in _forbidden_markers_in_text(text, REAL_BMC_J6_WINDOWS_FORBIDDEN_ACTION_MARKERS):
- failures.append(f"forbidden_action_marker:{marker}")
- failures.append(f"artifact_forbidden_action_marker:{role}:{marker}")
- except OSError as exc:
- failures.append(f"artifact_scan_unreadable:{role}:{exc.__class__.__name__}")
- parsed_j6sys, current_failures = _parse_j6sys_transcript(transcript_result)
- failures.extend(current_failures)
- last_j6sys, current_failures = _j6sys_threshold_failures(parsed_j6sys)
- failures.extend(current_failures)
- if last_j6sys is not None:
- protocol_valid = _safe_int(protocol_layer.get("valid_frame_count"), default=-1)
- if protocol_valid != _safe_int(last_j6sys.get("valid"), default=-2):
- failures.append("protocol_j6sys_valid_mismatch")
- if str(protocol_layer.get("source_id") or "") != "BMC_UART_TEXT":
- failures.append("source_id_not_bmc_uart_text")
- if safety_contract.get("ptc_fan_pins_exported") is not False:
- failures.append("ptc_fan_pins_exported")
- if safety_contract.get("real_actuator_action_attempted") is not False:
- failures.append("real_actuator_action_attempted")
- expected_artifact_hashes = {
- "bitstream_sha256": bitstream_sha256,
- "td_receipt_sha256": td_sha256,
- "manual_sram_attestation_sha256": attestation_sha256,
- "transcript_sha256": transcript_sha256,
- "event_stream_sha256": event_stream_sha256,
- "register_dump_sha256": register_dump_sha256,
- }
- for key, actual in expected_artifact_hashes.items():
- recorded = str(artifact_layer.get(key) or "")
- if not recorded:
- failures.append(f"missing_artifact_hash:{key}")
- elif actual and recorded.lower() != actual.lower():
- failures.append(f"artifact_hash_mismatch:{key}")
- failures.extend(_validate_real_bmc_j6_windows_safety_block(payload.get("safety") or {}))
- for marker in _forbidden_action_markers_in_keys_and_values(payload, REAL_BMC_J6_WINDOWS_FORBIDDEN_ACTION_MARKERS):
- failures.append(f"forbidden_action_marker:{marker}")
- if strict:
- authority = str(payload.get("authority_boundary") or "").lower()
- if "thermal performance pass" in authority or "thermal_performance_pass" in authority:
- failures.append("authority_overclaim_thermal_performance")
- if "flash pass" in authority or "program_flash pass" in authority:
- failures.append("authority_overclaim_flash")
- failure_set = set(failures)
- if (
- "programming_not_sram" in failure_set
- or any(item.startswith("forbidden_action_marker:") for item in failure_set)
- or any(item.startswith("artifact_forbidden_action_marker:") for item in failure_set)
- or (schema_ok and any(item.startswith("safety_flag:") for item in failure_set))
- ):
- final_status = "fail_forbidden_action"
- elif top_status.startswith("blocked_"):
- final_status = top_status
- elif any(item.startswith("blocked_layer:") for item in failure_set):
- final_status = "blocked"
- elif failures:
- final_status = "fail"
- else:
- final_status = "pass"
- return {
- "schema": "real-bmc-j6-windows-gate-v2-validation-v1",
- "generated_at": utc_now(),
- "status": final_status,
- "strict": strict,
- "receipt": str(receipt_path) if receipt_path is not None else None,
- "receipt_status": top_status,
- "last_j6sys": last_j6sys,
- "j6sys_line_count": len(parsed_j6sys),
- "transcript": transcript_result,
- "event_stream": event_stream_result,
- "register_dump": register_dump_result,
- "bitstream": bitstream_result,
- "failures": sorted(failure_set),
- "warnings": sorted(set(warnings)),
- "required_layers": REAL_BMC_J6_WINDOWS_REQUIRED_LAYERS,
- "authority_boundary": "real-bmc-j6-windows-gate-v2 proves SRAM-only Windows P10/R10 J6SYS evidence for controlled J6 BMC UART/parser/safety only. It does not certify flash, electrical compliance, full thermal performance, or real PTC/fan closed-loop behavior.",
- }
- def _validate_host_sensor_debug921_common(
- receipt: dict[str, Any] | Path | str,
- *,
- strict: bool = False,
- schema_name: str,
- schema_file: str,
- diagnostic_scope: str,
- required_layers: list[str],
- allowed_layers: set[str],
- allowed_top_module: str,
- expected_commands: list[str],
- expected_ack_cmds: dict[str, str],
- allowed_command,
- expected_fan_count: int,
- validation_schema: str,
- authority_boundary: str,
- allowed_top_statuses: set[str] | None = None,
- ignored_layer_status_failures: set[str] | None = None,
- host_sensor_report_schemas: set[str] | None = None,
- debug_frame_stream_schemas: set[str] | None = None,
- allowed_pin_profiles: dict[str, dict[str, str]] | None = None,
- allowed_top_modules_by_pin_profile: dict[str, str] | None = None,
- required_safety_false_fields: list[str] | None = None,
- forbidden_action_markers: list[str] | None = None,
- td_top_failure_name: str = "td_bitstream_not_host_sensor_top",
- ) -> dict[str, Any]:
- receipt_path: Path | None = None
- if isinstance(receipt, dict):
- payload = receipt
- else:
- receipt_path = Path(receipt)
- payload = read_json(receipt_path)
- failures: list[str] = []
- warnings: list[str] = []
- allowed_top_statuses = allowed_top_statuses or set()
- ignored_layer_status_failures = ignored_layer_status_failures or set()
- host_sensor_report_schemas = host_sensor_report_schemas or {"j6-host-sensor-pwm-host-sensor-report-v1"}
- debug_frame_stream_schemas = debug_frame_stream_schemas or {"j6-host-sensor-pwm-debug-frame-stream-v1"}
- allowed_pin_profiles = allowed_pin_profiles or {}
- allowed_top_modules_by_pin_profile = allowed_top_modules_by_pin_profile or {}
- required_safety_false_fields = required_safety_false_fields or REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_REQUIRED_SAFETY_FALSE_FIELDS
- forbidden_action_markers = forbidden_action_markers or REAL_BMC_J6_WINDOWS_FORBIDDEN_ACTION_MARKERS
- if payload.get("schema") != schema_name:
- failures.append("fail_schema")
- failures.extend(_validate_json_schema_file(payload, schema_file, required=False))
- top_status = str(payload.get("status") or "missing")
- if top_status not in allowed_top_statuses and top_status != "pass" and not top_status.startswith("blocked_"):
- failures.append(f"top_status_not_pass:{top_status}")
- if payload.get("counterparty") != "real_bmc":
- failures.append("counterparty_not_real_bmc")
- if payload.get("diagnostic_scope") != diagnostic_scope:
- failures.append(f"diagnostic_scope_not_{diagnostic_scope}")
- layers = payload.get("layers") or {}
- if not isinstance(layers, dict):
- layers = {}
- failures.append("layers_not_object")
- failures.extend(
- failure
- for failure in _validate_layer_statuses(
- layers=layers,
- required_layers=required_layers,
- allowed_layers=allowed_layers,
- )
- if failure not in ignored_layer_status_failures
- )
- programming = payload.get("programming") if isinstance(payload.get("programming"), dict) else {}
- if programming.get("mode") != "PROGRAM_SRAM":
- failures.append("programming_not_sram")
- if programming.get("manual_programming") is not True:
- failures.append("manual_programming_not_true")
- bitstream_result = _hash_validation_with_optional_receipt_path(receipt_path, programming.get("bitstream"), required=True)
- if bitstream_result["status"] == "missing":
- failures.append("bitstream_missing")
- elif bitstream_result["status"] == "hash_mismatch":
- failures.append("bitstream_hash_mismatch")
- elif strict and bitstream_result["status"] == "missing_hash":
- failures.append("missing_bitstream_hash")
- bitstream_sha256 = _artifact_hash_from_result(bitstream_result)
- pin_profile = payload.get("pin_profile") if isinstance(payload.get("pin_profile"), dict) else {}
- profile_name = str(pin_profile.get("name") or "")
- expected_profile = allowed_pin_profiles.get(profile_name)
- if expected_profile is None:
- failures.append("pin_profile_invalid")
- else:
- if pin_profile.get("connector") != "J6":
- failures.append("pin_profile_connector_not_j6")
- for field, expected in expected_profile.items():
- if pin_profile.get(field) != expected:
- failures.append(f"pin_profile_{field}_mismatch")
- collector = payload.get("collector") if isinstance(payload.get("collector"), dict) else {}
- host_port = str(collector.get("host_port") or "")
- debug_port = str(collector.get("debug_port") or "")
- debug_baud = _safe_int(collector.get("debug_baud"), default=0)
- if host_port != "COM8":
- failures.append("collector_host_port_not_com8")
- if debug_port != "COM7":
- failures.append("collector_debug_port_not_com7")
- if debug_baud != 921600:
- failures.append("debug_baud_not_921600")
- if _safe_int(collector.get("baud"), default=0) != 115200:
- failures.append("serial_baud_not_115200")
- if str(collector.get("format") or "").upper() != "8N1":
- failures.append("serial_format_not_8n1")
- if str(collector.get("flow_control") or "").lower() != "none":
- failures.append("serial_flow_control_not_none")
- if collector.get("dtr_enable") is not False:
- failures.append("collector_dtr_enabled")
- if collector.get("rts_enable") is not False:
- failures.append("collector_rts_enabled")
- if collector.get("write_port_role") != "HostPort":
- failures.append("collector_write_port_role_not_hostport")
- if collector.get("host_port_writes_to_serial") is not True:
- failures.append("collector_host_port_not_written")
- if collector.get("debug_port_writes_to_serial") is not False:
- failures.append("collector_debug_port_writes_to_serial")
- if collector.get("opens_unknown_com_ports") is not False:
- failures.append("collector_opens_unknown_com_ports")
- if collector.get("enumerates_com_ports") is not False:
- failures.append("collector_enumerates_com_ports")
- td_layer = layers.get("td_bitstream") if isinstance(layers.get("td_bitstream"), dict) else {}
- manual_layer = layers.get("manual_sram_programming") if isinstance(layers.get("manual_sram_programming"), dict) else {}
- command_layer = layers.get("host_command_sequence") if isinstance(layers.get("host_command_sequence"), dict) else {}
- host_transcript_layer = layers.get("host_control_transcript") if isinstance(layers.get("host_control_transcript"), dict) else {}
- host_sensor_layer = layers.get("host_sensor_reports") if isinstance(layers.get("host_sensor_reports"), dict) else {}
- debug_layer = layers.get("debug_frame_capture") if isinstance(layers.get("debug_frame_capture"), dict) else {}
- sampling_layer = layers.get("bmc_raw_sampling") if isinstance(layers.get("bmc_raw_sampling"), dict) else {}
- pid_layer = layers.get("pid_boundary") if isinstance(layers.get("pid_boundary"), dict) else {}
- timeout_layer = layers.get("timeout_evidence") if isinstance(layers.get("timeout_evidence"), dict) else {}
- pin_map_layer = layers.get("pin_map") if isinstance(layers.get("pin_map"), dict) else {}
- safety_contract = layers.get("safety_contract") if isinstance(layers.get("safety_contract"), dict) else {}
- artifact_layer = layers.get("artifact_hashes") if isinstance(layers.get("artifact_hashes"), dict) else {}
- td_result, current_failures = _validate_real_bmc_artifact(receipt_path, td_layer, "receipt", "td_receipt")
- failures.extend(current_failures)
- td_sha256 = _artifact_hash_from_result(td_result)
- if isinstance(td_result, dict) and td_result.get("exists"):
- try:
- td_payload = read_json(td_result["path"])
- except Exception as exc: # noqa: BLE001
- td_payload = {}
- failures.append(f"td_receipt_unreadable:{exc.__class__.__name__}")
- if isinstance(td_payload, dict):
- if str(td_payload.get("status") or "missing") != "pass":
- failures.append(f"td_bitstream_receipt_not_pass:{td_payload.get('status', 'missing')}")
- if td_payload.get("mode") != "implementation":
- failures.append("td_bitstream_not_implementation")
- expected_top_module = allowed_top_modules_by_pin_profile.get(profile_name, allowed_top_module)
- if td_payload.get("top_module") != expected_top_module:
- failures.append(td_top_failure_name)
- td_pin_profile = str(td_payload.get("pin_profile") or "")
- if profile_name and td_pin_profile and td_pin_profile != profile_name:
- failures.append("td_pin_profile_mismatch")
- td_bitstream = td_payload.get("bitstream") if isinstance(td_payload.get("bitstream"), dict) else {}
- td_bitstream_sha256 = str(td_bitstream.get("sha256") or "")
- if not td_bitstream_sha256:
- failures.append("td_bitstream_missing_hash")
- elif bitstream_sha256 and td_bitstream_sha256.lower() != bitstream_sha256.lower():
- failures.append("td_bitstream_hash_mismatch")
- if manual_layer.get("mode") != "PROGRAM_SRAM":
- failures.append("manual_sram_mode_not_program_sram")
- if manual_layer.get("manual_programming") is not True:
- failures.append("manual_sram_manual_programming_not_true")
- attestation_result, current_failures = _validate_real_bmc_artifact(receipt_path, manual_layer, "attestation", "manual_sram_attestation")
- failures.extend(current_failures)
- attestation_sha256 = _artifact_hash_from_result(attestation_result)
- if isinstance(attestation_result, dict) and attestation_result.get("exists"):
- try:
- attestation_payload = read_json(attestation_result["path"])
- except Exception as exc: # noqa: BLE001
- attestation_payload = {}
- failures.append(f"manual_sram_attestation_unreadable:{exc.__class__.__name__}")
- if isinstance(attestation_payload, dict):
- if str(attestation_payload.get("status") or "missing") != "pass":
- failures.append(f"manual_sram_attestation_not_pass:{attestation_payload.get('status', 'missing')}")
- if attestation_payload.get("mode") != "PROGRAM_SRAM":
- failures.append("manual_sram_attestation_wrong_mode")
- if bitstream_sha256 and str(attestation_payload.get("bitstream_sha256") or "").lower() != bitstream_sha256.lower():
- failures.append("manual_sram_attestation_bitstream_hash_mismatch")
- if td_sha256 and str(attestation_payload.get("td_receipt_sha256") or "").lower() != td_sha256.lower():
- failures.append("manual_sram_attestation_td_receipt_hash_mismatch")
- layer_commands = command_layer.get("commands") if isinstance(command_layer.get("commands"), list) else []
- host_commands = [str(command).strip() for command in layer_commands if str(command).strip()]
- if not host_commands:
- failures.append("missing_host_commands")
- elif host_commands != expected_commands:
- failures.append("host_command_sequence_mismatch")
- for command in host_commands:
- if not allowed_command(command):
- failures.append(f"host_command_not_allowed:{command}")
- host_transcript_result, current_failures = _validate_real_bmc_artifact(receipt_path, host_transcript_layer, "host_command_transcript", "host_command_transcript")
- failures.extend(current_failures)
- host_transcript_sha256 = _artifact_hash_from_result(host_transcript_result)
- host_transcript_payload, current_failures = _read_json_artifact(host_transcript_result, "host_command_transcript")
- failures.extend(current_failures)
- host_ack = {"status": "missing", "accepted": 0, "total": 0, "records": []}
- if host_transcript_payload:
- if str(host_transcript_payload.get("status") or "pass") != "pass":
- failures.append(f"host_command_transcript_status_not_pass:{host_transcript_payload.get('status', 'missing')}")
- if host_transcript_payload.get("host_port") != "COM8":
- failures.append("host_transcript_port_not_com8")
- if _safe_int(host_transcript_payload.get("baud"), default=115200) != 115200:
- failures.append("host_transcript_baud_not_115200")
- if host_transcript_payload.get("writes_to_serial") is not True:
- failures.append("host_transcript_writes_to_serial_not_true")
- if host_transcript_payload.get("write_port_role") != "HostPort":
- failures.append("host_transcript_write_port_role_not_hostport")
- if host_transcript_payload.get("debug_port_writes_to_serial") is not False:
- failures.append("host_transcript_debug_port_writes_to_serial")
- raw_commands = host_transcript_payload.get("commands") if isinstance(host_transcript_payload.get("commands"), list) else []
- preflight = host_transcript_payload.get("preflight")
- if isinstance(preflight, dict):
- if str(preflight.get("status") or "missing") != "pass":
- failures.append(f"host_preflight_not_pass:{preflight.get('status', 'missing')}")
- if preflight.get("ready_seen") is not True:
- failures.append("host_preflight_ready_missing")
- if preflight.get("epoch_locked") is False:
- failures.append("host_preflight_epoch_not_locked")
- sync_command = str(preflight.get("sync_command") or "").strip().lower()
- sync_ack_seen = preflight.get("sync_ack_seen")
- if sync_command not in {"", "none"} and sync_ack_seen is not True:
- failures.append("host_preflight_sync_ack_missing")
- if sync_ack_seen is True and sync_command in {"", "none"}:
- failures.append("host_preflight_sync_ack_unexpected")
- ready_line = str(preflight.get("ready_line") or "").strip()
- if ready_line and ready_line != "READY profile=temp-uart-ptc-remap seq=00000000":
- failures.append("host_preflight_ready_line_mismatch")
- preflight_ack = str(preflight.get("preflight_ack") or "").strip()
- if preflight_ack and preflight_ack != "OK seq=00000001 cmd=STATUS":
- failures.append("host_preflight_ack_mismatch")
- if preflight.get("counts_as_formal_command") is not False:
- failures.append("host_preflight_counts_as_formal_command")
- else:
- preflight = None
- accepted = 0
- records = []
- startup_shift_detected = False
- if raw_commands:
- first = raw_commands[0] if isinstance(raw_commands[0], dict) else {}
- host_text_for_epoch = ""
- host_text_result_for_epoch = _validate_real_bmc_artifact(receipt_path, host_sensor_layer, "host_transcript_text", "host_transcript_text")[0]
- if isinstance(host_text_result_for_epoch, dict):
- host_text_for_epoch = _read_artifact_text(host_text_result_for_epoch) or ""
- ready_after_ack = False
- if host_text_for_epoch:
- ready_index = host_text_for_epoch.find("READY profile=temp-uart-ptc-remap seq=00000000")
- first_old_ack_index = host_text_for_epoch.find("OK seq=0000000D cmd=STATUS")
- if ready_index >= 0 and first_old_ack_index >= 0 and first_old_ack_index < ready_index:
- ready_after_ack = True
- if (
- isinstance(preflight, dict)
- and str(preflight.get("status") or "") != "pass"
- and preflight.get("epoch_locked") is not True
- and (
- ready_after_ack
- or str(preflight.get("preflight_ack") or "").strip().startswith("OK seq=0000000D")
- or any(_safe_int((item if isinstance(item, dict) else {}).get("response_seq"), default=0) and (_safe_int(item.get("response_seq"), default=0) or 0) > len(raw_commands) for item in raw_commands if isinstance(item, dict))
- )
- ):
- failures.append("blocked_host_epoch_mixed")
- later_shifted = 0
- for shifted_index in range(1, len(raw_commands)):
- item = raw_commands[shifted_index]
- if not isinstance(item, dict):
- continue
- previous_expected = (
- expected_commands[shifted_index - 1]
- if shifted_index - 1 < len(expected_commands)
- else ""
- )
- previous_ack_cmd = expected_ack_cmds.get(previous_expected, "")
- if (
- str(item.get("response_class") or item.get("ack_status") or "").strip().lower() == "ok"
- and _safe_int(item.get("response_seq"), default=_safe_int(item.get("ack_seq"), default=None)) == shifted_index
- and str(item.get("response_cmd") or item.get("ack_cmd") or "").strip() == previous_ack_cmd
- ):
- later_shifted += 1
- startup_shift_detected = (
- isinstance(first, dict)
- and str(first.get("response_class") or first.get("ack_status") or "").strip().lower() in {"", "timeout", "missing"}
- and later_shifted >= max(1, len(raw_commands) // 2)
- )
- if startup_shift_detected:
- failures.append("blocked_host_startup_ack_shift")
- if preflight is None or str(preflight.get("status") or "missing") != "pass":
- failures.append("host_preflight_missing")
- elif preflight is None:
- failures.append("host_preflight_missing")
- for index, item in enumerate(raw_commands):
- if not isinstance(item, dict):
- failures.append(f"host_transcript_command_not_object:{index}")
- continue
- command = str(item.get("command") or "").strip()
- records.append(item)
- expected_command = (
- expected_commands[index]
- if index < len(expected_commands)
- else ""
- )
- expected_ack_cmd = expected_ack_cmds.get(expected_command, "")
- if not allowed_command(command):
- failures.append(f"host_transcript_command_not_allowed:{index}:{command}")
- if command != expected_command:
- failures.append(f"host_transcript_command_mismatch:{index}")
- if item.get("allowed") is not True:
- failures.append(f"host_transcript_command_not_allowed_flag:{index}")
- response_raw = str(item.get("response_raw") or item.get("ack_raw") or item.get("response") or item.get("ack_line") or "").strip()
- response_class = str(item.get("response_class") or item.get("ack_status") or "").strip().lower()
- response_seq = _safe_int(item.get("response_seq"), default=_safe_int(item.get("ack_seq"), default=None))
- response_cmd = str(item.get("response_cmd") or item.get("ack_cmd") or "").strip()
- strict_match = (
- response_class == "ok"
- and response_seq == index + 1
- and response_cmd == expected_ack_cmd
- and response_raw == f"OK seq={index + 1:08X} cmd={expected_ack_cmd}"
- and item.get("seq_match") is True
- and item.get("cmd_match") is True
- and item.get("stale") is not True
- and item.get("accepted") is True
- )
- ok = strict_match
- if ok:
- accepted += 1
- else:
- failures.append(f"host_ack_not_ok:{index}")
- if response_class != "ok":
- failures.append(f"host_ack_class_not_ok:{index}:{response_class or 'missing'}")
- if response_seq != index + 1:
- failures.append(f"host_ack_seq_mismatch:{index}")
- if response_cmd != expected_ack_cmd:
- failures.append(f"host_ack_cmd_mismatch:{index}")
- if response_raw != f"OK seq={index + 1:08X} cmd={expected_ack_cmd}":
- failures.append(f"host_ack_line_mismatch:{index}")
- if item.get("stale") is True:
- failures.append(f"host_ack_stale:{index}")
- if item.get("accepted") is not True:
- failures.append(f"host_ack_not_accepted:{index}")
- if len(raw_commands) != len(expected_commands) or len(raw_commands) != len(host_commands):
- failures.append("host_ack_command_count_mismatch")
- transcript_commands = [str(item.get("command") or "").strip() for item in raw_commands if isinstance(item, dict)]
- if transcript_commands != expected_commands:
- failures.append("host_transcript_command_sequence_mismatch")
- host_ack = {
- "status": "pass" if accepted == len(raw_commands) and len(raw_commands) == len(host_commands) else "fail",
- "accepted": accepted,
- "total": len(raw_commands),
- "records": records,
- }
- completed_samples = _safe_int(sampling_layer.get("completed_samples"), default=0) or 0
- min_samples = _safe_int(sampling_layer.get("minimum_completed_samples"), default=3) or 3
- bmc_timeout = bool(sampling_layer.get("bmc_timeout"))
- host_text_result, current_failures = _validate_real_bmc_artifact(receipt_path, host_sensor_layer, "host_transcript_text", "host_transcript_text")
- failures.extend(current_failures)
- host_raw_result, current_failures = _validate_real_bmc_artifact(receipt_path, host_sensor_layer, "host_raw_bin", "host_raw_bin")
- failures.extend(current_failures)
- host_sensor_report_result, current_failures = _validate_real_bmc_artifact(receipt_path, host_sensor_layer, "host_sensor_report", "host_sensor_report")
- failures.extend(current_failures)
- host_transcript_text_sha256 = _artifact_hash_from_result(host_text_result)
- host_raw_sha256 = _artifact_hash_from_result(host_raw_result)
- host_sensor_report_sha256 = _artifact_hash_from_result(host_sensor_report_result)
- if _artifact_size(host_raw_result) == 0:
- failures.append("host_raw_bin_empty")
- host_text = _read_artifact_text(host_text_result) or _read_artifact_text(host_raw_result)
- parsed_host = _parse_host_sensor_report_text(host_text)
- host_report_payload, current_failures = _read_json_artifact(host_sensor_report_result, "host_sensor_report")
- failures.extend(current_failures)
- if host_report_payload:
- if host_report_payload.get("schema") not in host_sensor_report_schemas:
- failures.append("host_sensor_report_wrong_schema")
- if host_report_payload.get("source") != "HostPort":
- failures.append("host_sensor_report_source_not_hostport")
- report_status = str(host_report_payload.get("status") or "pass")
- if report_status.startswith("blocked_"):
- warnings.append(f"host_sensor_report_status:{report_status}")
- elif report_status != "pass":
- failures.append(f"host_sensor_report_status_not_pass:{report_status}")
- report_samples = host_report_payload.get("samples") if isinstance(host_report_payload.get("samples"), list) else []
- report_dimm_rows = host_report_payload.get("dimm_rows") if isinstance(host_report_payload.get("dimm_rows"), list) else []
- if not bmc_timeout and not report_samples:
- failures.append("host_sensor_report_missing_samples")
- if report_samples and len(report_samples) != parsed_host["sample_count"]:
- failures.append("host_sensor_report_sample_count_mismatch")
- if report_samples and len(report_samples) != completed_samples:
- failures.append("host_sensor_report_completed_sample_count_mismatch")
- for index, sample in enumerate(report_samples, start=1):
- rows = sample.get("dimm_rows") if isinstance(sample, dict) and isinstance(sample.get("dimm_rows"), list) else []
- status_text = str(sample.get("status") or "").lower() if isinstance(sample, dict) else ""
- summary = sample.get("summary") if isinstance(sample, dict) and isinstance(sample.get("summary"), dict) else sample
- if status_text != "timeout" and len(rows) != 24:
- failures.append(f"host_sensor_report_sample_{index}_dimm_rows_not_24")
- if status_text != "timeout" and rows:
- ids = sorted(_safe_int(_host_sensor_row_fields(row).get("id"), default=-1) for row in rows if isinstance(row, dict))
- if ids != list(range(24)):
- failures.append(f"host_sensor_report_sample_{index}_dimm_ids_not_00_23")
- missing_rows = sum(1 for row in rows if isinstance(row, dict) and _host_sensor_row_missing(row))
- reported_missing = _safe_int((summary or {}).get("missing"), default=None) if isinstance(summary, dict) else None
- reported_valid = _safe_int((summary or {}).get("valid"), default=None) if isinstance(summary, dict) else None
- if reported_missing is not None and reported_missing != missing_rows:
- failures.append(f"host_sensor_report_sample_{index}_missing_count_mismatch")
- if reported_valid is not None and reported_valid != 24 - missing_rows:
- failures.append(f"host_sensor_report_sample_{index}_valid_count_mismatch")
- if report_dimm_rows:
- sidecar_sample_count = len({str(_host_sensor_row_fields(row).get("seq")) for row in report_dimm_rows if isinstance(row, dict)})
- if sidecar_sample_count and sidecar_sample_count != parsed_host["sample_count"]:
- failures.append("host_sensor_report_dimm_row_sample_count_mismatch")
- if _safe_int(host_report_payload.get("host_report_drop"), default=0):
- failures.append("host_report_drop_nonzero")
- if host_report_payload.get("bmc_timeout") is True:
- failures.append("bmc_timeout_observed")
- for index, row_count in enumerate(parsed_host["dimm_rows_per_sample"], start=1):
- summary = parsed_host["samples"][index - 1].get("summary") if parsed_host["samples"] else {}
- status_text = str((summary or {}).get("status") or "").lower()
- if status_text == "timeout":
- continue
- if row_count != 24:
- failures.append(f"sample_{index}_dimm_rows_not_24")
- rows = parsed_host["samples"][index - 1].get("dimm_rows") if parsed_host["samples"] else []
- ids = sorted(_safe_int(_host_sensor_row_fields(row).get("id"), default=-1) for row in rows if isinstance(row, dict))
- if ids != list(range(24)):
- failures.append(f"sample_{index}_dimm_ids_not_00_23")
- missing_rows = sum(1 for row in rows if isinstance(row, dict) and _host_sensor_row_missing(row))
- reported_missing = _safe_int((summary or {}).get("missing"), default=None)
- reported_valid = _safe_int((summary or {}).get("valid"), default=None)
- if reported_missing is not None and reported_missing != missing_rows:
- failures.append(f"sample_{index}_missing_count_mismatch")
- if reported_valid is not None and reported_valid != 24 - missing_rows:
- failures.append(f"sample_{index}_valid_count_mismatch")
- if parsed_host["sample_count"] == 0:
- failures.append("missing_host_sensor_samples")
- debug_raw_result, current_failures = _validate_real_bmc_artifact(receipt_path, debug_layer, "raw_bin", "debug_raw_bin")
- failures.extend(current_failures)
- debug_transcript_result, current_failures = _validate_real_bmc_artifact(receipt_path, debug_layer, "debug_transcript", "debug_transcript")
- failures.extend(current_failures)
- raw_replay_result, current_failures = _validate_real_bmc_artifact(receipt_path, debug_layer, "raw_replay", "raw_replay")
- failures.extend(current_failures)
- debug_frame_stream_result, current_failures = _validate_real_bmc_artifact(receipt_path, debug_layer, "debug_frame_stream", "debug_frame_stream")
- failures.extend(current_failures)
- manifest_result, current_failures = _validate_real_bmc_artifact(receipt_path, debug_layer, "manifest", "manifest")
- failures.extend(current_failures)
- debug_raw_sha256 = _artifact_hash_from_result(debug_raw_result)
- debug_transcript_sha256 = _artifact_hash_from_result(debug_transcript_result)
- raw_replay_sha256 = _artifact_hash_from_result(raw_replay_result)
- debug_frame_stream_sha256 = _artifact_hash_from_result(debug_frame_stream_result)
- manifest_sha256 = _artifact_hash_from_result(manifest_result)
- if _artifact_size(debug_raw_result) == 0:
- failures.append("debug_raw_bin_empty")
- debug_text = _read_artifact_text(debug_transcript_result) or _read_artifact_text(debug_raw_result)
- j6raw_frames = _parse_j6raw_frames(debug_text)
- replay_j6raw_frames = _post_j6ready_j6raw_frames(debug_text, j6raw_frames)
- j6ready_events = _parse_lossless_key_value_lines(debug_text, "J6READY")
- j6cmd_events = _parse_lossless_key_value_lines(debug_text, "J6CMD")
- j6evt_events = _parse_lossless_key_value_lines(debug_text, "J6EVT")
- j6pwm_events = _parse_lossless_key_value_lines(debug_text, "J6PWM")
- j6mod_events = _parse_lossless_key_value_lines(debug_text, "J6MOD")
- j6stat_events = _parse_lossless_key_value_lines(debug_text, "J6STAT")
- j6map_events = _parse_lossless_key_value_lines(debug_text, "J6MAP")
- j6temp_events = _parse_lossless_key_value_lines(debug_text, "J6TEMP")
- for prefix, events in [
- ("j6ready", j6ready_events),
- ("j6cmd", j6cmd_events),
- ("j6raw", j6raw_frames),
- ("j6evt", j6evt_events),
- ("j6pwm", j6pwm_events),
- ("j6mod", j6mod_events),
- ("j6stat", j6stat_events),
- ("j6map", j6map_events),
- ("j6temp", j6temp_events),
- ]:
- if not events and not (prefix == "j6raw" and sampling_layer.get("bmc_timeout") is True):
- failures.append(f"missing_{prefix}_frames")
- last_stat = j6stat_events[-1] if j6stat_events else None
- debug_frame_stream_payload, current_failures = _read_json_artifact(debug_frame_stream_result, "debug_frame_stream")
- failures.extend(current_failures)
- if debug_frame_stream_payload:
- if debug_frame_stream_payload.get("schema") not in debug_frame_stream_schemas:
- failures.append("debug_frame_stream_wrong_schema")
- if str(debug_frame_stream_payload.get("status") or "pass") != "pass":
- failures.append(f"debug_frame_stream_status_not_pass:{debug_frame_stream_payload.get('status', 'missing')}")
- stream_frames_raw = debug_frame_stream_payload.get("frames") if isinstance(debug_frame_stream_payload.get("frames"), list) else []
- if not stream_frames_raw and not bmc_timeout:
- failures.append("debug_frame_stream_missing_frames")
- stream_text = "\n".join(
- str(item.get("raw") or "") if isinstance(item, dict) else str(item)
- for item in stream_frames_raw
- )
- stream_counts = {
- "j6cmd": len(_parse_lossless_key_value_lines(stream_text, "J6CMD")),
- "j6ready": len(_parse_lossless_key_value_lines(stream_text, "J6READY")),
- "j6raw": len(_parse_j6raw_frames(stream_text)),
- "j6evt": len(_parse_lossless_key_value_lines(stream_text, "J6EVT")),
- "j6pwm": len(_parse_lossless_key_value_lines(stream_text, "J6PWM")),
- "j6mod": len(_parse_lossless_key_value_lines(stream_text, "J6MOD")),
- "j6stat": len(_parse_lossless_key_value_lines(stream_text, "J6STAT")),
- "j6map": len(_parse_lossless_key_value_lines(stream_text, "J6MAP")),
- "j6temp": len(_parse_lossless_key_value_lines(stream_text, "J6TEMP")),
- }
- expected_stream_counts = {
- "j6cmd": len(j6cmd_events),
- "j6ready": len(j6ready_events),
- "j6raw": len(j6raw_frames),
- "j6evt": len(j6evt_events),
- "j6pwm": len(j6pwm_events),
- "j6mod": len(j6mod_events),
- "j6stat": len(j6stat_events),
- "j6map": len(j6map_events),
- "j6temp": len(j6temp_events),
- }
- if stream_counts != expected_stream_counts:
- failures.append("debug_frame_stream_transcript_mismatch")
- if _safe_int(debug_frame_stream_payload.get("raw_drop"), default=0):
- failures.append("raw_drop_nonzero")
- if _safe_int(debug_frame_stream_payload.get("host_report_drop"), default=0):
- failures.append("host_report_drop_nonzero")
- if _safe_int(debug_frame_stream_payload.get("bmc_berr"), default=0):
- failures.append("bmc_uart_error_nonzero")
- if _safe_int(debug_frame_stream_payload.get("host_err"), default=0):
- failures.append("host_uart_error_nonzero")
- raw_replay, current_failures = _validate_j6raw_replay(replay_j6raw_frames, last_stat=last_stat, replay_result=raw_replay_result)
- if sampling_layer.get("bmc_timeout") is True:
- current_failures = [failure for failure in current_failures if failure != "missing_j6raw_frames"]
- failures.extend(current_failures)
- if last_stat is not None and _safe_int(last_stat.get("host_report_drop"), default=0):
- failures.append("host_report_drop_nonzero")
- if not j6ready_events:
- failures.append("missing_j6ready_frames")
- for index, event in enumerate(j6evt_events):
- for field in ("seq", "cmd", "ch", "pct"):
- if field not in event:
- failures.append(f"j6evt_missing_{field}:{index}")
- if _safe_int(event.get("ok"), default=1) != 1:
- failures.append(f"j6evt_not_ok:{index}")
- if _safe_int(event.get("err"), default=0) not in (0, None):
- failures.append(f"j6evt_err_nonzero:{index}")
- if last_stat is not None and _safe_int(last_stat.get("host_err"), default=0):
- failures.append("host_uart_error_nonzero")
- if bmc_timeout:
- failures.append("bmc_timeout_observed")
- elif completed_samples < min_samples:
- failures.append("completed_samples_lt_minimum")
- if completed_samples and parsed_host["sample_count"] and completed_samples != parsed_host["sample_count"]:
- failures.append("sampling_host_sample_count_mismatch")
- if j6temp_events and parsed_host["sample_count"] and len(j6temp_events) < parsed_host["sample_count"]:
- failures.append("debug_temp_sample_count_lt_host")
- pid_requested = bool(pid_layer.get("pid_requested_ever", pid_layer.get("pid_requested")))
- pid_active = bool(pid_layer.get("pid_active"))
- pwm_source = str(pid_layer.get("pwm_source") or "")
- if not pid_requested:
- failures.append("pid_requested_ever_not_recorded")
- if pid_active:
- failures.append("pid_active_not_false")
- if pwm_source != "host_manual":
- failures.append("pid_pwm_source_not_host_manual")
- for event in parsed_host["pid_events"]:
- if _safe_int(event.get("active"), default=0):
- failures.append("host_pid_active_not_false")
- for event in j6mod_events:
- if _safe_int(event.get("pid_active"), default=0):
- failures.append("debug_pid_active_not_false")
- if not any(_safe_int(event.get("pid_requested"), default=0) for event in j6mod_events) and not pid_layer.get("pid_requested_ever"):
- failures.append("debug_pid_requested_not_seen")
- timeout_status = timeout_layer.get("timeout_evidence") if isinstance(timeout_layer.get("timeout_evidence"), dict) else {}
- timeout_ptc = _safe_int(timeout_status.get("ptc_all_percent"), default=None)
- timeout_fan = _safe_int(timeout_status.get("fan_all_percent"), default=None)
- timeout_evidence = {"timeout_s": _safe_int(timeout_status.get("timeout_s"), default=None), "ptc_all_percent": timeout_ptc, "fan_all_percent": timeout_fan}
- if timeout_evidence["timeout_s"] != 5:
- failures.append("timeout_seconds_not_5")
- if timeout_ptc != 0:
- failures.append("timeout_ptc_not_zero")
- if timeout_fan != 30:
- failures.append("timeout_fan_not_background_30")
- timeout_pwm_events = [event for event in parsed_host["pwm_events"] + j6pwm_events if _safe_int(event.get("timeout"), default=0) == 1]
- if not timeout_pwm_events:
- failures.append("missing_timeout_debug_evidence")
- if _safe_int(pin_map_layer.get("ptc_count"), default=-1) != 24:
- failures.append("pin_map_ptc_count_not_24")
- if _safe_int(pin_map_layer.get("fan_count"), default=-1) != expected_fan_count:
- failures.append(f"pin_map_fan_count_not_{expected_fan_count}")
- pin_map_profile = str(pin_map_layer.get("profile") or pin_map_layer.get("name") or "")
- if profile_name and pin_map_profile and pin_map_profile != profile_name:
- failures.append("pin_map_profile_mismatch")
- if expected_profile is not None:
- for field, expected in expected_profile.items():
- if field in pin_map_layer and pin_map_layer.get(field) != expected:
- failures.append(f"pin_map_{field}_mismatch")
- if safety_contract.get("pid_default_enabled") is not False:
- failures.append("safety_contract_pid_default_enabled_not_false")
- if safety_contract.get("pid_active") is not False:
- failures.append("safety_contract_pid_active_not_false")
- if safety_contract.get("bmc_controls_pwm") is not False:
- failures.append("safety_contract_bmc_controls_pwm_not_false")
- if safety_contract.get("debug_port_writes_to_serial") is not False:
- failures.append("safety_contract_debug_port_writes_to_serial")
- if safety_contract.get("host_port_writes_to_serial") is not True:
- failures.append("safety_contract_host_port_writes_not_true")
- if safety_contract.get("real_thermal_performance_claimed") is not False:
- failures.append("safety_contract_real_thermal_performance_claimed")
- manifest_payload, current_failures = _read_json_artifact(manifest_result, "manifest")
- failures.extend(current_failures)
- if manifest_payload:
- if str(manifest_payload.get("status") or "pass") != "pass":
- failures.append(f"manifest_status_not_pass:{manifest_payload.get('status', 'missing')}")
- manifest_profile = manifest_payload.get("pin_profile_name")
- if manifest_profile is None:
- manifest_profile_obj = manifest_payload.get("pin_profile")
- if isinstance(manifest_profile_obj, dict):
- manifest_profile = manifest_profile_obj.get("name")
- elif isinstance(manifest_profile_obj, str):
- manifest_profile = manifest_profile_obj
- if profile_name and str(manifest_profile or "") and str(manifest_profile) != profile_name:
- failures.append("manifest_pin_profile_mismatch")
- if manifest_payload.get("host_port") != "COM8":
- failures.append("manifest_host_port_not_com8")
- if manifest_payload.get("debug_port") != "COM7":
- failures.append("manifest_debug_port_not_com7")
- if _safe_int(manifest_payload.get("debug_baud"), default=921600) != 921600:
- failures.append("manifest_debug_baud_not_921600")
- if manifest_payload.get("host_port_writes_to_serial") is not True:
- failures.append("manifest_host_port_writes_not_true")
- if manifest_payload.get("debug_port_writes_to_serial") is not False:
- failures.append("manifest_debug_port_writes_to_serial")
- if manifest_payload.get("enumerates_com_ports") not in (False, None):
- failures.append("manifest_enumerates_com_ports")
- if manifest_payload.get("opens_unknown_com_ports") not in (False, None):
- failures.append("manifest_opens_unknown_com_ports")
- expected_artifact_hashes = {
- "bitstream_sha256": bitstream_sha256,
- "td_receipt_sha256": td_sha256,
- "manual_sram_attestation_sha256": attestation_sha256,
- "host_transcript_text_sha256": host_transcript_text_sha256,
- "host_raw_bin_sha256": host_raw_sha256,
- "host_sensor_report_sha256": host_sensor_report_sha256,
- "debug_transcript_sha256": debug_transcript_sha256,
- "debug_raw_bin_sha256": debug_raw_sha256,
- "raw_replay_sha256": raw_replay_sha256,
- "debug_frame_stream_sha256": debug_frame_stream_sha256,
- "host_command_transcript_sha256": host_transcript_sha256,
- "manifest_sha256": manifest_sha256,
- }
- for key, actual in expected_artifact_hashes.items():
- recorded = str(artifact_layer.get(key) or "")
- if not recorded:
- failures.append(f"missing_artifact_hash:{key}")
- elif actual and recorded.lower() != actual.lower():
- failures.append(f"artifact_hash_mismatch:{key}")
- safety = payload.get("safety") if isinstance(payload.get("safety"), dict) else {}
- for field in required_safety_false_fields:
- if safety.get(field) is not False:
- failures.append(f"safety_flag:{field}")
- if safety.get("host_port_writes_to_serial") is not True:
- failures.append("safety_flag:host_port_writes_to_serial_not_true")
- for marker in _forbidden_action_markers_in_keys_and_values(payload, forbidden_action_markers):
- failures.append(f"forbidden_action_marker:{marker}")
- for role, artifact_result in [
- ("td_receipt", td_result),
- ("manual_sram_attestation", attestation_result),
- ("host_transcript_text", host_text_result),
- ("host_sensor_report", host_sensor_report_result),
- ("debug_transcript", debug_transcript_result),
- ("debug_frame_stream", debug_frame_stream_result),
- ("host_command_transcript", host_transcript_result),
- ("manifest", manifest_result),
- ]:
- if isinstance(artifact_result, dict) and artifact_result.get("exists") is True:
- path = Path(str(artifact_result.get("path") or ""))
- try:
- data = path.read_bytes()
- except OSError as exc:
- failures.append(f"artifact_scan_unreadable:{role}:{exc.__class__.__name__}")
- continue
- if b"\x00" in data[:4096]:
- continue
- text = data.decode("utf-8-sig", errors="ignore")
- for marker in _forbidden_markers_in_text(text, forbidden_action_markers):
- failures.append(f"forbidden_action_marker:{marker}")
- failures.append(f"artifact_forbidden_action_marker:{role}:{marker}")
- if strict:
- authority = str(payload.get("authority_boundary") or "").lower()
- negated_authority = "does not" in authority
- if ("final gate pass" in authority or "final-gate pass" in authority) and not negated_authority:
- failures.append("authority_overclaim_final_gate")
- if ("thermal performance pass" in authority or "thermal_performance_pass" in authority) and not negated_authority:
- failures.append("authority_overclaim_thermal_performance")
- if ("pid closed-loop pass" in authority or "real pid closed-loop pass" in authority) and not negated_authority:
- failures.append("authority_overclaim_pid_closed_loop")
- failure_set = set(failures)
- joined = "\n".join(failure_set)
- if (
- "programming_not_sram" in failure_set
- or "collector_debug_port_writes_to_serial" in failure_set
- or "host_transcript_debug_port_writes_to_serial" in failure_set
- or "manifest_debug_port_writes_to_serial" in failure_set
- or "safety_contract_debug_port_writes_to_serial" in failure_set
- or "collector_opens_unknown_com_ports" in failure_set
- or "collector_enumerates_com_ports" in failure_set
- or "collector_dtr_enabled" in failure_set
- or "collector_rts_enabled" in failure_set
- or "host_command_not_allowed:" in joined
- or "host_transcript_command_not_allowed:" in joined
- or any(item.startswith("forbidden_action_marker:") for item in failure_set)
- or any(item.startswith("artifact_forbidden_action_marker:") for item in failure_set)
- or any(item.startswith("safety_flag:") for item in failure_set)
- ):
- final_status = "fail_forbidden_action"
- elif "blocked_host_epoch_mixed" in failure_set:
- final_status = "blocked_host_epoch_mixed"
- elif (
- "host_preflight_epoch_not_locked" in failure_set
- or any(item.startswith("host_preflight_not_pass:blocked_waiting_for_ready_epoch") for item in failure_set)
- ):
- final_status = "blocked_waiting_for_ready_epoch"
- elif any(item.startswith("host_ack_") or item.startswith("host_transcript_response_not_ok") for item in failure_set):
- final_status = "blocked_host_ack"
- elif "bmc_uart_error_nonzero" in failure_set or "host_uart_error_nonzero" in failure_set or any(item.startswith("j6evt_err_nonzero") for item in failure_set):
- final_status = "blocked_uart_error"
- elif "raw_drop_nonzero" in failure_set:
- final_status = "blocked_cpld_raw_drop"
- elif "host_report_drop_nonzero" in failure_set:
- final_status = "blocked_host_report_drop"
- elif "bmc_timeout_observed" in failure_set:
- final_status = "blocked_bmc_timeout"
- elif any(
- item.endswith("_dimm_rows_not_24")
- or item in {
- "missing_host_sensor_samples",
- "host_sensor_report_missing_samples",
- "host_sensor_report_sample_count_mismatch",
- "host_sensor_report_completed_sample_count_mismatch",
- "host_sensor_report_dimm_row_sample_count_mismatch",
- "sampling_host_sample_count_mismatch",
- "debug_temp_sample_count_lt_host",
- }
- or item.startswith("host_sensor_report_sample_")
- for item in failure_set
- ):
- final_status = "blocked_sensor_report_mismatch"
- elif (
- any(item.startswith("raw_frame_") for item in failure_set)
- or "raw_in_replay_len_mismatch" in failure_set
- or "raw_out_replay_len_mismatch" in failure_set
- or "raw_replay_artifact_mismatch" in failure_set
- or "missing_j6raw_frames" in failure_set
- or "debug_frame_stream_missing_frames" in failure_set
- or "debug_frame_stream_transcript_mismatch" in failure_set
- ):
- final_status = "blocked_debug_frame_loss"
- elif any(item in failure_set for item in ["missing_timeout_debug_evidence", "timeout_ptc_not_zero", "timeout_fan_not_background_30"]):
- final_status = "blocked_pwm_evidence_mismatch"
- elif top_status.startswith("blocked_") and top_status not in allowed_top_statuses:
- final_status = top_status
- elif failures:
- final_status = "fail"
- else:
- final_status = "pass"
- return {
- "schema": validation_schema,
- "generated_at": utc_now(),
- "status": final_status,
- "strict": strict,
- "receipt": str(receipt_path) if receipt_path is not None else None,
- "receipt_status": top_status,
- "host_ports": {"host": host_port, "debug": debug_port},
- "debug_baud": debug_baud,
- "host_commands": host_commands,
- "host_ack": host_ack,
- "bmc_sampling": {
- "completed_samples": completed_samples,
- "minimum_completed_samples": min_samples,
- "bmc_timeout": bmc_timeout,
- },
- "sensor_reports": {
- "sample_count": parsed_host["sample_count"],
- "dimm_rows_per_sample": parsed_host["dimm_rows_per_sample"],
- "all_ff_samples": parsed_host["all_ff_samples"],
- },
- "raw_replay": raw_replay,
- "j6raw_frame_count": len(j6raw_frames),
- "j6temp_count": len(j6temp_events),
- "last_stat": last_stat,
- "pid_boundary": {"pid_requested": pid_requested, "pid_active": pid_active, "pwm_source": pwm_source},
- "timeout_evidence": timeout_evidence,
- "debug_transcript": debug_transcript_result,
- "host_transcript_text": host_text_result,
- "host_sensor_report": host_sensor_report_result,
- "raw_replay_artifact": raw_replay_result,
- "debug_frame_stream": debug_frame_stream_result,
- "host_command_transcript": host_transcript_result,
- "manifest": manifest_result,
- "bitstream": bitstream_result,
- "failures": sorted(failure_set),
- "warnings": sorted(set(warnings)),
- "required_layers": required_layers,
- "authority_boundary": authority_boundary,
- }
- def _validate_host_sensor_real_fan_ptc_host_ack(
- receipt_path: Path | None,
- layers: dict[str, Any],
- failures: list[str],
- ) -> tuple[list[str], dict[str, Any], dict[str, Any] | None]:
- command_layer = layers.get("host_command_sequence") if isinstance(layers.get("host_command_sequence"), dict) else {}
- layer_commands = command_layer.get("commands") if isinstance(command_layer.get("commands"), list) else []
- host_commands = [str(command).strip() for command in layer_commands if str(command).strip()]
- if not host_commands:
- failures.append("missing_host_commands")
- elif host_commands != REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_COMMANDS:
- failures.append("host_command_sequence_mismatch")
- for command in host_commands:
- if not _host_sensor_real_fan_ptc_allowed_command(command):
- failures.append(f"host_command_not_allowed:{command}")
- host_transcript_layer = layers.get("host_control_transcript") if isinstance(layers.get("host_control_transcript"), dict) else {}
- host_transcript_result, current_failures = _validate_real_bmc_artifact(
- receipt_path,
- host_transcript_layer,
- "host_command_transcript",
- "host_command_transcript",
- )
- failures.extend(current_failures)
- host_transcript_payload, current_failures = _read_json_artifact(host_transcript_result, "host_command_transcript")
- failures.extend(current_failures)
- host_ack = {"status": "missing", "accepted": 0, "total": 0, "records": []}
- if host_transcript_payload:
- if str(host_transcript_payload.get("status") or "pass") != "pass":
- failures.append(f"host_command_transcript_status_not_pass:{host_transcript_payload.get('status', 'missing')}")
- if host_transcript_payload.get("host_port") != "COM8":
- failures.append("host_transcript_port_not_com8")
- if _safe_int(host_transcript_payload.get("baud"), default=115200) != 115200:
- failures.append("host_transcript_baud_not_115200")
- if host_transcript_payload.get("writes_to_serial") is not True:
- failures.append("host_transcript_writes_to_serial_not_true")
- if host_transcript_payload.get("write_port_role") != "HostPort":
- failures.append("host_transcript_write_port_role_not_hostport")
- if host_transcript_payload.get("debug_port_writes_to_serial") is not False:
- failures.append("host_transcript_debug_port_writes_to_serial")
- raw_commands = host_transcript_payload.get("commands") if isinstance(host_transcript_payload.get("commands"), list) else []
- accepted = 0
- records = []
- for index, item in enumerate(raw_commands):
- if not isinstance(item, dict):
- failures.append(f"host_transcript_command_not_object:{index}")
- continue
- command = str(item.get("command") or "").strip()
- records.append(item)
- expected_command = (
- REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_COMMANDS[index]
- if index < len(REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_COMMANDS)
- else ""
- )
- expected_ack_cmd = REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_ACK_CMDS.get(expected_command, "")
- if not _host_sensor_real_fan_ptc_allowed_command(command):
- failures.append(f"host_transcript_command_not_allowed:{index}:{command}")
- if command != expected_command:
- failures.append(f"host_transcript_command_mismatch:{index}")
- if item.get("allowed") is not True:
- failures.append(f"host_transcript_command_not_allowed_flag:{index}")
- response_raw = str(item.get("response_raw") or item.get("ack_raw") or item.get("response") or item.get("ack_line") or "").strip()
- response_class = str(item.get("response_class") or item.get("ack_status") or "").strip().lower()
- response_seq = _safe_int(item.get("response_seq"), default=_safe_int(item.get("ack_seq"), default=None))
- response_cmd = str(item.get("response_cmd") or item.get("ack_cmd") or "").strip()
- strict_match = (
- response_class == "ok"
- and response_seq == index + 1
- and response_cmd == expected_ack_cmd
- and response_raw == f"OK seq={index + 1:08X} cmd={expected_ack_cmd}"
- and item.get("seq_match") is True
- and item.get("cmd_match") is True
- and item.get("stale") is not True
- )
- if strict_match:
- accepted += 1
- else:
- failures.append(f"host_ack_not_ok:{index}")
- if response_class != "ok":
- failures.append(f"host_ack_class_not_ok:{index}:{response_class or 'missing'}")
- if response_seq != index + 1:
- failures.append(f"host_ack_seq_mismatch:{index}")
- if response_cmd != expected_ack_cmd:
- failures.append(f"host_ack_cmd_mismatch:{index}")
- if response_raw != f"OK seq={index + 1:08X} cmd={expected_ack_cmd}":
- failures.append(f"host_ack_line_mismatch:{index}")
- if item.get("stale") is True:
- failures.append(f"host_ack_stale:{index}")
- if len(raw_commands) != len(host_commands):
- failures.append("host_ack_command_count_mismatch")
- transcript_commands = [str(item.get("command") or "").strip() for item in raw_commands if isinstance(item, dict)]
- if transcript_commands != REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_COMMANDS:
- failures.append("host_transcript_command_sequence_mismatch")
- host_ack = {
- "status": "pass" if accepted == len(raw_commands) and len(raw_commands) == len(host_commands) else "fail",
- "accepted": accepted,
- "total": len(raw_commands),
- "records": records,
- }
- return host_commands, host_ack, host_transcript_result
- def validate_real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt(
- receipt: dict[str, Any] | Path | str,
- *,
- strict: bool = False,
- ) -> dict[str, Any]:
- receipt_path: Path | None = None
- if isinstance(receipt, dict):
- payload = receipt
- else:
- receipt_path = Path(receipt)
- payload = read_json(receipt_path)
- top_status = str(payload.get("status") or "missing")
- layers = payload.get("layers") if isinstance(payload.get("layers"), dict) else {}
- base = _validate_host_sensor_debug921_common(
- receipt,
- strict=strict,
- schema_name="real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1-receipt-v1",
- schema_file="real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt.schema.json",
- diagnostic_scope="host_sensor_real_fan_ptc_debug921",
- required_layers=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_REQUIRED_LAYERS,
- allowed_layers=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_LAYER_SET,
- allowed_top_module=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_TOP_MODULE,
- expected_commands=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_COMMANDS,
- expected_ack_cmds=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_ACK_CMDS,
- allowed_command=_host_sensor_real_fan_ptc_allowed_command,
- expected_fan_count=4,
- validation_schema="real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1-validation-v1",
- authority_boundary=(
- "real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1 validates SRAM-only COM8 "
- "host 1-based real FAN/PTC command evidence, COM7 debug921 frame replay, BMC "
- "raw DIMM sampling, HostPort temperature reporting, PID requested-but-inactive "
- "boundary, timeout fallback, and real FAN/PTC hardware status. It does not "
- "satisfy final-gate-v2, real-bmc-j6-windows-gate-v2, flash, thermal performance, "
- "production PTC/FAN qualification, or real PID closed-loop pass."
- ),
- allowed_top_statuses={"not_run", "blocked_waiting_for_real_fan_ptc_hardware"},
- ignored_layer_status_failures={
- "blocked_layer:real_fan_ptc_hardware_status",
- "fail_layer:real_fan_ptc_hardware_status:not_run",
- },
- host_sensor_report_schemas={
- "j6-host-sensor-real-fan-ptc-host-sensor-report-v1",
- },
- debug_frame_stream_schemas={
- "j6-host-sensor-real-fan-ptc-debug-frame-stream-v1",
- },
- allowed_pin_profiles=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_PIN_PROFILES,
- allowed_top_modules_by_pin_profile=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_TOP_MODULES_BY_PIN_PROFILE,
- required_safety_false_fields=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_REQUIRED_SAFETY_FALSE_FIELDS,
- forbidden_action_markers=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_FORBIDDEN_ACTION_MARKERS,
- td_top_failure_name="td_bitstream_not_host_sensor_real_fan_ptc_top",
- )
- failures = [str(item) for item in base.get("failures", [])]
- warnings = [str(item) for item in base.get("warnings", [])]
- pin_map_layer = layers.get("pin_map") if isinstance(layers.get("pin_map"), dict) else {}
- if _safe_int(pin_map_layer.get("fan_fg_count"), default=8) != 8:
- failures.append("pin_map_fan_fg_count_not_8")
- if _safe_int(pin_map_layer.get("fan_install_count"), default=4) != 4:
- failures.append("pin_map_fan_install_count_not_4")
- hardware_layer = layers.get("real_fan_ptc_hardware_status") if isinstance(layers.get("real_fan_ptc_hardware_status"), dict) else {}
- hardware_status = str(hardware_layer.get("status") or "missing")
- hardware_summary = {
- "status": hardware_status,
- "real_fan_ptc_hardware_present": hardware_layer.get("real_fan_ptc_hardware_present"),
- "qualifies_final_gate": bool(hardware_layer.get("qualifies_final_gate")),
- }
- if hardware_status == "not_run":
- failures.append("real_fan_ptc_hardware_not_run")
- elif hardware_status == "blocked_waiting_for_real_fan_ptc_hardware":
- failures.append("real_fan_ptc_hardware_blocked_waiting")
- else:
- failures.append(f"real_fan_ptc_hardware_status_not_not_run_or_blocked:{hardware_status}")
- if hardware_layer.get("qualifies_final_gate") is not False:
- failures.append("real_fan_ptc_hardware_qualifies_final_gate")
- if hardware_layer.get("real_fan_ptc_hardware_present") not in (False, None):
- failures.append("real_fan_ptc_hardware_present_claimed")
- failure_set = set(failures)
- joined = "\n".join(failure_set)
- if (
- "programming_not_sram" in failure_set
- or "collector_debug_port_writes_to_serial" in failure_set
- or "host_transcript_debug_port_writes_to_serial" in failure_set
- or "collector_opens_unknown_com_ports" in failure_set
- or "collector_enumerates_com_ports" in failure_set
- or "collector_dtr_enabled" in failure_set
- or "collector_rts_enabled" in failure_set
- or "host_command_not_allowed:" in joined
- or "host_transcript_command_not_allowed:" in joined
- or any(item.startswith("forbidden_action_marker:") for item in failure_set)
- or any(item.startswith("artifact_forbidden_action_marker:") for item in failure_set)
- or any(item.startswith("safety_flag:") for item in failure_set)
- ):
- final_status = "fail_forbidden_action"
- elif "blocked_host_epoch_mixed" in failure_set:
- final_status = "blocked_host_epoch_mixed"
- elif (
- "host_preflight_epoch_not_locked" in failure_set
- or any(item.startswith("host_preflight_not_pass:blocked_waiting_for_ready_epoch") for item in failure_set)
- ):
- final_status = "blocked_waiting_for_ready_epoch"
- elif any(item.startswith("host_ack_") for item in failure_set):
- final_status = "blocked_host_ack"
- elif "bmc_uart_error_nonzero" in failure_set or "host_uart_error_nonzero" in failure_set or any(item.startswith("j6evt_err_nonzero") for item in failure_set):
- final_status = "blocked_uart_error"
- elif "raw_drop_nonzero" in failure_set:
- final_status = "blocked_cpld_raw_drop"
- elif "host_report_drop_nonzero" in failure_set:
- final_status = "blocked_host_report_drop"
- elif "bmc_timeout_observed" in failure_set:
- final_status = "blocked_bmc_timeout"
- elif any(
- item.endswith("_dimm_rows_not_24")
- or item in {
- "missing_host_sensor_samples",
- "host_sensor_report_missing_samples",
- "host_sensor_report_sample_count_mismatch",
- "host_sensor_report_completed_sample_count_mismatch",
- "host_sensor_report_dimm_row_sample_count_mismatch",
- "sampling_host_sample_count_mismatch",
- "debug_temp_sample_count_lt_host",
- }
- or item.startswith("host_sensor_report_sample_")
- for item in failure_set
- ):
- final_status = "blocked_sensor_report_mismatch"
- elif (
- any(item.startswith("raw_frame_") for item in failure_set)
- or "raw_in_replay_len_mismatch" in failure_set
- or "raw_out_replay_len_mismatch" in failure_set
- or "raw_replay_artifact_mismatch" in failure_set
- or "missing_j6raw_frames" in failure_set
- or "debug_frame_stream_missing_frames" in failure_set
- or "debug_frame_stream_transcript_mismatch" in failure_set
- ):
- final_status = "blocked_debug_frame_loss"
- elif any(item in failure_set for item in ["missing_timeout_debug_evidence", "timeout_ptc_not_zero", "timeout_fan_not_background_30"]):
- final_status = "blocked_pwm_evidence_mismatch"
- elif failure_set and failure_set <= {
- "real_fan_ptc_hardware_not_run",
- "real_fan_ptc_hardware_blocked_waiting",
- }:
- final_status = "blocked_waiting_for_real_fan_ptc_hardware"
- elif failures:
- final_status = "fail"
- else:
- final_status = "blocked_waiting_for_real_fan_ptc_hardware"
- return {
- "schema": "real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1-validation-v1",
- "generated_at": utc_now(),
- "status": final_status,
- "strict": strict,
- "receipt": str(receipt_path) if receipt_path is not None else None,
- "receipt_status": top_status,
- "host_ports": base.get("host_ports", {}),
- "debug_baud": base.get("debug_baud"),
- "host_commands": base.get("host_commands", []),
- "host_ack": base.get("host_ack", {}),
- "bmc_sampling": base.get("bmc_sampling", {}),
- "sensor_reports": base.get("sensor_reports", {}),
- "raw_replay": base.get("raw_replay", {}),
- "j6raw_frame_count": base.get("j6raw_frame_count", 0),
- "j6temp_count": base.get("j6temp_count", 0),
- "last_stat": base.get("last_stat"),
- "pid_boundary": base.get("pid_boundary", {}),
- "timeout_evidence": base.get("timeout_evidence", {}),
- "real_fan_ptc_hardware_status": hardware_summary,
- "pin_map": {
- "status": pin_map_layer.get("status"),
- "ptc_count": pin_map_layer.get("ptc_count"),
- "fan_count": pin_map_layer.get("fan_count"),
- "fan_fg_count": pin_map_layer.get("fan_fg_count"),
- "fan_install_count": pin_map_layer.get("fan_install_count"),
- },
- "debug_transcript": base.get("debug_transcript"),
- "host_transcript_text": base.get("host_transcript_text"),
- "host_sensor_report": base.get("host_sensor_report"),
- "raw_replay_artifact": base.get("raw_replay_artifact"),
- "debug_frame_stream": base.get("debug_frame_stream"),
- "host_command_transcript": base.get("host_command_transcript"),
- "manifest": base.get("manifest"),
- "bitstream": base.get("bitstream"),
- "failures": sorted(failure_set),
- "warnings": sorted(set(warnings)),
- "required_layers": REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_REQUIRED_LAYERS,
- "authority_boundary": "real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1 validates SRAM-only COM8 host 1-based real FAN/PTC command evidence, COM7 debug921 frame replay, BMC raw DIMM sampling, HostPort temperature reporting, PID requested-but-inactive boundary, timeout fallback, and real FAN/PTC hardware status. It does not satisfy final-gate-v2, real-bmc-j6-windows-gate-v2, flash, thermal performance, production PTC/FAN qualification, or real PID closed-loop pass.",
- }
- def validate_cpld_bmc_acceptance_v1_receipt(receipt: dict[str, Any] | Path | str, *, strict: bool = False) -> dict[str, Any]:
- receipt_path: Path | None = None
- if isinstance(receipt, dict):
- payload = receipt
- else:
- receipt_path = Path(receipt)
- payload = read_json(receipt_path)
- failures: list[str] = []
- child_results: dict[str, Any] = {}
- if payload.get("schema") != "cpld-bmc-acceptance-v1-receipt-v1":
- failures.append("fail_schema")
- failures.extend(_validate_json_schema_file(payload, "cpld_bmc_acceptance_v1_receipt.schema.json", required=False))
- top_status = str(payload.get("status") or "missing")
- if top_status != "pass":
- failures.append(f"top_status_not_pass:{top_status}")
- layers = payload.get("layers") or {}
- if not isinstance(layers, dict):
- layers = {}
- failures.append("layers_not_object")
- validators = {
- "final_gate_v2": validate_final_gate_v2_receipt,
- "real_bmc_j6_windows_gate_v2": validate_real_bmc_j6_windows_gate_v2_receipt,
- }
- for name, validator in validators.items():
- layer = layers.get(name)
- if not isinstance(layer, dict):
- failures.append(f"missing_layer:{name}")
- continue
- if str(layer.get("status") or "missing") != "pass":
- failures.append(f"fail_layer:{name}:{layer.get('status', 'missing')}")
- artifact_result, artifact_failures = _validate_real_bmc_artifact(receipt_path, layer, "receipt", name)
- failures.extend(artifact_failures)
- if isinstance(artifact_result, dict) and artifact_result.get("exists"):
- try:
- child = validator(Path(str(artifact_result["path"])), strict=True)
- except Exception as exc: # noqa: BLE001
- failures.append(f"{name}_unreadable:{exc.__class__.__name__}")
- child = {"status": "fail", "failures": [f"unreadable:{exc.__class__.__name__}"]}
- child_results[name] = child
- if child.get("status") != "pass":
- failures.append(f"{name}_not_pass:{child.get('status', 'unknown')}")
- else:
- child_results[name] = {"status": "missing", "artifact": artifact_result}
- for layer in sorted(set(layers) - set(validators)):
- failures.append(f"undeclared_layer:{layer}")
- if strict:
- authority = str(payload.get("authority_boundary") or "").lower()
- if "thermal performance pass" in authority or "thermal_performance_pass" in authority:
- failures.append("authority_overclaim_thermal_performance")
- if "flash pass" in authority or "program_flash pass" in authority:
- failures.append("authority_overclaim_flash")
- return {
- "schema": "cpld-bmc-acceptance-v1-validation-v1",
- "generated_at": utc_now(),
- "status": "pass" if not failures else "fail",
- "strict": strict,
- "receipt": str(receipt_path) if receipt_path is not None else None,
- "receipt_status": top_status,
- "children": child_results,
- "failures": sorted(set(failures)),
- "required_layers": sorted(validators),
- "authority_boundary": "cpld-bmc-acceptance-v1 requires final-gate-v2 and real-bmc-j6-windows-gate-v2 to pass. It remains scoped to SRAM-only control communication and parser/safety evidence.",
- }
- def _extract_status(receipt: dict[str, Any]) -> str:
- return str(receipt.get("status") or "fail_missing_status")
- def _schema_status(receipt: dict[str, Any]) -> str:
- schema = str(receipt.get("schema") or "")
- return UART_SCHEMAS.get(schema, "unknown-uart-validation-v1")
- def build_protocol_offline_receipt(*, text: str, scenario: str) -> dict[str, Any]:
- from pid_contract_model import BmcDimmFrameParser, PARSER_STATUS_OK
- parser = BmcDimmFrameParser(fraction_scale=100)
- result = parser.parse_text_response(text, frame_seq=1, sample_seq_base=0, age_ms=0)
- status = "pass" if result.parser_status == PARSER_STATUS_OK and len(result.samples) == 24 else "fail_protocol_parse"
- return {
- "schema": "bmc-uart-protocol-receipt-v1",
- "status": status,
- "generated_at": utc_now(),
- "scenario": scenario,
- "counterparty": "pc_emulator",
- "parser": {
- "status": result.parser_status,
- "sample_count": len(result.samples),
- "missing_mask": result.missing_mask,
- "raw_token_count": result.raw_token_count,
- "selected_window_start": result.selected_window_start,
- "rejected_echo_windows": result.rejected_echo_windows,
- },
- "safety": {"flash_attempted": False, "real_ptc_fan_bmc_action_attempted": False, "driver_install_attempted": False},
- "authority_boundary": "Offline parser evidence proves loose text BMC protocol handling only; it does not prove electrical UART timing or board wiring.",
- }
- def validate_uart_receipt(receipt_path: Path | str, *, strict: bool = False) -> dict[str, Any]:
- path = Path(receipt_path)
- receipt = read_json(path)
- schema = str(receipt.get("schema") or "")
- failures: list[str] = []
- warnings: list[str] = []
- if schema not in UART_SCHEMAS:
- failures.append("fail_schema")
- safety_failures = _validate_safety(receipt)
- failures.extend(safety_failures)
- status_value = _extract_status(receipt)
- validation_schema = _schema_status(receipt)
- transcript_required_schemas = {"uart-loopback-receipt-v1", "uart-board-sram-receipt-v1"}
- transcript_result = _hash_validation(path, receipt.get("transcript"), required=schema in transcript_required_schemas)
- if strict and schema in transcript_required_schemas and not (receipt.get("transcript") or {}).get("sha256"):
- failures.append("missing_transcript_hash")
- if transcript_result["status"] in {"missing", "hash_mismatch"} and schema in transcript_required_schemas:
- failures.append(f"transcript_{transcript_result['status']}")
- programming_result = None
- if schema == "uart-board-sram-receipt-v1":
- programming = receipt.get("programming") or {}
- if programming.get("mode") != "PROGRAM_SRAM":
- failures.append("programming_not_sram")
- bitstream = programming.get("bitstream")
- programming_result = _hash_validation(path, bitstream, required=True)
- if strict and programming_result["status"] == "missing_hash":
- failures.append("missing_bitstream_hash")
- elif programming_result["status"] in {"missing", "hash_mismatch"}:
- failures.append(f"bitstream_{programming_result['status']}")
- serial = receipt.get("serial") or {}
- if schema in {"uart-preflight-receipt-v1", "uart-loopback-receipt-v1", "uart-board-sram-receipt-v1"}:
- if int(serial.get("baud") or 0) != 115200:
- failures.append("serial_baud_not_115200")
- if str(serial.get("format") or "").upper() != "8N1":
- failures.append("serial_format_not_8n1")
- if strict and serial.get("allowlisted") is not True:
- failures.append("serial_not_allowlisted")
- if strict and schema == "uart-preflight-receipt-v1" and serial.get("opened") is True:
- failures.append("preflight_must_not_open_com")
- debug_evidence = receipt.get("debug_evidence") or {}
- if schema == "uart-board-sram-receipt-v1":
- for field in ["event_stream", "register_dump"]:
- evidence_path = debug_evidence.get(field)
- if not evidence_path:
- failures.append(f"missing_debug_{field}")
- continue
- resolved = _resolve_receipt_path(path, evidence_path)
- if not resolved.is_file():
- failures.append(f"missing_debug_{field}")
- if receipt.get("counterparty") not in {"pc_emulator", "real_bmc"}:
- failures.append("counterparty_not_declared")
- if schema == "uart-soak-receipt-v1":
- rounds = receipt.get("rounds") or []
- if not rounds:
- failures.append("missing_soak_rounds")
- for item in rounds:
- round_status = str((item or {}).get("status") or "missing")
- round_index = str((item or {}).get("index") or "?")
- if round_status.startswith("blocked_"):
- failures.append(f"blocked_soak_round:{round_index}")
- elif round_status != "pass":
- failures.append(f"fail_soak_round:{round_index}:{round_status}")
- round_receipt = (item or {}).get("receipt")
- if strict and not round_receipt:
- failures.append(f"missing_soak_round_receipt:{round_index}")
- elif strict and round_receipt:
- nested_path = _resolve_receipt_path(path, round_receipt)
- nested = validate_uart_receipt(nested_path, strict=True)
- if nested["status"] != "pass":
- failures.append(f"fail_soak_round_receipt:{round_index}:{nested['status']}")
- if "forbidden_action_marker" in safety_failures or "safety_flag:flash_attempted" in safety_failures:
- final_status = "fail_forbidden_action"
- elif status_value.startswith("blocked_"):
- final_status = status_value
- elif status_value.startswith("fail_"):
- final_status = status_value
- elif failures:
- if "serial_not_allowlisted" in failures:
- final_status = "blocked_no_allowlist"
- else:
- final_status = "fail"
- else:
- final_status = "pass"
- return {
- "schema": validation_schema,
- "generated_at": utc_now(),
- "status": final_status,
- "receipt": str(path),
- "strict": strict,
- "receipt_status": status_value,
- "backend_capabilities": backend_capabilities(),
- "transcript": transcript_result,
- "programming": programming_result,
- "failures": sorted(set(failures)),
- "warnings": sorted(set(warnings)),
- "authority_boundary": "UART receipt proves communication evidence and software safety strategy only. It does not certify thermal performance.",
- }
- def validate_final_gate_v2_receipt(receipt: dict[str, Any] | Path | str, *, strict: bool = False) -> dict[str, Any]:
- if not isinstance(receipt, dict):
- receipt = read_json(Path(receipt))
- failures: list[str] = []
- if receipt.get("schema") != "final-gate-v2-receipt-v1":
- failures.append("fail_schema")
- top_status = str(receipt.get("status") or "missing")
- if top_status != "pass":
- failures.append(f"top_status_not_pass:{top_status}")
- layers = receipt.get("layers") or {}
- for layer in FINAL_GATE_REQUIRED_LAYERS:
- item = layers.get(layer)
- status = str((item or {}).get("status") or "missing")
- if status == "missing":
- failures.append(f"missing_layer:{layer}")
- elif status.startswith("blocked_"):
- failures.append(f"blocked_layer:{layer}")
- elif status != "pass":
- failures.append(f"fail_layer:{layer}:{status}")
- if "chipwatcher" in layers:
- failures.append("forbidden_chipwatcher_layer")
- if strict and "thermal_performance_pass" in str(receipt.get("authority_boundary") or "").lower():
- failures.append("authority_overclaim_thermal_performance")
- return {
- "schema": "final-gate-v2-validation-v1",
- "generated_at": utc_now(),
- "status": "pass" if not failures else "fail",
- "strict": strict,
- "failures": sorted(set(failures)),
- "required_layers": FINAL_GATE_REQUIRED_LAYERS,
- "authority_boundary": "final-gate-v2 pass means software/control communication evidence passed. It does not certify full thermal performance.",
- }
- def validate_offline_fidelity_gate_v1_receipt(receipt: dict[str, Any] | Path | str, *, strict: bool = False) -> dict[str, Any]:
- if not isinstance(receipt, dict):
- receipt = read_json(Path(receipt))
- failures: list[str] = []
- if receipt.get("schema") != "offline-fidelity-gate-v1-receipt-v1":
- failures.append("fail_schema")
- top_status = str(receipt.get("status") or "missing")
- if top_status != "pass":
- failures.append(f"top_status_not_pass:{top_status}")
- layers = receipt.get("layers") or {}
- if not isinstance(layers, dict):
- layers = {}
- failures.append("layers_not_object")
- toolchain = receipt.get("toolchain") or {}
- if not isinstance(toolchain, dict):
- toolchain = {}
- failures.append("toolchain_not_object")
- toolchain_status = str(toolchain.get("status") or "missing")
- if toolchain_status != "pass":
- failures.append(f"toolchain_status_not_pass:{toolchain_status}")
- failures.extend(_validate_toolchain_evidence(toolchain))
- top_safety = receipt.get("safety")
- if not isinstance(top_safety, dict):
- failures.append("missing_safety")
- top_safety = {}
- for field in ["opens_com_ports", "toggles_dtr_rts", "programs_flash", "installs_drivers", "real_ptc_fan_bmc_action_attempted"]:
- if top_safety.get(field) is not False:
- failures.append(f"safety_not_false:{field}")
- toolchain_safety = toolchain.get("safety")
- if not isinstance(toolchain_safety, dict):
- failures.append("missing_toolchain_safety")
- toolchain_safety = {}
- for field in ["opens_com_ports", "toggles_dtr_rts", "installs_drivers", "programs_flash", "touches_ptc_fan_bmc"]:
- if toolchain_safety.get(field) is not False:
- failures.append(f"toolchain_safety_not_false:{field}")
- for layer in OFFLINE_FIDELITY_REQUIRED_LAYERS:
- item = layers.get(layer)
- status = str((item or {}).get("status") or "missing")
- if status == "missing":
- failures.append(f"missing_layer:{layer}")
- elif status.startswith("blocked_"):
- failures.append(f"blocked_layer:{layer}")
- elif status != "pass":
- failures.append(f"fail_layer:{layer}:{status}")
- elif isinstance(item, dict):
- failures.extend(_validate_offline_layer_evidence(layer, item))
- layer_safety = (item or {}).get("safety")
- if isinstance(layer_safety, dict):
- for field in [
- "opens_com_ports",
- "toggles_dtr_rts",
- "installs_drivers",
- "programs_flash",
- "touches_ptc_fan_bmc",
- "real_ptc_fan_bmc_action_attempted",
- ]:
- if field in layer_safety and layer_safety.get(field) is not False:
- failures.append(f"layer_safety_not_false:{layer}:{field}")
- for layer in sorted(set(layers) - set(OFFLINE_FIDELITY_REQUIRED_LAYERS)):
- failures.append(f"undeclared_layer:{layer}")
- for layer in sorted(set(layers) & OFFLINE_FIDELITY_FORBIDDEN_LAYERS):
- failures.append(f"forbidden_layer:{layer}")
- for marker in _forbidden_action_markers(receipt, OFFLINE_FIDELITY_FORBIDDEN_ACTION_MARKERS):
- failures.append(f"forbidden_action_marker:{marker}")
- if strict:
- authority = str(receipt.get("authority_boundary") or "").lower()
- if "thermal_performance_pass" in authority or "thermal performance pass" in authority:
- failures.append("authority_overclaim_thermal_performance")
- if "hardware pass" in authority or "board pass" in authority:
- failures.append("authority_overclaim_hardware")
- if "uart_strict pass" in authority or "uart strict pass" in authority:
- failures.append("authority_overclaim_uart_strict")
- if "chipwatcher pass" in authority or "chipwatcher evidence passed" in authority:
- failures.append("authority_overclaim_chipwatcher")
- return {
- "schema": "offline-fidelity-gate-v1-validation-v1",
- "generated_at": utc_now(),
- "status": "pass" if not failures else "fail",
- "strict": strict,
- "failures": sorted(set(failures)),
- "required_layers": OFFLINE_FIDELITY_REQUIRED_LAYERS,
- "forbidden_layers": sorted(OFFLINE_FIDELITY_FORBIDDEN_LAYERS),
- "authority_boundary": "offline-fidelity-gate-v1 proves offline logic/protocol/safety/debug/virtual-thermal evidence only. It does not certify real hardware or thermal performance.",
- }
- def enumerate_serial_ports_powershell() -> dict[str, Any]:
- command = [
- "powershell",
- "-NoProfile",
- "-Command",
- "Get-CimInstance Win32_PnPEntity | Where-Object { $_.Name -match 'COM[0-9]+' } | Select-Object Name,DeviceID | ConvertTo-Json -Compress",
- ]
- try:
- result = subprocess.run(command, cwd=ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20)
- except (OSError, subprocess.TimeoutExpired) as exc:
- return {"status": "blocked_serial_enumeration_failed", "error": str(exc), "ports": []}
- ports: list[dict[str, Any]] = []
- if result.returncode == 0 and result.stdout.strip():
- try:
- data = json.loads(result.stdout)
- if isinstance(data, dict):
- data = [data]
- for item in data if isinstance(data, list) else []:
- ports.append({"name": item.get("Name"), "device_id": item.get("DeviceID")})
- except json.JSONDecodeError:
- pass
- return {
- "status": "pass" if result.returncode == 0 else "blocked_serial_enumeration_failed",
- "backend": "powershell_dotnet_limited",
- "opened_com": False,
- "ports": ports,
- "stderr": result.stderr[-1000:],
- }
- def build_preflight_receipt(*, allowlist: list[str] | None = None) -> dict[str, Any]:
- ports = enumerate_serial_ports_powershell()
- allow = allowlist or []
- discovered = json.dumps(ports.get("ports", []))
- allowlisted = bool(allow and any(port in discovered for port in allow))
- status = "pass" if ports["status"] == "pass" and allowlisted else ("blocked_no_allowlist" if ports["status"] == "pass" else ports["status"])
- return {
- "schema": "uart-preflight-receipt-v1",
- "status": status,
- "generated_at": utc_now(),
- "serial": {"baud": 115200, "format": "8N1", "allowlisted": allowlisted, "opened": False, "allowlist": allow},
- "enumeration": ports,
- "safety": {"flash_attempted": False, "real_ptc_fan_bmc_action_attempted": False, "driver_install_attempted": False},
- "authority_boundary": "Preflight only enumerates COM candidates; it must not open unknown ports or toggle DTR/RTS.",
- }
- def write_json(payload: dict[str, Any], path: Path) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
- def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description=__doc__)
- sub = parser.add_subparsers(dest="command", required=True)
- preflight = sub.add_parser("preflight")
- preflight.add_argument("--allowlist", action="append", default=[])
- preflight.add_argument("--json", action="store_true")
- preflight.add_argument("--report-file", type=Path)
- preflight.set_defaults(func=cmd_preflight)
- protocol = sub.add_parser("protocol-offline")
- protocol.add_argument("--text-file", type=Path, required=True)
- protocol.add_argument("--scenario", default="manual_text")
- protocol.add_argument("--json", action="store_true")
- protocol.add_argument("--report-file", type=Path)
- protocol.set_defaults(func=cmd_protocol_offline)
- validate = sub.add_parser("validate")
- validate.add_argument("--receipt", type=Path, required=True)
- validate.add_argument("--strict", action="store_true")
- validate.add_argument("--json", action="store_true")
- validate.add_argument("--report-file", type=Path)
- validate.set_defaults(func=cmd_validate)
- final = sub.add_parser("final-gate-v2-validate")
- final.add_argument("--receipt", type=Path, required=True)
- final.add_argument("--strict", action="store_true")
- final.add_argument("--json", action="store_true")
- final.add_argument("--report-file", type=Path)
- final.set_defaults(func=cmd_final_validate)
- offline = sub.add_parser("offline-fidelity-gate-v1-validate")
- offline.add_argument("--receipt", type=Path, required=True)
- offline.add_argument("--strict", action="store_true")
- offline.add_argument("--json", action="store_true")
- offline.add_argument("--report-file", type=Path)
- offline.set_defaults(func=cmd_offline_validate)
- real_bmc_windows = sub.add_parser("real-bmc-j6-windows-gate-v2-validate")
- real_bmc_windows.add_argument("--receipt", type=Path, required=True)
- real_bmc_windows.add_argument("--strict", action="store_true")
- real_bmc_windows.add_argument("--json", action="store_true")
- real_bmc_windows.add_argument("--report-file", type=Path)
- real_bmc_windows.set_defaults(func=cmd_real_bmc_j6_windows_validate)
- host_sensor_real_fan_ptc = sub.add_parser("real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1-validate")
- host_sensor_real_fan_ptc.add_argument("--receipt", type=Path, required=True)
- host_sensor_real_fan_ptc.add_argument("--strict", action="store_true")
- host_sensor_real_fan_ptc.add_argument("--json", action="store_true")
- host_sensor_real_fan_ptc.add_argument("--report-file", type=Path)
- host_sensor_real_fan_ptc.set_defaults(func=cmd_real_bmc_j6_host_sensor_real_fan_ptc_debug921_validate)
- acceptance = sub.add_parser("cpld-bmc-acceptance-v1-validate")
- acceptance.add_argument("--receipt", type=Path, required=True)
- acceptance.add_argument("--strict", action="store_true")
- acceptance.add_argument("--json", action="store_true")
- acceptance.add_argument("--report-file", type=Path)
- acceptance.set_defaults(func=cmd_cpld_bmc_acceptance_validate)
- return parser
- def cmd_preflight(args: argparse.Namespace) -> int:
- payload = build_preflight_receipt(allowlist=args.allowlist)
- if args.report_file:
- write_json(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"uart-preflight: {payload['status']}")
- return 0 if payload["status"] == "pass" else 1
- def cmd_protocol_offline(args: argparse.Namespace) -> int:
- payload = build_protocol_offline_receipt(text=args.text_file.read_text(encoding="utf-8"), scenario=args.scenario)
- if args.report_file:
- write_json(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"uart-protocol-offline: {payload['status']}")
- return 0 if payload["status"] == "pass" else 1
- def cmd_validate(args: argparse.Namespace) -> int:
- payload = validate_uart_receipt(args.receipt, strict=args.strict)
- if args.report_file:
- write_json(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"uart-validate: {payload['status']}")
- return 0 if payload["status"] == "pass" else 1
- def cmd_final_validate(args: argparse.Namespace) -> int:
- payload = validate_final_gate_v2_receipt(args.receipt, strict=args.strict)
- if args.report_file:
- write_json(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"final-gate-v2-validate: {payload['status']}")
- return 0 if payload["status"] == "pass" else 1
- def cmd_offline_validate(args: argparse.Namespace) -> int:
- payload = validate_offline_fidelity_gate_v1_receipt(args.receipt, strict=args.strict)
- if args.report_file:
- write_json(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"offline-fidelity-gate-v1-validate: {payload['status']}")
- return 0 if payload["status"] == "pass" else 1
- def cmd_real_bmc_j6_windows_validate(args: argparse.Namespace) -> int:
- payload = validate_real_bmc_j6_windows_gate_v2_receipt(args.receipt, strict=args.strict)
- if args.report_file:
- write_json(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"real-bmc-j6-windows-gate-v2-validate: {payload['status']}")
- return 0 if payload["status"] == "pass" else 1
- def cmd_real_bmc_j6_host_sensor_real_fan_ptc_debug921_validate(args: argparse.Namespace) -> int:
- payload = validate_real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt(args.receipt, strict=args.strict)
- if args.report_file:
- write_json(payload, args.report_file)
- print(
- json.dumps(payload, indent=2)
- if args.json
- else f"real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1-validate: {payload['status']}"
- )
- return 0 if payload["status"] == "pass" else 1
- def cmd_cpld_bmc_acceptance_validate(args: argparse.Namespace) -> int:
- payload = validate_cpld_bmc_acceptance_v1_receipt(args.receipt, strict=args.strict)
- if args.report_file:
- write_json(payload, args.report_file)
- print(json.dumps(payload, indent=2) if args.json else f"cpld-bmc-acceptance-v1-validate: {payload['status']}")
- return 0 if payload["status"] == "pass" else 1
- def main(argv: list[str] | None = None) -> int:
- parser = build_parser()
- args = parser.parse_args(argv)
- return args.func(args)
- if __name__ == "__main__":
- raise SystemExit(main())
|