gen_run_manifest.py 9.1 KB

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