pid_harness.py 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570
  1. #!/usr/bin/env python3
  2. """Layered offline verification harness for pid_study_01."""
  3. from __future__ import annotations
  4. import argparse
  5. import csv
  6. import hashlib
  7. import importlib.util
  8. import json
  9. import os
  10. import re
  11. import shutil
  12. import socket
  13. import subprocess
  14. import sys
  15. import xml.etree.ElementTree as ET
  16. from datetime import datetime, timezone
  17. from pathlib import Path
  18. from typing import Any
  19. sys.dont_write_bytecode = True
  20. from pid_contract_model import (
  21. ACTUATOR_REASON_FAN_FALLBACK,
  22. ACTUATOR_REASON_HOST_TIMEOUT,
  23. ACTUATOR_REASON_OK,
  24. ACTUATOR_REASON_OVERTEMP,
  25. ACTUATOR_REASON_PID_OR_SENSOR_FAULT,
  26. ACTUATOR_REASON_SENSOR_STALE,
  27. ActuatorDomain,
  28. ActuatorSink,
  29. BMC_DIMM_USER_SAMPLE_TEXT,
  30. BMC_POLL_COMMAND_ASCII,
  31. BmcDimmFrameParser,
  32. FakeHostConfig,
  33. FakeStressModel,
  34. HostConfigV2,
  35. HostConfigStep,
  36. PARSER_STATUS_BAD_FRACTION,
  37. PARSER_STATUS_BAD_LENGTH,
  38. PARSER_STATUS_NO_CANDIDATE,
  39. PARSER_STATUS_OK,
  40. PidResult,
  41. SafetySupervisor,
  42. SensorSampleV2,
  43. ThermalControlService24Ch,
  44. TwentyFourChannelPid,
  45. load_contract_config,
  46. config_contract_summary,
  47. load_replay_expectations_csv,
  48. load_host_csv,
  49. load_sensor_csv,
  50. run_replay,
  51. verify_replay_expectations,
  52. )
  53. from debug_contract import (
  54. DEBUG_EVENT_REQUIRED_FIELDS,
  55. analyze_debug_bundle,
  56. build_debug_bundle,
  57. normalize_replay_trace,
  58. )
  59. from toolchain_probe import probe_toolchain
  60. from pin_inventory import diagnostic_profile_assignments, load_pin_inventory
  61. ROOT = Path(__file__).resolve().parents[1]
  62. TD_EXE = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412\bin\td_commands_prompt.exe")
  63. VERILATOR_LINT_MODE = "verilator --lint-only"
  64. DEFAULT_TOOLCHAIN_BASE = Path.home() / "CodexToolchains" / "CPLD"
  65. DEFAULT_OSS_CAD_SUITE_ROOT = DEFAULT_TOOLCHAIN_BASE / "oss-cad-suite" / "latest"
  66. DEFAULT_COCOTB_VENV_PYTHON = DEFAULT_TOOLCHAIN_BASE / "venvs" / "pid-study-cocotb-venv" / "Scripts" / "python.exe"
  67. COMPAT_COCOTB_VENV_PYTHON = DEFAULT_TOOLCHAIN_BASE / "venvs" / "pid-contract-cocotb-venv" / "Scripts" / "python.exe"
  68. TD_BUILD_SYN = ROOT / "td" / "build" / "syn"
  69. TD_BUILD_PHY = ROOT / "td" / "build" / "phy"
  70. EXTERNAL_TD_BIN_LOG = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412\bin\log")
  71. DEFAULT_TD_TOP = "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921"
  72. REAL_FAN_PTC_INVENTORY = ROOT / "config" / "pin_inventory.fcb_fpga_mcu0611.json"
  73. TD_TOP_PROFILES = {
  74. "system_contract": {
  75. "mode": "elaboration",
  76. "display_name": "unconstrained system contract logic top",
  77. "top_module": "system_contract_top",
  78. },
  79. "debug_max": {
  80. "mode": "elaboration",
  81. "display_name": "debug-max logic evidence top",
  82. "top_module": "system_contract_top",
  83. },
  84. "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921": {
  85. "mode": "implementation",
  86. "display_name": "J6 host sensor real FAN/PTC temporary UART diagnostic: current J6/COM7/COM8 wiring with six PTC channels remapped to verified spare GPIO",
  87. "top_module": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921_top",
  88. "source_prj": "td/uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921.prj",
  89. "build_subdir": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921",
  90. "syn_script": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921.tcl",
  91. "phy_script": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921.tcl",
  92. "bitstream": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921.bit",
  93. "area_report": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921_phy.area",
  94. "timing_report": "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921_pr.timing",
  95. "pin_profile": "temp-uart-ptc-remap",
  96. "tx_ball": "T4",
  97. "rx_ball": "R5",
  98. "host_uart_tx_ball": "P7",
  99. "host_uart_rx_ball": "P8",
  100. "debug_uart_rx_ball": "P10",
  101. "debug_uart_tx_ball": "R10",
  102. "host_uart_baud": 115200,
  103. "bmc_uart_baud": 115200,
  104. "debug_uart_baud": 921600,
  105. "debug_uart_clks_per_bit": 27,
  106. "requires_verified_real_fan_ptc_pin_map": True,
  107. "authority_boundary": "SRAM-only temp-uart-ptc-remap diagnostic evidence for current J6/COM7/COM8 wiring. Six overlapping PTC outputs are substituted; it does not claim real thermal performance, production PTC/FAN qualification, flash, or PID closed-loop pass.",
  108. },
  109. "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921": {
  110. "mode": "implementation",
  111. "display_name": "J6 host sensor real FAN/PTC formal UART diagnostic: schematic FAN/PTC pins retained and three diagnostic UARTs moved to spare GPIO",
  112. "top_module": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921_top",
  113. "source_prj": "td/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921.prj",
  114. "build_subdir": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921",
  115. "syn_script": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921.tcl",
  116. "phy_script": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921.tcl",
  117. "bitstream": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921.bit",
  118. "area_report": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921_phy.area",
  119. "timing_report": "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921_pr.timing",
  120. "pin_profile": "formal-uart",
  121. "tx_ball": "P5",
  122. "rx_ball": "T8",
  123. "host_uart_tx_ball": "M14",
  124. "host_uart_rx_ball": "M15",
  125. "debug_uart_rx_ball": "P15",
  126. "debug_uart_tx_ball": "N14",
  127. "host_uart_baud": 115200,
  128. "bmc_uart_baud": 115200,
  129. "debug_uart_baud": 921600,
  130. "debug_uart_clks_per_bit": 27,
  131. "requires_verified_real_fan_ptc_pin_map": True,
  132. "authority_boundary": "SRAM-only formal-uart diagnostic evidence. Schematic HEAT/FAN/FG/INSTALL pins are retained, diagnostic UARTs use spare GPIO, and reserved UART1/2 pins remain unused. It does not claim real thermal performance, production PTC/FAN qualification, flash, or PID closed-loop pass.",
  133. },
  134. }
  135. TD_GENERATED_SUFFIXES = {
  136. ".area",
  137. ".bid",
  138. ".bit",
  139. ".db",
  140. ".f",
  141. ".timing",
  142. ".tsm",
  143. }
  144. TD_GENERATED_PREFIXES = (
  145. "td_",
  146. )
  147. TD_SOURCE_SUFFIXES = {
  148. ".prj",
  149. ".tcl",
  150. }
  151. TD_PRESERVED_PATTERNS = [
  152. "*.tcl",
  153. "*.prj",
  154. ]
  155. VERILATOR_LINT_WAIVERS = [
  156. "MULTITOP", # Filelist intentionally lints reusable modules plus tops together.
  157. "WIDTHTRUNC", # Verilog-2001 parameters are range-constrained at assignment sites.
  158. "WIDTHEXPAND", # Signed fixed-point math uses explicit downstream clamps.
  159. "BLKSEQ", # Some clocked blocks use temporary next-value variables.
  160. "UNUSEDPARAM", # Contract modules expose forward-compatible parameters.
  161. "UNUSEDSIGNAL", # Debug/readback/status buses intentionally expose subsets.
  162. "VARHIDDEN", # Verilog task ports reuse contract field names locally.
  163. "CASEINCOMPLETE", # Source mux defaults to fake source for unknown selections.
  164. "SYNCASYNCNET", # Top-level reset is used by async-reset IP and sync debug wrapper logic.
  165. ]
  166. def toolchain_roots() -> list[Path]:
  167. roots: list[Path] = []
  168. for name in ["PID_STUDY_TOOLCHAIN_ROOT", "PID_STUDY_01_TOOLCHAIN_ROOT", "PID_CONTRACT_TOOLCHAIN_ROOT", "OSS_CAD_SUITE_ROOT"]:
  169. value = os.environ.get(name)
  170. if value:
  171. roots.append(Path(value))
  172. roots.append(DEFAULT_OSS_CAD_SUITE_ROOT)
  173. return roots
  174. def resolve_tool(name: str) -> str | None:
  175. path = shutil.which(name)
  176. if path:
  177. return path
  178. if name == "verilator":
  179. executable_names = ["verilator_bin.exe", "verilator.exe", "verilator"]
  180. else:
  181. executable_names = [name] if name.lower().endswith(".exe") else [name, f"{name}.exe"]
  182. for root in toolchain_roots():
  183. for exe_name in executable_names:
  184. for candidate in [root / "bin" / exe_name, root / exe_name]:
  185. if candidate.is_file():
  186. return str(candidate)
  187. return None
  188. def tool_env(extra: dict[str, str] | None = None) -> dict[str, str]:
  189. env = os.environ.copy()
  190. env.setdefault("PYTHONDONTWRITEBYTECODE", "1")
  191. path_parts = []
  192. for root in toolchain_roots():
  193. bin_dir = root / "bin"
  194. lib_dir = root / "lib"
  195. verilator_root = root / "share" / "verilator"
  196. smtbmc = root / "bin" / "yosys-smtbmc.exe.exe"
  197. if bin_dir.is_dir():
  198. path_parts.append(str(bin_dir))
  199. if lib_dir.is_dir():
  200. path_parts.append(str(lib_dir))
  201. if verilator_root.is_dir() and "VERILATOR_ROOT" not in env:
  202. env["VERILATOR_ROOT"] = str(verilator_root)
  203. if smtbmc.is_file() and "SMTBMC" not in env:
  204. env["SMTBMC"] = str(smtbmc)
  205. if path_parts:
  206. env["PATH"] = os.pathsep.join(path_parts + [env.get("PATH", "")])
  207. if extra:
  208. env.update(extra)
  209. return env
  210. def is_td_generated_output(path: Path) -> bool:
  211. if path.suffix.lower() in TD_SOURCE_SUFFIXES:
  212. return False
  213. if path.suffix.lower() in TD_GENERATED_SUFFIXES:
  214. return True
  215. if any(path.name.startswith(prefix) for prefix in TD_GENERATED_PREFIXES):
  216. return True
  217. return False
  218. def clean_td_outputs(project_root: Path = ROOT) -> dict[str, Any]:
  219. td_dirs = [project_root / "td" / "build" / "syn", project_root / "td" / "build" / "phy"]
  220. td_root_generated = project_root / "td"
  221. project_root_generated_patterns = ["td_*.log", "td_*.logw", "minidump-*.dmp"]
  222. project_log_generated_patterns = ["log/bw_*.log", "log/bw_*.logw"]
  223. build_started_at = datetime.now(timezone.utc).isoformat()
  224. deleted: list[str] = []
  225. preserved: list[str] = []
  226. errors: list[dict[str, str]] = []
  227. for directory in td_dirs:
  228. if not directory.is_dir():
  229. continue
  230. for path in sorted(directory.rglob("*"), key=lambda item: len(item.parts), reverse=True):
  231. rel = path.relative_to(project_root).as_posix()
  232. if path.is_dir():
  233. try:
  234. path.rmdir()
  235. deleted.append(rel + "/")
  236. except OSError:
  237. preserved.append(rel + "/")
  238. continue
  239. if not path.is_file():
  240. preserved.append(rel)
  241. continue
  242. try:
  243. path.unlink()
  244. deleted.append(rel)
  245. except OSError as exc:
  246. errors.append({"path": rel, "error": str(exc)})
  247. if td_root_generated.is_dir():
  248. for path in sorted(td_root_generated.glob("*.dmp")):
  249. rel = path.relative_to(project_root).as_posix()
  250. try:
  251. path.unlink()
  252. deleted.append(rel)
  253. except OSError as exc:
  254. errors.append({"path": rel, "error": str(exc)})
  255. for pattern in project_root_generated_patterns:
  256. for path in sorted(project_root.glob(pattern)):
  257. rel = path.relative_to(project_root).as_posix()
  258. try:
  259. path.unlink()
  260. deleted.append(rel)
  261. except OSError as exc:
  262. errors.append({"path": rel, "error": str(exc)})
  263. for pattern in project_log_generated_patterns:
  264. for path in sorted(project_root.glob(pattern)):
  265. rel = path.relative_to(project_root).as_posix()
  266. try:
  267. path.unlink()
  268. deleted.append(rel)
  269. except OSError as exc:
  270. errors.append({"path": rel, "error": str(exc)})
  271. return {
  272. "status": "pass" if not errors else "fail",
  273. "build_started_at": build_started_at,
  274. "deleted_count": len(deleted),
  275. "deleted": deleted,
  276. "preserved": preserved,
  277. "preserved_patterns": TD_PRESERVED_PATTERNS,
  278. "errors": errors,
  279. }
  280. def _safe_workspace_target(project_root: Path, target: Path) -> Path:
  281. root = project_root.resolve()
  282. resolved = target.resolve()
  283. if resolved == root or root not in resolved.parents:
  284. raise ValueError(f"refusing to delete outside project root: {target}")
  285. return resolved
  286. def _path_manifest_item(path: Path, base: Path | None = None) -> dict[str, Any]:
  287. item: dict[str, Any] = {
  288. "path": str(path if base is None else path.relative_to(base)),
  289. "exists": path.exists(),
  290. "kind": "dir" if path.is_dir() else "file" if path.is_file() else "missing",
  291. }
  292. if path.is_file():
  293. item["size"] = path.stat().st_size
  294. item["mtime_utc"] = datetime.fromtimestamp(path.stat().st_mtime, timezone.utc).isoformat()
  295. item["sha256"] = sha256(path)
  296. elif path.is_dir():
  297. files = [child for child in path.rglob("*") if child.is_file()]
  298. item["file_count"] = len(files)
  299. item["total_size"] = sum(child.stat().st_size for child in files)
  300. latest = max((child.stat().st_mtime for child in files), default=path.stat().st_mtime)
  301. item["latest_mtime_utc"] = datetime.fromtimestamp(latest, timezone.utc).isoformat()
  302. return item
  303. def _delete_path(path: Path, *, project_root: Path, external_allowed: bool = False) -> tuple[list[str], list[dict[str, str]]]:
  304. deleted: list[str] = []
  305. errors: list[dict[str, str]] = []
  306. try:
  307. target = path.resolve() if external_allowed else _safe_workspace_target(project_root, path)
  308. if not target.exists():
  309. return deleted, errors
  310. label = str(target)
  311. if target.is_dir():
  312. shutil.rmtree(target)
  313. deleted.append(label + os.sep)
  314. else:
  315. target.unlink()
  316. deleted.append(label)
  317. except OSError as exc:
  318. errors.append({"path": str(path), "error": str(exc)})
  319. return deleted, errors
  320. def clean_runtime_payload(
  321. project_root: Path = ROOT,
  322. *,
  323. include_external_td_log: bool = False,
  324. external_td_log_dir: Path = EXTERNAL_TD_BIN_LOG,
  325. ) -> dict[str, Any]:
  326. started_at = datetime.now(timezone.utc).isoformat()
  327. manifest_dir = project_root / ".codex" / "cleanup_manifests"
  328. manifest_dir.mkdir(parents=True, exist_ok=True)
  329. manifest_path = manifest_dir / (datetime.now().strftime("cleanup_%Y%m%d_%H%M%S.json"))
  330. workspace_targets = [
  331. project_root / "td" / "build",
  332. project_root / "tmp",
  333. project_root / "receipts" / "local",
  334. ]
  335. workspace_targets.extend(project_root.glob("td/project/*_Runs"))
  336. workspace_targets.extend(project_root.glob("td/project/log"))
  337. workspace_targets.extend(project_root.glob("td_*.log"))
  338. workspace_targets.extend(project_root.glob("td_*.logw"))
  339. workspace_targets.extend(project_root.glob("minidump-*.dmp"))
  340. workspace_targets.extend(project_root.rglob("__pycache__"))
  341. workspace_targets.extend(project_root.rglob(".pytest_cache"))
  342. before = [_path_manifest_item(path, project_root) for path in workspace_targets if path.exists()]
  343. external_targets: list[Path] = []
  344. if include_external_td_log and external_td_log_dir.is_dir():
  345. external_targets = list(external_td_log_dir.glob("bw_*.log")) + list(external_td_log_dir.glob("bw_*.logw"))
  346. external_before = [_path_manifest_item(path) for path in external_targets if path.exists()]
  347. deleted: list[str] = []
  348. errors: list[dict[str, str]] = []
  349. for target in sorted(set(workspace_targets), key=lambda item: len(item.parts), reverse=True):
  350. if not target.exists():
  351. continue
  352. current_deleted, current_errors = _delete_path(target, project_root=project_root)
  353. deleted.extend(current_deleted)
  354. errors.extend(current_errors)
  355. for target in external_targets:
  356. current_deleted, current_errors = _delete_path(target, project_root=project_root, external_allowed=True)
  357. deleted.extend(current_deleted)
  358. errors.extend(current_errors)
  359. payload = {
  360. "schema": "pid-study-runtime-cleanup-v1",
  361. "status": "pass" if not errors else "fail",
  362. "started_at": started_at,
  363. "finished_at": datetime.now(timezone.utc).isoformat(),
  364. "project_root": str(project_root),
  365. "include_external_td_log": include_external_td_log,
  366. "external_td_log_dir": str(external_td_log_dir),
  367. "deleted_count": len(deleted),
  368. "deleted": deleted,
  369. "before": before,
  370. "external_before": external_before,
  371. "errors": errors,
  372. "manifest": str(manifest_path.relative_to(project_root)),
  373. "authority_boundary": "Cleanup removes runtime/build/log evidence only. Source, tests, schemas, docs, and reference/original are not cleanup targets.",
  374. }
  375. manifest_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
  376. return payload
  377. def toolchain_clean_payload(
  378. *,
  379. install_root: Path = DEFAULT_OSS_CAD_SUITE_ROOT,
  380. cocotb_venv: Path = DEFAULT_COCOTB_VENV_PYTHON.parent.parent,
  381. include_downloads: bool = False,
  382. apply: bool = False,
  383. ) -> dict[str, Any]:
  384. try:
  385. from bootstrap_oss_cad_suite import uninstall_owned_toolchain
  386. payload = uninstall_owned_toolchain(
  387. install_root=install_root,
  388. cocotb_venv=cocotb_venv,
  389. dry_run=not apply,
  390. include_downloads=include_downloads,
  391. download_dir=DEFAULT_TOOLCHAIN_BASE / "downloads",
  392. )
  393. except Exception as exc: # pragma: no cover - import failure is environment-dependent.
  394. payload = {
  395. "schema": "offline-toolchain-uninstall-v1",
  396. "status": "blocked_clean_failed",
  397. "mode": "apply" if apply else "dry_run",
  398. "targets": [],
  399. "error": str(exc),
  400. "cleanup_policy": {
  401. "default": "dry_run",
  402. "requires_owner_marker": True,
  403. "owner_marker_name": ".cpld_toolchain_owner.json",
  404. "actual_delete_requires_apply": True,
  405. "allowed_root": str(DEFAULT_TOOLCHAIN_BASE),
  406. },
  407. "safety": {
  408. "opens_com_ports": False,
  409. "toggles_dtr_rts": False,
  410. "installs_drivers": False,
  411. "programs_flash": False,
  412. "touches_ptc_fan_bmc": False,
  413. },
  414. "authority_boundary": "toolchain-clean only removes user-mode toolchain paths that carry the CPLD owner marker; it never probes COM ports, installs drivers, programs flash, or touches real hardware.",
  415. }
  416. payload["schema"] = "offline-toolchain-clean-v1"
  417. payload["cleanup_policy"]["allowed_root"] = str(DEFAULT_TOOLCHAIN_BASE)
  418. return {
  419. **payload,
  420. "authority_boundary": "toolchain-clean only removes user-mode toolchain paths that carry the CPLD owner marker; it never probes COM ports, installs drivers, programs flash, or touches real hardware.",
  421. }
  422. def cocotb_python() -> str:
  423. return (
  424. os.environ.get("PID_STUDY_COCOTB_PYTHON")
  425. or os.environ.get("PID_STUDY_01_COCOTB_PYTHON")
  426. or os.environ.get("PID_CONTRACT_COCOTB_PYTHON")
  427. ) or (
  428. str(DEFAULT_COCOTB_VENV_PYTHON)
  429. if DEFAULT_COCOTB_VENV_PYTHON.is_file()
  430. else str(COMPAT_COCOTB_VENV_PYTHON)
  431. if COMPAT_COCOTB_VENV_PYTHON.is_file()
  432. else sys.executable
  433. )
  434. def cocotb_module_available(python_exe: str | None = None) -> bool:
  435. if python_exe and Path(python_exe) != Path(sys.executable):
  436. try:
  437. result = subprocess.run(
  438. [python_exe, "-c", "import cocotb"],
  439. cwd=ROOT,
  440. env=tool_env(),
  441. text=True,
  442. stdout=subprocess.PIPE,
  443. stderr=subprocess.PIPE,
  444. timeout=20,
  445. )
  446. except (OSError, subprocess.TimeoutExpired):
  447. return False
  448. return result.returncode == 0
  449. try:
  450. return importlib.util.find_spec("cocotb") is not None
  451. except (ImportError, ValueError):
  452. return False
  453. def run_python(script: str) -> subprocess.CompletedProcess[str]:
  454. env = os.environ.copy()
  455. env["PYTHONDONTWRITEBYTECODE"] = "1"
  456. return subprocess.run(
  457. [sys.executable, str(ROOT / "tools" / script)],
  458. cwd=ROOT,
  459. env=env,
  460. text=True,
  461. stdout=subprocess.PIPE,
  462. stderr=subprocess.PIPE,
  463. )
  464. def run_unit_test(script: str) -> subprocess.CompletedProcess[str]:
  465. env = tool_env({"PYTHONPATH": str(ROOT / "tools")})
  466. return subprocess.run(
  467. [sys.executable, str(ROOT / "tests" / "unit" / script)],
  468. cwd=ROOT,
  469. env=env,
  470. text=True,
  471. stdout=subprocess.PIPE,
  472. stderr=subprocess.PIPE,
  473. )
  474. def td_build_dirs_for_profile(top: str = DEFAULT_TD_TOP) -> tuple[Path, Path]:
  475. profile = TD_TOP_PROFILES[top]
  476. build_subdir = profile.get("build_subdir")
  477. if build_subdir:
  478. base = ROOT / "td" / "build" / str(build_subdir)
  479. return base / "syn", base / "phy"
  480. return TD_BUILD_SYN, TD_BUILD_PHY
  481. def _td_source_path_from_project_path(project_path: str) -> Path:
  482. if project_path.startswith("../../"):
  483. return ROOT / project_path[6:]
  484. if project_path.startswith("../"):
  485. return ROOT / project_path[3:]
  486. return ROOT / project_path
  487. def _td_build_project_path(top: str, project_path: str, source: Path, build_dir: Path) -> str:
  488. if project_path.startswith(("../../src/top/", "../src/top/")):
  489. return f"src/top/{source.name}"
  490. if project_path.startswith(("../../src/rtl/", "../src/rtl/")):
  491. return f"src/rtl/{source.name}"
  492. if project_path.startswith(("../../constraints/", "../constraints/")):
  493. return f"constraints/{source.name}"
  494. return Path(os.path.relpath(source, build_dir)).as_posix()
  495. def _copy_td_project_payload(prj: Path, build_dir: Path, top: str) -> None:
  496. text = prj.read_text(encoding="utf-8")
  497. replacements: dict[str, str] = {}
  498. for match in re.finditer(r'<File Path="([^"]+)">', text):
  499. project_path = match.group(1)
  500. source = _td_source_path_from_project_path(project_path)
  501. if not source.is_file():
  502. continue
  503. replacement = _td_build_project_path(top, project_path, source, build_dir)
  504. target = build_dir / replacement
  505. target.parent.mkdir(parents=True, exist_ok=True)
  506. shutil.copy2(source, target)
  507. replacements[project_path] = replacement
  508. for old, new in replacements.items():
  509. text = text.replace(old, new)
  510. prj.write_text(text, encoding="utf-8")
  511. def write_td_gui_project_from_prj(prj: Path, al_path: Path, project_root: Path) -> None:
  512. """Write a TD GUI .al project from the batch .prj source list."""
  513. tree = ET.parse(prj)
  514. root = tree.getroot()
  515. root.set("Path", project_root.as_posix())
  516. root.set("RunTime", datetime.now(timezone.utc).replace(microsecond=0).isoformat())
  517. source_files = root.find("Source_Files")
  518. runs = root.find("Runs")
  519. if runs is None:
  520. runs = ET.SubElement(root, "Runs")
  521. if not any(run.get("Name") == "syn" for run in runs.findall("Run")):
  522. syn = ET.SubElement(runs, "Run", {"Name": "syn", "Type": "Synthesis", "ConstraintSet": "constraint_1", "Description": "", "Active": "true"})
  523. ET.SubElement(syn, "Strategy", {"Name": "Default_Synthesis_Strategy"})
  524. if not any(run.get("Name") == "phy" for run in runs.findall("Run")):
  525. phy = ET.SubElement(runs, "Run", {"Name": "phy", "Type": "PhysicalDesign", "ConstraintSet": "constraint_1", "Description": "", "SynRun": "syn", "Active": "true"})
  526. ET.SubElement(phy, "Strategy", {"Name": "Default_PhysicalDesign_Strategy"})
  527. if root.find("Project_Settings") is None:
  528. ET.SubElement(root, "Project_Settings")
  529. al_path.parent.mkdir(parents=True, exist_ok=True)
  530. ET.indent(tree, space=" ")
  531. tree.write(al_path, encoding="utf-8", xml_declaration=True)
  532. def prepare_td_build_dirs(top: str = DEFAULT_TD_TOP) -> tuple[Path, Path]:
  533. if top not in TD_TOP_PROFILES:
  534. raise ValueError(f"unsupported TD top profile: {top}")
  535. profile = TD_TOP_PROFILES[top]
  536. syn_build, phy_build = td_build_dirs_for_profile(top)
  537. syn_build.mkdir(parents=True, exist_ok=True)
  538. phy_build.mkdir(parents=True, exist_ok=True)
  539. source_prj = ROOT / str(profile.get("source_prj", f"td/{top}.prj"))
  540. for source, target in [
  541. (source_prj, syn_build / str(profile["syn_script"]).replace(".tcl", ".prj")),
  542. (ROOT / "td" / "syn" / str(profile["syn_script"]), syn_build / str(profile["syn_script"])),
  543. (source_prj, phy_build / str(profile["phy_script"]).replace(".tcl", ".prj")),
  544. (ROOT / "td" / "phy" / str(profile["phy_script"]), phy_build / str(profile["phy_script"])),
  545. ]:
  546. shutil.copy2(source, target)
  547. for build_dir, script_key in [(syn_build, "syn_script"), (phy_build, "phy_script")]:
  548. prj = build_dir / str(profile[script_key]).replace(".tcl", ".prj")
  549. _copy_td_project_payload(prj, build_dir, top)
  550. return syn_build, phy_build
  551. def td_process_env(run_dir: Path) -> dict[str, str]:
  552. """Run TD with isolated temp files while keeping the licensed user profile."""
  553. env = os.environ.copy()
  554. env_root = run_dir / "td_user_env"
  555. temp_dir = env_root / "temp"
  556. temp_dir.mkdir(parents=True, exist_ok=True)
  557. env.update(
  558. {
  559. "TEMP": str(temp_dir),
  560. "TMP": str(temp_dir),
  561. }
  562. )
  563. return env
  564. def run_td_script(run_dir: Path, script_name: str) -> subprocess.CompletedProcess[str]:
  565. run_dir.mkdir(parents=True, exist_ok=True)
  566. # TD 2026.1 SP1 is sensitive to command ordering in batch mode; source the
  567. # script as an argument and let the Tcl keep import_device before open_project.
  568. return subprocess.run(
  569. [str(TD_EXE), script_name],
  570. cwd=run_dir,
  571. env=td_process_env(run_dir),
  572. text=True,
  573. encoding="utf-8",
  574. errors="replace",
  575. stdout=subprocess.PIPE,
  576. stderr=subprocess.PIPE,
  577. timeout=1800,
  578. )
  579. def td_profile_for_top_module(top_name: str) -> dict[str, Any]:
  580. for profile in TD_TOP_PROFILES.values():
  581. if profile.get("top_module") == top_name:
  582. return profile
  583. return {"source_prj": f"td/{DEFAULT_TD_TOP}.prj", "top_module": top_name}
  584. TD_FORBIDDEN_SCRIPT_COMMANDS = {
  585. "download",
  586. "program",
  587. "program_svf",
  588. "connect_cable",
  589. "read_device_id",
  590. "read_dna",
  591. "read_efuse",
  592. "write_phy_data",
  593. "read_phy_data",
  594. "write_bram",
  595. "write_bram18",
  596. "write_bram20",
  597. "write_bram32",
  598. }
  599. TD_FORBIDDEN_SCRIPT_TOKENS = {
  600. "PROGRAM_FLASH",
  601. "ERASE_FLASH",
  602. "PROGRAM_SPIBIN",
  603. "DIRECT_FLASH_WRITE",
  604. "PROGRAM_SRAM",
  605. }
  606. def td_verilog_sources_from_project(source_prj: Path) -> list[Path]:
  607. tree = ET.parse(source_prj)
  608. sources: list[Path] = []
  609. seen: set[Path] = set()
  610. for file_node in tree.findall(".//Verilog/File"):
  611. project_path = str(file_node.get("Path") or "").strip()
  612. if not project_path:
  613. continue
  614. candidate = Path(project_path)
  615. if not candidate.is_absolute():
  616. candidate = (source_prj.parent / candidate).resolve()
  617. else:
  618. candidate = candidate.resolve()
  619. if candidate in seen:
  620. continue
  621. if not candidate.is_file():
  622. raise FileNotFoundError(f"TD source file not found: {project_path} resolved to {candidate}")
  623. sources.append(candidate)
  624. seen.add(candidate)
  625. if not sources:
  626. raise ValueError(f"TD project contains no Verilog source files: {source_prj}")
  627. return sources
  628. def td_forbidden_script_markers(script_text: str) -> list[str]:
  629. markers: set[str] = set()
  630. for raw_line in script_text.splitlines():
  631. line = raw_line.strip()
  632. if not line or line.startswith("#"):
  633. continue
  634. command = re.split(r"\s+", line, maxsplit=1)[0].lower()
  635. if command in TD_FORBIDDEN_SCRIPT_COMMANDS:
  636. markers.add(command)
  637. upper_text = script_text.upper()
  638. for token in TD_FORBIDDEN_SCRIPT_TOKENS:
  639. if token in upper_text:
  640. markers.add(token)
  641. return sorted(markers)
  642. def build_td_elaboration_plan(top_name: str, source_prj: Path, build_dir: Path) -> dict[str, Any]:
  643. sources = td_verilog_sources_from_project(source_prj)
  644. build_dir.mkdir(parents=True, exist_ok=True)
  645. script_path = build_dir / f"elaborate_{top_name}.tcl"
  646. db_name = f"{top_name}_elaborate.db"
  647. lines = ["import_device ef2_4.db -package EF2L45BG256B"]
  648. for source in sources:
  649. lines.append(f"analyze -file {{{source.as_posix()}}}")
  650. lines.extend([
  651. f"elaborate -top {{{top_name}}}",
  652. f"export_db {db_name}",
  653. "",
  654. ])
  655. script_text = "\n".join(lines)
  656. forbidden = td_forbidden_script_markers(script_text)
  657. if forbidden:
  658. raise ValueError(f"TD elaboration script contains forbidden hardware command(s): {', '.join(forbidden)}")
  659. script_path.write_text(script_text, encoding="utf-8")
  660. manifest_payload = {
  661. "schema": "td-offline-elaboration-plan-v1",
  662. "top": top_name,
  663. "source_prj": str(source_prj),
  664. "source_prj_sha256": sha256(source_prj),
  665. "script": str(script_path),
  666. "script_sha256": sha256(script_path),
  667. "database": str(build_dir / db_name),
  668. "sources": [
  669. {
  670. "path": str(source),
  671. "sha256": sha256(source),
  672. }
  673. for source in sources
  674. ],
  675. "safety": {
  676. "opens_com_ports": False,
  677. "toggles_dtr_rts": False,
  678. "installs_drivers": False,
  679. "programs_flash": False,
  680. "downloads_to_hardware": False,
  681. "touches_ptc_fan_bmc": False,
  682. "real_ptc_fan_bmc_action_attempted": False,
  683. },
  684. "forbidden_markers": forbidden,
  685. "authority_boundary": "TD offline elaboration plan analyzes RTL and exports an elaboration database only; it never downloads, programs, opens cables, or touches real hardware.",
  686. }
  687. manifest_path = build_dir / f"{top_name}_elaboration_plan.json"
  688. manifest_path.write_text(json.dumps(manifest_payload, indent=2) + "\n", encoding="utf-8")
  689. return {
  690. **manifest_payload,
  691. "manifest": str(manifest_path),
  692. "manifest_sha256": sha256(manifest_path),
  693. }
  694. def run_td_elaboration(top_name: str) -> dict[str, Any]:
  695. if not TD_EXE.is_file():
  696. return {"status": "blocked", "reason": f"missing TD executable: {TD_EXE}"}
  697. profile = td_profile_for_top_module(top_name)
  698. source_prj = ROOT / str(profile.get("source_prj", f"td/{DEFAULT_TD_TOP}.prj"))
  699. build_dir = TD_BUILD_SYN / "elaboration" / top_name
  700. try:
  701. plan = build_td_elaboration_plan(top_name, source_prj, build_dir)
  702. except (OSError, ValueError, ET.ParseError) as exc:
  703. return {
  704. "status": "fail",
  705. "top": top_name,
  706. "invocation": "analyze_elaborate_script",
  707. "source_prj": str(source_prj),
  708. "reason": str(exc),
  709. "safety": {
  710. "opens_com_ports": False,
  711. "toggles_dtr_rts": False,
  712. "installs_drivers": False,
  713. "programs_flash": False,
  714. "downloads_to_hardware": False,
  715. "touches_ptc_fan_bmc": False,
  716. "real_ptc_fan_bmc_action_attempted": False,
  717. },
  718. }
  719. script_name = Path(str(plan["script"])).name
  720. result = subprocess.run(
  721. [str(TD_EXE), script_name],
  722. cwd=build_dir,
  723. env=td_process_env(build_dir),
  724. text=True,
  725. encoding="utf-8",
  726. errors="replace",
  727. stdout=subprocess.PIPE,
  728. stderr=subprocess.PIPE,
  729. timeout=600,
  730. )
  731. has_error = td_log_has_error(result.stdout, result.stderr)
  732. db_path = Path(str(plan["database"]))
  733. db_info = None
  734. if db_path.is_file() and db_path.stat().st_size > 0:
  735. db_info = {"path": str(db_path), "size": db_path.stat().st_size, "sha256": sha256(db_path)}
  736. return {
  737. "status": "pass" if result.returncode == 0 and not has_error and db_info else "fail",
  738. "top": top_name,
  739. "invocation": "analyze_elaborate_script",
  740. "source_prj": str(source_prj),
  741. "plan": plan,
  742. "script": str(build_dir / script_name),
  743. "database": db_info,
  744. "returncode": result.returncode,
  745. "log_has_error": has_error,
  746. "stdout_tail": result.stdout[-4000:],
  747. "stderr_tail": result.stderr[-4000:],
  748. "safety": plan["safety"],
  749. "authority_boundary": "TD elaboration evidence proves the vendor CLI analyzed RTL and elaborated the requested top offline; it does not generate/download/program a bitstream or certify pins/hardware.",
  750. }
  751. def run_logic_elaborations() -> dict[str, Any]:
  752. tops = [
  753. "system_contract_top",
  754. "uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top",
  755. ]
  756. results = {top: run_td_elaboration(top) for top in tops}
  757. statuses = {item["status"] for item in results.values()}
  758. if "fail" in statuses:
  759. status_value = "fail"
  760. elif "blocked" in statuses:
  761. status_value = "blocked"
  762. else:
  763. status_value = "pass"
  764. return {"status": status_value, "tops": results}
  765. def hdl_testbenches() -> list[dict[str, Any]]:
  766. return [
  767. {"name": "debug_trigger_unit_tb", "sources": ["src/rtl/debug_trigger_unit.v", "tests/sim/debug_trigger_unit_tb.v"]},
  768. {"name": "debug_trace_recorder_bram_tb", "sources": ["src/rtl/debug_trace_recorder_bram.v", "tests/sim/debug_trace_recorder_bram_tb.v"]},
  769. {"name": "debug_register_window_tb", "sources": ["src/rtl/debug_register_window.v", "tests/sim/debug_register_window_tb.v"]},
  770. {"name": "debug_uart_stream_tb", "sources": ["src/rtl/debug_uart_stream.v", "tests/sim/debug_uart_stream_tb.v"]},
  771. {"name": "uart_8n1_phy_tb", "sources": ["src/rtl/uart_tx_8n1.v", "src/rtl/uart_rx_8n1.v", "tests/sim/uart_8n1_phy_tb.v"]},
  772. {"name": "uart_rx_error_tb", "sources": ["src/rtl/uart_rx_8n1.v", "tests/sim/uart_rx_error_tb.v"]},
  773. {"name": "uart_rx_back_to_back_tb", "sources": ["src/rtl/uart_rx_8n1.v", "tests/sim/uart_rx_back_to_back_tb.v"]},
  774. {
  775. "name": "uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top_tb",
  776. "sources": [
  777. "src/rtl/uart_tx_8n1.v",
  778. "src/rtl/uart_rx_8n1.v",
  779. "src/rtl/bmc_uart_raw48_poll_lite.v",
  780. "src/top/uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top.v",
  781. "tests/sim/uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top_tb.v",
  782. ],
  783. },
  784. {"name": "bmc_uart_phy_bridge_tb", "sources": ["src/rtl/bmc_uart_phy_bridge.v", "tests/sim/bmc_uart_phy_bridge_tb.v"]},
  785. {"name": "bmc_uart_ascii_poll_tb", "sources": ["src/rtl/bmc_uart_ascii_poll.v", "tests/sim/bmc_uart_ascii_poll_tb.v"]},
  786. {"name": "bmc_dimm_frame_parser_tb", "sources": ["src/rtl/bmc_dimm_frame_parser.v", "tests/sim/bmc_dimm_frame_parser_tb.v"]},
  787. {"name": "source_arbitrator_tb", "sources": ["src/rtl/source_arbitrator.v", "tests/sim/source_arbitrator_tb.v"]},
  788. {"name": "hysteresis_pi_controller_tb", "sources": ["src/rtl/hysteresis_pi_controller.v", "tests/sim/hysteresis_pi_controller_tb.v"]},
  789. {
  790. "name": "control_service_24ch_tb",
  791. "sources": [
  792. "src/rtl/pid_24ch_scheduler.v",
  793. "src/rtl/control_service_24ch.v",
  794. "tests/sim/control_service_24ch_tb.v",
  795. ],
  796. },
  797. {"name": "pid_core_tb", "sources": ["src/rtl/pid_core.v", "tests/sim/pid_core_tb.v"]},
  798. {
  799. "name": "pid_contract_integration_tb",
  800. "sources": ["src/rtl/pid_24ch_scheduler.v", "src/rtl/actuator_sink.v", "tests/sim/pid_contract_integration_tb.v"],
  801. },
  802. {"name": "pid_source_mux_tb", "sources": ["src/rtl/sensor_source_mux.v", "tests/sim/pid_source_mux_tb.v"]},
  803. {"name": "pid_control_regfile_tb", "sources": ["src/rtl/pid_control_regfile.v", "tests/sim/pid_control_regfile_tb.v"]},
  804. {"name": "sensor_domain_tb", "sources": ["src/rtl/sensor_source_mux.v", "src/rtl/sensor_domain.v", "tests/sim/sensor_domain_tb.v"]},
  805. {"name": "host_command_plane_tb", "sources": ["src/rtl/pid_control_regfile.v", "src/rtl/host_command_plane.v", "tests/sim/host_command_plane_tb.v"]},
  806. {"name": "safety_supervisor_tb", "sources": ["src/rtl/safety_supervisor.v", "tests/sim/safety_supervisor_tb.v"]},
  807. {"name": "ptc_output_bank_tb", "sources": ["src/rtl/ptc_output_bank.v", "tests/sim/ptc_output_bank_tb.v"]},
  808. {"name": "fan_tach_domain_tb", "sources": ["src/rtl/fan_tach_domain.v", "tests/sim/fan_tach_domain_tb.v"]},
  809. {"name": "board_io_adapter_tb", "sources": ["src/rtl/board_io_adapter.v", "tests/sim/board_io_adapter_tb.v"]},
  810. {"name": "motor_limit_domain_tb", "sources": ["src/rtl/motor_limit_domain.v", "tests/sim/motor_limit_domain_tb.v"]},
  811. {
  812. "name": "actuator_domain_tb",
  813. "sources": [
  814. "src/rtl/ptc_output_bank.v",
  815. "src/rtl/fan_tach_domain.v",
  816. "src/rtl/board_io_adapter.v",
  817. "src/rtl/motor_limit_domain.v",
  818. "src/rtl/actuator_domain.v",
  819. "tests/sim/actuator_domain_tb.v",
  820. ],
  821. },
  822. {"name": "debug_snapshot_v2_tb", "sources": ["src/rtl/debug_snapshot_v2.v", "tests/sim/debug_snapshot_v2_tb.v"]},
  823. {
  824. "name": "system_contract_top_tb",
  825. "sources": [
  826. "src/rtl/bmc_uart_ascii_poll.v",
  827. "src/rtl/bmc_dimm_frame_parser.v",
  828. "src/rtl/fake_sensor_source.v",
  829. "src/rtl/i2c_master_sensor_adapter.v",
  830. "src/rtl/pid_control_regfile.v",
  831. "src/rtl/sensor_source_mux.v",
  832. "src/rtl/sensor_domain.v",
  833. "src/rtl/host_command_plane.v",
  834. "src/rtl/safety_supervisor.v",
  835. "src/rtl/ptc_output_bank.v",
  836. "src/rtl/fan_tach_domain.v",
  837. "src/rtl/board_io_adapter.v",
  838. "src/rtl/motor_limit_domain.v",
  839. "src/rtl/pid_24ch_scheduler.v",
  840. "src/rtl/actuator_domain.v",
  841. "src/rtl/debug_snapshot_v2.v",
  842. "src/rtl/debug_trigger_unit.v",
  843. "src/rtl/debug_trace_recorder_bram.v",
  844. "src/rtl/debug_register_window.v",
  845. "src/rtl/debug_uart_stream.v",
  846. "src/rtl/debug_probe_bus.v",
  847. "src/top/system_contract_top.v",
  848. "tests/sim/system_contract_top_tb.v",
  849. ],
  850. },
  851. ]
  852. def verilator_lint_targets() -> list[dict[str, Any]]:
  853. sources: list[str] = []
  854. for testbench in hdl_testbenches():
  855. for source in testbench["sources"]:
  856. if source.startswith(("src/rtl/", "src/top/")) and source not in sources:
  857. sources.append(source)
  858. return [
  859. {
  860. "name": "pid_contract_rtl_and_tops",
  861. "sources": sources,
  862. "waiver_file": "tests/verilator_waivers.vlt",
  863. }
  864. ]
  865. def cocotb_tests() -> list[dict[str, Any]]:
  866. return [
  867. {
  868. "name": "pid_core_smoke",
  869. "path": "tests/cocotb",
  870. "toplevel": "pid_core",
  871. "module": "test_pid_core_smoke",
  872. "simulator": "icarus",
  873. }
  874. ]
  875. def formal_targets() -> list[dict[str, Any]]:
  876. return [
  877. {"name": "fault_implies_ptc_off", "sby": "tests/formal/fault_implies_ptc_off.sby"},
  878. {"name": "invalid_channel_no_actuator", "sby": "tests/formal/invalid_channel_no_actuator.sby"},
  879. {"name": "disable_clears_history", "sby": "tests/formal/disable_clears_history.sby"},
  880. {"name": "thermal_fault_requests_fan_fallback", "sby": "tests/formal/thermal_fault_requests_fan_fallback.sby"},
  881. ]
  882. def detector_selftest_targets() -> dict[str, dict[str, Any]]:
  883. return {
  884. "icarus": {
  885. "required_tools": ["iverilog"],
  886. "command_kind": "compile_bad_testbench",
  887. "source": "tests/fixtures/bad_icarus_tb.v",
  888. },
  889. "verilator": {
  890. "required_tools": ["verilator"],
  891. "command_kind": "lint_bad_fixture",
  892. "source": "tests/fixtures/bad_verilator_lint.v",
  893. },
  894. "cocotb": {
  895. "required_tools": ["python_module:cocotb", "iverilog", "vvp"],
  896. "command_kind": "scoreboard_bad_expected",
  897. "path": "tests/cocotb",
  898. },
  899. "formal": {
  900. "required_tools": ["sby", "yosys"],
  901. "command_kind": "counterexample_bad_property",
  902. "sby": "tests/fixtures/bad_formal_fail.sby",
  903. },
  904. }
  905. def _missing_tool_payload(payload: dict[str, Any], missing_tools: list[str]) -> dict[str, Any]:
  906. return {
  907. "status": "blocked_missing_tool",
  908. "reason": "missing required external tool(s): " + ", ".join(missing_tools),
  909. "missing_tools": missing_tools,
  910. **payload,
  911. }
  912. def _tail(text: str, limit: int = 4000) -> str:
  913. return text[-limit:] if text else ""
  914. def detector_selftest_payload(run: bool, backend: str = "all") -> dict[str, Any]:
  915. all_targets = detector_selftest_targets()
  916. selected = all_targets if backend == "all" else {backend: all_targets[backend]}
  917. payload = {
  918. "verification_layer": "detector_selftest",
  919. "origin": "project_defined_strategy",
  920. "fact_class": "project_defined_strategy",
  921. "backend": backend,
  922. "authority_boundary": "These selftests intentionally run bad fixtures. A pass means the detector caught the failure; it does not validate the RTL design.",
  923. "targets": selected,
  924. }
  925. if not run:
  926. return {"status": "skipped", "reason": "Detector selftest not requested. Use detector-selftest --run.", **payload}
  927. results = []
  928. for name, target in selected.items():
  929. missing_tools = []
  930. for tool in target["required_tools"]:
  931. if tool == "python_module:cocotb":
  932. if not cocotb_module_available(cocotb_python()):
  933. missing_tools.append(tool)
  934. elif not resolve_tool(tool):
  935. missing_tools.append(tool)
  936. if missing_tools:
  937. results.append({
  938. "name": name,
  939. "status": "blocked_missing_tool",
  940. "missing_tools": missing_tools,
  941. "reason": "missing required external tool(s): " + ", ".join(missing_tools),
  942. })
  943. continue
  944. if name == "icarus":
  945. iverilog = resolve_tool("iverilog")
  946. assert iverilog is not None
  947. out = ROOT / "tmp" / "detector_selftest" / "bad_icarus.vvp"
  948. out.parent.mkdir(parents=True, exist_ok=True)
  949. cmd = [iverilog, "-g2005-sv", "-o", str(out), str(ROOT / target["source"])]
  950. result = subprocess.run(cmd, cwd=ROOT, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  951. elif name == "verilator":
  952. verilator = resolve_tool("verilator")
  953. assert verilator is not None
  954. cmd = [verilator, "--lint-only", "-Wall", "--Werror-UNUSEDSIGNAL", str(ROOT / target["source"])]
  955. result = subprocess.run(cmd, cwd=ROOT, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  956. elif name == "cocotb":
  957. env = tool_env({
  958. "PID_STUDY_COCOTB_FORCE_BAD_EXPECTED": "1",
  959. })
  960. cmd = [cocotb_python(), str(ROOT / target["path"] / "run_pid_core_smoke.py")]
  961. result = subprocess.run(cmd, cwd=ROOT / target["path"], env=env, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  962. elif name == "formal":
  963. sby = resolve_tool("sby")
  964. assert sby is not None
  965. sby_file = ROOT / target["sby"]
  966. workdir = ROOT / "tmp" / "formal_runs" / "detector_selftest" / name
  967. cmd = [sby, "-f", "-d", str(workdir), str(sby_file)]
  968. result = subprocess.run(cmd, cwd=sby_file.parent, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  969. else:
  970. results.append({"name": name, "status": "fail", "reason": f"unsupported selftest backend: {name}"})
  971. continue
  972. caught_failure = result.returncode != 0
  973. results.append({
  974. "name": name,
  975. "status": "pass" if caught_failure else "fail",
  976. "expected_bad_fixture_to_fail": True,
  977. "returncode": result.returncode,
  978. "command": cmd,
  979. "stdout": _tail(result.stdout),
  980. "stderr": _tail(result.stderr),
  981. "reason": "bad fixture failure was caught" if caught_failure else "bad fixture unexpectedly passed; detector is not trustworthy",
  982. })
  983. statuses = {item["status"] for item in results}
  984. if "fail" in statuses:
  985. status_value = "fail"
  986. elif statuses == {"blocked_missing_tool"}:
  987. status_value = "blocked_missing_tool"
  988. elif "blocked_missing_tool" in statuses:
  989. status_value = "partial"
  990. else:
  991. status_value = "pass"
  992. return {"status": status_value, **payload, "results": results}
  993. def hdl_sim_payload(run: bool, backend: str = "icarus", scenario: Path | None = None) -> dict[str, Any]:
  994. metadata = {
  995. "verification_layer": "hdl_sim",
  996. "origin": "project_defined_optional_verification_layer",
  997. "backend": backend,
  998. "fact_class": "project_defined_strategy",
  999. "authority_boundary": "This is a project harness strategy, not an Anlogic TD or chip-vendor requirement.",
  1000. "scenario": None if scenario is None else str(scenario),
  1001. }
  1002. testbenches = hdl_testbenches()
  1003. if backend == "all":
  1004. backends = ["icarus", "verilator", "cocotb"]
  1005. backend_results = {name: hdl_sim_payload(run=run, backend=name, scenario=scenario) for name in backends}
  1006. statuses = {item["status"] for item in backend_results.values()}
  1007. if "fail" in statuses:
  1008. status_value = "fail"
  1009. elif statuses == {"pass"}:
  1010. status_value = "pass"
  1011. elif statuses == {"blocked_missing_tool"}:
  1012. status_value = "blocked_missing_tool"
  1013. elif statuses == {"skipped"}:
  1014. status_value = "skipped"
  1015. else:
  1016. status_value = "partial"
  1017. missing_tools: list[str] = []
  1018. for item in backend_results.values():
  1019. missing_tools.extend(item.get("missing_tools", []))
  1020. return {
  1021. "status": status_value,
  1022. **metadata,
  1023. "mode": "multi_backend",
  1024. "required_tools": ["iverilog", "vvp", "verilator", "python_module:cocotb"],
  1025. "backend_results": backend_results,
  1026. "missing_tools": sorted(set(missing_tools)),
  1027. "authority_boundary": "This aggregates project-defined optional HDL backends. A partial result means at least one backend produced evidence and at least one backend was blocked by a missing external tool.",
  1028. }
  1029. if backend == "verilator":
  1030. verilator = resolve_tool("verilator")
  1031. targets = verilator_lint_targets()
  1032. payload = {
  1033. **metadata,
  1034. "mode": "lint_first",
  1035. "command_mode": VERILATOR_LINT_MODE,
  1036. "required_tools": ["verilator"],
  1037. "tests": targets,
  1038. }
  1039. if not run:
  1040. return {"status": "skipped", "reason": "HDL simulation not requested.", **payload}
  1041. if not verilator:
  1042. return _missing_tool_payload(payload, ["verilator"])
  1043. results = []
  1044. for target in targets:
  1045. waiver_file = ROOT / target["waiver_file"]
  1046. cmd = [verilator, "--lint-only", "-Wall", "--timing"]
  1047. cmd.extend(f"-Wno-{warning}" for warning in VERILATOR_LINT_WAIVERS)
  1048. if waiver_file.is_file():
  1049. cmd.append(str(waiver_file))
  1050. cmd.extend(str(ROOT / src) for src in target["sources"])
  1051. result = subprocess.run(cmd, cwd=ROOT, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  1052. results.append({
  1053. "name": target["name"],
  1054. "status": "pass" if result.returncode == 0 else "fail",
  1055. "returncode": result.returncode,
  1056. "command": cmd,
  1057. "stdout": _tail(result.stdout),
  1058. "stderr": _tail(result.stderr),
  1059. })
  1060. ok = all(item["status"] == "pass" for item in results)
  1061. return {"status": "pass" if ok else "fail", **payload, "tool": verilator, "tests": results}
  1062. if backend == "cocotb":
  1063. tests = cocotb_tests()
  1064. payload = {
  1065. **metadata,
  1066. "mode": "python_cosimulation",
  1067. "required_tools": ["python_module:cocotb", "iverilog", "vvp"],
  1068. "authority_boundary": "cocotb is a Python cosimulation framework and still needs a simulator backend; this is not an Anlogic TD requirement.",
  1069. "tests": tests,
  1070. }
  1071. py = cocotb_python()
  1072. has_cocotb = cocotb_module_available(py)
  1073. missing_tools = []
  1074. if not has_cocotb:
  1075. missing_tools.append("python_module:cocotb")
  1076. for tool in ["iverilog", "vvp"]:
  1077. if not resolve_tool(tool):
  1078. missing_tools.append(tool)
  1079. if not run:
  1080. return {"status": "skipped", "reason": "HDL simulation not requested.", **payload}
  1081. if missing_tools:
  1082. return _missing_tool_payload(payload, missing_tools)
  1083. results = []
  1084. for test in tests:
  1085. test_dir = ROOT / test["path"]
  1086. env = tool_env()
  1087. cmd = [py, str(test_dir / "run_pid_core_smoke.py")]
  1088. result = subprocess.run(cmd, cwd=test_dir, env=env, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  1089. results.append({
  1090. "name": test["name"],
  1091. "status": "pass" if result.returncode == 0 else "fail",
  1092. "returncode": result.returncode,
  1093. "command": cmd,
  1094. "cwd": str(test_dir),
  1095. "stdout": _tail(result.stdout),
  1096. "stderr": _tail(result.stderr),
  1097. })
  1098. ok = all(item["status"] == "pass" for item in results)
  1099. return {"status": "pass" if ok else "fail", **payload, "tests": results}
  1100. if backend != "icarus":
  1101. return {"status": "fail", "reason": f"unsupported hdl simulator backend: {backend}", **metadata, "tests": testbenches}
  1102. metadata["required_tools"] = ["iverilog", "vvp"]
  1103. iverilog = resolve_tool("iverilog")
  1104. vvp = resolve_tool("vvp")
  1105. if not run:
  1106. return {
  1107. "status": "skipped",
  1108. "reason": "HDL simulation not requested. Use hdl-sim --run.",
  1109. **metadata,
  1110. "tests": testbenches,
  1111. }
  1112. missing_tools = [name for name, path in [("iverilog", iverilog), ("vvp", vvp)] if not path]
  1113. if missing_tools:
  1114. return _missing_tool_payload({**metadata, "tests": testbenches}, missing_tools)
  1115. sim_dir = ROOT / "tmp" / "rtl_sim"
  1116. sim_dir.mkdir(parents=True, exist_ok=True)
  1117. results = []
  1118. for tb in testbenches:
  1119. out = sim_dir / f"{tb['name']}.vvp"
  1120. compile_cmd = [iverilog, "-g2005-sv", "-o", str(out)] + [str(ROOT / src) for src in tb["sources"]]
  1121. compile_result = subprocess.run(compile_cmd, cwd=ROOT, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  1122. run_result = None
  1123. if compile_result.returncode == 0:
  1124. run_result = subprocess.run([vvp, str(out)], cwd=ROOT, env=tool_env(), text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  1125. results.append({
  1126. "name": tb["name"],
  1127. "status": "pass" if compile_result.returncode == 0 and run_result is not None and run_result.returncode == 0 else "fail",
  1128. "compile_command": compile_cmd,
  1129. "compile_returncode": compile_result.returncode,
  1130. "compile_stdout": _tail(compile_result.stdout, 2000),
  1131. "compile_stderr": _tail(compile_result.stderr, 2000),
  1132. "run_returncode": None if run_result is None else run_result.returncode,
  1133. "run_stdout": "" if run_result is None else _tail(run_result.stdout, 2000),
  1134. "run_stderr": "" if run_result is None else _tail(run_result.stderr, 2000),
  1135. })
  1136. ok = all(item["compile_returncode"] == 0 and item["run_returncode"] == 0 for item in results)
  1137. return {"status": "pass" if ok else "fail", **metadata, "tool": iverilog, "tests": results}
  1138. def rtl_sim_payload(run: bool) -> dict[str, Any]:
  1139. payload = hdl_sim_payload(run=run, backend="icarus")
  1140. payload["verification_layer"] = "rtl_sim_compat"
  1141. return payload
  1142. def formal_payload(run: bool, engine: str = "sby") -> dict[str, Any]:
  1143. payload = {
  1144. "verification_layer": "formal",
  1145. "origin": "project_defined_optional_verification_layer",
  1146. "engine": engine,
  1147. "fact_class": "project_defined_strategy",
  1148. "authority_boundary": "Formal checks prove bounded design properties only when the selected engine actually runs; they are not board or thermal proof.",
  1149. "properties": [
  1150. "fault_implies_ptc_off",
  1151. "invalid_channel_no_actuator",
  1152. "disable_clears_history",
  1153. "thermal_fault_requests_fan_fallback",
  1154. ],
  1155. }
  1156. if engine != "sby":
  1157. return {"status": "fail", "reason": f"unsupported formal engine: {engine}", **payload}
  1158. payload["required_tools"] = ["sby", "yosys"]
  1159. payload["targets"] = formal_targets()
  1160. if not run:
  1161. return {"status": "skipped", "reason": "Formal verification not requested. Use formal --run.", **payload}
  1162. sby = resolve_tool("sby")
  1163. yosys = resolve_tool("yosys")
  1164. missing_tools = [name for name, path in [("sby", sby), ("yosys", yosys)] if not path]
  1165. if missing_tools:
  1166. return _missing_tool_payload(payload, missing_tools)
  1167. results = []
  1168. for target in formal_targets():
  1169. sby_file = ROOT / target["sby"]
  1170. if not sby_file.is_file():
  1171. results.append({
  1172. "name": target["name"],
  1173. "status": "fail",
  1174. "returncode": None,
  1175. "reason": f"missing formal target file: {sby_file}",
  1176. })
  1177. continue
  1178. workdir = ROOT / "tmp" / "formal_runs" / target["name"]
  1179. result = subprocess.run(
  1180. [sby, "-f", "-d", str(workdir), str(sby_file)],
  1181. cwd=sby_file.parent,
  1182. env=tool_env(),
  1183. text=True,
  1184. stdout=subprocess.PIPE,
  1185. stderr=subprocess.PIPE,
  1186. timeout=180,
  1187. )
  1188. counterexamples = []
  1189. if workdir.is_dir():
  1190. counterexamples = [str(path) for path in workdir.rglob("*.vcd")]
  1191. results.append({
  1192. "name": target["name"],
  1193. "status": "pass" if result.returncode == 0 else "fail",
  1194. "returncode": result.returncode,
  1195. "command": [sby, "-f", "-d", str(workdir), str(sby_file)],
  1196. "stdout": _tail(result.stdout),
  1197. "stderr": _tail(result.stderr),
  1198. "workdir": str(workdir),
  1199. "counterexamples": counterexamples,
  1200. })
  1201. ok = all(item["status"] == "pass" for item in results)
  1202. return {"status": "pass" if ok else "fail", **payload, "tool": sby, "yosys": yosys, "targets": results}
  1203. def status(returncode: int) -> str:
  1204. return "pass" if returncode == 0 else "fail"
  1205. def td_log_has_error(*chunks: str) -> bool:
  1206. text = "\n".join(chunk for chunk in chunks if chunk)
  1207. return re.search(r"\b(?:ERROR|Error|error)\b|invalid command name|Cannot open file", text) is not None
  1208. def parse_td_version(*chunks: str) -> dict[str, str | None]:
  1209. text = "\n".join(chunk for chunk in chunks if chunk)
  1210. release = re.search(r"Release_20[0-9.]+(?:_SP[0-9]+)?", text)
  1211. build = re.search(r"\b\d+\.\d+\.\d+\.\d{4,}\b", text)
  1212. return {
  1213. "release": release.group(0) if release else None,
  1214. "build": build.group(0) if build else None,
  1215. }
  1216. def sha256(path: Path) -> str:
  1217. digest = hashlib.sha256()
  1218. with path.open("rb") as handle:
  1219. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  1220. digest.update(chunk)
  1221. return digest.hexdigest()
  1222. def write_json_report(payload: dict[str, Any], path: Path) -> None:
  1223. path.parent.mkdir(parents=True, exist_ok=True)
  1224. path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
  1225. def _speed_history(rounds: list[dict[str, Any]]) -> list[str]:
  1226. history: list[str] = []
  1227. for item in rounds:
  1228. speed = str(item.get("speed") or "")
  1229. if speed and speed not in history:
  1230. history.append(speed)
  1231. return history
  1232. def parse_utc_datetime(value: str) -> datetime:
  1233. normalized = value.strip()
  1234. if normalized.endswith("Z"):
  1235. normalized = normalized[:-1] + "+00:00"
  1236. parsed = datetime.fromisoformat(normalized)
  1237. if parsed.tzinfo is None:
  1238. parsed = parsed.replace(tzinfo=timezone.utc)
  1239. return parsed.astimezone(timezone.utc)
  1240. def contract_replay_payload() -> dict[str, Any]:
  1241. sensor_vector = ROOT / "test_vectors" / "sensor_replay_basic.csv"
  1242. host_vector = ROOT / "test_vectors" / "host_config_replay_basic.csv"
  1243. expectation_vector = ROOT / "test_vectors" / "actuator_expectations_basic.csv"
  1244. samples = load_sensor_csv(sensor_vector)
  1245. host = load_host_csv(host_vector)
  1246. contract_config = load_contract_config()
  1247. control = contract_config.get("control", {})
  1248. actuator = contract_config.get("actuator", {})
  1249. fan_policy = contract_config.get("fan_policy", {})
  1250. if not isinstance(control, dict) or not isinstance(actuator, dict) or not isinstance(fan_policy, dict):
  1251. raise ValueError("pid contract config has invalid control/actuator/fan_policy sections")
  1252. report = run_replay(
  1253. samples=samples,
  1254. host=host,
  1255. pid=ThermalControlService24Ch(
  1256. channel_count=24,
  1257. out_min=int(actuator["out_min"]),
  1258. out_max=int(actuator["out_max"]),
  1259. target_tolerance_q=int(control.get("target_tolerance_q", 7)),
  1260. power_limit=int(control.get("power_limit_default", actuator["out_max"])),
  1261. kp_q=int(control.get("kp_q", 4)),
  1262. ki_q=int(control.get("ki_q", 1)),
  1263. manual_level=int(control.get("manual_level_default", 0)),
  1264. ),
  1265. sink=ActuatorDomain(
  1266. channel_count=24,
  1267. out_min=int(actuator["out_min"]),
  1268. out_max=int(actuator["out_max"]),
  1269. fan_background_level=int(fan_policy.get("background_level", 38)),
  1270. fan_fallback_level=int(fan_policy.get("fallback_level", 127)),
  1271. ),
  1272. )
  1273. verify_replay_expectations(report, load_replay_expectations_csv(expectation_vector))
  1274. return {
  1275. "status": "pass",
  1276. "control_service": str(control.get("default_mode", "incremental_pid_default")),
  1277. "config": config_contract_summary(),
  1278. "sensor_vector": str(sensor_vector),
  1279. "host_vector": str(host_vector),
  1280. "expectation_vector": str(expectation_vector),
  1281. **report.to_dict(),
  1282. }
  1283. def parse_area_report(path: Path) -> dict[str, Any] | None:
  1284. if not path.is_file():
  1285. return None
  1286. text = path.read_text(encoding="utf-8", errors="replace")
  1287. result: dict[str, Any] = {"path": str(path), "utilization": {}, "hierarchy": []}
  1288. hierarchy_columns: list[str] = []
  1289. for line in text.splitlines():
  1290. match = re.match(r"#(lut|reg|dsp|bram|bram32k|pad|pll)\s+(\d+)\s+out of\s+(\d+)\s+([0-9.]+)%", line.strip())
  1291. if match:
  1292. used = int(match.group(2))
  1293. total = int(match.group(3))
  1294. result["utilization"][match.group(1)] = {
  1295. "used": used,
  1296. "total": total,
  1297. "percent": float(match.group(4)),
  1298. }
  1299. continue
  1300. if line.startswith("|") and "Instance" in line and "Module" in line:
  1301. hierarchy_columns = [part.strip().lower() for part in line.strip("|").split("|")]
  1302. continue
  1303. if line.startswith("|") and hierarchy_columns:
  1304. values = [part.rstrip() for part in line.strip("|").split("|")]
  1305. if len(values) != len(hierarchy_columns):
  1306. continue
  1307. row = dict(zip(hierarchy_columns, values))
  1308. if not row.get("instance", "").strip() or row["instance"].strip() == "Instance":
  1309. continue
  1310. parsed_row: dict[str, Any] = {
  1311. "instance": row["instance"].strip(),
  1312. "module": row["module"].strip(),
  1313. }
  1314. for key, value in row.items():
  1315. if key in {"instance", "module"}:
  1316. continue
  1317. parsed_row[key] = int(value.strip())
  1318. result["hierarchy"].append(parsed_row)
  1319. return result
  1320. def parse_timing_report(path: Path) -> dict[str, Any] | None:
  1321. if not path.is_file():
  1322. return None
  1323. text = path.read_text(encoding="utf-8", errors="replace")
  1324. payload: dict[str, Any] = {"path": str(path)}
  1325. sta_coverage = re.search(r"STA coverage\s*:\s*([0-9.]+)%", text)
  1326. if sta_coverage:
  1327. payload["sta_coverage_percent"] = float(sta_coverage.group(1))
  1328. timing_status = re.search(
  1329. r"SWNS:\s*([0-9.+-]+)ns,\s*STNS:\s*([0-9.+-]+)ns\s+"
  1330. r"HWNS:\s*([0-9.+-]+)ns,\s*HTNS:\s*([0-9.+-]+)ns\s+"
  1331. r"Period Check WNS:\s*([0-9.+-]+)ns",
  1332. text,
  1333. )
  1334. if timing_status:
  1335. payload["swns_ns"] = float(timing_status.group(1))
  1336. payload["stns_ns"] = float(timing_status.group(2))
  1337. payload["hwns_ns"] = float(timing_status.group(3))
  1338. payload["htns_ns"] = float(timing_status.group(4))
  1339. payload["period_check_wns_ns"] = float(timing_status.group(5))
  1340. payload["error_count"] = 0 if payload["swns_ns"] >= 0 and payload["hwns_ns"] >= 0 else 1
  1341. clock_names: dict[str, str] = {}
  1342. for match in re.finditer(r"^\s*(clk\d+):\s+[0-9.]+\s+\d+\s+(.+?)\s*$", text, re.MULTILINE):
  1343. clock_names[match.group(1)] = match.group(2).strip()
  1344. clock_summaries: list[dict[str, Any]] = []
  1345. clock_row_re = re.compile(
  1346. r"^\s*(clk\d+)\s+(\S+)\s+"
  1347. r"([0-9.+-]+)\s+([0-9.+-]+)\s+"
  1348. r"([0-9.+-]+)\s+([0-9.+-]+)\s+"
  1349. r"([0-9.+-]+)\s+([0-9.+-]+)\s+"
  1350. r"([0-9.+-]+)\s+([0-9.+-]+)\s+"
  1351. r"([0-9.+-]+)\s+([0-9.+-]+)",
  1352. re.MULTILINE,
  1353. )
  1354. for match in clock_row_re.finditer(text):
  1355. row = {
  1356. "name": match.group(1),
  1357. "clock_name": clock_names.get(match.group(1), match.group(1)),
  1358. "type": match.group(2),
  1359. "rise_ns": float(match.group(3)),
  1360. "fall_ns": float(match.group(4)),
  1361. "period_ns": float(match.group(5)),
  1362. "clock_frequency_mhz": float(match.group(6)),
  1363. "minimum_period_ns": float(match.group(7)),
  1364. "fmax_mhz": float(match.group(8)),
  1365. "worst_setup_slack_ns": float(match.group(9)),
  1366. "setup_total_negative_slack_ns": float(match.group(10)),
  1367. "worst_hold_slack_ns": float(match.group(11)),
  1368. "hold_total_negative_slack_ns": float(match.group(12)),
  1369. }
  1370. clock_summaries.append(row)
  1371. if clock_summaries:
  1372. payload["clock_summaries"] = clock_summaries
  1373. period = re.search(r"Clock = ([^,]+), period ([0-9.]+)ns", text)
  1374. if period:
  1375. payload["clock"] = period.group(1).strip()
  1376. payload["period_ns"] = float(period.group(2))
  1377. clock_summary = re.search(
  1378. r"^\s*clk\d+\s+\S+\s+[0-9.]+\s+[0-9.]+\s+"
  1379. r"([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+"
  1380. r"([0-9.+-]+)\s+([0-9.+-]+)\s+([0-9.+-]+)\s+([0-9.+-]+)",
  1381. text,
  1382. re.MULTILINE,
  1383. )
  1384. if clock_summary:
  1385. payload["period_ns"] = float(clock_summary.group(1))
  1386. payload["clock_frequency_mhz"] = float(clock_summary.group(2))
  1387. payload["minimum_period_ns"] = float(clock_summary.group(3))
  1388. payload["fmax_mhz"] = float(clock_summary.group(4))
  1389. payload["worst_setup_slack_ns"] = float(clock_summary.group(5))
  1390. payload["setup_total_negative_slack_ns"] = float(clock_summary.group(6))
  1391. payload["worst_hold_slack_ns"] = float(clock_summary.group(7))
  1392. payload["hold_total_negative_slack_ns"] = float(clock_summary.group(8))
  1393. errors = re.search(r"(\d+) errors detected : (\d+) setup errors .*?, (\d+) hold errors", text)
  1394. if errors:
  1395. payload["error_count"] = int(errors.group(1))
  1396. payload["setup_error_count"] = int(errors.group(2))
  1397. payload["hold_error_count"] = int(errors.group(3))
  1398. minimum_period = re.search(r"Minimum period is ([0-9.]+)ns", text)
  1399. if minimum_period:
  1400. payload["minimum_period_ns"] = float(minimum_period.group(1))
  1401. slack = re.search(r"Slack \(setup check\):\s+([0-9.+-]+) ns", text)
  1402. if slack:
  1403. payload["worst_setup_slack_ns"] = float(slack.group(1))
  1404. timing_paths: list[dict[str, Any]] = []
  1405. group_context: dict[str, str] = {}
  1406. current_path: dict[str, Any] | None = None
  1407. for raw_line in text.splitlines():
  1408. line = raw_line.strip()
  1409. match = re.match(r"Path Group\s*:\s*(.+?)\s*$", line)
  1410. if match:
  1411. group_context = {"path_group": match.group(1).strip()}
  1412. continue
  1413. match = re.match(r"From Clock\s*:\s*(.+?)\s*$", line)
  1414. if match:
  1415. group_context["from_clock"] = match.group(1).strip()
  1416. continue
  1417. match = re.match(r"To Clock\s*:\s*(.+?)\s*$", line)
  1418. if match:
  1419. group_context["to_clock"] = match.group(1).strip()
  1420. continue
  1421. match = re.match(r"Slack\s*:\s*([0-9.+-]+)ns\s*$", line)
  1422. if match:
  1423. current_path = dict(group_context)
  1424. current_path["slack_ns"] = float(match.group(1))
  1425. continue
  1426. if current_path is None:
  1427. continue
  1428. match = re.match(r"Begin Point\s*:\s*(.+?)\s*$", line)
  1429. if match:
  1430. current_path["begin_point"] = match.group(1).strip()
  1431. continue
  1432. match = re.match(r"End Point\s*:\s*(.+?)\s*$", line)
  1433. if match:
  1434. current_path["end_point"] = match.group(1).strip()
  1435. continue
  1436. match = re.match(r"Check Type\s*:\s*(.+?)\s*$", line)
  1437. if match:
  1438. current_path["check_type"] = match.group(1).strip().lower()
  1439. timing_paths.append(current_path)
  1440. current_path = None
  1441. continue
  1442. if timing_paths:
  1443. payload["timing_paths"] = timing_paths
  1444. payload["negative_timing_paths"] = [item for item in timing_paths if float(item.get("slack_ns", 0.0)) < 0.0]
  1445. return payload
  1446. def td_timing_gate(timing: dict[str, Any] | None) -> dict[str, Any]:
  1447. if timing is None:
  1448. return {"status": "fail", "failures": ["missing timing report"]}
  1449. failures: list[str] = []
  1450. if int(timing.get("error_count", 0)) != 0:
  1451. failures.append(f"timing error_count={timing.get('error_count')}")
  1452. for field in [
  1453. "swns_ns",
  1454. "hwns_ns",
  1455. "period_check_wns_ns",
  1456. "worst_setup_slack_ns",
  1457. "worst_hold_slack_ns",
  1458. ]:
  1459. if field in timing and float(timing[field]) < 0:
  1460. failures.append(f"{field}={timing[field]}")
  1461. if (
  1462. "minimum_period_ns" in timing
  1463. and "period_ns" in timing
  1464. and float(timing["minimum_period_ns"]) > float(timing["period_ns"])
  1465. ):
  1466. failures.append(f"minimum_period_ns={timing['minimum_period_ns']} exceeds period_ns={timing['period_ns']}")
  1467. payload = {
  1468. "status": "pass" if not failures else "fail",
  1469. "failures": failures,
  1470. }
  1471. return payload
  1472. def cmd_model(_: argparse.Namespace) -> int:
  1473. results = [
  1474. run_unit_test("test_pid_model.py"),
  1475. run_unit_test("test_bmc_dimm_parser.py"),
  1476. run_unit_test("test_control_modes.py"),
  1477. run_unit_test("test_pid_contract_model.py"),
  1478. run_unit_test("test_pid_harness.py"),
  1479. run_unit_test("test_debug_bundle.py"),
  1480. run_unit_test("test_debug_environment.py"),
  1481. ]
  1482. ok = True
  1483. for result in results:
  1484. print(result.stdout, end="")
  1485. print(result.stderr, end="", file=sys.stderr)
  1486. ok = ok and result.returncode == 0
  1487. return 0 if ok else 1
  1488. def cmd_replay(args: argparse.Namespace) -> int:
  1489. payload = contract_replay_payload()
  1490. if args.report_file:
  1491. write_json_report(payload, args.report_file)
  1492. print(json.dumps(payload, indent=2) if args.json else render_replay(payload))
  1493. return 0
  1494. def cmd_static(_: argparse.Namespace) -> int:
  1495. result = run_python("verify_pid_study.py")
  1496. print(result.stdout, end="")
  1497. print(result.stderr, end="", file=sys.stderr)
  1498. return result.returncode
  1499. def cmd_td_build(args: argparse.Namespace) -> int:
  1500. payload = td_build_payload(run=args.run, top=getattr(args, "top", DEFAULT_TD_TOP))
  1501. if args.report_file:
  1502. write_json_report(payload, args.report_file)
  1503. print(json.dumps(payload, indent=2) if args.json else render_td_payload(payload))
  1504. return 0 if payload["status"] == "pass" else 1
  1505. def cmd_toolchain(args: argparse.Namespace) -> int:
  1506. payload = probe_toolchain()
  1507. if args.report_file:
  1508. write_json_report(payload, args.report_file)
  1509. print(json.dumps(payload, indent=2) if args.json else f"toolchain: {payload['status']}")
  1510. return 0 if payload["status"] == "pass" else 1
  1511. def cmd_uart_preflight(args: argparse.Namespace) -> int:
  1512. from uart_receipts import build_preflight_receipt
  1513. payload = build_preflight_receipt(allowlist=args.allowlist)
  1514. if args.report_file:
  1515. write_json_report(payload, args.report_file)
  1516. print(json.dumps(payload, indent=2) if args.json else f"uart-preflight: {payload['status']}")
  1517. return 0 if payload["status"] == "pass" else 1
  1518. def cmd_uart_protocol_offline(args: argparse.Namespace) -> int:
  1519. from uart_receipts import build_protocol_offline_receipt
  1520. payload = build_protocol_offline_receipt(
  1521. text=args.text_file.read_text(encoding="utf-8"),
  1522. scenario=args.scenario,
  1523. )
  1524. if args.report_file:
  1525. write_json_report(payload, args.report_file)
  1526. print(json.dumps(payload, indent=2) if args.json else f"uart-protocol-offline: {payload['status']}")
  1527. return 0 if payload["status"] == "pass" else 1
  1528. def cmd_uart_validate(args: argparse.Namespace) -> int:
  1529. from uart_receipts import validate_uart_receipt
  1530. payload = validate_uart_receipt(args.receipt, strict=args.strict)
  1531. if args.report_file:
  1532. write_json_report(payload, args.report_file)
  1533. print(json.dumps(payload, indent=2) if args.json else f"uart-validate: {payload['status']}")
  1534. return 0 if payload["status"] == "pass" else 1
  1535. def cmd_final_gate_v2(args: argparse.Namespace) -> int:
  1536. from uart_receipts import validate_final_gate_v2_receipt, validate_uart_receipt
  1537. static = run_python("verify_pid_study.py")
  1538. model_unit = run_unit_test("test_pid_model.py")
  1539. model_bmc_parser = run_unit_test("test_bmc_dimm_parser.py")
  1540. model_control_modes = run_unit_test("test_control_modes.py")
  1541. model_contract = run_unit_test("test_pid_contract_model.py")
  1542. model_harness = run_unit_test("test_pid_harness.py")
  1543. model_debug_bundle = run_unit_test("test_debug_bundle.py")
  1544. model_debug_environment = run_unit_test("test_debug_environment.py")
  1545. model_ok = all(
  1546. item.returncode == 0
  1547. for item in [
  1548. model_unit,
  1549. model_bmc_parser,
  1550. model_control_modes,
  1551. model_contract,
  1552. model_harness,
  1553. model_debug_bundle,
  1554. model_debug_environment,
  1555. ]
  1556. )
  1557. replay = contract_replay_payload()
  1558. rtl = hdl_sim_payload(run=args.rtl_sim, backend=args.hdl_backend)
  1559. formal_result = formal_payload(run=args.formal, engine=args.formal_engine)
  1560. detector = detector_selftest_payload(run=args.detector_selftest, backend="all")
  1561. td = td_build_payload(run=args.td_build, top=args.td_top)
  1562. uart = validate_uart_receipt(args.receipt, strict=True)
  1563. layers = {
  1564. "static": {"status": status(static.returncode), "returncode": static.returncode},
  1565. "model": {"status": "pass" if model_ok else "fail"},
  1566. "replay": replay,
  1567. "rtl_sim": {"status": rtl["status"]},
  1568. "formal": {"status": formal_result["status"]},
  1569. "detector_selftest": {"status": detector["status"]},
  1570. "td_build": {"status": td["status"]},
  1571. "uart_strict": uart,
  1572. }
  1573. receipt = {
  1574. "schema": "final-gate-v2-receipt-v1",
  1575. "generated_at": datetime.now(timezone.utc).isoformat(),
  1576. "status": "pass",
  1577. "layers": layers,
  1578. "authority_boundary": "Machine pass means control communication chain and software safety strategy passed; it does not certify full thermal performance.",
  1579. }
  1580. validation = validate_final_gate_v2_receipt(receipt, strict=True)
  1581. receipt["status"] = validation["status"]
  1582. payload = {
  1583. **receipt,
  1584. "validation": validation,
  1585. "static": {"stdout": static.stdout, "stderr": static.stderr},
  1586. "model_detail": {
  1587. "unit": model_unit.returncode,
  1588. "bmc_dimm_parser": model_bmc_parser.returncode,
  1589. "control_modes": model_control_modes.returncode,
  1590. "contract": model_contract.returncode,
  1591. "harness": model_harness.returncode,
  1592. "debug_bundle": model_debug_bundle.returncode,
  1593. "debug_environment": model_debug_environment.returncode,
  1594. },
  1595. }
  1596. if args.report_file:
  1597. write_json_report(payload, args.report_file)
  1598. print(json.dumps(payload, indent=2) if args.json else f"final-gate-v2: {payload['status']}")
  1599. return 0 if payload["status"] == "pass" else 1
  1600. def _tool_present(toolchain: dict[str, Any], name: str) -> bool:
  1601. tools = toolchain.get("tools", {})
  1602. item = tools.get(name)
  1603. return isinstance(item, dict) and item.get("status") == "present"
  1604. def _offline_required_tool_status(toolchain: dict[str, Any]) -> tuple[bool, list[str]]:
  1605. required = ["iverilog", "vvp", "verilator", "yosys", "sby", "cocotb", "td_cli"]
  1606. missing = [name for name in required if not _tool_present(toolchain, name)]
  1607. return not missing, missing
  1608. def offline_toolchain_probe_payload() -> dict[str, Any]:
  1609. tools = {
  1610. "python": {
  1611. "name": "python",
  1612. "status": "present",
  1613. "path": sys.executable,
  1614. "version": sys.version.split()[0],
  1615. "fact_class": "local_detected_fact",
  1616. },
  1617. "iverilog": {"name": "iverilog", "status": "present" if resolve_tool("iverilog") else "missing", "path": resolve_tool("iverilog")},
  1618. "vvp": {"name": "vvp", "status": "present" if resolve_tool("vvp") else "missing", "path": resolve_tool("vvp")},
  1619. "verilator": {"name": "verilator", "status": "present" if resolve_tool("verilator") else "missing", "path": resolve_tool("verilator")},
  1620. "yosys": {"name": "yosys", "status": "present" if resolve_tool("yosys") else "missing", "path": resolve_tool("yosys")},
  1621. "sby": {"name": "sby", "status": "present" if resolve_tool("sby") else "missing", "path": resolve_tool("sby")},
  1622. "cocotb": {
  1623. "name": "python_module:cocotb",
  1624. "status": "present" if cocotb_module_available(cocotb_python()) else "missing",
  1625. "python": cocotb_python(),
  1626. },
  1627. "td_cli": {
  1628. "name": "td_commands_prompt",
  1629. "status": "present" if TD_EXE.is_file() else "missing",
  1630. "path": str(TD_EXE) if TD_EXE.is_file() else None,
  1631. },
  1632. }
  1633. return {
  1634. "schema": "offline-toolchain-probe-v1",
  1635. "status": "pass",
  1636. "generated_at": datetime.now(timezone.utc).isoformat(),
  1637. "tools": tools,
  1638. "serial_ports": {
  1639. "status": "not_queried",
  1640. "reason": "offline-fidelity-gate-v1 forbids COM probing in toolchain bootstrap",
  1641. },
  1642. "authority_boundary": "Offline toolchain probe checks user-space simulator/formal/TD CLI availability only; it does not enumerate or open serial ports.",
  1643. }
  1644. def offline_toolchain_bootstrap_payload(auto_bootstrap: bool = False) -> dict[str, Any]:
  1645. before = offline_toolchain_probe_payload()
  1646. bootstrap_attempts: list[dict[str, Any]] = []
  1647. after = before
  1648. generated_at = datetime.now(timezone.utc).isoformat()
  1649. manifest: dict[str, Any] = {
  1650. "schema": "offline-toolchain-bootstrap-manifest-v1",
  1651. "generated_at": generated_at,
  1652. "project_root": str(ROOT),
  1653. "toolchain_base": str(DEFAULT_TOOLCHAIN_BASE),
  1654. "install_roots": {
  1655. "oss_cad_suite": str(DEFAULT_OSS_CAD_SUITE_ROOT),
  1656. "cocotb_venv": str(DEFAULT_COCOTB_VENV_PYTHON.parent.parent),
  1657. "downloads": str(DEFAULT_TOOLCHAIN_BASE / "downloads"),
  1658. "manifests": str(DEFAULT_TOOLCHAIN_BASE / "manifests"),
  1659. },
  1660. "created_paths": [],
  1661. "reused_paths": [],
  1662. "downloads": [],
  1663. "tools": [],
  1664. "cleanup_plan": {
  1665. "default": "dry_run",
  1666. "requires_owner_marker": True,
  1667. "allowed_root": str(DEFAULT_TOOLCHAIN_BASE),
  1668. },
  1669. "safety": {
  1670. "opens_com_ports": False,
  1671. "toggles_dtr_rts": False,
  1672. "installs_drivers": False,
  1673. "programs_flash": False,
  1674. "touches_ptc_fan_bmc": False,
  1675. },
  1676. }
  1677. if auto_bootstrap:
  1678. try:
  1679. from bootstrap_oss_cad_suite import (
  1680. DEFAULT_BUNDLED_PYTHON,
  1681. DEFAULT_COCOTB_VENV,
  1682. DEFAULT_DOWNLOAD_DIR,
  1683. DEFAULT_ROOT,
  1684. install_cocotb_venv,
  1685. install_latest_windows_x64,
  1686. )
  1687. _, missing_before = _offline_required_tool_status(before)
  1688. if any(name in missing_before for name in ["iverilog", "vvp", "verilator", "yosys", "sby"]):
  1689. try:
  1690. installed = install_latest_windows_x64(install_root=DEFAULT_ROOT, download_dir=DEFAULT_DOWNLOAD_DIR)
  1691. bootstrap_attempts.append({"name": "oss_cad_suite", "status": installed.get("status", "present"), "report": installed})
  1692. manifest["reused_paths"].append(str(installed.get("install_root", DEFAULT_ROOT)))
  1693. if installed.get("asset"):
  1694. manifest["downloads"].append({
  1695. "name": installed.get("asset", {}).get("name"),
  1696. "url": installed.get("asset", {}).get("browser_download_url"),
  1697. "size": installed.get("asset", {}).get("size"),
  1698. "sha256": installed.get("sha256"),
  1699. })
  1700. except Exception as exc: # pragma: no cover - network/tool bootstrap is environment-dependent.
  1701. bootstrap_attempts.append({"name": "oss_cad_suite", "status": "blocked_bootstrap_failed", "error": str(exc)})
  1702. if "cocotb" in missing_before:
  1703. try:
  1704. installed = install_cocotb_venv(venv_dir=DEFAULT_COCOTB_VENV, python_exe=DEFAULT_BUNDLED_PYTHON)
  1705. bootstrap_attempts.append({"name": "cocotb_venv", "status": installed.get("status", "present"), "report": installed})
  1706. manifest["reused_paths"].append(str(installed.get("venv_dir", DEFAULT_COCOTB_VENV)))
  1707. except Exception as exc: # pragma: no cover - venv/bootstrap is environment-dependent.
  1708. bootstrap_attempts.append({"name": "cocotb_venv", "status": "blocked_bootstrap_failed", "error": str(exc)})
  1709. except Exception as exc: # pragma: no cover - import path is stable in unit tests.
  1710. bootstrap_attempts.append({"name": "bootstrap_helper", "status": "blocked_bootstrap_failed", "error": str(exc)})
  1711. after = offline_toolchain_probe_payload()
  1712. ok, missing = _offline_required_tool_status(after)
  1713. manifest["tools"] = [
  1714. {"name": name, "status": info.get("status"), "path": info.get("path") or info.get("python")}
  1715. for name, info in (after.get("tools") or {}).items()
  1716. ]
  1717. cleanup_policy = {
  1718. "default": "dry_run",
  1719. "requires_owner_marker": True,
  1720. "allowed_root": str(DEFAULT_TOOLCHAIN_BASE),
  1721. "owner_marker_name": ".cpld_toolchain_owner.json",
  1722. "actual_delete_requires_apply": True,
  1723. }
  1724. return {
  1725. "schema": "offline-toolchain-bootstrap-v1",
  1726. "status": "pass" if ok else "blocked_missing_tool",
  1727. "auto_bootstrap_requested": auto_bootstrap,
  1728. "bootstrap_attempts": bootstrap_attempts,
  1729. "missing_tools": missing,
  1730. "toolchain": after,
  1731. "manifest": manifest,
  1732. "cleanup_policy": cleanup_policy,
  1733. "safety": {
  1734. "opens_com_ports": False,
  1735. "toggles_dtr_rts": False,
  1736. "installs_drivers": False,
  1737. "programs_flash": False,
  1738. "touches_ptc_fan_bmc": False,
  1739. },
  1740. "authority_boundary": "user-space offline toolchain bootstrap only: downloads/extracts local OSS CAD Suite or cocotb venv when requested; it never opens COM ports, installs drivers, programs flash, or actuates real hardware.",
  1741. }
  1742. def _protocol_status_matches(actual: str, expected: str) -> bool:
  1743. if expected == "pass":
  1744. return actual == PARSER_STATUS_OK
  1745. return actual == expected
  1746. def protocol_fuzz_payload() -> dict[str, Any]:
  1747. parser = BmcDimmFrameParser(fraction_scale=100)
  1748. valid_pairs = " ".join(["23 4b"] * 24)
  1749. valid_pairs_0x = " ".join(["0x23 0x4b"] * 24)
  1750. missing_all = " ".join(["ff ff"] * 24)
  1751. missing_some = " ".join((["ff ff"] * 4) + (["25 00"] * 20))
  1752. long_frame = "00 11 " + valid_pairs + " aa bb cc dd"
  1753. bad_fraction = " ".join(["23 64"] + ["23 4b"] * 23)
  1754. scenarios = [
  1755. ("no_echo_bare_hex", valid_pairs, "pass"),
  1756. ("echo_0x_multiline", "ipmitool raw 0x36 0x6c 0xdf 0xdd 0x00 0x03\n" + valid_pairs_0x, "pass"),
  1757. ("multi_line_commas_quotes", "(" + ", ".join(['\"23\"', '\"4b\"'] * 24) + ")", "pass"),
  1758. ("garbage_prefix_suffix", "noise ~~ " + valid_pairs + " trailing words", "pass"),
  1759. ("short_frame", " ".join(["23 4b"] * 12), PARSER_STATUS_NO_CANDIDATE),
  1760. ("long_frame", long_frame, "pass"),
  1761. ("bad_fraction", bad_fraction, PARSER_STATUS_NO_CANDIDATE),
  1762. ("all_missing", missing_all, PARSER_STATUS_NO_CANDIDATE),
  1763. ("partial_missing", missing_some, "pass"),
  1764. ("malformed_text", "zz yy hello world", PARSER_STATUS_NO_CANDIDATE),
  1765. ]
  1766. results = []
  1767. for index, (name, text, expected) in enumerate(scenarios, start=1):
  1768. result = parser.parse_text_response(text, frame_seq=index, sample_seq_base=index * 100, age_ms=0)
  1769. actual = result.parser_status
  1770. ok = _protocol_status_matches(actual, expected)
  1771. results.append({
  1772. "name": name,
  1773. "status": "pass" if ok else "fail",
  1774. "expected_parser_status": expected,
  1775. "parser_status": actual,
  1776. "sample_count": len(result.samples),
  1777. "missing_mask": result.missing_mask,
  1778. "raw_token_count": result.raw_token_count,
  1779. "selected_window_start": result.selected_window_start,
  1780. "rejected_echo_windows": result.rejected_echo_windows,
  1781. })
  1782. return {
  1783. "status": "pass" if all(item["status"] == "pass" for item in results) else "fail",
  1784. "verification_layer": "protocol_fuzz",
  1785. "scenarios": results,
  1786. "required_scenarios": [
  1787. "echo/no-echo",
  1788. "bare hex",
  1789. "0xNN",
  1790. "multi-line",
  1791. "garbage",
  1792. "short frame",
  1793. "long frame",
  1794. "bad fraction",
  1795. "all missing",
  1796. "partial missing",
  1797. ],
  1798. "authority_boundary": "Offline BMC text parser fuzzing proves parser contract behavior only; it does not prove electrical UART timing.",
  1799. }
  1800. def cocotb_virtual_lab_payload(run: bool, backend: str = "cocotb") -> dict[str, Any]:
  1801. sim = hdl_sim_payload(run=run, backend="cocotb")
  1802. return {
  1803. "status": sim["status"],
  1804. "verification_layer": "cocotb_virtual_lab",
  1805. "backend": backend,
  1806. "virtual_devices": [
  1807. "uart_8n1_bit_driver",
  1808. "bmc_text_emulator",
  1809. "host_register_plane",
  1810. "fault_injector",
  1811. "thermal_digital_twin_driver",
  1812. "scoreboard",
  1813. ],
  1814. "required_behaviors": [
  1815. "BMC RX/TX bit stream",
  1816. "debug UART TX decode",
  1817. "host register write/read",
  1818. "fault injection",
  1819. "thermal model callback",
  1820. "end-to-end scoreboard",
  1821. ],
  1822. "sim": sim,
  1823. "authority_boundary": "cocotb virtual lab is simulator-only evidence and never opens serial ports or acts on real PTC/fan/BMC devices.",
  1824. }
  1825. class VirtualDriverError(RuntimeError):
  1826. pass
  1827. class VirtualPipe:
  1828. def __init__(self, *, capacity: int = 8, readable: bool = True, writable: bool = True) -> None:
  1829. self.capacity = capacity
  1830. self.readable = readable
  1831. self.writable = writable
  1832. self.buffer = bytearray()
  1833. self.disconnected = False
  1834. def write(self, data: bytes) -> int:
  1835. if self.disconnected:
  1836. raise TimeoutError("virtual pipe disconnected")
  1837. if not self.writable:
  1838. raise PermissionError("virtual pipe write denied")
  1839. available = self.capacity - len(self.buffer)
  1840. if available <= 0:
  1841. raise BufferError("virtual pipe overflow/backpressure")
  1842. accepted = min(len(data), available)
  1843. self.buffer.extend(data[:accepted])
  1844. return accepted
  1845. def read(self, size: int) -> bytes:
  1846. if self.disconnected:
  1847. raise TimeoutError("virtual pipe disconnected")
  1848. if not self.readable:
  1849. raise PermissionError("virtual pipe read denied")
  1850. if not self.buffer:
  1851. raise TimeoutError("virtual pipe timeout")
  1852. count = min(size, len(self.buffer))
  1853. data = bytes(self.buffer[:count])
  1854. del self.buffer[:count]
  1855. return data
  1856. class HostRegisterPlane:
  1857. def __init__(self) -> None:
  1858. self.registers: dict[int, int] = {}
  1859. self.config_seq = 0
  1860. def write(self, addr: int, value: int, width: int = 4) -> None:
  1861. if addr < 0 or addr > 0x93:
  1862. raise ValueError("invalid host register address")
  1863. if width not in {1, 2, 4}:
  1864. raise ValueError("invalid partial write width")
  1865. mask = (1 << (width * 8)) - 1
  1866. previous = self.registers.get(addr, 0)
  1867. self.registers[addr] = (previous & ~mask) | (value & mask)
  1868. self.config_seq = (self.config_seq + 1) & 0xffff
  1869. def read(self, addr: int) -> int:
  1870. if addr < 0 or addr > 0x93:
  1871. raise ValueError("invalid host register address")
  1872. return self.registers.get(addr, 0)
  1873. def _debug_uart_frame(seq: int, payload: bytes) -> bytes:
  1874. checksum = 0xA5 ^ 0x5A ^ (seq & 0xff) ^ ((seq >> 8) & 0xff)
  1875. for byte in payload:
  1876. checksum ^= byte
  1877. return bytes([0xA5, 0x5A, seq & 0xff, (seq >> 8) & 0xff, *payload, checksum])
  1878. def _decode_debug_uart_frame(frame: bytes) -> dict[str, Any]:
  1879. if len(frame) < 5:
  1880. raise ValueError("short debug UART frame")
  1881. if frame[0:2] != b"\xa5\x5a":
  1882. raise ValueError("bad debug UART SOF")
  1883. checksum = 0
  1884. for byte in frame[:-1]:
  1885. checksum ^= byte
  1886. if checksum != frame[-1]:
  1887. raise ValueError("bad debug UART checksum")
  1888. return {
  1889. "sof": "a55a",
  1890. "frame_seq": frame[2] | (frame[3] << 8),
  1891. "payload_hex": frame[4:-1].hex(),
  1892. "checksum": frame[-1],
  1893. }
  1894. def _virtual_driver_lab_scenarios() -> list[dict[str, Any]]:
  1895. scenarios: list[dict[str, Any]] = []
  1896. pipe = VirtualPipe(capacity=32)
  1897. written = pipe.write(b"UART_LOOPBACK")
  1898. loopback = pipe.read(32)
  1899. scenarios.append({
  1900. "name": "pyserial_loopback_url",
  1901. "status": "pass" if written == 13 and loopback == b"UART_LOOPBACK" else "fail",
  1902. "transport": "loop:// user-mode emulation",
  1903. "assertions": ["write_count", "readback_match", "no_com_name"],
  1904. "transcript": {"written": written, "read_hex": loopback.hex()},
  1905. })
  1906. left, right = socket.socketpair()
  1907. try:
  1908. left.settimeout(0.1)
  1909. right.settimeout(0.1)
  1910. left.sendall(b"host->bmc")
  1911. received = right.recv(32)
  1912. finally:
  1913. left.close()
  1914. right.close()
  1915. scenarios.append({
  1916. "name": "socket_pipe_transport",
  1917. "status": "pass" if received == b"host->bmc" else "fail",
  1918. "transport": "in_process_socketpair",
  1919. "assertions": ["full_duplex_user_mode_transport"],
  1920. "transcript": {"received_hex": received.hex()},
  1921. })
  1922. parser_cases = [
  1923. ("echo", BMC_POLL_COMMAND_ASCII + "\n" + BMC_DIMM_USER_SAMPLE_TEXT),
  1924. ("no_echo", BMC_DIMM_USER_SAMPLE_TEXT),
  1925. ("multi_line", "noise\n" + BMC_DIMM_USER_SAMPLE_TEXT + "\n"),
  1926. ("malformed_hex", "0xGG"),
  1927. ("short_frame", "10 20"),
  1928. ("long_frame", " ".join(["10"] * 40)),
  1929. ("missing", "-- -- --"),
  1930. ]
  1931. parser = BmcDimmFrameParser(fraction_scale=100)
  1932. parser_results = []
  1933. for index, (name, text_value) in enumerate(parser_cases, start=1):
  1934. result = parser.parse_text_response(text_value, frame_seq=index, sample_seq_base=0, age_ms=0)
  1935. parser_results.append({
  1936. "name": name,
  1937. "parser_status": result.parser_status,
  1938. "sample_count": len(result.samples),
  1939. "missing_mask": result.missing_mask,
  1940. })
  1941. scenarios.append({
  1942. "name": "bmc_text_driver",
  1943. "status": "pass" if any(item["parser_status"] == PARSER_STATUS_OK for item in parser_results) and any(item["parser_status"] != PARSER_STATUS_OK for item in parser_results) else "fail",
  1944. "transport": "in_process_text_stream",
  1945. "assertions": ["valid_and_invalid_bmc_text_paths_executed"],
  1946. "transcript": parser_results,
  1947. })
  1948. regs = HostRegisterPlane()
  1949. host_assertions = []
  1950. try:
  1951. regs.write(0x10, 0x12345678)
  1952. regs.write(0x10, 0xAB, width=1)
  1953. host_assertions.append(regs.read(0x10) == 0x123456AB)
  1954. try:
  1955. regs.write(0x200, 1)
  1956. host_assertions.append(False)
  1957. except ValueError:
  1958. host_assertions.append(True)
  1959. host_assertions.append(regs.config_seq == 2)
  1960. except Exception:
  1961. host_assertions.append(False)
  1962. scenarios.append({
  1963. "name": "host_register_plane",
  1964. "status": "pass" if all(host_assertions) else "fail",
  1965. "transport": "in_process_register_api",
  1966. "assertions": ["readback", "partial_write", "invalid_addr", "config_seq"],
  1967. "transcript": {"reg_0x10": regs.read(0x10), "config_seq": regs.config_seq, "assertions": host_assertions},
  1968. })
  1969. frame = _debug_uart_frame(2, bytes.fromhex("12345678"))
  1970. decoded = _decode_debug_uart_frame(frame)
  1971. bad_checksum_detected = False
  1972. try:
  1973. _decode_debug_uart_frame(frame[:-1] + bytes([frame[-1] ^ 0x01]))
  1974. except ValueError:
  1975. bad_checksum_detected = True
  1976. scenarios.append({
  1977. "name": "debug_uart_decoder",
  1978. "status": "pass" if decoded["frame_seq"] == 2 and decoded["payload_hex"] == "12345678" and bad_checksum_detected else "fail",
  1979. "transport": "in_process_uart_frame_decoder",
  1980. "assertions": ["sof", "frame_seq", "payload", "checksum", "bad_checksum_rejected"],
  1981. "transcript": {"decoded": decoded, "bad_checksum_detected": bad_checksum_detected},
  1982. })
  1983. fault_results = []
  1984. for fault in [
  1985. "timeout",
  1986. "disconnect",
  1987. "partial_read",
  1988. "partial_write",
  1989. "permission_denied",
  1990. "buffer_overflow",
  1991. "tx_backpressure",
  1992. "rx_overflow",
  1993. ]:
  1994. status_value = "fail"
  1995. detail: dict[str, Any] = {"fault": fault}
  1996. try:
  1997. if fault == "timeout":
  1998. VirtualPipe().read(1)
  1999. elif fault == "disconnect":
  2000. p = VirtualPipe()
  2001. p.disconnected = True
  2002. p.write(b"x")
  2003. elif fault == "partial_read":
  2004. p = VirtualPipe(capacity=8)
  2005. p.write(b"abcdef")
  2006. status_value = "pass" if p.read(3) == b"abc" and p.read(3) == b"def" else "fail"
  2007. elif fault == "partial_write":
  2008. p = VirtualPipe(capacity=3)
  2009. status_value = "pass" if p.write(b"abcdef") == 3 and p.read(3) == b"abc" else "fail"
  2010. elif fault == "permission_denied":
  2011. VirtualPipe(writable=False).write(b"x")
  2012. elif fault in {"buffer_overflow", "tx_backpressure"}:
  2013. p = VirtualPipe(capacity=1)
  2014. p.write(b"x")
  2015. p.write(b"y")
  2016. elif fault == "rx_overflow":
  2017. p = VirtualPipe(capacity=2)
  2018. p.write(b"xy")
  2019. p.write(b"z")
  2020. except (TimeoutError, PermissionError, BufferError):
  2021. if fault not in {"partial_read", "partial_write"}:
  2022. status_value = "pass"
  2023. fault_results.append({"name": fault, "status": status_value, **detail})
  2024. scenarios.append({
  2025. "name": "fault_injection_facade",
  2026. "status": "pass" if all(item["status"] == "pass" for item in fault_results) else "fail",
  2027. "transport": "in_process_error_injector",
  2028. "assertions": [item["name"] for item in fault_results],
  2029. "transcript": fault_results,
  2030. })
  2031. return scenarios
  2032. def virtual_driver_lab_payload(long_run: str = "ci") -> dict[str, Any]:
  2033. fault_cases = [
  2034. "timeout",
  2035. "disconnect",
  2036. "partial_read",
  2037. "partial_write",
  2038. "permission_denied",
  2039. "buffer_overflow",
  2040. "tx_backpressure",
  2041. "rx_overflow",
  2042. ]
  2043. scenarios = _virtual_driver_lab_scenarios()
  2044. trace_hash = hashlib.sha256(json.dumps({"long_run": long_run, "scenarios": scenarios}, sort_keys=True).encode("utf-8")).hexdigest()
  2045. return {
  2046. "status": "pass" if all(item["status"] == "pass" for item in scenarios) else "fail",
  2047. "verification_layer": "virtual_driver_lab",
  2048. "long_run": long_run,
  2049. "user_mode_shims": scenarios,
  2050. "fault_contracts": fault_cases,
  2051. "scenario_count": len(scenarios),
  2052. "sandbox_evidence": {
  2053. "status": "not_required",
  2054. "mode": "optional_windows_sandbox_or_vm_receipt",
  2055. "host_driver_install_allowed": False,
  2056. },
  2057. "trace_hash": trace_hash,
  2058. "safety": {
  2059. "opens_com_ports": False,
  2060. "toggles_dtr_rts": False,
  2061. "installs_drivers": False,
  2062. "programs_flash": False,
  2063. "touches_ptc_fan_bmc": False,
  2064. "real_ptc_fan_bmc_action_attempted": False,
  2065. },
  2066. "authority_boundary": "virtual_driver_lab proves user-mode simulated driver contracts only; it does not certify host OS drivers, hardware UART, board wiring, or thermal performance.",
  2067. }
  2068. def _scenario_duration(long_run: str) -> tuple[float, int]:
  2069. if long_run == "final":
  2070. return 24.0, 24 * 60 * 60
  2071. if long_run == "nightly":
  2072. return 8.0, 8 * 60 * 60
  2073. return 60.0 / 3600.0, 60
  2074. def _thermal_model_specs() -> list[dict[str, Any]]:
  2075. return [
  2076. {"name": "conservative", "seed": 260626, "self": 1.35, "neighbor": 0.08, "same_zone": 0.03, "cross": 0.01, "noise": 1, "missing_mask": 0},
  2077. {"name": "optimistic", "seed": 260627, "self": 0.55, "neighbor": 0.02, "same_zone": 0.005, "cross": 0.002, "noise": 0, "missing_mask": 0},
  2078. {"name": "extreme", "seed": 260628, "self": 1.75, "neighbor": 0.12, "same_zone": 0.05, "cross": 0.02, "noise": 3, "missing_mask": 0},
  2079. {"name": "random_perturbation", "seed": 260629, "self": 1.10, "neighbor": 0.06, "same_zone": 0.02, "cross": 0.015, "noise": 5, "missing_mask": 0},
  2080. {"name": "sensor_drift_delay", "seed": 260630, "self": 1.00, "neighbor": 0.05, "same_zone": 0.02, "cross": 0.01, "noise": 2, "missing_mask": 1 << 7},
  2081. {"name": "crosstalk_fan_degradation", "seed": 260631, "self": 1.25, "neighbor": 0.10, "same_zone": 0.04, "cross": 0.035, "noise": 2, "missing_mask": 0},
  2082. {"name": "ptc_thermal_inertia", "seed": 260632, "self": 1.45, "neighbor": 0.07, "same_zone": 0.025, "cross": 0.015, "noise": 1, "missing_mask": 1 << 13},
  2083. ]
  2084. def thermal_digital_twin_payload(long_run: str = "ci") -> dict[str, Any]:
  2085. duration_hours, duration_seconds = _scenario_duration(long_run)
  2086. max_epochs = {"ci": 60, "nightly": 240, "final": 720}.get(long_run, 60)
  2087. models = []
  2088. for spec in _thermal_model_specs():
  2089. model = FakeStressModel(
  2090. seed=int(spec["seed"]),
  2091. self_coupling=float(spec["self"]),
  2092. neighbor_coupling=float(spec["neighbor"]),
  2093. same_zone_coupling=float(spec["same_zone"]),
  2094. cross_zone_coupling=float(spec["cross"]),
  2095. missing_mask=int(spec["missing_mask"]),
  2096. )
  2097. safety = SafetySupervisor(host_timeout_samples=10)
  2098. actuator = ActuatorDomain()
  2099. max_temp = 0
  2100. violations: list[str] = []
  2101. reason_counts: dict[str, int] = {}
  2102. trace_points: list[dict[str, Any]] = []
  2103. duties = [80 if channel % 4 else 127 for channel in range(24)]
  2104. for epoch in range(max_epochs):
  2105. steps = model.step_long_scenario(duties)
  2106. for step in steps:
  2107. drift_q = 6 if spec["name"] == "sensor_drift_delay" and epoch > max_epochs // 2 else 0
  2108. degraded_temp = step.temp_q + drift_q
  2109. if spec["name"] == "ptc_thermal_inertia" and epoch % 9 == 0:
  2110. degraded_temp += 5
  2111. sample = SensorSampleV2(
  2112. valid=not step.missing,
  2113. ready=True,
  2114. source_id=6,
  2115. channel=step.channel,
  2116. temp_q=degraded_temp,
  2117. fault=step.missing,
  2118. stale=step.stale,
  2119. sample_seq=step.sample_seq,
  2120. raw_status=0,
  2121. )
  2122. config = HostConfigV2(
  2123. enable=True,
  2124. target_q=70,
  2125. a0=6,
  2126. a1=-2,
  2127. a2=1,
  2128. mode=3,
  2129. config_seq=epoch + 1,
  2130. watchdog_kick=not step.stale,
  2131. )
  2132. state = safety.evaluate(sample, config, interlock=False)
  2133. pid_result = PidResult(
  2134. valid=sample.valid,
  2135. channel=sample.channel,
  2136. error_q=max(0, config.target_q - sample.temp_q),
  2137. ctrl_q=0 if sample.temp_q >= 90 else step.duty,
  2138. done=True,
  2139. fault=sample.fault or sample.stale or sample.temp_q >= 90,
  2140. sample_seq=sample.sample_seq,
  2141. target_q=config.target_q,
  2142. )
  2143. ptc = actuator.route_ptc(pid_result, state)
  2144. fan = actuator.route_fan(0, state)
  2145. reason_counts[ptc.reason] = reason_counts.get(ptc.reason, 0) + 1
  2146. max_temp = max(max_temp, degraded_temp)
  2147. fail_closed_fault = ptc.force_off and not ptc.enable and ptc.duty_or_level == 0
  2148. if (sample.fault or sample.stale or state.fault_code != 0 or degraded_temp >= 90) and not fail_closed_fault:
  2149. violations.append(f"ptc_not_fail_closed:epoch={epoch}:channel={sample.channel}:fault_code={state.fault_code}")
  2150. if state.fault_code in {2, 3, 4, 5} and fan.duty_or_level != 127:
  2151. violations.append(f"fan_not_fallback:epoch={epoch}:channel={sample.channel}:fault_code={state.fault_code}")
  2152. if epoch < 16 and len(trace_points) < 128:
  2153. trace_points.append({
  2154. "epoch": epoch,
  2155. "channel": sample.channel,
  2156. "temp_q": sample.temp_q,
  2157. "fault_code": state.fault_code,
  2158. "ptc_force_off": ptc.force_off,
  2159. "fan_duty": fan.duty_or_level,
  2160. "reason": ptc.reason,
  2161. })
  2162. trace_hash = hashlib.sha256(json.dumps(trace_points, sort_keys=True).encode("utf-8")).hexdigest()
  2163. models.append({
  2164. "name": spec["name"],
  2165. "status": "pass" if not violations else "fail",
  2166. "seed": spec["seed"],
  2167. "epochs_executed": max_epochs,
  2168. "duration_seconds_requested": duration_seconds,
  2169. "max_temp_q_observed": max_temp,
  2170. "reason_counts": reason_counts,
  2171. "trace_hash": trace_hash,
  2172. "trace_point_count": len(trace_points),
  2173. "violations": violations[:20],
  2174. "parameters": {
  2175. "self_coupling": spec["self"],
  2176. "neighbor_coupling": spec["neighbor"],
  2177. "same_zone_coupling": spec["same_zone"],
  2178. "cross_zone_coupling": spec["cross"],
  2179. "noise_q": spec["noise"],
  2180. "missing_mask": spec["missing_mask"],
  2181. },
  2182. })
  2183. return {
  2184. "status": "pass" if all(item["status"] == "pass" for item in models) else "fail",
  2185. "verification_layer": "thermal_digital_twin",
  2186. "long_run": long_run,
  2187. "duration_hours_requested": int(duration_hours) if duration_hours.is_integer() else duration_hours,
  2188. "duration_seconds_requested": duration_seconds,
  2189. "execution_policy": "compressed deterministic offline epochs; final receipt records requested soak duration and reproducible model seeds",
  2190. "models": models,
  2191. "calibration_status": "uncalibrated_verification_assumption",
  2192. "authority_boundary": "The digital twin stresses fail-closed logic under synthetic thermal assumptions; it is not a real calibrated thermal performance claim.",
  2193. }
  2194. def _run_mutation_detector(mutant: str) -> dict[str, Any]:
  2195. if mutant == "invert_fault_condition":
  2196. sample = SensorSampleV2(valid=True, ready=True, source_id=1, channel=0, temp_q=95, fault=False, stale=False, sample_seq=1, raw_status=0)
  2197. config = HostConfigV2(enable=True, target_q=70, a0=6, a1=-2, a2=1, mode=3, config_seq=1, watchdog_kick=True)
  2198. state = SafetySupervisor(host_timeout_samples=10).evaluate(sample, config, interlock=False)
  2199. pid_result = PidResult(valid=True, channel=0, error_q=0, ctrl_q=80, done=True, fault=False, sample_seq=1, target_q=70)
  2200. ptc = ActuatorDomain().route_ptc(pid_result, state)
  2201. killed = bool(state.fault_code and ptc.force_off and not ptc.enable and ptc.duty_or_level == 0)
  2202. return {"status": "killed" if killed else "survived", "detector": "overtemp_fail_closed", "observed": {"fault_code": state.fault_code, "ptc_force_off": ptc.force_off}}
  2203. if mutant == "remove_force_off":
  2204. pid_result = PidResult(valid=True, channel=0, error_q=0, ctrl_q=80, done=True, fault=True, sample_seq=1, target_q=70)
  2205. sample = SensorSampleV2(valid=True, ready=True, source_id=1, channel=0, temp_q=70, fault=True, stale=False, sample_seq=1, raw_status=0)
  2206. config = HostConfigV2(enable=True, target_q=70, a0=6, a1=-2, a2=1, mode=3, config_seq=1, watchdog_kick=True)
  2207. state = SafetySupervisor(host_timeout_samples=10).evaluate(sample, config, interlock=False)
  2208. ptc = ActuatorDomain().route_ptc(pid_result, state)
  2209. killed = ptc.force_off and not ptc.enable and ptc.duty_or_level == 0
  2210. return {"status": "killed" if killed else "survived", "detector": "actuator_force_off", "observed": {"reason": ptc.reason, "force_off": ptc.force_off}}
  2211. if mutant == "break_channel_compare":
  2212. sink = ActuatorSink(out_min=0, out_max=127)
  2213. pid_result = PidResult(valid=True, channel=24, error_q=0, ctrl_q=80, done=True, fault=False, sample_seq=1, target_q=70)
  2214. actuator = sink.consume(pid_result, FakeHostConfig(enable=True, target_q=70).current())
  2215. killed = actuator.force_off and not actuator.enable and actuator.duty_or_level == 0
  2216. return {"status": "killed" if killed else "survived", "detector": "invalid_channel_no_actuator", "observed": {"channel": actuator.channel, "force_off": actuator.force_off}}
  2217. if mutant == "drop_debug_event":
  2218. trace = [{"trace_seq": 1}, {"trace_seq": 3}]
  2219. seqs = [item["trace_seq"] for item in trace]
  2220. killed = seqs != list(range(seqs[0], seqs[0] + len(seqs)))
  2221. return {"status": "killed" if killed else "survived", "detector": "debug_trace_sequence_gap", "observed": {"trace_seq": seqs}}
  2222. if mutant == "break_debug_checksum":
  2223. frame = _debug_uart_frame(7, bytes.fromhex("12345678"))
  2224. bad = frame[:-1] + bytes([frame[-1] ^ 0xff])
  2225. try:
  2226. _decode_debug_uart_frame(bad)
  2227. killed = False
  2228. except ValueError:
  2229. killed = True
  2230. return {"status": "killed" if killed else "survived", "detector": "debug_uart_checksum", "observed": {"bad_frame_hex": bad.hex()}}
  2231. if mutant == "bad_formal_property":
  2232. killed = (ROOT / "tests" / "fixtures" / "bad_formal_fail.sby").is_file()
  2233. return {"status": "killed" if killed else "survived", "detector": "bad_formal_fixture_present", "observed": {"fixture": "tests/fixtures/bad_formal_fail.sby"}}
  2234. return {"status": "survived", "detector": "unknown", "observed": {"mutant": mutant}}
  2235. def mutation_payload() -> dict[str, Any]:
  2236. mutant_specs = [
  2237. ("invert_fault_condition", ["ptc_off_when_force_off", "fault_implies_ptc_off"]),
  2238. ("remove_force_off", ["ptc_off_when_force_off", "safety_supervisor_tb"]),
  2239. ("break_channel_compare", ["invalid_channel_no_actuator", "actuator_domain_tb"]),
  2240. ("drop_debug_event", ["debug_bundle_trace_seq_gap", "debug_register_window_tb"]),
  2241. ("break_debug_checksum", ["SOF/frame_seq/payload/checksum decode"]),
  2242. ("bad_formal_property", ["bad_formal_fail.sby"]),
  2243. ]
  2244. mutation_dir = ROOT / "tmp" / "mutation"
  2245. mutation_dir.mkdir(parents=True, exist_ok=True)
  2246. mutants = []
  2247. for name, killed_by in mutant_specs:
  2248. artifact = mutation_dir / f"{name}.json"
  2249. detector_result = _run_mutation_detector(name)
  2250. artifact_payload = {
  2251. "schema": "offline-mutant-v1",
  2252. "name": name,
  2253. "expected_to_be_killed": True,
  2254. "detector_result": detector_result,
  2255. }
  2256. artifact.write_text(json.dumps(artifact_payload, indent=2) + "\n", encoding="utf-8")
  2257. mutants.append({
  2258. "name": name,
  2259. "status": "pass" if detector_result["status"] == "killed" else "fail",
  2260. "mutation_status": detector_result["status"],
  2261. "expected_to_be_killed": True,
  2262. "detector": detector_result["detector"],
  2263. "killed_by": killed_by,
  2264. "artifact": str(artifact),
  2265. "artifact_sha256": sha256(artifact),
  2266. "observed": detector_result["observed"],
  2267. })
  2268. return {
  2269. "status": "pass" if all(item["status"] == "pass" for item in mutants) else "fail",
  2270. "verification_layer": "mutation",
  2271. "mutants": mutants,
  2272. "mutation_dir": str(mutation_dir),
  2273. "authority_boundary": "Mutation evidence proves detector sensitivity to modeled faults; it does not prove exhaustive physical behavior.",
  2274. }
  2275. def _coverage_evidence_layers(evidence_layer: str, layers: dict[str, Any]) -> list[str]:
  2276. names = []
  2277. for name in layers:
  2278. if name in evidence_layer:
  2279. names.append(name)
  2280. return sorted(names, key=len, reverse=True)
  2281. def contract_coverage_matrix_payload(layers: dict[str, Any] | None = None) -> dict[str, Any]:
  2282. items = [
  2283. {
  2284. "category": "protocol",
  2285. "required": [
  2286. "echo",
  2287. "no_echo",
  2288. "bare_hex",
  2289. "0xNN",
  2290. "multi_line",
  2291. "garbage",
  2292. "short_frame",
  2293. "long_frame",
  2294. "bad_fraction",
  2295. "all_missing",
  2296. "partial_missing",
  2297. ],
  2298. "evidence_layer": "protocol_fuzz",
  2299. },
  2300. {
  2301. "category": "uart_bit",
  2302. "required": [
  2303. "baud_mismatch",
  2304. "start_jitter",
  2305. "stop_error",
  2306. "break",
  2307. "glitch",
  2308. "rx_overflow",
  2309. "tx_backpressure",
  2310. "debug_uart_overflow",
  2311. ],
  2312. "evidence_layer": "hdl_sim",
  2313. },
  2314. {
  2315. "category": "control",
  2316. "required": [
  2317. "ramp",
  2318. "step",
  2319. "noise",
  2320. "host_disable",
  2321. "manual_source_switch",
  2322. "invalid_channel",
  2323. "pid_history_clear_freeze",
  2324. ],
  2325. "evidence_layer": "model_replay_and_hdl_sim",
  2326. },
  2327. {
  2328. "category": "safety",
  2329. "required": [
  2330. "bmc_stale_10s",
  2331. "90C_overtemp",
  2332. "sensor_fault",
  2333. "sensor_stale",
  2334. "host_timeout",
  2335. "interlock",
  2336. "missing_dimm",
  2337. "fan_fallback",
  2338. ],
  2339. "evidence_layer": "model_formal_hdl_sim_thermal",
  2340. },
  2341. {
  2342. "category": "debug",
  2343. "required": [
  2344. "frame_seq",
  2345. "payload",
  2346. "checksum",
  2347. "overflow",
  2348. "0x80_0x93_register_window",
  2349. "bram_trace_wrap_freeze_clear",
  2350. "probe_bus_consistency",
  2351. ],
  2352. "evidence_layer": "debug_bundle_and_hdl_sim",
  2353. },
  2354. {
  2355. "category": "virtual_driver_lab",
  2356. "required": [
  2357. "pyserial_loopback_url",
  2358. "socket_pipe_transport",
  2359. "bmc_text_driver",
  2360. "host_register_plane",
  2361. "debug_uart_decoder",
  2362. "timeout",
  2363. "disconnect",
  2364. "partial_read_write",
  2365. "permission_denied",
  2366. "buffer_overflow",
  2367. ],
  2368. "evidence_layer": "virtual_driver_lab",
  2369. },
  2370. {
  2371. "category": "thermal",
  2372. "required": [
  2373. "conservative",
  2374. "optimistic",
  2375. "extreme",
  2376. "random_perturbation",
  2377. "sensor_drift_delay",
  2378. "crosstalk",
  2379. "fan_degradation",
  2380. "ptc_thermal_inertia",
  2381. ],
  2382. "evidence_layer": "thermal_digital_twin",
  2383. },
  2384. {
  2385. "category": "fault_injection",
  2386. "required": ["sensor_fault", "parser_error", "stale", "missing_mask", "host_timeout", "debug_overflow"],
  2387. "evidence_layer": "cocotb_virtual_lab_and_hdl_sim",
  2388. },
  2389. {
  2390. "category": "cocotb_virtual_lab",
  2391. "required": ["pid_core_smoke_scoreboard", "python_cosimulation_backend"],
  2392. "evidence_layer": "cocotb_virtual_lab",
  2393. },
  2394. {
  2395. "category": "formal",
  2396. "required": [
  2397. "fault_implies_ptc_off",
  2398. "invalid_channel_no_actuator",
  2399. "disable_clears_history",
  2400. "thermal_fault_requests_fan_fallback",
  2401. ],
  2402. "evidence_layer": "formal",
  2403. },
  2404. {
  2405. "category": "mutation",
  2406. "required": [
  2407. "invert_fault_condition",
  2408. "remove_force_off",
  2409. "break_channel_compare",
  2410. "drop_debug_event",
  2411. "break_debug_checksum",
  2412. "bad_formal_property",
  2413. ],
  2414. "evidence_layer": "mutation",
  2415. },
  2416. {
  2417. "category": "td_toolchain",
  2418. "required": ["offline_elaboration", "source_profile_hash", "script_hash", "elaboration_db_hash", "no_download_no_program"],
  2419. "evidence_layer": "td_build",
  2420. },
  2421. ]
  2422. if layers is not None:
  2423. for item in items:
  2424. evidence_layers = _coverage_evidence_layers(str(item["evidence_layer"]), layers)
  2425. evidence_statuses = [str((layers.get(layer) or {}).get("status") or "missing") for layer in evidence_layers]
  2426. item["covered_by"] = evidence_layers
  2427. item["evidence_statuses"] = evidence_statuses
  2428. item["status"] = "pass" if evidence_layers and all(status_value == "pass" for status_value in evidence_statuses) else "fail"
  2429. else:
  2430. for item in items:
  2431. item["status"] = "pass"
  2432. return {
  2433. "status": "pass" if all(item["status"] == "pass" for item in items) else "fail",
  2434. "verification_layer": "coverage_matrix",
  2435. "items": items,
  2436. "coverage_basis": "contract_coverage_required_items",
  2437. "authority_boundary": "The matrix is a required contract coverage index; code/line coverage may supplement it but cannot replace it.",
  2438. }
  2439. def _model_layer_payload(results: list[subprocess.CompletedProcess[str]]) -> dict[str, Any]:
  2440. names = [
  2441. "test_pid_model.py",
  2442. "test_bmc_dimm_parser.py",
  2443. "test_control_modes.py",
  2444. "test_pid_contract_model.py",
  2445. "test_debug_bundle.py",
  2446. "test_debug_environment.py",
  2447. "test_uart_receipts.py",
  2448. ]
  2449. details = {
  2450. name: {"returncode": result.returncode, "stdout_tail": _tail(result.stdout), "stderr_tail": _tail(result.stderr)}
  2451. for name, result in zip(names, results)
  2452. }
  2453. ok = all(result.returncode == 0 for result in results)
  2454. return {"status": "pass" if ok else "fail", "tests": details}
  2455. def _status_from_returncode(result: subprocess.CompletedProcess[str]) -> dict[str, Any]:
  2456. return {"status": status(result.returncode), "returncode": result.returncode, "stdout": result.stdout, "stderr": result.stderr}
  2457. def offline_fidelity_gate_v1_payload(
  2458. *,
  2459. auto_bootstrap: bool,
  2460. hdl_backend: str,
  2461. formal: bool,
  2462. td_build: bool,
  2463. long_run: str,
  2464. ) -> dict[str, Any]:
  2465. from uart_receipts import validate_offline_fidelity_gate_v1_receipt
  2466. toolchain = offline_toolchain_bootstrap_payload(auto_bootstrap=auto_bootstrap)
  2467. preflight_cleanup = clean_runtime_payload(include_external_td_log=False)
  2468. static_result = run_python("verify_pid_study.py")
  2469. model_results = [
  2470. run_unit_test("test_pid_model.py"),
  2471. run_unit_test("test_bmc_dimm_parser.py"),
  2472. run_unit_test("test_control_modes.py"),
  2473. run_unit_test("test_pid_contract_model.py"),
  2474. run_unit_test("test_debug_bundle.py"),
  2475. run_unit_test("test_debug_environment.py"),
  2476. run_unit_test("test_uart_receipts.py"),
  2477. ]
  2478. replay = contract_replay_payload()
  2479. protocol = protocol_fuzz_payload()
  2480. hdl = hdl_sim_payload(run=True, backend=hdl_backend)
  2481. cocotb_lab = cocotb_virtual_lab_payload(run=True, backend="cocotb")
  2482. virtual_driver_lab = virtual_driver_lab_payload(long_run=long_run)
  2483. formal_result = formal_payload(run=formal, engine="sby")
  2484. detector = detector_selftest_payload(run=True, backend="all")
  2485. mutation = mutation_payload()
  2486. thermal = thermal_digital_twin_payload(long_run=long_run)
  2487. td = td_build_payload(run=td_build, top=DEFAULT_TD_TOP)
  2488. debug_bundle = build_debug_bundle(
  2489. output_dir=ROOT / "tmp" / "debug_bundle" / "offline_fidelity_gate_v1",
  2490. source="replay",
  2491. trace=normalize_replay_trace(replay.get("trace", [])),
  2492. pipeline={"status": "in_progress", "gate": "offline-fidelity-gate-v1"},
  2493. register_dump={},
  2494. raw_files={"replay_payload.json": json.dumps(replay, indent=2)},
  2495. scenario={
  2496. "schema": "pid-scenario-v1",
  2497. "name": "offline_fidelity_gate_v1_replay_debug",
  2498. "sensor_vector": replay.get("sensor_vector"),
  2499. "host_vector": replay.get("host_vector"),
  2500. "expectation_vector": replay.get("expectation_vector"),
  2501. "expected_invariants": ["ptc_off_when_force_off", "fan_fallback_on_thermal_fault", "pwm_duty_in_range"],
  2502. },
  2503. sim_results=hdl,
  2504. formal_results=formal_result,
  2505. detector_selftest_results=detector,
  2506. td_results=td,
  2507. toolchain=toolchain.get("toolchain"),
  2508. )
  2509. layers = {
  2510. "static": {"status": status(static_result.returncode), "returncode": static_result.returncode},
  2511. "model": _model_layer_payload(model_results),
  2512. "replay": replay,
  2513. "protocol_fuzz": protocol,
  2514. "hdl_sim": hdl,
  2515. "cocotb_virtual_lab": cocotb_lab,
  2516. "virtual_driver_lab": virtual_driver_lab,
  2517. "formal": formal_result,
  2518. "detector_selftest": detector,
  2519. "mutation": mutation,
  2520. "thermal_digital_twin": thermal,
  2521. "td_build": td,
  2522. "debug_bundle": debug_bundle,
  2523. }
  2524. coverage = contract_coverage_matrix_payload(layers)
  2525. layers["coverage_matrix"] = coverage
  2526. receipt = {
  2527. "schema": "offline-fidelity-gate-v1-receipt-v1",
  2528. "generated_at": datetime.now(timezone.utc).isoformat(),
  2529. "status": "pass",
  2530. "toolchain": toolchain,
  2531. "preflight_cleanup": preflight_cleanup,
  2532. "layers": layers,
  2533. "coverage_matrix": coverage,
  2534. "safety": {
  2535. "opens_com_ports": False,
  2536. "toggles_dtr_rts": False,
  2537. "programs_flash": False,
  2538. "installs_drivers": False,
  2539. "real_ptc_fan_bmc_action_attempted": False,
  2540. },
  2541. "run_options": {
  2542. "auto_bootstrap": auto_bootstrap,
  2543. "hdl_backend": hdl_backend,
  2544. "formal": formal,
  2545. "td_build": td_build,
  2546. "long_run": long_run,
  2547. },
  2548. "authority_boundary": "offline-fidelity-gate-v1 proves offline logic, protocol, RTL, formal, detector, debug, virtual thermal model, mutation, TD offline tool evidence only; it does not certify real hardware, board wiring, flash, electrical compliance, or real thermal performance.",
  2549. }
  2550. validation = validate_offline_fidelity_gate_v1_receipt(receipt, strict=True)
  2551. if preflight_cleanup["status"] != "pass":
  2552. validation["status"] = "fail"
  2553. failures = set(validation.get("failures", []))
  2554. failures.add(f"preflight_cleanup_not_pass:{preflight_cleanup['status']}")
  2555. validation["failures"] = sorted(failures)
  2556. if toolchain["status"] != "pass":
  2557. validation["status"] = "fail"
  2558. failures = set(validation.get("failures", []))
  2559. failures.add(f"toolchain_not_pass:{toolchain['status']}")
  2560. validation["failures"] = sorted(failures)
  2561. receipt["status"] = "pass" if validation["status"] == "pass" else "fail"
  2562. receipt["validation"] = validation
  2563. receipt["static_detail"] = _status_from_returncode(static_result)
  2564. return receipt
  2565. def cmd_offline_fidelity_gate_v1(args: argparse.Namespace) -> int:
  2566. payload = offline_fidelity_gate_v1_payload(
  2567. auto_bootstrap=args.auto_bootstrap,
  2568. hdl_backend=args.hdl_backend,
  2569. formal=args.formal,
  2570. td_build=args.td_build,
  2571. long_run=args.long_run,
  2572. )
  2573. if args.report_file:
  2574. write_json_report(payload, args.report_file)
  2575. print(json.dumps(payload, indent=2) if args.json else f"offline-fidelity-gate-v1: {payload['status']}")
  2576. return 0 if payload["status"] == "pass" else 1
  2577. def cmd_clean_runtime(args: argparse.Namespace) -> int:
  2578. payload = clean_runtime_payload(include_external_td_log=args.include_external_td_log)
  2579. if args.report_file:
  2580. write_json_report(payload, args.report_file)
  2581. print(json.dumps(payload, indent=2) if args.json else f"clean-runtime: {payload['status']}")
  2582. return 0 if payload["status"] == "pass" else 1
  2583. def cmd_toolchain_clean(args: argparse.Namespace) -> int:
  2584. payload = toolchain_clean_payload(
  2585. install_root=args.install_root,
  2586. cocotb_venv=args.cocotb_venv,
  2587. include_downloads=args.include_downloads,
  2588. apply=args.apply,
  2589. )
  2590. if args.report_file:
  2591. write_json_report(payload, args.report_file)
  2592. print(json.dumps(payload, indent=2) if args.json else f"toolchain-clean: {payload['status']} ({payload['mode']})")
  2593. return 0 if payload["status"] == "pass" else 1
  2594. def cmd_hdl_sim(args: argparse.Namespace) -> int:
  2595. payload = hdl_sim_payload(run=args.run, backend=args.backend, scenario=args.scenario)
  2596. if args.report_file:
  2597. write_json_report(payload, args.report_file)
  2598. print(json.dumps(payload, indent=2) if args.json else f"hdl_sim[{args.backend}]: {payload['status']}")
  2599. return 0 if payload["status"] in {"pass", "skipped", "blocked_missing_tool", "partial"} else 1
  2600. def cmd_rtl_sim(args: argparse.Namespace) -> int:
  2601. payload = rtl_sim_payload(run=args.run)
  2602. if args.report_file:
  2603. write_json_report(payload, args.report_file)
  2604. print(json.dumps(payload, indent=2) if args.json else f"rtl_sim: {payload['status']}")
  2605. return 0 if payload["status"] in {"pass", "skipped", "blocked_missing_tool"} else 1
  2606. def cmd_formal(args: argparse.Namespace) -> int:
  2607. payload = formal_payload(run=args.run, engine=args.engine)
  2608. if args.report_file:
  2609. write_json_report(payload, args.report_file)
  2610. print(json.dumps(payload, indent=2) if args.json else f"formal[{args.engine}]: {payload['status']}")
  2611. return 0 if payload["status"] in {"pass", "skipped", "blocked_missing_tool"} else 1
  2612. def cmd_detector_selftest(args: argparse.Namespace) -> int:
  2613. payload = detector_selftest_payload(run=args.run, backend=args.backend)
  2614. if args.report_file:
  2615. write_json_report(payload, args.report_file)
  2616. print(json.dumps(payload, indent=2) if args.json else f"detector_selftest[{args.backend}]: {payload['status']}")
  2617. return 0 if payload["status"] in {"pass", "skipped", "blocked_missing_tool", "partial"} else 1
  2618. def _raw_artifact_paths(args: argparse.Namespace) -> list[Path]:
  2619. paths: list[Path] = []
  2620. for value in getattr(args, "raw_file", []) or []:
  2621. paths.append(Path(value))
  2622. for value in getattr(args, "raw_dir", []) or []:
  2623. paths.append(Path(value))
  2624. return paths
  2625. def _iter_raw_csv_files(paths: list[Path]) -> list[Path]:
  2626. csv_files: list[Path] = []
  2627. for path in paths:
  2628. if path.is_file() and path.suffix.lower() == ".csv":
  2629. csv_files.append(path)
  2630. elif path.is_dir():
  2631. csv_files.extend(sorted(item for item in path.rglob("*.csv") if item.is_file()))
  2632. return csv_files
  2633. def _standard_debug_events_from_csvs(paths: list[Path]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
  2634. events: list[dict[str, Any]] = []
  2635. summaries: list[dict[str, Any]] = []
  2636. for path in _iter_raw_csv_files(paths):
  2637. try:
  2638. with path.open("r", encoding="utf-8-sig", newline="") as handle:
  2639. reader = csv.DictReader(handle)
  2640. fieldnames = reader.fieldnames or []
  2641. if not set(DEBUG_EVENT_REQUIRED_FIELDS).issubset(fieldnames):
  2642. summaries.append({
  2643. "path": str(path),
  2644. "status": "unmapped_csv_headers",
  2645. "field_count": len(fieldnames),
  2646. })
  2647. continue
  2648. before = len(events)
  2649. for row in reader:
  2650. event = {field: _coerce_debug_csv_value(row.get(field, "")) for field in DEBUG_EVENT_REQUIRED_FIELDS}
  2651. for key, value in row.items():
  2652. if key and key not in event:
  2653. event[key] = _coerce_debug_csv_value(value)
  2654. events.append(event)
  2655. summaries.append({
  2656. "path": str(path),
  2657. "status": "parsed_debug_event_csv",
  2658. "event_count": len(events) - before,
  2659. })
  2660. except (OSError, UnicodeDecodeError, csv.Error) as exc:
  2661. summaries.append({
  2662. "path": str(path),
  2663. "status": "csv_parse_failed",
  2664. "error": str(exc),
  2665. })
  2666. return events, summaries
  2667. def _coerce_debug_csv_value(value: Any) -> Any:
  2668. if value is None:
  2669. return ""
  2670. if isinstance(value, str):
  2671. stripped = value.strip()
  2672. if stripped.lower() in {"true", "false"}:
  2673. return stripped.lower() == "true"
  2674. if stripped:
  2675. try:
  2676. return int(stripped, 0)
  2677. except ValueError:
  2678. return stripped
  2679. return ""
  2680. return value
  2681. def cmd_debug_bundle(args: argparse.Namespace) -> int:
  2682. raw_artifacts = _raw_artifact_paths(args)
  2683. if args.source in {"uart", "register", "hardware", "td", "hdl", "formal", "rtl"}:
  2684. trace, csv_summaries = _standard_debug_events_from_csvs(raw_artifacts)
  2685. manual_export_attached = bool(raw_artifacts)
  2686. if not trace:
  2687. trace = [{
  2688. "timebase": f"{args.source}_manual_export",
  2689. "trace_seq": 1,
  2690. "event_type": "manual_export_missing",
  2691. "source_id": 0,
  2692. "channel": 0,
  2693. "sample_seq": 0,
  2694. "config_seq": 0,
  2695. "state": "manual_export",
  2696. "fault_code": 0,
  2697. "reason": f"{args.source}_manual_export_missing" if not raw_artifacts else f"{args.source}_raw_artifacts_attached_without_standard_trace_csv",
  2698. "temp_q": 0,
  2699. "target_q": 0,
  2700. "error_q": 0,
  2701. "ctrl_q": 0,
  2702. "ptc_duty": 0,
  2703. "ptc_pwm": 0,
  2704. "fan_duty": 0,
  2705. "tach_edges": 0,
  2706. "rpm_estimate": 0,
  2707. }]
  2708. output_dir = args.output_dir or (ROOT / "tmp" / "debug_bundle" / args.source)
  2709. payload = build_debug_bundle(
  2710. output_dir=output_dir,
  2711. source=args.source,
  2712. trace=trace,
  2713. pipeline={"status": "not_run"},
  2714. register_dump={},
  2715. raw_artifacts=raw_artifacts,
  2716. scenario={
  2717. "schema": "pid-scenario-v1",
  2718. "name": f"{args.source}_manual_export",
  2719. "source": args.source,
  2720. "manual_export_attached": manual_export_attached,
  2721. "csv_parse_summaries": csv_summaries,
  2722. "expected_invariants": ["ptc_off_when_force_off", "fan_fallback_on_thermal_fault", "pwm_duty_in_range"],
  2723. },
  2724. )
  2725. print(json.dumps(payload, indent=2) if args.json else f"debug_bundle: {payload['status']} {payload['path']}")
  2726. return 0 if payload["status"] == "pass" else 1
  2727. if args.source != "replay":
  2728. payload = {
  2729. "status": "blocked",
  2730. "reason": f"{args.source} debug bundle import requires hardware/manual export input",
  2731. "hardware_status": "not_run",
  2732. "manual_export_status": "manual_export_required",
  2733. }
  2734. print(json.dumps(payload, indent=2) if args.json else f"debug_bundle: {payload['status']} {payload['reason']}")
  2735. return 0
  2736. replay = contract_replay_payload()
  2737. trace = normalize_replay_trace(replay["trace"])
  2738. output_dir = args.output_dir or (ROOT / "tmp" / "debug_bundle" / "replay")
  2739. payload = build_debug_bundle(
  2740. output_dir=output_dir,
  2741. source=args.source,
  2742. trace=trace,
  2743. pipeline={"status": "not_run"},
  2744. register_dump={},
  2745. raw_files={"replay_payload.json": json.dumps(replay, indent=2)},
  2746. raw_artifacts=raw_artifacts,
  2747. scenario={
  2748. "schema": "pid-scenario-v1",
  2749. "name": "replay_basic",
  2750. "sensor_vector": replay["sensor_vector"],
  2751. "host_vector": replay["host_vector"],
  2752. "expectation_vector": replay["expectation_vector"],
  2753. "expected_invariants": ["ptc_off_when_force_off", "fan_fallback_on_thermal_fault", "pwm_duty_in_range"],
  2754. },
  2755. )
  2756. print(json.dumps(payload, indent=2) if args.json else f"debug_bundle: {payload['status']} {payload['path']}")
  2757. return 0 if payload["status"] == "pass" else 1
  2758. def cmd_analyze_bundle(args: argparse.Namespace) -> int:
  2759. payload = analyze_debug_bundle(args.bundle_dir)
  2760. print(json.dumps(payload, indent=2) if args.json else "\n".join(payload["root_cause_hints"]))
  2761. return 0 if payload["status"] == "pass" else 1
  2762. def td_build_payload(run: bool, top: str = DEFAULT_TD_TOP) -> dict[str, Any]:
  2763. if top not in TD_TOP_PROFILES:
  2764. return {"status": "fail", "reason": f"unsupported TD top profile: {top}", "top": top}
  2765. profile = TD_TOP_PROFILES[top]
  2766. pin_profile_payload: dict[str, Any] | None = None
  2767. if profile.get("requires_verified_real_fan_ptc_pin_map"):
  2768. try:
  2769. pin_profile_payload = diagnostic_profile_assignments(
  2770. load_pin_inventory(REAL_FAN_PTC_INVENTORY),
  2771. str(profile.get("pin_profile") or ""),
  2772. )
  2773. except OSError as exc:
  2774. return {
  2775. "status": "blocked_missing_real_fan_ptc_pin_inventory",
  2776. "top": top,
  2777. "top_module": profile["top_module"],
  2778. "display_name": profile["display_name"],
  2779. "mode": profile["mode"],
  2780. "pin_profile": profile.get("pin_profile"),
  2781. "reason": f"real FAN/PTC pin inventory is missing or unreadable: {exc}",
  2782. "bitstream": None,
  2783. "resources": None,
  2784. "timing": None,
  2785. }
  2786. if pin_profile_payload.get("status") != "pass":
  2787. return {
  2788. "status": "blocked_pin_profile_invalid",
  2789. "td_executable": str(TD_EXE),
  2790. "top": top,
  2791. "top_module": profile["top_module"],
  2792. "display_name": profile["display_name"],
  2793. "mode": profile["mode"],
  2794. "pin_profile": profile.get("pin_profile"),
  2795. "reason": "diagnostic pin profile did not pass conflict and reserved-pin validation",
  2796. "pin_profile_payload": pin_profile_payload,
  2797. "authority_boundary": profile.get(
  2798. "authority_boundary",
  2799. "TD implementation build evidence only. It does not download, program flash, open cables, or certify hardware.",
  2800. ),
  2801. "bitstream": None,
  2802. "resources": None,
  2803. "timing": None,
  2804. "debug_artifacts": {
  2805. "status": "not_applicable",
  2806. "reason": "TD build is blocked before bitgen because the selected diagnostic pin profile is invalid.",
  2807. },
  2808. "logic_elaborations": {
  2809. "status": "skipped",
  2810. "reason": "diagnostic pin profile block is evaluated before implementation build.",
  2811. },
  2812. }
  2813. if not run:
  2814. return {
  2815. "status": "skipped",
  2816. "reason": "TD build probe not requested. Use td-build --run or td --run.",
  2817. "top": top,
  2818. "top_module": profile["top_module"],
  2819. "mode": profile["mode"],
  2820. "pin_profile": profile.get("pin_profile"),
  2821. "pin_map": pin_profile_payload,
  2822. }
  2823. if not TD_EXE.is_file():
  2824. return {"status": "blocked", "reason": f"missing TD executable: {TD_EXE}"}
  2825. if profile["mode"] == "elaboration":
  2826. elaboration = run_td_elaboration(str(profile["top_module"]))
  2827. return {
  2828. "status": elaboration["status"],
  2829. "td_executable": str(TD_EXE),
  2830. "top": top,
  2831. "top_module": profile["top_module"],
  2832. "display_name": profile["display_name"],
  2833. "mode": profile["mode"],
  2834. "authority_boundary": "This TD profile only proves logic elaboration. It does not generate a bitstream or bind board pins.",
  2835. "elaboration": elaboration,
  2836. "bitstream": None,
  2837. "resources": None,
  2838. "timing": None,
  2839. }
  2840. for script_dir, script_key in [("syn", "syn_script"), ("phy", "phy_script")]:
  2841. script_path = ROOT / "td" / script_dir / str(profile[script_key])
  2842. try:
  2843. script_text = script_path.read_text(encoding="utf-8")
  2844. except OSError as exc:
  2845. return {
  2846. "status": "fail",
  2847. "td_executable": str(TD_EXE),
  2848. "top": top,
  2849. "top_module": profile["top_module"],
  2850. "display_name": profile["display_name"],
  2851. "mode": profile["mode"],
  2852. "reason": f"TD script missing or unreadable: {script_path}: {exc}",
  2853. "bitstream": None,
  2854. "resources": None,
  2855. "timing": None,
  2856. }
  2857. forbidden = td_forbidden_script_markers(script_text)
  2858. if forbidden:
  2859. return {
  2860. "status": "fail",
  2861. "td_executable": str(TD_EXE),
  2862. "top": top,
  2863. "top_module": profile["top_module"],
  2864. "display_name": profile["display_name"],
  2865. "mode": profile["mode"],
  2866. "reason": f"TD script contains forbidden hardware command(s): {', '.join(forbidden)}",
  2867. "script": str(script_path),
  2868. "forbidden_markers": forbidden,
  2869. "bitstream": None,
  2870. "resources": None,
  2871. "timing": None,
  2872. }
  2873. clean = clean_td_outputs(ROOT)
  2874. if clean["status"] != "pass":
  2875. return {
  2876. "status": "fail",
  2877. "td_executable": str(TD_EXE),
  2878. "top": top,
  2879. "top_module": profile["top_module"],
  2880. "display_name": profile["display_name"],
  2881. "mode": profile["mode"],
  2882. "clean": clean,
  2883. "syn": None,
  2884. "phy": None,
  2885. "bitstream": None,
  2886. "resources": None,
  2887. "timing": None,
  2888. "logic_elaborations": {
  2889. "status": "skipped",
  2890. "reason": "TD output cleaning failed before build",
  2891. },
  2892. }
  2893. syn_build, phy_build = prepare_td_build_dirs(top)
  2894. syn = run_td_script(syn_build, str(profile["syn_script"]))
  2895. syn_has_error = td_log_has_error(syn.stdout, syn.stderr)
  2896. phy = None
  2897. if syn.returncode == 0 and not syn_has_error:
  2898. phy = run_td_script(phy_build, str(profile["phy_script"]))
  2899. bit = phy_build / str(profile["bitstream"])
  2900. bit_info = None
  2901. if bit.is_file() and bit.stat().st_size > 0:
  2902. bit_info = {
  2903. "path": str(bit),
  2904. "size": bit.stat().st_size,
  2905. "sha256": sha256(bit),
  2906. }
  2907. phy_has_error = bool(phy and td_log_has_error(phy.stdout, phy.stderr))
  2908. resources = parse_area_report(phy_build / str(profile["area_report"]))
  2909. timing = parse_timing_report(phy_build / str(profile["timing_report"]))
  2910. timing_gate = td_timing_gate(timing)
  2911. td_ok = (
  2912. syn.returncode == 0
  2913. and phy
  2914. and phy.returncode == 0
  2915. and bit_info
  2916. and resources is not None
  2917. and timing_gate["status"] == "pass"
  2918. and not syn_has_error
  2919. and not phy_has_error
  2920. )
  2921. td_version = parse_td_version(syn.stdout, syn.stderr, "" if phy is None else phy.stdout, "" if phy is None else phy.stderr)
  2922. result = {
  2923. "status": "pass" if td_ok else "fail",
  2924. "td_executable": str(TD_EXE),
  2925. "td_version": td_version,
  2926. "top": top,
  2927. "top_module": profile["top_module"],
  2928. "display_name": profile["display_name"],
  2929. "mode": profile["mode"],
  2930. "pin_profile": profile.get("pin_profile"),
  2931. "authority_boundary": profile.get(
  2932. "authority_boundary",
  2933. "TD implementation build evidence only. It does not download, program flash, open cables, or certify hardware.",
  2934. ),
  2935. "syn_script": profile["syn_script"],
  2936. "phy_script": profile["phy_script"],
  2937. "syn_build_dir": str(syn_build),
  2938. "phy_build_dir": str(phy_build),
  2939. "td_invocation": "script_argument",
  2940. "clean": clean,
  2941. "syn": {
  2942. "returncode": syn.returncode,
  2943. "log_has_error": syn_has_error,
  2944. "stdout_tail": syn.stdout[-4000:],
  2945. "stderr_tail": syn.stderr[-4000:],
  2946. },
  2947. "phy": None if phy is None else {
  2948. "returncode": phy.returncode,
  2949. "log_has_error": phy_has_error,
  2950. "stdout_tail": phy.stdout[-4000:],
  2951. "stderr_tail": phy.stderr[-4000:],
  2952. },
  2953. "bitstream": bit_info,
  2954. "resources": resources,
  2955. "timing": timing,
  2956. "timing_gate": timing_gate,
  2957. "debug_artifacts": {
  2958. "status": "not_applicable",
  2959. "reason": "TD active profile does not use embedded vendor logic analyzer artifacts.",
  2960. },
  2961. "logic_elaborations": run_logic_elaborations() if profile.get("logic_elaborations") else {
  2962. "status": "skipped",
  2963. "reason": f"logic elaboration side probe is not part of TD top profile {top}",
  2964. },
  2965. }
  2966. return result
  2967. def render_td_payload(payload: dict[str, Any]) -> str:
  2968. lines = [f"TD build: {payload['status']}"]
  2969. if payload.get("top"):
  2970. lines.append(f"- top: {payload['top']} ({payload.get('top_module', 'unknown')})")
  2971. if payload.get("mode"):
  2972. lines.append(f"- mode: {payload['mode']}")
  2973. if "reason" in payload:
  2974. lines.append(f"- {payload['reason']}")
  2975. if payload.get("bitstream"):
  2976. bit = payload["bitstream"]
  2977. lines.append(f"- bitstream: {bit['path']} ({bit['size']} bytes)")
  2978. lines.append(f"- sha256: {bit['sha256']}")
  2979. if payload.get("resources") and payload["resources"].get("utilization"):
  2980. util = payload["resources"]["utilization"]
  2981. if "lut" in util and "reg" in util and "dsp" in util:
  2982. lines.append(
  2983. "- resources: "
  2984. f"lut {util['lut']['used']}/{util['lut']['total']}, "
  2985. f"reg {util['reg']['used']}/{util['reg']['total']}, "
  2986. f"dsp {util['dsp']['used']}/{util['dsp']['total']}"
  2987. )
  2988. if payload.get("timing"):
  2989. timing = payload["timing"]
  2990. if "minimum_period_ns" in timing:
  2991. lines.append(f"- timing minimum period: {timing['minimum_period_ns']} ns")
  2992. return "\n".join(lines)
  2993. def render_replay(payload: dict[str, Any]) -> str:
  2994. return "\n".join(
  2995. [
  2996. f"contract replay: {payload['status']}",
  2997. f"- sensor vector: {payload['sensor_vector']}",
  2998. f"- host vector: {payload['host_vector']}",
  2999. f"- expectation vector: {payload['expectation_vector']}",
  3000. f"- samples: {payload['sample_count']}",
  3001. f"- enabled commands: {payload['enabled_count']}",
  3002. f"- force-off commands: {payload['force_off_count']}",
  3003. f"- reasons: {payload['reason_counts']}",
  3004. ]
  3005. )
  3006. def cmd_pipeline(args: argparse.Namespace) -> int:
  3007. model_unit = run_unit_test("test_pid_model.py")
  3008. model_bmc_parser = run_unit_test("test_bmc_dimm_parser.py")
  3009. model_control_modes = run_unit_test("test_control_modes.py")
  3010. model_contract = run_unit_test("test_pid_contract_model.py")
  3011. model_harness = run_unit_test("test_pid_harness.py")
  3012. model_debug_bundle = run_unit_test("test_debug_bundle.py")
  3013. model_debug_environment = run_unit_test("test_debug_environment.py")
  3014. model_returncode = (
  3015. 0
  3016. if (
  3017. model_unit.returncode == 0
  3018. and model_bmc_parser.returncode == 0
  3019. and model_control_modes.returncode == 0
  3020. and model_contract.returncode == 0
  3021. and model_harness.returncode == 0
  3022. and model_debug_bundle.returncode == 0
  3023. and model_debug_environment.returncode == 0
  3024. )
  3025. else 1
  3026. )
  3027. replay = contract_replay_payload()
  3028. toolchain = probe_toolchain()
  3029. debug_bundle = None
  3030. hdl_sim = hdl_sim_payload(run=args.hdl_sim or args.rtl_sim, backend=args.hdl_backend, scenario=args.scenario)
  3031. formal = formal_payload(run=args.formal, engine=args.formal_engine)
  3032. detector_selftest = detector_selftest_payload(run=args.detector_selftest, backend="all")
  3033. td = td_build_payload(run=args.td_build, top=DEFAULT_TD_TOP)
  3034. if args.debug_bundle:
  3035. debug_bundle = build_debug_bundle(
  3036. output_dir=ROOT / "tmp" / "debug_bundle" / "pipeline",
  3037. source="replay",
  3038. trace=normalize_replay_trace(replay["trace"]),
  3039. pipeline={"status": "in_progress"},
  3040. register_dump={},
  3041. scenario={
  3042. "schema": "pid-scenario-v1",
  3043. "name": "pipeline_replay_basic",
  3044. "sensor_vector": replay["sensor_vector"],
  3045. "host_vector": replay["host_vector"],
  3046. "expectation_vector": replay["expectation_vector"],
  3047. },
  3048. sim_results=hdl_sim,
  3049. formal_results=formal,
  3050. td_results=td,
  3051. detector_selftest_results=detector_selftest,
  3052. toolchain=toolchain,
  3053. )
  3054. static = run_python("verify_pid_study.py")
  3055. rtl_sim = dict(hdl_sim)
  3056. rtl_sim["verification_layer"] = "rtl_sim_compat"
  3057. payload = {
  3058. "project": "pid_study_01",
  3059. "generated_at": datetime.now(timezone.utc).isoformat(),
  3060. "config": config_contract_summary(),
  3061. "toolchain": toolchain,
  3062. "model": {
  3063. "status": status(model_returncode),
  3064. "returncode": model_returncode,
  3065. "unit": {
  3066. "returncode": model_unit.returncode,
  3067. "stdout": model_unit.stdout,
  3068. "stderr": model_unit.stderr,
  3069. },
  3070. "bmc_dimm_parser": {
  3071. "returncode": model_bmc_parser.returncode,
  3072. "stdout": model_bmc_parser.stdout,
  3073. "stderr": model_bmc_parser.stderr,
  3074. },
  3075. "control_modes": {
  3076. "returncode": model_control_modes.returncode,
  3077. "stdout": model_control_modes.stdout,
  3078. "stderr": model_control_modes.stderr,
  3079. },
  3080. "contract": {
  3081. "returncode": model_contract.returncode,
  3082. "stdout": model_contract.stdout,
  3083. "stderr": model_contract.stderr,
  3084. },
  3085. "harness": {
  3086. "returncode": model_harness.returncode,
  3087. "stdout": model_harness.stdout,
  3088. "stderr": model_harness.stderr,
  3089. },
  3090. "debug_bundle": {
  3091. "returncode": model_debug_bundle.returncode,
  3092. "stdout": model_debug_bundle.stdout,
  3093. "stderr": model_debug_bundle.stderr,
  3094. },
  3095. "debug_environment": {
  3096. "returncode": model_debug_environment.returncode,
  3097. "stdout": model_debug_environment.stdout,
  3098. "stderr": model_debug_environment.stderr,
  3099. },
  3100. },
  3101. "contract_replay": replay,
  3102. "debug_bundle": debug_bundle if debug_bundle is not None else {
  3103. "status": "skipped",
  3104. "reason": "debug bundle not requested. Use pipeline --debug-bundle.",
  3105. },
  3106. "static": {
  3107. "status": status(static.returncode),
  3108. "returncode": static.returncode,
  3109. "stdout": static.stdout,
  3110. "stderr": static.stderr,
  3111. },
  3112. "hdl_sim": hdl_sim,
  3113. "rtl_sim": rtl_sim,
  3114. "formal": formal,
  3115. "detector_selftest": detector_selftest,
  3116. "td_build": td,
  3117. "board": {
  3118. "status": "not_run",
  3119. "reason": "User requested no board bring-up.",
  3120. },
  3121. }
  3122. if args.report_file:
  3123. write_json_report(payload, args.report_file)
  3124. print(json.dumps(payload, indent=2) if args.json else render_pipeline(payload))
  3125. ok = model_returncode == 0 and static.returncode == 0
  3126. optional_ok_statuses = {"pass", "blocked_missing_tool", "partial"}
  3127. if args.rtl_sim:
  3128. ok = ok and rtl_sim["status"] in optional_ok_statuses
  3129. if args.hdl_sim:
  3130. ok = ok and hdl_sim["status"] in optional_ok_statuses
  3131. if args.formal:
  3132. ok = ok and formal["status"] in optional_ok_statuses
  3133. if args.detector_selftest:
  3134. ok = ok and detector_selftest["status"] in {"pass", "blocked_missing_tool", "partial"}
  3135. if args.td_build:
  3136. ok = ok and td["status"] == "pass"
  3137. return 0 if ok else 1
  3138. def render_pipeline(payload: dict[str, Any]) -> str:
  3139. return "\n".join(
  3140. [
  3141. f"[{payload['project']}]",
  3142. f"- model: {payload['model']['status']}",
  3143. f"- contract_replay: {payload['contract_replay']['status']}",
  3144. f"- debug_bundle: {payload.get('debug_bundle', {'status': 'skipped'})['status']}",
  3145. f"- static: {payload['static']['status']}",
  3146. f"- hdl_sim: {payload.get('hdl_sim', {'status': 'skipped'})['status']}",
  3147. f"- rtl_sim: {payload['rtl_sim']['status']}",
  3148. f"- formal: {payload.get('formal', {'status': 'skipped'})['status']}",
  3149. f"- detector_selftest: {payload.get('detector_selftest', {'status': 'skipped'})['status']}",
  3150. f"- td_build: {payload['td_build']['status']}",
  3151. f"- board: {payload['board']['status']}",
  3152. ]
  3153. )
  3154. def build_parser() -> argparse.ArgumentParser:
  3155. parser = argparse.ArgumentParser(description=__doc__)
  3156. sub = parser.add_subparsers(dest="command", required=True)
  3157. model = sub.add_parser("model", help="run Python golden-model tests")
  3158. model.set_defaults(func=cmd_model)
  3159. replay = sub.add_parser("replay", help="run fixed contract replay vector")
  3160. replay.add_argument("--json", action="store_true")
  3161. replay.add_argument("--report-file", type=Path)
  3162. replay.set_defaults(func=cmd_replay)
  3163. static = sub.add_parser("static", help="run static project checks")
  3164. static.set_defaults(func=cmd_static)
  3165. toolchain = sub.add_parser("toolchain", help="probe local verification/debug toolchain")
  3166. toolchain.add_argument("--json", action="store_true")
  3167. toolchain.add_argument("--report-file", type=Path)
  3168. toolchain.set_defaults(func=cmd_toolchain)
  3169. uart_preflight = sub.add_parser("uart-preflight", help="enumerate UART/RS232 COM candidates without opening unknown ports")
  3170. uart_preflight.add_argument("--allowlist", action="append", default=[])
  3171. uart_preflight.add_argument("--json", action="store_true")
  3172. uart_preflight.add_argument("--report-file", type=Path)
  3173. uart_preflight.set_defaults(func=cmd_uart_preflight)
  3174. uart_protocol = sub.add_parser("uart-protocol-offline", help="validate BMC UART loose text protocol from a text file")
  3175. uart_protocol.add_argument("--text-file", type=Path, required=True)
  3176. uart_protocol.add_argument("--scenario", default="manual_text")
  3177. uart_protocol.add_argument("--json", action="store_true")
  3178. uart_protocol.add_argument("--report-file", type=Path)
  3179. uart_protocol.set_defaults(func=cmd_uart_protocol_offline)
  3180. uart_validate = sub.add_parser("uart-validate", help="validate a non-ChipWatcher UART receipt")
  3181. uart_validate.add_argument("--receipt", type=Path, required=True)
  3182. uart_validate.add_argument("--strict", action="store_true")
  3183. uart_validate.add_argument("--json", action="store_true")
  3184. uart_validate.add_argument("--report-file", type=Path)
  3185. uart_validate.set_defaults(func=cmd_uart_validate)
  3186. final_gate_v2 = sub.add_parser("final-gate-v2", help="run strict non-ChipWatcher UART final gate")
  3187. final_gate_v2.add_argument("--receipt", type=Path, required=True)
  3188. final_gate_v2.add_argument("--rtl-sim", action="store_true", help="include RTL simulator evidence; blocked does not pass")
  3189. final_gate_v2.add_argument("--hdl-backend", choices=["icarus", "verilator", "cocotb", "all"], default="icarus")
  3190. final_gate_v2.add_argument("--formal", action="store_true", help="include formal evidence; blocked does not pass")
  3191. final_gate_v2.add_argument("--formal-engine", choices=["sby"], default="sby")
  3192. final_gate_v2.add_argument("--detector-selftest", action="store_true", help="include detector selftests; blocked does not pass")
  3193. final_gate_v2.add_argument("--td-build", action="store_true", help="include TD top evidence; blocked/skipped does not pass")
  3194. final_gate_v2.add_argument("--td-top", choices=list(TD_TOP_PROFILES), default=DEFAULT_TD_TOP)
  3195. final_gate_v2.add_argument("--json", action="store_true")
  3196. final_gate_v2.add_argument("--report-file", type=Path)
  3197. final_gate_v2.set_defaults(func=cmd_final_gate_v2)
  3198. offline_gate = sub.add_parser("offline-fidelity-gate-v1", help="run strict no-hardware offline fidelity gate")
  3199. offline_gate.add_argument("--auto-bootstrap", action="store_true", help="allow user-space OSS CAD Suite/cocotb bootstrap only")
  3200. offline_gate.add_argument("--hdl-backend", choices=["icarus", "verilator", "cocotb", "all"], default="all")
  3201. offline_gate.add_argument("--formal", action="store_true", help="require formal evidence")
  3202. offline_gate.add_argument("--td-build", action="store_true", help="require TD offline elaboration/build evidence")
  3203. offline_gate.add_argument("--long-run", choices=["ci", "nightly", "final"], default="ci")
  3204. offline_gate.add_argument("--json", action="store_true")
  3205. offline_gate.add_argument("--report-file", type=Path)
  3206. offline_gate.set_defaults(func=cmd_offline_fidelity_gate_v1)
  3207. clean_runtime = sub.add_parser("clean-runtime", help="clear runtime build/log/receipt outputs before fresh verification")
  3208. clean_runtime.add_argument("--include-external-td-log", action="store_true", help="also clear TD install bin/log bw_*.log* files")
  3209. clean_runtime.add_argument("--json", action="store_true")
  3210. clean_runtime.add_argument("--report-file", type=Path)
  3211. clean_runtime.set_defaults(func=cmd_clean_runtime)
  3212. toolchain_clean = sub.add_parser("toolchain-clean", help="dry-run or remove owned user-mode verification toolchain caches")
  3213. toolchain_clean.add_argument("--install-root", type=Path, default=DEFAULT_OSS_CAD_SUITE_ROOT)
  3214. toolchain_clean.add_argument("--cocotb-venv", type=Path, default=DEFAULT_COCOTB_VENV_PYTHON.parent.parent)
  3215. toolchain_clean.add_argument("--include-downloads", action="store_true")
  3216. toolchain_clean.add_argument("--apply", action="store_true", help="actually delete owned toolchain paths; default is dry-run")
  3217. toolchain_clean.add_argument("--json", action="store_true")
  3218. toolchain_clean.add_argument("--report-file", type=Path)
  3219. toolchain_clean.set_defaults(func=cmd_toolchain_clean)
  3220. td = sub.add_parser("td-build", help="probe TD synthesis/implementation")
  3221. td.add_argument("--run", action="store_true", help="actually invoke TD")
  3222. td.add_argument("--top", choices=list(TD_TOP_PROFILES), default=DEFAULT_TD_TOP)
  3223. td.add_argument("--json", action="store_true")
  3224. td.add_argument("--report-file", type=Path)
  3225. td.set_defaults(func=cmd_td_build)
  3226. td_alias = sub.add_parser("td", help="probe TD synthesis/implementation")
  3227. td_alias.add_argument("--run", action="store_true", help="actually invoke TD")
  3228. td_alias.add_argument("--top", choices=list(TD_TOP_PROFILES), default=DEFAULT_TD_TOP)
  3229. td_alias.add_argument("--json", action="store_true")
  3230. td_alias.add_argument("--report-file", type=Path)
  3231. td_alias.set_defaults(func=cmd_td_build)
  3232. hdl = sub.add_parser("hdl-sim", help="run optional HDL simulation tests")
  3233. hdl.add_argument("--run", action="store_true", help="actually invoke the selected simulator backend")
  3234. hdl.add_argument("--backend", choices=["icarus", "verilator", "cocotb", "all"], default="icarus")
  3235. hdl.add_argument("--scenario", type=Path)
  3236. hdl.add_argument("--json", action="store_true")
  3237. hdl.add_argument("--report-file", type=Path)
  3238. hdl.set_defaults(func=cmd_hdl_sim)
  3239. rtl = sub.add_parser("rtl-sim", help="run optional RTL simulation tests")
  3240. rtl.add_argument("--run", action="store_true", help="actually invoke iverilog/vvp")
  3241. rtl.add_argument("--json", action="store_true")
  3242. rtl.add_argument("--report-file", type=Path)
  3243. rtl.set_defaults(func=cmd_rtl_sim)
  3244. formal = sub.add_parser("formal", help="run optional formal property checks")
  3245. formal.add_argument("--run", action="store_true", help="actually invoke the selected formal engine")
  3246. formal.add_argument("--engine", choices=["sby"], default="sby")
  3247. formal.add_argument("--json", action="store_true")
  3248. formal.add_argument("--report-file", type=Path)
  3249. formal.set_defaults(func=cmd_formal)
  3250. selftest = sub.add_parser("detector-selftest", help="run bad-fixture selftests for verification detectors")
  3251. selftest.add_argument("--run", action="store_true", help="actually invoke detector backends on bad fixtures")
  3252. selftest.add_argument("--backend", choices=["all", "icarus", "verilator", "cocotb", "formal"], default="all")
  3253. selftest.add_argument("--json", action="store_true")
  3254. selftest.add_argument("--report-file", type=Path)
  3255. selftest.set_defaults(func=cmd_detector_selftest)
  3256. dbg = sub.add_parser("debug-bundle", help="build an agent-readable debug bundle")
  3257. dbg.add_argument("--source", choices=["replay", "hdl", "formal", "td", "hardware", "rtl", "register", "uart"], default="replay")
  3258. dbg.add_argument("--output-dir", type=Path)
  3259. dbg.add_argument("--raw-file", type=Path, action="append", default=[], help="copy a manual export file into the bundle raw/ directory")
  3260. dbg.add_argument("--raw-dir", type=Path, action="append", default=[], help="copy a manual export directory into the bundle raw/ directory")
  3261. dbg.add_argument("--json", action="store_true")
  3262. dbg.set_defaults(func=cmd_debug_bundle)
  3263. analyze = sub.add_parser("analyze-bundle", help="analyze an agent-readable debug bundle")
  3264. analyze.add_argument("bundle_dir", type=Path)
  3265. analyze.add_argument("--json", action="store_true")
  3266. analyze.set_defaults(func=cmd_analyze_bundle)
  3267. pipe = sub.add_parser("pipeline", help="run layered checks")
  3268. pipe.add_argument("--td-build", action="store_true", help="include TD build probe")
  3269. pipe.add_argument("--rtl-sim", action="store_true", help="include optional RTL simulation probe")
  3270. pipe.add_argument("--hdl-sim", action="store_true", help="include optional HDL simulation probe")
  3271. pipe.add_argument("--hdl-backend", choices=["icarus", "verilator", "cocotb", "all"], default="all")
  3272. pipe.add_argument("--scenario", type=Path)
  3273. pipe.add_argument("--formal", action="store_true", help="include optional formal verification probe")
  3274. pipe.add_argument("--formal-engine", choices=["sby"], default="sby")
  3275. pipe.add_argument("--detector-selftest", action="store_true", help="run bad-fixture detector selftests")
  3276. pipe.add_argument("--debug-bundle", action="store_true", help="write a replay-based agent debug bundle")
  3277. pipe.add_argument("--json", action="store_true")
  3278. pipe.add_argument("--report-file", type=Path)
  3279. pipe.set_defaults(func=cmd_pipeline)
  3280. return parser
  3281. def main(argv: list[str] | None = None) -> int:
  3282. parser = build_parser()
  3283. args = parser.parse_args(argv)
  3284. return args.func(args)
  3285. if __name__ == "__main__":
  3286. sys.exit(main())