gen_run_manifest.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. import hashlib
  54. sha = hashlib.sha256(log.read_bytes()).hexdigest()
  55. cmd = meta.get("command") or name
  56. st = status_of(meta, name)
  57. reason = ""
  58. reason_sha = ""
  59. if st == "NOT RUN":
  60. reason = (meta.get("reason") or cmd or "not executed this run").strip()
  61. import hashlib
  62. reason_sha = hashlib.sha256(reason.encode("utf-8")).hexdigest()
  63. rows.append(
  64. {
  65. "name": name,
  66. "command": cmd,
  67. "status": st,
  68. "exit": meta.get("exit") or meta.get("pytest_exit") or "",
  69. "start_utc": meta.get("start_utc", ""),
  70. "end_utc": meta.get("end_utc", ""),
  71. "duration_s": meta.get("duration_s", ""),
  72. "cwd": meta.get("cwd", ""),
  73. "commit": meta.get("commit", ""),
  74. "tree": meta.get("tree", ""),
  75. "dirty": meta.get("dirty", ""),
  76. "log": f"{name}.log" if log.is_file() else "",
  77. "log_sha256": sha,
  78. "not_run_reason": reason,
  79. "not_run_reason_sha256": reason_sha,
  80. "required_for_stage": meta.get("required_for_stage", ""),
  81. "recorded_utc": meta.get("end_utc") or meta.get("start_utc", ""),
  82. }
  83. )
  84. # honor explicit NOT RUN / BLOCKED text files
  85. for p in sorted(run.iterdir()):
  86. if p.suffix == ".txt" and ("NOT_RUN" in p.name or "NOT RUN" in p.read_text(encoding="utf-8", errors="replace")[:200]):
  87. reason = p.read_text(encoding="utf-8", errors="replace").strip()
  88. reason_sha = hashlib.sha256(reason.encode("utf-8")).hexdigest()
  89. rows.append(
  90. {
  91. "name": p.stem,
  92. "command": reason.splitlines()[0][:200] if reason else p.name,
  93. "status": "NOT RUN",
  94. "exit": "",
  95. "start_utc": "",
  96. "end_utc": "",
  97. "log": p.name,
  98. "log_sha256": "",
  99. "not_run_reason": reason,
  100. "not_run_reason_sha256": reason_sha,
  101. "required_for_stage": "release_candidate",
  102. "recorded_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
  103. "commit": os.environ.get("HTH_GIT_COMMIT", ""),
  104. "tree": os.environ.get("HTH_GIT_TREE", ""),
  105. }
  106. )
  107. nspawn = run / "systemd-nspawn-vm.log"
  108. if nspawn.is_file():
  109. txt = nspawn.read_text(encoding="utf-8", errors="replace")
  110. if "BLOCKED" in txt:
  111. rows.append(
  112. {
  113. "name": "systemd-nspawn-vm",
  114. "command": "systemd-nspawn Debian VM host safety matrix",
  115. "status": "BLOCKED",
  116. "exit": "2",
  117. "start_utc": "",
  118. "end_utc": "",
  119. "log": nspawn.name,
  120. "log_sha256": "",
  121. }
  122. )
  123. git_root = Path(os.environ.get("HTH_GIT_ROOT") or Path(__file__).resolve().parents[2])
  124. commit = os.environ.get("HTH_GIT_COMMIT", "")
  125. tree = os.environ.get("HTH_GIT_TREE", "")
  126. dirty = os.environ.get("HTH_GIT_DIRTY", "")
  127. if not commit:
  128. try:
  129. commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=git_root, text=True).strip()
  130. except (subprocess.CalledProcessError, FileNotFoundError):
  131. commit = "unknown"
  132. if not tree:
  133. try:
  134. tree = subprocess.check_output(["git", "rev-parse", "HEAD^{tree}"], cwd=git_root, text=True).strip()
  135. except (subprocess.CalledProcessError, FileNotFoundError):
  136. tree = "unknown"
  137. if not dirty:
  138. try:
  139. scope = os.environ.get("HTH_GIT_SCOPE", "host")
  140. args = ["git", "status", "--porcelain"]
  141. if scope == "host":
  142. args.extend(["--", "host"])
  143. st = subprocess.check_output(args, cwd=git_root, text=True)
  144. dirty = "dirty" if st.strip() else "clean"
  145. except (subprocess.CalledProcessError, FileNotFoundError):
  146. dirty = "unknown"
  147. sys.path.insert(0, str(Path(__file__).resolve().parent))
  148. from evaluate_gates import evaluate
  149. verdict = evaluate(rows, expect_commit=commit, expect_tree=tree)
  150. payload = {
  151. "run_id": os.environ.get("HTH_RUN_ID", run.name),
  152. "git_commit": commit,
  153. "git_tree": tree,
  154. "git_dirty": dirty != "clean",
  155. "git_dirty_state": dirty,
  156. "generated_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
  157. "commands": rows,
  158. "software_safety_acceptance": verdict["software_safety_acceptance"],
  159. "software_simulation_integration_acceptance": verdict["software_simulation_integration_acceptance"],
  160. "hardware_validation": verdict["hardware_validation"],
  161. "real_actuator_validation": verdict["real_actuator_validation"],
  162. "architecture_direction": verdict["architecture_direction"],
  163. "ready_for_controlled_hardware_validation": verdict["ready_for_controlled_hardware_validation"],
  164. "release_candidate_readiness": verdict["release_candidate_readiness"],
  165. "production_readiness": verdict["production_readiness"],
  166. "gates": verdict["gates"],
  167. }
  168. out_json = run / "run-manifest.json"
  169. out_md = run / "run-manifest.md"
  170. out_json.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
  171. lines = [
  172. f"# Run manifest {payload['run_id']}",
  173. "",
  174. f"Generated {payload['generated_utc']}",
  175. "",
  176. "| Name | Command | Status | SHA-256 |",
  177. "|---|---|---|---|",
  178. ]
  179. for r in rows:
  180. cmd = r["command"].replace("|", "\\|")[:120]
  181. lines.append(f"| `{r['name']}` | `{cmd}` | {r['status']} | `{r['log_sha256']}` |")
  182. lines.extend(
  183. [
  184. "",
  185. f"Software simulation & integration acceptance: **{payload['software_simulation_integration_acceptance']}**",
  186. f"Ready for controlled hardware validation: **{payload['ready_for_controlled_hardware_validation']}**",
  187. f"Release candidate readiness: **{payload['release_candidate_readiness']}**",
  188. f"Production readiness: **{payload['production_readiness']}**",
  189. f"Hardware validation: **{payload['hardware_validation']}**",
  190. f"Real actuator validation: **{payload['real_actuator_validation']}**",
  191. f"Architecture direction: **{payload['architecture_direction']}**",
  192. "",
  193. ]
  194. )
  195. out_md.write_text("\n".join(lines) + "\n", encoding="utf-8")
  196. matrix = [
  197. "# Acceptance Matrix",
  198. "",
  199. f"Run ID: `{payload['run_id']}`",
  200. f"Git commit: `{payload['git_commit']}`",
  201. f"Git tree: `{payload['git_tree']}`",
  202. f"Dirty: `{payload['git_dirty_state']}`",
  203. "",
  204. "| Gate | Status |",
  205. "|---|---|",
  206. ]
  207. for k, v in (payload.get("gates") or {}).items():
  208. matrix.append(f"| `{k}` | **{v}** |")
  209. matrix.extend(
  210. [
  211. "",
  212. f"architecture_direction: **{payload['architecture_direction']}**",
  213. f"software_simulation_integration_acceptance: **{payload['software_simulation_integration_acceptance']}**",
  214. f"ready_for_controlled_hardware_validation: **{payload['ready_for_controlled_hardware_validation']}**",
  215. f"release_candidate_readiness: **{payload['release_candidate_readiness']}**",
  216. f"production_readiness: **{payload['production_readiness']}**",
  217. f"hardware_validation: **{payload['hardware_validation']}**",
  218. f"real_actuator_validation: **{payload['real_actuator_validation']}**",
  219. "",
  220. "This file is generated by `gen_run_manifest.py` / Gate Evaluator. Do not hand-edit PASS.",
  221. "",
  222. ]
  223. )
  224. (run / "ACCEPTANCE_MATRIX.md").write_text("\n".join(matrix), encoding="utf-8")
  225. (run / "acceptance-verdict.json").write_text(json.dumps(verdict, indent=2) + "\n", encoding="utf-8")
  226. print(out_json)
  227. print(out_md)
  228. return 0
  229. if __name__ == "__main__":
  230. raise SystemExit(main())