betterwithage commited on
Commit
19e015f
·
verified ·
1 Parent(s): a13444d

chore(sync): mirror backend .py + Dockerfile to Space (hf-sync-backend)

Browse files

Automated backend sync from szl-holdings/a11oy main via hf-sync-backend.
Updated (differed from the Space): szl3d_holographic.py, szl_anatomy_loop.py
Deleted (gone from the repo + Dockerfile COPY set): (none)

Keeps the Space-built backend (serve.py + the Dockerfile-COPY'd .py
modules) identical to GitHub main so the Space never rebuilds from a
stale backend, new endpoints don't 404 there, and orphaned modules
removed from the repo don't linger in the Space tree.

Files changed (2) hide show
  1. szl3d_holographic.py +0 -3
  2. szl_anatomy_loop.py +630 -1
szl3d_holographic.py CHANGED
@@ -83,9 +83,6 @@ SURFACES: List[Dict[str, str]] = [
83
  {"id": "router", "title": "Router", "owner": "Dev7"},
84
  {"id": "anatomy", "title": "Anatomy", "owner": "Dev8"},
85
  {"id": "estate", "title": "Estate", "owner": "Dev9"},
86
- {"id": "muon", "title": "Muon Orthogonalized-Momentum Optimizer", "owner": "Wave13"},
87
- {"id": "specexec", "title": "Tree Speculative Execution", "owner": "Wave13"},
88
- {"id": "nvfp4", "title": "NVFP4 4-bit Training Format", "owner": "Wave13"},
89
  ]
90
 
91
  # Content-type by extension (the only extensions we serve from the 3d tree).
 
83
  {"id": "router", "title": "Router", "owner": "Dev7"},
84
  {"id": "anatomy", "title": "Anatomy", "owner": "Dev8"},
85
  {"id": "estate", "title": "Estate", "owner": "Dev9"},
 
 
 
86
  ]
87
 
88
  # Content-type by extension (the only extensions we serve from the 3d tree).
szl_anatomy_loop.py CHANGED
@@ -124,6 +124,35 @@ DOCTRINE = "v11"
124
  SAMPLE_LABEL = "sample" # default — off-box, no real power meter wired
125
  MEASURED_LABEL = "measured" # ONLY when a real metered source is present
126
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  # Physics floors/ceilings for a bounded WORK credit (NOT free energy):
128
  # Bekenstein software bound : a window of N bytes carries at most N*8 bits.
129
  # Landauer minimum : erasing one bit costs at least kT ln 2 joules.
@@ -347,12 +376,15 @@ def _read_intake() -> dict:
347
  # grid price is only carried through if the live feed actually supplied one;
348
  # absence -> None (never a fabricated figure).
349
  grid_price = raw.get("grid_price_eur_mwh", None)
 
350
  return {
351
  "ok": bool(raw.get("ok", False)),
352
  "posture": raw.get("posture", "unknown"),
353
  "degraded": False, # a live posture was actually reached
354
  "gpu_state": raw.get("gpu_state", "awake"), # node posture, passed through if reported
355
  "grid_price_eur_mwh": grid_price,
 
 
356
  "wasted_energy_available": bool(raw.get("wasted_energy_available", False)),
357
  "joules_label": joules_label,
358
  "joules_evidence": joules_evidence, # self-verifying: present iff measured
@@ -361,6 +393,37 @@ def _read_intake() -> dict:
361
  }
362
 
363
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
364
  # ---------------------------------------------------------------------------
365
  # SAMAY (lungs/soak) -> KALLPA (metabolize to bounded work_credits).
366
  # ---------------------------------------------------------------------------
@@ -525,6 +588,156 @@ def _ayni_balance(intake_credits: int, output_credits: int, stored_credits: int,
525
  }
526
 
527
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
528
  # ---------------------------------------------------------------------------
529
  # The loop: run ONE circulation cycle and return its live state. Crash-proof.
530
  # ---------------------------------------------------------------------------
@@ -539,7 +752,15 @@ def run_loop(ns: str = "a11oy") -> dict:
539
  soak = _samay_soak(intake)
540
  metab = _kallpa_metabolize(soak)
541
  beat = _heart_beat(metab)
542
- flowing = bool(soak.get("soaked", False))
 
 
 
 
 
 
 
 
543
  organs = _yarqa_disperse(beat, flowing)
544
 
545
  credits = int(metab.get("work_credits", 0))
@@ -579,13 +800,32 @@ def run_loop(ns: str = "a11oy") -> dict:
579
  "joules_label": intake.get("joules_label", SAMPLE_LABEL),
580
  "joules_evidence": intake.get("joules_evidence", {}),
581
  },
 
 
 
 
 
 
 
 
 
 
 
582
  "organs": organs,
583
  "beats_last_cycle": int(beats_last_cycle),
584
  "reservoir": {
585
  "work_credits": reservoir.get("work_credits", 0),
586
  "joules_label": SAMPLE_LABEL,
587
  "stored": bool(reservoir.get("stored", False)),
 
 
 
 
 
 
 
588
  },
 
589
  "last_receipt_id": prov.get("last_receipt_id", ""),
590
  "ayni": {
591
  "balanced": bool(ayni.get("balanced", False)),
@@ -639,6 +879,390 @@ def run_loop(ns: str = "a11oy") -> dict:
639
  }
640
 
641
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
642
  # ---------------------------------------------------------------------------
643
  # HTTP handler + registration (matches szl_energy_provenance / szl_heart_blood).
644
  # ---------------------------------------------------------------------------
@@ -660,8 +1284,13 @@ def register(app, ns="a11oy"):
660
  from starlette.responses import JSONResponse
661
  return JSONResponse(run_loop(ns=ns))
662
 
 
 
 
 
663
  handlers = [
664
  (f"{base}/loop", _loop_handler),
 
665
  ]
666
  add_api_route = getattr(app, "add_api_route", None)
667
  for path, fn in handlers:
 
124
  SAMPLE_LABEL = "sample" # default — off-box, no real power meter wired
125
  MEASURED_LABEL = "measured" # ONLY when a real metered source is present
126
 
127
+ # VERBATIM honesty vocabulary (doctrine v11) for the reservoir energy + the 8
128
+ # software systems. These MUST match szl_frontier_manifest / szl_energy_live exactly
129
+ # so no reader ever sees a novel/soft label. Never upgraded; a dead source is
130
+ # UNAVAILABLE, never faked.
131
+ LABEL_MEASURED = "MEASURED"
132
+ LABEL_SAMPLE = "SAMPLE"
133
+ LABEL_MODELED = "MODELED"
134
+ LABEL_UNAVAILABLE = "UNAVAILABLE"
135
+
136
+ # Health bands per system — always a LABEL string (never colour-only).
137
+ BAND_HEALTHY = "healthy"
138
+ BAND_DEGRADED = "degraded"
139
+ BAND_DOWN = "down"
140
+ BAND_UNAVAILABLE = "unavailable"
141
+
142
+ # A 20 s TTL cache for the assembled living state + the live merged-meter reservoir
143
+ # reading. SAME TTLCache class the intake probe already uses (szl_backend_hardening),
144
+ # so the vitals endpoint is a handful of cache reads, never a per-request fan-out to
145
+ # 52 organ endpoints. Guarded: absent helper -> compute fresh every call (honest).
146
+ try: # pragma: no cover - exercised via the offline tests with the helper present
147
+ from szl_backend_hardening import TTLCache as _TTLCache2
148
+ _VITALS_CACHE = _TTLCache2(ttl=20.0)
149
+ except Exception: # pragma: no cover - defensive
150
+ _VITALS_CACHE = None
151
+
152
+ # Last-seen signed joule-ledger totals, so the circulation loop can be driven by
153
+ # REAL measured-billable joule DELTAS between cycles (never a fabricated flow).
154
+ _LAST_LEDGER = {"joules": None, "jobs": None}
155
+
156
  # Physics floors/ceilings for a bounded WORK credit (NOT free energy):
157
  # Bekenstein software bound : a window of N bytes carries at most N*8 bits.
158
  # Landauer minimum : erasing one bit costs at least kT ln 2 joules.
 
376
  # grid price is only carried through if the live feed actually supplied one;
377
  # absence -> None (never a fabricated figure).
378
  grid_price = raw.get("grid_price_eur_mwh", None)
379
+ grid = _extract_grid_intake(raw)
380
  return {
381
  "ok": bool(raw.get("ok", False)),
382
  "posture": raw.get("posture", "unknown"),
383
  "degraded": False, # a live posture was actually reached
384
  "gpu_state": raw.get("gpu_state", "awake"), # node posture, passed through if reported
385
  "grid_price_eur_mwh": grid_price,
386
+ "negative_price": grid["negative_price"], # MEASURED public-feed posture
387
+ "renewable_pct": grid["renewable_pct"], # MEASURED share of load, else None
388
  "wasted_energy_available": bool(raw.get("wasted_energy_available", False)),
389
  "joules_label": joules_label,
390
  "joules_evidence": joules_evidence, # self-verifying: present iff measured
 
393
  }
394
 
395
 
396
+ def _extract_grid_intake(raw: dict) -> dict:
397
+ """Pull the live grid harvest posture (metabolic INTAKE rate) out of the posture
398
+ payload we ALREADY fetched — we do NOT re-implement or re-scrape the feed.
399
+
400
+ Returns {negative_price, renewable_pct}. negative_price is the MEASURED
401
+ public-feed posture (aWATTar negative-price / curtailed window). renewable_pct is
402
+ scanned best-effort out of the per-feed readings (Energy-Charts renewable share of
403
+ load); absent/unparseable -> None (never fabricated)."""
404
+ posture = str(raw.get("posture", "") or "").lower()
405
+ negative_price = bool(
406
+ raw.get("wasted_energy_available", False)
407
+ or "negative" in posture
408
+ or bool(raw.get("soak_hard", False))
409
+ )
410
+ renewable_pct = None
411
+ for reading in (raw.get("readings") or []):
412
+ if not isinstance(reading, dict):
413
+ continue
414
+ name = " ".join(str(reading.get(k, "")) for k in ("name", "feed", "source")).lower()
415
+ if "renewable" not in name and "share" not in name:
416
+ continue
417
+ for vk in ("value", "share", "measured_value", "pct", "percent"):
418
+ v = reading.get(vk)
419
+ if isinstance(v, (int, float)):
420
+ renewable_pct = round(float(v), 3)
421
+ break
422
+ if renewable_pct is not None:
423
+ break
424
+ return {"negative_price": negative_price, "renewable_pct": renewable_pct}
425
+
426
+
427
  # ---------------------------------------------------------------------------
428
  # SAMAY (lungs/soak) -> KALLPA (metabolize to bounded work_credits).
429
  # ---------------------------------------------------------------------------
 
588
  }
589
 
590
 
591
+ # ---------------------------------------------------------------------------
592
+ # LAYER 1 — make the metabolism CIRCULATE. Feed MEASURED joules into the
593
+ # reservoir, the live grid posture as the intake rate, and drive the loop from
594
+ # signed joule-ledger DELTAS. We REUSE the already-shipped accessors; we never
595
+ # re-scrape a meter and never fabricate a joule.
596
+ # ---------------------------------------------------------------------------
597
+ def _ledger_snapshot() -> dict:
598
+ """Cheap, in-process read of the signed joule-ledger totals + chain status.
599
+
600
+ Reuses szl_energy_ledger (a local hash-linked receipt chain — NO network). Its
601
+ joules_measured_billable is the sum of REAL NVML deltas (measured-billable).
602
+ Guarded: a missing/broken ledger degrades to available:false, never a fabricated
603
+ total."""
604
+ try:
605
+ import szl_energy_ledger as L
606
+ led = L.get_ledger()
607
+ totals = led.totals()
608
+ chain = led.verify()
609
+ return {
610
+ "available": True,
611
+ "jobs": totals.get("jobs"),
612
+ "joules": totals.get("joules_measured_billable"),
613
+ "kwh_total": totals.get("kwh_total"),
614
+ "chain_ok": bool(chain.get("ok")),
615
+ }
616
+ except Exception as exc: # noqa: BLE001 — honest degrade
617
+ return {"available": False, "reason": type(exc).__name__}
618
+
619
+
620
+ def _probe_merged_meter_joules():
621
+ """Live MEASURED joule total from the MERGED multi-meter scrape (both GPU meters).
622
+
623
+ Reuses szl_energy_live._merged_engine_readings() -> szl_energy_operator
624
+ ._fetch_joule_meter() (reads A11OY_JOULE_METER_URLS). Hard-bounded by the shipped
625
+ short-timeout probe so it can never hang the loop; returns None when no meter is
626
+ reachable (the reservoir then degrades honestly, never fabricates)."""
627
+ def _do():
628
+ import szl_energy_live as el
629
+ engines = el._merged_engine_readings() or {}
630
+ vals = [v.get("joules") for v in engines.values()
631
+ if isinstance(v.get("joules"), (int, float))]
632
+ if not vals:
633
+ return None
634
+ total = round(sum(vals), 6)
635
+ if total <= 0:
636
+ return None
637
+ ts = _now()
638
+ return {
639
+ "joules": total,
640
+ "label": f"{LABEL_MEASURED}-as-of-{ts}",
641
+ "as_of": ts,
642
+ "source": "merged joule meter (A11OY_JOULE_METER_URLS: both GPU NVML exporters)",
643
+ "engines": {k: v.get("joules") for k, v in engines.items()},
644
+ }
645
+ try:
646
+ if _probe_with_timeout is not None:
647
+ env = _probe_with_timeout(_do, timeout=0.5)
648
+ return env.get("result") if env.get("reachable") else None
649
+ return _do()
650
+ except Exception: # noqa: BLE001
651
+ return None
652
+
653
+
654
+ def _reservoir_energy(ledger_snap: dict, intake_degraded: bool) -> dict:
655
+ """The metabolism RESERVOIR fill. Fills off-box from MEASURED joules — honestly.
656
+
657
+ Priority (doctrine v11, never fake / never zero-when-data-exists):
658
+ 1. LIVE merged-meter MEASURED joule total -> label 'MEASURED-as-of-<ts>'.
659
+ Attempted only when a live posture was reached (so the offline/degraded/
660
+ latency paths never pay a meter probe), cached 20 s.
661
+ 2. else the signed joule-ledger measured-billable total, shown honestly as
662
+ SAMPLE (a historical total, not a fresh reading).
663
+ 3. else UNAVAILABLE (value None, 'not fabricated').
664
+ """
665
+ if not intake_degraded:
666
+ cached = _VITALS_CACHE.peek(key="reservoir_measured") if _VITALS_CACHE is not None else None
667
+ if isinstance(cached, dict) and cached.get("joules") is not None:
668
+ return dict(cached)
669
+ live = _probe_merged_meter_joules()
670
+ if isinstance(live, dict) and live.get("joules") is not None:
671
+ if _VITALS_CACHE is not None:
672
+ try:
673
+ _VITALS_CACHE.get_or_compute(lambda: dict(live), key="reservoir_measured")
674
+ except Exception:
675
+ pass
676
+ return dict(live)
677
+ if (ledger_snap.get("available")
678
+ and isinstance(ledger_snap.get("jobs"), int) and ledger_snap["jobs"] > 0
679
+ and isinstance(ledger_snap.get("joules"), (int, float)) and ledger_snap["joules"] > 0):
680
+ return {
681
+ "joules": round(float(ledger_snap["joules"]), 6),
682
+ "label": LABEL_SAMPLE,
683
+ "as_of": None,
684
+ "source": "signed joule-ledger (measured-billable total, historical)",
685
+ "note": ("degraded: no fresh live-meter reading; historical signed-ledger "
686
+ "measured-billable total shown as SAMPLE, never upgraded"),
687
+ }
688
+ return {
689
+ "joules": None,
690
+ "label": LABEL_UNAVAILABLE,
691
+ "as_of": None,
692
+ "source": "no live meter and no signed-ledger total reachable",
693
+ "note": "not fabricated",
694
+ }
695
+
696
+
697
+ def _circulation(ledger_snap: dict, soaked: bool) -> dict:
698
+ """Drive the circulation from REAL signed joule-ledger DELTAS between cycles.
699
+
700
+ Off-box the ledger carries the persistent signed history (jobs + measured-billable
701
+ joules), so the loop is no longer idle: `flowing` is True when work actually moved
702
+ (a positive joule delta, or an existing signed history), or when this cycle soaked
703
+ a wasted-work window. Deltas are computed against the last-seen totals — never a
704
+ fabricated flow. label is MEASURED only when the chain verifies."""
705
+ global _LAST_LEDGER
706
+ available = bool(ledger_snap.get("available"))
707
+ jobs = ledger_snap.get("jobs")
708
+ joules = ledger_snap.get("joules")
709
+ chain_ok = bool(ledger_snap.get("chain_ok"))
710
+ delta_joules = None
711
+ delta_jobs = None
712
+ if available and isinstance(joules, (int, float)):
713
+ last_j = _LAST_LEDGER.get("joules")
714
+ if isinstance(last_j, (int, float)) and joules >= last_j:
715
+ delta_joules = round(joules - last_j, 6)
716
+ last_jobs = _LAST_LEDGER.get("jobs")
717
+ if isinstance(last_jobs, int) and isinstance(jobs, int) and jobs >= last_jobs:
718
+ delta_jobs = jobs - last_jobs
719
+ _LAST_LEDGER = {"joules": joules, "jobs": jobs}
720
+ has_history = available and isinstance(jobs, int) and jobs > 0
721
+ flowing = bool(soaked) or bool(delta_joules and delta_joules > 0) or has_history
722
+ if available and chain_ok and has_history:
723
+ label = LABEL_MEASURED
724
+ elif available:
725
+ label = LABEL_SAMPLE
726
+ else:
727
+ label = LABEL_UNAVAILABLE
728
+ return {
729
+ "flowing": flowing,
730
+ "label": label,
731
+ "ledger_jobs": jobs if available else None,
732
+ "ledger_joules_measured_billable": joules if available else None,
733
+ "chain_ok": chain_ok if available else None,
734
+ "delta_joules_since_last_cycle": delta_joules,
735
+ "delta_jobs_since_last_cycle": delta_jobs,
736
+ "note": ("circulation driven by signed joule-ledger deltas (measured-billable); "
737
+ "flowing reflects real signed history/deltas, never a fabricated flow"),
738
+ }
739
+
740
+
741
  # ---------------------------------------------------------------------------
742
  # The loop: run ONE circulation cycle and return its live state. Crash-proof.
743
  # ---------------------------------------------------------------------------
 
752
  soak = _samay_soak(intake)
753
  metab = _kallpa_metabolize(soak)
754
  beat = _heart_beat(metab)
755
+
756
+ # LAYER 1 — CIRCULATE: drive the loop from REAL signed joule-ledger deltas so
757
+ # it is no longer idle off-box, and fill the reservoir from MEASURED joules.
758
+ ledger_snap = _ledger_snapshot()
759
+ circulation = _circulation(ledger_snap, soaked=bool(soak.get("soaked", False)))
760
+ reservoir_energy = _reservoir_energy(ledger_snap, intake_degraded=bool(intake.get("degraded", False)))
761
+
762
+ # Organs flow when this cycle soaked OR when real signed work is circulating.
763
+ flowing = bool(soak.get("soaked", False)) or bool(circulation.get("flowing", False))
764
  organs = _yarqa_disperse(beat, flowing)
765
 
766
  credits = int(metab.get("work_credits", 0))
 
800
  "joules_label": intake.get("joules_label", SAMPLE_LABEL),
801
  "joules_evidence": intake.get("joules_evidence", {}),
802
  },
803
+ # LAYER 1 — the live grid harvest posture as the metabolic INTAKE RATE
804
+ # (MEASURED public feed; absent sub-fields stay None, never fabricated).
805
+ "intake_rate": {
806
+ "grid_price_eur_mwh": intake.get("grid_price_eur_mwh"),
807
+ "negative_price": bool(intake.get("negative_price", False)),
808
+ "renewable_pct": intake.get("renewable_pct"),
809
+ "posture": intake.get("posture"),
810
+ "label": (LABEL_MEASURED if (not intake.get("degraded", False)
811
+ and intake.get("grid_price_eur_mwh") is not None) else LABEL_UNAVAILABLE),
812
+ "source": "harvest/posture public grid feed (aWATTar price + Energy-Charts renewable share)",
813
+ },
814
  "organs": organs,
815
  "beats_last_cycle": int(beats_last_cycle),
816
  "reservoir": {
817
  "work_credits": reservoir.get("work_credits", 0),
818
  "joules_label": SAMPLE_LABEL,
819
  "stored": bool(reservoir.get("stored", False)),
820
+ # LAYER 1 — the reservoir FILL: last MEASURED merged-meter joule total
821
+ # (MEASURED-as-of-<ts>), degrading to the signed-ledger total (SAMPLE),
822
+ # then UNAVAILABLE. Never fabricated, never zero-when-data-exists.
823
+ "energy_joules": reservoir_energy.get("joules"),
824
+ "energy_label": reservoir_energy.get("label"),
825
+ "energy_as_of": reservoir_energy.get("as_of"),
826
+ "energy_source": reservoir_energy.get("source"),
827
  },
828
+ "circulation": circulation,
829
  "last_receipt_id": prov.get("last_receipt_id", ""),
830
  "ayni": {
831
  "balanced": bool(ayni.get("balanced", False)),
 
879
  }
880
 
881
 
882
+ # ---------------------------------------------------------------------------
883
+ # LAYER 2 — wire the organs + the 8 anatomical SYSTEMS into ONE living state.
884
+ #
885
+ # This is a MODELED physiological VIEW over real telemetry. We never claim SZL is
886
+ # literally alive; every value carries a VERBATIM honesty label and a health BAND
887
+ # (a label string, never colour-only). We REUSE the already-shipped surfaces:
888
+ # LUNGS = the 2 GPU meters (szl_energy_live.build_mesh, per-engine)
889
+ # IMMUNE = the receipt/guard organ status (szl_immune._status)
890
+ # FABRIC/ = the frontier manifest tiles (szl_frontier_manifest.build_manifest,
891
+ # GOVERN. cached 20 s — we do NOT fan out to 52 organ endpoints)
892
+ # ANATOMY = this loop's own beat
893
+ # All other organs have no live in-process probe wired -> UNAVAILABLE (honest),
894
+ # never a fabricated OK. The whole assembly is cached 20 s in _VITALS_CACHE.
895
+ # ---------------------------------------------------------------------------
896
+
897
+ # The 52 organs (szl3d_holographic.SURFACES) projected into 8 anatomical systems.
898
+ # The PROJECTION is MODELED; each organ's live vitals carry their OWN real label.
899
+ # Every organ id below appears EXACTLY once; the set is the full 52-organ surface.
900
+ _SYSTEMS = (
901
+ ("nervous", "Nervous — cognition, attention, memory, reasoning", (
902
+ "neuromorphic", "interpretability", "worldmodel", "episodic", "ssm", "genie",
903
+ "ringattn", "kvcache", "mla", "blt", "nsa", "kan", "steering", "titans", "mor",
904
+ "goat", "kla", "hrm", "aimc", "nested", "matgran", "graphmem", "elf",
905
+ )),
906
+ ("respiratory", "Respiratory — intake, decoding throughput (the LUNGS breathe here)", (
907
+ "specdecode", "dllm", "moe", "testtime", "inplacettt", "flowmatch",
908
+ )),
909
+ ("circulatory", "Circulatory — energy routing + flow", (
910
+ "energy", "router", "pfield", "s3search", "slidesparse",
911
+ )),
912
+ ("immune", "Immune — uncertainty, safety, attestation, defense", (
913
+ "qhall", "sement", "rauq", "ccattest", "counter-uas",
914
+ )),
915
+ ("skeletal", "Skeletal — formal structure, math, quantization", (
916
+ "formalmath", "qec", "ternary", "catq",
917
+ )),
918
+ ("muscular", "Muscular — orchestration, agent action", (
919
+ "agentcoh", "grpo",
920
+ )),
921
+ ("governance", "Governance — control, provenance, physical priors", (
922
+ "governance", "pinn", "frontier",
923
+ )),
924
+ ("integumentary", "Integumentary — compute fabric, estate, anatomy, PNT", (
925
+ "fabric", "estate", "anatomy", "pnt",
926
+ )),
927
+ )
928
+
929
+
930
+ def _organ_titles() -> dict:
931
+ """id -> human title from the single source of truth (szl3d_holographic.SURFACES).
932
+
933
+ Guarded: if the surface list is not importable we fall back to the id as its own
934
+ title — never fabricated, just unadorned."""
935
+ try:
936
+ import szl3d_holographic as H
937
+ return {s["id"]: s.get("title", s["id"]) for s in getattr(H, "SURFACES", [])}
938
+ except Exception: # noqa: BLE001
939
+ return {}
940
+
941
+
942
+ def _band_from(label: str, ok: bool) -> str:
943
+ """Map a VERBATIM honesty label + a liveness flag to a health BAND (a label).
944
+
945
+ Never colour-only: the band is itself an honest word. UNAVAILABLE -> unavailable;
946
+ a live measured/modeled source that is ok -> healthy; a reachable-but-degraded
947
+ source -> degraded; an explicit failure -> down."""
948
+ if label == LABEL_UNAVAILABLE:
949
+ return BAND_UNAVAILABLE
950
+ if not ok:
951
+ return BAND_DOWN
952
+ if label in (LABEL_MEASURED, LABEL_MODELED):
953
+ return BAND_HEALTHY
954
+ return BAND_DEGRADED # SAMPLE / historical -> honestly not fully healthy
955
+
956
+
957
+ def _live_vitals_index(mesh: dict, manifest: dict, immune: dict, loop_state: dict) -> dict:
958
+ """Build the id -> {label, band, live, detail} index of the organs we CAN probe.
959
+
960
+ Every entry is derived from a REAL surface read. Organs not present here have no
961
+ live probe wired and default to UNAVAILABLE in _project_systems (honest)."""
962
+ idx: dict = {}
963
+
964
+ # energy organ <- the GPU mesh (LUNGS). MEASURED only when a meter is reachable.
965
+ mesh_label = mesh.get("label") if isinstance(mesh, dict) else None
966
+ if mesh_label in (LABEL_MEASURED, LABEL_UNAVAILABLE):
967
+ live = mesh_label == LABEL_MEASURED
968
+ idx["energy"] = {
969
+ "label": mesh_label,
970
+ "band": _band_from(mesh_label, ok=live),
971
+ "live": live,
972
+ "detail": {
973
+ "total_watts": mesh.get("total_watts"),
974
+ "total_joules": mesh.get("total_joules"),
975
+ "live_count": mesh.get("live_count"),
976
+ "node_count": mesh.get("node_count"),
977
+ },
978
+ }
979
+
980
+ # fabric + governance + frontier <- the frontier manifest tiles (cached 20 s).
981
+ tiles = (manifest.get("capabilities") if isinstance(manifest, dict) else None) or []
982
+ by_cat = {}
983
+ for t in tiles:
984
+ if isinstance(t, dict):
985
+ by_cat.setdefault(t.get("category", ""), t)
986
+ fabric_t = by_cat.get("fabric")
987
+ if isinstance(fabric_t, dict):
988
+ ok = bool(fabric_t.get("ok", True))
989
+ reachable = fabric_t.get("nodes_reachable")
990
+ total = fabric_t.get("nodes_total")
991
+ band = _band_from(fabric_t.get("label", LABEL_UNAVAILABLE), ok=ok)
992
+ if (isinstance(reachable, int) and isinstance(total, int)
993
+ and total > 0 and reachable < total and band == BAND_HEALTHY):
994
+ band = BAND_DEGRADED # some nodes down -> honestly degraded
995
+ idx["fabric"] = {
996
+ "label": fabric_t.get("label", LABEL_UNAVAILABLE),
997
+ "band": band, "live": ok,
998
+ "detail": {"nodes_reachable": reachable, "nodes_total": total,
999
+ "gpu_reachable": fabric_t.get("gpu_reachable")},
1000
+ }
1001
+ gov_t = by_cat.get("governance")
1002
+ if isinstance(gov_t, dict):
1003
+ ok = bool(gov_t.get("ok", True))
1004
+ idx["governance"] = {
1005
+ "label": gov_t.get("label", LABEL_UNAVAILABLE),
1006
+ "band": _band_from(gov_t.get("label", LABEL_UNAVAILABLE), ok=ok),
1007
+ "live": ok,
1008
+ "detail": {"signed_receipts": gov_t.get("signed_receipts"),
1009
+ "lambda": gov_t.get("lambda_")},
1010
+ }
1011
+ if isinstance(manifest, dict) and manifest.get("summary"):
1012
+ summ = manifest["summary"]
1013
+ deg = summ.get("degraded_tiles") or []
1014
+ ok = len(deg) == 0
1015
+ idx["frontier"] = {
1016
+ "label": LABEL_MODELED, # the roll-up is a modeled view over real tiles
1017
+ "band": BAND_HEALTHY if ok else BAND_DEGRADED,
1018
+ "live": True,
1019
+ "detail": {"tiles": summ.get("tiles"), "degraded_tiles": deg},
1020
+ }
1021
+
1022
+ # immune organs <- the guard/receipt status. deny-by-default egress gate.
1023
+ if isinstance(immune, dict) and immune.get("ok"):
1024
+ khipu = immune.get("khipu") or {}
1025
+ chain_ok = bool(khipu.get("chain_verified"))
1026
+ vit = {
1027
+ "label": LABEL_MEASURED if chain_ok else LABEL_SAMPLE,
1028
+ "band": BAND_HEALTHY if chain_ok else BAND_DEGRADED,
1029
+ "live": True,
1030
+ "detail": {"deny_rate": immune.get("deny_rate"),
1031
+ "verdicts_this_process": immune.get("verdicts_this_process"),
1032
+ "chain_depth": khipu.get("chain_depth"),
1033
+ "chain_verified": chain_ok},
1034
+ }
1035
+ # sement/rauq/qhall are the self-check uncertainty organs the immune guard fronts.
1036
+ for oid in ("sement", "rauq", "qhall", "ccattest"):
1037
+ idx[oid] = dict(vit)
1038
+
1039
+ # anatomy organ <- this very loop's beat (self-referential, honest).
1040
+ if isinstance(loop_state, dict) and loop_state.get("ok"):
1041
+ flowing = bool(loop_state.get("beats_last_cycle"))
1042
+ idx["anatomy"] = {
1043
+ "label": LABEL_MEASURED if flowing else LABEL_SAMPLE,
1044
+ "band": BAND_HEALTHY if flowing else BAND_DEGRADED,
1045
+ "live": True,
1046
+ "detail": {"beats_last_cycle": loop_state.get("beats_last_cycle"),
1047
+ "circulation_flowing": bool((loop_state.get("circulation") or {}).get("flowing"))},
1048
+ }
1049
+ return idx
1050
+
1051
+
1052
+ def _project_systems(vitals_idx: dict, titles: dict) -> list:
1053
+ """Project the 52 organs into the 8 systems, each organ carrying an honest label.
1054
+
1055
+ An organ with a live probe carries its real vital; an organ WITHOUT one is
1056
+ UNAVAILABLE (band unavailable) — honest, never faked. The system band is the
1057
+ worst honest band among its organs (down < degraded < unavailable < healthy is
1058
+ NOT the order — we use: any down -> down; else any degraded -> degraded; else if
1059
+ every organ unavailable -> unavailable; else healthy)."""
1060
+ systems = []
1061
+ for sys_id, sys_desc, organ_ids in _SYSTEMS:
1062
+ organs = []
1063
+ for oid in organ_ids:
1064
+ v = vitals_idx.get(oid)
1065
+ if v is None:
1066
+ organs.append({
1067
+ "id": oid,
1068
+ "title": titles.get(oid, oid),
1069
+ "label": LABEL_UNAVAILABLE,
1070
+ "band": BAND_UNAVAILABLE,
1071
+ "live": False,
1072
+ "detail": {"note": "no live in-process probe wired — UNAVAILABLE, not faked"},
1073
+ })
1074
+ else:
1075
+ organs.append({
1076
+ "id": oid, "title": titles.get(oid, oid),
1077
+ "label": v["label"], "band": v["band"],
1078
+ "live": bool(v["live"]), "detail": v.get("detail", {}),
1079
+ })
1080
+ live_n = sum(1 for o in organs if o["live"])
1081
+ bands = {o["band"] for o in organs}
1082
+ if BAND_DOWN in bands:
1083
+ sys_band = BAND_DOWN
1084
+ elif BAND_DEGRADED in bands:
1085
+ sys_band = BAND_DEGRADED
1086
+ elif bands == {BAND_UNAVAILABLE}:
1087
+ sys_band = BAND_UNAVAILABLE
1088
+ else:
1089
+ sys_band = BAND_HEALTHY
1090
+ systems.append({
1091
+ "system": sys_id,
1092
+ "name": sys_desc,
1093
+ "label": LABEL_MODELED, # the organ->system PROJECTION is a modeled view
1094
+ "band": sys_band,
1095
+ "organs_total": len(organs),
1096
+ "organs_live": live_n,
1097
+ "organs": organs,
1098
+ })
1099
+ return systems
1100
+
1101
+
1102
+ def _build_lungs(mesh: dict) -> dict:
1103
+ """LUNGS = the 2 GPU meters. Breathing rate ∝ live watts, capacity ∝ joules.
1104
+
1105
+ Read straight from szl_energy_live.build_mesh per-engine (omen->tower RTX 4060 Ti,
1106
+ betterwithage->laptop RTX 5050). MEASURED only from a reachable NVML exporter;
1107
+ a null watts/joules stays UNAVAILABLE — never a fabricated breath."""
1108
+ nodes = (mesh.get("nodes") if isinstance(mesh, dict) else None) or []
1109
+ breaths = []
1110
+ for n in nodes:
1111
+ if not isinstance(n, dict):
1112
+ continue
1113
+ watts = n.get("watts")
1114
+ joules = n.get("joules")
1115
+ jl = n.get("joules_label", LABEL_UNAVAILABLE)
1116
+ breaths.append({
1117
+ "name": n.get("name"),
1118
+ "role": n.get("role"),
1119
+ "live": n.get("live"),
1120
+ "breathing_rate_watts": watts, # ∝ live power draw (MEASURED or None)
1121
+ "capacity_joules": joules, # ∝ metered joules (MEASURED or None)
1122
+ "joules_label": jl,
1123
+ "source": n.get("source"),
1124
+ })
1125
+ label = mesh.get("label", LABEL_UNAVAILABLE) if isinstance(mesh, dict) else LABEL_UNAVAILABLE
1126
+ return {
1127
+ "breaths": breaths,
1128
+ "total_watts": mesh.get("total_watts") if isinstance(mesh, dict) else None,
1129
+ "total_joules": mesh.get("total_joules") if isinstance(mesh, dict) else None,
1130
+ "label": label,
1131
+ "band": _band_from(label, ok=(label == LABEL_MEASURED)),
1132
+ "note": ("breathing rate ∝ live watts, capacity ∝ joules; MEASURED only from a "
1133
+ "reachable NVML exporter, else UNAVAILABLE — never fabricated"),
1134
+ }
1135
+
1136
+
1137
+ def _safe_mesh() -> dict:
1138
+ """szl_energy_live.build_mesh under a short hard timeout — never hang the vitals read."""
1139
+ def _do():
1140
+ import szl_energy_live as el
1141
+ return el.build_mesh()
1142
+ try:
1143
+ if _probe_with_timeout is not None:
1144
+ env = _probe_with_timeout(_do, timeout=0.8)
1145
+ res = env.get("result") if env.get("reachable") else None
1146
+ return res if isinstance(res, dict) else {"label": LABEL_UNAVAILABLE, "nodes": []}
1147
+ out = _do()
1148
+ return out if isinstance(out, dict) else {"label": LABEL_UNAVAILABLE, "nodes": []}
1149
+ except Exception: # noqa: BLE001
1150
+ return {"label": LABEL_UNAVAILABLE, "nodes": []}
1151
+
1152
+
1153
+ def _safe_manifest() -> dict:
1154
+ try:
1155
+ import szl_frontier_manifest as M
1156
+ out = M.build_manifest()
1157
+ return out if isinstance(out, dict) else {}
1158
+ except Exception: # noqa: BLE001
1159
+ return {}
1160
+
1161
+
1162
+ def _safe_immune() -> dict:
1163
+ try:
1164
+ import szl_immune as I
1165
+ out = I._status()
1166
+ return out if isinstance(out, dict) else {}
1167
+ except Exception: # noqa: BLE001
1168
+ return {}
1169
+
1170
+
1171
+ def _assemble_living_state(ns: str) -> dict:
1172
+ """Compose the ONE honest living-anatomy object (uncached inner build)."""
1173
+ loop_state = run_loop(ns=ns)
1174
+ mesh = _safe_mesh()
1175
+ manifest = _safe_manifest()
1176
+ immune = _safe_immune()
1177
+ titles = _organ_titles()
1178
+
1179
+ vitals_idx = _live_vitals_index(mesh, manifest, immune, loop_state)
1180
+ systems = _project_systems(vitals_idx, titles)
1181
+ lungs = _build_lungs(mesh)
1182
+
1183
+ organs_total = sum(s["organs_total"] for s in systems)
1184
+ organs_live = sum(s["organs_live"] for s in systems)
1185
+ band_counts: dict = {}
1186
+ for s in systems:
1187
+ band_counts[s["band"]] = band_counts.get(s["band"], 0) + 1
1188
+
1189
+ return {
1190
+ "ok": True,
1191
+ "kind": "living-anatomy-vitals",
1192
+ "ns": ns,
1193
+ "doctrine": DOCTRINE,
1194
+ "view": ("MODELED physiological projection over REAL telemetry — a body-systems "
1195
+ "VIEW; SZL is never claimed to be literally alive"),
1196
+ "metal": {
1197
+ # LUNGS = the 2 GPU meters (breathing rate ∝ watts, capacity ∝ joules).
1198
+ "lungs": lungs,
1199
+ },
1200
+ "systems": systems,
1201
+ # The metabolism (Layer 1): reservoir fill + grid intake rate + circulation.
1202
+ "metabolism": {
1203
+ "reservoir": loop_state.get("reservoir", {}),
1204
+ "intake_rate": loop_state.get("intake_rate", {}),
1205
+ "circulation": loop_state.get("circulation", {}),
1206
+ "beats_last_cycle": loop_state.get("beats_last_cycle", 0),
1207
+ "ayni": loop_state.get("ayni", {}),
1208
+ },
1209
+ "summary": {
1210
+ "systems": len(systems),
1211
+ "organs_total": organs_total,
1212
+ "organs_live": organs_live,
1213
+ "system_band_counts": band_counts,
1214
+ "labels_legend": {
1215
+ LABEL_MEASURED: "real metered/probed value",
1216
+ LABEL_MODELED: "modeled view derived from real telemetry",
1217
+ LABEL_SAMPLE: "historical/illustrative, not a fresh reading",
1218
+ LABEL_UNAVAILABLE: "no live probe reachable — honest, not faked",
1219
+ },
1220
+ "bands_legend": {
1221
+ BAND_HEALTHY: "live + labeled measured/modeled",
1222
+ BAND_DEGRADED: "reachable but partial/historical",
1223
+ BAND_DOWN: "an expected live source failed",
1224
+ BAND_UNAVAILABLE: "no live probe wired",
1225
+ },
1226
+ },
1227
+ "honesty": (
1228
+ "MODELED physiological view over real telemetry; every value carries a "
1229
+ "VERBATIM label + a health BAND (always a word, never colour-only); organs "
1230
+ "without a live probe are UNAVAILABLE (never faked); joules MEASURED only from "
1231
+ "a reachable NVML exporter; Ayni balances; Λ = Conjecture 1; locked-8 unchanged "
1232
+ "(these systems are a VIEW, not locked-8 additions); no free-energy; SZL is "
1233
+ "never claimed literally alive."
1234
+ ),
1235
+ "computed_at": _now(),
1236
+ }
1237
+
1238
+
1239
+ def build_living_state(ns: str = "a11oy") -> dict:
1240
+ """Assemble the living-anatomy vitals, cached 20 s (crash-proof, honest degrade).
1241
+
1242
+ Cached via the SAME TTLCache the intake probe uses, so a GET is a handful of cache
1243
+ reads — never a per-request fan-out to 52 organ endpoints. Any fault degrades to an
1244
+ honest, doctrine-clean response; it can NEVER raise into the app."""
1245
+ try:
1246
+ if _VITALS_CACHE is not None:
1247
+ return _VITALS_CACHE.get_or_compute(lambda: _assemble_living_state(ns),
1248
+ key=f"living_state:{ns}")
1249
+ return _assemble_living_state(ns)
1250
+ except Exception as exc: # noqa: BLE001 — never raise into the app
1251
+ return {
1252
+ "ok": False,
1253
+ "kind": "living-anatomy-vitals",
1254
+ "ns": ns,
1255
+ "doctrine": DOCTRINE,
1256
+ "view": "MODELED physiological projection over real telemetry",
1257
+ "metal": {"lungs": {"breaths": [], "label": LABEL_UNAVAILABLE, "band": BAND_UNAVAILABLE}},
1258
+ "systems": [],
1259
+ "metabolism": {},
1260
+ "summary": {"systems": 0, "organs_total": 0, "organs_live": 0},
1261
+ "honesty": f"degraded honestly ({type(exc).__name__}); UNAVAILABLE only; nothing fabricated",
1262
+ "computed_at": _now(),
1263
+ }
1264
+
1265
+
1266
  # ---------------------------------------------------------------------------
1267
  # HTTP handler + registration (matches szl_energy_provenance / szl_heart_blood).
1268
  # ---------------------------------------------------------------------------
 
1284
  from starlette.responses import JSONResponse
1285
  return JSONResponse(run_loop(ns=ns))
1286
 
1287
+ def _vitals_handler(req=None):
1288
+ from starlette.responses import JSONResponse
1289
+ return JSONResponse(build_living_state(ns=ns))
1290
+
1291
  handlers = [
1292
  (f"{base}/loop", _loop_handler),
1293
+ (f"{base}/vitals", _vitals_handler),
1294
  ]
1295
  add_api_route = getattr(app, "add_api_route", None)
1296
  for path, fn in handlers: