fw_targets.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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. # Active-closure ban list of retired 6400 *modules and source paths*. It is not
  11. # a protocol filter: the new 8-bit frame's TYPE bytes and macro names are legal
  12. # and must never be added here.
  13. FORBIDDEN_6400_SUBSTRINGS = (
  14. "startup_close_seek",
  15. "door_motor_engine",
  16. "door_action_dispatcher",
  17. "door_percent_planner",
  18. "door_motion",
  19. "door_axis",
  20. "door_calibration",
  21. "door_shared_dda",
  22. "door_rate_quantum",
  23. "door_profile_quantum",
  24. "prod2u_runtime_step_limit_gate",
  25. "output_target_ram",
  26. "host_i2c",
  27. "src/modules/pwm_scheduler.v",
  28. "src/project/command_controller.v",
  29. "src/project/project_adapter.v",
  30. "src/top/prod2u_p4_normal_v3_top",
  31. )
  32. def repo_root() -> Path:
  33. return Path(__file__).resolve().parents[1]
  34. def load_registry(root: Path | None = None, registry_path: Path | None = None) -> dict[str, Any]:
  35. base = Path(root) if root is not None else repo_root()
  36. path = registry_path or base / REGISTRY_REL
  37. payload = json.loads(path.read_text(encoding="utf-8"))
  38. if payload.get("schema") != "prod2u-target-registry-v1":
  39. raise ValueError("target registry schema mismatch")
  40. targets = payload.get("targets")
  41. if not isinstance(targets, dict) or not targets:
  42. raise ValueError("target registry has no targets")
  43. aliases = list(targets)
  44. if len(aliases) != len(set(aliases)):
  45. raise ValueError("target aliases are not unique")
  46. ids = [str(item.get("project_id")) for item in targets.values()]
  47. if len(ids) != len(set(ids)):
  48. raise ValueError("target project_id values are not unique")
  49. owner: dict[str, str] = {}
  50. for canonical, entry in targets.items():
  51. for alias in {canonical, str(entry['project_id']), *entry.get('aliases', [])}:
  52. key=str(alias).strip().lower()
  53. if not key or (key in owner and owner[key]!=canonical):
  54. raise ValueError(f"ambiguous target alias: {alias}")
  55. owner[key]=canonical
  56. return payload
  57. def list_aliases(root: Path | None = None) -> tuple[str, ...]:
  58. return tuple(load_registry(root)["targets"])
  59. def resolve_target(name: str, root: Path | None = None, registry_path: Path | None = None) -> dict[str, Any]:
  60. base = Path(root) if root is not None else repo_root()
  61. key = str(name).strip().lower()
  62. targets = load_registry(base, registry_path)["targets"]
  63. choices=[canonical for canonical, entry in targets.items() if key in
  64. {str(x).strip().lower() for x in {canonical, entry['project_id'], *entry.get('aliases', [])}}]
  65. if len(choices)!=1:
  66. known = ", ".join(sorted(targets))
  67. raise ValueError(f"unknown target {name!r}; known targets: {known}")
  68. canonical=choices[0]
  69. entry = dict(targets[canonical])
  70. entry["alias"] = canonical
  71. entry["root"] = str(base)
  72. return entry
  73. def sha256_file(path: Path) -> str:
  74. return hashlib.sha256(path.read_bytes()).hexdigest()
  75. def load_source_closure(path: Path, expected_project_id: str | None = None) -> tuple[str, ...]:
  76. payload = json.loads(path.read_text(encoding="utf-8"))
  77. if payload.get("schema") != "prod2u-source-closure-v1":
  78. raise ValueError(f"source closure schema mismatch: {path}")
  79. if expected_project_id and payload.get("project_id") != expected_project_id:
  80. raise ValueError(f"source closure project_id mismatch in {path}")
  81. sources = payload.get("sources")
  82. if not isinstance(sources, list) or not sources:
  83. raise ValueError(f"source closure missing sources: {path}")
  84. normalized: list[str] = []
  85. for value in sources:
  86. if not isinstance(value, str) or not value:
  87. raise ValueError("source closure entry must be a non-empty string")
  88. parts = Path(value).parts
  89. if ".." in parts or Path(value).is_absolute():
  90. raise ValueError(f"unsafe source closure path: {value}")
  91. normalized.append(value)
  92. if len(normalized) != len(set(normalized)):
  93. raise ValueError(f"source closure contains duplicates: {path}")
  94. root = next((parent for parent in path.resolve().parents if (parent/REGISTRY_REL).is_file()),None)
  95. if root is None:
  96. raise ValueError(f"source closure has no owning target registry: {path}")
  97. missing = [item for item in normalized if not (root / item).is_file()]
  98. # Generated headers may be absent before first generate.
  99. missing_real = [item for item in missing if not item.replace("\\", "/").startswith("generated/")]
  100. if missing_real:
  101. raise ValueError(f"source closure references missing files: {missing_real}")
  102. return tuple(normalized)
  103. def assert_6400_closure_clean(sources: Mapping[str, Any] | Iterable[str]) -> None:
  104. values = list(sources.get("sources", [])) if isinstance(sources, dict) else list(sources)
  105. joined = "\n".join(str(item) for item in values)
  106. hits = [token for token in FORBIDDEN_6400_SUBSTRINGS if token in joined]
  107. if hits:
  108. raise ValueError(f"6400 source closure contains forbidden motor/limit modules: {hits}")
  109. def unresolved_pins(project: Mapping[str, Any]) -> list[str]:
  110. names: list[str] = []
  111. for channel in project.get("outputs", {}).get("fan_channels", []):
  112. if str(channel.get("pin_status", "confirmed")) != "confirmed":
  113. names.append(str(channel.get("name", "unknown")))
  114. for channel in project.get("outputs", {}).get("ptc_channels", []):
  115. if str(channel.get("pin_status", "confirmed")) != "confirmed":
  116. names.append(str(channel.get("name", "unknown")))
  117. return names
  118. def target_status_line(alias: str, root: Path | None = None) -> str:
  119. entry = resolve_target(alias, root)
  120. if entry.get('status')=='CURRENT_PRODUCT_FULL_PENDING':
  121. return f"{entry['alias']:8} {entry['project_id']} / {entry['board']} / Full acceptance pending"
  122. if entry.get("production_bitstream") == "allowed":
  123. return f"{alias:8} release-ready"
  124. if entry.get("production_bitstream") == "blocked_td_not_wired":
  125. return f"{alias:8} logic-ready / release-blocked: 6400 production TD not wired"
  126. if entry.get("release_pin_policy") == "fail_closed_unresolved":
  127. return f"{alias:8} logic-ready / release-blocked: unresolved pins"
  128. return f"{alias:8} unknown"