File size: 5,810 Bytes
d5b79ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#!/usr/bin/env python3
"""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]:
    # Accept multiple key spellings.
    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"),
        },
    }

    # Optional extras preserved if present.
    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]:
    # Receipt formats vary; we support common patterns.
    # Try direct fields first.
    omega = pick(receipt, ["omega", "Ω"]) 
    psi = pick(receipt, ["psi", "Ψ"]) 
    theta = pick(receipt, ["theta", "Θ"]) 
    cvar = pick(receipt, ["cvar", "CVaR"]) 

    # Or nested in a 'metrics' object.
    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())