gen_run_manifest.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. #!/usr/bin/env python3
  2. """Build run-manifest.md/json from this-run *.meta files. Never invent Pass."""
  3. from __future__ import annotations
  4. import hashlib
  5. import json
  6. import os
  7. import subprocess
  8. from datetime import datetime, timezone
  9. from pathlib import Path
  10. def parse_meta(path: Path) -> dict[str, str]:
  11. out: dict[str, str] = {}
  12. for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
  13. for tok in line.replace(",", " ").split():
  14. if "=" not in tok:
  15. continue
  16. k, _, v = tok.partition("=")
  17. out[k.strip()] = v.strip()
  18. if line.startswith("command="):
  19. out["command"] = line[len("command=") :]
  20. return out
  21. def status_of(meta: dict[str, str], name: str) -> str:
  22. raw = (meta.get("status") or "").upper()
  23. if raw in {"PASS", "FAIL", "BLOCKED", "NOT RUN", "NOT_RUN"}:
  24. return "NOT RUN" if raw == "NOT_RUN" else raw
  25. if "BLOCKED" in name.upper():
  26. return "BLOCKED"
  27. if "NOT_RUN" in name.upper() or "NOT RUN" in name.upper():
  28. return "NOT RUN"
  29. if "govulncheck" in name:
  30. return "FAIL" if meta.get("exit", "1") not in {"0"} else "PASS"
  31. for key in ("exit", "pytest_exit", "python_exit", "capture_exit", "buf_lint_exit", "buf_breaking_exit"):
  32. if key in meta:
  33. try:
  34. if int(meta[key]) != 0:
  35. return "FAIL"
  36. except ValueError:
  37. return "UNKNOWN"
  38. if any(k in meta for k in ("exit", "pytest_exit", "python_exit", "capture_exit", "buf_lint_exit")):
  39. return "PASS"
  40. return "UNKNOWN"
  41. def main() -> int:
  42. import sys
  43. run = Path(os.environ.get("HTH_RUN_DIR") or (sys.argv[1] if len(sys.argv) > 1 else ""))
  44. if not run.is_dir():
  45. raise SystemExit(f"missing run dir {run}")
  46. rows = []
  47. for meta_path in sorted(run.glob("*.meta")):
  48. meta = parse_meta(meta_path)
  49. name = meta_path.name[: -len(".meta")]
  50. log = run / f"{name}.log"
  51. sha = meta.get("log_sha256", "")
  52. if not sha and log.is_file():
  53. sha = hashlib.sha256(log.read_bytes()).hexdigest()
  54. cmd = meta.get("command") or name
  55. st = status_of(meta, name)
  56. reason = ""
  57. reason_sha = ""
  58. if st == "NOT RUN":
  59. reason = (meta.get("reason") or cmd or "not executed this run").strip()
  60. reason_sha = hashlib.sha256(reason.encode("utf-8")).hexdigest()
  61. rows.append(
  62. {
  63. "name": name,
  64. "command": cmd,
  65. "status": st,
  66. "exit": meta.get("exit") or meta.get("pytest_exit") or "",
  67. "start_utc": meta.get("start_utc", ""),
  68. "end_utc": meta.get("end_utc", ""),
  69. "duration_s": meta.get("duration_s", ""),
  70. "cwd": meta.get("cwd", ""),
  71. "commit": meta.get("commit", ""),
  72. "tree": meta.get("tree", ""),
  73. "dirty": meta.get("dirty", ""),
  74. "log": f"{name}.log" if log.is_file() else "",
  75. "log_sha256": sha,
  76. "not_run_reason": reason,
  77. "not_run_reason_sha256": reason_sha,
  78. "required_for_stage": meta.get("required_for_stage", ""),
  79. "recorded_utc": meta.get("end_utc") or meta.get("start_utc", ""),
  80. }
  81. )
  82. # honor explicit NOT RUN / BLOCKED text files
  83. for p in sorted(run.iterdir()):
  84. if p.suffix == ".txt" and ("NOT_RUN" in p.name or "NOT RUN" in p.read_text(encoding="utf-8", errors="replace")[:200]):
  85. reason = p.read_text(encoding="utf-8", errors="replace").strip()
  86. reason_sha = hashlib.sha256(reason.encode("utf-8")).hexdigest()
  87. rows.append(
  88. {
  89. "name": p.stem,
  90. "command": reason.splitlines()[0][:200] if reason else p.name,
  91. "status": "NOT RUN",
  92. "exit": "",
  93. "start_utc": "",
  94. "end_utc": "",
  95. "log": p.name,
  96. "log_sha256": "",
  97. "not_run_reason": reason,
  98. "not_run_reason_sha256": reason_sha,
  99. "required_for_stage": "release_candidate",
  100. "recorded_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
  101. "commit": os.environ.get("HTH_GIT_COMMIT", ""),
  102. "tree": os.environ.get("HTH_GIT_TREE", ""),
  103. }
  104. )
  105. nspawn = run / "systemd-nspawn-vm.log"
  106. if nspawn.is_file():
  107. txt = nspawn.read_text(encoding="utf-8", errors="replace")
  108. if "BLOCKED" in txt:
  109. rows.append(
  110. {
  111. "name": "systemd-nspawn-vm",
  112. "command": "systemd-nspawn Debian VM host safety matrix",
  113. "status": "BLOCKED",
  114. "exit": "2",
  115. "start_utc": "",
  116. "end_utc": "",
  117. "log": nspawn.name,
  118. "log_sha256": "",
  119. }
  120. )
  121. git_root = Path(os.environ.get("HTH_GIT_ROOT") or Path(__file__).resolve().parents[2])
  122. commit = os.environ.get("HTH_GIT_COMMIT", "")
  123. tree = os.environ.get("HTH_GIT_TREE", "")
  124. dirty = os.environ.get("HTH_GIT_DIRTY", "")
  125. if not commit:
  126. try:
  127. commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=git_root, text=True).strip()
  128. except (subprocess.CalledProcessError, FileNotFoundError):
  129. commit = "unknown"
  130. if not tree:
  131. try:
  132. tree = subprocess.check_output(["git", "rev-parse", "HEAD^{tree}"], cwd=git_root, text=True).strip()
  133. except (subprocess.CalledProcessError, FileNotFoundError):
  134. tree = "unknown"
  135. if not dirty:
  136. try:
  137. scope = os.environ.get("HTH_GIT_SCOPE", "host")
  138. args = ["git", "status", "--porcelain"]
  139. if scope == "host":
  140. args.extend(["--", "host"])
  141. st = subprocess.check_output(args, cwd=git_root, text=True)
  142. dirty = "dirty" if st.strip() else "clean"
  143. except (subprocess.CalledProcessError, FileNotFoundError):
  144. dirty = "unknown"
  145. sys.path.insert(0, str(Path(__file__).resolve().parent))
  146. from evaluate_gates import evaluate
  147. verdict = evaluate(rows, expect_commit=commit, expect_tree=tree)
  148. payload = {
  149. "run_id": os.environ.get("HTH_RUN_ID", run.name),
  150. "git_commit": commit,
  151. "git_tree": tree,
  152. "git_dirty": dirty != "clean",
  153. "git_dirty_state": dirty,
  154. "generated_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
  155. "commands": rows,
  156. "software_safety_acceptance": verdict["software_safety_acceptance"],
  157. "software_simulation_integration_acceptance": verdict["software_simulation_integration_acceptance"],
  158. "hardware_validation": verdict["hardware_validation"],
  159. "real_actuator_validation": verdict["real_actuator_validation"],
  160. "architecture_direction": verdict["architecture_direction"],
  161. "ready_for_controlled_hardware_validation": verdict["ready_for_controlled_hardware_validation"],
  162. "release_candidate_readiness": verdict["release_candidate_readiness"],
  163. "production_readiness": verdict["production_readiness"],
  164. "gates": verdict["gates"],
  165. "algorithm_facade_acceptance": verdict.get("algorithm_facade_acceptance"),
  166. "algorithm_installation_acceptance": verdict.get("algorithm_installation_acceptance"),
  167. "algorithm_portable_kit_acceptance": verdict.get("algorithm_portable_kit_acceptance"),
  168. "ready_for_algorithm_development": verdict.get("ready_for_algorithm_development"),
  169. }
  170. out_json = run / "run-manifest.json"
  171. out_md = run / "run-manifest.md"
  172. out_json.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
  173. lines = [
  174. f"# Run manifest {payload['run_id']}",
  175. "",
  176. f"Generated {payload['generated_utc']}",
  177. "",
  178. "| Name | Command | Status | SHA-256 |",
  179. "|---|---|---|---|",
  180. ]
  181. for r in rows:
  182. cmd = r["command"].replace("|", "\\|")[:120]
  183. lines.append(f"| `{r['name']}` | `{cmd}` | {r['status']} | `{r['log_sha256']}` |")
  184. lines.extend(
  185. [
  186. "",
  187. f"Software simulation & integration acceptance: **{payload['software_simulation_integration_acceptance']}**",
  188. f"Ready for controlled hardware validation: **{payload['ready_for_controlled_hardware_validation']}**",
  189. f"Release candidate readiness: **{payload['release_candidate_readiness']}**",
  190. f"Production readiness: **{payload['production_readiness']}**",
  191. f"Hardware validation: **{payload['hardware_validation']}**",
  192. f"Real actuator validation: **{payload['real_actuator_validation']}**",
  193. f"Architecture direction: **{payload['architecture_direction']}**",
  194. "",
  195. ]
  196. )
  197. out_md.write_text("\n".join(lines) + "\n", encoding="utf-8")
  198. matrix = [
  199. "# Acceptance Matrix",
  200. "",
  201. f"Run ID: `{payload['run_id']}`",
  202. f"Git commit: `{payload['git_commit']}`",
  203. f"Git tree: `{payload['git_tree']}`",
  204. f"Dirty: `{payload['git_dirty_state']}`",
  205. "",
  206. "| Gate | Status |",
  207. "|---|---|",
  208. ]
  209. for k, v in (payload.get("gates") or {}).items():
  210. matrix.append(f"| `{k}` | **{v}** |")
  211. matrix.extend(
  212. [
  213. "",
  214. f"architecture_direction: **{payload['architecture_direction']}**",
  215. f"software_simulation_integration_acceptance: **{payload['software_simulation_integration_acceptance']}**",
  216. f"ready_for_controlled_hardware_validation: **{payload['ready_for_controlled_hardware_validation']}**",
  217. f"release_candidate_readiness: **{payload['release_candidate_readiness']}**",
  218. f"production_readiness: **{payload['production_readiness']}**",
  219. f"hardware_validation: **{payload['hardware_validation']}**",
  220. f"real_actuator_validation: **{payload['real_actuator_validation']}**",
  221. f"algorithm_facade_acceptance: **{payload.get('algorithm_facade_acceptance')}**",
  222. f"algorithm_installation_acceptance: **{payload.get('algorithm_installation_acceptance')}**",
  223. f"algorithm_portable_kit_acceptance: **{payload.get('algorithm_portable_kit_acceptance')}**",
  224. f"ready_for_algorithm_development: **{payload.get('ready_for_algorithm_development')}**",
  225. "",
  226. "This file is generated by `gen_run_manifest.py` / Gate Evaluator. Do not hand-edit PASS.",
  227. "",
  228. ]
  229. )
  230. (run / "ACCEPTANCE_MATRIX.md").write_text("\n".join(matrix), encoding="utf-8")
  231. (run / "acceptance-verdict.json").write_text(json.dumps(verdict, indent=2) + "\n", encoding="utf-8")
  232. print(out_json)
  233. print(out_md)
  234. return 0
  235. if __name__ == "__main__":
  236. raise SystemExit(main())