Spaces:
Running
Running
chore(sync): mirror backend .py + Dockerfile to Space (hf-sync-backend)
Browse filesAutomated backend sync from szl-holdings/a11oy main via hf-sync-backend.
Updated (differed from the Space): Dockerfile, a11oy_quant_signals.py, a11oy_quant_signals_nav.py, serve.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.
- Dockerfile +9 -0
- a11oy_quant_signals.py +608 -0
- a11oy_quant_signals_nav.py +172 -0
- serve.py +23 -0
Dockerfile
CHANGED
|
@@ -1640,6 +1640,15 @@ COPY a11oy_khipu_demo_traces.json ./a11oy_khipu_demo_traces.json
|
|
| 1640 |
# missing. Idempotent BaseHTTPMiddleware; edits no SPA source; 0 CDN.
|
| 1641 |
COPY a11oy_khipu_demo_nav.py ./a11oy_khipu_demo_nav.py
|
| 1642 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1643 |
# git_sha wireup (FORGE-INSTRUCTION-gitsha-quiet-window): surface the deployed commit
|
| 1644 |
# at the /honest endpoint so a stale box or Space is self-detecting. Provided at build
|
| 1645 |
# time (box rebuild passes --build-arg SZL_GIT_SHA=$(git rev-parse HEAD); HF Space sets
|
|
|
|
| 1640 |
# missing. Idempotent BaseHTTPMiddleware; edits no SPA source; 0 CDN.
|
| 1641 |
COPY a11oy_khipu_demo_nav.py ./a11oy_khipu_demo_nav.py
|
| 1642 |
|
| 1643 |
+
# QUANT SIGNALS WALL (2026-07-16): /api/quant/signals + /signals — the quant
|
| 1644 |
+
# engine's DSSE-signed ADVISORY / PAPER-ONLY receipts (szl-holdings/szl-quant
|
| 1645 |
+
# @main), re-verified server-side per request against a PINNED ed25519 key. No
|
| 1646 |
+
# new deps (httpx + cryptography already in the image). Module + its idempotent
|
| 1647 |
+
# nav injector; the nav MUST be COPY'd or serve.py's guarded import falls back
|
| 1648 |
+
# and the /signals nav item is missing. Both edit no SPA source; 0 CDN.
|
| 1649 |
+
COPY a11oy_quant_signals.py ./a11oy_quant_signals.py
|
| 1650 |
+
COPY a11oy_quant_signals_nav.py ./a11oy_quant_signals_nav.py
|
| 1651 |
+
|
| 1652 |
# git_sha wireup (FORGE-INSTRUCTION-gitsha-quiet-window): surface the deployed commit
|
| 1653 |
# at the /honest endpoint so a stale box or Space is self-detecting. Provided at build
|
| 1654 |
# time (box rebuild passes --build-arg SZL_GIT_SHA=$(git rev-parse HEAD); HF Space sets
|
a11oy_quant_signals.py
ADDED
|
@@ -0,0 +1,608 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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wall — GET /api/quant/signals + GET /signals
|
| 5 |
+
|
| 6 |
+
The public, visitor-reachable evidence wall for the doctrine-governed quant
|
| 7 |
+
engine (szl-holdings/szl-quant@main). Every signal and backtest ships as a
|
| 8 |
+
DSSE envelope; this module re-verifies each envelope's ed25519 signature
|
| 9 |
+
SERVER-SIDE on every request against a PINNED engine key and renders the
|
| 10 |
+
result honestly.
|
| 11 |
+
|
| 12 |
+
HONESTY DOCTRINE (law — labels only REDUCE claims):
|
| 13 |
+
* The signals are ADVISORY_PAPER_ONLY research artifacts. There is NO
|
| 14 |
+
execution, NO custody, and this is NOT financial advice — those code
|
| 15 |
+
paths do not exist upstream.
|
| 16 |
+
* Signature verification proves INTEGRITY + ORIGIN only. A green VERIFIED
|
| 17 |
+
badge means "this receipt's bytes were signed by the pinned engine key
|
| 18 |
+
and have not been tampered with" — it is NEVER a claim of accuracy,
|
| 19 |
+
profitability, or that any signal will make money.
|
| 20 |
+
* Λ (Lambda) is "Conjecture 1 (open)", NEVER a theorem. Λ roll-ups are
|
| 21 |
+
advisory only.
|
| 22 |
+
* The receipt's own _doctrine.disclaimer text is reproduced VERBATIM on
|
| 23 |
+
the page banner — never paraphrased.
|
| 24 |
+
|
| 25 |
+
Verification detail (mirrors a11oy_forge_family.py's server-side, fail-closed,
|
| 26 |
+
key-pinned design; reuses the image's `cryptography` lib — no new deps):
|
| 27 |
+
* DSSE PAE = b"DSSEv1 " + len(payloadType) + " " + payloadType + " " +
|
| 28 |
+
len(payload_bytes) + " " + payload_bytes (lengths as ASCII decimals,
|
| 29 |
+
single spaces). ed25519-verify each envelope signature over the PAE.
|
| 30 |
+
* The key used to verify is the PINNED engine key, NOT the envelope's
|
| 31 |
+
embedded publicKeySpkiBase64. Pin source: env A11OY_QUANT_ENGINE_KEYID
|
| 32 |
+
(expected keyId). We compute keyId = sha256(SPKI DER)[:16 hex] from the
|
| 33 |
+
fetched keys/engine_pubkey.json and REQUIRE it to equal the env pin AND
|
| 34 |
+
require the envelope's embedded SPKI to equal the fetched one. Any
|
| 35 |
+
mismatch, or a missing env pin, renders FAIL-CLOSED ("pin not configured
|
| 36 |
+
/ mismatch") — never a green check.
|
| 37 |
+
|
| 38 |
+
On fetch failure the wall fails CLOSED with an honest "receipts unavailable"
|
| 39 |
+
page / JSON — it never serves stale bytes as fresh and never invents a result.
|
| 40 |
+
Receipt BYTES are cached ~300s to spare the raw host; the cryptographic
|
| 41 |
+
verification itself runs on every request and is never cached or skipped.
|
| 42 |
+
|
| 43 |
+
Additive module per Space convention: register(app) adds both routes and
|
| 44 |
+
front-moves them so the exact paths win over the SPA history fallback.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
import base64
|
| 48 |
+
import hashlib
|
| 49 |
+
import html
|
| 50 |
+
import json
|
| 51 |
+
import os
|
| 52 |
+
import time
|
| 53 |
+
from datetime import datetime, timezone
|
| 54 |
+
|
| 55 |
+
import httpx
|
| 56 |
+
from cryptography.hazmat.primitives.serialization import load_der_public_key
|
| 57 |
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
| 58 |
+
|
| 59 |
+
_API_ROUTE = "/api/quant/signals"
|
| 60 |
+
_PAGE_ROUTE = "/signals"
|
| 61 |
+
|
| 62 |
+
_RAW = "https://raw.githubusercontent.com/szl-holdings/szl-quant/main"
|
| 63 |
+
_SOURCE = "szl-holdings/szl-quant@main"
|
| 64 |
+
_PUBKEY_FILE = "keys/engine_pubkey.json"
|
| 65 |
+
_PIN_ENV = "A11OY_QUANT_ENGINE_KEYID"
|
| 66 |
+
_CACHE_TTL_SECONDS = 300 # receipt BYTES only; verification always re-runs
|
| 67 |
+
|
| 68 |
+
# The signal_* and backtest_* receipt sets (source of truth). raw.githubusercontent
|
| 69 |
+
# needs the literal names; "$" is percent-encoded in the URL path only.
|
| 70 |
+
_RECEIPT_NAMES = (
|
| 71 |
+
"signal_SOL_1784088245451.receipt.json",
|
| 72 |
+
"signal_JUP_1784088245451.receipt.json",
|
| 73 |
+
"signal_Bonk_1784088245451.receipt.json",
|
| 74 |
+
"signal_$WIF_1784088245451.receipt.json",
|
| 75 |
+
"backtest_BTC_365d.receipt.json",
|
| 76 |
+
"backtest_ETH_365d.receipt.json",
|
| 77 |
+
"backtest_SOL_365d.receipt.json",
|
| 78 |
+
"backtest_BONK_365d.receipt.json",
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
# Independent, offline verifier one-liner published by the repo itself.
|
| 82 |
+
_VERIFY_CMD = "node verify/verify.mjs --pubkey keys/engine_pubkey.json --dir receipts/"
|
| 83 |
+
_REPO_URL = "https://github.com/szl-holdings/szl-quant"
|
| 84 |
+
|
| 85 |
+
# Estate palette (Doctrine): dark background + teal / blue / gold accents.
|
| 86 |
+
_BG = "#0a0e12"
|
| 87 |
+
_PANEL = "#0f151b"
|
| 88 |
+
_TEAL = "#3af4c8"
|
| 89 |
+
_BLUE = "#5b8dee"
|
| 90 |
+
_GOLD = "#d7b96b"
|
| 91 |
+
_INK = "#c9d6e2"
|
| 92 |
+
_MUTE = "#7d93a6"
|
| 93 |
+
|
| 94 |
+
# name -> {"at": epoch, "bytes": bytes} (receipt bytes only)
|
| 95 |
+
_byte_cache: dict = {}
|
| 96 |
+
# engine pubkey bytes cache: {"at": epoch, "bytes": bytes}
|
| 97 |
+
_pubkey_cache: dict = {}
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _now_iso() -> str:
|
| 101 |
+
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _sha256_hex(data: bytes) -> str:
|
| 105 |
+
return hashlib.sha256(data).hexdigest()
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _url_for(name: str) -> str:
|
| 109 |
+
"""raw.githubusercontent URL; percent-encode '$' in the path segment only."""
|
| 110 |
+
return f"{_RAW}/receipts/{name.replace('$', '%24')}"
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _dsse_pae(payload_type: str, payload_bytes: bytes) -> bytes:
|
| 114 |
+
"""DSSE Pre-Authentication Encoding, spec-exact:
|
| 115 |
+
b"DSSEv1 " + len(payloadType) + " " + payloadType + " " +
|
| 116 |
+
len(payload_bytes) + " " + payload_bytes (lengths as ASCII decimals)."""
|
| 117 |
+
pt = payload_type.encode("utf-8")
|
| 118 |
+
return (
|
| 119 |
+
b"DSSEv1 "
|
| 120 |
+
+ str(len(pt)).encode("ascii") + b" "
|
| 121 |
+
+ pt + b" "
|
| 122 |
+
+ str(len(payload_bytes)).encode("ascii") + b" "
|
| 123 |
+
+ payload_bytes
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
async def _fetch_bytes(client: httpx.AsyncClient, url: str) -> bytes:
|
| 128 |
+
resp = await client.get(url)
|
| 129 |
+
resp.raise_for_status()
|
| 130 |
+
return resp.content
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
async def _fetch_pubkey_bytes(client: httpx.AsyncClient) -> bytes:
|
| 134 |
+
cached = _pubkey_cache.get("k")
|
| 135 |
+
if cached and (time.time() - cached["at"]) < _CACHE_TTL_SECONDS:
|
| 136 |
+
return cached["bytes"]
|
| 137 |
+
data = await _fetch_bytes(client, f"{_RAW}/{_PUBKEY_FILE}")
|
| 138 |
+
_pubkey_cache["k"] = {"at": time.time(), "bytes": data}
|
| 139 |
+
return data
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
async def _fetch_receipt_bytes(client: httpx.AsyncClient, name: str) -> bytes:
|
| 143 |
+
cached = _byte_cache.get(name)
|
| 144 |
+
if cached and (time.time() - cached["at"]) < _CACHE_TTL_SECONDS:
|
| 145 |
+
return cached["bytes"]
|
| 146 |
+
data = await _fetch_bytes(client, _url_for(name))
|
| 147 |
+
_byte_cache[name] = {"at": time.time(), "bytes": data}
|
| 148 |
+
return data
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _resolve_pin(pubkey_bytes: bytes) -> dict:
|
| 152 |
+
"""Fail-closed key pinning. Returns the pinned-key context; pinOk is False
|
| 153 |
+
(and a reason is given) whenever the env pin is missing or does not match
|
| 154 |
+
the keyId derived from the fetched engine_pubkey.json."""
|
| 155 |
+
key = json.loads(pubkey_bytes)
|
| 156 |
+
fetched_spki_b64 = key.get("publicKeySpkiBase64", "")
|
| 157 |
+
declared_key_id = key.get("keyId", "")
|
| 158 |
+
algo = key.get("alg") or key.get("algo")
|
| 159 |
+
|
| 160 |
+
derived_key_id = ""
|
| 161 |
+
try:
|
| 162 |
+
derived_key_id = _sha256_hex(base64.b64decode(fetched_spki_b64, validate=True))[:16]
|
| 163 |
+
except Exception:
|
| 164 |
+
derived_key_id = ""
|
| 165 |
+
|
| 166 |
+
env_pin = os.environ.get(_PIN_ENV, "").strip()
|
| 167 |
+
|
| 168 |
+
if algo != "ed25519":
|
| 169 |
+
return {"pinOk": False, "reason": "engine key algorithm is not ed25519",
|
| 170 |
+
"keyId": derived_key_id, "spkiB64": fetched_spki_b64, "envPin": env_pin}
|
| 171 |
+
if not derived_key_id or derived_key_id != declared_key_id:
|
| 172 |
+
return {"pinOk": False,
|
| 173 |
+
"reason": "engine keyId does not derive from its SPKI (sha256(SPKI)[:16] mismatch)",
|
| 174 |
+
"keyId": derived_key_id, "spkiB64": fetched_spki_b64, "envPin": env_pin}
|
| 175 |
+
if not env_pin:
|
| 176 |
+
return {"pinOk": False,
|
| 177 |
+
"reason": f"pin not configured: env {_PIN_ENV} is unset (fail-closed)",
|
| 178 |
+
"keyId": derived_key_id, "spkiB64": fetched_spki_b64, "envPin": env_pin}
|
| 179 |
+
if env_pin != derived_key_id:
|
| 180 |
+
return {"pinOk": False,
|
| 181 |
+
"reason": f"pin mismatch: env {_PIN_ENV}={env_pin} != engine keyId {derived_key_id} (fail-closed)",
|
| 182 |
+
"keyId": derived_key_id, "spkiB64": fetched_spki_b64, "envPin": env_pin}
|
| 183 |
+
return {"pinOk": True, "reason": "pinned", "keyId": derived_key_id,
|
| 184 |
+
"spkiB64": fetched_spki_b64, "envPin": env_pin}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _verify_envelope(raw: bytes, pin: dict) -> dict:
|
| 188 |
+
"""Verify one DSSE envelope against the PINNED key. Fail-closed.
|
| 189 |
+
|
| 190 |
+
verified is True only when: the pin is OK, the envelope's embedded SPKI
|
| 191 |
+
equals the fetched engine SPKI, and at least one signature verifies over
|
| 192 |
+
the spec-exact PAE with the pinned key."""
|
| 193 |
+
envelope = json.loads(raw)
|
| 194 |
+
payload_type = envelope.get("payloadType", "")
|
| 195 |
+
payload_b64 = envelope.get("payload", "")
|
| 196 |
+
signatures = envelope.get("signatures") or []
|
| 197 |
+
embedded_spki = envelope.get("publicKeySpkiBase64", "")
|
| 198 |
+
|
| 199 |
+
checks = {
|
| 200 |
+
"pinConfiguredAndMatches": bool(pin.get("pinOk")),
|
| 201 |
+
"payloadTypeIsInToto": payload_type == "application/vnd.in-toto+json",
|
| 202 |
+
"embeddedSpkiMatchesPinned": bool(embedded_spki) and embedded_spki == pin.get("spkiB64"),
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
sig_ok = False
|
| 206 |
+
sig_keyid = ""
|
| 207 |
+
try:
|
| 208 |
+
payload_bytes = base64.b64decode(payload_b64, validate=True)
|
| 209 |
+
except Exception:
|
| 210 |
+
payload_bytes = b""
|
| 211 |
+
if pin.get("pinOk") and checks["embeddedSpkiMatchesPinned"] and payload_bytes:
|
| 212 |
+
try:
|
| 213 |
+
spki_der = base64.b64decode(pin["spkiB64"], validate=True)
|
| 214 |
+
public_key = load_der_public_key(spki_der)
|
| 215 |
+
if isinstance(public_key, Ed25519PublicKey):
|
| 216 |
+
pae = _dsse_pae(payload_type, payload_bytes)
|
| 217 |
+
for sig in signatures:
|
| 218 |
+
try:
|
| 219 |
+
public_key.verify(base64.b64decode(sig.get("sig", ""), validate=True), pae)
|
| 220 |
+
sig_ok = True
|
| 221 |
+
sig_keyid = sig.get("keyid", "") or sig_keyid
|
| 222 |
+
break
|
| 223 |
+
except Exception:
|
| 224 |
+
continue
|
| 225 |
+
except Exception:
|
| 226 |
+
sig_ok = False
|
| 227 |
+
checks["ed25519SignatureVerifiesWithPinnedKey"] = sig_ok
|
| 228 |
+
|
| 229 |
+
payload = {}
|
| 230 |
+
try:
|
| 231 |
+
payload = json.loads(payload_bytes.decode("utf-8")) if payload_bytes else {}
|
| 232 |
+
except Exception:
|
| 233 |
+
payload = {}
|
| 234 |
+
|
| 235 |
+
verified = all(checks.values())
|
| 236 |
+
return {
|
| 237 |
+
"verified": verified,
|
| 238 |
+
"checks": checks,
|
| 239 |
+
"sigKeyId": sig_keyid or (signatures[0].get("keyid", "") if signatures else ""),
|
| 240 |
+
"envelope": envelope,
|
| 241 |
+
"payload": payload,
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _summarize(payload: dict) -> dict:
|
| 246 |
+
"""Extract the honest highlights that ARE in the predicate — show, never
|
| 247 |
+
editorialize. Different predicate types carry different fields."""
|
| 248 |
+
predicate_type = payload.get("predicateType", "")
|
| 249 |
+
subjects = payload.get("subject") or []
|
| 250 |
+
subject_name = subjects[0].get("name", "") if subjects else ""
|
| 251 |
+
subject_sha = (subjects[0].get("digest") or {}).get("sha256", "") if subjects else ""
|
| 252 |
+
predicate = payload.get("predicate") or {}
|
| 253 |
+
doctrine = predicate.get("_doctrine") or {}
|
| 254 |
+
|
| 255 |
+
summary = {
|
| 256 |
+
"predicateType": predicate_type,
|
| 257 |
+
"subject": subject_name,
|
| 258 |
+
"subjectSha256": subject_sha,
|
| 259 |
+
}
|
| 260 |
+
if "signal" in predicate_type:
|
| 261 |
+
decision = predicate.get("decision") or {}
|
| 262 |
+
asset = decision.get("asset") or {}
|
| 263 |
+
summary["kind"] = "signal"
|
| 264 |
+
summary["asset"] = asset.get("symbol", "")
|
| 265 |
+
summary["chain"] = asset.get("chain", "")
|
| 266 |
+
summary["proposedAction"] = decision.get("proposedAction", "")
|
| 267 |
+
summary["verdict"] = decision.get("verdict", "")
|
| 268 |
+
summary["conviction"] = decision.get("conviction")
|
| 269 |
+
summary["blockedBy"] = decision.get("blockedBy") or []
|
| 270 |
+
elif "backtest" in predicate_type:
|
| 271 |
+
smry = predicate.get("summary") or {}
|
| 272 |
+
asset = smry.get("asset") or {}
|
| 273 |
+
wf = smry.get("walkForward") or {}
|
| 274 |
+
summary["kind"] = "backtest"
|
| 275 |
+
summary["asset"] = asset.get("symbol", "")
|
| 276 |
+
summary["populationSize"] = wf.get("populationSize")
|
| 277 |
+
summary["outOfSampleBars"] = wf.get("outOfSampleBars")
|
| 278 |
+
else:
|
| 279 |
+
summary["kind"] = "unknown"
|
| 280 |
+
return {"summary": summary, "doctrine": doctrine}
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
async def _collect() -> dict:
|
| 284 |
+
"""Fetch + verify every receipt. Fail-closed on any fetch failure — never
|
| 285 |
+
serve stale-as-fresh, never invent a result."""
|
| 286 |
+
async with httpx.AsyncClient(timeout=10.0, follow_redirects=True) as client:
|
| 287 |
+
pubkey_bytes = await _fetch_pubkey_bytes(client)
|
| 288 |
+
pin = _resolve_pin(pubkey_bytes)
|
| 289 |
+
receipts = []
|
| 290 |
+
for name in _RECEIPT_NAMES:
|
| 291 |
+
raw = await _fetch_receipt_bytes(client, name)
|
| 292 |
+
result = _verify_envelope(raw, pin)
|
| 293 |
+
extra = _summarize(result["payload"])
|
| 294 |
+
receipts.append({
|
| 295 |
+
"name": name,
|
| 296 |
+
"verified": result["verified"],
|
| 297 |
+
"checks": result["checks"],
|
| 298 |
+
"keyId": result["sigKeyId"],
|
| 299 |
+
"summary": extra["summary"],
|
| 300 |
+
"doctrine": extra["doctrine"],
|
| 301 |
+
"envelope": result["envelope"],
|
| 302 |
+
"payload": result["payload"],
|
| 303 |
+
"receiptSha256": _sha256_hex(raw),
|
| 304 |
+
})
|
| 305 |
+
return {"pin": pin, "receipts": receipts}
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
# ---------------------------------------------------------------------------
|
| 309 |
+
# JSON API
|
| 310 |
+
# ---------------------------------------------------------------------------
|
| 311 |
+
async def _signals_api():
|
| 312 |
+
try:
|
| 313 |
+
data = await _collect()
|
| 314 |
+
pin = data["pin"]
|
| 315 |
+
return {
|
| 316 |
+
"ok": pin["pinOk"] and all(r["verified"] for r in data["receipts"]),
|
| 317 |
+
"wall": "quant-signals",
|
| 318 |
+
"source": _SOURCE,
|
| 319 |
+
"pinnedKeyId": pin["keyId"] if pin["pinOk"] else None,
|
| 320 |
+
"pinStatus": pin["reason"],
|
| 321 |
+
"posture": "ADVISORY_PAPER_ONLY — no execution, no custody, NOT financial advice",
|
| 322 |
+
"note": "Signature verification proves INTEGRITY + ORIGIN only — never accuracy or profitability.",
|
| 323 |
+
"verifier": {
|
| 324 |
+
"mode": "DSSE PAE + ed25519 via cryptography, server-side, pinned key",
|
| 325 |
+
"perRequest": True,
|
| 326 |
+
"note": "receipt bytes cached briefly; verification never cached; fail-closed",
|
| 327 |
+
"independentCommand": _VERIFY_CMD,
|
| 328 |
+
},
|
| 329 |
+
"fetchedAt": _now_iso(),
|
| 330 |
+
"receipts": [
|
| 331 |
+
{
|
| 332 |
+
"name": r["name"],
|
| 333 |
+
"verified": r["verified"],
|
| 334 |
+
"keyId": r["keyId"],
|
| 335 |
+
"checks": r["checks"],
|
| 336 |
+
"summary": r["summary"],
|
| 337 |
+
"doctrine": r["doctrine"],
|
| 338 |
+
}
|
| 339 |
+
for r in data["receipts"]
|
| 340 |
+
],
|
| 341 |
+
}
|
| 342 |
+
except Exception as err: # fail-closed, loud, honest — never stale-as-fresh
|
| 343 |
+
return {
|
| 344 |
+
"ok": False,
|
| 345 |
+
"wall": "quant-signals",
|
| 346 |
+
"source": _SOURCE,
|
| 347 |
+
"pinnedKeyId": None,
|
| 348 |
+
"posture": "ADVISORY_PAPER_ONLY — no execution, no custody, NOT financial advice",
|
| 349 |
+
"receipts": [],
|
| 350 |
+
"fetchedAt": _now_iso(),
|
| 351 |
+
"error": f"receipts unavailable: {type(err).__name__}: {err}",
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
# ---------------------------------------------------------------------------
|
| 356 |
+
# Server-rendered page (0 CDN, no external assets, inline vanilla JS only)
|
| 357 |
+
# ---------------------------------------------------------------------------
|
| 358 |
+
def _fail_closed_page(message: str, status: int = 503) -> str:
|
| 359 |
+
e = html.escape
|
| 360 |
+
return (
|
| 361 |
+
"<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\">"
|
| 362 |
+
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
|
| 363 |
+
"<title>Quant Signals unavailable · a11oy</title></head>"
|
| 364 |
+
f"<body style='background:{_BG};color:{_GOLD};"
|
| 365 |
+
"font:15px/1.6 system-ui,sans-serif;padding:2.2rem;max-width:820px;margin:0 auto'>"
|
| 366 |
+
"<h1 style='color:#fff'>Quant Signals — receipts unavailable</h1>"
|
| 367 |
+
"<p>The wall fails <strong>CLOSED</strong>: it will not serve stale receipts as fresh, "
|
| 368 |
+
"and it never invents a verification result.</p>"
|
| 369 |
+
f"<pre style='background:#070b0e;border:1px solid #16202a;border-radius:8px;"
|
| 370 |
+
f"padding:.8rem;color:{_INK};white-space:pre-wrap'>{e(message)}</pre>"
|
| 371 |
+
"<p style='color:#7d93a6'>Advisory research artifacts. Paper-only. NOT financial advice. "
|
| 372 |
+
"No execution, no custody.</p>"
|
| 373 |
+
f"</body></html>"
|
| 374 |
+
), status
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def _pretty(value) -> str:
|
| 378 |
+
return json.dumps(value, indent=2, ensure_ascii=False)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def _render_page(data: dict) -> str:
|
| 382 |
+
e = html.escape
|
| 383 |
+
pin = data["pin"]
|
| 384 |
+
receipts = data["receipts"]
|
| 385 |
+
|
| 386 |
+
# Verbatim disclaimer: reproduce the receipt's own _doctrine.disclaimer text.
|
| 387 |
+
disclaimer = ""
|
| 388 |
+
for r in receipts:
|
| 389 |
+
d = (r.get("doctrine") or {}).get("disclaimer")
|
| 390 |
+
if d:
|
| 391 |
+
disclaimer = d
|
| 392 |
+
break
|
| 393 |
+
if not disclaimer:
|
| 394 |
+
disclaimer = ("Advisory research output. Paper-only. NOT financial advice. "
|
| 395 |
+
"No execution, no custody.")
|
| 396 |
+
|
| 397 |
+
# Pin banner state.
|
| 398 |
+
if pin["pinOk"]:
|
| 399 |
+
pin_line = (f"Pinned engine key <code>{e(pin['keyId'])}</code> "
|
| 400 |
+
f"(env {e(_PIN_ENV)}) — verification runs server-side, per request.")
|
| 401 |
+
else:
|
| 402 |
+
pin_line = (f"FAIL-CLOSED: {e(pin['reason'])}. No receipt can show a green check "
|
| 403 |
+
f"until the pin is configured and matches.")
|
| 404 |
+
|
| 405 |
+
cards = []
|
| 406 |
+
for i, r in enumerate(receipts):
|
| 407 |
+
verified = r["verified"]
|
| 408 |
+
badge = "VERIFIED" if verified else "VERIFICATION FAILED"
|
| 409 |
+
badge_color = _TEAL if verified else _GOLD
|
| 410 |
+
s = r["summary"]
|
| 411 |
+
doctrine = r.get("doctrine") or {}
|
| 412 |
+
|
| 413 |
+
rows = [("subject", s.get("subject", "")),
|
| 414 |
+
("predicateType", s.get("predicateType", "")),
|
| 415 |
+
("keyId", r.get("keyId", ""))]
|
| 416 |
+
if s.get("kind") == "signal":
|
| 417 |
+
rows += [("asset", s.get("asset", "")),
|
| 418 |
+
("chain", s.get("chain", "")),
|
| 419 |
+
("proposedAction", s.get("proposedAction", "")),
|
| 420 |
+
("verdict", s.get("verdict", "")),
|
| 421 |
+
("conviction", str(s.get("conviction", ""))),
|
| 422 |
+
("blockedBy", ", ".join(s.get("blockedBy", []) or []))]
|
| 423 |
+
elif s.get("kind") == "backtest":
|
| 424 |
+
rows += [("asset", s.get("asset", "")),
|
| 425 |
+
("populationSize", str(s.get("populationSize", ""))),
|
| 426 |
+
("outOfSampleBars", str(s.get("outOfSampleBars", "")))]
|
| 427 |
+
highlight_rows = "".join(
|
| 428 |
+
f"<div class='kv'><span class='k'>{e(str(k))}</span>"
|
| 429 |
+
f"<span class='v'>{e(str(v))}</span></div>"
|
| 430 |
+
for k, v in rows if str(v) != ""
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
# Λ Conjecture-1 line — only if the predicate carries it.
|
| 434 |
+
lambda_line = ""
|
| 435 |
+
lam = doctrine.get("lambdaStatus")
|
| 436 |
+
if lam:
|
| 437 |
+
lambda_line = (f"<p class='lam'>Λ — Conjecture 1 (open): "
|
| 438 |
+
f"{e(str(lam))}</p>")
|
| 439 |
+
|
| 440 |
+
checks_ok = "".join(
|
| 441 |
+
f"<li class='{'ok' if v else 'bad'}'>{e(str(k))}: {'PASS' if v else 'FAIL'}</li>"
|
| 442 |
+
for k, v in (r.get("checks") or {}).items()
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
raw_envelope = _pretty(r["envelope"])
|
| 446 |
+
raw_payload = _pretty(r["payload"])
|
| 447 |
+
|
| 448 |
+
cards.append(f"""
|
| 449 |
+
<article class="card" data-quantsignals-card="s1">
|
| 450 |
+
<header class="card-head">
|
| 451 |
+
<span class="case">{e(str(r['name']))}</span>
|
| 452 |
+
<span class="badge" style="color:{badge_color};border-color:{badge_color}">{badge}</span>
|
| 453 |
+
</header>
|
| 454 |
+
<div class="kvs">{highlight_rows}</div>
|
| 455 |
+
{lambda_line}
|
| 456 |
+
<details>
|
| 457 |
+
<summary>Verification checks (fail-closed)</summary>
|
| 458 |
+
<ul class="checks">{checks_ok}</ul>
|
| 459 |
+
</details>
|
| 460 |
+
<details>
|
| 461 |
+
<summary>Raw DSSE envelope (JSON)</summary>
|
| 462 |
+
<pre id="env-{i}">{e(raw_envelope)}</pre>
|
| 463 |
+
<button class="copy" data-target="env-{i}">Copy envelope JSON</button>
|
| 464 |
+
</details>
|
| 465 |
+
<details>
|
| 466 |
+
<summary>Decoded in-toto payload (JSON)</summary>
|
| 467 |
+
<pre id="pay-{i}">{e(raw_payload)}</pre>
|
| 468 |
+
<button class="copy" data-target="pay-{i}">Copy payload JSON</button>
|
| 469 |
+
</details>
|
| 470 |
+
</article>""")
|
| 471 |
+
|
| 472 |
+
cards_html = "".join(cards)
|
| 473 |
+
pinned_id = e(pin["keyId"]) if pin["pinOk"] else "—"
|
| 474 |
+
|
| 475 |
+
return f"""<!DOCTYPE html>
|
| 476 |
+
<html lang="en">
|
| 477 |
+
<head>
|
| 478 |
+
<meta charset="utf-8">
|
| 479 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 480 |
+
<title>Quant Signals — signed, verifiable · a11oy</title>
|
| 481 |
+
<style>
|
| 482 |
+
:root {{ color-scheme: dark; }}
|
| 483 |
+
* {{ box-sizing: border-box; }}
|
| 484 |
+
body {{ margin:0; background:{_BG}; color:{_INK};
|
| 485 |
+
font:15px/1.6 system-ui,-apple-system,Segoe UI,Roboto,sans-serif; }}
|
| 486 |
+
.wrap {{ max-width:980px; margin:0 auto; padding:2rem 1.1rem 4rem; }}
|
| 487 |
+
h1 {{ font-size:1.5rem; margin:.2rem 0 .3rem; color:#fff; }}
|
| 488 |
+
.sub {{ color:{_MUTE}; margin:0 0 1.3rem; }}
|
| 489 |
+
.banner {{ border:1px solid {_GOLD}; border-left-width:5px; border-radius:8px;
|
| 490 |
+
background:rgba(215,185,107,.06); color:{_GOLD};
|
| 491 |
+
padding:.85rem 1rem; margin:0 0 1rem; font-weight:600; }}
|
| 492 |
+
.pin {{ border:1px solid #1c2733; border-radius:8px; background:{_PANEL};
|
| 493 |
+
padding:.7rem 1rem; margin:0 0 1.6rem; color:{_INK}; font-size:.92rem; }}
|
| 494 |
+
.pin code {{ color:{_TEAL}; }}
|
| 495 |
+
.card {{ background:{_PANEL}; border:1px solid #1c2733; border-radius:10px;
|
| 496 |
+
padding:1.05rem 1.1rem; margin:0 0 1.15rem; }}
|
| 497 |
+
.card-head {{ display:flex; justify-content:space-between; align-items:center;
|
| 498 |
+
gap:.6rem; flex-wrap:wrap; }}
|
| 499 |
+
.case {{ font-weight:700; color:#fff; word-break:break-all; }}
|
| 500 |
+
.badge {{ font-size:.72rem; font-weight:700; text-transform:uppercase;
|
| 501 |
+
letter-spacing:.05em; padding:.18em .6em; border:1px solid;
|
| 502 |
+
border-radius:6px; white-space:nowrap; }}
|
| 503 |
+
.kvs {{ margin:.7rem 0 .3rem; }}
|
| 504 |
+
.kv {{ display:flex; gap:.6rem; padding:.12rem 0; border-bottom:1px solid #131c25; }}
|
| 505 |
+
.kv .k {{ color:{_MUTE}; min-width:9.5rem; }}
|
| 506 |
+
.kv .v {{ color:{_INK}; word-break:break-all; }}
|
| 507 |
+
.lam {{ color:{_BLUE}; font-size:.9rem; margin:.6rem 0 .2rem; }}
|
| 508 |
+
details {{ border-top:1px solid #1c2733; padding-top:.55rem; margin-top:.55rem; }}
|
| 509 |
+
summary {{ cursor:pointer; color:{_BLUE}; font-weight:600; }}
|
| 510 |
+
ul.checks {{ list-style:none; padding:.4rem 0 0; margin:0; font-size:.88rem; }}
|
| 511 |
+
ul.checks li.ok {{ color:{_TEAL}; }}
|
| 512 |
+
ul.checks li.bad {{ color:{_GOLD}; }}
|
| 513 |
+
pre {{ background:#070b0e; border:1px solid #16202a; border-radius:8px;
|
| 514 |
+
padding:.75rem .85rem; overflow:auto; max-height:22rem;
|
| 515 |
+
font:12.5px/1.55 ui-monospace,SFMono-Regular,Menlo,monospace;
|
| 516 |
+
color:{_INK}; white-space:pre; }}
|
| 517 |
+
button.copy {{ margin:.5rem 0 .2rem; background:transparent; color:{_TEAL};
|
| 518 |
+
border:1px solid {_TEAL}; border-radius:6px; padding:.35em .8em;
|
| 519 |
+
font:inherit; font-size:.82rem; cursor:pointer; }}
|
| 520 |
+
button.copy:hover {{ background:rgba(58,244,200,.08); }}
|
| 521 |
+
button.copy.ok {{ color:{_GOLD}; border-color:{_GOLD}; }}
|
| 522 |
+
footer {{ margin-top:2.4rem; padding-top:1rem; border-top:1px solid #1c2733;
|
| 523 |
+
color:{_MUTE}; font-size:.9rem; }}
|
| 524 |
+
footer a {{ color:{_TEAL}; text-decoration:none; }}
|
| 525 |
+
footer a:hover {{ text-decoration:underline; }}
|
| 526 |
+
footer pre {{ margin:.5rem 0; }}
|
| 527 |
+
</style>
|
| 528 |
+
</head>
|
| 529 |
+
<body>
|
| 530 |
+
<main class="wrap">
|
| 531 |
+
<h1>Quant Signals — signed, verifiable</h1>
|
| 532 |
+
<p class="sub">Doctrine-governed quant engine · every signal & backtest ships a
|
| 533 |
+
DSSE-signed receipt, re-verified server-side against a pinned key on every request.</p>
|
| 534 |
+
<div class="banner" data-quantsignals-banner="s1">{e(disclaimer)}</div>
|
| 535 |
+
<div class="pin">{pin_line}
|
| 536 |
+
<br><span style="color:{_MUTE}">A VERIFIED badge proves INTEGRITY + ORIGIN only — that the
|
| 537 |
+
receipt was signed by the pinned engine key and not tampered with. It is
|
| 538 |
+
<strong>never</strong> a claim of accuracy or profitability. Λ is Conjecture 1 (open),
|
| 539 |
+
never a theorem.</span>
|
| 540 |
+
</div>
|
| 541 |
+
{cards_html}
|
| 542 |
+
<footer>
|
| 543 |
+
Source of truth: <a href="{e(_REPO_URL)}" rel="noopener">{e(_REPO_URL)}</a>
|
| 544 |
+
· pinned engine keyId: <code style="color:{_TEAL}">{pinned_id}</code>
|
| 545 |
+
<br>Verify independently, offline, with the repo's own verifier:
|
| 546 |
+
<pre id="verify-cmd">{e(_VERIFY_CMD)}</pre>
|
| 547 |
+
<button class="copy" data-target="verify-cmd">Copy verify command</button>
|
| 548 |
+
</footer>
|
| 549 |
+
</main>
|
| 550 |
+
<script>
|
| 551 |
+
(function () {{
|
| 552 |
+
document.querySelectorAll("button.copy").forEach(function (btn) {{
|
| 553 |
+
btn.addEventListener("click", function () {{
|
| 554 |
+
var el = document.getElementById(btn.getAttribute("data-target"));
|
| 555 |
+
if (!el) return;
|
| 556 |
+
var text = el.textContent || "";
|
| 557 |
+
var done = function () {{
|
| 558 |
+
var orig = btn.textContent;
|
| 559 |
+
btn.textContent = "Copied";
|
| 560 |
+
btn.classList.add("ok");
|
| 561 |
+
setTimeout(function () {{ btn.textContent = orig; btn.classList.remove("ok"); }}, 1400);
|
| 562 |
+
}};
|
| 563 |
+
if (navigator.clipboard && navigator.clipboard.writeText) {{
|
| 564 |
+
navigator.clipboard.writeText(text).then(done, function () {{ fallback(text, done); }});
|
| 565 |
+
}} else {{ fallback(text, done); }}
|
| 566 |
+
}});
|
| 567 |
+
}});
|
| 568 |
+
function fallback(text, done) {{
|
| 569 |
+
var ta = document.createElement("textarea");
|
| 570 |
+
ta.value = text; ta.setAttribute("readonly", "");
|
| 571 |
+
ta.style.position = "absolute"; ta.style.left = "-9999px";
|
| 572 |
+
document.body.appendChild(ta); ta.select();
|
| 573 |
+
try {{ document.execCommand("copy"); done(); }} catch (e) {{}}
|
| 574 |
+
document.body.removeChild(ta);
|
| 575 |
+
}}
|
| 576 |
+
}})();
|
| 577 |
+
</script>
|
| 578 |
+
</body>
|
| 579 |
+
</html>"""
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
async def _signals_page():
|
| 583 |
+
from starlette.responses import HTMLResponse
|
| 584 |
+
try:
|
| 585 |
+
data = await _collect()
|
| 586 |
+
return HTMLResponse(_render_page(data))
|
| 587 |
+
except Exception as page_error: # fail-closed: never a fabricated page
|
| 588 |
+
body, status = _fail_closed_page(
|
| 589 |
+
f"{type(page_error).__name__}: {page_error}", status=503)
|
| 590 |
+
return HTMLResponse(body, status_code=status)
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def register(app, ns: str = "a11oy") -> str:
|
| 594 |
+
"""Additive registration + front-move (exact routes must beat SPA fallback).
|
| 595 |
+
|
| 596 |
+
Adds two routes off the SAME source of truth (szl-quant@main receipts):
|
| 597 |
+
* GET /api/quant/signals — machine JSON, per-receipt verify result
|
| 598 |
+
* GET /signals — visitor-reachable, self-contained server-rendered page
|
| 599 |
+
Both are front-moved so the exact paths win over the SPA history fallback."""
|
| 600 |
+
app.add_api_route(_API_ROUTE, _signals_api, methods=["GET"], include_in_schema=False)
|
| 601 |
+
app.add_api_route(_PAGE_ROUTE, _signals_page, methods=["GET"], include_in_schema=False)
|
| 602 |
+
for target in (_API_ROUTE, _PAGE_ROUTE):
|
| 603 |
+
for index, route in enumerate(app.router.routes):
|
| 604 |
+
if getattr(route, "path", None) == target:
|
| 605 |
+
app.router.routes.insert(0, app.router.routes.pop(index))
|
| 606 |
+
break
|
| 607 |
+
return (f"{_API_ROUTE} + {_PAGE_ROUTE} (szl-quant@main signed receipts; "
|
| 608 |
+
f"server-verified, pinned key, fail-closed)")
|
a11oy_quant_signals_nav.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 3 |
+
# © 2026 Lutar, Stephen P. — SZL Holdings · ORCID 0009-0001-0110-4173 · Doctrine v11
|
| 4 |
+
# ===========================================================================
|
| 5 |
+
# a11oy_quant_signals_nav.py — idempotent nav-injection for the QUANT SIGNALS page.
|
| 6 |
+
# ---------------------------------------------------------------------------
|
| 7 |
+
# Adds ONE honest left-nav item → /signals into the /console (a11oy) and
|
| 8 |
+
# /elite (killinchu) SPAs, plus a small cross-link strip on the /signals
|
| 9 |
+
# page itself. Mirrors the proven a11oy_khipu_demo_nav.py / a11oy_uds_portability_nav.py
|
| 10 |
+
# BaseHTTPMiddleware pattern:
|
| 11 |
+
# • never rewrites the SPA source (pages/console.html is NOT edited);
|
| 12 |
+
# • only ADDS markup into text/html responses, removes nothing;
|
| 13 |
+
# • idempotent via the data-quantsignals-nav="s1" marker (re-runs never double-inject);
|
| 14 |
+
# • 0 CDN (pure inline markup, no external assets, no <script>);
|
| 15 |
+
# • 0 user-visible codenames; honest label only.
|
| 16 |
+
#
|
| 17 |
+
# A SEPARATE injector from QA10 / WILLAY / WAQAY / YUPAY / UDS / KHIPU so none collide:
|
| 18 |
+
# QA10 keys data-nav-wireup="qa10"; WILLAY data-willay-nav="w1"; WAQAY
|
| 19 |
+
# data-waqay-nav="q1"; YUPAY data-yupay-nav="y1"; UDS data-udsport-nav="u1";
|
| 20 |
+
# KHIPU data-khipudemo-nav="k1"; this keys data-quantsignals-nav="s1".
|
| 21 |
+
#
|
| 22 |
+
# Doctrine: locked=8 @ c7c0ba17 · Λ = Conjecture 1 · additive-only · never weakens a gate.
|
| 23 |
+
# Honesty: the target page shows DSSE-signed ADVISORY / PAPER-ONLY receipts,
|
| 24 |
+
# re-verified server-side; verification proves INTEGRITY + ORIGIN only. The nav
|
| 25 |
+
# label makes no accuracy claim — "signed receipts" only, never "profitable".
|
| 26 |
+
# Signed-off-by: Stephen P. Lutar Jr. · Co-Authored-By: Perplexity Computer Agent.
|
| 27 |
+
# ===========================================================================
|
| 28 |
+
from typing import Any, Dict
|
| 29 |
+
|
| 30 |
+
_SIGNALS_PATH = "/signals"
|
| 31 |
+
_SIGNALS_ICO = "\U0001F4C8" # 📈 (signals — advisory research, not advice)
|
| 32 |
+
_SIGNALS_LABEL = "Quant Signals \u2014 signed receipts"
|
| 33 |
+
|
| 34 |
+
_NAV_MARKER = b'data-quantsignals-nav="s1"'
|
| 35 |
+
_REL_MARKER = b'data-quantsignals-rel="s1"'
|
| 36 |
+
|
| 37 |
+
# Sidebar anchors (same as the QA10 / WILLAY / WAQAY / YUPAY / UDS / KHIPU injectors).
|
| 38 |
+
_FOOT_ANCHOR = b'<div class="side-foot">'
|
| 39 |
+
_GROUP_ANCHOR = b'<div class="nav-group">'
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _build_nav_block() -> bytes:
|
| 43 |
+
item = (
|
| 44 |
+
'<div class="nav-item" data-quantsignals-nav="s1" data-quantsignals-path="%s" '
|
| 45 |
+
'onclick="location.href=\'%s\'" style="cursor:pointer">'
|
| 46 |
+
'<span class="ico">%s</span>%s</div>' % (_SIGNALS_PATH, _SIGNALS_PATH, _SIGNALS_ICO, _SIGNALS_LABEL)
|
| 47 |
+
)
|
| 48 |
+
block = ('<div class="nav-group" data-quantsignals-nav="s1">Quant (signed)</div>' + item)
|
| 49 |
+
return block.encode("utf-8")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _build_rel_strip() -> bytes:
|
| 53 |
+
rel = [("/yupay", "YUPAY — Governed Audit"), ("/waqay", "WAQAY — Sovereign Memory"),
|
| 54 |
+
("/willay", "WILLAY — Safety Gateway"), ("/khipu-demo", "Khipu Demo")]
|
| 55 |
+
links = "".join(
|
| 56 |
+
'<a href="%s" style="color:#39d8c8;text-decoration:none;margin:0 .55em;'
|
| 57 |
+
'white-space:nowrap">%s</a>' % (p, l) for p, l in rel)
|
| 58 |
+
strip = (
|
| 59 |
+
'<nav data-quantsignals-rel="s1" aria-label="Quant signals related surfaces" '
|
| 60 |
+
'style="margin:1.25rem auto;max-width:1180px;padding:.6rem .9rem;'
|
| 61 |
+
'border-top:1px solid #1c2733;font:13px/1.6 system-ui,sans-serif;'
|
| 62 |
+
'color:#9fb4c6;text-align:center">'
|
| 63 |
+
'<span style="margin-right:.4em">Related sovereign surfaces:</span>' + links + '</nav>')
|
| 64 |
+
return strip.encode("utf-8")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _make_injector():
|
| 68 |
+
from starlette.middleware.base import BaseHTTPMiddleware
|
| 69 |
+
from starlette.responses import Response
|
| 70 |
+
|
| 71 |
+
nav_block = _build_nav_block()
|
| 72 |
+
rel_strip = _build_rel_strip()
|
| 73 |
+
|
| 74 |
+
class _QuantSignalsNavInjector(BaseHTTPMiddleware):
|
| 75 |
+
async def dispatch(self, request, call_next):
|
| 76 |
+
resp = await call_next(request)
|
| 77 |
+
try:
|
| 78 |
+
ct = (resp.headers.get("content-type") or "").lower()
|
| 79 |
+
if "text/html" not in ct:
|
| 80 |
+
return resp
|
| 81 |
+
p = request.url.path
|
| 82 |
+
if (p.startswith("/api/") or p.startswith("/v1/")
|
| 83 |
+
or p.startswith("/vendor/") or p.startswith("/assets/")
|
| 84 |
+
or p.startswith("/static/")):
|
| 85 |
+
return resp
|
| 86 |
+
|
| 87 |
+
body = b""
|
| 88 |
+
async for chunk in resp.body_iterator:
|
| 89 |
+
body += chunk if isinstance(chunk, (bytes, bytearray)) else str(chunk).encode()
|
| 90 |
+
|
| 91 |
+
# (1) Nav-item injection — idempotent, only where the sidebar exists.
|
| 92 |
+
if _NAV_MARKER not in body:
|
| 93 |
+
if _FOOT_ANCHOR in body:
|
| 94 |
+
body = body.replace(_FOOT_ANCHOR, nav_block + _FOOT_ANCHOR, 1)
|
| 95 |
+
elif _GROUP_ANCHOR in body:
|
| 96 |
+
body = body.replace(_GROUP_ANCHOR, _GROUP_ANCHOR + nav_block, 1)
|
| 97 |
+
|
| 98 |
+
# (2) Related strip on the /signals page only — idempotent.
|
| 99 |
+
if p == _SIGNALS_PATH and _REL_MARKER not in body and b"</body>" in body:
|
| 100 |
+
body = body.replace(b"</body>", rel_strip + b"</body>", 1)
|
| 101 |
+
|
| 102 |
+
headers = dict(resp.headers)
|
| 103 |
+
headers.pop("content-length", None)
|
| 104 |
+
return Response(content=body, status_code=resp.status_code,
|
| 105 |
+
headers=headers, media_type="text/html")
|
| 106 |
+
except Exception:
|
| 107 |
+
return resp
|
| 108 |
+
|
| 109 |
+
return _QuantSignalsNavInjector
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def register(app, ns: str = "a11oy") -> Dict[str, Any]:
|
| 113 |
+
"""Attach the idempotent Quant-signals nav injector. ADDITIVE; the SPA
|
| 114 |
+
source is never edited. try/except-guarded by the caller."""
|
| 115 |
+
app.add_middleware(_make_injector())
|
| 116 |
+
return {
|
| 117 |
+
"registered": ["MIDDLEWARE quant-signals-nav injector (s1)"],
|
| 118 |
+
"capability": "Quant Signals nav wire-up",
|
| 119 |
+
"tab_route": _SIGNALS_PATH,
|
| 120 |
+
"data_label": "QUANT-SIGNALS-NAV",
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
# ---------------------------------------------------------------------------
|
| 125 |
+
# Self-test (run: python a11oy_quant_signals_nav.py).
|
| 126 |
+
# ---------------------------------------------------------------------------
|
| 127 |
+
if __name__ == "__main__":
|
| 128 |
+
from starlette.applications import Starlette
|
| 129 |
+
from starlette.responses import HTMLResponse
|
| 130 |
+
from starlette.routing import Route
|
| 131 |
+
from starlette.testclient import TestClient
|
| 132 |
+
|
| 133 |
+
SAMPLE_CONSOLE = (
|
| 134 |
+
'<html><body><aside>'
|
| 135 |
+
'<div class="nav-group">Operate</div>'
|
| 136 |
+
'<div class="nav-item" onclick="go(\'x\')"><span class="ico">x</span>Existing</div>'
|
| 137 |
+
'<div class="side-foot">footer</div>'
|
| 138 |
+
'</aside><main>x</main></body></html>')
|
| 139 |
+
SAMPLE_PAGE = '<html><body><h1>Quant Signals</h1></body></html>'
|
| 140 |
+
|
| 141 |
+
async def _console(req):
|
| 142 |
+
return HTMLResponse(SAMPLE_CONSOLE)
|
| 143 |
+
|
| 144 |
+
async def _page(req):
|
| 145 |
+
return HTMLResponse(SAMPLE_PAGE)
|
| 146 |
+
|
| 147 |
+
app = Starlette(routes=[Route("/console", _console), Route("/signals", _page)])
|
| 148 |
+
st = register(app, ns="a11oy")
|
| 149 |
+
assert st["tab_route"] == "/signals", st
|
| 150 |
+
c = TestClient(app)
|
| 151 |
+
|
| 152 |
+
h1 = c.get("/console").text
|
| 153 |
+
h2 = c.get("/console").text
|
| 154 |
+
assert h1 == h2, "console injection must be byte-identical (idempotent)"
|
| 155 |
+
assert h1.count('data-quantsignals-nav="s1"') == 2, "one group + one item marker"
|
| 156 |
+
assert "location.href='/signals'" in h1, "nav must link /signals"
|
| 157 |
+
assert "Existing" in h1 and "Operate</div>" in h1 and "footer</div>" in h1, \
|
| 158 |
+
"must NOT remove existing nav markup"
|
| 159 |
+
|
| 160 |
+
w1 = c.get("/signals").text
|
| 161 |
+
w2 = c.get("/signals").text
|
| 162 |
+
assert w1 == w2, "page injection must be idempotent"
|
| 163 |
+
assert w1.count('data-quantsignals-rel="s1"') == 1, "related strip injects exactly once"
|
| 164 |
+
assert "/yupay" in w1 and "/waqay" in w1, "related strip must cross-link governance surfaces"
|
| 165 |
+
|
| 166 |
+
inj = (_build_nav_block().decode() + _build_rel_strip().decode()).lower()
|
| 167 |
+
assert "http://" not in inj and "https://" not in inj, "nav markup must be 0-CDN"
|
| 168 |
+
assert "<script" not in inj, "nav markup must inject no script"
|
| 169 |
+
for bad in ("am" + "aru", "ro" + "sie", "sen" + "tra", "jar" + "vis"):
|
| 170 |
+
assert bad not in inj, "no user-visible internal codenames in nav markup"
|
| 171 |
+
print("a11oy_quant_signals_nav: ALL OK — /signals nav item injected once; "
|
| 172 |
+
"idempotent; additive; 0 codenames; 0 CDN")
|
serve.py
CHANGED
|
@@ -6325,6 +6325,7 @@ for _navmod, _navlabel in (
|
|
| 6325 |
("a11oy_yupay_nav", "YUPAY"),
|
| 6326 |
("a11oy_uds_portability_nav", "UDS Portability"),
|
| 6327 |
("a11oy_khipu_demo_nav", "Khipu Demo"),
|
|
|
|
| 6328 |
):
|
| 6329 |
try:
|
| 6330 |
_nm = __import__(_navmod)
|
|
@@ -13471,6 +13472,28 @@ except Exception as _khipu_demo_error: # additive: never take down the SPA
|
|
| 13471 |
)
|
| 13472 |
|
| 13473 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13474 |
if __name__ == "__main__":
|
| 13475 |
import uvicorn
|
| 13476 |
port = int(os.environ.get("PORT", "7860"))
|
|
|
|
| 6325 |
("a11oy_yupay_nav", "YUPAY"),
|
| 6326 |
("a11oy_uds_portability_nav", "UDS Portability"),
|
| 6327 |
("a11oy_khipu_demo_nav", "Khipu Demo"),
|
| 6328 |
+
("a11oy_quant_signals_nav", "Quant Signals"),
|
| 6329 |
):
|
| 6330 |
try:
|
| 6331 |
_nm = __import__(_navmod)
|
|
|
|
| 13472 |
)
|
| 13473 |
|
| 13474 |
|
| 13475 |
+
# ============================================================================
|
| 13476 |
+
# QUANT SIGNALS WALL (2026-07-16): /api/quant/signals + /signals — the doctrine-
|
| 13477 |
+
# governed quant engine's DSSE-signed advisory receipts (szl-holdings/szl-quant
|
| 13478 |
+
# @main), re-verified SERVER-SIDE per request against a PINNED ed25519 engine key
|
| 13479 |
+
# (env A11OY_QUANT_ENGINE_KEYID). ADVISORY_PAPER_ONLY: no execution, no custody,
|
| 13480 |
+
# NOT financial advice. A VERIFIED badge proves INTEGRITY + ORIGIN only — never
|
| 13481 |
+
# accuracy or profitability. Λ = Conjecture 1 (open), never a theorem. Fail-closed
|
| 13482 |
+
# on fetch failure or pin mismatch. Additive, front-moved routes so the exact
|
| 13483 |
+
# paths win over the SPA history fallback.
|
| 13484 |
+
# ============================================================================
|
| 13485 |
+
try:
|
| 13486 |
+
import a11oy_quant_signals as _a11oy_quant_signals
|
| 13487 |
+
|
| 13488 |
+
_quant_signals_result = _a11oy_quant_signals.register(app)
|
| 13489 |
+
print(f"[a11oy] quant signals wall registered (front-moved): {_quant_signals_result}", file=sys.stderr)
|
| 13490 |
+
except Exception as _quant_signals_error: # additive: never take down the SPA
|
| 13491 |
+
print(
|
| 13492 |
+
f"[a11oy] quant signals wall NOT registered (non-fatal): {_quant_signals_error!r}",
|
| 13493 |
+
file=sys.stderr,
|
| 13494 |
+
)
|
| 13495 |
+
|
| 13496 |
+
|
| 13497 |
if __name__ == "__main__":
|
| 13498 |
import uvicorn
|
| 13499 |
port = int(os.environ.get("PORT", "7860"))
|