| |
| """Generate a canonical metrics payload for the WebX dashboard. |
| |
| Design goals: |
| - No hidden magic: deterministic, explicit inputs. |
| - Works with either a 'receipt' JSON (OME‑1 style) or a generic metrics JSON. |
| - Emits a single canonical JSON with timestamps and minimal provenance. |
| |
| This file is intentionally dependency‑free (stdlib only). |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import sys |
| from dataclasses import dataclass |
| from datetime import datetime, timezone |
| from pathlib import Path |
| from typing import Any, Dict, Optional |
|
|
|
|
| ISO_FMT = "%Y-%m-%dT%H:%M:%SZ" |
|
|
|
|
| def now_utc_iso() -> str: |
| return datetime.now(timezone.utc).strftime(ISO_FMT) |
|
|
|
|
| def read_json(path: Path) -> Dict[str, Any]: |
| try: |
| return json.loads(path.read_text(encoding="utf-8")) |
| except Exception as e: |
| raise SystemExit(f"Failed to read JSON from {path}: {e}") |
|
|
|
|
| def pick(d: Dict[str, Any], keys: list[str]) -> Optional[Any]: |
| for k in keys: |
| if k in d: |
| return d[k] |
| return None |
|
|
|
|
| def coerce_float(x: Any, field: str) -> float: |
| try: |
| return float(x) |
| except Exception: |
| raise SystemExit(f"Field '{field}' must be numeric; got: {x!r}") |
|
|
|
|
| @dataclass |
| class Provenance: |
| source_repo: str |
| source_commit: str |
| updated_at: str |
|
|
|
|
| def build_from_generic(metrics: Dict[str, Any], prov: Provenance) -> Dict[str, Any]: |
| |
| omega = pick(metrics, ["omega", "Ω", "Omega", "OMEGA"]) |
| psi = pick(metrics, ["psi", "Ψ", "Psi", "PSI"]) |
| theta = pick(metrics, ["theta", "Θ", "Theta", "THETA"]) |
| cvar = pick(metrics, ["cvar", "CVaR", "CVAR"]) |
|
|
| if omega is None or psi is None or theta is None or cvar is None: |
| missing = [ |
| name |
| for name, val in [("omega", omega), ("psi", psi), ("theta", theta), ("cvar", cvar)] |
| if val is None |
| ] |
| raise SystemExit( |
| "Missing required metric fields in --in JSON: " + ", ".join(missing) |
| ) |
|
|
| payload = { |
| "schema": "matverse.webx.metrics.v1", |
| "updated_at": prov.updated_at, |
| "source": {"repo": prov.source_repo, "commit": prov.source_commit}, |
| "metrics": { |
| "omega": coerce_float(omega, "omega"), |
| "psi": coerce_float(psi, "psi"), |
| "theta": coerce_float(theta, "theta"), |
| "cvar": coerce_float(cvar, "cvar"), |
| }, |
| } |
|
|
| |
| extras = {} |
| for k in ["ccr", "CCR", "viability", "antifragility", "epsilon", "energy", "tau", "delta_i"]: |
| if k in metrics: |
| extras[k.lower()] = metrics[k] |
| if extras: |
| payload["metrics"].update(extras) |
|
|
| return payload |
|
|
|
|
| def build_from_receipt(receipt: Dict[str, Any], prov: Provenance) -> Dict[str, Any]: |
| |
| |
| omega = pick(receipt, ["omega", "Ω"]) |
| psi = pick(receipt, ["psi", "Ψ"]) |
| theta = pick(receipt, ["theta", "Θ"]) |
| cvar = pick(receipt, ["cvar", "CVaR"]) |
|
|
| |
| if isinstance(receipt.get("metrics"), dict): |
| m = receipt["metrics"] |
| omega = omega if omega is not None else pick(m, ["omega", "Ω"]) |
| psi = psi if psi is not None else pick(m, ["psi", "Ψ"]) |
| theta = theta if theta is not None else pick(m, ["theta", "Θ"]) |
| cvar = cvar if cvar is not None else pick(m, ["cvar", "CVaR"]) |
|
|
| if omega is None or psi is None or theta is None or cvar is None: |
| raise SystemExit( |
| "Receipt does not expose omega/psi/theta/cvar (directly or under 'metrics')." |
| ) |
|
|
| merkle_root = pick(receipt, ["merkle_root", "merkle", "root"]) |
| ledger_path = pick(receipt, ["ledger", "ledger_path", "rb_ledger"]) |
| ohash = pick(receipt, ["ohash", "OHASH"]) |
|
|
| payload = { |
| "schema": "matverse.webx.metrics.v1", |
| "updated_at": prov.updated_at, |
| "source": {"repo": prov.source_repo, "commit": prov.source_commit}, |
| "artifacts": { |
| "receipt": "receipt.json", |
| "merkle_root": merkle_root, |
| "ledger": ledger_path, |
| "ohash": ohash, |
| }, |
| "metrics": { |
| "omega": coerce_float(omega, "omega"), |
| "psi": coerce_float(psi, "psi"), |
| "theta": coerce_float(theta, "theta"), |
| "cvar": coerce_float(cvar, "cvar"), |
| }, |
| } |
|
|
| return payload |
|
|
|
|
| def main() -> int: |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--in", dest="in_path", help="Generic metrics JSON input") |
| ap.add_argument("--receipt", help="Receipt JSON input (OME‑1 style)") |
| ap.add_argument("--out", required=True, help="Output metrics.json") |
| ap.add_argument("--source-repo", default="matverse-acoa/core") |
| ap.add_argument("--source-commit", default="unknown") |
| ap.add_argument("--updated-at", default=None) |
|
|
| args = ap.parse_args() |
|
|
| if not args.in_path and not args.receipt: |
| raise SystemExit("Provide either --in <json> or --receipt <json>.") |
| if args.in_path and args.receipt: |
| raise SystemExit("Provide only one: --in or --receipt.") |
|
|
| updated_at = args.updated_at or now_utc_iso() |
| prov = Provenance(args.source_repo, args.source_commit, updated_at) |
|
|
| if args.in_path: |
| data = read_json(Path(args.in_path)) |
| payload = build_from_generic(data, prov) |
| else: |
| receipt = read_json(Path(args.receipt)) |
| payload = build_from_receipt(receipt, prov) |
|
|
| out_path = Path(args.out) |
| out_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") |
|
|
| print(f"Wrote {out_path} ({payload['schema']})") |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|