| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244 |
- #!/usr/bin/env python3
- """Build run-manifest.md/json from this-run *.meta files. Never invent Pass."""
- from __future__ import annotations
- import hashlib
- import json
- import os
- import subprocess
- from datetime import datetime, timezone
- from pathlib import Path
- def parse_meta(path: Path) -> dict[str, str]:
- out: dict[str, str] = {}
- for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
- for tok in line.replace(",", " ").split():
- if "=" not in tok:
- continue
- k, _, v = tok.partition("=")
- out[k.strip()] = v.strip()
- if line.startswith("command="):
- out["command"] = line[len("command=") :]
- return out
- def status_of(meta: dict[str, str], name: str) -> str:
- raw = (meta.get("status") or "").upper()
- if raw in {"PASS", "FAIL", "BLOCKED", "NOT RUN", "NOT_RUN"}:
- return "NOT RUN" if raw == "NOT_RUN" else raw
- if "BLOCKED" in name.upper():
- return "BLOCKED"
- if "NOT_RUN" in name.upper() or "NOT RUN" in name.upper():
- return "NOT RUN"
- if "govulncheck" in name:
- return "FAIL" if meta.get("exit", "1") not in {"0"} else "PASS"
- for key in ("exit", "pytest_exit", "python_exit", "capture_exit", "buf_lint_exit", "buf_breaking_exit"):
- if key in meta:
- try:
- if int(meta[key]) != 0:
- return "FAIL"
- except ValueError:
- return "UNKNOWN"
- if any(k in meta for k in ("exit", "pytest_exit", "python_exit", "capture_exit", "buf_lint_exit")):
- return "PASS"
- return "UNKNOWN"
- def main() -> int:
- import sys
- run = Path(os.environ.get("HTH_RUN_DIR") or (sys.argv[1] if len(sys.argv) > 1 else ""))
- if not run.is_dir():
- raise SystemExit(f"missing run dir {run}")
- rows = []
- for meta_path in sorted(run.glob("*.meta")):
- meta = parse_meta(meta_path)
- name = meta_path.name[: -len(".meta")]
- log = run / f"{name}.log"
- sha = meta.get("log_sha256", "")
- if not sha and log.is_file():
- import hashlib
- sha = hashlib.sha256(log.read_bytes()).hexdigest()
- cmd = meta.get("command") or name
- st = status_of(meta, name)
- reason = ""
- reason_sha = ""
- if st == "NOT RUN":
- reason = (meta.get("reason") or cmd or "not executed this run").strip()
- import hashlib
- reason_sha = hashlib.sha256(reason.encode("utf-8")).hexdigest()
- rows.append(
- {
- "name": name,
- "command": cmd,
- "status": st,
- "exit": meta.get("exit") or meta.get("pytest_exit") or "",
- "start_utc": meta.get("start_utc", ""),
- "end_utc": meta.get("end_utc", ""),
- "duration_s": meta.get("duration_s", ""),
- "cwd": meta.get("cwd", ""),
- "commit": meta.get("commit", ""),
- "tree": meta.get("tree", ""),
- "dirty": meta.get("dirty", ""),
- "log": f"{name}.log" if log.is_file() else "",
- "log_sha256": sha,
- "not_run_reason": reason,
- "not_run_reason_sha256": reason_sha,
- "required_for_stage": meta.get("required_for_stage", ""),
- "recorded_utc": meta.get("end_utc") or meta.get("start_utc", ""),
- }
- )
- # honor explicit NOT RUN / BLOCKED text files
- for p in sorted(run.iterdir()):
- if p.suffix == ".txt" and ("NOT_RUN" in p.name or "NOT RUN" in p.read_text(encoding="utf-8", errors="replace")[:200]):
- reason = p.read_text(encoding="utf-8", errors="replace").strip()
- reason_sha = hashlib.sha256(reason.encode("utf-8")).hexdigest()
- rows.append(
- {
- "name": p.stem,
- "command": reason.splitlines()[0][:200] if reason else p.name,
- "status": "NOT RUN",
- "exit": "",
- "start_utc": "",
- "end_utc": "",
- "log": p.name,
- "log_sha256": "",
- "not_run_reason": reason,
- "not_run_reason_sha256": reason_sha,
- "required_for_stage": "release_candidate",
- "recorded_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
- "commit": os.environ.get("HTH_GIT_COMMIT", ""),
- "tree": os.environ.get("HTH_GIT_TREE", ""),
- }
- )
- nspawn = run / "systemd-nspawn-vm.log"
- if nspawn.is_file():
- txt = nspawn.read_text(encoding="utf-8", errors="replace")
- if "BLOCKED" in txt:
- rows.append(
- {
- "name": "systemd-nspawn-vm",
- "command": "systemd-nspawn Debian VM host safety matrix",
- "status": "BLOCKED",
- "exit": "2",
- "start_utc": "",
- "end_utc": "",
- "log": nspawn.name,
- "log_sha256": "",
- }
- )
- git_root = Path(os.environ.get("HTH_GIT_ROOT") or Path(__file__).resolve().parents[2])
- commit = os.environ.get("HTH_GIT_COMMIT", "")
- tree = os.environ.get("HTH_GIT_TREE", "")
- dirty = os.environ.get("HTH_GIT_DIRTY", "")
- if not commit:
- try:
- commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=git_root, text=True).strip()
- except (subprocess.CalledProcessError, FileNotFoundError):
- commit = "unknown"
- if not tree:
- try:
- tree = subprocess.check_output(["git", "rev-parse", "HEAD^{tree}"], cwd=git_root, text=True).strip()
- except (subprocess.CalledProcessError, FileNotFoundError):
- tree = "unknown"
- if not dirty:
- try:
- scope = os.environ.get("HTH_GIT_SCOPE", "host")
- args = ["git", "status", "--porcelain"]
- if scope == "host":
- args.extend(["--", "host"])
- st = subprocess.check_output(args, cwd=git_root, text=True)
- dirty = "dirty" if st.strip() else "clean"
- except (subprocess.CalledProcessError, FileNotFoundError):
- dirty = "unknown"
- sys.path.insert(0, str(Path(__file__).resolve().parent))
- from evaluate_gates import evaluate
- verdict = evaluate(rows, expect_commit=commit, expect_tree=tree)
- payload = {
- "run_id": os.environ.get("HTH_RUN_ID", run.name),
- "git_commit": commit,
- "git_tree": tree,
- "git_dirty": dirty != "clean",
- "git_dirty_state": dirty,
- "generated_utc": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
- "commands": rows,
- "software_safety_acceptance": verdict["software_safety_acceptance"],
- "software_simulation_integration_acceptance": verdict["software_simulation_integration_acceptance"],
- "hardware_validation": verdict["hardware_validation"],
- "real_actuator_validation": verdict["real_actuator_validation"],
- "architecture_direction": verdict["architecture_direction"],
- "ready_for_controlled_hardware_validation": verdict["ready_for_controlled_hardware_validation"],
- "release_candidate_readiness": verdict["release_candidate_readiness"],
- "production_readiness": verdict["production_readiness"],
- "gates": verdict["gates"],
- }
- out_json = run / "run-manifest.json"
- out_md = run / "run-manifest.md"
- out_json.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
- lines = [
- f"# Run manifest {payload['run_id']}",
- "",
- f"Generated {payload['generated_utc']}",
- "",
- "| Name | Command | Status | SHA-256 |",
- "|---|---|---|---|",
- ]
- for r in rows:
- cmd = r["command"].replace("|", "\\|")[:120]
- lines.append(f"| `{r['name']}` | `{cmd}` | {r['status']} | `{r['log_sha256']}` |")
- lines.extend(
- [
- "",
- f"Software simulation & integration acceptance: **{payload['software_simulation_integration_acceptance']}**",
- f"Ready for controlled hardware validation: **{payload['ready_for_controlled_hardware_validation']}**",
- f"Release candidate readiness: **{payload['release_candidate_readiness']}**",
- f"Production readiness: **{payload['production_readiness']}**",
- f"Hardware validation: **{payload['hardware_validation']}**",
- f"Real actuator validation: **{payload['real_actuator_validation']}**",
- f"Architecture direction: **{payload['architecture_direction']}**",
- "",
- ]
- )
- out_md.write_text("\n".join(lines) + "\n", encoding="utf-8")
- matrix = [
- "# Acceptance Matrix",
- "",
- f"Run ID: `{payload['run_id']}`",
- f"Git commit: `{payload['git_commit']}`",
- f"Git tree: `{payload['git_tree']}`",
- f"Dirty: `{payload['git_dirty_state']}`",
- "",
- "| Gate | Status |",
- "|---|---|",
- ]
- for k, v in (payload.get("gates") or {}).items():
- matrix.append(f"| `{k}` | **{v}** |")
- matrix.extend(
- [
- "",
- f"architecture_direction: **{payload['architecture_direction']}**",
- f"software_simulation_integration_acceptance: **{payload['software_simulation_integration_acceptance']}**",
- f"ready_for_controlled_hardware_validation: **{payload['ready_for_controlled_hardware_validation']}**",
- f"release_candidate_readiness: **{payload['release_candidate_readiness']}**",
- f"production_readiness: **{payload['production_readiness']}**",
- f"hardware_validation: **{payload['hardware_validation']}**",
- f"real_actuator_validation: **{payload['real_actuator_validation']}**",
- "",
- "This file is generated by `gen_run_manifest.py` / Gate Evaluator. Do not hand-edit PASS.",
- "",
- ]
- )
- (run / "ACCEPTANCE_MATRIX.md").write_text("\n".join(matrix), encoding="utf-8")
- (run / "acceptance-verdict.json").write_text(json.dumps(verdict, indent=2) + "\n", encoding="utf-8")
- print(out_json)
- print(out_md)
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|