"""BlueMorpho — the monitoring layer. One rule governs measurement here: **nothing is reported that was not observed.** Every seat appends an event when it acts, and the Monitor is the only writer of the ledger. The ledger is append-only, so no seat can rewrite its own history, and every number in a report is derivable from a line on disk. from blue_morpho.monitor import Monitor mon = Monitor() mon.record("the-beam-answers-back", "author", "Story", "consulted", engine="Qwen3-VL-8B", artifact="beats[0:4]", inputs_hash=..., duration_s=41.2) python -m blue_morpho.monitor report """ from __future__ import annotations import argparse import json import shutil import subprocess import time from dataclasses import asdict, dataclass, field from pathlib import Path HOUSE = "BlueMorpho" ROOT = Path(__file__).resolve().parents[1] LEDGER = ROOT / "ledger" / "events.jsonl" HF_HUB = Path.home() / ".cache" / "huggingface" / "hub" # The gates a film must clear, in order. A film is not released until every one has passed. GATES = { "G0": ("Greenlight", "Executive Producer accepts the premise as shootable"), "G1": ("Hook", "the eyes score the hook frame at or above the House threshold"), "G2": ("Continuity", "no shot contradicts the cast, set, or wardrobe sheets"), "G3": ("Licence", "every engine used is clear for monetized release"), "G4": ("Technical QC", "loudness, aspect, duration and captions all in spec"), } HOUSE_HOOK_THRESHOLD = 7.0 TECH_SPEC = {"lufs": -14.0, "aspect": "9:16", "max_seconds": 60.0} @dataclass class Event: """One thing one seat did, at one moment, with one engine.""" production: str seat: str department: str action: str # greenlight|consulted|rendered|scored|gated|released|installed|failed artifact: str = "" engine: str = "" model_rev: str = "" seed: int | None = None inputs_hash: str = "" duration_s: float | None = None vram_peak_mb: int | None = None score: float | None = None gate: str = "" result: str = "" note: str = "" ts: float = field(default_factory=time.time) class Monitor: """Append events, then ask it what actually happened.""" def __init__(self, ledger: Path | str = LEDGER): self.ledger = Path(ledger) self.ledger.parent.mkdir(parents=True, exist_ok=True) # -- writing --------------------------------------------------------------------------- def record(self, production: str, seat: str, department: str, action: str, **fields) -> Event: """Append one event. Returns it so the caller can display what was written.""" event = Event(production=production, seat=seat, department=department, action=action, **fields) with self.ledger.open("a") as handle: handle.write(json.dumps(asdict(event)) + "\n") return event # -- reading --------------------------------------------------------------------------- def events(self, production: str | None = None) -> list[dict]: """Every event on disk, oldest first, optionally for one production.""" if not self.ledger.exists(): return [] rows = [] for line in self.ledger.read_text().splitlines(): if not line.strip(): continue try: row = json.loads(line) except json.JSONDecodeError: continue # a torn line is dropped, never guessed at if production is None or row.get("production") == production: rows.append(row) return rows def productions(self) -> list[str]: return sorted({row["production"] for row in self.events()}) def rollup(self) -> dict: """Per-seat activity: what each seat did, how often, and how long it took.""" table: dict[str, dict] = {} for row in self.events(): seat = table.setdefault( row["seat"], {"department": row.get("department", ""), "acts": 0, "failures": 0, "seconds": 0.0, "engines": set(), "last": 0.0, "scores": []}, ) seat["acts"] += 1 seat["failures"] += int(row.get("result") == "fail") seat["seconds"] += row.get("duration_s") or 0.0 if row.get("engine"): seat["engines"].add(row["engine"]) if row.get("score") is not None: seat["scores"].append(row["score"]) seat["last"] = max(seat["last"], row.get("ts") or 0.0) for seat in table.values(): seat["engines"] = sorted(seat["engines"]) seat["mean_score"] = round(sum(seat["scores"]) / len(seat["scores"]), 2) if seat["scores"] else None seat.pop("scores") return table def gates(self, production: str) -> dict[str, dict]: """Which gates have passed, from the gated events alone. Silence is never a pass.""" found = {row.get("gate"): row for row in self.events(production) if row.get("action") == "gated"} state = {} for key, (name, means) in GATES.items(): row = found.get(key) state[key] = { "name": name, "means": means, "result": (row or {}).get("result", "not run"), "by": (row or {}).get("seat", ""), "note": (row or {}).get("note", ""), } return state def hook_series(self, production: str) -> list[tuple[str, float]]: """Every hook score this film has been given, in order: the film's actual progress.""" return [(row.get("artifact", ""), row["score"]) for row in self.events(production) if row.get("action") == "scored" and row.get("score") is not None] # -- the box --------------------------------------------------------------------------- def health(self) -> dict: """The state of the machine the house stands on.""" def sh(cmd: str) -> str: try: return subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=15).stdout.strip() except Exception: return "" gpu = sh("nvidia-smi --query-gpu=memory.used,memory.total,utilization.gpu --format=csv,noheader,nounits") used = total = util = None if gpu: try: used, total, util = (float(v) for v in gpu.split(",")[:3]) except ValueError: pass disk = shutil.disk_usage(ROOT) disk_free_tb = disk.free / 1e12 disk_note = "" if disk_free_tb > 1e6: # overlayfs reports a synthetic, meaningless capacity disk_free_tb = None disk_note = "overlayfs reports a synthetic size; read the host volume for real capacity" return { "gpu_mem_used_mb": used, "gpu_mem_total_mb": total, "gpu_util_pct": util, "gpu_free_gb": round((total - used) / 1024, 1) if used is not None else None, "disk_free_tb": round(disk_free_tb, 2) if disk_free_tb else None, "disk_note": disk_note, "hf_cache_gb": round(sum(f.stat().st_size for f in HF_HUB.rglob("*") if f.is_file()) / 1e9, 1) if HF_HUB.exists() else None, "ledger_events": len(self.events()), } # -- the report ------------------------------------------------------------------------ def report(self, production: str | None = None) -> str: lines = [f"{HOUSE} — monitor", "=" * 68] health = self.health() lines.append( "box: GPU {gpu_mem_used_mb}/{gpu_mem_total_mb} MB used ({gpu_free_gb} GB free) · " "disk {disk_display} · HF cache {hf_cache_gb} GB · {ledger_events} events".format( disk_display=( f"{health['disk_free_tb']} TB free" if health["disk_free_tb"] else "capacity unmeasurable" ), **health) ) for slug in ([production] if production else self.productions()): lines += ["", f"# {slug}"] lines.append(" gates: " + " ".join( f"{k}:{v['result']}" for k, v in self.gates(slug).items())) series = self.hook_series(slug) if series: best = max(s for _, s in series) lines.append(f" hook scores: {series} (best {best}, threshold {HOUSE_HOOK_THRESHOLD})") lines += ["", "seat activity:"] for seat, row in sorted(self.rollup().items(), key=lambda kv: -kv[1]["acts"]): lines.append(f" {seat:<26} {row['department']:<12} {row['acts']:>3} acts" f" {row['seconds']:>7.1f}s fails={row['failures']}" f" engines={','.join(row['engines']) or '-'}") return "\n".join(lines) def main(argv: Iterable[str] | None = None) -> int: parser = argparse.ArgumentParser(prog="blue_morpho.monitor", description=f"{HOUSE} monitoring") parser.add_argument("command", choices=["report", "gates", "rollup", "health"], nargs="?", default="report") parser.add_argument("production", nargs="?", default=None) args = parser.parse_args(list(argv) if argv is not None else None) mon = Monitor() if args.command == "report": print(mon.report(args.production)) elif args.command == "health": print(json.dumps(mon.health(), indent=2)) elif args.command == "rollup": print(json.dumps(mon.rollup(), indent=2)) else: print(json.dumps(mon.gates(args.production or ""), indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())