uart_receipts.py 166 KB

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