| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870 |
- #!/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",
- "changxin-temp-uart-publisher-receipt-v1": "changxin-temp-uart-publisher-validation-v1",
- "changxin-temp-uart-tty0tty-receipt-v1": "changxin-temp-uart-tty0tty-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",
- "j6-binary921-evidence-manifest-v1": "j6-binary921-evidence-validation-v1",
- }
- BINARY921_ALLOWED_PROFILES = {
- "debug-photo-bmc-replay-binary921",
- "formal-uart1-bmc-replay-binary921",
- "production-two-uart-bmc-replay-binary921",
- }
- BINARY921_REQUIRED_SAFETY_FALSE_FIELDS = [
- "flash_attempted",
- "driver_install_attempted",
- "programs_nonvolatile",
- "enumerates_com_ports",
- "debug_port_writes_to_serial",
- "toggles_dtr_rts",
- ]
- BINARY921_FORBIDDEN_ACTION_MARKERS = [
- "PROGRAM_FLASH",
- "ERASE_FLASH",
- "PROGRAM_SPIBIN",
- "DIRECT_FLASH_WRITE",
- "DRIVER_INSTALL",
- "DRIVER_REINSTALL",
- ]
- CHANGXIN_TEMP_UART_REQUIRED_SAFETY_FALSE_FIELDS = [
- "flash_attempted",
- "programs_flash",
- "programs_nonvolatile",
- "driver_install_attempted",
- "real_ptc_fan_action_attempted",
- "uncontrolled_real_bmc_action_attempted",
- "thermal_performance_claimed",
- "cpld_bitstream_generated",
- "program_sram_attempted",
- "ipmi_lan_attempted",
- "network_bmc_attempted",
- "opens_unknown_serial_ports",
- "toggles_dtr_rts",
- ]
- 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",
- "debug-photo-uart-bmc-replay": "uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_debug921_top",
- "formal-uart1-bmc-replay": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_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",
- },
- "debug-photo-uart-bmc-replay": {
- "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-uart1-bmc-replay": {
- "tx_ball": "L10",
- "rx_ball": "M9",
- "bmc_tx_ball": "L10",
- "bmc_rx_ball": "M9",
- "host_tx_ball": "M10",
- "host_rx_ball": "N11",
- "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",
- "programs_flash",
- "programs_nonvolatile",
- ]:
- if field not in safety:
- continue
- 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_changxin_temp_uart_receipt(receipt: dict[str, Any], *, strict: bool) -> list[str]:
- failures: list[str] = []
- if receipt.get("status") != "pass":
- failures.append(f"changxin_status_not_pass:{receipt.get('status')}")
- config = receipt.get("config") or {}
- if strict and not re.fullmatch(r"[0-9a-f]{64}", str(config.get("toml_sha256") or "")):
- failures.append("changxin_missing_config_hash")
- bmc = receipt.get("bmc") or {}
- if bmc.get("method") != "serial_tty":
- failures.append("changxin_bmc_method_not_serial_tty")
- if bmc.get("device") != "/dev/ttyUSB1":
- failures.append("changxin_bmc_device_not_ttyusb1")
- if int(bmc.get("baudrate") or 0) != 115200:
- failures.append("changxin_bmc_baudrate_not_115200")
- for field in ["host", "username", "password", "interface", "lanplus"]:
- if field in bmc:
- failures.append(f"changxin_legacy_bmc_network_key:{field}")
- if str(bmc.get("raw_command") or "") not in set(map(str, bmc.get("readonly_whitelist") or [])):
- failures.append("changxin_raw_command_not_allowlisted")
- mapping = receipt.get("mapping") or {}
- if mapping.get("source_groups") != 24:
- failures.append("changxin_source_groups_not_24")
- if mapping.get("destination_groups") != 32:
- failures.append("changxin_destination_groups_not_32")
- if mapping.get("invalid_fill_groups") != "25-32":
- failures.append("changxin_invalid_fill_groups_not_25_32")
- table = mapping.get("table") or []
- if strict and len(table) != 32:
- failures.append("changxin_mapping_table_not_32")
- frame = receipt.get("frame") or {}
- if frame.get("logical_length_bytes") != 66:
- failures.append("changxin_frame_length_not_66")
- checksum = frame.get("checksum") or {}
- if checksum.get("algorithm") != "ones_complement_sum_first_49_bytes":
- failures.append("changxin_checksum_algorithm")
- if checksum.get("protected_length_bytes") != 49:
- failures.append("changxin_checksum_protected_length_not_49")
- if strict and not all(checksum.get("results") or []):
- failures.append("changxin_checksum_result_not_pass")
- if strict and not checksum.get("protocol_risk"):
- failures.append("changxin_missing_protocol_risk")
- serial = receipt.get("serial") or {}
- if serial.get("virtual_serial") not in {"pty_socat", "pty_python", "tty0tty"}:
- failures.append("changxin_virtual_serial_backend")
- if serial.get("output_format") not in {"ascii_hex_space_lf", "ascii_hex_space_crlf", "binary_66_bytes"}:
- failures.append("changxin_output_format")
- required_hash = "wire_transcript_sha256" if serial.get("output_format") == "binary_66_bytes" else "ascii_transcript_sha256"
- for field in ["pty_path", required_hash, "consumer_transcript_sha256"]:
- if strict and not serial.get(field):
- failures.append(f"changxin_missing_serial_{field}")
- timing = receipt.get("timing") or {}
- publish_interval = timing.get("publish_interval") or {}
- for field in ["avg_sec", "p95_sec", "p99_sec", "max_sec"]:
- if strict and field not in publish_interval:
- failures.append(f"changxin_missing_timing_{field}")
- errors = receipt.get("errors") or {}
- for field in ["timeout", "stale", "parse_error", "missing"]:
- if field not in errors:
- failures.append(f"changxin_missing_error_count:{field}")
- safety = receipt.get("safety") or {}
- for field in CHANGXIN_TEMP_UART_REQUIRED_SAFETY_FALSE_FIELDS:
- if safety.get(field) is not False:
- failures.append(f"safety_flag:{field}")
- authority = str(receipt.get("authority_boundary") or "").lower()
- if "thermal performance" not in authority or "does not prove" not in authority:
- failures.append("changxin_authority_boundary_missing_thermal_exclusion")
- return failures
- def _validate_binary921_evidence_manifest(receipt: dict[str, Any], *, strict: bool) -> list[str]:
- failures: list[str] = []
- if receipt.get("status") != "pass":
- failures.append(f"binary921_status_not_pass:{receipt.get('status')}")
- if receipt.get("protocol") != "binary921":
- failures.append("binary921_protocol_not_binary921")
- if receipt.get("profile") not in BINARY921_ALLOWED_PROFILES:
- failures.append("binary921_profile_not_allowed")
- transport = receipt.get("transport") or "separate_host_debug_uart"
- if receipt.get("profile") == "production-two-uart-bmc-replay-binary921":
- if transport != "combined_host_debug_uart":
- failures.append("binary921_production_transport_not_combined")
- if receipt.get("combined_uart_baud") != 921600:
- failures.append("binary921_combined_uart_baud_not_921600")
- if receipt.get("bmc_replay_uart_baud") != 115200:
- failures.append("binary921_bmc_replay_uart_baud_not_115200")
- artifact_hashes = receipt.get("artifact_hashes") or {}
- if not isinstance(artifact_hashes, dict) or not artifact_hashes.get("combined-uart-binary921.raw"):
- failures.append("binary921_combined_uart_artifact_missing")
- elif not re.fullmatch(r"[0-9a-fA-F]{64}", str(artifact_hashes.get("combined-uart-binary921.raw"))):
- failures.append("binary921_combined_uart_artifact_hash_invalid")
- elif transport not in {"separate_host_debug_uart", None}:
- failures.append("binary921_nonproduction_transport_not_separate")
- if receipt.get("bmc_source") != "pc_replay_from_real_bmc_capture":
- failures.append("binary921_bmc_source_not_pc_replay")
- if receipt.get("live_bmc_link_status") != "not_used":
- failures.append("binary921_live_bmc_link_status_must_be_not_used")
- if receipt.get("real_fan_ptc_hardware_status") != "not_run":
- failures.append("binary921_real_fan_ptc_hardware_status_must_be_not_run")
- if receipt.get("host_command_count") != 12:
- failures.append("binary921_host_command_count_not_12")
- if receipt.get("host_ack_count") != 12:
- failures.append("binary921_host_ack_count_not_12")
- if receipt.get("host_ack_matched_count") != 12:
- failures.append("binary921_host_ack_matched_count_not_12")
- try:
- debug_frame_count = int(receipt.get("debug_frame_count") or 0)
- except (TypeError, ValueError):
- debug_frame_count = 0
- if debug_frame_count <= 0:
- failures.append("binary921_debug_frame_count_not_positive")
- try:
- bmc_payload_frame_count = int(receipt.get("bmc_payload_frame_count") or 0)
- except (TypeError, ValueError):
- bmc_payload_frame_count = 0
- if bmc_payload_frame_count <= 0:
- failures.append("binary921_bmc_payload_frame_missing")
- try:
- sensor_cache_frame_count = int(receipt.get("sensor_cache_frame_count") or 0)
- except (TypeError, ValueError):
- sensor_cache_frame_count = 0
- if sensor_cache_frame_count <= 0:
- failures.append("binary921_sensor_cache_frame_missing")
- bmc_replay = receipt.get("bmc_replay") or {}
- if not isinstance(bmc_replay, dict) or bmc_replay.get("status") != "pass":
- failures.append("binary921_bmc_replay_not_pass")
- else:
- if bmc_replay.get("bmc_source") != "pc_replay_from_real_bmc_capture":
- failures.append("binary921_bmc_replay_source_not_pc_replay")
- if bmc_replay.get("byte_count") != 48:
- failures.append("binary921_bmc_replay_byte_count_not_48")
- if receipt.get("profile") == "production-two-uart-bmc-replay-binary921":
- if bmc_replay.get("source") != "real_bmc_capture":
- failures.append("binary921_bmc_replay_source_not_real_capture")
- if not bmc_replay.get("payload_reply_sha256") and not bmc_replay.get("reply_sha256"):
- failures.append("binary921_bmc_replay_payload_hash_missing")
- for hash_field in ["payload_reply_sha256", "reply_sha256", "capture_text_sha256"]:
- value = bmc_replay.get(hash_field)
- if value is not None and not re.fullmatch(r"[0-9a-fA-F]{64}", str(value)):
- failures.append(f"binary921_bmc_replay_{hash_field}_invalid")
- if not bmc_replay.get("capture_text_sha256"):
- failures.append("binary921_bmc_replay_capture_hash_missing")
- if bmc_replay.get("valid_count") is None or bmc_replay.get("missing_count") is None:
- failures.append("binary921_bmc_replay_valid_missing_counts_absent")
- if int(receipt.get("module_snapshot_count") or 0) <= 0:
- failures.append("binary921_module_snapshot_missing")
- latest_snapshot = receipt.get("latest_module_snapshot") or {}
- if not isinstance(latest_snapshot, dict):
- failures.append("binary921_latest_module_snapshot_not_object")
- latest_snapshot = {}
- if latest_snapshot.get("profile_id_payload") != 3:
- failures.append("binary921_module_snapshot_profile_mismatch")
- if int(latest_snapshot.get("command_count_seen") or 0) < 12:
- failures.append("binary921_module_snapshot_command_count_lt_12")
- if latest_snapshot.get("host_err_count") not in (0, None):
- failures.append("binary921_module_snapshot_host_err_nonzero")
- if latest_snapshot.get("pid_requested") is not False:
- failures.append("binary921_pid_not_inactive")
- if latest_snapshot.get("timeout_active") is not True:
- failures.append("binary921_timeout_not_active")
- if latest_snapshot.get("ptc01_percent") != 0 or latest_snapshot.get("ptc24_percent") != 0:
- failures.append("binary921_timeout_ptc_not_zero")
- if latest_snapshot.get("fan01_percent") != 30 or latest_snapshot.get("fan04_percent") != 30:
- failures.append("binary921_timeout_fan_not_30")
- for evidence_field in ["pwm_logic_evidence", "pid_evidence", "timeout_fallback_evidence"]:
- evidence = receipt.get(evidence_field) or {}
- if not isinstance(evidence, dict) or evidence.get("status") != "pass":
- failures.append(f"binary921_{evidence_field}_not_pass")
- safety = receipt.get("safety") or {}
- if not isinstance(safety, dict):
- failures.append("binary921_safety_not_object")
- safety = {}
- for field in BINARY921_REQUIRED_SAFETY_FALSE_FIELDS:
- if safety.get(field) is not False:
- failures.append(f"binary921_safety_flag:{field}")
- for marker in _forbidden_action_markers(receipt, BINARY921_FORBIDDEN_ACTION_MARKERS):
- failures.append(f"binary921_forbidden_action_marker:{marker}")
- startup_ready = receipt.get("startup_ready") or {}
- decoded = startup_ready.get("decoded") if isinstance(startup_ready, dict) else None
- frame_type = startup_ready.get("frame_type") if isinstance(startup_ready, dict) else None
- if strict and not (
- isinstance(decoded, dict)
- and decoded.get("kind") == "ready"
- and int(frame_type if frame_type is not None else -1) == 1
- ):
- failures.append("binary921_startup_ready_missing")
- return failures
- def _validate_changxin_temp_uart_tty0tty_receipt(receipt: dict[str, Any], *, strict: bool) -> list[str]:
- failures: list[str] = []
- if receipt.get("status") != "pass":
- failures.append(f"tty0tty_status_not_pass:{receipt.get('status')}")
- if receipt.get("operation") not in {"doctor", "setup", "teardown"}:
- failures.append("tty0tty_operation")
- failures.extend(_validate_json_schema_file(receipt, "changxin_temp_uart_tty0tty_receipt.schema.json", required=strict))
- safety = receipt.get("safety") or {}
- for field in [
- "flash_attempted",
- "program_sram_attempted",
- "programs_flash",
- "programs_nonvolatile",
- "real_ptc_fan_action_attempted",
- "thermal_performance_claimed",
- "auto_setup_from_run_attempted",
- ]:
- if safety.get(field) is not False:
- failures.append(f"safety_flag:{field}")
- if strict and not receipt.get("rollback"):
- failures.append("tty0tty_missing_rollback")
- authority = str(receipt.get("authority_boundary") or "").lower()
- if "thermal performance" not in authority or "does not prove" not in authority:
- failures.append("tty0tty_authority_boundary_missing_thermal_exclusion")
- 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 line_index, raw in enumerate(_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
- fields["line_index"] = line_index
- 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
- last_frame_end = first_off
- last_stat_line_index = _safe_int((last_stat or {}).get("line_index"), default=None)
- tail_bytes_after_last_stat = 0
- tail_frames_after_last_stat = 0
- replay_len_at_last_stat = 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)
- last_frame_end = off + length
- if last_stat_line_index is not None and _safe_int(frame.get("line_index"), default=-1) < last_stat_line_index:
- replay_len_at_last_stat = last_frame_end
- elif last_stat_line_index is not None and _safe_int(frame.get("line_index"), default=-1) > last_stat_line_index:
- tail_bytes_after_last_stat += length
- tail_frames_after_last_stat += 1
- 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
- raw_in_covers_replay = raw_in is not None and raw_in == expected_replay_len
- raw_out_covers_replay = raw_out is not None and raw_out == expected_replay_len
- raw_in_covers_last_stat = raw_in is not None and raw_in == replay_len_at_last_stat and expected_replay_len >= raw_in
- raw_out_covers_last_stat = raw_out is not None and raw_out == replay_len_at_last_stat and expected_replay_len >= raw_out
- if raw_in is not None and not (raw_in_covers_replay or (tail_bytes_after_last_stat > 0 and raw_in_covers_last_stat)):
- failures.append("raw_in_replay_len_mismatch")
- if raw_out is not None and not (raw_out_covers_replay or (tail_bytes_after_last_stat > 0 and raw_out_covers_last_stat)):
- 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,
- "last_frame_end_offset": last_frame_end,
- "last_j6stat_line_index": last_stat_line_index,
- "replay_len_at_last_j6stat": replay_len_at_last_stat,
- "post_j6stat_tail_bytes": tail_bytes_after_last_stat,
- "post_j6stat_tail_frames": tail_frames_after_last_stat,
- "last_j6stat_covers_replay": (
- raw_in == len(replay) + first_off and raw_out == len(replay) + first_off
- if raw_in is not None and raw_out is not None
- else False
- ),
- },
- 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")
- if _safe_int(programming.get("jtag_speed_hz"), default=0) != 200000:
- failures.append("jtag_speed_hz_not_200000")
- if programming.get("board_power_present_before_program") is not True:
- failures.append("board_power_present_before_program_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")
- if _safe_int(manual_layer.get("jtag_speed_hz"), default=0) != 200000:
- failures.append("manual_sram_jtag_speed_hz_not_200000")
- if manual_layer.get("board_power_present_before_program") is not True:
- failures.append("manual_sram_board_power_present_before_program_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 _safe_int(attestation_payload.get("jtag_speed_hz"), default=0) != 200000:
- failures.append("manual_sram_attestation_jtag_speed_hz_not_200000")
- if attestation_payload.get("board_power_present_before_program") is not True:
- failures.append("manual_sram_attestation_board_power_present_before_program_not_true")
- 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)
- jtag_attestation_failures = {
- "jtag_speed_hz_not_200000",
- "board_power_present_before_program_not_true",
- "manual_sram_jtag_speed_hz_not_200000",
- "manual_sram_board_power_present_before_program_not_true",
- "manual_sram_attestation_jtag_speed_hz_not_200000",
- "manual_sram_attestation_board_power_present_before_program_not_true",
- }
- 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 failure_set.intersection(jtag_attestation_failures):
- final_status = "fail"
- 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",
- "blocked_layer:artifact_hashes",
- "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")
- if schema == "j6-binary921-evidence-manifest-v1":
- safety_failures = []
- failures.extend(_validate_binary921_evidence_manifest(receipt, strict=strict))
- else:
- safety_failures = _validate_safety(receipt)
- failures.extend(safety_failures)
- if schema == "changxin-temp-uart-publisher-receipt-v1":
- failures.extend(_validate_changxin_temp_uart_receipt(receipt, strict=strict))
- if schema == "changxin-temp-uart-tty0tty-receipt-v1":
- failures.extend(_validate_changxin_temp_uart_tty0tty_receipt(receipt, strict=strict))
- 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 any(item.startswith("safety_flag:") for item in 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())
|