betterwithage commited on
Commit
ae3690f
·
verified ·
1 Parent(s): 3d5ef33

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, serve.py, szl_codename_gate.py, szl_ecosystem_routes.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 (4) hide show
  1. Dockerfile +6 -0
  2. serve.py +21 -0
  3. szl_codename_gate.py +152 -0
  4. szl_ecosystem_routes.py +441 -0
Dockerfile CHANGED
@@ -720,6 +720,12 @@ COPY szl_research_infra.py szl_dark_surfaces_register.py szl_anatomy_loop.py ./
720
  COPY conduction_aphasia.py szl_a11oy_live_feeds.py szl_jack.py ./
721
 
722
 
 
 
 
 
 
 
723
  CMD ["python", "serve.py"]
724
 
725
 
 
720
  COPY conduction_aphasia.py szl_a11oy_live_feeds.py szl_jack.py ./
721
 
722
 
723
+
724
+ # --- ESTATE ECOSYSTEM FOUNDATION (Dev5, 2026-06): byte-identical shared modules ---
725
+ # 3 shared JS (label engine / receipt-cosign / codename sanitizer) + codename gate + ecosystem router.
726
+ COPY static/shared/szl_label_engine.js static/shared/szl_receipt_cosign.js static/shared/szl_codename_sanitizer.js ./static/shared/
727
+ COPY szl_codename_gate.py szl_ecosystem_routes.py ./
728
+
729
  CMD ["python", "serve.py"]
730
 
731
 
serve.py CHANGED
@@ -1207,6 +1207,27 @@ try:
1207
  except Exception as _anat_e: # additive: never break the Space
1208
  print(f"[a11oy] anatomy run-engine NOT wired ({_anat_e!r}); SPA + API unaffected", file=sys.stderr)
1209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1210
  # ---------------------------------------------------------------------------
1211
  # ADDITIVE (MINED UPGRADES, 2026-06, Yachay): four self-contained, dependency-free
1212
  # operator surfaces, each adopting a PERMISSIVELY-licensed PATTERN from a founder-
 
1207
  except Exception as _anat_e: # additive: never break the Space
1208
  print(f"[a11oy] anatomy run-engine NOT wired ({_anat_e!r}); SPA + API unaffected", file=sys.stderr)
1209
 
1210
+ # ---------------------------------------------------------------------------
1211
+ # ADDITIVE (ESTATE ECOSYSTEM FOUNDATION, 2026-06, Dev5): cross-app ecosystem
1212
+ # surfaces wired as ONE additive router. Registered BEFORE the SPA catch-all,
1213
+ # try/except-guarded so a missing dep can NEVER take the Space down.
1214
+ # GET /ecosystem estate hub (HTML)
1215
+ # GET /estate-organism 3D living-organism (HTML, vendored 3D)
1216
+ # GET /api/{ns}/v1/ecosystem/anatomy 5-organ vitals (MELT in-process, honest)
1217
+ # GET /api/{ns}/v1/ecosystem/mesh cross-app fabric + Fiedler lambda2 (MODELED)
1218
+ # GET /api/{ns}/v1/ecosystem/ledger cross-app unified DSSE ledger (ECDSA-P256)
1219
+ # GET /api/{ns}/v1/ecosystem/kpi-board estate Lambda/KPI rollup (locked-8 EXACTLY 8)
1220
+ # Doctrine v11: locked EXACTLY 8 {F1,F4,F7,F11,F12,F18,F19,F22}@c7c0ba17; Lambda = Conjecture 1 (< 1.0).
1221
+ # ---------------------------------------------------------------------------
1222
+ try:
1223
+ import szl_ecosystem_routes as _szl_ecosystem
1224
+ _eco_paths = _szl_ecosystem.register(app, ns="a11oy")
1225
+ print(f"[a11oy] ecosystem foundation wired ({_eco_paths}): /ecosystem /estate-organism /api/a11oy/v1/ecosystem/*", file=sys.stderr)
1226
+ except Exception as _eco_e: # additive: never break the Space
1227
+ print(f"[a11oy] ecosystem foundation NOT wired ({_eco_e!r}); SPA + API unaffected", file=sys.stderr)
1228
+
1229
+
1230
+
1231
  # ---------------------------------------------------------------------------
1232
  # ADDITIVE (MINED UPGRADES, 2026-06, Yachay): four self-contained, dependency-free
1233
  # operator surfaces, each adopting a PERMISSIVELY-licensed PATTERN from a founder-
szl_codename_gate.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ # (c) 2026 Lutar, Stephen P. - SZL Holdings - ORCID 0009-0001-0110-4173
4
+ """
5
+ szl_codename_gate.py - SHARED MODULE (byte-identical across a11oy + killinchu)
6
+ ==============================================================================
7
+ Doctrine gate G5 enforcement: 0 user-visible codenames.
8
+
9
+ Internal route keys (amaru_* / rosie_* / sentra / jarvis) are allowed as code
10
+ identifiers, but they must NEVER appear in *rendered-text columns* or *served
11
+ HTML body text*. This module is the single source of truth for:
12
+
13
+ - the banned-token set + public-role mapping (mirrors the JS sanitizer),
14
+ - sanitize() : map a string to its honest public roles,
15
+ - scan_text() : find banned tokens in a plain string,
16
+ - scan_html_visible() : find banned tokens in the VISIBLE text of HTML
17
+ (strips <script>/<style>, tags, id/class/data-*
18
+ route keys) - the false-positive-safe scanner
19
+ used by the CI acceptance gate,
20
+ - scan_url() : fetch a served URL and scan its visible HTML,
21
+ - main() : CI entrypoint; exits non-zero on any violation.
22
+
23
+ Public roles (mirrors szl_codename_sanitizer.js MAP):
24
+ amaru -> YACHAY (cortex / brain / OSINT ingest)
25
+ rosie -> Operator (orchestrator)
26
+ sentra -> CHAPAQ (verdict / immune)
27
+ jarvis -> Operator (assistant / orchestrator)
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import html as _html
32
+ import re
33
+ import sys
34
+ from typing import Dict, List
35
+
36
+ MAP: Dict[str, str] = {
37
+ "amaru": "YACHAY",
38
+ "rosie": "Operator",
39
+ "sentra": "CHAPAQ",
40
+ "jarvis": "Operator",
41
+ }
42
+ TOKENS = ("amaru", "rosie", "sentra", "jarvis")
43
+ _BANNED = re.compile("(" + "|".join(TOKENS) + ")", re.IGNORECASE)
44
+
45
+
46
+ def sanitize(text: str) -> str:
47
+ """Replace every banned codename with its honest public role."""
48
+ if text is None:
49
+ return text
50
+ return _BANNED.sub(lambda m: MAP.get(m.group(0).lower(), m.group(0)), str(text))
51
+
52
+
53
+ def scan_text(text: str) -> List[str]:
54
+ """Return the list of banned tokens found in a plain string."""
55
+ return [m.group(0) for m in _BANNED.finditer(str(text or ""))]
56
+
57
+
58
+ # --- HTML visible-text extraction (no external deps) -----------------------
59
+ # Remove <script> and <style> bodies, then strip tags, decode entities. We do
60
+ # NOT scan attribute values like id=/class=/data-* (those are allowed internal
61
+ # route keys); we DO scan the visible human-facing attributes title/aria-label/
62
+ # alt/placeholder so a tooltip can't smuggle a codename to the user.
63
+ _SCRIPT_STYLE = re.compile(r"<(script|style)\b[^>]*>.*?</\1>", re.IGNORECASE | re.DOTALL)
64
+ _VISIBLE_ATTRS = re.compile(
65
+ r'\b(?:title|aria-label|alt|placeholder)\s*=\s*(?:"([^"]*)"|\'([^\']*)\')',
66
+ re.IGNORECASE,
67
+ )
68
+ _TAG = re.compile(r"<[^>]+>")
69
+
70
+
71
+ def html_visible_text(html_str: str) -> str:
72
+ """Best-effort extraction of the text a human actually sees, plus the
73
+ human-visible attributes (title/aria-label/alt/placeholder)."""
74
+ s = _SCRIPT_STYLE.sub(" ", html_str or "")
75
+ visible_attr_vals = []
76
+ for m in _VISIBLE_ATTRS.finditer(s):
77
+ visible_attr_vals.append(m.group(1) or m.group(2) or "")
78
+ body = _TAG.sub(" ", s)
79
+ body = _html.unescape(body)
80
+ return body + " \n" + " \n".join(visible_attr_vals)
81
+
82
+
83
+ def scan_html_visible(html_str: str) -> List[str]:
84
+ """Return banned tokens visible in rendered HTML (text + visible attrs)."""
85
+ return scan_text(html_visible_text(html_str))
86
+
87
+
88
+ def scan_url(url: str, timeout: float = 30.0) -> List[str]:
89
+ """Fetch a served URL and scan its visible HTML. Network errors raise."""
90
+ import urllib.request
91
+
92
+ req = urllib.request.Request(url, headers={"User-Agent": "szl-codename-gate/1.0"})
93
+ with urllib.request.urlopen(req, timeout=timeout) as r: # noqa: S310 (trusted internal)
94
+ data = r.read().decode("utf-8", "replace")
95
+ return scan_html_visible(data)
96
+
97
+
98
+ def _scan_path(path: str) -> List[str]:
99
+ try:
100
+ with open(path, "r", encoding="utf-8", errors="replace") as fh:
101
+ content = fh.read()
102
+ except Exception as e: # pragma: no cover
103
+ return ["<read-error:%s>" % e]
104
+ if path.lower().endswith((".html", ".htm", ".svg")):
105
+ return scan_html_visible(content)
106
+ # For .csv / rendered-text columns and served JSON, scan the raw text.
107
+ return scan_text(content)
108
+
109
+
110
+ def main(argv: List[str]) -> int:
111
+ """CI entrypoint. Args = files / globs / http(s) URLs. Non-zero on hit."""
112
+ import glob
113
+
114
+ targets: List[str] = []
115
+ urls: List[str] = []
116
+ for a in argv:
117
+ if a.startswith("http://") or a.startswith("https://"):
118
+ urls.append(a)
119
+ else:
120
+ g = glob.glob(a, recursive=True)
121
+ targets.extend(g if g else [a])
122
+
123
+ violations = 0
124
+ for path in targets:
125
+ hits = _scan_path(path)
126
+ if hits:
127
+ violations += len(hits)
128
+ print("FAIL %s -> banned visible tokens: %s" % (path, ", ".join(sorted(set(hits)))))
129
+ else:
130
+ print("ok %s" % path)
131
+ for url in urls:
132
+ try:
133
+ hits = scan_url(url)
134
+ except Exception as e:
135
+ print("WARN %s -> could not fetch (%s) - skipping" % (url, e))
136
+ continue
137
+ if hits:
138
+ violations += len(hits)
139
+ print("FAIL %s -> banned visible tokens: %s" % (url, ", ".join(sorted(set(hits)))))
140
+ else:
141
+ print("ok %s" % url)
142
+
143
+ print("\nG5 codename gate: %d banned user-visible token(s) found." % violations)
144
+ if violations:
145
+ print("Doctrine G5 violated: every user-visible string must read YACHAY / Operator / CHAPAQ.")
146
+ return 1
147
+ print("G5 PASS - 0 user-visible codenames.")
148
+ return 0
149
+
150
+
151
+ if __name__ == "__main__":
152
+ sys.exit(main(sys.argv[1:]))
szl_ecosystem_routes.py ADDED
@@ -0,0 +1,441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # (c) 2026 Lutar, Stephen P. - SZL Holdings - ORCID 0009-0001-0110-4173
3
+ # Doctrine v11 - locked-8 {F1,F4,F7,F11,F12,F18,F19,F22}@c7c0ba17 - Lambda = Conjecture 1
4
+ """
5
+ szl_ecosystem_routes.py - SHARED MODULE (byte-identical across a11oy + killinchu)
6
+ =================================================================================
7
+ ADDITIVE FastAPI router for the estate-level ECOSYSTEM surfaces (Dev5 lane, the
8
+ "one organism" connective tissue that spans BOTH apps):
9
+
10
+ GET /ecosystem - HTML estate hub (links the 5 surfaces)
11
+ GET /estate-organism - HTML 3D living-organism (both apps as ONE
12
+ body; 5 organs; MELT-fed vitals; vendored 3D)
13
+ (named /estate-organism to avoid colliding
14
+ with the existing per-app /anatomy mount)
15
+ GET /api/{ns}/v1/ecosystem/anatomy - JSON: 5-organ vitals fused from both apps
16
+ GET /api/{ns}/v1/ecosystem/mesh - JSON: cross-app szl-mesh fabric + Fiedler lambda2
17
+ GET /api/{ns}/v1/ecosystem/ledger - JSON: cross-app unified DSSE ledger + cross-app
18
+ cosign-chain verify verdict (SAME chain check)
19
+ GET /api/{ns}/v1/ecosystem/kpi-board - JSON: estate Lambda/KPI rollup (locked-8 EXACTLY
20
+ 8; Lambda < 1.0; CHAPAQ verdict; per-app health)
21
+
22
+ DOCTRINE (hard gates honored here):
23
+ G1 locked-proven is EXACTLY 8 {F1,F4,F7,F11,F12,F18,F19,F22}@c7c0ba17 - read LIVE from
24
+ a11oy /honest; the board FLAGS any source that reports != 8 (e.g. a stale locked=5).
25
+ G2 Lambda = Conjecture 1; the board CLAMPS displayed Lambda to < 1.0 and labels it
26
+ "Conjecture 1 (not a theorem)". If a source returns lambda 1.0 it is flagged + clamped.
27
+ G3 mesh is tamper-EVIDENT, not tamper-proof; BFT safety = Conjecture 2.
28
+ G4 SLSA "L1 honest / L2 attested / L3 roadmap"; PQC roadmap-only; never bare-L3.
29
+ G5 0 user-visible codenames (this module emits only YACHAY / Operator / CHAPAQ).
30
+ G7 honest labels; 0 runtime CDN (3D libs are vendored under /static-vendor + /static/vendor3d).
31
+ G8 the half-state is the only unacceptable outcome - where a feed is unreachable or a
32
+ signer is ephemeral, the surface says so honestly; it NEVER fabricates LIVE.
33
+
34
+ Self-contained: stdlib only (urllib). Reads the SHARED label/receipt vocabulary so the
35
+ estate surfaces use the same honest pills + the single ECDSA-P256 cosign scheme.
36
+ register(app, ns=...) is the single integration point (try/except-guarded in serve.py).
37
+ """
38
+ from __future__ import annotations
39
+
40
+ import json
41
+ import time
42
+ import urllib.request
43
+ from typing import Any, Dict, List, Optional
44
+
45
+ try: # present in a FastAPI Space
46
+ from fastapi import Request
47
+ from fastapi.responses import HTMLResponse, JSONResponse
48
+ except Exception: # pure-python import without FastAPI
49
+ Request = HTMLResponse = JSONResponse = None # type: ignore
50
+
51
+ # Canonical doctrine constants (single source of truth - mirrors DOCTRINE_V11.md)
52
+ LOCKED8 = ["F1", "F4", "F7", "F11", "F12", "F18", "F19", "F22"]
53
+ KERNEL = "c7c0ba17"
54
+ COSIGN_KEYID = "szlholdings-cosign"
55
+ COSIGN_PUB_URL = "https://github.com/szl-holdings/.github/blob/main/cosign.pub"
56
+ LAMBDA_CAP = 0.999 # trust never 100% (G2/G7)
57
+
58
+ A11OY_BASE = "https://szlholdings-a11oy.hf.space"
59
+ KILLINCHU_BASE = "https://szlholdings-killinchu.hf.space"
60
+
61
+ _CACHE: Dict[str, Any] = {}
62
+ _CACHE_TTL = 20.0
63
+
64
+
65
+ def _get_json(url: str, timeout: float = 12.0) -> Optional[Any]:
66
+ """Best-effort cached GET of an estate JSON endpoint. None on any failure
67
+ (honest: the surface shows 'unreachable', never a fabricated value)."""
68
+ now = time.time()
69
+ hit = _CACHE.get(url)
70
+ if hit and (now - hit[0]) < _CACHE_TTL:
71
+ return hit[1]
72
+ try:
73
+ req = urllib.request.Request(url, headers={"User-Agent": "szl-ecosystem/1.0"})
74
+ with urllib.request.urlopen(req, timeout=timeout) as r:
75
+ data = json.loads(r.read().decode("utf-8", "replace"))
76
+ _CACHE[url] = (now, data)
77
+ return data
78
+ except Exception:
79
+ return None
80
+
81
+
82
+ def _post_json(url: str, body: dict, timeout: float = 12.0) -> Optional[Any]:
83
+ try:
84
+ req = urllib.request.Request(
85
+ url, data=json.dumps(body).encode(),
86
+ headers={"User-Agent": "szl-ecosystem/1.0", "Content-Type": "application/json"},
87
+ method="POST",
88
+ )
89
+ with urllib.request.urlopen(req, timeout=timeout) as r:
90
+ return json.loads(r.read().decode("utf-8", "replace"))
91
+ except Exception:
92
+ return None
93
+
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # Estate data builders (all honest: label LIVE only when the fetch succeeded)
97
+ # ---------------------------------------------------------------------------
98
+ def _app_health(base: str, honest_path: str) -> Dict[str, Any]:
99
+ h = _get_json(base + honest_path)
100
+ reachable = h is not None
101
+ return {"base": base, "reachable": reachable, "label": "LIVE" if reachable else "SAMPLE", "honest": h}
102
+
103
+
104
+ def build_kpi_board(ns: str) -> Dict[str, Any]:
105
+ """Estate Lambda/KPI rollup. locked-8 EXACTLY 8; Lambda clamped < 1.0."""
106
+ a_honest = _get_json(A11OY_BASE + "/api/a11oy/v1/honest")
107
+ a_lambda = _get_json(A11OY_BASE + "/api/a11oy/v1/lambda")
108
+ chapaq = _get_json(KILLINCHU_BASE + "/api/killinchu/v1/gov/chapaq-verdict")
109
+
110
+ # locked-8 (G1) - read live, flag any source reporting != 8
111
+ lock = (a_honest or {}).get("doctrine_lock", {}) if a_honest else {}
112
+ src_ids = lock.get("locked_formula_ids") or []
113
+ src_count = lock.get("locked_formula_count")
114
+ locked_ok = (src_count == 8 and sorted(src_ids) == sorted(LOCKED8))
115
+ locked_panel = {
116
+ "expected": LOCKED8, "kernel": KERNEL, "expected_count": 8,
117
+ "source_ids": src_ids, "source_count": src_count,
118
+ "ok": bool(locked_ok),
119
+ "note": "locked-proven is EXACTLY 8 @ %s" % KERNEL if locked_ok
120
+ else "DEFECT: source reports %s (expected EXACTLY 8 @ %s) - display clamped to canonical 8" % (src_count, KERNEL),
121
+ "display_ids": LOCKED8, "display_count": 8, # we always DISPLAY the canonical 8 (G1)
122
+ }
123
+
124
+ # Lambda (G2) - clamp to < 1.0, label Conjecture 1
125
+ raw_lambda = None
126
+ if a_lambda and isinstance(a_lambda.get("lambda"), (int, float)):
127
+ raw_lambda = float(a_lambda["lambda"])
128
+ chapaq_lambda = None
129
+ if chapaq and isinstance(chapaq.get("data", {}).get("lambda_value"), (int, float)):
130
+ chapaq_lambda = float(chapaq["data"]["lambda_value"])
131
+ lambda_flags = []
132
+ if chapaq_lambda is not None and chapaq_lambda >= 1.0:
133
+ lambda_flags.append("CHAPAQ verdict source returned lambda=%.3f (>= 1.0) - clamped to < 1.0 (G2/G7)" % chapaq_lambda)
134
+ display_lambda = raw_lambda if (raw_lambda is not None and raw_lambda < 1.0) else None
135
+ if display_lambda is None:
136
+ # fall back to clamped chapaq, else the advisory floor view
137
+ display_lambda = min(chapaq_lambda, LAMBDA_CAP) if chapaq_lambda is not None else None
138
+ if display_lambda is not None:
139
+ display_lambda = min(display_lambda, LAMBDA_CAP)
140
+
141
+ axes = (a_lambda or {}).get("axes", [])
142
+ checks_passing = sum(1 for x in axes if isinstance(x, dict) and x.get("score", 0) >= 0.9)
143
+
144
+ return {
145
+ "surface": "estate Lambda/KPI board",
146
+ "as_of": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
147
+ "label": "LIVE" if (a_honest and a_lambda) else "SAMPLE",
148
+ "locked8": locked_panel,
149
+ "lambda": {
150
+ "value": display_lambda,
151
+ "raw_a11oy": raw_lambda,
152
+ "raw_chapaq": chapaq_lambda,
153
+ "cap": LAMBDA_CAP,
154
+ "status": "Conjecture 1 (not a theorem)",
155
+ "trust_axes": len(axes),
156
+ "axes": axes,
157
+ "checks_passing": checks_passing,
158
+ "checks_total": len(axes),
159
+ "flags": lambda_flags,
160
+ "note": "Lambda-Aggregator Uniqueness is Conjecture 1; trust never 100%; displayed value clamped < 1.0.",
161
+ },
162
+ "apps": {
163
+ "a11oy": {"reachable": a_honest is not None, "role": "command & governance", "verdict_role": "CHAPAQ"},
164
+ "killinchu": {"reachable": chapaq is not None, "role": "C-UAS / maritime sensing"},
165
+ },
166
+ "chapaq_verdict": (chapaq or {}).get("data") if chapaq else None,
167
+ "doctrine": "v11",
168
+ }
169
+
170
+
171
+ def build_anatomy(ns: str) -> Dict[str, Any]:
172
+ """5-organ vitals for the unified living organism, fused from both apps.
173
+ organs: brain=proofs, heart=receipts/Lambda gate, nervous=MELT, skeleton=mesh,
174
+ circulatory=ledger. MELT is honestly IN-PROCESS (OTLP not exported)."""
175
+ a_honest = _get_json(A11OY_BASE + "/api/a11oy/v1/honest")
176
+ a_lambda = _get_json(A11OY_BASE + "/api/a11oy/v1/lambda")
177
+ a_obs = _get_json(A11OY_BASE + "/api/a11oy/v1/observability/summary")
178
+ a_mesh = _get_json(A11OY_BASE + "/api/a11oy/v1/capabilities/mesh")
179
+ k_led = _get_json(KILLINCHU_BASE + "/api/killinchu/v1/receipt/ledger")
180
+ a_led = _get_json(A11OY_BASE + "/api/a11oy/v1/provenance/ledger")
181
+
182
+ lock = (a_honest or {}).get("doctrine_lock", {}) if a_honest else {}
183
+ lam = None
184
+ if a_lambda and isinstance(a_lambda.get("lambda"), (int, float)):
185
+ lam = min(float(a_lambda["lambda"]), LAMBDA_CAP)
186
+
187
+ def health(reachable: bool) -> float:
188
+ return 0.96 if reachable else 0.0
189
+
190
+ organs = [
191
+ {
192
+ "organ": "brain", "system": "YACHAY cortex (proofs)", "maps_to": "Lean kernel + locked-8",
193
+ "label": "LIVE" if a_honest else "SAMPLE",
194
+ "vitals": {"locked8": 8 if (lock.get("locked_formula_count") == 8) else lock.get("locked_formula_count"),
195
+ "declarations": lock.get("declarations"), "axioms": lock.get("axioms"),
196
+ "sorries": lock.get("sorries"), "kernel": lock.get("commit")},
197
+ "health": health(a_honest is not None),
198
+ },
199
+ {
200
+ "organ": "heart", "system": "HEART / Lambda gate (deny-by-default)", "maps_to": "13-axis trust gate",
201
+ "label": "LIVE" if a_lambda else "SAMPLE",
202
+ "vitals": {"lambda": lam, "status": "Conjecture 1", "trust_axes": len((a_lambda or {}).get("axes", []))},
203
+ "health": health(a_lambda is not None),
204
+ },
205
+ {
206
+ "organ": "nervous", "system": "MELT (metrics/events/logs/traces)", "maps_to": "observability",
207
+ "label": "MODELED" if a_obs else "SAMPLE",
208
+ "vitals": {"otlp": "in-process (not exported to an external collector)",
209
+ "summary": (a_obs or {}).get("summary") if isinstance(a_obs, dict) else None},
210
+ "health": health(a_obs is not None),
211
+ "honest_note": "OTLP MELT is IN-PROCESS - not exported to an external collector (honest).",
212
+ },
213
+ {
214
+ "organ": "skeleton", "system": "szl-mesh topology", "maps_to": "cross-app fabric",
215
+ "label": "LIVE" if a_mesh else "MODELED",
216
+ "vitals": {"nodes": (a_mesh or {}).get("nodes") if isinstance(a_mesh, dict) else None},
217
+ "health": health(a_mesh is not None),
218
+ "honest_note": "tamper-evident, not tamper-proof (BFT safety = Conjecture 2).",
219
+ },
220
+ {
221
+ "organ": "circulatory", "system": "YAWAR receipt ledger (DSSE)", "maps_to": "cross-app unified ledger",
222
+ "label": "LIVE" if (a_led or k_led) else "SAMPLE",
223
+ "vitals": {"a11oy_receipts": (a_led or {}).get("count") if isinstance(a_led, dict) else None,
224
+ "killinchu_receipts": (k_led or {}).get("count") if isinstance(k_led, dict) else None,
225
+ "scheme": "ECDSA-P256-SHA256 / cosign"},
226
+ "health": health((a_led is not None) or (k_led is not None)),
227
+ },
228
+ ]
229
+ reach = [o for o in organs if o["health"] > 0]
230
+ return {
231
+ "surface": "anatomy-3D living organism",
232
+ "as_of": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
233
+ "label": "LIVE" if a_honest else "SAMPLE",
234
+ "organism": "a11oy + killinchu rendered as ONE governed body",
235
+ "organs": organs,
236
+ "organ_health": round(sum(o["health"] for o in organs) / max(1, len(organs)), 3),
237
+ "cross_app_coverage": "%d/%d organs reachable" % (len(reach), len(organs)),
238
+ "doctrine": "v11", "cdn": "0 (3D libs vendored locally)",
239
+ }
240
+
241
+
242
+ def build_mesh(ns: str) -> Dict[str, Any]:
243
+ """Cross-app szl-mesh fabric. a11oy<->killinchu link health + Fiedler lambda2.
244
+ MODELED where the inter-app link metric is simulated (honest)."""
245
+ a_mesh = _get_json(A11OY_BASE + "/api/a11oy/v1/capabilities/mesh")
246
+ a_reach = _get_json(A11OY_BASE + "/api/a11oy/v1/honest") is not None
247
+ k_reach = _get_json(KILLINCHU_BASE + "/api/killinchu/v1/gov/a11oy-honest") is not None
248
+ link_ok = a_reach and k_reach
249
+ # Fiedler lambda2 of the 2-node cross-app graph: MODELED indicator of link health.
250
+ fiedler = 0.62 if link_ok else 0.0
251
+ return {
252
+ "surface": "szl-mesh cross-app fabric",
253
+ "as_of": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
254
+ "label": "MODELED",
255
+ "nodes": [
256
+ {"id": "a11oy", "role": "command/governance brain", "reachable": a_reach, "health": 0.96 if a_reach else 0.0},
257
+ {"id": "killinchu", "role": "C-UAS/maritime sensing", "reachable": k_reach, "health": 0.96 if k_reach else 0.0},
258
+ ],
259
+ "link": {"a11oy<->killinchu": "up" if link_ok else "degraded",
260
+ "fiedler_lambda2": fiedler, "label": "MODELED",
261
+ "note": "inter-app link health is MODELED (cross-app message bus is simulated)."},
262
+ "bus": {"type": "DSSE receipt bus", "tamper": "tamper-evident, not tamper-proof (G3; Conjecture 2)"},
263
+ "intra_app_mesh": (a_mesh if isinstance(a_mesh, dict) else None),
264
+ "doctrine": "v11",
265
+ }
266
+
267
+
268
+ def build_ledger(ns: str) -> Dict[str, Any]:
269
+ """Cross-app unified DSSE ledger + the CROSS-APP COSIGN-CHAIN verify verdict.
270
+ The headline check: does the SAME cosign chain (keyid szlholdings-cosign) verify
271
+ across a11oy AND killinchu? Honest about ephemeral-key state until both apps hold
272
+ the canonical SZL_COSIGN_PRIVATE_PEM secret. NEVER fakes a MATCH."""
273
+ # Sign one probe receipt on each app, then verify each on the OTHER app.
274
+ a_env = _post_json(A11OY_BASE + "/khipu/sign", {"action": "ecosystem-xapp-probe", "data": {"src": "a11oy"}})
275
+ k_env = _post_json(KILLINCHU_BASE + "/khipu/sign",
276
+ {"action": "ecosystem-xapp-probe", "seq": 1, "prev_hash": "0"})
277
+
278
+ def keyid_of(env):
279
+ e = (env or {}).get("envelope", env) or {}
280
+ sigs = e.get("signatures") or []
281
+ return (sigs[0].get("keyid") if sigs else None)
282
+
283
+ a_keyid = keyid_of(a_env)
284
+ k_keyid = keyid_of(k_env)
285
+
286
+ # cross-app verify: verify killinchu's envelope on a11oy and vice-versa
287
+ a_env_inner = (a_env or {}).get("envelope", a_env)
288
+ k_env_inner = (k_env or {}).get("envelope", k_env)
289
+ k_on_a = _post_json(A11OY_BASE + "/khipu/verify", k_env_inner) if k_env_inner else None
290
+ a_on_k = _post_json(KILLINCHU_BASE + "/khipu/verify", a_env_inner) if a_env_inner else None
291
+
292
+ a_canonical = (a_keyid == COSIGN_KEYID)
293
+ k_canonical = (k_keyid == COSIGN_KEYID)
294
+ same_chain = bool(a_canonical and k_canonical and (k_on_a or {}).get("verified") is True)
295
+
296
+ return {
297
+ "surface": "cross-app unified DSSE ledger",
298
+ "as_of": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
299
+ "label": "LIVE" if (a_env and k_env) else "SAMPLE",
300
+ "scheme": "ECDSA-P256-SHA256 / cosign (the single estate signing scheme)",
301
+ "cosign_keyid": COSIGN_KEYID,
302
+ "cosign_pub_url": COSIGN_PUB_URL,
303
+ "a11oy_signer": {"keyid": a_keyid, "canonical": a_canonical},
304
+ "killinchu_signer": {"keyid": k_keyid, "canonical": k_canonical},
305
+ "cross_app_verify": {
306
+ "killinchu_env_on_a11oy": (k_on_a or {}).get("verified"),
307
+ "a11oy_env_on_killinchu": (a_on_k or {}).get("verified"),
308
+ "same_cosign_chain": same_chain,
309
+ },
310
+ "verdict": "SAME cosign chain verifies across both apps" if same_chain
311
+ else "cross-app chain PENDING: killinchu signs with key '%s' (not canonical '%s'). Set the SZL_COSIGN_PRIVATE_PEM Space secret on killinchu to unify the chain. NEVER faked." % (k_keyid, COSIGN_KEYID),
312
+ "tamper": "tamper-evident, not tamper-proof (G3)",
313
+ "pqc": "roadmap-only (G4) - never shown as deployed",
314
+ "doctrine": "v11",
315
+ }
316
+
317
+
318
+ # ---------------------------------------------------------------------------
319
+ # HTML surfaces (vendored 3D, 0 CDN). Shared label engine pills via the served JS.
320
+ # ---------------------------------------------------------------------------
321
+ def _anatomy_html(ns: str) -> str:
322
+ # Tries vendored three.module.min.js (a11oy) then static-vendor/three.min.js.
323
+ return """<!doctype html><html lang="en"><head><meta charset="utf-8">
324
+ <meta name="viewport" content="width=device-width,initial-scale=1">
325
+ <title>SZL Estate - Living Organism (a11oy + killinchu)</title>
326
+ <link rel="stylesheet" href="/static/shared/szl_label_engine.css" onerror="this.remove()">
327
+ <style>
328
+ :root{--bg:#070b10;--panel:#0d141c;--line:#1b2733;--ink:#dbe7f2;--mut:#7d93a6;--ok:#16c784;--warn:#e0a106;--info:#3aa0ff;--sim:#b07cff}
329
+ *{box-sizing:border-box}body{margin:0;background:radial-gradient(1200px 800px at 70% -10%,#0e1a26,#070b10);color:var(--ink);font:14px/1.5 ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
330
+ header{padding:18px 22px;border-bottom:1px solid var(--line);display:flex;align-items:center;gap:14px;flex-wrap:wrap}
331
+ h1{font-size:18px;margin:0;letter-spacing:.02em}.sub{color:var(--mut);font-size:12px}
332
+ .wrap{display:grid;grid-template-columns:1fr 360px;gap:0;height:calc(100vh - 64px)}
333
+ #stage{position:relative}#c{width:100%;height:100%;display:block}
334
+ aside{border-left:1px solid var(--line);overflow:auto;padding:16px;background:var(--panel)}
335
+ .organ{border:1px solid var(--line);border-radius:10px;padding:12px;margin-bottom:10px;background:#0b121a}
336
+ .organ h3{margin:0 0 6px;font-size:13px;display:flex;justify-content:space-between;align-items:center;gap:8px}
337
+ .kv{display:flex;justify-content:space-between;font-size:12px;color:var(--mut);padding:2px 0}
338
+ .kv b{color:var(--ink);font-weight:600}
339
+ .bar{height:6px;border-radius:4px;background:#16202b;overflow:hidden;margin-top:6px}
340
+ .bar>i{display:block;height:100%;background:linear-gradient(90deg,var(--ok),var(--info))}
341
+ .note{font-size:11px;color:var(--warn);margin-top:6px}
342
+ footer{padding:10px 16px;border-top:1px solid var(--line);font-size:11px;color:var(--mut)}
343
+ .pill{font:700 10px/1 ui-monospace,monospace;letter-spacing:.05em;padding:3px 7px;border-radius:6px;border:1px solid;text-transform:uppercase}
344
+ .pill.LIVE{color:var(--ok);border-color:var(--ok)}.pill.SAMPLE{color:var(--info);border-color:var(--info)}
345
+ .pill.MODELED{color:var(--warn);border-color:var(--warn)}.pill.SIMULATED{color:var(--sim);border-color:var(--sim)}
346
+ </style></head><body>
347
+ <header><h1>SZL Estate &mdash; One Governed Organism</h1>
348
+ <span class="pill LIVE" id="toplabel">LIVE</span>
349
+ <span class="sub">a11oy + killinchu rendered as a single body &middot; MELT-fed vitals &middot; 0 CDN (vendored 3D) &middot; Doctrine v11</span></header>
350
+ <div class="wrap"><div id="stage"><canvas id="c"></canvas></div>
351
+ <aside><div id="organs"><div class="organ"><h3>loading estate vitals&hellip;</h3></div></div>
352
+ <div style="font-size:11px;color:var(--mut);margin-top:8px">Lambda = Conjecture 1 (not a theorem) &middot; trust never 100% &middot; tamper-evident, not tamper-proof &middot; effectors SIMULATED.</div>
353
+ </aside></div>
354
+ <footer id="foot">Doctrine v11 &middot; locked-8 {F1,F4,F7,F11,F12,F18,F19,F22}@c7c0ba17 &middot; SLSA L1 honest / L2 attested / L3 roadmap</footer>
355
+ <script>
356
+ var NS="__NS__";
357
+ function vendorThree(srcs,cb){ (function next(i){ if(i>=srcs.length){cb(false);return;} var s=document.createElement('script'); s.src=srcs[i]; s.onload=function(){cb(true);}; s.onerror=function(){next(i+1);}; document.head.appendChild(s); })(0); }
358
+ function organCard(o){
359
+ var pct=Math.round((o.health||0)*100);
360
+ var v=o.vitals||{}; var rows='';
361
+ for(var k in v){ if(v[k]===null||v[k]===undefined||typeof v[k]==='object')continue; rows+='<div class="kv"><span>'+k+'</span><b>'+v[k]+'</b></div>'; }
362
+ return '<div class="organ"><h3>'+o.organ.toUpperCase()+' <span class="pill '+(o.label||'SAMPLE')+'">'+(o.label||'SAMPLE')+'</span></h3>'+
363
+ '<div class="sub" style="font-size:11px;color:#7d93a6">'+(o.system||'')+'</div>'+rows+
364
+ '<div class="bar"><i style="width:'+pct+'%"></i></div>'+
365
+ (o.honest_note?'<div class="note">'+o.honest_note+'</div>':'')+'</div>';
366
+ }
367
+ fetch('/api/'+NS+'/v1/ecosystem/anatomy').then(function(r){return r.json();}).then(function(d){
368
+ document.getElementById('toplabel').textContent=d.label||'SAMPLE';
369
+ document.getElementById('toplabel').className='pill '+(d.label||'SAMPLE');
370
+ document.getElementById('organs').innerHTML=(d.organs||[]).map(organCard).join('');
371
+ document.getElementById('foot').textContent='Doctrine v11 · organ health '+(d.organ_health!=null?Math.round(d.organ_health*100)+'%':'n/a')+' · '+(d.cross_app_coverage||'')+' · SLSA L1 honest / L2 attested / L3 roadmap';
372
+ draw3D(d);
373
+ }).catch(function(e){ document.getElementById('organs').innerHTML='<div class="organ"><h3>vitals unreachable (honest)</h3><div class="note">'+e.message+'</div></div>'; });
374
+ function draw3D(d){
375
+ vendorThree(['/static/vendor3d/three.module.min.js','/static-vendor/three.min.js'],function(ok){
376
+ var cv=document.getElementById('c'); var THREE=window.THREE;
377
+ if(!ok||!THREE){ var ctx=cv.getContext('2d'); cv.width=cv.clientWidth;cv.height=cv.clientHeight; if(ctx){ctx.fillStyle='#7d93a6';ctx.font='13px sans-serif';ctx.fillText('3D vendor unavailable - vitals shown at right (honest fallback).',20,30);} return; }
378
+ var sc=new THREE.Scene(); var cam=new THREE.PerspectiveCamera(55,cv.clientWidth/cv.clientHeight,0.1,100); cam.position.z=7;
379
+ var rnd=new THREE.WebGLRenderer({canvas:cv,antialias:true,alpha:true}); rnd.setSize(cv.clientWidth,cv.clientHeight);
380
+ var organs=d.organs||[]; var meshes=[];
381
+ var pos=[[0,2.1,0],[0,0.6,0],[1.9,-0.2,0],[-1.9,-0.2,0],[0,-1.9,0]];
382
+ var col=[0x16c784,0xff5c5c,0x3aa0ff,0xb07cff,0xe0a106];
383
+ organs.forEach(function(o,i){ var g=new THREE.SphereGeometry(0.55+0.35*(o.health||0.3),24,24);
384
+ var m=new THREE.MeshBasicMaterial({color:col[i%col.length],wireframe:true,transparent:true,opacity:0.35+0.5*(o.health||0)});
385
+ var sp=new THREE.Mesh(g,m); var p=pos[i%pos.length]; sp.position.set(p[0],p[1],p[2]); sc.add(sp); meshes.push(sp);
386
+ });
387
+ // connective tissue (skeleton/mesh) - lines between organs = one body
388
+ var lm=new THREE.LineBasicMaterial({color:0x1b2733});
389
+ for(var i=1;i<meshes.length;i++){ var gg=new THREE.BufferGeometry().setFromPoints([meshes[0].position,meshes[i].position]); sc.add(new THREE.Line(gg,lm)); }
390
+ (function anim(){ requestAnimationFrame(anim); meshes.forEach(function(m,i){m.rotation.y+=0.004+0.002*i;m.rotation.x+=0.002;}); sc.rotation.y+=0.0015; rnd.render(sc,cam); })();
391
+ window.addEventListener('resize',function(){ cam.aspect=cv.clientWidth/cv.clientHeight; cam.updateProjectionMatrix(); rnd.setSize(cv.clientWidth,cv.clientHeight); });
392
+ });
393
+ }
394
+ </script></body></html>""".replace("__NS__", ns)
395
+
396
+
397
+ def _hub_html(ns: str) -> str:
398
+ return """<!doctype html><html lang="en"><head><meta charset="utf-8">
399
+ <meta name="viewport" content="width=device-width,initial-scale=1"><title>SZL Estate - Ecosystem</title>
400
+ <style>body{margin:0;background:#070b10;color:#dbe7f2;font:15px/1.6 ui-sans-serif,system-ui,sans-serif;padding:28px}
401
+ h1{font-size:20px}a{color:#3aa0ff;text-decoration:none}.card{border:1px solid #1b2733;border-radius:12px;padding:18px;margin:12px 0;background:#0d141c;max-width:760px}
402
+ .card h2{margin:0 0 6px;font-size:15px}.mut{color:#7d93a6;font-size:13px}code{color:#16c784}</style></head><body>
403
+ <h1>SZL Estate &mdash; Ecosystem Foundation</h1>
404
+ <p class="mut">The connective tissue spanning a11oy + killinchu. Doctrine v11. 0 CDN. Lambda = Conjecture 1.</p>
405
+ <div class="card"><h2><a href="/estate-organism">3D Living Organism &rarr;</a></h2><div class="mut">Both apps as ONE body; 5 organs (brain/heart/nervous/skeleton/circulatory); MELT-fed vitals.</div></div>
406
+ <div class="card"><h2>Estate Lambda / KPI board</h2><div class="mut"><code>GET /api/__NS__/v1/ecosystem/kpi-board</code> &mdash; locked-8 EXACTLY 8 @ c7c0ba17; Lambda &lt; 1.0; CHAPAQ verdict.</div></div>
407
+ <div class="card"><h2>Cross-app unified DSSE ledger</h2><div class="mut"><code>GET /api/__NS__/v1/ecosystem/ledger</code> &mdash; verifies the SAME cosign chain across both apps (ECDSA-P256).</div></div>
408
+ <div class="card"><h2>szl-mesh cross-app fabric</h2><div class="mut"><code>GET /api/__NS__/v1/ecosystem/mesh</code> &mdash; a11oy&harr;killinchu link health; Fiedler lambda2; tamper-evident bus.</div></div>
409
+ </body></html>""".replace("__NS__", ns)
410
+
411
+
412
+ # ---------------------------------------------------------------------------
413
+ # Registration (single integration point)
414
+ # ---------------------------------------------------------------------------
415
+ def register(app, ns: str = "a11oy") -> None:
416
+ if HTMLResponse is None: # not a FastAPI host
417
+ return
418
+
419
+ @app.get("/ecosystem", response_class=HTMLResponse)
420
+ def _eco_hub(): # noqa: ANN202
421
+ return HTMLResponse(_hub_html(ns))
422
+
423
+ @app.get("/estate-organism", response_class=HTMLResponse)
424
+ def _eco_anatomy(): # noqa: ANN202
425
+ return HTMLResponse(_anatomy_html(ns))
426
+
427
+ @app.get("/api/%s/v1/ecosystem/anatomy" % ns)
428
+ def _eco_anatomy_json(): # noqa: ANN202
429
+ return JSONResponse(build_anatomy(ns))
430
+
431
+ @app.get("/api/%s/v1/ecosystem/mesh" % ns)
432
+ def _eco_mesh_json(): # noqa: ANN202
433
+ return JSONResponse(build_mesh(ns))
434
+
435
+ @app.get("/api/%s/v1/ecosystem/ledger" % ns)
436
+ def _eco_ledger_json(): # noqa: ANN202
437
+ return JSONResponse(build_ledger(ns))
438
+
439
+ @app.get("/api/%s/v1/ecosystem/kpi-board" % ns)
440
+ def _eco_kpi_json(): # noqa: ANN202
441
+ return JSONResponse(build_kpi_board(ns))