check_debug_environment.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. #!/usr/bin/env python3
  2. """Read-only environment check for the top-level CPLD PID debug workflows."""
  3. from __future__ import annotations
  4. import argparse
  5. import json
  6. import os
  7. import shutil
  8. import subprocess
  9. import sys
  10. from dataclasses import dataclass
  11. from pathlib import Path
  12. from typing import Any
  13. sys.dont_write_bytecode = True
  14. PID_ROOT = Path(__file__).resolve().parents[1]
  15. REPO_ROOT = PID_ROOT
  16. TD_GUI = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412\bin\td.exe")
  17. TD_CLI = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412\bin\td_commands_prompt.exe")
  18. BUNDLED_PYTHON = Path(
  19. str(Path.home() / ".cache" / "codex-runtimes" / "codex-primary-runtime" / "dependencies" / "python" / "python.exe")
  20. )
  21. GIT_EXE = Path(r"C:\Program Files\Git\cmd\git.exe")
  22. DEFAULT_OSS_CAD_SUITE_ROOT = Path.home() / "CodexToolchains" / "CPLD" / "oss-cad-suite" / "latest"
  23. @dataclass(frozen=True)
  24. class CommandResult:
  25. returncode: int
  26. stdout: str
  27. stderr: str
  28. def run_text(args: list[str], cwd: Path | None = None, timeout: int = 20) -> CommandResult:
  29. """Run a read-only command and return text output without raising."""
  30. try:
  31. result = subprocess.run(
  32. args,
  33. cwd=cwd,
  34. text=True,
  35. stdout=subprocess.PIPE,
  36. stderr=subprocess.PIPE,
  37. timeout=timeout,
  38. )
  39. except (OSError, subprocess.SubprocessError) as exc:
  40. return CommandResult(1, "", str(exc))
  41. return CommandResult(result.returncode, result.stdout, result.stderr)
  42. def path_status(path: Path) -> dict[str, Any]:
  43. status = "present" if path.is_file() else "missing"
  44. return {"status": status, "path": str(path)}
  45. def which_status(name: str) -> dict[str, Any]:
  46. path = shutil.which(name)
  47. discovery = "PATH" if path else "not_found"
  48. if not path:
  49. executable_names = [name] if name.lower().endswith(".exe") else [name, f"{name}.exe"]
  50. roots = [
  51. os.environ.get("PID_STUDY_TOOLCHAIN_ROOT"),
  52. os.environ.get("PID_STUDY_01_TOOLCHAIN_ROOT"),
  53. os.environ.get("OSS_CAD_SUITE_ROOT"),
  54. str(DEFAULT_OSS_CAD_SUITE_ROOT),
  55. ]
  56. for root_text in roots:
  57. if not root_text:
  58. continue
  59. root = Path(root_text)
  60. for exe_name in executable_names:
  61. candidate = root / "bin" / exe_name
  62. if candidate.is_file():
  63. path = str(candidate)
  64. discovery = "env_or_default_toolchain_root"
  65. break
  66. if path:
  67. break
  68. return {"status": "present" if path else "missing", "path": path, "discovery": discovery}
  69. def detect_repo(repo_root: Path, git_exe: Path) -> dict[str, Any]:
  70. if not git_exe.is_file():
  71. return {"root": str(repo_root), "branch": None, "head": None, "git_status": "missing"}
  72. branch = run_text([str(git_exe), "branch", "--show-current"], cwd=repo_root)
  73. head = run_text([str(git_exe), "rev-parse", "--short", "HEAD"], cwd=repo_root)
  74. return {
  75. "root": str(repo_root),
  76. "branch": branch.stdout.strip() if branch.returncode == 0 else None,
  77. "head": head.stdout.strip() if head.returncode == 0 else None,
  78. "git_status": "present",
  79. "branch_probe_returncode": branch.returncode,
  80. "head_probe_returncode": head.returncode,
  81. }
  82. def detect_bundled_python(path: Path) -> dict[str, Any]:
  83. payload = path_status(path)
  84. if payload["status"] == "present":
  85. result = run_text([str(path), "--version"])
  86. version_text = (result.stdout or result.stderr).strip()
  87. payload["version"] = version_text if result.returncode == 0 else None
  88. payload["version_probe_returncode"] = result.returncode
  89. return payload
  90. def detect_serial_ports() -> list[dict[str, Any]]:
  91. """Read Win32_SerialPort through PowerShell. Empty/error means no usable evidence."""
  92. script = (
  93. "Get-CimInstance Win32_SerialPort | "
  94. "Select-Object DeviceID,Name,Description,PNPDeviceID | "
  95. "ConvertTo-Json -Compress"
  96. )
  97. result = run_text(["powershell", "-NoProfile", "-Command", script], cwd=REPO_ROOT)
  98. if result.returncode != 0 or not result.stdout.strip():
  99. return []
  100. try:
  101. parsed = json.loads(result.stdout)
  102. except json.JSONDecodeError:
  103. return []
  104. if isinstance(parsed, dict):
  105. parsed = [parsed]
  106. if not isinstance(parsed, list):
  107. return []
  108. ports: list[dict[str, Any]] = []
  109. for item in parsed:
  110. if not isinstance(item, dict):
  111. continue
  112. ports.append({
  113. "device_id": item.get("DeviceID"),
  114. "name": item.get("Name"),
  115. "description": item.get("Description"),
  116. "pnp_device_id": item.get("PNPDeviceID"),
  117. })
  118. return ports
  119. def compute_overall_status(tools: dict[str, Any]) -> str:
  120. required = ["td_gui", "td_cli", "bundled_python", "git"]
  121. if all(tools[name]["status"] == "present" for name in required):
  122. return "ready_for_offline_debug"
  123. return "blocked_missing_required_tools"
  124. def build_environment_report(
  125. repo_root: Path = REPO_ROOT,
  126. pid_root: Path = PID_ROOT,
  127. td_gui: Path = TD_GUI,
  128. td_cli: Path = TD_CLI,
  129. bundled_python: Path = BUNDLED_PYTHON,
  130. git_exe: Path = GIT_EXE,
  131. ) -> dict[str, Any]:
  132. tools: dict[str, Any] = {
  133. "td_gui": path_status(td_gui),
  134. "td_cli": path_status(td_cli),
  135. "bundled_python": detect_bundled_python(bundled_python),
  136. "git": path_status(git_exe),
  137. "iverilog": which_status("iverilog"),
  138. "vvp": which_status("vvp"),
  139. }
  140. serial_ports = detect_serial_ports()
  141. return {
  142. "schema": "pid_study_01.debug_environment.v1",
  143. "status": compute_overall_status(tools),
  144. "repo": detect_repo(repo_root, git_exe),
  145. "paths": {
  146. "pid_study_01": str(pid_root),
  147. "td_bin": str(td_cli.parent),
  148. },
  149. "tools": tools,
  150. "hardware": {
  151. "serial_ports": {
  152. "status": "detected" if serial_ports else "not_detected",
  153. "ports": serial_ports,
  154. "probe": "Win32_SerialPort",
  155. },
  156. },
  157. "debug": {
  158. "rtl_sim": {
  159. "status": "available"
  160. if tools["iverilog"]["status"] == "present" and tools["vvp"]["status"] == "present"
  161. else "blocked_missing_tool",
  162. "origin": "project_defined_optional_verification_layer",
  163. "backend": "icarus",
  164. "required_tools": ["iverilog", "vvp"],
  165. "authority_boundary": "This is a project harness strategy, not an Anlogic TD or chip-vendor requirement.",
  166. "reason": None
  167. if tools["iverilog"]["status"] == "present" and tools["vvp"]["status"] == "present"
  168. else "missing iverilog or vvp",
  169. "missing_tools": [
  170. name for name in ["iverilog", "vvp"]
  171. if tools[name]["status"] != "present"
  172. ],
  173. },
  174. "uart": {
  175. "status": "hardware_not_detected" if not serial_ports else "serial_port_detected",
  176. "electrical_boundary": "FPGA UART debug is 3.3V TTL; RS232 requires MAX3232 or isolation.",
  177. "preflight_boundary": "Read-only COM enumeration only; do not open unknown COM ports or toggle DTR/RTS.",
  178. },
  179. },
  180. }
  181. def render_human(report: dict[str, Any]) -> str:
  182. serial = report["hardware"]["serial_ports"]
  183. lines = [
  184. f"status: {report['status']}",
  185. f"repo: {report['repo']['root']}",
  186. f"branch: {report['repo']['branch']}",
  187. f"head: {report['repo']['head']}",
  188. f"TD GUI: {report['tools']['td_gui']['status']} {report['tools']['td_gui']['path']}",
  189. f"TD CLI: {report['tools']['td_cli']['status']} {report['tools']['td_cli']['path']}",
  190. f"Python: {report['tools']['bundled_python']['status']} {report['tools']['bundled_python'].get('version')}",
  191. f"Git: {report['tools']['git']['status']} {report['tools']['git']['path']}",
  192. f"iverilog: {report['tools']['iverilog']['status']}",
  193. f"vvp: {report['tools']['vvp']['status']}",
  194. f"serial_ports: {serial['status']} count={len(serial['ports'])}",
  195. f"UART debug: {report['debug']['uart']['status']}",
  196. ]
  197. return "\n".join(lines)
  198. def build_parser() -> argparse.ArgumentParser:
  199. parser = argparse.ArgumentParser(description=__doc__)
  200. parser.add_argument("--json", action="store_true", help="print machine-readable JSON")
  201. return parser
  202. def main(argv: list[str] | None = None) -> int:
  203. args = build_parser().parse_args(argv)
  204. report = build_environment_report()
  205. if args.json:
  206. print(json.dumps(report, indent=2, ensure_ascii=False))
  207. else:
  208. print(render_human(report))
  209. return 0 if report["status"] in {"ready_for_offline_debug", "blocked_missing_required_tools"} else 1
  210. if __name__ == "__main__":
  211. sys.exit(main())