fw_targets.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. #!/usr/bin/env python3
  2. """Tiny target registry: alias -> project/build entry. Not a product contract."""
  3. from __future__ import annotations
  4. import hashlib
  5. import json
  6. from pathlib import Path
  7. from collections.abc import Iterable
  8. from typing import Any, Mapping
  9. REGISTRY_REL = Path("projects") / "registry.json"
  10. FORBIDDEN_6400_SUBSTRINGS = (
  11. "startup_close_seek",
  12. "door_motor_engine",
  13. "door_action_dispatcher",
  14. "door_percent_planner",
  15. "door_motion",
  16. "door_axis",
  17. "door_calibration",
  18. "door_shared_dda",
  19. "door_rate_quantum",
  20. "door_profile_quantum",
  21. "prod2u_runtime_step_limit_gate",
  22. "output_target_ram",
  23. "src/modules/pwm_scheduler.v",
  24. "src/project/command_controller.v",
  25. "src/project/project_adapter.v",
  26. "src/top/prod2u_p4_normal_v3_top",
  27. )
  28. def repo_root() -> Path:
  29. return Path(__file__).resolve().parents[1]
  30. def load_registry(root: Path | None = None) -> dict[str, Any]:
  31. base = Path(root) if root is not None else repo_root()
  32. path = base / REGISTRY_REL
  33. payload = json.loads(path.read_text(encoding="utf-8"))
  34. if payload.get("schema") != "prod2u-target-registry-v1":
  35. raise ValueError("target registry schema mismatch")
  36. targets = payload.get("targets")
  37. if not isinstance(targets, dict) or not targets:
  38. raise ValueError("target registry has no targets")
  39. aliases = list(targets)
  40. if len(aliases) != len(set(aliases)):
  41. raise ValueError("target aliases are not unique")
  42. ids = [str(item.get("project_id")) for item in targets.values()]
  43. if len(ids) != len(set(ids)):
  44. raise ValueError("target project_id values are not unique")
  45. return payload
  46. def list_aliases(root: Path | None = None) -> tuple[str, ...]:
  47. return tuple(load_registry(root)["targets"])
  48. def resolve_target(name: str, root: Path | None = None) -> dict[str, Any]:
  49. base = Path(root) if root is not None else repo_root()
  50. key = str(name).strip().lower()
  51. targets = load_registry(base)["targets"]
  52. if key not in targets:
  53. known = ", ".join(sorted(targets))
  54. raise ValueError(f"unknown target {name!r}; known targets: {known}")
  55. entry = dict(targets[key])
  56. entry["alias"] = key
  57. entry["root"] = str(base)
  58. return entry
  59. def sha256_file(path: Path) -> str:
  60. return hashlib.sha256(path.read_bytes()).hexdigest()
  61. def load_source_closure(path: Path, expected_project_id: str | None = None) -> tuple[str, ...]:
  62. payload = json.loads(path.read_text(encoding="utf-8"))
  63. if payload.get("schema") != "prod2u-source-closure-v1":
  64. raise ValueError(f"source closure schema mismatch: {path}")
  65. if expected_project_id and payload.get("project_id") != expected_project_id:
  66. raise ValueError(f"source closure project_id mismatch in {path}")
  67. sources = payload.get("sources")
  68. if not isinstance(sources, list) or not sources:
  69. raise ValueError(f"source closure missing sources: {path}")
  70. normalized: list[str] = []
  71. for value in sources:
  72. if not isinstance(value, str) or not value:
  73. raise ValueError("source closure entry must be a non-empty string")
  74. parts = Path(value).parts
  75. if ".." in parts or Path(value).is_absolute():
  76. raise ValueError(f"unsafe source closure path: {value}")
  77. normalized.append(value)
  78. if len(normalized) != len(set(normalized)):
  79. raise ValueError(f"source closure contains duplicates: {path}")
  80. root = path.parents[1] if path.parent.name != "prod2u-6400-front-back" else path.parents[2]
  81. if path.parent.name == "prod2u-6400-front-back":
  82. root = path.resolve().parents[2]
  83. else:
  84. root = path.resolve().parents[1]
  85. missing = [item for item in normalized if not (root / item).is_file()]
  86. # Generated headers may be absent before first generate.
  87. missing_real = [item for item in missing if "/generated/" not in item.replace("\\", "/")]
  88. if missing_real:
  89. raise ValueError(f"source closure references missing files: {missing_real}")
  90. return tuple(normalized)
  91. def assert_6400_closure_clean(sources: Mapping[str, Any] | Iterable[str]) -> None:
  92. values = list(sources.get("sources", [])) if isinstance(sources, dict) else list(sources)
  93. joined = "\n".join(str(item) for item in values)
  94. hits = [token for token in FORBIDDEN_6400_SUBSTRINGS if token in joined]
  95. if hits:
  96. raise ValueError(f"6400 source closure contains forbidden motor/limit modules: {hits}")
  97. def unresolved_pins(project: Mapping[str, Any]) -> list[str]:
  98. names: list[str] = []
  99. for channel in project.get("outputs", {}).get("fan_channels", []):
  100. if str(channel.get("pin_status", "confirmed")) != "confirmed":
  101. names.append(str(channel.get("name", "unknown")))
  102. for channel in project.get("outputs", {}).get("ptc_channels", []):
  103. if str(channel.get("pin_status", "confirmed")) != "confirmed":
  104. names.append(str(channel.get("name", "unknown")))
  105. return names
  106. def target_status_line(alias: str, root: Path | None = None) -> str:
  107. entry = resolve_target(alias, root)
  108. if entry.get("production_bitstream") == "allowed":
  109. return f"{alias:8} release-ready"
  110. if entry.get("production_bitstream") == "blocked_td_not_wired":
  111. return f"{alias:8} logic-ready / release-blocked: 6400 production TD not wired"
  112. if entry.get("release_pin_policy") == "fail_closed_unresolved":
  113. return f"{alias:8} logic-ready / release-blocked: unresolved pins"
  114. return f"{alias:8} unknown"