fw_targets.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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, registry_path: Path | None = None) -> dict[str, Any]:
  31. base = Path(root) if root is not None else repo_root()
  32. path = registry_path or 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. owner: dict[str, str] = {}
  46. for canonical, entry in targets.items():
  47. for alias in {canonical, str(entry['project_id']), *entry.get('aliases', [])}:
  48. key=str(alias).strip().lower()
  49. if not key or (key in owner and owner[key]!=canonical):
  50. raise ValueError(f"ambiguous target alias: {alias}")
  51. owner[key]=canonical
  52. return payload
  53. def list_aliases(root: Path | None = None) -> tuple[str, ...]:
  54. return tuple(load_registry(root)["targets"])
  55. def resolve_target(name: str, root: Path | None = None, registry_path: Path | None = None) -> dict[str, Any]:
  56. base = Path(root) if root is not None else repo_root()
  57. key = str(name).strip().lower()
  58. targets = load_registry(base, registry_path)["targets"]
  59. choices=[canonical for canonical, entry in targets.items() if key in
  60. {str(x).strip().lower() for x in {canonical, entry['project_id'], *entry.get('aliases', [])}}]
  61. if len(choices)!=1:
  62. known = ", ".join(sorted(targets))
  63. raise ValueError(f"unknown target {name!r}; known targets: {known}")
  64. canonical=choices[0]
  65. entry = dict(targets[canonical])
  66. entry["alias"] = canonical
  67. entry["root"] = str(base)
  68. return entry
  69. def sha256_file(path: Path) -> str:
  70. return hashlib.sha256(path.read_bytes()).hexdigest()
  71. def load_source_closure(path: Path, expected_project_id: str | None = None) -> tuple[str, ...]:
  72. payload = json.loads(path.read_text(encoding="utf-8"))
  73. if payload.get("schema") != "prod2u-source-closure-v1":
  74. raise ValueError(f"source closure schema mismatch: {path}")
  75. if expected_project_id and payload.get("project_id") != expected_project_id:
  76. raise ValueError(f"source closure project_id mismatch in {path}")
  77. sources = payload.get("sources")
  78. if not isinstance(sources, list) or not sources:
  79. raise ValueError(f"source closure missing sources: {path}")
  80. normalized: list[str] = []
  81. for value in sources:
  82. if not isinstance(value, str) or not value:
  83. raise ValueError("source closure entry must be a non-empty string")
  84. parts = Path(value).parts
  85. if ".." in parts or Path(value).is_absolute():
  86. raise ValueError(f"unsafe source closure path: {value}")
  87. normalized.append(value)
  88. if len(normalized) != len(set(normalized)):
  89. raise ValueError(f"source closure contains duplicates: {path}")
  90. root = next((parent for parent in path.resolve().parents if (parent/REGISTRY_REL).is_file()),None)
  91. if root is None:
  92. raise ValueError(f"source closure has no owning target registry: {path}")
  93. missing = [item for item in normalized if not (root / item).is_file()]
  94. # Generated headers may be absent before first generate.
  95. missing_real = [item for item in missing if not item.replace("\\", "/").startswith("generated/")]
  96. if missing_real:
  97. raise ValueError(f"source closure references missing files: {missing_real}")
  98. return tuple(normalized)
  99. def assert_6400_closure_clean(sources: Mapping[str, Any] | Iterable[str]) -> None:
  100. values = list(sources.get("sources", [])) if isinstance(sources, dict) else list(sources)
  101. joined = "\n".join(str(item) for item in values)
  102. hits = [token for token in FORBIDDEN_6400_SUBSTRINGS if token in joined]
  103. if hits:
  104. raise ValueError(f"6400 source closure contains forbidden motor/limit modules: {hits}")
  105. def unresolved_pins(project: Mapping[str, Any]) -> list[str]:
  106. names: list[str] = []
  107. for channel in project.get("outputs", {}).get("fan_channels", []):
  108. if str(channel.get("pin_status", "confirmed")) != "confirmed":
  109. names.append(str(channel.get("name", "unknown")))
  110. for channel in project.get("outputs", {}).get("ptc_channels", []):
  111. if str(channel.get("pin_status", "confirmed")) != "confirmed":
  112. names.append(str(channel.get("name", "unknown")))
  113. return names
  114. def target_status_line(alias: str, root: Path | None = None) -> str:
  115. entry = resolve_target(alias, root)
  116. if entry.get('status')=='CURRENT_PRODUCT_FULL_PENDING':
  117. return f"{entry['alias']:8} {entry['project_id']} / {entry['board']} / Full acceptance pending"
  118. if entry.get("production_bitstream") == "allowed":
  119. return f"{alias:8} release-ready"
  120. if entry.get("production_bitstream") == "blocked_td_not_wired":
  121. return f"{alias:8} logic-ready / release-blocked: 6400 production TD not wired"
  122. if entry.get("release_pin_policy") == "fail_closed_unresolved":
  123. return f"{alias:8} logic-ready / release-blocked: unresolved pins"
  124. return f"{alias:8} unknown"