uart_receipts.py 164 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527
  1. #!/usr/bin/env python3
  2. """UART/RS232 receipt builders and validators that do not depend on ChipWatcher."""
  3. from __future__ import annotations
  4. import argparse
  5. import copy
  6. import hashlib
  7. import importlib.util
  8. import json
  9. import os
  10. import re
  11. import subprocess
  12. import sys
  13. from datetime import datetime, timezone
  14. from pathlib import Path
  15. from typing import Any
  16. ROOT = Path(__file__).resolve().parents[1]
  17. FORBIDDEN_ACTION_MARKERS = [
  18. "PROGRAM_FLASH",
  19. "ERASE_FLASH",
  20. "PROGRAM_SPIBIN",
  21. "DIRECT_FLASH_WRITE",
  22. "DRIVER_INSTALL",
  23. "DRIVER_REINSTALL",
  24. "REAL_PTC",
  25. "REAL_FAN",
  26. "REAL_BMC",
  27. ]
  28. REAL_BMC_J6_FORBIDDEN_ACTION_MARKERS = [
  29. marker for marker in FORBIDDEN_ACTION_MARKERS if marker != "REAL_BMC"
  30. ]
  31. REAL_BMC_J6_FORBIDDEN_ACTION_MARKERS.extend(
  32. [
  33. "DRIVER_INSTALL",
  34. "DRIVER_REINSTALL",
  35. "PROGRAM_DEVICE",
  36. "DOWNLOAD",
  37. "CONNECT_CABLE",
  38. "OPEN_COM",
  39. "COM_OPEN",
  40. "TOGGLE_DTR",
  41. "TOGGLE_RTS",
  42. "READ_DEVICE_ID",
  43. ]
  44. )
  45. REAL_BMC_J6_WINDOWS_FORBIDDEN_ACTION_MARKERS = [
  46. marker
  47. for marker in REAL_BMC_J6_FORBIDDEN_ACTION_MARKERS
  48. if marker not in {"OPEN_COM", "COM_OPEN"}
  49. ]
  50. OFFLINE_FIDELITY_FORBIDDEN_ACTION_MARKERS = [
  51. *FORBIDDEN_ACTION_MARKERS,
  52. "PROGRAM_SRAM",
  53. "OPEN_COM",
  54. "COM_OPEN",
  55. "TOGGLE_DTR",
  56. "TOGGLE_RTS",
  57. "DTR",
  58. "RTS",
  59. "CONNECT_CABLE",
  60. "DOWNLOAD",
  61. "PROGRAM_DEVICE",
  62. "READ_DEVICE_ID",
  63. ]
  64. UART_SCHEMAS = {
  65. "uart-preflight-receipt-v1": "uart-preflight-validation-v1",
  66. "bmc-uart-protocol-receipt-v1": "bmc-uart-protocol-validation-v1",
  67. "uart-loopback-receipt-v1": "uart-loopback-validation-v1",
  68. "uart-board-sram-receipt-v1": "uart-board-sram-validation-v1",
  69. "uart-soak-receipt-v1": "uart-soak-validation-v1",
  70. }
  71. FINAL_GATE_REQUIRED_LAYERS = [
  72. "static",
  73. "model",
  74. "replay",
  75. "rtl_sim",
  76. "formal",
  77. "detector_selftest",
  78. "td_build",
  79. "uart_strict",
  80. ]
  81. OFFLINE_FIDELITY_REQUIRED_LAYERS = [
  82. "static",
  83. "model",
  84. "replay",
  85. "protocol_fuzz",
  86. "hdl_sim",
  87. "cocotb_virtual_lab",
  88. "virtual_driver_lab",
  89. "formal",
  90. "detector_selftest",
  91. "mutation",
  92. "thermal_digital_twin",
  93. "coverage_matrix",
  94. "td_build",
  95. "debug_bundle",
  96. ]
  97. OFFLINE_FIDELITY_FORBIDDEN_LAYERS = {
  98. "hardware",
  99. "board",
  100. "uart_strict",
  101. "chipwatcher",
  102. "thermal_performance_pass",
  103. }
  104. OFFLINE_FIDELITY_LAYER_EVIDENCE = {
  105. "static": ["returncode"],
  106. "model": ["tests"],
  107. "replay": ["sample_count"],
  108. "protocol_fuzz": ["scenarios"],
  109. "hdl_sim": ["tests", "backend_results"],
  110. "cocotb_virtual_lab": ["sim"],
  111. "virtual_driver_lab": ["user_mode_shims", "trace_hash"],
  112. "formal": ["targets"],
  113. "detector_selftest": ["results"],
  114. "mutation": ["mutants"],
  115. "thermal_digital_twin": ["models"],
  116. "coverage_matrix": ["items"],
  117. "td_build": ["elaboration"],
  118. "debug_bundle": ["path", "bundle_dir"],
  119. }
  120. OFFLINE_FIDELITY_REQUIRED_COVERAGE_CATEGORIES = {
  121. "protocol",
  122. "uart_bit",
  123. "control",
  124. "safety",
  125. "debug",
  126. "virtual_driver_lab",
  127. "thermal",
  128. "fault_injection",
  129. "cocotb_virtual_lab",
  130. "formal",
  131. "mutation",
  132. "td_toolchain",
  133. }
  134. OFFLINE_FIDELITY_REQUIRED_VIRTUAL_SHIMS = {
  135. "pyserial_loopback_url",
  136. "socket_pipe_transport",
  137. "bmc_text_driver",
  138. "host_register_plane",
  139. "debug_uart_decoder",
  140. "fault_injection_facade",
  141. }
  142. OFFLINE_FIDELITY_REQUIRED_VIRTUAL_FAULTS = {
  143. "timeout",
  144. "disconnect",
  145. "partial_read",
  146. "partial_write",
  147. "permission_denied",
  148. "buffer_overflow",
  149. "tx_backpressure",
  150. "rx_overflow",
  151. }
  152. OFFLINE_FIDELITY_REQUIRED_THERMAL_SCENARIOS = {
  153. "conservative",
  154. "optimistic",
  155. "extreme",
  156. "random_perturbation",
  157. "sensor_drift",
  158. "sensor_delay",
  159. "crosstalk",
  160. "fan_degradation",
  161. "ptc_thermal_inertia",
  162. }
  163. OFFLINE_FIDELITY_REQUIRED_MUTANTS = {
  164. "invert_fault_condition",
  165. "remove_force_off",
  166. "break_channel_compare",
  167. "drop_debug_event",
  168. "break_debug_checksum",
  169. "bad_formal_property",
  170. }
  171. OFFLINE_FIDELITY_REQUIRED_TOOLCHAIN_TOOLS = {
  172. "python",
  173. "iverilog",
  174. "vvp",
  175. "verilator",
  176. "yosys",
  177. "sby",
  178. "cocotb",
  179. "td_cli",
  180. }
  181. REAL_BMC_J6_WINDOWS_REQUIRED_LAYERS = [
  182. "td_bitstream",
  183. "manual_sram_programming",
  184. "windows_serial_capture",
  185. "real_bmc_protocol",
  186. "safety_contract",
  187. "artifact_hashes",
  188. ]
  189. REAL_BMC_J6_WINDOWS_ALLOWED_LAYER_SET = set(REAL_BMC_J6_WINDOWS_REQUIRED_LAYERS)
  190. REAL_BMC_J6_WINDOWS_ALLOWED_PIN_PROFILES = {
  191. "primary": {"tx_ball": "T4", "rx_ball": "R5", "debug_rx_ball": "P10", "debug_tx_ball": "R10"},
  192. "swapped": {"tx_ball": "R5", "rx_ball": "T4", "debug_rx_ball": "P10", "debug_tx_ball": "R10"},
  193. }
  194. REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_REQUIRED_LAYERS = [
  195. "td_bitstream",
  196. "manual_sram_programming",
  197. "host_command_sequence",
  198. "host_control_transcript",
  199. "host_sensor_reports",
  200. "debug_frame_capture",
  201. "bmc_raw_sampling",
  202. "pid_boundary",
  203. "timeout_evidence",
  204. "pin_map",
  205. "safety_contract",
  206. "real_fan_ptc_hardware_status",
  207. "artifact_hashes",
  208. ]
  209. REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_LAYER_SET = set(
  210. REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_REQUIRED_LAYERS
  211. )
  212. REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_TOP_MODULE = (
  213. "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921_top"
  214. )
  215. REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_TOP_MODULES_BY_PIN_PROFILE = {
  216. "temp-uart-ptc-remap": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921_top",
  217. "formal-uart": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921_top",
  218. }
  219. REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_PIN_PROFILES = {
  220. "temp-uart-ptc-remap": {
  221. "tx_ball": "T4",
  222. "rx_ball": "R5",
  223. "bmc_tx_ball": "T4",
  224. "bmc_rx_ball": "R5",
  225. "host_tx_ball": "P7",
  226. "host_rx_ball": "P8",
  227. "debug_rx_ball": "P10",
  228. "debug_tx_ball": "R10",
  229. },
  230. "formal-uart": {
  231. "tx_ball": "P5",
  232. "rx_ball": "T8",
  233. "bmc_tx_ball": "P5",
  234. "bmc_rx_ball": "T8",
  235. "host_tx_ball": "M14",
  236. "host_rx_ball": "M15",
  237. "debug_rx_ball": "P15",
  238. "debug_tx_ball": "N14",
  239. },
  240. }
  241. REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_COMMANDS = [
  242. "SET PTC 01 10",
  243. "SET PTC 24 20",
  244. "SET FAN 01 40",
  245. "SET FAN 04 30",
  246. "SET PID ENABLE",
  247. "GET STATUS",
  248. "GET MAP",
  249. "GET SENSOR",
  250. "GET SENSOR",
  251. "GET SENSOR",
  252. "SET PID DISABLE",
  253. "DISABLE",
  254. ]
  255. REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_ACK_CMDS = {
  256. "SET PTC 01 10": "PTCCH",
  257. "SET PTC 24 20": "PTCCH",
  258. "SET FAN 01 40": "FANCH",
  259. "SET FAN 04 30": "FANCH",
  260. "SET PID ENABLE": "PID_EN",
  261. "GET STATUS": "STATUS",
  262. "GET MAP": "MAP___",
  263. "GET SENSOR": "SENSOR",
  264. "SET PID DISABLE": "PID_DI",
  265. "DISABLE": "DISABL",
  266. }
  267. REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_COMMAND_RE = re.compile(
  268. r"^(?:"
  269. r"SET PTC (?:0[1-9]|1[0-9]|2[0-4]) (?:0|[1-9][0-9]?|100)|"
  270. r"SET FAN (?:0[1-4]) (?:0|[1-9][0-9]?|100)|"
  271. r"SET PID ENABLE|"
  272. r"SET PID DISABLE|"
  273. r"GET STATUS|"
  274. r"GET MAP|"
  275. r"GET SENSOR|"
  276. r"DISABLE"
  277. r")$"
  278. )
  279. REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_FORBIDDEN_ACTION_MARKERS = [
  280. marker
  281. for marker in REAL_BMC_J6_WINDOWS_FORBIDDEN_ACTION_MARKERS
  282. if marker not in {"REAL_FAN", "REAL_PTC"}
  283. ]
  284. REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_REQUIRED_SAFETY_FALSE_FIELDS = [
  285. "flash_attempted",
  286. "driver_install_attempted",
  287. "programs_flash",
  288. "programs_nonvolatile",
  289. "opens_unknown_com_ports",
  290. "enumerates_com_ports",
  291. "toggles_dtr_rts",
  292. "debug_port_writes_to_serial",
  293. "uncontrolled_real_bmc_action_attempted",
  294. "real_thermal_performance_claimed",
  295. ]
  296. REAL_BMC_J6_WINDOWS_REQUIRED_SAFETY_FALSE_FIELDS = [
  297. "flash_attempted",
  298. "driver_install_attempted",
  299. "programs_flash",
  300. "opens_unknown_com_ports",
  301. "toggles_dtr_rts",
  302. "ptc_fan_pins_exported",
  303. "real_ptc_fan_action_attempted",
  304. "uncontrolled_real_bmc_action_attempted",
  305. ]
  306. REAL_BMC_J6_ACTION_SAFETY_ALIASES = {
  307. "com_open",
  308. "connect_cable",
  309. "connects_cable",
  310. "download_to_hardware",
  311. "downloads_to_hardware",
  312. "driver_install",
  313. "driver_installed",
  314. "erase_flash",
  315. "install_driver",
  316. "installs_drivers",
  317. "open_com",
  318. "opened_com",
  319. "program_device",
  320. "program_flash",
  321. "programs_device",
  322. "read_device_id",
  323. "real_bmc_action_attempted",
  324. "real_fan_action_attempted",
  325. "real_ptc_action_attempted",
  326. "real_ptc_fan_bmc_action_attempted",
  327. "touches_ptc_fan_bmc",
  328. "toggle_dtr",
  329. "toggle_rts",
  330. "toggles_dtr",
  331. "toggles_rts",
  332. }
  333. J6SYS_RE = re.compile(
  334. r"J6SYS\s+wake=(?P<wake>[0-9A-Fa-f]{8})\s+poll=(?P<poll>[0-9A-Fa-f]{8})"
  335. r"\s+tx=(?P<tx>[0-9A-Fa-f]{8})\s+rx=(?P<rx>[0-9A-Fa-f]{8})"
  336. r"\s+uerr=(?P<uerr>[0-9A-Fa-f]{2,8})\s+state=(?P<state>[0-9A-Fa-f]+)"
  337. r"\s+tok=(?P<tok>[0-9A-Fa-f]{8})\s+seq=(?P<seq>[0-9A-Fa-f]{8})"
  338. r"\s+valid=(?P<valid>[0-9A-Fa-f]{8})\s+perr=(?P<perr>[0-9A-Fa-f]+)"
  339. r"\s+stale=(?P<stale>[0-9A-Fa-f]+)\s+frame=(?P<frame>[0-9A-Fa-f]+)"
  340. r"\s+duovf=(?P<duovf>[0-9A-Fa-f]+)\s+dbg=(?P<dbg>[0-9A-Fa-f]{8})"
  341. r"\s+derr=(?P<derr>[0-9A-Fa-f]{8})"
  342. )
  343. def _parse_j6sys_line(raw: str) -> dict[str, object] | None:
  344. match = J6SYS_RE.search(raw)
  345. if not match:
  346. return None
  347. return {
  348. "kind": "j6sys",
  349. "raw": raw,
  350. "wake": int(match.group("wake"), 16),
  351. "poll": int(match.group("poll"), 16),
  352. "tx": int(match.group("tx"), 16),
  353. "rx": int(match.group("rx"), 16),
  354. "uerr": int(match.group("uerr"), 16),
  355. "state": int(match.group("state"), 16),
  356. "tok": int(match.group("tok"), 16),
  357. "seq": int(match.group("seq"), 16),
  358. "valid": int(match.group("valid"), 16),
  359. "perr": int(match.group("perr"), 16),
  360. "stale": int(match.group("stale"), 16),
  361. "frame": int(match.group("frame"), 16),
  362. "duovf": int(match.group("duovf"), 16),
  363. "dbg": int(match.group("dbg"), 16),
  364. "derr": int(match.group("derr"), 16),
  365. }
  366. def utc_now() -> str:
  367. return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
  368. def compute_file_hash(path: Path | str) -> str:
  369. digest = hashlib.sha256()
  370. with Path(path).open("rb") as handle:
  371. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  372. digest.update(chunk)
  373. return digest.hexdigest()
  374. def read_json(path: Path | str) -> dict[str, Any]:
  375. return json.loads(Path(path).read_text(encoding="utf-8-sig"))
  376. def backend_capabilities() -> dict[str, Any]:
  377. has_pyserial = importlib.util.find_spec("serial") is not None
  378. has_jsonschema = importlib.util.find_spec("jsonschema") is not None
  379. return {
  380. "schema": "uart-tool-backend-capabilities-v1",
  381. "generated_at": utc_now(),
  382. "python": sys.executable,
  383. "serial_backend": "pyserial" if has_pyserial else "powershell_dotnet_limited",
  384. "schema_backend": "jsonschema" if has_jsonschema else "builtin_limited",
  385. "pyserial_available": has_pyserial,
  386. "jsonschema_available": has_jsonschema,
  387. "strict_gate_requires": [
  388. "explicit COM allowlist",
  389. "hashes for transcript and bitstream artifacts",
  390. "SRAM-only programming evidence",
  391. "debug UART event stream",
  392. "register dump snapshot",
  393. ],
  394. }
  395. def _resolve_receipt_path(receipt_path: Path, value: Any) -> Path:
  396. if isinstance(value, dict):
  397. value = value.get("path")
  398. path = Path(str(value))
  399. if not path.is_absolute():
  400. path = receipt_path.parent / path
  401. return path
  402. def _receipt_path_candidates(receipt_path: Path, value: Any) -> list[tuple[Path, str]]:
  403. if isinstance(value, dict):
  404. value = value.get("path")
  405. raw = str(value)
  406. path = Path(raw)
  407. if not path.is_absolute():
  408. return [(receipt_path.parent / path, "package_relative")]
  409. candidates: list[tuple[Path, str]] = [(path, "as_recorded")]
  410. package_dir = receipt_path.parent
  411. if path.name:
  412. try:
  413. if path.parent.name == package_dir.name:
  414. candidates.append((package_dir / path.name, "package_relative"))
  415. else:
  416. candidates.append((package_dir / path.name, "package_basename"))
  417. except OSError:
  418. candidates.append((package_dir / path.name, "package_basename"))
  419. package_name = package_dir.name
  420. parts = path.parts
  421. if package_name in parts:
  422. index = parts.index(package_name)
  423. suffix = Path(*parts[index + 1 :]) if index + 1 < len(parts) else Path()
  424. if str(suffix):
  425. candidates.append((package_dir / suffix, "package_suffix"))
  426. deduped: list[tuple[Path, str]] = []
  427. seen: set[str] = set()
  428. for candidate, resolution in candidates:
  429. key = str(candidate)
  430. if key in seen:
  431. continue
  432. seen.add(key)
  433. deduped.append((candidate, resolution))
  434. return deduped
  435. def _hash_validation(receipt_path: Path, item: Any, *, required: bool) -> dict[str, Any]:
  436. if not item:
  437. return {"status": "missing" if required else "not_provided", "exists": False}
  438. raw_path = item.get("path") if isinstance(item, dict) else item
  439. expected = item.get("sha256") if isinstance(item, dict) else None
  440. if not raw_path:
  441. return {"status": "missing", "exists": False}
  442. candidates = _receipt_path_candidates(receipt_path, item)
  443. path, resolution = candidates[0]
  444. for candidate, candidate_resolution in candidates:
  445. if candidate.is_file():
  446. path = candidate
  447. resolution = candidate_resolution
  448. break
  449. result: dict[str, Any] = {
  450. "raw_path": str(raw_path),
  451. "path": str(path),
  452. "exists": path.is_file(),
  453. "resolution": resolution,
  454. "tried": [str(candidate) for candidate, _ in candidates],
  455. }
  456. if not path.is_file():
  457. result["status"] = "missing"
  458. return result
  459. actual = compute_file_hash(path)
  460. result["sha256"] = actual
  461. if not expected:
  462. result["status"] = "missing_hash"
  463. elif str(expected).lower() != actual:
  464. result["status"] = "hash_mismatch"
  465. else:
  466. result["status"] = "pass"
  467. return result
  468. def _hash_validation_with_optional_receipt_path(
  469. receipt_path: Path | None,
  470. item: Any,
  471. *,
  472. required: bool,
  473. ) -> dict[str, Any]:
  474. if receipt_path is not None:
  475. return _hash_validation(receipt_path, item, required=required)
  476. if not item:
  477. return {"status": "missing" if required else "not_provided", "exists": False}
  478. raw_path = item.get("path") if isinstance(item, dict) else item
  479. expected = item.get("sha256") if isinstance(item, dict) else None
  480. if not raw_path:
  481. return {"status": "missing", "exists": False}
  482. path = Path(str(raw_path))
  483. result: dict[str, Any] = {
  484. "raw_path": str(raw_path),
  485. "path": str(path),
  486. "exists": path.is_file() if path.is_absolute() else False,
  487. "resolution": "absolute_direct" if path.is_absolute() else "unresolved_without_receipt_path",
  488. "tried": [str(path)],
  489. }
  490. if not path.is_absolute():
  491. result["status"] = "relative_without_receipt_path"
  492. return result
  493. if not path.is_file():
  494. result["status"] = "missing"
  495. return result
  496. actual = compute_file_hash(path)
  497. result["sha256"] = actual
  498. if not expected:
  499. result["status"] = "missing_hash"
  500. elif str(expected).lower() != actual:
  501. result["status"] = "hash_mismatch"
  502. else:
  503. result["status"] = "pass"
  504. return result
  505. def _safe_int(value: Any, *, default: int | None = None) -> int | None:
  506. try:
  507. if isinstance(value, bool):
  508. return int(value)
  509. if isinstance(value, str):
  510. token = value.strip()
  511. if token.lower().startswith("0x"):
  512. return int(token[2:], 16)
  513. if re.fullmatch(r"[0-9A-Fa-f]+", token) and any(ch in "ABCDEFabcdef" for ch in token):
  514. return int(token, 16)
  515. return int(value)
  516. except (TypeError, ValueError):
  517. return default
  518. def _safe_fixed_hex_int(value: Any, *, default: int | None = None) -> int | None:
  519. try:
  520. if isinstance(value, bool):
  521. return int(value)
  522. if isinstance(value, int):
  523. return value
  524. if isinstance(value, str):
  525. token = value.strip()
  526. if token.lower().startswith("0x"):
  527. token = token[2:]
  528. if re.fullmatch(r"[0-9A-Fa-f]+", token):
  529. return int(token, 16)
  530. return int(value)
  531. except (TypeError, ValueError):
  532. return default
  533. def _raw_field_token(raw: Any, key: str) -> str | None:
  534. if not isinstance(raw, str):
  535. return None
  536. match = re.search(rf"(?:^|\s){re.escape(key)}=([^ \t\r\n]+)", raw)
  537. if not match:
  538. return None
  539. return match.group(1).rstrip("\\r").rstrip("\\n")
  540. def _normalize_compact_alias_value(field: str, value: Any) -> Any:
  541. if not isinstance(value, str):
  542. return value
  543. if field in {"source", "pwm_source"} and value == "hm":
  544. return "host_manual"
  545. if field == "status" and value == "ok":
  546. return "valid"
  547. if field == "status" and value == "v":
  548. return "valid"
  549. if field == "status" and value == "a":
  550. return "all_ff"
  551. if field == "status" and value == "m":
  552. return "missing"
  553. return value
  554. def _artifact_hash_from_result(result: dict[str, Any] | None) -> str | None:
  555. if isinstance(result, dict) and result.get("status") in {"pass", "missing_hash"}:
  556. return str(result.get("sha256") or "")
  557. return None
  558. def _iter_string_values(value: Any):
  559. if isinstance(value, str):
  560. yield value
  561. elif isinstance(value, dict):
  562. for child in value.values():
  563. yield from _iter_string_values(child)
  564. elif isinstance(value, list):
  565. for child in value:
  566. yield from _iter_string_values(child)
  567. def _iter_string_keys_and_values(value: Any):
  568. if isinstance(value, str):
  569. yield value
  570. elif isinstance(value, dict):
  571. for key, child in value.items():
  572. yield str(key)
  573. yield from _iter_string_keys_and_values(child)
  574. elif isinstance(value, list):
  575. for child in value:
  576. yield from _iter_string_keys_and_values(child)
  577. def _contains_forbidden_action(receipt: dict[str, Any]) -> bool:
  578. text = "\n".join(_iter_string_values(receipt)).upper()
  579. return any(marker in text for marker in FORBIDDEN_ACTION_MARKERS)
  580. def _forbidden_action_markers(receipt: dict[str, Any], markers: list[str] | None = None) -> list[str]:
  581. text = "\n".join(_iter_string_values(receipt)).upper()
  582. return _forbidden_markers_in_text(text, markers)
  583. def _forbidden_action_markers_in_keys_and_values(receipt: dict[str, Any], markers: list[str] | None = None) -> list[str]:
  584. text = "\n".join(_iter_string_keys_and_values(receipt)).upper()
  585. return _forbidden_markers_in_text(text, markers)
  586. def _forbidden_markers_in_text(text: str, markers: list[str] | None = None) -> list[str]:
  587. text = text.upper()
  588. found: list[str] = []
  589. for marker in markers or FORBIDDEN_ACTION_MARKERS:
  590. pattern = rf"(?<![A-Z0-9_\\/]){re.escape(marker.upper())}(?![A-Z0-9_\\/])"
  591. if re.search(pattern, text):
  592. found.append(marker)
  593. return found
  594. def _validate_json_schema_file(payload: dict[str, Any], schema_file: str, *, required: bool) -> list[str]:
  595. if importlib.util.find_spec("jsonschema") is None:
  596. return ["schema_validation_unavailable"] if required else []
  597. schema_path = ROOT / "schemas" / schema_file
  598. if not schema_path.is_file():
  599. return ["schema_file_missing"] if required else []
  600. try:
  601. from jsonschema import Draft202012Validator # type: ignore
  602. schema = read_json(schema_path)
  603. errors = sorted(
  604. Draft202012Validator(schema).iter_errors(payload),
  605. key=lambda error: list(error.absolute_path),
  606. )
  607. except Exception as exc: # noqa: BLE001 - schema failures should fail closed.
  608. return [f"schema_validation_error:{exc.__class__.__name__}"]
  609. if not errors:
  610. return []
  611. failures = ["schema_error"]
  612. for error in errors[:5]:
  613. location = "/".join(str(part) for part in error.absolute_path) or "<root>"
  614. failures.append(f"schema_error:{location}:{error.validator}")
  615. if len(errors) > 5:
  616. failures.append(f"schema_error:additional_count:{len(errors) - 5}")
  617. return failures
  618. def _has_nonempty_evidence(item: dict[str, Any], keys: list[str]) -> tuple[bool, str]:
  619. for key in keys:
  620. value = item.get(key)
  621. if value is None:
  622. continue
  623. if isinstance(value, (list, dict, str)) and not value:
  624. continue
  625. return True, key
  626. return False, keys[0]
  627. def _set_from_named_items(items: Any, field: str = "name") -> set[str]:
  628. if not isinstance(items, list):
  629. return set()
  630. names: set[str] = set()
  631. for item in items:
  632. if isinstance(item, dict) and item.get(field):
  633. names.add(str(item[field]))
  634. return names
  635. def _scenario_covered(model_name: str, required: str) -> bool:
  636. if model_name == required:
  637. return True
  638. if required == "sensor_drift" and "sensor_drift" in model_name:
  639. return True
  640. if required == "sensor_delay" and "delay" in model_name:
  641. return True
  642. if required == "crosstalk" and "crosstalk" in model_name:
  643. return True
  644. if required == "fan_degradation" and "fan_degradation" in model_name:
  645. return True
  646. return False
  647. def _validate_toolchain_evidence(toolchain: dict[str, Any]) -> list[str]:
  648. failures: list[str] = []
  649. manifest = toolchain.get("manifest")
  650. if not isinstance(manifest, dict):
  651. failures.append("missing_toolchain_manifest")
  652. manifest = {}
  653. cleanup_policy = toolchain.get("cleanup_policy")
  654. if not isinstance(cleanup_policy, dict):
  655. failures.append("missing_toolchain_cleanup_policy")
  656. cleanup_policy = {}
  657. install_roots = manifest.get("install_roots") if isinstance(manifest, dict) else None
  658. if not isinstance(install_roots, dict) or not install_roots:
  659. failures.append("missing_toolchain_manifest:install_roots")
  660. manifest_tools = manifest.get("tools") if isinstance(manifest, dict) else None
  661. toolchain_tools = (toolchain.get("toolchain") or {}).get("tools") if isinstance(toolchain.get("toolchain"), dict) else None
  662. seen_tools = _set_from_named_items(manifest_tools)
  663. if isinstance(toolchain_tools, dict):
  664. seen_tools.update(str(name) for name, info in toolchain_tools.items() if isinstance(info, dict) and info.get("status") == "present")
  665. for tool in sorted(OFFLINE_FIDELITY_REQUIRED_TOOLCHAIN_TOOLS - seen_tools):
  666. failures.append(f"missing_toolchain_tool:{tool}")
  667. for item in manifest_tools if isinstance(manifest_tools, list) else []:
  668. if not isinstance(item, dict):
  669. continue
  670. if item.get("status") != "present":
  671. failures.append(f"toolchain_tool_not_present:{item.get('name', 'unknown')}")
  672. if not (item.get("path") or item.get("python")):
  673. failures.append(f"missing_toolchain_tool_path:{item.get('name', 'unknown')}")
  674. if cleanup_policy.get("default") != "dry_run":
  675. failures.append("toolchain_cleanup_not_dry_run")
  676. if cleanup_policy.get("requires_owner_marker") is not True:
  677. failures.append("toolchain_cleanup_missing_owner_marker")
  678. if not cleanup_policy.get("allowed_root"):
  679. failures.append("toolchain_cleanup_missing_allowed_root")
  680. return failures
  681. def _validate_offline_layer_evidence(layer: str, item: dict[str, Any]) -> list[str]:
  682. failures: list[str] = []
  683. keys = OFFLINE_FIDELITY_LAYER_EVIDENCE.get(layer, [])
  684. ok, representative = _has_nonempty_evidence(item, keys)
  685. if not ok:
  686. failures.append(f"missing_layer_evidence:{layer}:{representative}")
  687. return failures
  688. if layer == "virtual_driver_lab":
  689. shims = item.get("user_mode_shims") or []
  690. if not isinstance(shims, list) or not shims or any(not isinstance(shim, dict) or not shim.get("transcript") for shim in shims):
  691. failures.append("missing_layer_evidence:virtual_driver_lab:transcript")
  692. shim_names = _set_from_named_items(shims)
  693. for name in sorted(OFFLINE_FIDELITY_REQUIRED_VIRTUAL_SHIMS - shim_names):
  694. failures.append(f"missing_layer_evidence:virtual_driver_lab:{name}")
  695. for shim in shims if isinstance(shims, list) else []:
  696. if isinstance(shim, dict) and shim.get("status") != "pass":
  697. failures.append(f"missing_layer_evidence:virtual_driver_lab:shim_status:{shim.get('name', 'unknown')}")
  698. faults = set(str(value) for value in item.get("fault_contracts", []) if value) if isinstance(item.get("fault_contracts"), list) else set()
  699. for fault in sorted(OFFLINE_FIDELITY_REQUIRED_VIRTUAL_FAULTS - faults):
  700. failures.append(f"missing_layer_evidence:virtual_driver_lab:{fault}")
  701. if len(str(item.get("trace_hash") or "")) != 64:
  702. failures.append("missing_layer_evidence:virtual_driver_lab:trace_hash")
  703. elif layer == "mutation":
  704. mutants = item.get("mutants") or []
  705. if not isinstance(mutants, list) or not mutants:
  706. failures.append("missing_layer_evidence:mutation:mutants")
  707. mutant_names = _set_from_named_items(mutants)
  708. for mutant_name in sorted(OFFLINE_FIDELITY_REQUIRED_MUTANTS - mutant_names):
  709. failures.append(f"missing_layer_evidence:mutation:{mutant_name}")
  710. for mutant in mutants if isinstance(mutants, list) else []:
  711. if not isinstance(mutant, dict) or mutant.get("mutation_status") != "killed":
  712. failures.append("missing_layer_evidence:mutation:killed")
  713. break
  714. if len(str(mutant.get("artifact_sha256") or "")) != 64:
  715. failures.append("missing_layer_evidence:mutation:artifact_sha256")
  716. break
  717. elif layer == "thermal_digital_twin":
  718. models = item.get("models") or []
  719. model_names = _set_from_named_items(models)
  720. for required in sorted(OFFLINE_FIDELITY_REQUIRED_THERMAL_SCENARIOS):
  721. if not any(_scenario_covered(name, required) for name in model_names):
  722. failures.append(f"missing_layer_evidence:thermal_digital_twin:{required}")
  723. for model in models if isinstance(models, list) else []:
  724. if not isinstance(model, dict) or len(str(model.get("trace_hash") or "")) != 64:
  725. failures.append("missing_layer_evidence:thermal_digital_twin:trace_hash")
  726. break
  727. if model.get("status") != "pass":
  728. failures.append("missing_layer_evidence:thermal_digital_twin:model_status")
  729. break
  730. if model.get("violations") not in (None, []):
  731. failures.append("missing_layer_evidence:thermal_digital_twin:violations")
  732. break
  733. elif layer == "coverage_matrix":
  734. rows = item.get("items") or []
  735. if not isinstance(rows, list) or not rows or any(not isinstance(row, dict) or row.get("status") != "pass" for row in rows):
  736. failures.append("missing_layer_evidence:coverage_matrix:covered_items")
  737. categories = set()
  738. for row in rows if isinstance(rows, list) else []:
  739. if isinstance(row, dict) and row.get("category"):
  740. categories.add(str(row["category"]))
  741. if isinstance(row, dict) and not row.get("covered_by"):
  742. failures.append(f"missing_layer_evidence:coverage_matrix:covered_by:{row.get('category', 'unknown')}")
  743. for category in sorted(OFFLINE_FIDELITY_REQUIRED_COVERAGE_CATEGORIES - categories):
  744. failures.append(f"missing_layer_evidence:coverage_matrix:{category}")
  745. elif layer == "td_build":
  746. elaboration = item.get("elaboration") or {}
  747. if not isinstance(elaboration, dict) or elaboration.get("status") != "pass":
  748. failures.append("missing_layer_evidence:td_build:elaboration")
  749. else:
  750. database = elaboration.get("database") or {}
  751. plan = elaboration.get("plan") or {}
  752. if not isinstance(database, dict) or len(str(database.get("sha256") or "")) != 64:
  753. failures.append("missing_layer_evidence:td_build:database")
  754. if not isinstance(plan, dict) or len(str(plan.get("script_sha256") or "")) != 64:
  755. failures.append("missing_layer_evidence:td_build:script_sha256")
  756. return failures
  757. def _validate_safety(receipt: dict[str, Any]) -> list[str]:
  758. failures: list[str] = []
  759. safety = receipt.get("safety") or {}
  760. for field in ["flash_attempted", "real_ptc_fan_bmc_action_attempted", "driver_install_attempted"]:
  761. if safety.get(field) is not False:
  762. failures.append(f"safety_flag:{field}")
  763. if _contains_forbidden_action(receipt):
  764. failures.append("forbidden_action_marker")
  765. return failures
  766. def _validate_real_bmc_artifact(
  767. receipt_path: Path | None,
  768. layer: dict[str, Any],
  769. key: str,
  770. failure_prefix: str,
  771. *,
  772. required: bool = True,
  773. ) -> tuple[dict[str, Any] | None, list[str]]:
  774. failures: list[str] = []
  775. result = _hash_validation_with_optional_receipt_path(receipt_path, layer.get(key), required=required)
  776. if result["status"] == "missing":
  777. failures.append(f"missing_{failure_prefix}")
  778. elif result["status"] == "relative_without_receipt_path":
  779. failures.append(f"{failure_prefix}_relative_without_receipt_path")
  780. elif result["status"] == "missing_hash":
  781. failures.append(f"missing_{failure_prefix}_hash")
  782. elif result["status"] == "hash_mismatch":
  783. failures.append(f"{failure_prefix}_hash_mismatch")
  784. return result, failures
  785. def _validate_real_bmc_debug_artifact(
  786. receipt_path: Path | None,
  787. remote_layer: dict[str, Any],
  788. field: str,
  789. ) -> tuple[dict[str, Any] | None, list[str]]:
  790. debug_evidence = remote_layer.get("debug_evidence") if isinstance(remote_layer, dict) else None
  791. item = debug_evidence.get(field) if isinstance(debug_evidence, dict) else None
  792. failure_name = f"debug_{field}"
  793. if receipt_path is None:
  794. return None, ([] if item else [f"missing_{failure_name}"])
  795. result = _hash_validation(receipt_path, item, required=True)
  796. failures: list[str] = []
  797. if result["status"] == "missing":
  798. failures.append(f"missing_{failure_name}")
  799. elif result["status"] == "missing_hash":
  800. failures.append(f"missing_{failure_name}_hash")
  801. elif result["status"] == "hash_mismatch":
  802. failures.append(f"{failure_name}_hash_mismatch")
  803. return result, failures
  804. def _real_bmc_artifact_content_status(result: dict[str, Any] | None, role: str) -> tuple[str, list[str]]:
  805. if not isinstance(result, dict) or result.get("exists") is not True:
  806. return "missing", []
  807. path = Path(str(result.get("path") or ""))
  808. if not path.is_file():
  809. return "missing", []
  810. try:
  811. data = path.read_bytes()
  812. except OSError as exc:
  813. return "fail", [f"{role}_unreadable:{exc.__class__.__name__}"]
  814. if b"\x00" in data[:4096]:
  815. return "pass", []
  816. try:
  817. text = data.decode("utf-8-sig")
  818. except UnicodeDecodeError:
  819. try:
  820. text = data.decode("utf-16")
  821. except UnicodeDecodeError:
  822. return "fail", [f"{role}_unreadable:UnicodeDecodeError"]
  823. try:
  824. payload = json.loads(text)
  825. except json.JSONDecodeError:
  826. lowered = text.lower()
  827. if "blocked_pending" in lowered or "blocked_missing" in lowered:
  828. return "blocked", [f"{role}_status_not_pass:blocked_placeholder"]
  829. return ("pass", []) if text.strip() else ("blocked", [f"{role}_status_not_pass:empty"])
  830. if isinstance(payload, dict):
  831. failures: list[str] = []
  832. normalized = "pass"
  833. status = str(payload.get("status") or "pass")
  834. if status != "pass":
  835. normalized = "blocked" if status.startswith("blocked_") else "fail"
  836. failures.append(f"{role}_status_not_pass:{status}")
  837. if role == "debug_event_stream" and not payload.get("events"):
  838. normalized = "blocked" if normalized == "pass" else normalized
  839. failures.append(f"{role}_status_not_pass:empty_events")
  840. if role == "debug_register_dump" and not payload.get("debug_registers"):
  841. normalized = "blocked" if normalized == "pass" else normalized
  842. failures.append(f"{role}_status_not_pass:empty_registers")
  843. if role == "event_stream" and not payload.get("events"):
  844. normalized = "blocked" if normalized == "pass" else normalized
  845. failures.append(f"{role}_status_not_pass:empty_events")
  846. if role == "register_dump" and not payload.get("debug_registers"):
  847. normalized = "blocked" if normalized == "pass" else normalized
  848. failures.append(f"{role}_status_not_pass:empty_registers")
  849. if failures:
  850. return normalized, failures
  851. return "pass", []
  852. def _validate_real_bmc_j6_windows_safety_block(safety: Any) -> list[str]:
  853. failures: list[str] = []
  854. if not isinstance(safety, dict):
  855. return ["safety_not_object"]
  856. for field in REAL_BMC_J6_WINDOWS_REQUIRED_SAFETY_FALSE_FIELDS:
  857. if safety.get(field) is not False:
  858. failures.append(f"safety_flag:{field}")
  859. for key, value in safety.items():
  860. key_text = str(key)
  861. key_normalized = key_text.lower()
  862. if key_normalized in REAL_BMC_J6_ACTION_SAFETY_ALIASES and key_normalized not in {"open_com", "opened_com", "com_open"}:
  863. if value is not False and value not in (None, "", 0):
  864. failures.append(f"safety_flag:{key_text}")
  865. for marker in _forbidden_markers_in_text(key_text, REAL_BMC_J6_FORBIDDEN_ACTION_MARKERS):
  866. if value is not False and value not in (None, "", 0):
  867. failures.append(f"forbidden_action_marker:{marker}")
  868. return failures
  869. def _status_from_layer(layer: Any) -> str:
  870. if not isinstance(layer, dict):
  871. return "missing"
  872. status = str(layer.get("status") or "missing")
  873. if status == "pass":
  874. return "pass"
  875. if status.startswith("blocked_"):
  876. return "blocked"
  877. if status == "missing":
  878. return "missing"
  879. return "fail"
  880. def _status_from_artifact(result: dict[str, Any] | None) -> str:
  881. if not isinstance(result, dict):
  882. return "missing"
  883. status = str(result.get("status") or "missing")
  884. if status == "pass":
  885. return "pass"
  886. if status in {"missing", "not_provided"}:
  887. return "missing"
  888. if status in {"missing_hash", "hash_mismatch"}:
  889. return "fail"
  890. return status
  891. def _parse_j6sys_transcript(result: dict[str, Any] | None) -> tuple[list[dict[str, object]], list[str]]:
  892. if not isinstance(result, dict) or result.get("exists") is not True:
  893. return [], []
  894. path = Path(str(result.get("path") or ""))
  895. if not path.is_file():
  896. return [], []
  897. lines: list[dict[str, object]] = []
  898. try:
  899. for raw in path.read_text(encoding="utf-8-sig", errors="replace").splitlines():
  900. parsed = _parse_j6sys_line(raw.strip())
  901. if parsed is not None:
  902. lines.append(parsed)
  903. except OSError as exc:
  904. return [], [f"j6sys_transcript_unreadable:{exc.__class__.__name__}"]
  905. if not lines:
  906. return [], ["missing_j6sys_lines"]
  907. return lines, []
  908. def _j6sys_threshold_failures(parsed_lines: list[dict[str, object]]) -> tuple[dict[str, object] | None, list[str]]:
  909. if not parsed_lines:
  910. return None, ["missing_j6sys_lines"]
  911. last = parsed_lines[-1]
  912. failures: list[str] = []
  913. poll = int(last.get("poll", 0))
  914. expected_tx = 3 + (43 * poll)
  915. checks = [
  916. ("wake", int(last.get("wake", 0)) == 3, "j6sys_wake_not_3"),
  917. ("poll", poll >= 3, "j6sys_poll_lt_3"),
  918. ("tx", int(last.get("tx", 0)) >= expected_tx, "j6sys_tx_count_low"),
  919. ("rx", int(last.get("rx", 0)) > 0, "j6sys_no_bmc_rx"),
  920. ("uerr", int(last.get("uerr", 0)) == 0, "j6sys_uart_error"),
  921. ("tok", int(last.get("tok", 0)) > 0, "j6sys_no_tokens"),
  922. ("seq", int(last.get("seq", 0)) >= 3, "j6sys_seq_lt_3"),
  923. ("valid", int(last.get("valid", 0)) >= 3, "j6sys_valid_lt_3"),
  924. ("perr", int(last.get("perr", 0)) == 0, "j6sys_parser_error"),
  925. ("stale", int(last.get("stale", 0)) == 0, "j6sys_stale"),
  926. ("frame", int(last.get("frame", 0)) == 0, "j6sys_frame_error"),
  927. ("duovf", int(last.get("duovf", 0)) == 0, "j6sys_debug_uart_overflow"),
  928. ("dbg", int(last.get("dbg", 0)) > 0, "j6sys_debug_ping_not_seen"),
  929. ("derr", int(last.get("derr", 0)) == 0, "j6sys_debug_uart_error"),
  930. ]
  931. for _field, passed, failure in checks:
  932. if not passed:
  933. failures.append(failure)
  934. return last, failures
  935. J6RAW_RE = re.compile(
  936. r"J6RAW\s+cr=(?P<cr>[0-9A-Fa-f]{8})\s+rx=(?P<rx>[0-9A-Fa-f]{8})"
  937. r"\s+drop=(?P<drop>[0-9A-Fa-f]{8})\s+berr=(?P<berr>[0-9A-Fa-f]{8})"
  938. r"\s+derr=(?P<derr>[0-9A-Fa-f]{8})\s+last=(?P<last>[0-9A-Fa-f]{2})"
  939. r"\s+dbg=(?P<dbg>[0-9A-Fa-f]{8})"
  940. )
  941. J6RAW_FRAME_RE = re.compile(
  942. r"\bJ6RAW\s+seq=(?P<seq>[0-9A-Fa-f]{8})\s+off=(?P<off>[0-9A-Fa-f]{8})"
  943. r"\s+len=(?P<len>[0-9A-Fa-f]{2})\s+sum=(?P<sum>[0-9A-Fa-f]{4})"
  944. r"\s+data=(?P<data>[0-9A-Fa-f]*)\b"
  945. )
  946. J6RAW_FRAME_COMPACT_RE = re.compile(
  947. r"\bJ6RAW\s+s=(?P<seq>[0-9A-Fa-f]{1,8})\s+o=(?P<off>[0-9A-Fa-f]{8})"
  948. r"\s+l=(?P<len>[0-9A-Fa-f]{2})\s+u=(?P<sum>[0-9A-Fa-f]{4})"
  949. r"\s+d=(?P<data>[0-9A-Fa-f]*)\b"
  950. )
  951. LOSSLESS_HEX_FIELDS = {
  952. "seq",
  953. "cmd",
  954. "id",
  955. "i",
  956. "s",
  957. "v",
  958. "m",
  959. "tp",
  960. "t",
  961. "tx",
  962. "rx",
  963. "drop",
  964. "off",
  965. "raw_in",
  966. "ri",
  967. "raw_out",
  968. "ro",
  969. "raw_drop",
  970. "rd",
  971. "hd",
  972. "fifo",
  973. "fifo_max",
  974. "bmc_berr",
  975. "be",
  976. "host_err",
  977. "he",
  978. "e",
  979. "ty",
  980. "c",
  981. "p",
  982. "p0",
  983. "p23",
  984. "f0",
  985. "f3",
  986. "f5",
  987. "to",
  988. "ts",
  989. }
  990. LOSSLESS_STRING_FIELDS = {
  991. "st",
  992. "status",
  993. "src",
  994. "source",
  995. "pwm",
  996. "pwm_source",
  997. "pid",
  998. }
  999. def _parse_lossless_value(key: str, value: str) -> Any:
  1000. token = value.strip()
  1001. while token.endswith("\\r") or token.endswith("\\n"):
  1002. token = token[:-2]
  1003. if key in LOSSLESS_STRING_FIELDS:
  1004. return token
  1005. if key in LOSSLESS_HEX_FIELDS or token.lower().startswith("0x"):
  1006. try:
  1007. return int(token[2:] if token.lower().startswith("0x") else token, 16)
  1008. except ValueError:
  1009. return token
  1010. parsed = _parse_int_token(token)
  1011. return parsed if parsed is not None else token
  1012. def _normalized_transcript_lines(text: str) -> list[str]:
  1013. """Split real or escaped UART line delimiters without changing payload fields."""
  1014. normalized = text.replace("\\r\\n", "\n").replace("\\n", "\n").replace("\\r", "\n")
  1015. return normalized.splitlines()
  1016. def _parse_lossless_key_value_lines(text: str, prefix: str) -> list[dict[str, Any]]:
  1017. lines: list[dict[str, Any]] = []
  1018. pattern = re.compile(rf"\b{re.escape(prefix)}\b(?P<body>[^\r\n]*)")
  1019. for raw in _normalized_transcript_lines(text):
  1020. match = pattern.search(raw)
  1021. if not match:
  1022. continue
  1023. fields: dict[str, Any] = {}
  1024. for key, raw_value in re.findall(r"([A-Za-z0-9_]+)=([^ \t\r\n]+)", match.group("body")):
  1025. fields[key] = _parse_lossless_value(key, raw_value)
  1026. fields["raw"] = raw
  1027. if "host_report_drop" not in fields and "hd" in fields:
  1028. fields["host_report_drop"] = fields["hd"]
  1029. if "raw_in" not in fields and "ri" in fields:
  1030. fields["raw_in"] = fields["ri"]
  1031. if "raw_out" not in fields and "ro" in fields:
  1032. fields["raw_out"] = fields["ro"]
  1033. if "seq" not in fields and "s" in fields:
  1034. fields["seq"] = fields["s"]
  1035. if "id" not in fields and "i" in fields:
  1036. fields["id"] = fields["i"]
  1037. if "temp" not in fields and "tp" in fields:
  1038. fields["temp"] = fields["tp"]
  1039. if "temp" not in fields and "t" in fields:
  1040. fields["temp"] = fields["t"]
  1041. if "raw_drop" not in fields and "rd" in fields:
  1042. fields["raw_drop"] = fields["rd"]
  1043. if "bmc_berr" not in fields and "be" in fields:
  1044. fields["bmc_berr"] = fields["be"]
  1045. if "host_err" not in fields and "he" in fields:
  1046. fields["host_err"] = fields["he"]
  1047. if "err" not in fields and "e" in fields:
  1048. fields["err"] = fields["e"]
  1049. if "type" not in fields and "ty" in fields:
  1050. fields["type"] = fields["ty"]
  1051. if "ch" not in fields and "c" in fields:
  1052. fields["ch"] = fields["c"]
  1053. if "pct" not in fields and "p" in fields:
  1054. fields["pct"] = fields["p"]
  1055. if "status" not in fields and "st" in fields:
  1056. fields["status"] = fields["st"]
  1057. if "valid" not in fields and "v" in fields:
  1058. fields["valid"] = fields["v"]
  1059. if "missing" not in fields and "m" in fields:
  1060. fields["missing"] = fields["m"]
  1061. if "missing" not in fields and "miss" in fields:
  1062. fields["missing"] = fields["miss"]
  1063. if "requested" not in fields and "req" in fields:
  1064. fields["requested"] = fields["req"]
  1065. if "pid_requested" not in fields and "req" in fields:
  1066. fields["pid_requested"] = fields["req"]
  1067. if "active" not in fields and "act" in fields:
  1068. fields["active"] = fields["act"]
  1069. if "pid_active" not in fields and "act" in fields:
  1070. fields["pid_active"] = fields["act"]
  1071. if "source" not in fields and "src" in fields:
  1072. fields["source"] = fields["src"]
  1073. if "pwm_source" not in fields and "src" in fields:
  1074. fields["pwm_source"] = fields["src"]
  1075. if "ptc00" not in fields and "p0" in fields:
  1076. fields["ptc00"] = fields["p0"]
  1077. if "ptc23" not in fields and "p23" in fields:
  1078. fields["ptc23"] = fields["p23"]
  1079. if "fan00" not in fields and "f0" in fields:
  1080. fields["fan00"] = fields["f0"]
  1081. if "fan03" not in fields and "f3" in fields:
  1082. fields["fan03"] = fields["f3"]
  1083. if "fan05" not in fields and "f5" in fields:
  1084. fields["fan05"] = fields["f5"]
  1085. if "timeout" not in fields and "to" in fields:
  1086. fields["timeout"] = fields["to"]
  1087. if "timeout_s" not in fields and "ts" in fields:
  1088. fields["timeout_s"] = fields["ts"]
  1089. if "timeout" not in fields and "to" in fields:
  1090. fields["timeout"] = fields["to"]
  1091. if "timeout_s" not in fields and "ts" in fields:
  1092. fields["timeout_s"] = fields["ts"]
  1093. for alias_field in ("status", "source", "pwm_source"):
  1094. if alias_field in fields:
  1095. fields[alias_field] = _normalize_compact_alias_value(alias_field, fields[alias_field])
  1096. lines.append(fields)
  1097. return lines
  1098. def _host_sensor_row_fields(row: Any) -> dict[str, Any]:
  1099. if not isinstance(row, dict):
  1100. return {}
  1101. fields = row.get("fields") if isinstance(row.get("fields"), dict) else {}
  1102. merged: dict[str, Any] = dict(fields)
  1103. for key in ("seq", "s", "id", "i", "temp", "tp", "t", "missing", "miss", "status", "st", "raw", "fault"):
  1104. if key in row and key not in merged:
  1105. merged[key] = row[key]
  1106. if "seq" not in merged and "s" in merged:
  1107. merged["seq"] = merged["s"]
  1108. if "id" not in merged and "i" in merged:
  1109. raw_i = _raw_field_token(row.get("raw"), "i")
  1110. merged["id"] = _safe_fixed_hex_int(raw_i if raw_i is not None else merged["i"], default=merged["i"])
  1111. elif "id" in merged:
  1112. raw_id = _raw_field_token(row.get("raw"), "id")
  1113. normalized_id = _safe_fixed_hex_int(raw_id if raw_id is not None else merged["id"], default=None)
  1114. if normalized_id is not None:
  1115. merged["id"] = normalized_id
  1116. if "temp" not in merged and "tp" in merged:
  1117. merged["temp"] = merged["tp"]
  1118. if "temp" not in merged and "t" in merged:
  1119. merged["temp"] = merged["t"]
  1120. if "missing" not in merged and "miss" in merged:
  1121. merged["missing"] = merged["miss"]
  1122. if "status" not in merged and "st" in merged:
  1123. merged["status"] = merged["st"]
  1124. if "status" in merged:
  1125. merged["status"] = _normalize_compact_alias_value("status", merged["status"])
  1126. return merged
  1127. def _host_sensor_row_missing(row: Any) -> bool:
  1128. fields = _host_sensor_row_fields(row)
  1129. missing = _safe_int(fields.get("missing"), default=None)
  1130. if missing is not None:
  1131. return missing == 1
  1132. return str(fields.get("status") or "").lower() in {"missing", "no_reading", "na", "disabled"}
  1133. def _parse_j6raw_frames(text: str) -> list[dict[str, Any]]:
  1134. frames: list[dict[str, Any]] = []
  1135. for line_index, raw in enumerate(_normalized_transcript_lines(text)):
  1136. match = J6RAW_FRAME_RE.search(raw) or J6RAW_FRAME_COMPACT_RE.search(raw)
  1137. if not match:
  1138. continue
  1139. data_hex = match.group("data")
  1140. frames.append(
  1141. {
  1142. "kind": "j6raw_frame",
  1143. "raw": raw,
  1144. "line_index": line_index,
  1145. "seq": int(match.group("seq"), 16),
  1146. "off": int(match.group("off"), 16),
  1147. "len": int(match.group("len"), 16),
  1148. "sum": int(match.group("sum"), 16),
  1149. "data_hex": data_hex,
  1150. }
  1151. )
  1152. return frames
  1153. def _post_j6ready_j6raw_frames(text: str, frames: list[dict[str, Any]]) -> list[dict[str, Any]]:
  1154. lines = _normalized_transcript_lines(text)
  1155. j6ready_index = next(
  1156. (index for index, raw in enumerate(lines) if raw.startswith("J6READY")),
  1157. None,
  1158. )
  1159. if j6ready_index is None:
  1160. return frames
  1161. filtered = [frame for frame in frames if int(frame.get("line_index", -1)) > j6ready_index]
  1162. return filtered or frames
  1163. def _validate_j6raw_replay(
  1164. frames: list[dict[str, Any]],
  1165. *,
  1166. last_stat: dict[str, Any] | None,
  1167. replay_result: dict[str, Any] | None,
  1168. ) -> tuple[dict[str, Any], list[str]]:
  1169. failures: list[str] = []
  1170. replay = bytearray()
  1171. first_seq = int(frames[0].get("seq") or 0) if frames else 0
  1172. first_off = int(frames[0].get("off") or 0) if frames else 0
  1173. expected_seq = first_seq
  1174. expected_off = first_off
  1175. if not frames:
  1176. failures.append("missing_j6raw_frames")
  1177. for frame in frames:
  1178. seq = int(frame.get("seq") or 0)
  1179. off = int(frame.get("off") or 0)
  1180. length = int(frame.get("len") or 0)
  1181. checksum = int(frame.get("sum") or 0)
  1182. data_hex = str(frame.get("data_hex") or "")
  1183. if seq != expected_seq:
  1184. failures.append("raw_frame_seq_gap")
  1185. if off != expected_off:
  1186. failures.append("raw_frame_offset_gap")
  1187. if len(data_hex) != length * 2:
  1188. failures.append(f"raw_frame_len_mismatch:{seq}")
  1189. data = b""
  1190. else:
  1191. try:
  1192. data = bytes.fromhex(data_hex)
  1193. except ValueError:
  1194. data = b""
  1195. failures.append(f"raw_frame_hex_malformed:{seq}")
  1196. if len(data) != length:
  1197. failures.append(f"raw_frame_data_len_mismatch:{seq}")
  1198. if (sum(data) & 0xFFFF) != checksum:
  1199. failures.append(f"raw_frame_checksum_mismatch:{seq}")
  1200. replay.extend(data)
  1201. expected_seq = seq + 1
  1202. expected_off = off + length
  1203. raw_in = _safe_int((last_stat or {}).get("raw_in"), default=None)
  1204. raw_out = _safe_int((last_stat or {}).get("raw_out"), default=None)
  1205. raw_drop = _safe_int((last_stat or {}).get("raw_drop"), default=None)
  1206. bmc_berr = _safe_int((last_stat or {}).get("bmc_berr"), default=0) or 0
  1207. host_err = _safe_int((last_stat or {}).get("host_err"), default=0) or 0
  1208. if last_stat is None:
  1209. failures.append("missing_j6stat_lines")
  1210. else:
  1211. if raw_drop not in (0, None):
  1212. failures.append("raw_drop_nonzero")
  1213. if bmc_berr:
  1214. failures.append("bmc_uart_error_nonzero")
  1215. if host_err:
  1216. failures.append("host_uart_error_nonzero")
  1217. expected_replay_len = len(replay) + first_off
  1218. if raw_in is not None and raw_in != expected_replay_len:
  1219. failures.append("raw_in_replay_len_mismatch")
  1220. if raw_out is not None and raw_out != expected_replay_len:
  1221. failures.append("raw_out_replay_len_mismatch")
  1222. replay_artifact_status = "not_provided"
  1223. replay_artifact_sha256 = hashlib.sha256(bytes(replay)).hexdigest()
  1224. if isinstance(replay_result, dict) and replay_result.get("exists") is True:
  1225. replay_path = Path(str(replay_result.get("path") or ""))
  1226. try:
  1227. artifact_bytes = replay_path.read_bytes()
  1228. replay_artifact_status = "pass"
  1229. if artifact_bytes != bytes(replay):
  1230. failures.append("raw_replay_artifact_mismatch")
  1231. replay_artifact_status = "mismatch"
  1232. except OSError as exc:
  1233. replay_artifact_status = f"unreadable:{exc.__class__.__name__}"
  1234. failures.append("raw_replay_artifact_unreadable")
  1235. else:
  1236. failures.append("missing_raw_replay_artifact")
  1237. status = "pass" if not failures else "fail"
  1238. return (
  1239. {
  1240. "status": status,
  1241. "frames": len(frames),
  1242. "bytes": len(replay),
  1243. "first_seq": first_seq,
  1244. "first_off": first_off,
  1245. "baseline_bytes": first_off,
  1246. "sha256": replay_artifact_sha256,
  1247. "artifact_status": replay_artifact_status,
  1248. "raw_in": raw_in,
  1249. "raw_out": raw_out,
  1250. "raw_drop": raw_drop,
  1251. },
  1252. failures,
  1253. )
  1254. def _parse_j6raw_text(text: str) -> list[dict[str, object]]:
  1255. lines: list[dict[str, object]] = []
  1256. for raw in text.splitlines():
  1257. match = J6RAW_RE.search(raw)
  1258. if match:
  1259. lines.append(
  1260. {
  1261. "kind": "j6raw",
  1262. "raw": raw,
  1263. "cr": int(match.group("cr"), 16),
  1264. "rx": int(match.group("rx"), 16),
  1265. "drop": int(match.group("drop"), 16),
  1266. "berr": int(match.group("berr"), 16),
  1267. "derr": int(match.group("derr"), 16),
  1268. "last": int(match.group("last"), 16),
  1269. "dbg": int(match.group("dbg"), 16),
  1270. }
  1271. )
  1272. return lines
  1273. def _read_artifact_text(result: dict[str, Any] | None) -> str:
  1274. if not isinstance(result, dict) or result.get("exists") is not True:
  1275. return ""
  1276. path = Path(str(result.get("path") or ""))
  1277. if not path.is_file():
  1278. return ""
  1279. try:
  1280. data = path.read_bytes()
  1281. except OSError:
  1282. return ""
  1283. return data.decode("utf-8-sig", errors="replace")
  1284. def _artifact_size(result: dict[str, Any] | None) -> int | None:
  1285. if not isinstance(result, dict) or result.get("exists") is not True:
  1286. return None
  1287. path = Path(str(result.get("path") or ""))
  1288. try:
  1289. return path.stat().st_size
  1290. except OSError:
  1291. return None
  1292. def _classify_j6raw_text(text: str, last_j6raw: dict[str, object] | None) -> str:
  1293. lower = text.lower()
  1294. if last_j6raw is not None:
  1295. if int(last_j6raw.get("berr", 0)) > 0 or int(last_j6raw.get("derr", 0)) > 0:
  1296. return "garbled_or_wrong_baud_suspected"
  1297. if int(last_j6raw.get("drop", 0)) > 0:
  1298. return "raw_debug_overflow"
  1299. if int(last_j6raw.get("rx", 0)) <= 0 and not text.strip():
  1300. return "no_bmc_return"
  1301. if re.search(r"login:|password:", lower):
  1302. return "login_or_password_prompt"
  1303. if re.search(r"(^|[\r\n])[^ \r\n].*(#|\$)\s*($|[\r\n])", lower) or re.search(r"root@|admin@|bmc.*[#\$]", lower):
  1304. return "shell_prompt"
  1305. if re.search(r"boot|linux|kernel|uboot|u-boot|init|systemd", lower):
  1306. return "boot_log"
  1307. if re.search(r"not found|permission denied|command not found|usage:|error", lower):
  1308. return "command_or_shell_error"
  1309. if re.search(r"\\x(00|01|02|03|04|05|06|07|08|0b|0c|0e|0f|1[0-9a-f]|7f)", lower):
  1310. return "garbled_or_wrong_baud_suspected"
  1311. if not text.strip():
  1312. return "no_bmc_return"
  1313. return "unclassified_text"
  1314. J6SENS_RE = re.compile(
  1315. r"J6SENS\s+cmd=(?P<cmd>[0-9A-Fa-f]{8})\s+tx=(?P<tx>[0-9A-Fa-f]{8})"
  1316. r"\s+rx=(?P<rx>[0-9A-Fa-f]{8})\s+drop=(?P<drop>[0-9A-Fa-f]{8})"
  1317. r"\s+berr=(?P<berr>[0-9A-Fa-f]{8})\s+derr=(?P<derr>[0-9A-Fa-f]{8})"
  1318. r"\s+phase=(?P<phase>[0-9A-Fa-f]{8})"
  1319. )
  1320. J6CMD_RE = re.compile(
  1321. r"J6CMD\s+seq=(?P<seq>[0-9A-Fa-f]{8})\s+idx=(?P<index>[0-9A-Fa-f]{2})"
  1322. r"\s+name=(?P<name>[A-Za-z0-9_]+)\s+text=(?P<text>[^\r\n]*)"
  1323. )
  1324. HEX48_RE = re.compile(r"(?i)(^|[^0-9a-f])((?:[0-9a-f]{2}\s+){47}[0-9a-f]{2})([^0-9a-f]|$)")
  1325. def _parse_j6sens_text(text: str) -> list[dict[str, object]]:
  1326. lines: list[dict[str, object]] = []
  1327. for raw in text.splitlines():
  1328. match = J6SENS_RE.search(raw)
  1329. if match:
  1330. lines.append(
  1331. {
  1332. "kind": "j6sens",
  1333. "raw": raw,
  1334. "cmd": int(match.group("cmd"), 16),
  1335. "tx": int(match.group("tx"), 16),
  1336. "rx": int(match.group("rx"), 16),
  1337. "drop": int(match.group("drop"), 16),
  1338. "berr": int(match.group("berr"), 16),
  1339. "derr": int(match.group("derr"), 16),
  1340. "phase": int(match.group("phase"), 16),
  1341. }
  1342. )
  1343. return lines
  1344. def _parse_int_token(value: Any) -> int | None:
  1345. if isinstance(value, bool):
  1346. return int(value)
  1347. if isinstance(value, int):
  1348. return value
  1349. if isinstance(value, float):
  1350. return int(value)
  1351. if not isinstance(value, str):
  1352. return None
  1353. token = value.strip()
  1354. if not token:
  1355. return None
  1356. try:
  1357. if token.lower().startswith("0x"):
  1358. return int(token[2:], 16)
  1359. if re.search(r"[A-Fa-f]", token):
  1360. return int(token, 16)
  1361. return int(token, 10)
  1362. except ValueError:
  1363. return None
  1364. def _parse_key_value_status_lines(text: str, prefix: str) -> list[dict[str, Any]]:
  1365. lines: list[dict[str, Any]] = []
  1366. pattern = re.compile(rf"\b{re.escape(prefix)}\b(?P<body>[^\r\n]*)")
  1367. for raw in text.splitlines():
  1368. match = pattern.search(raw)
  1369. if not match:
  1370. continue
  1371. fields: dict[str, Any] = {}
  1372. for key, raw_value in re.findall(r"([A-Za-z0-9_]+)=([A-Za-z0-9_]+)", match.group("body")):
  1373. parsed = _parse_int_token(raw_value)
  1374. fields[key] = parsed if parsed is not None else raw_value
  1375. fields["raw"] = raw
  1376. lines.append(fields)
  1377. return lines
  1378. def _merge_status_events(text_events: list[dict[str, Any]], stream_events: list[dict[str, Any]], kind: str) -> list[dict[str, Any]]:
  1379. merged: list[dict[str, Any]] = []
  1380. seen: set[str] = set()
  1381. for event in text_events:
  1382. raw = str(event.get("raw") or "")
  1383. key = f"text:{raw}"
  1384. if key in seen:
  1385. continue
  1386. seen.add(key)
  1387. event = dict(event)
  1388. event["kind"] = kind
  1389. merged.append(event)
  1390. for event in stream_events:
  1391. if str(event.get("kind") or "") != kind:
  1392. continue
  1393. raw = str(event.get("raw") or "")
  1394. key = f"stream:{raw}:{json.dumps(event, sort_keys=True, default=str)}"
  1395. if raw and any(str(item.get("raw") or "") == raw for item in merged):
  1396. continue
  1397. if key in seen:
  1398. continue
  1399. seen.add(key)
  1400. merged.append(event)
  1401. return merged
  1402. def _parse_modtrace_flags(modtrace: dict[str, Any] | None) -> dict[str, bool]:
  1403. raw = str((modtrace or {}).get("raw") or "")
  1404. lower = raw.lower()
  1405. return {
  1406. "pid_disabled": "pid=disabled" in lower,
  1407. "bmc_observe_only": "bmc=observe_only" in lower,
  1408. "host_slave": "host=slave" in lower,
  1409. "pwm_host_manual": "pwm=host_manual" in lower,
  1410. "timeout_s_5": "timeout_s=5" in lower,
  1411. }
  1412. def _host_sensor_real_fan_ptc_allowed_command(command: str) -> bool:
  1413. return REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_COMMAND_RE.match(command.strip()) is not None
  1414. def _parse_host_sensor_report_text(text: str) -> dict[str, Any]:
  1415. samples: dict[int, dict[str, Any]] = {}
  1416. pwm_events: list[dict[str, Any]] = []
  1417. pid_events: list[dict[str, Any]] = []
  1418. stat_events: list[dict[str, Any]] = []
  1419. current_seq = 0
  1420. for raw in _normalized_transcript_lines(text):
  1421. line = raw.strip()
  1422. if not line:
  1423. continue
  1424. if line.startswith("SENS "):
  1425. fields = _parse_lossless_key_value_lines(line, "SENS")
  1426. parsed = fields[0] if fields else {"raw": line}
  1427. seq = _safe_int(parsed.get("seq"), default=0) or 0
  1428. current_seq = seq
  1429. sample = samples.setdefault(seq, {"seq": seq, "summary": {}, "dimm_rows": []})
  1430. sample["summary"] = parsed
  1431. elif line.startswith("DIMM "):
  1432. fields = _parse_lossless_key_value_lines(line, "DIMM")
  1433. parsed = fields[0] if fields else {"raw": line}
  1434. seq = _safe_int(parsed.get("seq"), default=None)
  1435. if seq is None:
  1436. seq = current_seq
  1437. parsed["seq"] = seq
  1438. sample = samples.setdefault(seq, {"seq": seq, "summary": {}, "dimm_rows": []})
  1439. sample["dimm_rows"].append(parsed)
  1440. elif line.startswith("PWM "):
  1441. pwm_events.extend(_parse_lossless_key_value_lines(line, "PWM"))
  1442. elif line.startswith("PID "):
  1443. pid_events.extend(_parse_lossless_key_value_lines(line, "PID"))
  1444. elif line.startswith("STAT "):
  1445. stat_events.extend(_parse_lossless_key_value_lines(line, "STAT"))
  1446. ordered = [samples[key] for key in sorted(samples)]
  1447. all_ff_samples: list[int] = []
  1448. for sample in ordered:
  1449. summary = sample.get("summary") if isinstance(sample.get("summary"), dict) else {}
  1450. if str(summary.get("status") or "").lower() in {"all_ff", "all_raw_ff"}:
  1451. all_ff_samples.append(_safe_int(sample.get("seq"), default=0) or 0)
  1452. return {
  1453. "samples": ordered,
  1454. "sample_count": len(ordered),
  1455. "dimm_rows_per_sample": [len(sample.get("dimm_rows") or []) for sample in ordered],
  1456. "all_ff_samples": all_ff_samples,
  1457. "pwm_events": pwm_events,
  1458. "pid_events": pid_events,
  1459. "stat_events": stat_events,
  1460. }
  1461. def _read_json_artifact(result: dict[str, Any] | None, role: str) -> tuple[dict[str, Any], list[str]]:
  1462. if not isinstance(result, dict) or result.get("exists") is not True:
  1463. return {}, []
  1464. path = Path(str(result.get("path") or ""))
  1465. try:
  1466. payload = read_json(path)
  1467. except Exception as exc: # noqa: BLE001 - validation reports malformed sidecars as receipt failures.
  1468. return {}, [f"{role}_unreadable:{exc.__class__.__name__}"]
  1469. return (payload if isinstance(payload, dict) else {}), []
  1470. def _validate_layer_statuses(
  1471. *,
  1472. layers: dict[str, Any],
  1473. required_layers: list[str],
  1474. allowed_layers: set[str],
  1475. ) -> list[str]:
  1476. failures: list[str] = []
  1477. for layer in required_layers:
  1478. item = layers.get(layer)
  1479. if item is not None and not isinstance(item, dict):
  1480. failures.append(f"layer_not_object:{layer}")
  1481. item = {}
  1482. status_value = str((item or {}).get("status") or "missing")
  1483. if status_value == "missing":
  1484. failures.append(f"missing_layer:{layer}")
  1485. elif status_value.startswith("blocked_"):
  1486. failures.append(f"blocked_layer:{layer}")
  1487. elif status_value != "pass":
  1488. failures.append(f"fail_layer:{layer}:{status_value}")
  1489. for layer in sorted(set(layers) - allowed_layers):
  1490. failures.append(f"undeclared_layer:{layer}")
  1491. return failures
  1492. def validate_real_bmc_j6_windows_gate_v2_receipt(receipt: dict[str, Any] | Path | str, *, strict: bool = False) -> dict[str, Any]:
  1493. receipt_path: Path | None = None
  1494. if isinstance(receipt, dict):
  1495. payload = receipt
  1496. else:
  1497. receipt_path = Path(receipt)
  1498. payload = read_json(receipt_path)
  1499. failures: list[str] = []
  1500. warnings: list[str] = []
  1501. schema_ok = payload.get("schema") == "real-bmc-j6-windows-gate-v2-receipt-v1"
  1502. if not schema_ok:
  1503. failures.append("fail_schema")
  1504. failures.extend(_validate_json_schema_file(payload, "real_bmc_j6_windows_gate_v2_receipt.schema.json", required=False))
  1505. top_status = str(payload.get("status") or "missing")
  1506. if top_status != "pass":
  1507. failures.append(f"top_status_not_pass:{top_status}")
  1508. if payload.get("counterparty") != "real_bmc":
  1509. failures.append("counterparty_not_real_bmc")
  1510. layers = payload.get("layers") or {}
  1511. if not isinstance(layers, dict):
  1512. failures.append("layers_not_object")
  1513. layers = {}
  1514. failures.extend(
  1515. _validate_layer_statuses(
  1516. layers=layers,
  1517. required_layers=REAL_BMC_J6_WINDOWS_REQUIRED_LAYERS,
  1518. allowed_layers=REAL_BMC_J6_WINDOWS_ALLOWED_LAYER_SET,
  1519. )
  1520. )
  1521. programming = payload.get("programming") or {}
  1522. if not isinstance(programming, dict):
  1523. programming = {}
  1524. failures.append("programming_not_object")
  1525. if programming.get("mode") != "PROGRAM_SRAM":
  1526. failures.append("programming_not_sram")
  1527. if programming.get("manual_programming") is not True:
  1528. failures.append("manual_programming_not_true")
  1529. bitstream_result = None
  1530. if receipt_path is not None:
  1531. bitstream_result = _hash_validation(receipt_path, programming.get("bitstream"), required=True)
  1532. if bitstream_result["status"] in {"missing", "hash_mismatch"}:
  1533. failures.append(f"bitstream_{bitstream_result['status']}")
  1534. elif strict and bitstream_result["status"] == "missing_hash":
  1535. failures.append("missing_bitstream_hash")
  1536. bitstream_sha256 = _artifact_hash_from_result(bitstream_result)
  1537. pin_profile = payload.get("pin_profile") or {}
  1538. if not isinstance(pin_profile, dict):
  1539. pin_profile = {}
  1540. failures.append("pin_profile_not_object")
  1541. profile_name = str(pin_profile.get("name") or "")
  1542. expected_profile = REAL_BMC_J6_WINDOWS_ALLOWED_PIN_PROFILES.get(profile_name)
  1543. if expected_profile is None:
  1544. failures.append("pin_profile_invalid")
  1545. else:
  1546. if pin_profile.get("connector") != "J6":
  1547. failures.append("pin_profile_connector_not_j6")
  1548. for field, expected in expected_profile.items():
  1549. if pin_profile.get(field) != expected:
  1550. failures.append(f"pin_profile_{field}_mismatch")
  1551. td_layer = layers.get("td_bitstream") if isinstance(layers.get("td_bitstream"), dict) else {}
  1552. manual_layer = layers.get("manual_sram_programming") if isinstance(layers.get("manual_sram_programming"), dict) else {}
  1553. capture_layer = layers.get("windows_serial_capture") if isinstance(layers.get("windows_serial_capture"), dict) else {}
  1554. protocol_layer = layers.get("real_bmc_protocol") if isinstance(layers.get("real_bmc_protocol"), dict) else {}
  1555. safety_contract = layers.get("safety_contract") if isinstance(layers.get("safety_contract"), dict) else {}
  1556. artifact_layer = layers.get("artifact_hashes") if isinstance(layers.get("artifact_hashes"), dict) else {}
  1557. td_result, current_failures = _validate_real_bmc_artifact(receipt_path, td_layer, "receipt", "td_receipt")
  1558. failures.extend(current_failures)
  1559. td_sha256 = _artifact_hash_from_result(td_result)
  1560. if isinstance(td_result, dict) and td_result.get("exists"):
  1561. try:
  1562. td_payload = read_json(td_result["path"])
  1563. except Exception as exc: # noqa: BLE001
  1564. failures.append(f"td_receipt_unreadable:{exc.__class__.__name__}")
  1565. td_payload = {}
  1566. if isinstance(td_payload, dict):
  1567. if str(td_payload.get("status") or "missing") != "pass":
  1568. failures.append(f"td_bitstream_receipt_not_pass:{td_payload.get('status', 'missing')}")
  1569. if td_payload.get("mode") != "implementation":
  1570. failures.append("td_bitstream_not_implementation")
  1571. if td_payload.get("top_module") != "uart_rs232_j6_system_debug_top":
  1572. failures.append("td_bitstream_wrong_top_module")
  1573. td_profile = str(td_payload.get("pin_profile") or "")
  1574. if profile_name and td_profile and td_profile != profile_name:
  1575. failures.append("td_bitstream_pin_profile_mismatch")
  1576. td_bitstream = td_payload.get("bitstream") if isinstance(td_payload.get("bitstream"), dict) else {}
  1577. td_bitstream_sha256 = str(td_bitstream.get("sha256") or "")
  1578. if not td_bitstream_sha256:
  1579. failures.append("td_bitstream_missing_hash")
  1580. elif bitstream_sha256 and td_bitstream_sha256.lower() != bitstream_sha256.lower():
  1581. failures.append("td_bitstream_hash_mismatch")
  1582. if manual_layer.get("mode") != "PROGRAM_SRAM":
  1583. failures.append("manual_sram_mode_not_program_sram")
  1584. if manual_layer.get("manual_programming") is not True:
  1585. failures.append("manual_sram_manual_programming_not_true")
  1586. if not manual_layer.get("operator"):
  1587. failures.append("manual_sram_missing_operator")
  1588. if not manual_layer.get("programmed_at"):
  1589. failures.append("manual_sram_missing_programmed_at")
  1590. attestation_result, current_failures = _validate_real_bmc_artifact(
  1591. receipt_path,
  1592. manual_layer,
  1593. "attestation",
  1594. "manual_sram_attestation",
  1595. )
  1596. failures.extend(current_failures)
  1597. attestation_sha256 = _artifact_hash_from_result(attestation_result)
  1598. if isinstance(attestation_result, dict) and attestation_result.get("exists"):
  1599. try:
  1600. attestation_payload = read_json(attestation_result["path"])
  1601. except Exception as exc: # noqa: BLE001
  1602. failures.append(f"manual_sram_attestation_unreadable:{exc.__class__.__name__}")
  1603. attestation_payload = {}
  1604. if isinstance(attestation_payload, dict):
  1605. if str(attestation_payload.get("status") or "missing") != "pass":
  1606. failures.append(f"manual_sram_attestation_not_pass:{attestation_payload.get('status', 'missing')}")
  1607. if attestation_payload.get("mode") != "PROGRAM_SRAM":
  1608. failures.append("manual_sram_attestation_wrong_mode")
  1609. attested_bitstream_sha256 = str(attestation_payload.get("bitstream_sha256") or "")
  1610. if not attested_bitstream_sha256:
  1611. failures.append("manual_sram_attestation_missing_bitstream_hash")
  1612. elif bitstream_sha256 and attested_bitstream_sha256.lower() != bitstream_sha256.lower():
  1613. failures.append("manual_sram_attestation_bitstream_hash_mismatch")
  1614. attested_td_receipt_sha256 = str(attestation_payload.get("td_receipt_sha256") or "")
  1615. if not attested_td_receipt_sha256:
  1616. failures.append("manual_sram_attestation_missing_td_receipt_hash")
  1617. elif td_sha256 and attested_td_receipt_sha256.lower() != td_sha256.lower():
  1618. failures.append("manual_sram_attestation_td_receipt_hash_mismatch")
  1619. if int(capture_layer.get("baud") or 0) != 115200:
  1620. failures.append("serial_baud_not_115200")
  1621. if str(capture_layer.get("format") or "").upper() != "8N1":
  1622. failures.append("serial_format_not_8n1")
  1623. if _safe_int(capture_layer.get("duration_s"), default=0) < 90:
  1624. failures.append("capture_duration_lt_90")
  1625. transcript_result, current_failures = _validate_real_bmc_artifact(receipt_path, capture_layer, "transcript", "transcript")
  1626. failures.extend(current_failures)
  1627. event_stream_result, current_failures = _validate_real_bmc_artifact(receipt_path, capture_layer, "event_stream", "event_stream")
  1628. failures.extend(current_failures)
  1629. register_dump_result, current_failures = _validate_real_bmc_artifact(receipt_path, capture_layer, "register_dump", "register_dump")
  1630. failures.extend(current_failures)
  1631. transcript_sha256 = _artifact_hash_from_result(transcript_result)
  1632. event_stream_sha256 = _artifact_hash_from_result(event_stream_result)
  1633. register_dump_sha256 = _artifact_hash_from_result(register_dump_result)
  1634. event_stream_content_status, current_failures = _real_bmc_artifact_content_status(event_stream_result, "event_stream")
  1635. failures.extend(current_failures)
  1636. register_dump_content_status, current_failures = _real_bmc_artifact_content_status(register_dump_result, "register_dump")
  1637. failures.extend(current_failures)
  1638. for role, artifact_result in [
  1639. ("td_receipt", td_result),
  1640. ("manual_sram_attestation", attestation_result),
  1641. ("transcript", transcript_result),
  1642. ("event_stream", event_stream_result),
  1643. ("register_dump", register_dump_result),
  1644. ]:
  1645. if isinstance(artifact_result, dict) and artifact_result.get("exists") is True:
  1646. path = Path(str(artifact_result.get("path") or ""))
  1647. try:
  1648. data = path.read_bytes()
  1649. if b"\x00" not in data[:4096]:
  1650. text = data.decode("utf-8-sig", errors="ignore")
  1651. for marker in _forbidden_markers_in_text(text, REAL_BMC_J6_WINDOWS_FORBIDDEN_ACTION_MARKERS):
  1652. failures.append(f"forbidden_action_marker:{marker}")
  1653. failures.append(f"artifact_forbidden_action_marker:{role}:{marker}")
  1654. except OSError as exc:
  1655. failures.append(f"artifact_scan_unreadable:{role}:{exc.__class__.__name__}")
  1656. parsed_j6sys, current_failures = _parse_j6sys_transcript(transcript_result)
  1657. failures.extend(current_failures)
  1658. last_j6sys, current_failures = _j6sys_threshold_failures(parsed_j6sys)
  1659. failures.extend(current_failures)
  1660. if last_j6sys is not None:
  1661. protocol_valid = _safe_int(protocol_layer.get("valid_frame_count"), default=-1)
  1662. if protocol_valid != _safe_int(last_j6sys.get("valid"), default=-2):
  1663. failures.append("protocol_j6sys_valid_mismatch")
  1664. if str(protocol_layer.get("source_id") or "") != "BMC_UART_TEXT":
  1665. failures.append("source_id_not_bmc_uart_text")
  1666. if safety_contract.get("ptc_fan_pins_exported") is not False:
  1667. failures.append("ptc_fan_pins_exported")
  1668. if safety_contract.get("real_actuator_action_attempted") is not False:
  1669. failures.append("real_actuator_action_attempted")
  1670. expected_artifact_hashes = {
  1671. "bitstream_sha256": bitstream_sha256,
  1672. "td_receipt_sha256": td_sha256,
  1673. "manual_sram_attestation_sha256": attestation_sha256,
  1674. "transcript_sha256": transcript_sha256,
  1675. "event_stream_sha256": event_stream_sha256,
  1676. "register_dump_sha256": register_dump_sha256,
  1677. }
  1678. for key, actual in expected_artifact_hashes.items():
  1679. recorded = str(artifact_layer.get(key) or "")
  1680. if not recorded:
  1681. failures.append(f"missing_artifact_hash:{key}")
  1682. elif actual and recorded.lower() != actual.lower():
  1683. failures.append(f"artifact_hash_mismatch:{key}")
  1684. failures.extend(_validate_real_bmc_j6_windows_safety_block(payload.get("safety") or {}))
  1685. for marker in _forbidden_action_markers_in_keys_and_values(payload, REAL_BMC_J6_WINDOWS_FORBIDDEN_ACTION_MARKERS):
  1686. failures.append(f"forbidden_action_marker:{marker}")
  1687. if strict:
  1688. authority = str(payload.get("authority_boundary") or "").lower()
  1689. if "thermal performance pass" in authority or "thermal_performance_pass" in authority:
  1690. failures.append("authority_overclaim_thermal_performance")
  1691. if "flash pass" in authority or "program_flash pass" in authority:
  1692. failures.append("authority_overclaim_flash")
  1693. failure_set = set(failures)
  1694. if (
  1695. "programming_not_sram" in failure_set
  1696. or any(item.startswith("forbidden_action_marker:") for item in failure_set)
  1697. or any(item.startswith("artifact_forbidden_action_marker:") for item in failure_set)
  1698. or (schema_ok and any(item.startswith("safety_flag:") for item in failure_set))
  1699. ):
  1700. final_status = "fail_forbidden_action"
  1701. elif top_status.startswith("blocked_"):
  1702. final_status = top_status
  1703. elif any(item.startswith("blocked_layer:") for item in failure_set):
  1704. final_status = "blocked"
  1705. elif failures:
  1706. final_status = "fail"
  1707. else:
  1708. final_status = "pass"
  1709. return {
  1710. "schema": "real-bmc-j6-windows-gate-v2-validation-v1",
  1711. "generated_at": utc_now(),
  1712. "status": final_status,
  1713. "strict": strict,
  1714. "receipt": str(receipt_path) if receipt_path is not None else None,
  1715. "receipt_status": top_status,
  1716. "last_j6sys": last_j6sys,
  1717. "j6sys_line_count": len(parsed_j6sys),
  1718. "transcript": transcript_result,
  1719. "event_stream": event_stream_result,
  1720. "register_dump": register_dump_result,
  1721. "bitstream": bitstream_result,
  1722. "failures": sorted(failure_set),
  1723. "warnings": sorted(set(warnings)),
  1724. "required_layers": REAL_BMC_J6_WINDOWS_REQUIRED_LAYERS,
  1725. "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.",
  1726. }
  1727. def _validate_host_sensor_debug921_common(
  1728. receipt: dict[str, Any] | Path | str,
  1729. *,
  1730. strict: bool = False,
  1731. schema_name: str,
  1732. schema_file: str,
  1733. diagnostic_scope: str,
  1734. required_layers: list[str],
  1735. allowed_layers: set[str],
  1736. allowed_top_module: str,
  1737. expected_commands: list[str],
  1738. expected_ack_cmds: dict[str, str],
  1739. allowed_command,
  1740. expected_fan_count: int,
  1741. validation_schema: str,
  1742. authority_boundary: str,
  1743. allowed_top_statuses: set[str] | None = None,
  1744. ignored_layer_status_failures: set[str] | None = None,
  1745. host_sensor_report_schemas: set[str] | None = None,
  1746. debug_frame_stream_schemas: set[str] | None = None,
  1747. allowed_pin_profiles: dict[str, dict[str, str]] | None = None,
  1748. allowed_top_modules_by_pin_profile: dict[str, str] | None = None,
  1749. required_safety_false_fields: list[str] | None = None,
  1750. forbidden_action_markers: list[str] | None = None,
  1751. td_top_failure_name: str = "td_bitstream_not_host_sensor_top",
  1752. ) -> dict[str, Any]:
  1753. receipt_path: Path | None = None
  1754. if isinstance(receipt, dict):
  1755. payload = receipt
  1756. else:
  1757. receipt_path = Path(receipt)
  1758. payload = read_json(receipt_path)
  1759. failures: list[str] = []
  1760. warnings: list[str] = []
  1761. allowed_top_statuses = allowed_top_statuses or set()
  1762. ignored_layer_status_failures = ignored_layer_status_failures or set()
  1763. host_sensor_report_schemas = host_sensor_report_schemas or {"j6-host-sensor-pwm-host-sensor-report-v1"}
  1764. debug_frame_stream_schemas = debug_frame_stream_schemas or {"j6-host-sensor-pwm-debug-frame-stream-v1"}
  1765. allowed_pin_profiles = allowed_pin_profiles or {}
  1766. allowed_top_modules_by_pin_profile = allowed_top_modules_by_pin_profile or {}
  1767. required_safety_false_fields = required_safety_false_fields or REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_REQUIRED_SAFETY_FALSE_FIELDS
  1768. forbidden_action_markers = forbidden_action_markers or REAL_BMC_J6_WINDOWS_FORBIDDEN_ACTION_MARKERS
  1769. if payload.get("schema") != schema_name:
  1770. failures.append("fail_schema")
  1771. failures.extend(_validate_json_schema_file(payload, schema_file, required=False))
  1772. top_status = str(payload.get("status") or "missing")
  1773. if top_status not in allowed_top_statuses and top_status != "pass" and not top_status.startswith("blocked_"):
  1774. failures.append(f"top_status_not_pass:{top_status}")
  1775. if payload.get("counterparty") != "real_bmc":
  1776. failures.append("counterparty_not_real_bmc")
  1777. if payload.get("diagnostic_scope") != diagnostic_scope:
  1778. failures.append(f"diagnostic_scope_not_{diagnostic_scope}")
  1779. layers = payload.get("layers") or {}
  1780. if not isinstance(layers, dict):
  1781. layers = {}
  1782. failures.append("layers_not_object")
  1783. failures.extend(
  1784. failure
  1785. for failure in _validate_layer_statuses(
  1786. layers=layers,
  1787. required_layers=required_layers,
  1788. allowed_layers=allowed_layers,
  1789. )
  1790. if failure not in ignored_layer_status_failures
  1791. )
  1792. programming = payload.get("programming") if isinstance(payload.get("programming"), dict) else {}
  1793. if programming.get("mode") != "PROGRAM_SRAM":
  1794. failures.append("programming_not_sram")
  1795. if programming.get("manual_programming") is not True:
  1796. failures.append("manual_programming_not_true")
  1797. bitstream_result = _hash_validation_with_optional_receipt_path(receipt_path, programming.get("bitstream"), required=True)
  1798. if bitstream_result["status"] == "missing":
  1799. failures.append("bitstream_missing")
  1800. elif bitstream_result["status"] == "hash_mismatch":
  1801. failures.append("bitstream_hash_mismatch")
  1802. elif strict and bitstream_result["status"] == "missing_hash":
  1803. failures.append("missing_bitstream_hash")
  1804. bitstream_sha256 = _artifact_hash_from_result(bitstream_result)
  1805. pin_profile = payload.get("pin_profile") if isinstance(payload.get("pin_profile"), dict) else {}
  1806. profile_name = str(pin_profile.get("name") or "")
  1807. expected_profile = allowed_pin_profiles.get(profile_name)
  1808. if expected_profile is None:
  1809. failures.append("pin_profile_invalid")
  1810. else:
  1811. if pin_profile.get("connector") != "J6":
  1812. failures.append("pin_profile_connector_not_j6")
  1813. for field, expected in expected_profile.items():
  1814. if pin_profile.get(field) != expected:
  1815. failures.append(f"pin_profile_{field}_mismatch")
  1816. collector = payload.get("collector") if isinstance(payload.get("collector"), dict) else {}
  1817. host_port = str(collector.get("host_port") or "")
  1818. debug_port = str(collector.get("debug_port") or "")
  1819. debug_baud = _safe_int(collector.get("debug_baud"), default=0)
  1820. if host_port != "COM8":
  1821. failures.append("collector_host_port_not_com8")
  1822. if debug_port != "COM7":
  1823. failures.append("collector_debug_port_not_com7")
  1824. if debug_baud != 921600:
  1825. failures.append("debug_baud_not_921600")
  1826. if _safe_int(collector.get("baud"), default=0) != 115200:
  1827. failures.append("serial_baud_not_115200")
  1828. if str(collector.get("format") or "").upper() != "8N1":
  1829. failures.append("serial_format_not_8n1")
  1830. if str(collector.get("flow_control") or "").lower() != "none":
  1831. failures.append("serial_flow_control_not_none")
  1832. if collector.get("dtr_enable") is not False:
  1833. failures.append("collector_dtr_enabled")
  1834. if collector.get("rts_enable") is not False:
  1835. failures.append("collector_rts_enabled")
  1836. if collector.get("write_port_role") != "HostPort":
  1837. failures.append("collector_write_port_role_not_hostport")
  1838. if collector.get("host_port_writes_to_serial") is not True:
  1839. failures.append("collector_host_port_not_written")
  1840. if collector.get("debug_port_writes_to_serial") is not False:
  1841. failures.append("collector_debug_port_writes_to_serial")
  1842. if collector.get("opens_unknown_com_ports") is not False:
  1843. failures.append("collector_opens_unknown_com_ports")
  1844. if collector.get("enumerates_com_ports") is not False:
  1845. failures.append("collector_enumerates_com_ports")
  1846. td_layer = layers.get("td_bitstream") if isinstance(layers.get("td_bitstream"), dict) else {}
  1847. manual_layer = layers.get("manual_sram_programming") if isinstance(layers.get("manual_sram_programming"), dict) else {}
  1848. command_layer = layers.get("host_command_sequence") if isinstance(layers.get("host_command_sequence"), dict) else {}
  1849. host_transcript_layer = layers.get("host_control_transcript") if isinstance(layers.get("host_control_transcript"), dict) else {}
  1850. host_sensor_layer = layers.get("host_sensor_reports") if isinstance(layers.get("host_sensor_reports"), dict) else {}
  1851. debug_layer = layers.get("debug_frame_capture") if isinstance(layers.get("debug_frame_capture"), dict) else {}
  1852. sampling_layer = layers.get("bmc_raw_sampling") if isinstance(layers.get("bmc_raw_sampling"), dict) else {}
  1853. pid_layer = layers.get("pid_boundary") if isinstance(layers.get("pid_boundary"), dict) else {}
  1854. timeout_layer = layers.get("timeout_evidence") if isinstance(layers.get("timeout_evidence"), dict) else {}
  1855. pin_map_layer = layers.get("pin_map") if isinstance(layers.get("pin_map"), dict) else {}
  1856. safety_contract = layers.get("safety_contract") if isinstance(layers.get("safety_contract"), dict) else {}
  1857. artifact_layer = layers.get("artifact_hashes") if isinstance(layers.get("artifact_hashes"), dict) else {}
  1858. td_result, current_failures = _validate_real_bmc_artifact(receipt_path, td_layer, "receipt", "td_receipt")
  1859. failures.extend(current_failures)
  1860. td_sha256 = _artifact_hash_from_result(td_result)
  1861. if isinstance(td_result, dict) and td_result.get("exists"):
  1862. try:
  1863. td_payload = read_json(td_result["path"])
  1864. except Exception as exc: # noqa: BLE001
  1865. td_payload = {}
  1866. failures.append(f"td_receipt_unreadable:{exc.__class__.__name__}")
  1867. if isinstance(td_payload, dict):
  1868. if str(td_payload.get("status") or "missing") != "pass":
  1869. failures.append(f"td_bitstream_receipt_not_pass:{td_payload.get('status', 'missing')}")
  1870. if td_payload.get("mode") != "implementation":
  1871. failures.append("td_bitstream_not_implementation")
  1872. expected_top_module = allowed_top_modules_by_pin_profile.get(profile_name, allowed_top_module)
  1873. if td_payload.get("top_module") != expected_top_module:
  1874. failures.append(td_top_failure_name)
  1875. td_pin_profile = str(td_payload.get("pin_profile") or "")
  1876. if profile_name and td_pin_profile and td_pin_profile != profile_name:
  1877. failures.append("td_pin_profile_mismatch")
  1878. td_bitstream = td_payload.get("bitstream") if isinstance(td_payload.get("bitstream"), dict) else {}
  1879. td_bitstream_sha256 = str(td_bitstream.get("sha256") or "")
  1880. if not td_bitstream_sha256:
  1881. failures.append("td_bitstream_missing_hash")
  1882. elif bitstream_sha256 and td_bitstream_sha256.lower() != bitstream_sha256.lower():
  1883. failures.append("td_bitstream_hash_mismatch")
  1884. if manual_layer.get("mode") != "PROGRAM_SRAM":
  1885. failures.append("manual_sram_mode_not_program_sram")
  1886. if manual_layer.get("manual_programming") is not True:
  1887. failures.append("manual_sram_manual_programming_not_true")
  1888. attestation_result, current_failures = _validate_real_bmc_artifact(receipt_path, manual_layer, "attestation", "manual_sram_attestation")
  1889. failures.extend(current_failures)
  1890. attestation_sha256 = _artifact_hash_from_result(attestation_result)
  1891. if isinstance(attestation_result, dict) and attestation_result.get("exists"):
  1892. try:
  1893. attestation_payload = read_json(attestation_result["path"])
  1894. except Exception as exc: # noqa: BLE001
  1895. attestation_payload = {}
  1896. failures.append(f"manual_sram_attestation_unreadable:{exc.__class__.__name__}")
  1897. if isinstance(attestation_payload, dict):
  1898. if str(attestation_payload.get("status") or "missing") != "pass":
  1899. failures.append(f"manual_sram_attestation_not_pass:{attestation_payload.get('status', 'missing')}")
  1900. if attestation_payload.get("mode") != "PROGRAM_SRAM":
  1901. failures.append("manual_sram_attestation_wrong_mode")
  1902. if bitstream_sha256 and str(attestation_payload.get("bitstream_sha256") or "").lower() != bitstream_sha256.lower():
  1903. failures.append("manual_sram_attestation_bitstream_hash_mismatch")
  1904. if td_sha256 and str(attestation_payload.get("td_receipt_sha256") or "").lower() != td_sha256.lower():
  1905. failures.append("manual_sram_attestation_td_receipt_hash_mismatch")
  1906. layer_commands = command_layer.get("commands") if isinstance(command_layer.get("commands"), list) else []
  1907. host_commands = [str(command).strip() for command in layer_commands if str(command).strip()]
  1908. if not host_commands:
  1909. failures.append("missing_host_commands")
  1910. elif host_commands != expected_commands:
  1911. failures.append("host_command_sequence_mismatch")
  1912. for command in host_commands:
  1913. if not allowed_command(command):
  1914. failures.append(f"host_command_not_allowed:{command}")
  1915. host_transcript_result, current_failures = _validate_real_bmc_artifact(receipt_path, host_transcript_layer, "host_command_transcript", "host_command_transcript")
  1916. failures.extend(current_failures)
  1917. host_transcript_sha256 = _artifact_hash_from_result(host_transcript_result)
  1918. host_transcript_payload, current_failures = _read_json_artifact(host_transcript_result, "host_command_transcript")
  1919. failures.extend(current_failures)
  1920. host_ack = {"status": "missing", "accepted": 0, "total": 0, "records": []}
  1921. if host_transcript_payload:
  1922. if str(host_transcript_payload.get("status") or "pass") != "pass":
  1923. failures.append(f"host_command_transcript_status_not_pass:{host_transcript_payload.get('status', 'missing')}")
  1924. if host_transcript_payload.get("host_port") != "COM8":
  1925. failures.append("host_transcript_port_not_com8")
  1926. if _safe_int(host_transcript_payload.get("baud"), default=115200) != 115200:
  1927. failures.append("host_transcript_baud_not_115200")
  1928. if host_transcript_payload.get("writes_to_serial") is not True:
  1929. failures.append("host_transcript_writes_to_serial_not_true")
  1930. if host_transcript_payload.get("write_port_role") != "HostPort":
  1931. failures.append("host_transcript_write_port_role_not_hostport")
  1932. if host_transcript_payload.get("debug_port_writes_to_serial") is not False:
  1933. failures.append("host_transcript_debug_port_writes_to_serial")
  1934. raw_commands = host_transcript_payload.get("commands") if isinstance(host_transcript_payload.get("commands"), list) else []
  1935. preflight = host_transcript_payload.get("preflight")
  1936. if isinstance(preflight, dict):
  1937. if str(preflight.get("status") or "missing") != "pass":
  1938. failures.append(f"host_preflight_not_pass:{preflight.get('status', 'missing')}")
  1939. if preflight.get("ready_seen") is not True:
  1940. failures.append("host_preflight_ready_missing")
  1941. if preflight.get("epoch_locked") is False:
  1942. failures.append("host_preflight_epoch_not_locked")
  1943. sync_command = str(preflight.get("sync_command") or "").strip().lower()
  1944. sync_ack_seen = preflight.get("sync_ack_seen")
  1945. if sync_command not in {"", "none"} and sync_ack_seen is not True:
  1946. failures.append("host_preflight_sync_ack_missing")
  1947. if sync_ack_seen is True and sync_command in {"", "none"}:
  1948. failures.append("host_preflight_sync_ack_unexpected")
  1949. ready_line = str(preflight.get("ready_line") or "").strip()
  1950. if ready_line and ready_line != "READY profile=temp-uart-ptc-remap seq=00000000":
  1951. failures.append("host_preflight_ready_line_mismatch")
  1952. preflight_ack = str(preflight.get("preflight_ack") or "").strip()
  1953. if preflight_ack and preflight_ack != "OK seq=00000001 cmd=STATUS":
  1954. failures.append("host_preflight_ack_mismatch")
  1955. if preflight.get("counts_as_formal_command") is not False:
  1956. failures.append("host_preflight_counts_as_formal_command")
  1957. else:
  1958. preflight = None
  1959. accepted = 0
  1960. records = []
  1961. startup_shift_detected = False
  1962. if raw_commands:
  1963. first = raw_commands[0] if isinstance(raw_commands[0], dict) else {}
  1964. host_text_for_epoch = ""
  1965. host_text_result_for_epoch = _validate_real_bmc_artifact(receipt_path, host_sensor_layer, "host_transcript_text", "host_transcript_text")[0]
  1966. if isinstance(host_text_result_for_epoch, dict):
  1967. host_text_for_epoch = _read_artifact_text(host_text_result_for_epoch) or ""
  1968. ready_after_ack = False
  1969. if host_text_for_epoch:
  1970. ready_index = host_text_for_epoch.find("READY profile=temp-uart-ptc-remap seq=00000000")
  1971. first_old_ack_index = host_text_for_epoch.find("OK seq=0000000D cmd=STATUS")
  1972. if ready_index >= 0 and first_old_ack_index >= 0 and first_old_ack_index < ready_index:
  1973. ready_after_ack = True
  1974. if (
  1975. isinstance(preflight, dict)
  1976. and str(preflight.get("status") or "") != "pass"
  1977. and preflight.get("epoch_locked") is not True
  1978. and (
  1979. ready_after_ack
  1980. or str(preflight.get("preflight_ack") or "").strip().startswith("OK seq=0000000D")
  1981. 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))
  1982. )
  1983. ):
  1984. failures.append("blocked_host_epoch_mixed")
  1985. later_shifted = 0
  1986. for shifted_index in range(1, len(raw_commands)):
  1987. item = raw_commands[shifted_index]
  1988. if not isinstance(item, dict):
  1989. continue
  1990. previous_expected = (
  1991. expected_commands[shifted_index - 1]
  1992. if shifted_index - 1 < len(expected_commands)
  1993. else ""
  1994. )
  1995. previous_ack_cmd = expected_ack_cmds.get(previous_expected, "")
  1996. if (
  1997. str(item.get("response_class") or item.get("ack_status") or "").strip().lower() == "ok"
  1998. and _safe_int(item.get("response_seq"), default=_safe_int(item.get("ack_seq"), default=None)) == shifted_index
  1999. and str(item.get("response_cmd") or item.get("ack_cmd") or "").strip() == previous_ack_cmd
  2000. ):
  2001. later_shifted += 1
  2002. startup_shift_detected = (
  2003. isinstance(first, dict)
  2004. and str(first.get("response_class") or first.get("ack_status") or "").strip().lower() in {"", "timeout", "missing"}
  2005. and later_shifted >= max(1, len(raw_commands) // 2)
  2006. )
  2007. if startup_shift_detected:
  2008. failures.append("blocked_host_startup_ack_shift")
  2009. if preflight is None or str(preflight.get("status") or "missing") != "pass":
  2010. failures.append("host_preflight_missing")
  2011. elif preflight is None:
  2012. failures.append("host_preflight_missing")
  2013. for index, item in enumerate(raw_commands):
  2014. if not isinstance(item, dict):
  2015. failures.append(f"host_transcript_command_not_object:{index}")
  2016. continue
  2017. command = str(item.get("command") or "").strip()
  2018. records.append(item)
  2019. expected_command = (
  2020. expected_commands[index]
  2021. if index < len(expected_commands)
  2022. else ""
  2023. )
  2024. expected_ack_cmd = expected_ack_cmds.get(expected_command, "")
  2025. if not allowed_command(command):
  2026. failures.append(f"host_transcript_command_not_allowed:{index}:{command}")
  2027. if command != expected_command:
  2028. failures.append(f"host_transcript_command_mismatch:{index}")
  2029. if item.get("allowed") is not True:
  2030. failures.append(f"host_transcript_command_not_allowed_flag:{index}")
  2031. response_raw = str(item.get("response_raw") or item.get("ack_raw") or item.get("response") or item.get("ack_line") or "").strip()
  2032. response_class = str(item.get("response_class") or item.get("ack_status") or "").strip().lower()
  2033. response_seq = _safe_int(item.get("response_seq"), default=_safe_int(item.get("ack_seq"), default=None))
  2034. response_cmd = str(item.get("response_cmd") or item.get("ack_cmd") or "").strip()
  2035. strict_match = (
  2036. response_class == "ok"
  2037. and response_seq == index + 1
  2038. and response_cmd == expected_ack_cmd
  2039. and response_raw == f"OK seq={index + 1:08X} cmd={expected_ack_cmd}"
  2040. and item.get("seq_match") is True
  2041. and item.get("cmd_match") is True
  2042. and item.get("stale") is not True
  2043. and item.get("accepted") is True
  2044. )
  2045. ok = strict_match
  2046. if ok:
  2047. accepted += 1
  2048. else:
  2049. failures.append(f"host_ack_not_ok:{index}")
  2050. if response_class != "ok":
  2051. failures.append(f"host_ack_class_not_ok:{index}:{response_class or 'missing'}")
  2052. if response_seq != index + 1:
  2053. failures.append(f"host_ack_seq_mismatch:{index}")
  2054. if response_cmd != expected_ack_cmd:
  2055. failures.append(f"host_ack_cmd_mismatch:{index}")
  2056. if response_raw != f"OK seq={index + 1:08X} cmd={expected_ack_cmd}":
  2057. failures.append(f"host_ack_line_mismatch:{index}")
  2058. if item.get("stale") is True:
  2059. failures.append(f"host_ack_stale:{index}")
  2060. if item.get("accepted") is not True:
  2061. failures.append(f"host_ack_not_accepted:{index}")
  2062. if len(raw_commands) != len(expected_commands) or len(raw_commands) != len(host_commands):
  2063. failures.append("host_ack_command_count_mismatch")
  2064. transcript_commands = [str(item.get("command") or "").strip() for item in raw_commands if isinstance(item, dict)]
  2065. if transcript_commands != expected_commands:
  2066. failures.append("host_transcript_command_sequence_mismatch")
  2067. host_ack = {
  2068. "status": "pass" if accepted == len(raw_commands) and len(raw_commands) == len(host_commands) else "fail",
  2069. "accepted": accepted,
  2070. "total": len(raw_commands),
  2071. "records": records,
  2072. }
  2073. completed_samples = _safe_int(sampling_layer.get("completed_samples"), default=0) or 0
  2074. min_samples = _safe_int(sampling_layer.get("minimum_completed_samples"), default=3) or 3
  2075. bmc_timeout = bool(sampling_layer.get("bmc_timeout"))
  2076. host_text_result, current_failures = _validate_real_bmc_artifact(receipt_path, host_sensor_layer, "host_transcript_text", "host_transcript_text")
  2077. failures.extend(current_failures)
  2078. host_raw_result, current_failures = _validate_real_bmc_artifact(receipt_path, host_sensor_layer, "host_raw_bin", "host_raw_bin")
  2079. failures.extend(current_failures)
  2080. host_sensor_report_result, current_failures = _validate_real_bmc_artifact(receipt_path, host_sensor_layer, "host_sensor_report", "host_sensor_report")
  2081. failures.extend(current_failures)
  2082. host_transcript_text_sha256 = _artifact_hash_from_result(host_text_result)
  2083. host_raw_sha256 = _artifact_hash_from_result(host_raw_result)
  2084. host_sensor_report_sha256 = _artifact_hash_from_result(host_sensor_report_result)
  2085. if _artifact_size(host_raw_result) == 0:
  2086. failures.append("host_raw_bin_empty")
  2087. host_text = _read_artifact_text(host_text_result) or _read_artifact_text(host_raw_result)
  2088. parsed_host = _parse_host_sensor_report_text(host_text)
  2089. host_report_payload, current_failures = _read_json_artifact(host_sensor_report_result, "host_sensor_report")
  2090. failures.extend(current_failures)
  2091. if host_report_payload:
  2092. if host_report_payload.get("schema") not in host_sensor_report_schemas:
  2093. failures.append("host_sensor_report_wrong_schema")
  2094. if host_report_payload.get("source") != "HostPort":
  2095. failures.append("host_sensor_report_source_not_hostport")
  2096. report_status = str(host_report_payload.get("status") or "pass")
  2097. if report_status.startswith("blocked_"):
  2098. warnings.append(f"host_sensor_report_status:{report_status}")
  2099. elif report_status != "pass":
  2100. failures.append(f"host_sensor_report_status_not_pass:{report_status}")
  2101. report_samples = host_report_payload.get("samples") if isinstance(host_report_payload.get("samples"), list) else []
  2102. report_dimm_rows = host_report_payload.get("dimm_rows") if isinstance(host_report_payload.get("dimm_rows"), list) else []
  2103. if not bmc_timeout and not report_samples:
  2104. failures.append("host_sensor_report_missing_samples")
  2105. if report_samples and len(report_samples) != parsed_host["sample_count"]:
  2106. failures.append("host_sensor_report_sample_count_mismatch")
  2107. if report_samples and len(report_samples) != completed_samples:
  2108. failures.append("host_sensor_report_completed_sample_count_mismatch")
  2109. for index, sample in enumerate(report_samples, start=1):
  2110. rows = sample.get("dimm_rows") if isinstance(sample, dict) and isinstance(sample.get("dimm_rows"), list) else []
  2111. status_text = str(sample.get("status") or "").lower() if isinstance(sample, dict) else ""
  2112. summary = sample.get("summary") if isinstance(sample, dict) and isinstance(sample.get("summary"), dict) else sample
  2113. if status_text != "timeout" and len(rows) != 24:
  2114. failures.append(f"host_sensor_report_sample_{index}_dimm_rows_not_24")
  2115. if status_text != "timeout" and rows:
  2116. ids = sorted(_safe_int(_host_sensor_row_fields(row).get("id"), default=-1) for row in rows if isinstance(row, dict))
  2117. if ids != list(range(24)):
  2118. failures.append(f"host_sensor_report_sample_{index}_dimm_ids_not_00_23")
  2119. missing_rows = sum(1 for row in rows if isinstance(row, dict) and _host_sensor_row_missing(row))
  2120. reported_missing = _safe_int((summary or {}).get("missing"), default=None) if isinstance(summary, dict) else None
  2121. reported_valid = _safe_int((summary or {}).get("valid"), default=None) if isinstance(summary, dict) else None
  2122. if reported_missing is not None and reported_missing != missing_rows:
  2123. failures.append(f"host_sensor_report_sample_{index}_missing_count_mismatch")
  2124. if reported_valid is not None and reported_valid != 24 - missing_rows:
  2125. failures.append(f"host_sensor_report_sample_{index}_valid_count_mismatch")
  2126. if report_dimm_rows:
  2127. sidecar_sample_count = len({str(_host_sensor_row_fields(row).get("seq")) for row in report_dimm_rows if isinstance(row, dict)})
  2128. if sidecar_sample_count and sidecar_sample_count != parsed_host["sample_count"]:
  2129. failures.append("host_sensor_report_dimm_row_sample_count_mismatch")
  2130. if _safe_int(host_report_payload.get("host_report_drop"), default=0):
  2131. failures.append("host_report_drop_nonzero")
  2132. if host_report_payload.get("bmc_timeout") is True:
  2133. failures.append("bmc_timeout_observed")
  2134. for index, row_count in enumerate(parsed_host["dimm_rows_per_sample"], start=1):
  2135. summary = parsed_host["samples"][index - 1].get("summary") if parsed_host["samples"] else {}
  2136. status_text = str((summary or {}).get("status") or "").lower()
  2137. if status_text == "timeout":
  2138. continue
  2139. if row_count != 24:
  2140. failures.append(f"sample_{index}_dimm_rows_not_24")
  2141. rows = parsed_host["samples"][index - 1].get("dimm_rows") if parsed_host["samples"] else []
  2142. ids = sorted(_safe_int(_host_sensor_row_fields(row).get("id"), default=-1) for row in rows if isinstance(row, dict))
  2143. if ids != list(range(24)):
  2144. failures.append(f"sample_{index}_dimm_ids_not_00_23")
  2145. missing_rows = sum(1 for row in rows if isinstance(row, dict) and _host_sensor_row_missing(row))
  2146. reported_missing = _safe_int((summary or {}).get("missing"), default=None)
  2147. reported_valid = _safe_int((summary or {}).get("valid"), default=None)
  2148. if reported_missing is not None and reported_missing != missing_rows:
  2149. failures.append(f"sample_{index}_missing_count_mismatch")
  2150. if reported_valid is not None and reported_valid != 24 - missing_rows:
  2151. failures.append(f"sample_{index}_valid_count_mismatch")
  2152. if parsed_host["sample_count"] == 0:
  2153. failures.append("missing_host_sensor_samples")
  2154. debug_raw_result, current_failures = _validate_real_bmc_artifact(receipt_path, debug_layer, "raw_bin", "debug_raw_bin")
  2155. failures.extend(current_failures)
  2156. debug_transcript_result, current_failures = _validate_real_bmc_artifact(receipt_path, debug_layer, "debug_transcript", "debug_transcript")
  2157. failures.extend(current_failures)
  2158. raw_replay_result, current_failures = _validate_real_bmc_artifact(receipt_path, debug_layer, "raw_replay", "raw_replay")
  2159. failures.extend(current_failures)
  2160. debug_frame_stream_result, current_failures = _validate_real_bmc_artifact(receipt_path, debug_layer, "debug_frame_stream", "debug_frame_stream")
  2161. failures.extend(current_failures)
  2162. manifest_result, current_failures = _validate_real_bmc_artifact(receipt_path, debug_layer, "manifest", "manifest")
  2163. failures.extend(current_failures)
  2164. debug_raw_sha256 = _artifact_hash_from_result(debug_raw_result)
  2165. debug_transcript_sha256 = _artifact_hash_from_result(debug_transcript_result)
  2166. raw_replay_sha256 = _artifact_hash_from_result(raw_replay_result)
  2167. debug_frame_stream_sha256 = _artifact_hash_from_result(debug_frame_stream_result)
  2168. manifest_sha256 = _artifact_hash_from_result(manifest_result)
  2169. if _artifact_size(debug_raw_result) == 0:
  2170. failures.append("debug_raw_bin_empty")
  2171. debug_text = _read_artifact_text(debug_transcript_result) or _read_artifact_text(debug_raw_result)
  2172. j6raw_frames = _parse_j6raw_frames(debug_text)
  2173. replay_j6raw_frames = _post_j6ready_j6raw_frames(debug_text, j6raw_frames)
  2174. j6ready_events = _parse_lossless_key_value_lines(debug_text, "J6READY")
  2175. j6cmd_events = _parse_lossless_key_value_lines(debug_text, "J6CMD")
  2176. j6evt_events = _parse_lossless_key_value_lines(debug_text, "J6EVT")
  2177. j6pwm_events = _parse_lossless_key_value_lines(debug_text, "J6PWM")
  2178. j6mod_events = _parse_lossless_key_value_lines(debug_text, "J6MOD")
  2179. j6stat_events = _parse_lossless_key_value_lines(debug_text, "J6STAT")
  2180. j6map_events = _parse_lossless_key_value_lines(debug_text, "J6MAP")
  2181. j6temp_events = _parse_lossless_key_value_lines(debug_text, "J6TEMP")
  2182. for prefix, events in [
  2183. ("j6ready", j6ready_events),
  2184. ("j6cmd", j6cmd_events),
  2185. ("j6raw", j6raw_frames),
  2186. ("j6evt", j6evt_events),
  2187. ("j6pwm", j6pwm_events),
  2188. ("j6mod", j6mod_events),
  2189. ("j6stat", j6stat_events),
  2190. ("j6map", j6map_events),
  2191. ("j6temp", j6temp_events),
  2192. ]:
  2193. if not events and not (prefix == "j6raw" and sampling_layer.get("bmc_timeout") is True):
  2194. failures.append(f"missing_{prefix}_frames")
  2195. last_stat = j6stat_events[-1] if j6stat_events else None
  2196. debug_frame_stream_payload, current_failures = _read_json_artifact(debug_frame_stream_result, "debug_frame_stream")
  2197. failures.extend(current_failures)
  2198. if debug_frame_stream_payload:
  2199. if debug_frame_stream_payload.get("schema") not in debug_frame_stream_schemas:
  2200. failures.append("debug_frame_stream_wrong_schema")
  2201. if str(debug_frame_stream_payload.get("status") or "pass") != "pass":
  2202. failures.append(f"debug_frame_stream_status_not_pass:{debug_frame_stream_payload.get('status', 'missing')}")
  2203. stream_frames_raw = debug_frame_stream_payload.get("frames") if isinstance(debug_frame_stream_payload.get("frames"), list) else []
  2204. if not stream_frames_raw and not bmc_timeout:
  2205. failures.append("debug_frame_stream_missing_frames")
  2206. stream_text = "\n".join(
  2207. str(item.get("raw") or "") if isinstance(item, dict) else str(item)
  2208. for item in stream_frames_raw
  2209. )
  2210. stream_counts = {
  2211. "j6cmd": len(_parse_lossless_key_value_lines(stream_text, "J6CMD")),
  2212. "j6ready": len(_parse_lossless_key_value_lines(stream_text, "J6READY")),
  2213. "j6raw": len(_parse_j6raw_frames(stream_text)),
  2214. "j6evt": len(_parse_lossless_key_value_lines(stream_text, "J6EVT")),
  2215. "j6pwm": len(_parse_lossless_key_value_lines(stream_text, "J6PWM")),
  2216. "j6mod": len(_parse_lossless_key_value_lines(stream_text, "J6MOD")),
  2217. "j6stat": len(_parse_lossless_key_value_lines(stream_text, "J6STAT")),
  2218. "j6map": len(_parse_lossless_key_value_lines(stream_text, "J6MAP")),
  2219. "j6temp": len(_parse_lossless_key_value_lines(stream_text, "J6TEMP")),
  2220. }
  2221. expected_stream_counts = {
  2222. "j6cmd": len(j6cmd_events),
  2223. "j6ready": len(j6ready_events),
  2224. "j6raw": len(j6raw_frames),
  2225. "j6evt": len(j6evt_events),
  2226. "j6pwm": len(j6pwm_events),
  2227. "j6mod": len(j6mod_events),
  2228. "j6stat": len(j6stat_events),
  2229. "j6map": len(j6map_events),
  2230. "j6temp": len(j6temp_events),
  2231. }
  2232. if stream_counts != expected_stream_counts:
  2233. failures.append("debug_frame_stream_transcript_mismatch")
  2234. if _safe_int(debug_frame_stream_payload.get("raw_drop"), default=0):
  2235. failures.append("raw_drop_nonzero")
  2236. if _safe_int(debug_frame_stream_payload.get("host_report_drop"), default=0):
  2237. failures.append("host_report_drop_nonzero")
  2238. if _safe_int(debug_frame_stream_payload.get("bmc_berr"), default=0):
  2239. failures.append("bmc_uart_error_nonzero")
  2240. if _safe_int(debug_frame_stream_payload.get("host_err"), default=0):
  2241. failures.append("host_uart_error_nonzero")
  2242. raw_replay, current_failures = _validate_j6raw_replay(replay_j6raw_frames, last_stat=last_stat, replay_result=raw_replay_result)
  2243. if sampling_layer.get("bmc_timeout") is True:
  2244. current_failures = [failure for failure in current_failures if failure != "missing_j6raw_frames"]
  2245. failures.extend(current_failures)
  2246. if last_stat is not None and _safe_int(last_stat.get("host_report_drop"), default=0):
  2247. failures.append("host_report_drop_nonzero")
  2248. if not j6ready_events:
  2249. failures.append("missing_j6ready_frames")
  2250. for index, event in enumerate(j6evt_events):
  2251. for field in ("seq", "cmd", "ch", "pct"):
  2252. if field not in event:
  2253. failures.append(f"j6evt_missing_{field}:{index}")
  2254. if _safe_int(event.get("ok"), default=1) != 1:
  2255. failures.append(f"j6evt_not_ok:{index}")
  2256. if _safe_int(event.get("err"), default=0) not in (0, None):
  2257. failures.append(f"j6evt_err_nonzero:{index}")
  2258. if last_stat is not None and _safe_int(last_stat.get("host_err"), default=0):
  2259. failures.append("host_uart_error_nonzero")
  2260. if bmc_timeout:
  2261. failures.append("bmc_timeout_observed")
  2262. elif completed_samples < min_samples:
  2263. failures.append("completed_samples_lt_minimum")
  2264. if completed_samples and parsed_host["sample_count"] and completed_samples != parsed_host["sample_count"]:
  2265. failures.append("sampling_host_sample_count_mismatch")
  2266. if j6temp_events and parsed_host["sample_count"] and len(j6temp_events) < parsed_host["sample_count"]:
  2267. failures.append("debug_temp_sample_count_lt_host")
  2268. pid_requested = bool(pid_layer.get("pid_requested_ever", pid_layer.get("pid_requested")))
  2269. pid_active = bool(pid_layer.get("pid_active"))
  2270. pwm_source = str(pid_layer.get("pwm_source") or "")
  2271. if not pid_requested:
  2272. failures.append("pid_requested_ever_not_recorded")
  2273. if pid_active:
  2274. failures.append("pid_active_not_false")
  2275. if pwm_source != "host_manual":
  2276. failures.append("pid_pwm_source_not_host_manual")
  2277. for event in parsed_host["pid_events"]:
  2278. if _safe_int(event.get("active"), default=0):
  2279. failures.append("host_pid_active_not_false")
  2280. for event in j6mod_events:
  2281. if _safe_int(event.get("pid_active"), default=0):
  2282. failures.append("debug_pid_active_not_false")
  2283. if not any(_safe_int(event.get("pid_requested"), default=0) for event in j6mod_events) and not pid_layer.get("pid_requested_ever"):
  2284. failures.append("debug_pid_requested_not_seen")
  2285. timeout_status = timeout_layer.get("timeout_evidence") if isinstance(timeout_layer.get("timeout_evidence"), dict) else {}
  2286. timeout_ptc = _safe_int(timeout_status.get("ptc_all_percent"), default=None)
  2287. timeout_fan = _safe_int(timeout_status.get("fan_all_percent"), default=None)
  2288. timeout_evidence = {"timeout_s": _safe_int(timeout_status.get("timeout_s"), default=None), "ptc_all_percent": timeout_ptc, "fan_all_percent": timeout_fan}
  2289. if timeout_evidence["timeout_s"] != 5:
  2290. failures.append("timeout_seconds_not_5")
  2291. if timeout_ptc != 0:
  2292. failures.append("timeout_ptc_not_zero")
  2293. if timeout_fan != 30:
  2294. failures.append("timeout_fan_not_background_30")
  2295. timeout_pwm_events = [event for event in parsed_host["pwm_events"] + j6pwm_events if _safe_int(event.get("timeout"), default=0) == 1]
  2296. if not timeout_pwm_events:
  2297. failures.append("missing_timeout_debug_evidence")
  2298. if _safe_int(pin_map_layer.get("ptc_count"), default=-1) != 24:
  2299. failures.append("pin_map_ptc_count_not_24")
  2300. if _safe_int(pin_map_layer.get("fan_count"), default=-1) != expected_fan_count:
  2301. failures.append(f"pin_map_fan_count_not_{expected_fan_count}")
  2302. pin_map_profile = str(pin_map_layer.get("profile") or pin_map_layer.get("name") or "")
  2303. if profile_name and pin_map_profile and pin_map_profile != profile_name:
  2304. failures.append("pin_map_profile_mismatch")
  2305. if expected_profile is not None:
  2306. for field, expected in expected_profile.items():
  2307. if field in pin_map_layer and pin_map_layer.get(field) != expected:
  2308. failures.append(f"pin_map_{field}_mismatch")
  2309. if safety_contract.get("pid_default_enabled") is not False:
  2310. failures.append("safety_contract_pid_default_enabled_not_false")
  2311. if safety_contract.get("pid_active") is not False:
  2312. failures.append("safety_contract_pid_active_not_false")
  2313. if safety_contract.get("bmc_controls_pwm") is not False:
  2314. failures.append("safety_contract_bmc_controls_pwm_not_false")
  2315. if safety_contract.get("debug_port_writes_to_serial") is not False:
  2316. failures.append("safety_contract_debug_port_writes_to_serial")
  2317. if safety_contract.get("host_port_writes_to_serial") is not True:
  2318. failures.append("safety_contract_host_port_writes_not_true")
  2319. if safety_contract.get("real_thermal_performance_claimed") is not False:
  2320. failures.append("safety_contract_real_thermal_performance_claimed")
  2321. manifest_payload, current_failures = _read_json_artifact(manifest_result, "manifest")
  2322. failures.extend(current_failures)
  2323. if manifest_payload:
  2324. if str(manifest_payload.get("status") or "pass") != "pass":
  2325. failures.append(f"manifest_status_not_pass:{manifest_payload.get('status', 'missing')}")
  2326. manifest_profile = manifest_payload.get("pin_profile_name")
  2327. if manifest_profile is None:
  2328. manifest_profile_obj = manifest_payload.get("pin_profile")
  2329. if isinstance(manifest_profile_obj, dict):
  2330. manifest_profile = manifest_profile_obj.get("name")
  2331. elif isinstance(manifest_profile_obj, str):
  2332. manifest_profile = manifest_profile_obj
  2333. if profile_name and str(manifest_profile or "") and str(manifest_profile) != profile_name:
  2334. failures.append("manifest_pin_profile_mismatch")
  2335. if manifest_payload.get("host_port") != "COM8":
  2336. failures.append("manifest_host_port_not_com8")
  2337. if manifest_payload.get("debug_port") != "COM7":
  2338. failures.append("manifest_debug_port_not_com7")
  2339. if _safe_int(manifest_payload.get("debug_baud"), default=921600) != 921600:
  2340. failures.append("manifest_debug_baud_not_921600")
  2341. if manifest_payload.get("host_port_writes_to_serial") is not True:
  2342. failures.append("manifest_host_port_writes_not_true")
  2343. if manifest_payload.get("debug_port_writes_to_serial") is not False:
  2344. failures.append("manifest_debug_port_writes_to_serial")
  2345. if manifest_payload.get("enumerates_com_ports") not in (False, None):
  2346. failures.append("manifest_enumerates_com_ports")
  2347. if manifest_payload.get("opens_unknown_com_ports") not in (False, None):
  2348. failures.append("manifest_opens_unknown_com_ports")
  2349. expected_artifact_hashes = {
  2350. "bitstream_sha256": bitstream_sha256,
  2351. "td_receipt_sha256": td_sha256,
  2352. "manual_sram_attestation_sha256": attestation_sha256,
  2353. "host_transcript_text_sha256": host_transcript_text_sha256,
  2354. "host_raw_bin_sha256": host_raw_sha256,
  2355. "host_sensor_report_sha256": host_sensor_report_sha256,
  2356. "debug_transcript_sha256": debug_transcript_sha256,
  2357. "debug_raw_bin_sha256": debug_raw_sha256,
  2358. "raw_replay_sha256": raw_replay_sha256,
  2359. "debug_frame_stream_sha256": debug_frame_stream_sha256,
  2360. "host_command_transcript_sha256": host_transcript_sha256,
  2361. "manifest_sha256": manifest_sha256,
  2362. }
  2363. for key, actual in expected_artifact_hashes.items():
  2364. recorded = str(artifact_layer.get(key) or "")
  2365. if not recorded:
  2366. failures.append(f"missing_artifact_hash:{key}")
  2367. elif actual and recorded.lower() != actual.lower():
  2368. failures.append(f"artifact_hash_mismatch:{key}")
  2369. safety = payload.get("safety") if isinstance(payload.get("safety"), dict) else {}
  2370. for field in required_safety_false_fields:
  2371. if safety.get(field) is not False:
  2372. failures.append(f"safety_flag:{field}")
  2373. if safety.get("host_port_writes_to_serial") is not True:
  2374. failures.append("safety_flag:host_port_writes_to_serial_not_true")
  2375. for marker in _forbidden_action_markers_in_keys_and_values(payload, forbidden_action_markers):
  2376. failures.append(f"forbidden_action_marker:{marker}")
  2377. for role, artifact_result in [
  2378. ("td_receipt", td_result),
  2379. ("manual_sram_attestation", attestation_result),
  2380. ("host_transcript_text", host_text_result),
  2381. ("host_sensor_report", host_sensor_report_result),
  2382. ("debug_transcript", debug_transcript_result),
  2383. ("debug_frame_stream", debug_frame_stream_result),
  2384. ("host_command_transcript", host_transcript_result),
  2385. ("manifest", manifest_result),
  2386. ]:
  2387. if isinstance(artifact_result, dict) and artifact_result.get("exists") is True:
  2388. path = Path(str(artifact_result.get("path") or ""))
  2389. try:
  2390. data = path.read_bytes()
  2391. except OSError as exc:
  2392. failures.append(f"artifact_scan_unreadable:{role}:{exc.__class__.__name__}")
  2393. continue
  2394. if b"\x00" in data[:4096]:
  2395. continue
  2396. text = data.decode("utf-8-sig", errors="ignore")
  2397. for marker in _forbidden_markers_in_text(text, forbidden_action_markers):
  2398. failures.append(f"forbidden_action_marker:{marker}")
  2399. failures.append(f"artifact_forbidden_action_marker:{role}:{marker}")
  2400. if strict:
  2401. authority = str(payload.get("authority_boundary") or "").lower()
  2402. negated_authority = "does not" in authority
  2403. if ("final gate pass" in authority or "final-gate pass" in authority) and not negated_authority:
  2404. failures.append("authority_overclaim_final_gate")
  2405. if ("thermal performance pass" in authority or "thermal_performance_pass" in authority) and not negated_authority:
  2406. failures.append("authority_overclaim_thermal_performance")
  2407. if ("pid closed-loop pass" in authority or "real pid closed-loop pass" in authority) and not negated_authority:
  2408. failures.append("authority_overclaim_pid_closed_loop")
  2409. failure_set = set(failures)
  2410. joined = "\n".join(failure_set)
  2411. if (
  2412. "programming_not_sram" in failure_set
  2413. or "collector_debug_port_writes_to_serial" in failure_set
  2414. or "host_transcript_debug_port_writes_to_serial" in failure_set
  2415. or "manifest_debug_port_writes_to_serial" in failure_set
  2416. or "safety_contract_debug_port_writes_to_serial" in failure_set
  2417. or "collector_opens_unknown_com_ports" in failure_set
  2418. or "collector_enumerates_com_ports" in failure_set
  2419. or "collector_dtr_enabled" in failure_set
  2420. or "collector_rts_enabled" in failure_set
  2421. or "host_command_not_allowed:" in joined
  2422. or "host_transcript_command_not_allowed:" in joined
  2423. or any(item.startswith("forbidden_action_marker:") for item in failure_set)
  2424. or any(item.startswith("artifact_forbidden_action_marker:") for item in failure_set)
  2425. or any(item.startswith("safety_flag:") for item in failure_set)
  2426. ):
  2427. final_status = "fail_forbidden_action"
  2428. elif "blocked_host_epoch_mixed" in failure_set:
  2429. final_status = "blocked_host_epoch_mixed"
  2430. elif (
  2431. "host_preflight_epoch_not_locked" in failure_set
  2432. or any(item.startswith("host_preflight_not_pass:blocked_waiting_for_ready_epoch") for item in failure_set)
  2433. ):
  2434. final_status = "blocked_waiting_for_ready_epoch"
  2435. elif any(item.startswith("host_ack_") or item.startswith("host_transcript_response_not_ok") for item in failure_set):
  2436. final_status = "blocked_host_ack"
  2437. 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):
  2438. final_status = "blocked_uart_error"
  2439. elif "raw_drop_nonzero" in failure_set:
  2440. final_status = "blocked_cpld_raw_drop"
  2441. elif "host_report_drop_nonzero" in failure_set:
  2442. final_status = "blocked_host_report_drop"
  2443. elif "bmc_timeout_observed" in failure_set:
  2444. final_status = "blocked_bmc_timeout"
  2445. elif any(
  2446. item.endswith("_dimm_rows_not_24")
  2447. or item in {
  2448. "missing_host_sensor_samples",
  2449. "host_sensor_report_missing_samples",
  2450. "host_sensor_report_sample_count_mismatch",
  2451. "host_sensor_report_completed_sample_count_mismatch",
  2452. "host_sensor_report_dimm_row_sample_count_mismatch",
  2453. "sampling_host_sample_count_mismatch",
  2454. "debug_temp_sample_count_lt_host",
  2455. }
  2456. or item.startswith("host_sensor_report_sample_")
  2457. for item in failure_set
  2458. ):
  2459. final_status = "blocked_sensor_report_mismatch"
  2460. elif (
  2461. any(item.startswith("raw_frame_") for item in failure_set)
  2462. or "raw_in_replay_len_mismatch" in failure_set
  2463. or "raw_out_replay_len_mismatch" in failure_set
  2464. or "raw_replay_artifact_mismatch" in failure_set
  2465. or "missing_j6raw_frames" in failure_set
  2466. or "debug_frame_stream_missing_frames" in failure_set
  2467. or "debug_frame_stream_transcript_mismatch" in failure_set
  2468. ):
  2469. final_status = "blocked_debug_frame_loss"
  2470. elif any(item in failure_set for item in ["missing_timeout_debug_evidence", "timeout_ptc_not_zero", "timeout_fan_not_background_30"]):
  2471. final_status = "blocked_pwm_evidence_mismatch"
  2472. elif top_status.startswith("blocked_") and top_status not in allowed_top_statuses:
  2473. final_status = top_status
  2474. elif failures:
  2475. final_status = "fail"
  2476. else:
  2477. final_status = "pass"
  2478. return {
  2479. "schema": validation_schema,
  2480. "generated_at": utc_now(),
  2481. "status": final_status,
  2482. "strict": strict,
  2483. "receipt": str(receipt_path) if receipt_path is not None else None,
  2484. "receipt_status": top_status,
  2485. "host_ports": {"host": host_port, "debug": debug_port},
  2486. "debug_baud": debug_baud,
  2487. "host_commands": host_commands,
  2488. "host_ack": host_ack,
  2489. "bmc_sampling": {
  2490. "completed_samples": completed_samples,
  2491. "minimum_completed_samples": min_samples,
  2492. "bmc_timeout": bmc_timeout,
  2493. },
  2494. "sensor_reports": {
  2495. "sample_count": parsed_host["sample_count"],
  2496. "dimm_rows_per_sample": parsed_host["dimm_rows_per_sample"],
  2497. "all_ff_samples": parsed_host["all_ff_samples"],
  2498. },
  2499. "raw_replay": raw_replay,
  2500. "j6raw_frame_count": len(j6raw_frames),
  2501. "j6temp_count": len(j6temp_events),
  2502. "last_stat": last_stat,
  2503. "pid_boundary": {"pid_requested": pid_requested, "pid_active": pid_active, "pwm_source": pwm_source},
  2504. "timeout_evidence": timeout_evidence,
  2505. "debug_transcript": debug_transcript_result,
  2506. "host_transcript_text": host_text_result,
  2507. "host_sensor_report": host_sensor_report_result,
  2508. "raw_replay_artifact": raw_replay_result,
  2509. "debug_frame_stream": debug_frame_stream_result,
  2510. "host_command_transcript": host_transcript_result,
  2511. "manifest": manifest_result,
  2512. "bitstream": bitstream_result,
  2513. "failures": sorted(failure_set),
  2514. "warnings": sorted(set(warnings)),
  2515. "required_layers": required_layers,
  2516. "authority_boundary": authority_boundary,
  2517. }
  2518. def _validate_host_sensor_real_fan_ptc_host_ack(
  2519. receipt_path: Path | None,
  2520. layers: dict[str, Any],
  2521. failures: list[str],
  2522. ) -> tuple[list[str], dict[str, Any], dict[str, Any] | None]:
  2523. command_layer = layers.get("host_command_sequence") if isinstance(layers.get("host_command_sequence"), dict) else {}
  2524. layer_commands = command_layer.get("commands") if isinstance(command_layer.get("commands"), list) else []
  2525. host_commands = [str(command).strip() for command in layer_commands if str(command).strip()]
  2526. if not host_commands:
  2527. failures.append("missing_host_commands")
  2528. elif host_commands != REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_COMMANDS:
  2529. failures.append("host_command_sequence_mismatch")
  2530. for command in host_commands:
  2531. if not _host_sensor_real_fan_ptc_allowed_command(command):
  2532. failures.append(f"host_command_not_allowed:{command}")
  2533. host_transcript_layer = layers.get("host_control_transcript") if isinstance(layers.get("host_control_transcript"), dict) else {}
  2534. host_transcript_result, current_failures = _validate_real_bmc_artifact(
  2535. receipt_path,
  2536. host_transcript_layer,
  2537. "host_command_transcript",
  2538. "host_command_transcript",
  2539. )
  2540. failures.extend(current_failures)
  2541. host_transcript_payload, current_failures = _read_json_artifact(host_transcript_result, "host_command_transcript")
  2542. failures.extend(current_failures)
  2543. host_ack = {"status": "missing", "accepted": 0, "total": 0, "records": []}
  2544. if host_transcript_payload:
  2545. if str(host_transcript_payload.get("status") or "pass") != "pass":
  2546. failures.append(f"host_command_transcript_status_not_pass:{host_transcript_payload.get('status', 'missing')}")
  2547. if host_transcript_payload.get("host_port") != "COM8":
  2548. failures.append("host_transcript_port_not_com8")
  2549. if _safe_int(host_transcript_payload.get("baud"), default=115200) != 115200:
  2550. failures.append("host_transcript_baud_not_115200")
  2551. if host_transcript_payload.get("writes_to_serial") is not True:
  2552. failures.append("host_transcript_writes_to_serial_not_true")
  2553. if host_transcript_payload.get("write_port_role") != "HostPort":
  2554. failures.append("host_transcript_write_port_role_not_hostport")
  2555. if host_transcript_payload.get("debug_port_writes_to_serial") is not False:
  2556. failures.append("host_transcript_debug_port_writes_to_serial")
  2557. raw_commands = host_transcript_payload.get("commands") if isinstance(host_transcript_payload.get("commands"), list) else []
  2558. accepted = 0
  2559. records = []
  2560. for index, item in enumerate(raw_commands):
  2561. if not isinstance(item, dict):
  2562. failures.append(f"host_transcript_command_not_object:{index}")
  2563. continue
  2564. command = str(item.get("command") or "").strip()
  2565. records.append(item)
  2566. expected_command = (
  2567. REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_COMMANDS[index]
  2568. if index < len(REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_COMMANDS)
  2569. else ""
  2570. )
  2571. expected_ack_cmd = REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_ACK_CMDS.get(expected_command, "")
  2572. if not _host_sensor_real_fan_ptc_allowed_command(command):
  2573. failures.append(f"host_transcript_command_not_allowed:{index}:{command}")
  2574. if command != expected_command:
  2575. failures.append(f"host_transcript_command_mismatch:{index}")
  2576. if item.get("allowed") is not True:
  2577. failures.append(f"host_transcript_command_not_allowed_flag:{index}")
  2578. response_raw = str(item.get("response_raw") or item.get("ack_raw") or item.get("response") or item.get("ack_line") or "").strip()
  2579. response_class = str(item.get("response_class") or item.get("ack_status") or "").strip().lower()
  2580. response_seq = _safe_int(item.get("response_seq"), default=_safe_int(item.get("ack_seq"), default=None))
  2581. response_cmd = str(item.get("response_cmd") or item.get("ack_cmd") or "").strip()
  2582. strict_match = (
  2583. response_class == "ok"
  2584. and response_seq == index + 1
  2585. and response_cmd == expected_ack_cmd
  2586. and response_raw == f"OK seq={index + 1:08X} cmd={expected_ack_cmd}"
  2587. and item.get("seq_match") is True
  2588. and item.get("cmd_match") is True
  2589. and item.get("stale") is not True
  2590. )
  2591. if strict_match:
  2592. accepted += 1
  2593. else:
  2594. failures.append(f"host_ack_not_ok:{index}")
  2595. if response_class != "ok":
  2596. failures.append(f"host_ack_class_not_ok:{index}:{response_class or 'missing'}")
  2597. if response_seq != index + 1:
  2598. failures.append(f"host_ack_seq_mismatch:{index}")
  2599. if response_cmd != expected_ack_cmd:
  2600. failures.append(f"host_ack_cmd_mismatch:{index}")
  2601. if response_raw != f"OK seq={index + 1:08X} cmd={expected_ack_cmd}":
  2602. failures.append(f"host_ack_line_mismatch:{index}")
  2603. if item.get("stale") is True:
  2604. failures.append(f"host_ack_stale:{index}")
  2605. if len(raw_commands) != len(host_commands):
  2606. failures.append("host_ack_command_count_mismatch")
  2607. transcript_commands = [str(item.get("command") or "").strip() for item in raw_commands if isinstance(item, dict)]
  2608. if transcript_commands != REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_COMMANDS:
  2609. failures.append("host_transcript_command_sequence_mismatch")
  2610. host_ack = {
  2611. "status": "pass" if accepted == len(raw_commands) and len(raw_commands) == len(host_commands) else "fail",
  2612. "accepted": accepted,
  2613. "total": len(raw_commands),
  2614. "records": records,
  2615. }
  2616. return host_commands, host_ack, host_transcript_result
  2617. def validate_real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt(
  2618. receipt: dict[str, Any] | Path | str,
  2619. *,
  2620. strict: bool = False,
  2621. ) -> dict[str, Any]:
  2622. receipt_path: Path | None = None
  2623. if isinstance(receipt, dict):
  2624. payload = receipt
  2625. else:
  2626. receipt_path = Path(receipt)
  2627. payload = read_json(receipt_path)
  2628. top_status = str(payload.get("status") or "missing")
  2629. layers = payload.get("layers") if isinstance(payload.get("layers"), dict) else {}
  2630. base = _validate_host_sensor_debug921_common(
  2631. receipt,
  2632. strict=strict,
  2633. schema_name="real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1-receipt-v1",
  2634. schema_file="real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt.schema.json",
  2635. diagnostic_scope="host_sensor_real_fan_ptc_debug921",
  2636. required_layers=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_REQUIRED_LAYERS,
  2637. allowed_layers=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_LAYER_SET,
  2638. allowed_top_module=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_TOP_MODULE,
  2639. expected_commands=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_COMMANDS,
  2640. expected_ack_cmds=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_EXPECTED_ACK_CMDS,
  2641. allowed_command=_host_sensor_real_fan_ptc_allowed_command,
  2642. expected_fan_count=4,
  2643. validation_schema="real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1-validation-v1",
  2644. authority_boundary=(
  2645. "real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1 validates SRAM-only COM8 "
  2646. "host 1-based real FAN/PTC command evidence, COM7 debug921 frame replay, BMC "
  2647. "raw DIMM sampling, HostPort temperature reporting, PID requested-but-inactive "
  2648. "boundary, timeout fallback, and real FAN/PTC hardware status. It does not "
  2649. "satisfy final-gate-v2, real-bmc-j6-windows-gate-v2, flash, thermal performance, "
  2650. "production PTC/FAN qualification, or real PID closed-loop pass."
  2651. ),
  2652. allowed_top_statuses={"not_run", "blocked_waiting_for_real_fan_ptc_hardware"},
  2653. ignored_layer_status_failures={
  2654. "blocked_layer:real_fan_ptc_hardware_status",
  2655. "fail_layer:real_fan_ptc_hardware_status:not_run",
  2656. },
  2657. host_sensor_report_schemas={
  2658. "j6-host-sensor-real-fan-ptc-host-sensor-report-v1",
  2659. },
  2660. debug_frame_stream_schemas={
  2661. "j6-host-sensor-real-fan-ptc-debug-frame-stream-v1",
  2662. },
  2663. allowed_pin_profiles=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_PIN_PROFILES,
  2664. allowed_top_modules_by_pin_profile=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_ALLOWED_TOP_MODULES_BY_PIN_PROFILE,
  2665. required_safety_false_fields=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_REQUIRED_SAFETY_FALSE_FIELDS,
  2666. forbidden_action_markers=REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_FORBIDDEN_ACTION_MARKERS,
  2667. td_top_failure_name="td_bitstream_not_host_sensor_real_fan_ptc_top",
  2668. )
  2669. failures = [str(item) for item in base.get("failures", [])]
  2670. warnings = [str(item) for item in base.get("warnings", [])]
  2671. pin_map_layer = layers.get("pin_map") if isinstance(layers.get("pin_map"), dict) else {}
  2672. if _safe_int(pin_map_layer.get("fan_fg_count"), default=8) != 8:
  2673. failures.append("pin_map_fan_fg_count_not_8")
  2674. if _safe_int(pin_map_layer.get("fan_install_count"), default=4) != 4:
  2675. failures.append("pin_map_fan_install_count_not_4")
  2676. hardware_layer = layers.get("real_fan_ptc_hardware_status") if isinstance(layers.get("real_fan_ptc_hardware_status"), dict) else {}
  2677. hardware_status = str(hardware_layer.get("status") or "missing")
  2678. hardware_summary = {
  2679. "status": hardware_status,
  2680. "real_fan_ptc_hardware_present": hardware_layer.get("real_fan_ptc_hardware_present"),
  2681. "qualifies_final_gate": bool(hardware_layer.get("qualifies_final_gate")),
  2682. }
  2683. if hardware_status == "not_run":
  2684. failures.append("real_fan_ptc_hardware_not_run")
  2685. elif hardware_status == "blocked_waiting_for_real_fan_ptc_hardware":
  2686. failures.append("real_fan_ptc_hardware_blocked_waiting")
  2687. else:
  2688. failures.append(f"real_fan_ptc_hardware_status_not_not_run_or_blocked:{hardware_status}")
  2689. if hardware_layer.get("qualifies_final_gate") is not False:
  2690. failures.append("real_fan_ptc_hardware_qualifies_final_gate")
  2691. if hardware_layer.get("real_fan_ptc_hardware_present") not in (False, None):
  2692. failures.append("real_fan_ptc_hardware_present_claimed")
  2693. failure_set = set(failures)
  2694. joined = "\n".join(failure_set)
  2695. if (
  2696. "programming_not_sram" in failure_set
  2697. or "collector_debug_port_writes_to_serial" in failure_set
  2698. or "host_transcript_debug_port_writes_to_serial" in failure_set
  2699. or "collector_opens_unknown_com_ports" in failure_set
  2700. or "collector_enumerates_com_ports" in failure_set
  2701. or "collector_dtr_enabled" in failure_set
  2702. or "collector_rts_enabled" in failure_set
  2703. or "host_command_not_allowed:" in joined
  2704. or "host_transcript_command_not_allowed:" in joined
  2705. or any(item.startswith("forbidden_action_marker:") for item in failure_set)
  2706. or any(item.startswith("artifact_forbidden_action_marker:") for item in failure_set)
  2707. or any(item.startswith("safety_flag:") for item in failure_set)
  2708. ):
  2709. final_status = "fail_forbidden_action"
  2710. elif "blocked_host_epoch_mixed" in failure_set:
  2711. final_status = "blocked_host_epoch_mixed"
  2712. elif (
  2713. "host_preflight_epoch_not_locked" in failure_set
  2714. or any(item.startswith("host_preflight_not_pass:blocked_waiting_for_ready_epoch") for item in failure_set)
  2715. ):
  2716. final_status = "blocked_waiting_for_ready_epoch"
  2717. elif any(item.startswith("host_ack_") for item in failure_set):
  2718. final_status = "blocked_host_ack"
  2719. 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):
  2720. final_status = "blocked_uart_error"
  2721. elif "raw_drop_nonzero" in failure_set:
  2722. final_status = "blocked_cpld_raw_drop"
  2723. elif "host_report_drop_nonzero" in failure_set:
  2724. final_status = "blocked_host_report_drop"
  2725. elif "bmc_timeout_observed" in failure_set:
  2726. final_status = "blocked_bmc_timeout"
  2727. elif any(
  2728. item.endswith("_dimm_rows_not_24")
  2729. or item in {
  2730. "missing_host_sensor_samples",
  2731. "host_sensor_report_missing_samples",
  2732. "host_sensor_report_sample_count_mismatch",
  2733. "host_sensor_report_completed_sample_count_mismatch",
  2734. "host_sensor_report_dimm_row_sample_count_mismatch",
  2735. "sampling_host_sample_count_mismatch",
  2736. "debug_temp_sample_count_lt_host",
  2737. }
  2738. or item.startswith("host_sensor_report_sample_")
  2739. for item in failure_set
  2740. ):
  2741. final_status = "blocked_sensor_report_mismatch"
  2742. elif (
  2743. any(item.startswith("raw_frame_") for item in failure_set)
  2744. or "raw_in_replay_len_mismatch" in failure_set
  2745. or "raw_out_replay_len_mismatch" in failure_set
  2746. or "raw_replay_artifact_mismatch" in failure_set
  2747. or "missing_j6raw_frames" in failure_set
  2748. or "debug_frame_stream_missing_frames" in failure_set
  2749. or "debug_frame_stream_transcript_mismatch" in failure_set
  2750. ):
  2751. final_status = "blocked_debug_frame_loss"
  2752. elif any(item in failure_set for item in ["missing_timeout_debug_evidence", "timeout_ptc_not_zero", "timeout_fan_not_background_30"]):
  2753. final_status = "blocked_pwm_evidence_mismatch"
  2754. elif failure_set and failure_set <= {
  2755. "real_fan_ptc_hardware_not_run",
  2756. "real_fan_ptc_hardware_blocked_waiting",
  2757. }:
  2758. final_status = "blocked_waiting_for_real_fan_ptc_hardware"
  2759. elif failures:
  2760. final_status = "fail"
  2761. else:
  2762. final_status = "blocked_waiting_for_real_fan_ptc_hardware"
  2763. return {
  2764. "schema": "real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1-validation-v1",
  2765. "generated_at": utc_now(),
  2766. "status": final_status,
  2767. "strict": strict,
  2768. "receipt": str(receipt_path) if receipt_path is not None else None,
  2769. "receipt_status": top_status,
  2770. "host_ports": base.get("host_ports", {}),
  2771. "debug_baud": base.get("debug_baud"),
  2772. "host_commands": base.get("host_commands", []),
  2773. "host_ack": base.get("host_ack", {}),
  2774. "bmc_sampling": base.get("bmc_sampling", {}),
  2775. "sensor_reports": base.get("sensor_reports", {}),
  2776. "raw_replay": base.get("raw_replay", {}),
  2777. "j6raw_frame_count": base.get("j6raw_frame_count", 0),
  2778. "j6temp_count": base.get("j6temp_count", 0),
  2779. "last_stat": base.get("last_stat"),
  2780. "pid_boundary": base.get("pid_boundary", {}),
  2781. "timeout_evidence": base.get("timeout_evidence", {}),
  2782. "real_fan_ptc_hardware_status": hardware_summary,
  2783. "pin_map": {
  2784. "status": pin_map_layer.get("status"),
  2785. "ptc_count": pin_map_layer.get("ptc_count"),
  2786. "fan_count": pin_map_layer.get("fan_count"),
  2787. "fan_fg_count": pin_map_layer.get("fan_fg_count"),
  2788. "fan_install_count": pin_map_layer.get("fan_install_count"),
  2789. },
  2790. "debug_transcript": base.get("debug_transcript"),
  2791. "host_transcript_text": base.get("host_transcript_text"),
  2792. "host_sensor_report": base.get("host_sensor_report"),
  2793. "raw_replay_artifact": base.get("raw_replay_artifact"),
  2794. "debug_frame_stream": base.get("debug_frame_stream"),
  2795. "host_command_transcript": base.get("host_command_transcript"),
  2796. "manifest": base.get("manifest"),
  2797. "bitstream": base.get("bitstream"),
  2798. "failures": sorted(failure_set),
  2799. "warnings": sorted(set(warnings)),
  2800. "required_layers": REAL_BMC_J6_HOST_SENSOR_REAL_FAN_PTC_REQUIRED_LAYERS,
  2801. "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.",
  2802. }
  2803. def validate_cpld_bmc_acceptance_v1_receipt(receipt: dict[str, Any] | Path | str, *, strict: bool = False) -> dict[str, Any]:
  2804. receipt_path: Path | None = None
  2805. if isinstance(receipt, dict):
  2806. payload = receipt
  2807. else:
  2808. receipt_path = Path(receipt)
  2809. payload = read_json(receipt_path)
  2810. failures: list[str] = []
  2811. child_results: dict[str, Any] = {}
  2812. if payload.get("schema") != "cpld-bmc-acceptance-v1-receipt-v1":
  2813. failures.append("fail_schema")
  2814. failures.extend(_validate_json_schema_file(payload, "cpld_bmc_acceptance_v1_receipt.schema.json", required=False))
  2815. top_status = str(payload.get("status") or "missing")
  2816. if top_status != "pass":
  2817. failures.append(f"top_status_not_pass:{top_status}")
  2818. layers = payload.get("layers") or {}
  2819. if not isinstance(layers, dict):
  2820. layers = {}
  2821. failures.append("layers_not_object")
  2822. validators = {
  2823. "final_gate_v2": validate_final_gate_v2_receipt,
  2824. "real_bmc_j6_windows_gate_v2": validate_real_bmc_j6_windows_gate_v2_receipt,
  2825. }
  2826. for name, validator in validators.items():
  2827. layer = layers.get(name)
  2828. if not isinstance(layer, dict):
  2829. failures.append(f"missing_layer:{name}")
  2830. continue
  2831. if str(layer.get("status") or "missing") != "pass":
  2832. failures.append(f"fail_layer:{name}:{layer.get('status', 'missing')}")
  2833. artifact_result, artifact_failures = _validate_real_bmc_artifact(receipt_path, layer, "receipt", name)
  2834. failures.extend(artifact_failures)
  2835. if isinstance(artifact_result, dict) and artifact_result.get("exists"):
  2836. try:
  2837. child = validator(Path(str(artifact_result["path"])), strict=True)
  2838. except Exception as exc: # noqa: BLE001
  2839. failures.append(f"{name}_unreadable:{exc.__class__.__name__}")
  2840. child = {"status": "fail", "failures": [f"unreadable:{exc.__class__.__name__}"]}
  2841. child_results[name] = child
  2842. if child.get("status") != "pass":
  2843. failures.append(f"{name}_not_pass:{child.get('status', 'unknown')}")
  2844. else:
  2845. child_results[name] = {"status": "missing", "artifact": artifact_result}
  2846. for layer in sorted(set(layers) - set(validators)):
  2847. failures.append(f"undeclared_layer:{layer}")
  2848. if strict:
  2849. authority = str(payload.get("authority_boundary") or "").lower()
  2850. if "thermal performance pass" in authority or "thermal_performance_pass" in authority:
  2851. failures.append("authority_overclaim_thermal_performance")
  2852. if "flash pass" in authority or "program_flash pass" in authority:
  2853. failures.append("authority_overclaim_flash")
  2854. return {
  2855. "schema": "cpld-bmc-acceptance-v1-validation-v1",
  2856. "generated_at": utc_now(),
  2857. "status": "pass" if not failures else "fail",
  2858. "strict": strict,
  2859. "receipt": str(receipt_path) if receipt_path is not None else None,
  2860. "receipt_status": top_status,
  2861. "children": child_results,
  2862. "failures": sorted(set(failures)),
  2863. "required_layers": sorted(validators),
  2864. "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.",
  2865. }
  2866. def _extract_status(receipt: dict[str, Any]) -> str:
  2867. return str(receipt.get("status") or "fail_missing_status")
  2868. def _schema_status(receipt: dict[str, Any]) -> str:
  2869. schema = str(receipt.get("schema") or "")
  2870. return UART_SCHEMAS.get(schema, "unknown-uart-validation-v1")
  2871. def build_protocol_offline_receipt(*, text: str, scenario: str) -> dict[str, Any]:
  2872. from pid_contract_model import BmcDimmFrameParser, PARSER_STATUS_OK
  2873. parser = BmcDimmFrameParser(fraction_scale=100)
  2874. result = parser.parse_text_response(text, frame_seq=1, sample_seq_base=0, age_ms=0)
  2875. status = "pass" if result.parser_status == PARSER_STATUS_OK and len(result.samples) == 24 else "fail_protocol_parse"
  2876. return {
  2877. "schema": "bmc-uart-protocol-receipt-v1",
  2878. "status": status,
  2879. "generated_at": utc_now(),
  2880. "scenario": scenario,
  2881. "counterparty": "pc_emulator",
  2882. "parser": {
  2883. "status": result.parser_status,
  2884. "sample_count": len(result.samples),
  2885. "missing_mask": result.missing_mask,
  2886. "raw_token_count": result.raw_token_count,
  2887. "selected_window_start": result.selected_window_start,
  2888. "rejected_echo_windows": result.rejected_echo_windows,
  2889. },
  2890. "safety": {"flash_attempted": False, "real_ptc_fan_bmc_action_attempted": False, "driver_install_attempted": False},
  2891. "authority_boundary": "Offline parser evidence proves loose text BMC protocol handling only; it does not prove electrical UART timing or board wiring.",
  2892. }
  2893. def validate_uart_receipt(receipt_path: Path | str, *, strict: bool = False) -> dict[str, Any]:
  2894. path = Path(receipt_path)
  2895. receipt = read_json(path)
  2896. schema = str(receipt.get("schema") or "")
  2897. failures: list[str] = []
  2898. warnings: list[str] = []
  2899. if schema not in UART_SCHEMAS:
  2900. failures.append("fail_schema")
  2901. safety_failures = _validate_safety(receipt)
  2902. failures.extend(safety_failures)
  2903. status_value = _extract_status(receipt)
  2904. validation_schema = _schema_status(receipt)
  2905. transcript_required_schemas = {"uart-loopback-receipt-v1", "uart-board-sram-receipt-v1"}
  2906. transcript_result = _hash_validation(path, receipt.get("transcript"), required=schema in transcript_required_schemas)
  2907. if strict and schema in transcript_required_schemas and not (receipt.get("transcript") or {}).get("sha256"):
  2908. failures.append("missing_transcript_hash")
  2909. if transcript_result["status"] in {"missing", "hash_mismatch"} and schema in transcript_required_schemas:
  2910. failures.append(f"transcript_{transcript_result['status']}")
  2911. programming_result = None
  2912. if schema == "uart-board-sram-receipt-v1":
  2913. programming = receipt.get("programming") or {}
  2914. if programming.get("mode") != "PROGRAM_SRAM":
  2915. failures.append("programming_not_sram")
  2916. bitstream = programming.get("bitstream")
  2917. programming_result = _hash_validation(path, bitstream, required=True)
  2918. if strict and programming_result["status"] == "missing_hash":
  2919. failures.append("missing_bitstream_hash")
  2920. elif programming_result["status"] in {"missing", "hash_mismatch"}:
  2921. failures.append(f"bitstream_{programming_result['status']}")
  2922. serial = receipt.get("serial") or {}
  2923. if schema in {"uart-preflight-receipt-v1", "uart-loopback-receipt-v1", "uart-board-sram-receipt-v1"}:
  2924. if int(serial.get("baud") or 0) != 115200:
  2925. failures.append("serial_baud_not_115200")
  2926. if str(serial.get("format") or "").upper() != "8N1":
  2927. failures.append("serial_format_not_8n1")
  2928. if strict and serial.get("allowlisted") is not True:
  2929. failures.append("serial_not_allowlisted")
  2930. if strict and schema == "uart-preflight-receipt-v1" and serial.get("opened") is True:
  2931. failures.append("preflight_must_not_open_com")
  2932. debug_evidence = receipt.get("debug_evidence") or {}
  2933. if schema == "uart-board-sram-receipt-v1":
  2934. for field in ["event_stream", "register_dump"]:
  2935. evidence_path = debug_evidence.get(field)
  2936. if not evidence_path:
  2937. failures.append(f"missing_debug_{field}")
  2938. continue
  2939. resolved = _resolve_receipt_path(path, evidence_path)
  2940. if not resolved.is_file():
  2941. failures.append(f"missing_debug_{field}")
  2942. if receipt.get("counterparty") not in {"pc_emulator", "real_bmc"}:
  2943. failures.append("counterparty_not_declared")
  2944. if schema == "uart-soak-receipt-v1":
  2945. rounds = receipt.get("rounds") or []
  2946. if not rounds:
  2947. failures.append("missing_soak_rounds")
  2948. for item in rounds:
  2949. round_status = str((item or {}).get("status") or "missing")
  2950. round_index = str((item or {}).get("index") or "?")
  2951. if round_status.startswith("blocked_"):
  2952. failures.append(f"blocked_soak_round:{round_index}")
  2953. elif round_status != "pass":
  2954. failures.append(f"fail_soak_round:{round_index}:{round_status}")
  2955. round_receipt = (item or {}).get("receipt")
  2956. if strict and not round_receipt:
  2957. failures.append(f"missing_soak_round_receipt:{round_index}")
  2958. elif strict and round_receipt:
  2959. nested_path = _resolve_receipt_path(path, round_receipt)
  2960. nested = validate_uart_receipt(nested_path, strict=True)
  2961. if nested["status"] != "pass":
  2962. failures.append(f"fail_soak_round_receipt:{round_index}:{nested['status']}")
  2963. if "forbidden_action_marker" in safety_failures or "safety_flag:flash_attempted" in safety_failures:
  2964. final_status = "fail_forbidden_action"
  2965. elif status_value.startswith("blocked_"):
  2966. final_status = status_value
  2967. elif status_value.startswith("fail_"):
  2968. final_status = status_value
  2969. elif failures:
  2970. if "serial_not_allowlisted" in failures:
  2971. final_status = "blocked_no_allowlist"
  2972. else:
  2973. final_status = "fail"
  2974. else:
  2975. final_status = "pass"
  2976. return {
  2977. "schema": validation_schema,
  2978. "generated_at": utc_now(),
  2979. "status": final_status,
  2980. "receipt": str(path),
  2981. "strict": strict,
  2982. "receipt_status": status_value,
  2983. "backend_capabilities": backend_capabilities(),
  2984. "transcript": transcript_result,
  2985. "programming": programming_result,
  2986. "failures": sorted(set(failures)),
  2987. "warnings": sorted(set(warnings)),
  2988. "authority_boundary": "UART receipt proves communication evidence and software safety strategy only. It does not certify thermal performance.",
  2989. }
  2990. def validate_final_gate_v2_receipt(receipt: dict[str, Any] | Path | str, *, strict: bool = False) -> dict[str, Any]:
  2991. if not isinstance(receipt, dict):
  2992. receipt = read_json(Path(receipt))
  2993. failures: list[str] = []
  2994. if receipt.get("schema") != "final-gate-v2-receipt-v1":
  2995. failures.append("fail_schema")
  2996. top_status = str(receipt.get("status") or "missing")
  2997. if top_status != "pass":
  2998. failures.append(f"top_status_not_pass:{top_status}")
  2999. layers = receipt.get("layers") or {}
  3000. for layer in FINAL_GATE_REQUIRED_LAYERS:
  3001. item = layers.get(layer)
  3002. status = str((item or {}).get("status") or "missing")
  3003. if status == "missing":
  3004. failures.append(f"missing_layer:{layer}")
  3005. elif status.startswith("blocked_"):
  3006. failures.append(f"blocked_layer:{layer}")
  3007. elif status != "pass":
  3008. failures.append(f"fail_layer:{layer}:{status}")
  3009. if "chipwatcher" in layers:
  3010. failures.append("forbidden_chipwatcher_layer")
  3011. if strict and "thermal_performance_pass" in str(receipt.get("authority_boundary") or "").lower():
  3012. failures.append("authority_overclaim_thermal_performance")
  3013. return {
  3014. "schema": "final-gate-v2-validation-v1",
  3015. "generated_at": utc_now(),
  3016. "status": "pass" if not failures else "fail",
  3017. "strict": strict,
  3018. "failures": sorted(set(failures)),
  3019. "required_layers": FINAL_GATE_REQUIRED_LAYERS,
  3020. "authority_boundary": "final-gate-v2 pass means software/control communication evidence passed. It does not certify full thermal performance.",
  3021. }
  3022. def validate_offline_fidelity_gate_v1_receipt(receipt: dict[str, Any] | Path | str, *, strict: bool = False) -> dict[str, Any]:
  3023. if not isinstance(receipt, dict):
  3024. receipt = read_json(Path(receipt))
  3025. failures: list[str] = []
  3026. if receipt.get("schema") != "offline-fidelity-gate-v1-receipt-v1":
  3027. failures.append("fail_schema")
  3028. top_status = str(receipt.get("status") or "missing")
  3029. if top_status != "pass":
  3030. failures.append(f"top_status_not_pass:{top_status}")
  3031. layers = receipt.get("layers") or {}
  3032. if not isinstance(layers, dict):
  3033. layers = {}
  3034. failures.append("layers_not_object")
  3035. toolchain = receipt.get("toolchain") or {}
  3036. if not isinstance(toolchain, dict):
  3037. toolchain = {}
  3038. failures.append("toolchain_not_object")
  3039. toolchain_status = str(toolchain.get("status") or "missing")
  3040. if toolchain_status != "pass":
  3041. failures.append(f"toolchain_status_not_pass:{toolchain_status}")
  3042. failures.extend(_validate_toolchain_evidence(toolchain))
  3043. top_safety = receipt.get("safety")
  3044. if not isinstance(top_safety, dict):
  3045. failures.append("missing_safety")
  3046. top_safety = {}
  3047. for field in ["opens_com_ports", "toggles_dtr_rts", "programs_flash", "installs_drivers", "real_ptc_fan_bmc_action_attempted"]:
  3048. if top_safety.get(field) is not False:
  3049. failures.append(f"safety_not_false:{field}")
  3050. toolchain_safety = toolchain.get("safety")
  3051. if not isinstance(toolchain_safety, dict):
  3052. failures.append("missing_toolchain_safety")
  3053. toolchain_safety = {}
  3054. for field in ["opens_com_ports", "toggles_dtr_rts", "installs_drivers", "programs_flash", "touches_ptc_fan_bmc"]:
  3055. if toolchain_safety.get(field) is not False:
  3056. failures.append(f"toolchain_safety_not_false:{field}")
  3057. for layer in OFFLINE_FIDELITY_REQUIRED_LAYERS:
  3058. item = layers.get(layer)
  3059. status = str((item or {}).get("status") or "missing")
  3060. if status == "missing":
  3061. failures.append(f"missing_layer:{layer}")
  3062. elif status.startswith("blocked_"):
  3063. failures.append(f"blocked_layer:{layer}")
  3064. elif status != "pass":
  3065. failures.append(f"fail_layer:{layer}:{status}")
  3066. elif isinstance(item, dict):
  3067. failures.extend(_validate_offline_layer_evidence(layer, item))
  3068. layer_safety = (item or {}).get("safety")
  3069. if isinstance(layer_safety, dict):
  3070. for field in [
  3071. "opens_com_ports",
  3072. "toggles_dtr_rts",
  3073. "installs_drivers",
  3074. "programs_flash",
  3075. "touches_ptc_fan_bmc",
  3076. "real_ptc_fan_bmc_action_attempted",
  3077. ]:
  3078. if field in layer_safety and layer_safety.get(field) is not False:
  3079. failures.append(f"layer_safety_not_false:{layer}:{field}")
  3080. for layer in sorted(set(layers) - set(OFFLINE_FIDELITY_REQUIRED_LAYERS)):
  3081. failures.append(f"undeclared_layer:{layer}")
  3082. for layer in sorted(set(layers) & OFFLINE_FIDELITY_FORBIDDEN_LAYERS):
  3083. failures.append(f"forbidden_layer:{layer}")
  3084. for marker in _forbidden_action_markers(receipt, OFFLINE_FIDELITY_FORBIDDEN_ACTION_MARKERS):
  3085. failures.append(f"forbidden_action_marker:{marker}")
  3086. if strict:
  3087. authority = str(receipt.get("authority_boundary") or "").lower()
  3088. if "thermal_performance_pass" in authority or "thermal performance pass" in authority:
  3089. failures.append("authority_overclaim_thermal_performance")
  3090. if "hardware pass" in authority or "board pass" in authority:
  3091. failures.append("authority_overclaim_hardware")
  3092. if "uart_strict pass" in authority or "uart strict pass" in authority:
  3093. failures.append("authority_overclaim_uart_strict")
  3094. if "chipwatcher pass" in authority or "chipwatcher evidence passed" in authority:
  3095. failures.append("authority_overclaim_chipwatcher")
  3096. return {
  3097. "schema": "offline-fidelity-gate-v1-validation-v1",
  3098. "generated_at": utc_now(),
  3099. "status": "pass" if not failures else "fail",
  3100. "strict": strict,
  3101. "failures": sorted(set(failures)),
  3102. "required_layers": OFFLINE_FIDELITY_REQUIRED_LAYERS,
  3103. "forbidden_layers": sorted(OFFLINE_FIDELITY_FORBIDDEN_LAYERS),
  3104. "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.",
  3105. }
  3106. def enumerate_serial_ports_powershell() -> dict[str, Any]:
  3107. command = [
  3108. "powershell",
  3109. "-NoProfile",
  3110. "-Command",
  3111. "Get-CimInstance Win32_PnPEntity | Where-Object { $_.Name -match 'COM[0-9]+' } | Select-Object Name,DeviceID | ConvertTo-Json -Compress",
  3112. ]
  3113. try:
  3114. result = subprocess.run(command, cwd=ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=20)
  3115. except (OSError, subprocess.TimeoutExpired) as exc:
  3116. return {"status": "blocked_serial_enumeration_failed", "error": str(exc), "ports": []}
  3117. ports: list[dict[str, Any]] = []
  3118. if result.returncode == 0 and result.stdout.strip():
  3119. try:
  3120. data = json.loads(result.stdout)
  3121. if isinstance(data, dict):
  3122. data = [data]
  3123. for item in data if isinstance(data, list) else []:
  3124. ports.append({"name": item.get("Name"), "device_id": item.get("DeviceID")})
  3125. except json.JSONDecodeError:
  3126. pass
  3127. return {
  3128. "status": "pass" if result.returncode == 0 else "blocked_serial_enumeration_failed",
  3129. "backend": "powershell_dotnet_limited",
  3130. "opened_com": False,
  3131. "ports": ports,
  3132. "stderr": result.stderr[-1000:],
  3133. }
  3134. def build_preflight_receipt(*, allowlist: list[str] | None = None) -> dict[str, Any]:
  3135. ports = enumerate_serial_ports_powershell()
  3136. allow = allowlist or []
  3137. discovered = json.dumps(ports.get("ports", []))
  3138. allowlisted = bool(allow and any(port in discovered for port in allow))
  3139. status = "pass" if ports["status"] == "pass" and allowlisted else ("blocked_no_allowlist" if ports["status"] == "pass" else ports["status"])
  3140. return {
  3141. "schema": "uart-preflight-receipt-v1",
  3142. "status": status,
  3143. "generated_at": utc_now(),
  3144. "serial": {"baud": 115200, "format": "8N1", "allowlisted": allowlisted, "opened": False, "allowlist": allow},
  3145. "enumeration": ports,
  3146. "safety": {"flash_attempted": False, "real_ptc_fan_bmc_action_attempted": False, "driver_install_attempted": False},
  3147. "authority_boundary": "Preflight only enumerates COM candidates; it must not open unknown ports or toggle DTR/RTS.",
  3148. }
  3149. def write_json(payload: dict[str, Any], path: Path) -> None:
  3150. path.parent.mkdir(parents=True, exist_ok=True)
  3151. path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
  3152. def build_parser() -> argparse.ArgumentParser:
  3153. parser = argparse.ArgumentParser(description=__doc__)
  3154. sub = parser.add_subparsers(dest="command", required=True)
  3155. preflight = sub.add_parser("preflight")
  3156. preflight.add_argument("--allowlist", action="append", default=[])
  3157. preflight.add_argument("--json", action="store_true")
  3158. preflight.add_argument("--report-file", type=Path)
  3159. preflight.set_defaults(func=cmd_preflight)
  3160. protocol = sub.add_parser("protocol-offline")
  3161. protocol.add_argument("--text-file", type=Path, required=True)
  3162. protocol.add_argument("--scenario", default="manual_text")
  3163. protocol.add_argument("--json", action="store_true")
  3164. protocol.add_argument("--report-file", type=Path)
  3165. protocol.set_defaults(func=cmd_protocol_offline)
  3166. validate = sub.add_parser("validate")
  3167. validate.add_argument("--receipt", type=Path, required=True)
  3168. validate.add_argument("--strict", action="store_true")
  3169. validate.add_argument("--json", action="store_true")
  3170. validate.add_argument("--report-file", type=Path)
  3171. validate.set_defaults(func=cmd_validate)
  3172. final = sub.add_parser("final-gate-v2-validate")
  3173. final.add_argument("--receipt", type=Path, required=True)
  3174. final.add_argument("--strict", action="store_true")
  3175. final.add_argument("--json", action="store_true")
  3176. final.add_argument("--report-file", type=Path)
  3177. final.set_defaults(func=cmd_final_validate)
  3178. offline = sub.add_parser("offline-fidelity-gate-v1-validate")
  3179. offline.add_argument("--receipt", type=Path, required=True)
  3180. offline.add_argument("--strict", action="store_true")
  3181. offline.add_argument("--json", action="store_true")
  3182. offline.add_argument("--report-file", type=Path)
  3183. offline.set_defaults(func=cmd_offline_validate)
  3184. real_bmc_windows = sub.add_parser("real-bmc-j6-windows-gate-v2-validate")
  3185. real_bmc_windows.add_argument("--receipt", type=Path, required=True)
  3186. real_bmc_windows.add_argument("--strict", action="store_true")
  3187. real_bmc_windows.add_argument("--json", action="store_true")
  3188. real_bmc_windows.add_argument("--report-file", type=Path)
  3189. real_bmc_windows.set_defaults(func=cmd_real_bmc_j6_windows_validate)
  3190. host_sensor_real_fan_ptc = sub.add_parser("real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1-validate")
  3191. host_sensor_real_fan_ptc.add_argument("--receipt", type=Path, required=True)
  3192. host_sensor_real_fan_ptc.add_argument("--strict", action="store_true")
  3193. host_sensor_real_fan_ptc.add_argument("--json", action="store_true")
  3194. host_sensor_real_fan_ptc.add_argument("--report-file", type=Path)
  3195. host_sensor_real_fan_ptc.set_defaults(func=cmd_real_bmc_j6_host_sensor_real_fan_ptc_debug921_validate)
  3196. acceptance = sub.add_parser("cpld-bmc-acceptance-v1-validate")
  3197. acceptance.add_argument("--receipt", type=Path, required=True)
  3198. acceptance.add_argument("--strict", action="store_true")
  3199. acceptance.add_argument("--json", action="store_true")
  3200. acceptance.add_argument("--report-file", type=Path)
  3201. acceptance.set_defaults(func=cmd_cpld_bmc_acceptance_validate)
  3202. return parser
  3203. def cmd_preflight(args: argparse.Namespace) -> int:
  3204. payload = build_preflight_receipt(allowlist=args.allowlist)
  3205. if args.report_file:
  3206. write_json(payload, args.report_file)
  3207. print(json.dumps(payload, indent=2) if args.json else f"uart-preflight: {payload['status']}")
  3208. return 0 if payload["status"] == "pass" else 1
  3209. def cmd_protocol_offline(args: argparse.Namespace) -> int:
  3210. payload = build_protocol_offline_receipt(text=args.text_file.read_text(encoding="utf-8"), scenario=args.scenario)
  3211. if args.report_file:
  3212. write_json(payload, args.report_file)
  3213. print(json.dumps(payload, indent=2) if args.json else f"uart-protocol-offline: {payload['status']}")
  3214. return 0 if payload["status"] == "pass" else 1
  3215. def cmd_validate(args: argparse.Namespace) -> int:
  3216. payload = validate_uart_receipt(args.receipt, strict=args.strict)
  3217. if args.report_file:
  3218. write_json(payload, args.report_file)
  3219. print(json.dumps(payload, indent=2) if args.json else f"uart-validate: {payload['status']}")
  3220. return 0 if payload["status"] == "pass" else 1
  3221. def cmd_final_validate(args: argparse.Namespace) -> int:
  3222. payload = validate_final_gate_v2_receipt(args.receipt, strict=args.strict)
  3223. if args.report_file:
  3224. write_json(payload, args.report_file)
  3225. print(json.dumps(payload, indent=2) if args.json else f"final-gate-v2-validate: {payload['status']}")
  3226. return 0 if payload["status"] == "pass" else 1
  3227. def cmd_offline_validate(args: argparse.Namespace) -> int:
  3228. payload = validate_offline_fidelity_gate_v1_receipt(args.receipt, strict=args.strict)
  3229. if args.report_file:
  3230. write_json(payload, args.report_file)
  3231. print(json.dumps(payload, indent=2) if args.json else f"offline-fidelity-gate-v1-validate: {payload['status']}")
  3232. return 0 if payload["status"] == "pass" else 1
  3233. def cmd_real_bmc_j6_windows_validate(args: argparse.Namespace) -> int:
  3234. payload = validate_real_bmc_j6_windows_gate_v2_receipt(args.receipt, strict=args.strict)
  3235. if args.report_file:
  3236. write_json(payload, args.report_file)
  3237. print(json.dumps(payload, indent=2) if args.json else f"real-bmc-j6-windows-gate-v2-validate: {payload['status']}")
  3238. return 0 if payload["status"] == "pass" else 1
  3239. def cmd_real_bmc_j6_host_sensor_real_fan_ptc_debug921_validate(args: argparse.Namespace) -> int:
  3240. payload = validate_real_bmc_j6_host_sensor_real_fan_ptc_debug921_v1_receipt(args.receipt, strict=args.strict)
  3241. if args.report_file:
  3242. write_json(payload, args.report_file)
  3243. print(
  3244. json.dumps(payload, indent=2)
  3245. if args.json
  3246. else f"real-bmc-j6-host-sensor-real-fan-ptc-debug921-v1-validate: {payload['status']}"
  3247. )
  3248. return 0 if payload["status"] == "pass" else 1
  3249. def cmd_cpld_bmc_acceptance_validate(args: argparse.Namespace) -> int:
  3250. payload = validate_cpld_bmc_acceptance_v1_receipt(args.receipt, strict=args.strict)
  3251. if args.report_file:
  3252. write_json(payload, args.report_file)
  3253. print(json.dumps(payload, indent=2) if args.json else f"cpld-bmc-acceptance-v1-validate: {payload['status']}")
  3254. return 0 if payload["status"] == "pass" else 1
  3255. def main(argv: list[str] | None = None) -> int:
  3256. parser = build_parser()
  3257. args = parser.parse_args(argv)
  3258. return args.func(args)
  3259. if __name__ == "__main__":
  3260. raise SystemExit(main())