betterwithage commited on
Commit
7620ee7
·
verified ·
1 Parent(s): 7810d8b

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): Dockerfile, szl_fabric_surface.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. Dockerfile +11 -0
  2. szl_fabric_surface.py +537 -0
Dockerfile CHANGED
@@ -174,6 +174,17 @@ COPY szl_kverify.py ./
174
  # served page) is per-file COPY'd below and declared image_only in
175
  # .github/copy-sync-lockstep.json (same baked-only pattern as web/energy.html).
176
  COPY szl_immune.py ./
 
 
 
 
 
 
 
 
 
 
 
177
  # SWEEP DEV 3 status module — imported by serve.py (guarded). MUST be per-file
178
  # COPY'd (this Dockerfile uses no `COPY . .`) or the import falls back to a STUB
179
  # and /api/a11oy/v1/{quant,qbio,holographic}/status 404 live. Reuses szl_quantum_bio,
 
174
  # served page) is per-file COPY'd below and declared image_only in
175
  # .github/copy-sync-lockstep.json (same baked-only pattern as web/energy.html).
176
  COPY szl_immune.py ./
177
+ # SWEEP D5 — Fabric/Tawantin + Auto-review HONEST /status SUMMARY surfaces.
178
+ # szl_fabric_surface.py serves /api/a11oy/v1/{tawantin,fabric}/status (honest
179
+ # summary over compute-pool-hardened + energy operator/provenance — nodes
180
+ # reachable, sovereign count, MEASURED joules, signed-receipt head) and
181
+ # /api/a11oy/v1/autoreview/status (honest summary over the real autoreview
182
+ # classifier/calibration/dial; rates ROADMAP until real runs). MUST be per-file
183
+ # COPY'd (this Dockerfile uses no `COPY . .`) or serve.py's guarded import falls
184
+ # back and those /status routes 404 live AND hf-sync-backend.yml (it parses this
185
+ # COPY set) would not mirror it to the HF Space. Reuses the live sibling
186
+ # endpoints via loopback; no new dep. Summary-only — no fabricated node/joule data.
187
+ COPY szl_fabric_surface.py ./
188
  # SWEEP DEV 3 status module — imported by serve.py (guarded). MUST be per-file
189
  # COPY'd (this Dockerfile uses no `COPY . .`) or the import falls back to a STUB
190
  # and /api/a11oy/v1/{quant,qbio,holographic}/status 404 live. Reuses szl_quantum_bio,
szl_fabric_surface.py ADDED
@@ -0,0 +1,537 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # © 2026 Lutar, Stephen P. — SZL Holdings · ORCID 0009-0001-0110-4173
3
+ # Doctrine v11 — Fabric / Tawantin / Auto-review honest SUMMARY surfaces.
4
+ """
5
+ szl_fabric_surface.py — honest /status summaries for the Governed Distributed
6
+ Compute Fabric (user-visible names "Fabric" + "Tawantin") and the Governed
7
+ Auto-review autonomy layer.
8
+
9
+ WHY THIS MODULE EXISTS
10
+ ----------------------
11
+ The /fabric and /tawantin PAGES are live (200) and the /autoreview page is live,
12
+ but a page-vs-api sweep found NO honest `/api/a11oy/v1/{tawantin,fabric}/status`
13
+ summary endpoint (404) and NO `/api/a11oy/v1/autoreview/status` (the autoreview
14
+ module registers classify/policy/metrics/dial/recent but not /status).
15
+
16
+ The REAL data already exists and is LIVE elsewhere — we do NOT duplicate it and
17
+ we NEVER fabricate node/joule data:
18
+ * compute fabric nodes / reachability / sovereignty:
19
+ GET /api/a11oy/v1/compute-pool-hardened (szl_backend_hardening, LIVE)
20
+ * MEASURED joules / node compute state:
21
+ GET /api/a11oy/v1/energy/operator/status (szl_energy_operator, LIVE)
22
+ * signed energy-provenance chain head:
23
+ GET /api/a11oy/v1/energy/provenance (szl_energy_provenance, LIVE)
24
+ * governed auto-review classifier + calibration + dial:
25
+ GET /api/a11oy/v1/autoreview/{metrics,dial,policy} (a11oy_autoreview, LIVE)
26
+
27
+ This module mounts honest SUMMARY endpoints that AGGREGATE those live sources
28
+ (short internal HTTP self-call against 127.0.0.1, cached/cheap) and report ONLY
29
+ what the sources truly say:
30
+ GET /api/a11oy/v1/tawantin/status — fabric summary (Quechua name "Tawantin").
31
+ GET /api/a11oy/v1/fabric/status — SAME honest summary (canonical "Fabric").
32
+ GET /api/a11oy/v1/autoreview/status — honest summary over the real autoreview
33
+ substance (calibration MEASURED, dial,
34
+ block-rate ROADMAP until real runs land).
35
+
36
+ HONESTY (doctrine v11)
37
+ ----------------------
38
+ * Summaries reflect TRUE live state. If a source is unreachable this sweep, the
39
+ summary says so (sources_reachable=false) and the affected fields read
40
+ UNKNOWN — never a fabricated green.
41
+ * nodes_reachable / sovereign_count / joules are PASSED THROUGH from the real
42
+ sources, never re-probed, never invented here.
43
+ * MEASURED joules only (the billable figure from the on-box NVML exporter);
44
+ SAMPLE energy is reported separately and labelled, never billable.
45
+ * Khipu receipt OPTIONAL — the underlying sources already sign (energy
46
+ provenance chain + per-source receipts); this summary cites the signed
47
+ provenance head rather than minting a duplicate node-data receipt.
48
+ * locked = EXACTLY 8 {F1,F4,F7,F11,F12,F18,F19,F22} @ c7c0ba17 (add nothing);
49
+ Λ = Conjecture 1; Khipu = Conjecture 2; trust never 100%; effectors
50
+ SIMULATED; HORIZONTAL scale only (NEVER a fused-VRAM claim); orbital =
51
+ ROADMAP; NO user-visible codenames; never commit a key.
52
+
53
+ Stdlib only (urllib for the internal self-call). Additive; try/except-guarded by
54
+ the caller; registered BEFORE the SPA catch-all. `from __future__ import
55
+ annotations` + module-level FastAPI imports so `request: Request` resolves.
56
+ """
57
+ from __future__ import annotations
58
+
59
+ import datetime
60
+ import json
61
+ import os
62
+ import time
63
+ import urllib.request
64
+ from typing import Any, Optional
65
+
66
+ from fastapi import Request
67
+ from fastapi.responses import JSONResponse
68
+
69
+ # ---------------------------------------------------------------------------
70
+ # Identity + doctrine constants (honest, never a codename).
71
+ # ---------------------------------------------------------------------------
72
+ _FABRIC_NAME = "Fabric (Tawantin) — Governed Distributed Compute Fabric"
73
+ _AUTOREVIEW_NAME = "Governed Auto-review"
74
+ _LOCKED_PROVEN = ["F1", "F4", "F7", "F11", "F12", "F18", "F19", "F22"] # EXACTLY 8
75
+ _KERNEL_COMMIT = "c7c0ba17"
76
+
77
+ # Internal self-base: the SAME process serves these sibling endpoints, so a short
78
+ # loopback call returns the already-cached live payloads cheaply. Env-overridable.
79
+ _SELF_PORT = os.environ.get("PORT", "7860")
80
+ _SELF_BASE = os.environ.get("SZL_SELF_BASE_URL", f"http://127.0.0.1:{_SELF_PORT}")
81
+ _SELF_TIMEOUT = float(os.environ.get("SZL_FABRIC_SELF_TIMEOUT", "6.0"))
82
+
83
+ _COMPUTE_POOL_PATH = "/api/a11oy/v1/compute-pool-hardened"
84
+ _ENERGY_OP_PATH = "/api/a11oy/v1/energy/operator/status"
85
+ _ENERGY_PROV_PATH = "/api/a11oy/v1/energy/provenance"
86
+ _AR_METRICS_PATH = "/api/a11oy/v1/autoreview/metrics"
87
+ _AR_DIAL_PATH = "/api/a11oy/v1/autoreview/dial"
88
+ _AR_POLICY_PATH = "/api/a11oy/v1/autoreview/policy"
89
+
90
+ _HONESTY = {
91
+ "lambda": "Conjecture 1 (NOT a theorem)",
92
+ "khipu": "Conjecture 2",
93
+ "trust_ceiling": "never 100%",
94
+ "effectors": "simulated",
95
+ "scale_model": "HORIZONTAL only — independent nodes; NO fused/pooled VRAM is ever claimed",
96
+ "orbital": "ROADMAP",
97
+ "fabricated_data": False,
98
+ "key_committed": False,
99
+ }
100
+
101
+
102
+ def _now_iso() -> str:
103
+ return datetime.datetime.now(datetime.timezone.utc).isoformat()
104
+
105
+
106
+ def _gov(payload: dict, status: str = "REAL", **extra) -> dict:
107
+ """Governed envelope — byte-compatible with serve.py's gov_envelope contract
108
+ ({status, citations, fetchedAt, doctrine}). Reproduced inline so this module
109
+ never imports the heavy serve module at request time."""
110
+ out = dict(payload)
111
+ st = str(status or "REAL").upper()
112
+ if st not in ("REAL", "DEMO", "DEGRADED"):
113
+ st = "DEGRADED"
114
+ out["status"] = st
115
+ if out.get("citations") is None:
116
+ out["citations"] = []
117
+ out["fetchedAt"] = _now_iso()
118
+ out.setdefault("doctrine", "v11")
119
+ for k, v in extra.items():
120
+ out[k] = v
121
+ return out
122
+
123
+
124
+ def _self_get(path: str, timeout: Optional[float] = None) -> Optional[dict]:
125
+ """Short loopback GET of a sibling live endpoint. Returns parsed JSON or None
126
+ (None == source unreachable THIS sweep; the caller degrades honestly, never
127
+ fabricates). Pure stdlib, no new dep."""
128
+ url = _SELF_BASE + path
129
+ try:
130
+ req = urllib.request.Request(url, headers={"accept": "application/json",
131
+ "user-agent": "szl-fabric-summary/1"})
132
+ with urllib.request.urlopen(req, timeout=timeout or _SELF_TIMEOUT) as resp:
133
+ raw = resp.read()
134
+ data = json.loads(raw.decode("utf-8"))
135
+ return data if isinstance(data, dict) else {"_list": data}
136
+ except Exception: # noqa: BLE001 — any failure => honest "source unreachable"
137
+ return None
138
+
139
+
140
+ # ---------------------------------------------------------------------------
141
+ # Fabric / Tawantin honest summary — aggregate the live sources, NEVER duplicate
142
+ # or fabricate node/joule data. nodes/sovereign/joules are PASSED THROUGH.
143
+ # ---------------------------------------------------------------------------
144
+ def _fabric_summary() -> dict:
145
+ pool = _self_get(_COMPUTE_POOL_PATH)
146
+ energy = _self_get(_ENERGY_OP_PATH)
147
+ prov = _self_get(_ENERGY_PROV_PATH)
148
+
149
+ pool_ok = isinstance(pool, dict) and "nodes" in pool
150
+ energy_ok = isinstance(energy, dict) and "joules_measured_total" in energy
151
+ prov_ok = isinstance(prov, dict) and "verify" in prov
152
+
153
+ # --- node reachability + sovereignty: PASS THROUGH from compute-pool only ---
154
+ if pool_ok:
155
+ counts = pool.get("counts", {}) or {}
156
+ nodes = pool.get("nodes", []) or []
157
+ nodes_total = counts.get("nodes_total", len(nodes))
158
+ nodes_reachable = counts.get("nodes_reachable",
159
+ sum(1 for n in nodes if n.get("reachable")))
160
+ gpu_nodes_reachable = counts.get("gpu_nodes_reachable")
161
+ sovereign_count = sum(1 for n in nodes if n.get("sovereign"))
162
+ sovereign_reachable = sum(1 for n in nodes
163
+ if n.get("sovereign") and n.get("reachable"))
164
+ node_brief = [
165
+ {"name": n.get("name"), "kind": n.get("kind"),
166
+ "reachable": n.get("reachable"), "sovereign": n.get("sovereign"),
167
+ "detail": n.get("detail")}
168
+ for n in nodes
169
+ ]
170
+ pool_cached_at = pool.get("cached_at")
171
+ else:
172
+ nodes_total = nodes_reachable = gpu_nodes_reachable = None
173
+ sovereign_count = sovereign_reachable = None
174
+ node_brief = []
175
+ pool_cached_at = None
176
+
177
+ # --- MEASURED joules: PASS THROUGH from the energy operator only ---
178
+ if energy_ok:
179
+ joules_measured_total = energy.get("joules_measured_total")
180
+ joules_measured_label = energy.get("joules_measured_label", "MEASURED")
181
+ joules_sample_total = energy.get("joules_sample_total")
182
+ joules_sample_label = energy.get("joules_sample_label", "SAMPLE")
183
+ nodes_computing = energy.get("nodes_computing", [])
184
+ operator_running = energy.get("running")
185
+ exporter_node = energy.get("exporter_node")
186
+ jobs_done = energy.get("jobs_done")
187
+ else:
188
+ joules_measured_total = None
189
+ joules_measured_label = "UNKNOWN — energy operator unreachable this sweep"
190
+ joules_sample_total = None
191
+ joules_sample_label = "UNKNOWN"
192
+ nodes_computing = []
193
+ operator_running = None
194
+ exporter_node = None
195
+ jobs_done = None
196
+
197
+ # --- signed-receipt head: cite the energy-provenance chain (already signed) ---
198
+ if prov_ok:
199
+ verify = prov.get("verify", {}) or {}
200
+ signed_head = {
201
+ "source": "energy-provenance chain (hash-linked + Bekenstein gate)",
202
+ "head_hash": prov.get("head_hash", "") or verify.get("head_hash", ""),
203
+ "chain_length": prov.get("length", verify.get("length")),
204
+ "links_intact": verify.get("links_intact"),
205
+ "verified_ok": verify.get("ok"),
206
+ "kind": "Conjecture 2 (Khipu/provenance: tamper-EVIDENT, not tamper-proof)",
207
+ }
208
+ else:
209
+ signed_head = {
210
+ "source": "energy-provenance chain",
211
+ "head_hash": "UNKNOWN — provenance source unreachable this sweep",
212
+ "verified_ok": None,
213
+ "kind": "Conjecture 2",
214
+ }
215
+
216
+ sources_reachable = bool(pool_ok and energy_ok)
217
+ status = "REAL" if sources_reachable else "DEGRADED"
218
+
219
+ payload = {
220
+ "ok": True,
221
+ "service": "fabric",
222
+ "surface_names": ["Fabric", "Tawantin"],
223
+ "organ": _FABRIC_NAME,
224
+ "kind": "Governed Distributed Compute Fabric (honest SUMMARY over live sources)",
225
+ "role": "horizontal multi-node governed compute — independent nodes, NOT a fused pool",
226
+ "summary": {
227
+ "nodes_total": nodes_total,
228
+ "nodes_reachable": nodes_reachable,
229
+ "gpu_nodes_reachable": gpu_nodes_reachable,
230
+ "sovereign_count": sovereign_count,
231
+ "sovereign_reachable": sovereign_reachable,
232
+ "joules_measured_total": joules_measured_total,
233
+ "joules_measured_label": joules_measured_label,
234
+ "joules_sample_total": joules_sample_total,
235
+ "joules_sample_label": joules_sample_label,
236
+ "operator_running": operator_running,
237
+ "nodes_computing": nodes_computing,
238
+ "jobs_done": jobs_done,
239
+ "exporter_node": exporter_node,
240
+ "signed_receipt_head": signed_head,
241
+ },
242
+ "nodes": node_brief,
243
+ "sources": {
244
+ "compute_pool": {"path": _COMPUTE_POOL_PATH, "reachable": pool_ok,
245
+ "cached_at": pool_cached_at,
246
+ "note": "node identity / reachability / sovereignty (LIVE)"},
247
+ "energy_operator": {"path": _ENERGY_OP_PATH, "reachable": energy_ok,
248
+ "note": "MEASURED joules via on-box NVML exporter (LIVE)"},
249
+ "energy_provenance": {"path": _ENERGY_PROV_PATH, "reachable": prov_ok,
250
+ "note": "signed hash-linked provenance chain head (LIVE)"},
251
+ },
252
+ "sources_reachable": sources_reachable,
253
+ "honesty": dict(_HONESTY, **{
254
+ "summary_only": "This endpoint AGGREGATES the live sources above. It "
255
+ "duplicates NO node data and fabricates NO joule/node "
256
+ "value — every figure is passed through from its real "
257
+ "source, or UNKNOWN when that source is unreachable.",
258
+ "scale": "HORIZONTAL scale only — independent nodes. There is NO fused/"
259
+ "pooled VRAM claim anywhere in this fabric.",
260
+ "joules": "joules_measured_total is the SUM of fresh (<30s) per-job "
261
+ "MEASURED NVML deltas — the only billable figure. SAMPLE "
262
+ "energy is tracked separately and is never billable.",
263
+ "khipu_receipt": "OPTIONAL here — the underlying energy-provenance + "
264
+ "per-source receipts already sign. This summary CITES "
265
+ "the signed provenance head rather than minting a "
266
+ "duplicate node-data receipt.",
267
+ }),
268
+ "locked_proven": {
269
+ "set": _LOCKED_PROVEN, "count": len(_LOCKED_PROVEN),
270
+ "kernel_commit": _KERNEL_COMMIT,
271
+ "note": "EXACTLY 8 locked-proven; this summary adds nothing to the set.",
272
+ },
273
+ "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
274
+ }
275
+ return _gov(payload, status=status)
276
+
277
+
278
+ # ---------------------------------------------------------------------------
279
+ # Auto-review honest summary — over the REAL governed auto-review substance.
280
+ # Calibration is MEASURED (LIVE); decision-rate metrics are ROADMAP until real
281
+ # runs are logged. NEVER faked.
282
+ # ---------------------------------------------------------------------------
283
+ def _autoreview_summary() -> dict:
284
+ metrics = _self_get(_AR_METRICS_PATH)
285
+ dial = _self_get(_AR_DIAL_PATH)
286
+ policy = _self_get(_AR_POLICY_PATH)
287
+
288
+ metrics_ok = isinstance(metrics, dict)
289
+ dial_ok = isinstance(dial, dict)
290
+ policy_ok = isinstance(policy, dict)
291
+
292
+ # --- calibration: MEASURED, passed through from the live metrics source ---
293
+ calib = (metrics.get("calibration") if metrics_ok else None) or {}
294
+ calib_status = calib.get("status") # "measured" when real predictions exist
295
+ calibration_live = calib_status == "measured"
296
+
297
+ # --- decision rates: MEASURED when real decisions logged, else ROADMAP ---
298
+ decisions_logged = metrics.get("decisions_logged") if metrics_ok else None
299
+ rate_status = metrics.get("rate_status") if metrics_ok else None
300
+ rates_live = bool(decisions_logged) if decisions_logged is not None else False
301
+
302
+ dial_levels = dial.get("levels", []) if dial_ok else []
303
+ default_level = None
304
+ for lvl in dial_levels:
305
+ if isinstance(lvl, dict) and "default" in str(lvl.get("label", "")).lower():
306
+ default_level = lvl.get("level")
307
+
308
+ automated_gate = metrics.get("automated_response_gate") if metrics_ok else None
309
+
310
+ # The classifier itself is REAL + LIVE (deterministic intent-relative scorer,
311
+ # policy-as-code, signed DSSE verdicts). The fast-model wiring is ROADMAP.
312
+ sources_reachable = bool(metrics_ok and dial_ok)
313
+ status = "REAL" if sources_reachable else "DEGRADED"
314
+
315
+ payload = {
316
+ "ok": True,
317
+ "service": "autoreview",
318
+ "organ": _AUTOREVIEW_NAME,
319
+ "kind": "Governed + signed + standards-mapped Auto-review autonomy layer "
320
+ "(honest SUMMARY over the live classifier/calibration/dial sources)",
321
+ "classifier": {
322
+ "kind": "fast deterministic intent-relative rule+feature scorer (HEURISTIC)",
323
+ "live": True,
324
+ "label": "LIVE — the classifier + policy-as-code + signed DSSE verdict "
325
+ "path are real and served (classify/gated-run/policy/metrics).",
326
+ "production_fast_model": "sovereign GPU/router fast model (RTX role-split) "
327
+ "— ROADMAP (labelled, not wired).",
328
+ },
329
+ "calibration": {
330
+ "live": calibration_live,
331
+ "label": "LIVE — MEASURED ECE/Brier" if calibration_live
332
+ else "ROADMAP — no measured calibration yet",
333
+ "model": calib.get("model"),
334
+ "n": calib.get("n"),
335
+ "ece": calib.get("ece"),
336
+ "brier": calib.get("brier"),
337
+ "accuracy": calib.get("accuracy"),
338
+ "ece_gate_threshold": calib.get("ece_gate_threshold"),
339
+ "note": "ECE/Brier over the last N verified predictions; ECE<0.05 gates "
340
+ "automated responses. MEASURED, never faked.",
341
+ },
342
+ "decision_rates": {
343
+ "live": rates_live,
344
+ "label": "LIVE — MEASURED from the rolling decision log" if rates_live
345
+ else "ROADMAP — no real decisions logged yet (rates are null, never faked)",
346
+ "decisions_logged": decisions_logged,
347
+ "block_rate": metrics.get("block_rate") if metrics_ok else None,
348
+ "interrupt_rate": metrics.get("interrupt_rate") if metrics_ok else None,
349
+ "escalate_rate": metrics.get("escalate_rate") if metrics_ok else None,
350
+ "rate_status": rate_status,
351
+ "honest_note": "Block/interrupt/escalate rates are MEASURED from the local "
352
+ "rolling decision log, or ROADMAP (null) when no real runs "
353
+ "exist yet. We never borrow another vendor's published number.",
354
+ },
355
+ "autonomy_dial": {
356
+ "live": dial_ok,
357
+ "levels": len(dial_levels),
358
+ "default_level": default_level,
359
+ "label": "LIVE — autonomy is a DIAL (L0..L5), not a switch",
360
+ },
361
+ "policy_as_code": {
362
+ "live": policy_ok,
363
+ "label": "LIVE — OPA/Rego rules mapped to OSCAL control IDs + NIST AI RMF "
364
+ "MANAGE subcategories" if policy_ok else "ROADMAP",
365
+ },
366
+ "automated_response_gate": automated_gate,
367
+ "sources": {
368
+ "metrics": {"path": _AR_METRICS_PATH, "reachable": metrics_ok},
369
+ "dial": {"path": _AR_DIAL_PATH, "reachable": dial_ok},
370
+ "policy": {"path": _AR_POLICY_PATH, "reachable": policy_ok},
371
+ },
372
+ "sources_reachable": sources_reachable,
373
+ "honesty": dict(_HONESTY, **{
374
+ "verdict_signing": "Auto-review verdicts are signed into DSSE receipts "
375
+ "(reuses the host's real ECDSA-P256 signer) — tamper-"
376
+ "EVIDENT, not tamper-proof.",
377
+ "summary_only": "This endpoint summarizes the live autoreview sources; it "
378
+ "fabricates no metric. Decision rates stay ROADMAP/null "
379
+ "until real runs are logged.",
380
+ "borrow": "Pattern honestly borrowed-and-evolved from Cursor's Auto-review "
381
+ "(autonomy as a dial). We MEASURE our own numbers; we do not "
382
+ "borrow theirs.",
383
+ }),
384
+ "locked_proven": {
385
+ "set": _LOCKED_PROVEN, "count": len(_LOCKED_PROVEN),
386
+ "kernel_commit": _KERNEL_COMMIT,
387
+ "note": "EXACTLY 8 locked-proven; this summary adds nothing to the set.",
388
+ },
389
+ "ts": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
390
+ }
391
+ return _gov(payload, status=status)
392
+
393
+
394
+ def _healthz(service: str, organ: str) -> dict:
395
+ return {"status": "ok", "service": service, "organ": organ, "doctrine": "v11"}
396
+
397
+
398
+ # ---------------------------------------------------------------------------
399
+ # Registration — dual-register under /api/{ns}/v1/* AND /v1/*. add_api_route,
400
+ # mirroring szl_immune. Registered BEFORE the SPA catch-all so these JSON routes
401
+ # win ordering. Module-level Request/JSONResponse imports keep annotations valid.
402
+ # ---------------------------------------------------------------------------
403
+ def register(app, ns: str = "a11oy") -> dict:
404
+ async def _h_tawantin_status(): # noqa: ANN202
405
+ return JSONResponse(_fabric_summary())
406
+
407
+ async def _h_fabric_status(): # noqa: ANN202
408
+ return JSONResponse(_fabric_summary())
409
+
410
+ async def _h_autoreview_status(): # noqa: ANN202
411
+ return JSONResponse(_autoreview_summary())
412
+
413
+ async def _h_tawantin_healthz(): # noqa: ANN202
414
+ return JSONResponse(_healthz("tawantin", _FABRIC_NAME))
415
+
416
+ async def _h_fabric_healthz(): # noqa: ANN202
417
+ return JSONResponse(_healthz("fabric", _FABRIC_NAME))
418
+
419
+ routes: list[str] = []
420
+ for base in (f"/api/{ns}/v1", "/v1"):
421
+ app.add_api_route(f"{base}/tawantin/status", _h_tawantin_status,
422
+ methods=["GET"], include_in_schema=True)
423
+ app.add_api_route(f"{base}/tawantin/healthz", _h_tawantin_healthz,
424
+ methods=["GET"], include_in_schema=True)
425
+ app.add_api_route(f"{base}/fabric/status", _h_fabric_status,
426
+ methods=["GET"], include_in_schema=True)
427
+ app.add_api_route(f"{base}/fabric/healthz", _h_fabric_healthz,
428
+ methods=["GET"], include_in_schema=True)
429
+ app.add_api_route(f"{base}/autoreview/status", _h_autoreview_status,
430
+ methods=["GET"], include_in_schema=True)
431
+ routes.extend([f"{base}/tawantin/status", f"{base}/tawantin/healthz",
432
+ f"{base}/fabric/status", f"{base}/fabric/healthz",
433
+ f"{base}/autoreview/status"])
434
+
435
+ print(f"[{ns}] szl_fabric_surface routes registered "
436
+ f"(Fabric/Tawantin + Auto-review honest summaries, {len(routes)} routes)",
437
+ flush=True)
438
+ return {"ok": True, "ns": ns, "organ": _FABRIC_NAME, "routes": routes}
439
+
440
+
441
+ # ---------------------------------------------------------------------------
442
+ # No-server self-test — proves the aggregation/honesty logic with mocked sources
443
+ # (no HTTP, no live deps). Validates: pass-through, honest degradation, no
444
+ # codename leak, no fused-VRAM claim.
445
+ # ---------------------------------------------------------------------------
446
+ def _selftest() -> dict:
447
+ import unittest.mock as mock
448
+ out: dict = {}
449
+
450
+ fake_pool = {
451
+ "counts": {"nodes_total": 7, "nodes_reachable": 4, "gpu_nodes_reachable": 0},
452
+ "nodes": [
453
+ {"name": "hetzner-box-cpu", "kind": "cpu", "reachable": True,
454
+ "sovereign": True, "detail": "self"},
455
+ {"name": "rtx-betterwithage", "kind": "sovereign-gpu", "reachable": False,
456
+ "sovereign": True, "detail": "timeout"},
457
+ {"name": "groq", "kind": "hosted-inference", "reachable": True,
458
+ "sovereign": False, "detail": "tcp reachable"},
459
+ ],
460
+ "cached_at": "2026-06-16T05:00:00Z",
461
+ }
462
+ fake_energy = {
463
+ "joules_measured_total": 0.0, "joules_measured_label": "MEASURED",
464
+ "joules_sample_total": 0.0, "joules_sample_label": "SAMPLE",
465
+ "running": False, "nodes_computing": [], "jobs_done": 0,
466
+ "exporter_node": "betterwithage",
467
+ }
468
+ fake_prov = {"head_hash": "abc123", "length": 3,
469
+ "verify": {"ok": True, "links_intact": True, "length": 3,
470
+ "head_hash": "abc123"}}
471
+ fake_metrics = {
472
+ "decisions_logged": 0, "block_rate": None, "interrupt_rate": None,
473
+ "rate_status": "ROADMAP — no real decisions logged yet",
474
+ "calibration": {"model": "a11oy-autoreview-classifier", "n": 24,
475
+ "status": "measured", "ece": 0.03875, "brier": 0.002017,
476
+ "accuracy": 1.0, "ece_gate_threshold": 0.05},
477
+ "automated_response_gate": {"allow": True},
478
+ }
479
+ fake_dial = {"levels": [{"level": i, "label": f"L{i}"} for i in range(6)]}
480
+ fake_dial["levels"][3]["label"] = "L3 — Governed (default)"
481
+ fake_policy = {"rules": []}
482
+
483
+ def _route(path, timeout=None):
484
+ return {
485
+ _COMPUTE_POOL_PATH: fake_pool, _ENERGY_OP_PATH: fake_energy,
486
+ _ENERGY_PROV_PATH: fake_prov, _AR_METRICS_PATH: fake_metrics,
487
+ _AR_DIAL_PATH: fake_dial, _AR_POLICY_PATH: fake_policy,
488
+ }.get(path)
489
+
490
+ with mock.patch(__name__ + "._self_get", side_effect=_route):
491
+ fab = _fabric_summary()
492
+ ar = _autoreview_summary()
493
+
494
+ # Pass-through correctness (no fabrication, no invention).
495
+ assert fab["status"] == "REAL", fab
496
+ assert fab["summary"]["nodes_total"] == 7, fab
497
+ assert fab["summary"]["nodes_reachable"] == 4, fab
498
+ assert fab["summary"]["sovereign_count"] == 2, fab
499
+ assert fab["summary"]["sovereign_reachable"] == 1, fab
500
+ assert fab["summary"]["joules_measured_total"] == 0.0, fab
501
+ assert fab["summary"]["signed_receipt_head"]["head_hash"] == "abc123", fab
502
+ out["fabric_passthrough"] = True
503
+
504
+ # Auto-review: calibration MEASURED live, rates ROADMAP.
505
+ assert ar["calibration"]["live"] is True, ar
506
+ assert ar["calibration"]["ece"] == 0.03875, ar
507
+ assert ar["decision_rates"]["live"] is False, ar
508
+ assert ar["autonomy_dial"]["default_level"] == 3, ar
509
+ out["autoreview_labels"] = True
510
+
511
+ # Honest degradation when a source is unreachable.
512
+ with mock.patch(__name__ + "._self_get", side_effect=lambda p, timeout=None: None):
513
+ fab_d = _fabric_summary()
514
+ ar_d = _autoreview_summary()
515
+ assert fab_d["status"] == "DEGRADED", fab_d
516
+ assert fab_d["sources_reachable"] is False, fab_d
517
+ assert fab_d["summary"]["nodes_total"] is None, fab_d
518
+ assert ar_d["status"] == "DEGRADED", ar_d
519
+ out["honest_degradation"] = True
520
+
521
+ # No codename leak; no fused-VRAM claim.
522
+ served = json.dumps([fab, ar, fab_d, ar_d]).lower()
523
+ for bad in ("sentra", "amaru", "rosie", "jarvis"):
524
+ assert bad not in served, f"codename leak: {bad}"
525
+ # The ONLY mentions of fused/pooled VRAM must be honest NEGATIONS (we deny it).
526
+ assert "horizontal" in served, "missing horizontal-scale honesty"
527
+ assert ("no fused" in served and "not a fused pool" in served), \
528
+ "fused-VRAM must appear only as an explicit denial"
529
+ # No POSITIVE fused-VRAM claim (e.g. 'fused vram', 'pooled vram' without 'no').
530
+ assert "fused vram" not in served, "positive fused-VRAM claim leaked"
531
+ out["no_codename_no_fused_vram"] = True
532
+
533
+ return out
534
+
535
+
536
+ if __name__ == "__main__":
537
+ print(json.dumps(_selftest(), indent=2))