| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242 |
- #!/usr/bin/env python3
- """Read-only environment check for the top-level CPLD PID debug workflows."""
- from __future__ import annotations
- import argparse
- import json
- import os
- import shutil
- import subprocess
- import sys
- from dataclasses import dataclass
- from pathlib import Path
- from typing import Any
- sys.dont_write_bytecode = True
- PID_ROOT = Path(__file__).resolve().parents[1]
- REPO_ROOT = PID_ROOT
- TD_GUI = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412\bin\td.exe")
- TD_CLI = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412\bin\td_commands_prompt.exe")
- BUNDLED_PYTHON = Path(
- str(Path.home() / ".cache" / "codex-runtimes" / "codex-primary-runtime" / "dependencies" / "python" / "python.exe")
- )
- GIT_EXE = Path(r"C:\Program Files\Git\cmd\git.exe")
- DEFAULT_OSS_CAD_SUITE_ROOT = Path.home() / "CodexToolchains" / "CPLD" / "oss-cad-suite" / "latest"
- @dataclass(frozen=True)
- class CommandResult:
- returncode: int
- stdout: str
- stderr: str
- def run_text(args: list[str], cwd: Path | None = None, timeout: int = 20) -> CommandResult:
- """Run a read-only command and return text output without raising."""
- try:
- result = subprocess.run(
- args,
- cwd=cwd,
- text=True,
- stdout=subprocess.PIPE,
- stderr=subprocess.PIPE,
- timeout=timeout,
- )
- except (OSError, subprocess.SubprocessError) as exc:
- return CommandResult(1, "", str(exc))
- return CommandResult(result.returncode, result.stdout, result.stderr)
- def path_status(path: Path) -> dict[str, Any]:
- status = "present" if path.is_file() else "missing"
- return {"status": status, "path": str(path)}
- def which_status(name: str) -> dict[str, Any]:
- path = shutil.which(name)
- discovery = "PATH" if path else "not_found"
- if not path:
- executable_names = [name] if name.lower().endswith(".exe") else [name, f"{name}.exe"]
- roots = [
- os.environ.get("PID_STUDY_TOOLCHAIN_ROOT"),
- os.environ.get("PID_STUDY_01_TOOLCHAIN_ROOT"),
- os.environ.get("OSS_CAD_SUITE_ROOT"),
- str(DEFAULT_OSS_CAD_SUITE_ROOT),
- ]
- for root_text in roots:
- if not root_text:
- continue
- root = Path(root_text)
- for exe_name in executable_names:
- candidate = root / "bin" / exe_name
- if candidate.is_file():
- path = str(candidate)
- discovery = "env_or_default_toolchain_root"
- break
- if path:
- break
- return {"status": "present" if path else "missing", "path": path, "discovery": discovery}
- def detect_repo(repo_root: Path, git_exe: Path) -> dict[str, Any]:
- if not git_exe.is_file():
- return {"root": str(repo_root), "branch": None, "head": None, "git_status": "missing"}
- branch = run_text([str(git_exe), "branch", "--show-current"], cwd=repo_root)
- head = run_text([str(git_exe), "rev-parse", "--short", "HEAD"], cwd=repo_root)
- return {
- "root": str(repo_root),
- "branch": branch.stdout.strip() if branch.returncode == 0 else None,
- "head": head.stdout.strip() if head.returncode == 0 else None,
- "git_status": "present",
- "branch_probe_returncode": branch.returncode,
- "head_probe_returncode": head.returncode,
- }
- def detect_bundled_python(path: Path) -> dict[str, Any]:
- payload = path_status(path)
- if payload["status"] == "present":
- result = run_text([str(path), "--version"])
- version_text = (result.stdout or result.stderr).strip()
- payload["version"] = version_text if result.returncode == 0 else None
- payload["version_probe_returncode"] = result.returncode
- return payload
- def detect_serial_ports() -> list[dict[str, Any]]:
- """Read Win32_SerialPort through PowerShell. Empty/error means no usable evidence."""
- script = (
- "Get-CimInstance Win32_SerialPort | "
- "Select-Object DeviceID,Name,Description,PNPDeviceID | "
- "ConvertTo-Json -Compress"
- )
- result = run_text(["powershell", "-NoProfile", "-Command", script], cwd=REPO_ROOT)
- if result.returncode != 0 or not result.stdout.strip():
- return []
- try:
- parsed = json.loads(result.stdout)
- except json.JSONDecodeError:
- return []
- if isinstance(parsed, dict):
- parsed = [parsed]
- if not isinstance(parsed, list):
- return []
- ports: list[dict[str, Any]] = []
- for item in parsed:
- if not isinstance(item, dict):
- continue
- ports.append({
- "device_id": item.get("DeviceID"),
- "name": item.get("Name"),
- "description": item.get("Description"),
- "pnp_device_id": item.get("PNPDeviceID"),
- })
- return ports
- def compute_overall_status(tools: dict[str, Any]) -> str:
- required = ["td_gui", "td_cli", "bundled_python", "git"]
- if all(tools[name]["status"] == "present" for name in required):
- return "ready_for_offline_debug"
- return "blocked_missing_required_tools"
- def build_environment_report(
- repo_root: Path = REPO_ROOT,
- pid_root: Path = PID_ROOT,
- td_gui: Path = TD_GUI,
- td_cli: Path = TD_CLI,
- bundled_python: Path = BUNDLED_PYTHON,
- git_exe: Path = GIT_EXE,
- ) -> dict[str, Any]:
- tools: dict[str, Any] = {
- "td_gui": path_status(td_gui),
- "td_cli": path_status(td_cli),
- "bundled_python": detect_bundled_python(bundled_python),
- "git": path_status(git_exe),
- "iverilog": which_status("iverilog"),
- "vvp": which_status("vvp"),
- }
- serial_ports = detect_serial_ports()
- return {
- "schema": "pid_study_01.debug_environment.v1",
- "status": compute_overall_status(tools),
- "repo": detect_repo(repo_root, git_exe),
- "paths": {
- "pid_study_01": str(pid_root),
- "td_bin": str(td_cli.parent),
- },
- "tools": tools,
- "hardware": {
- "serial_ports": {
- "status": "detected" if serial_ports else "not_detected",
- "ports": serial_ports,
- "probe": "Win32_SerialPort",
- },
- },
- "debug": {
- "rtl_sim": {
- "status": "available"
- if tools["iverilog"]["status"] == "present" and tools["vvp"]["status"] == "present"
- else "blocked_missing_tool",
- "origin": "project_defined_optional_verification_layer",
- "backend": "icarus",
- "required_tools": ["iverilog", "vvp"],
- "authority_boundary": "This is a project harness strategy, not an Anlogic TD or chip-vendor requirement.",
- "reason": None
- if tools["iverilog"]["status"] == "present" and tools["vvp"]["status"] == "present"
- else "missing iverilog or vvp",
- "missing_tools": [
- name for name in ["iverilog", "vvp"]
- if tools[name]["status"] != "present"
- ],
- },
- "uart": {
- "status": "hardware_not_detected" if not serial_ports else "serial_port_detected",
- "electrical_boundary": "FPGA UART debug is 3.3V TTL; RS232 requires MAX3232 or isolation.",
- "preflight_boundary": "Read-only COM enumeration only; do not open unknown COM ports or toggle DTR/RTS.",
- },
- },
- }
- def render_human(report: dict[str, Any]) -> str:
- serial = report["hardware"]["serial_ports"]
- lines = [
- f"status: {report['status']}",
- f"repo: {report['repo']['root']}",
- f"branch: {report['repo']['branch']}",
- f"head: {report['repo']['head']}",
- f"TD GUI: {report['tools']['td_gui']['status']} {report['tools']['td_gui']['path']}",
- f"TD CLI: {report['tools']['td_cli']['status']} {report['tools']['td_cli']['path']}",
- f"Python: {report['tools']['bundled_python']['status']} {report['tools']['bundled_python'].get('version')}",
- f"Git: {report['tools']['git']['status']} {report['tools']['git']['path']}",
- f"iverilog: {report['tools']['iverilog']['status']}",
- f"vvp: {report['tools']['vvp']['status']}",
- f"serial_ports: {serial['status']} count={len(serial['ports'])}",
- f"UART debug: {report['debug']['uart']['status']}",
- ]
- return "\n".join(lines)
- def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--json", action="store_true", help="print machine-readable JSON")
- return parser
- def main(argv: list[str] | None = None) -> int:
- args = build_parser().parse_args(argv)
- report = build_environment_report()
- if args.json:
- print(json.dumps(report, indent=2, ensure_ascii=False))
- else:
- print(render_human(report))
- return 0 if report["status"] in {"ready_for_offline_debug", "blocked_missing_required_tools"} else 1
- if __name__ == "__main__":
- sys.exit(main())
|