uart_receipts.py 181 KB

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