Spaces:
Running
Running
feat(amaru): per-app cortex brain + unified LLM router + Wire D/E/F (additive, Doctrine v10). Add /brain (cortex theorems TH1 Λ-Conjecture / TH8 GLR proven / TH10, 7 chakras, 5 founder-locked LLM tiers) and API /api/amaru/v1/brain, /brain/reason, /llm/route, /llm/tiers, /cortex-subscribe (Wire E SSE), /mesh/state, /v1/brainz. Wire D: in-process W3C traceparent middleware (real per-request generation+propagation; cross-Space broker NOT wired — labeled LIVE_IN_PROCESS, links to a11oy /wires). Wire E: amaru subscribes to a11oy brand-decision events (in-memory SSE bus). Wire F: receipts ingest into Khipu DAG (DSSE sig=PLACEHOLDER, Sigstore CI not wired). Does NOT shadow existing /api/amaru/healthz (7 chakras) — brain status at additive /api/amaru/v1/brainz. Honest numbers 749/14/163 @ c7c0ba17. Preserves /conduit SPA + /upgrades + root cortex. ZERO BANDAID. Yachay CTO + Opus.
Browse files- Dockerfile +5 -1
- serve.py +139 -2
- szl_brain.py +219 -0
- szl_wire.py +224 -0
Dockerfile
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
# SPDX-License-Identifier: LicenseRef-SZL-Proprietary
|
| 2 |
-
# © 2026 Lutar, Stephen P. — SZL Holdings · ORCID 0009-0001-0110-4173 · Doctrine
|
| 3 |
# amaru HF Docker Space — serves the amaru memory-cortex operator surface + the
|
| 4 |
# real 7-chakra runtime API at /api/amaru/* + the verbatim Replit reverse-ETL
|
| 5 |
# React SPA at /conduit/ (BASE_PATH=/conduit/, title "Amaru — The Andean Ouroboros").
|
|
@@ -33,6 +33,10 @@ COPY conduit/ /app/static/conduit/
|
|
| 33 |
|
| 34 |
COPY serve.py /app/serve.py
|
| 35 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
ENV PORT=7860
|
| 37 |
EXPOSE 7860
|
| 38 |
|
|
|
|
| 1 |
# SPDX-License-Identifier: LicenseRef-SZL-Proprietary
|
| 2 |
+
# © 2026 Lutar, Stephen P. — SZL Holdings · ORCID 0009-0001-0110-4173 · Doctrine v10
|
| 3 |
# amaru HF Docker Space — serves the amaru memory-cortex operator surface + the
|
| 4 |
# real 7-chakra runtime API at /api/amaru/* + the verbatim Replit reverse-ETL
|
| 5 |
# React SPA at /conduit/ (BASE_PATH=/conduit/, title "Amaru — The Andean Ouroboros").
|
|
|
|
| 33 |
|
| 34 |
COPY serve.py /app/serve.py
|
| 35 |
|
| 36 |
+
# ADDITIVE (Doctrine v10): shared per-app BRAIN + unified LLM router + mesh wires.
|
| 37 |
+
COPY szl_brain.py /app/szl_brain.py
|
| 38 |
+
COPY szl_wire.py /app/szl_wire.py
|
| 39 |
+
|
| 40 |
ENV PORT=7860
|
| 41 |
EXPOSE 7860
|
| 42 |
|
serve.py
CHANGED
|
@@ -20,14 +20,19 @@ import sys
|
|
| 20 |
|
| 21 |
sys.path.insert(0, "/app")
|
| 22 |
|
|
|
|
| 23 |
from pathlib import Path
|
| 24 |
-
from fastapi import FastAPI
|
| 25 |
from fastapi.staticfiles import StaticFiles
|
| 26 |
-
from fastapi.responses import FileResponse
|
| 27 |
from starlette.middleware.cors import CORSMiddleware
|
| 28 |
|
| 29 |
from amaru.app import app as amaru_app
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
app = FastAPI(title="Amaru — Full Stack")
|
| 32 |
|
| 33 |
app.add_middleware(
|
|
@@ -37,6 +42,94 @@ app.add_middleware(
|
|
| 37 |
allow_headers=["*"],
|
| 38 |
)
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
app.mount("/api/amaru", amaru_app)
|
| 41 |
|
| 42 |
STATIC_DIR = Path("/app/static")
|
|
@@ -101,6 +194,50 @@ async def upgrades_index():
|
|
| 101 |
# registered, which 404'd the root memory-cortex landing. Dedented to module level
|
| 102 |
# to restore the GREEN root route. ADDITIVE/no-content-change to /upgrades or v10.
|
| 103 |
# Registered LAST so /api/amaru, /conduit, /upgrades all take precedence.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
@app.get("/{path:path}")
|
| 105 |
async def serve_spa(path: str):
|
| 106 |
file_path = STATIC_DIR / path
|
|
|
|
| 20 |
|
| 21 |
sys.path.insert(0, "/app")
|
| 22 |
|
| 23 |
+
import asyncio as _asyncio
|
| 24 |
from pathlib import Path
|
| 25 |
+
from fastapi import FastAPI, Request
|
| 26 |
from fastapi.staticfiles import StaticFiles
|
| 27 |
+
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse, HTMLResponse
|
| 28 |
from starlette.middleware.cors import CORSMiddleware
|
| 29 |
|
| 30 |
from amaru.app import app as amaru_app
|
| 31 |
|
| 32 |
+
# Doctrine v10 ADDITIVE: shared per-app BRAIN + unified LLM router + mesh wiring.
|
| 33 |
+
import szl_brain as _brain
|
| 34 |
+
import szl_wire as _wire
|
| 35 |
+
|
| 36 |
app = FastAPI(title="Amaru — Full Stack")
|
| 37 |
|
| 38 |
app.add_middleware(
|
|
|
|
| 42 |
allow_headers=["*"],
|
| 43 |
)
|
| 44 |
|
| 45 |
+
# Wire D — W3C traceparent propagation middleware.
|
| 46 |
+
_wire.install_traceparent_middleware(app, "amaru")
|
| 47 |
+
|
| 48 |
+
# ---------------------------------------------------------------------------
|
| 49 |
+
# PER-APP BRAIN (amaru = cortex / reasoning) + UNIFIED LLM ROUTER + Wire E.
|
| 50 |
+
# Registered on the ROOT app BEFORE the /api/amaru mount so they take precedence.
|
| 51 |
+
# ADDITIVE, Doctrine v10.
|
| 52 |
+
# ---------------------------------------------------------------------------
|
| 53 |
+
|
| 54 |
+
@app.get("/api/amaru/v1/brain")
|
| 55 |
+
async def amaru_brain() -> JSONResponse:
|
| 56 |
+
"""amaru cortex brain: TH1 (Λ Conjecture), TH8 GLR (proven), TH10 (Conjecture 1), 7 chakras."""
|
| 57 |
+
return JSONResponse(_brain.brain_payload("amaru"))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@app.post("/api/amaru/v1/brain/reason")
|
| 61 |
+
async def amaru_brain_reason(request: Request) -> JSONResponse:
|
| 62 |
+
"""Axis-scored reasoning with theorem citations. POST {prompt, axis_scores}."""
|
| 63 |
+
try:
|
| 64 |
+
body = await request.json()
|
| 65 |
+
except Exception:
|
| 66 |
+
body = {}
|
| 67 |
+
axis = body.get("axis_scores") or [0.9] * 13
|
| 68 |
+
L = _brain.lambda_aggregate(axis)
|
| 69 |
+
th = _brain.THEOREMS
|
| 70 |
+
cited = {k: th[k] for k in ("TH1", "TH8", "TH10")}
|
| 71 |
+
routed = _brain.route(body.get("prompt", ""), axis, task_hint="math")
|
| 72 |
+
return JSONResponse({
|
| 73 |
+
"lambda": round(L, 6),
|
| 74 |
+
"chakras": _brain.ROLE_SLICES["amaru"]["chakras"],
|
| 75 |
+
"theorems_cited": cited,
|
| 76 |
+
"llm_route": routed,
|
| 77 |
+
"note": "Λ uniqueness is a Conjecture (TH1), not a closed theorem; TH8 GLR is proven; TH10 is Conjecture 1.",
|
| 78 |
+
"doctrine": "v10",
|
| 79 |
+
})
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@app.post("/api/amaru/v1/llm/route")
|
| 83 |
+
async def amaru_llm_route(request: Request) -> JSONResponse:
|
| 84 |
+
try:
|
| 85 |
+
body = await request.json()
|
| 86 |
+
except Exception:
|
| 87 |
+
body = {}
|
| 88 |
+
return JSONResponse(_brain.route(
|
| 89 |
+
prompt=body.get("prompt", ""), axis_scores=body.get("axis_scores"),
|
| 90 |
+
max_tier=body.get("max_tier", 4),
|
| 91 |
+
require_lambda_receipt=body.get("require_λ_receipt", body.get("require_lambda_receipt", True)),
|
| 92 |
+
task_hint=body.get("task_hint", "")))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
@app.get("/api/amaru/v1/llm/tiers")
|
| 96 |
+
async def amaru_llm_tiers() -> JSONResponse:
|
| 97 |
+
return JSONResponse({"count": len(_brain.TIERS), "tiers": _brain.TIERS, "default": "claude_sonnet_4_6", "doctrine": "v10"})
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@app.get("/api/amaru/v1/cortex-subscribe")
|
| 101 |
+
async def amaru_cortex_subscribe() -> StreamingResponse:
|
| 102 |
+
"""Wire E: amaru subscribes to a11oy brand-decision events via Server-Sent Events.
|
| 103 |
+
Honest: in-memory ring buffer (no external broker in a static HF Space)."""
|
| 104 |
+
async def gen():
|
| 105 |
+
for chunk in _wire.cortex_sse_stream(max_events=5):
|
| 106 |
+
yield chunk
|
| 107 |
+
await _asyncio.sleep(0.05)
|
| 108 |
+
return StreamingResponse(gen(), media_type="text/event-stream")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@app.get("/api/amaru/v1/mesh/state")
|
| 112 |
+
async def amaru_mesh_state() -> JSONResponse:
|
| 113 |
+
return JSONResponse(_wire.mesh_status())
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@app.get("/api/amaru/v1/brainz")
|
| 117 |
+
async def amaru_brainz() -> JSONResponse:
|
| 118 |
+
"""Brain/router/wire status (additive; does NOT shadow the existing
|
| 119 |
+
/api/amaru/healthz '7 chakras' endpoint inside the mounted amaru_app)."""
|
| 120 |
+
return JSONResponse({
|
| 121 |
+
"ok": True, "service": "amaru", "surface": "memory cortex (7 chakras)",
|
| 122 |
+
"doctrine": "v10",
|
| 123 |
+
"traceparent_propagating": "in-process only (real within this Space; not distributed across Spaces)",
|
| 124 |
+
"wires": {"B": "LIVE", "C": "LIVE",
|
| 125 |
+
"D": "LIVE_IN_PROCESS (traceparent generated+propagated per request; cross-Space broker NOT wired — see a11oy /wires)",
|
| 126 |
+
"E": "LIVE (cortex SSE, in-memory bus)", "F": "LIVE (Khipu receipt DAG via vessels ingest)"},
|
| 127 |
+
"brain": "/brain + /api/amaru/v1/brain/*", "llm_router": "/api/amaru/v1/llm/route",
|
| 128 |
+
"declarations": 749, "axioms": 14, "sorries": 163,
|
| 129 |
+
"note": "Canonical chakra healthz remains /api/amaru/healthz (unchanged). This brainz endpoint is additive.",
|
| 130 |
+
})
|
| 131 |
+
|
| 132 |
+
|
| 133 |
app.mount("/api/amaru", amaru_app)
|
| 134 |
|
| 135 |
STATIC_DIR = Path("/app/static")
|
|
|
|
| 194 |
# registered, which 404'd the root memory-cortex landing. Dedented to module level
|
| 195 |
# to restore the GREEN root route. ADDITIVE/no-content-change to /upgrades or v10.
|
| 196 |
# Registered LAST so /api/amaru, /conduit, /upgrades all take precedence.
|
| 197 |
+
# ---------------------------------------------------------------------------
|
| 198 |
+
# /brain — amaru cortex brain page (ADDITIVE, Doctrine v10). Renders the cortex
|
| 199 |
+
# theorems (TH1 Λ Conjecture, TH8 GLR proven, TH10 Conjecture 1) + 7 chakras +
|
| 200 |
+
# the 5 founder-locked LLM tiers + live axis-scored reasoning playground.
|
| 201 |
+
# Registered BEFORE the catch-all so it is a real distinct page.
|
| 202 |
+
# ---------------------------------------------------------------------------
|
| 203 |
+
|
| 204 |
+
_BRAIN_HTML = """<!DOCTYPE html><html lang="en"><head><meta charset="utf-8">
|
| 205 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 206 |
+
<title>amaru — Brain (cortex / reasoning) · Doctrine v10</title>
|
| 207 |
+
<style>:root{--bg:#0b0e14;--card:#121826;--ink:#e8eef7;--mut:#8aa0bf;--acc:#5ad1c0;--acc2:#7aa2ff;--line:#243149;--warn:#e0c060}
|
| 208 |
+
*{box-sizing:border-box}body{margin:0;font:15px/1.55 -apple-system,Segoe UI,Roboto,Arial,sans-serif;background:var(--bg);color:var(--ink)}
|
| 209 |
+
.wrap{max-width:1060px;margin:0 auto;padding:32px 20px 90px}h1{font-size:27px;margin:0 0 4px}h2{font-size:18px;margin:30px 0 10px;border-bottom:1px solid var(--line);padding-bottom:6px}
|
| 210 |
+
.sub{color:var(--mut);margin:0 0 18px}.card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:16px 18px;margin:14px 0}
|
| 211 |
+
code{background:#0a1626;padding:1px 5px;border-radius:5px;color:var(--acc);font-size:12px}a{color:var(--acc);text-decoration:none}a:hover{text-decoration:underline}
|
| 212 |
+
.b{display:inline-block;padding:1px 8px;border-radius:999px;font-size:11px;font-weight:700}.green{background:#0f3a2e;color:#5ad1c0}.amber{background:#3a2f0f;color:var(--warn)}
|
| 213 |
+
table{width:100%;border-collapse:collapse;font-size:13px}th,td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line);vertical-align:top}th{color:var(--mut)}
|
| 214 |
+
button{background:var(--acc2);color:#06101f;border:0;border-radius:8px;padding:8px 14px;font-weight:700;cursor:pointer}pre{background:#0a1626;border:1px solid var(--line);border-radius:8px;padding:12px;overflow:auto;font-size:12px}
|
| 215 |
+
.note{color:var(--mut);font-size:13px}.kpis{display:flex;gap:10px;flex-wrap:wrap;margin:10px 0}.kpi{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:10px 14px;min-width:110px}.kpi b{font-size:20px;display:block;color:var(--acc)}
|
| 216 |
+
nav a{margin-right:14px;font-weight:600}.foot{margin-top:40px;color:var(--mut);font-size:12px;border-top:1px solid var(--line);padding-top:14px}</style></head>
|
| 217 |
+
<body><div class="wrap">
|
| 218 |
+
<nav class="note"><a href="/">home</a><a href="/conduit/">/conduit</a><a href="/upgrades">/upgrades</a><a href="https://szlholdings-a11oy.hf.space/mesh" target="_blank" rel="noopener">a11oy /mesh</a></nav>
|
| 219 |
+
<h1>amaru — Brain</h1>
|
| 220 |
+
<p class="sub">Anatomy role: <b>cortex / reasoning</b> · Doctrine v10 · cortex theorems + 7 reasoning chakras + unified LLM router</p>
|
| 221 |
+
<div class="kpis"><div class="kpi"><b>7</b>chakras</div><div class="kpi"><b>3</b>cortex theorems</div><div class="kpi"><b>5</b>LLM tiers</div><div class="kpi"><b>749</b>Lean decls</div><div class="kpi"><b>163</b>sorries</div></div>
|
| 222 |
+
<h2>1 · Cortex theorems (honest status)</h2><div class="card"><table id="th"><tr><th>id</th><th>name</th><th>status</th><th>Lean</th></tr></table>
|
| 223 |
+
<p class="note">TH1 Λ uniqueness is a <b>Conjecture</b> (open CAUCHY_ND sorry at <code>Uniqueness.lean:120</code> + missing symmetry axiom) — NOT a closed theorem. TH8 GLR is <b>proven</b>. TH10 is Conjecture 1 (v9 mis-promoted; reverted in v10).</p></div>
|
| 224 |
+
<h2>2 · 7 reasoning chakras</h2><div class="card"><p id="ch" class="note">…</p></div>
|
| 225 |
+
<h2>3 · Live axis-scored reasoning (cites theorems)</h2><div class="card"><button onclick="reason()">POST /api/amaru/v1/brain/reason</button> <button onclick="sub()">GET /api/amaru/v1/cortex-subscribe (Wire E SSE)</button><pre id="out">// result</pre></div>
|
| 226 |
+
<h2>4 · Unified LLM router (5 founder-locked tiers)</h2><div class="card"><table id="tiers"><tr><th>rank</th><th>model</th><th>use</th></tr></table>
|
| 227 |
+
<p class="note">Same router on every Space. HONEST: no model key wired — <code>response</code> is a stub; tier selection + Λ-receipt are real; receipt <code>signature</code> is a PLACEHOLDER (Sigstore CI not wired).</p></div>
|
| 228 |
+
<div class="foot">Canonical numbers <a href="https://github.com/szl-holdings/.github/blob/main/.github/data/lean_numbers.json" target="_blank" rel="noopener">lean_numbers.json</a> @ <code>c7c0ba17</code> (749/14/163). Router source <a href="https://github.com/szl-holdings/platform/tree/main/packages/llm-router" target="_blank" rel="noopener">platform/packages/llm-router</a>. ADDITIVE — /conduit, /upgrades, root cortex all preserved. ZERO BANDAID.</div>
|
| 229 |
+
</div><script>
|
| 230 |
+
async function reason(){const o=document.getElementById('out');o.textContent='…';try{const r=await fetch('/api/amaru/v1/brain/reason',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({prompt:'Is Λ uniqueness proven?',axis_scores:[0.92,0.9,0.88,0.91,0.93,0.9,0.89,0.92,0.9,0.91,0.93,0.9,0.92]})});o.textContent=JSON.stringify(await r.json(),null,2);}catch(e){o.textContent='error: '+e;}}
|
| 231 |
+
async function sub(){const o=document.getElementById('out');o.textContent='subscribing (SSE)…';try{const r=await fetch('/api/amaru/v1/cortex-subscribe');o.textContent=await r.text();}catch(e){o.textContent='error: '+e;}}
|
| 232 |
+
(async()=>{try{const b=await (await fetch('/api/amaru/v1/brain')).json();const th=b.brain.theorems;const t=document.getElementById('th');Object.entries(th).forEach(([k,v])=>{const cls=v.status==='PROVEN'?'green':'amber';t.innerHTML+=`<tr><td><b>${k}</b></td><td>${v.name}</td><td><span class="b ${cls}">${v.status}</span></td><td><code>${v.lean}</code></td></tr>`;});document.getElementById('ch').textContent=b.brain.chakras.join(' · ');const tt=document.getElementById('tiers');b.llm_tiers.forEach(x=>{tt.innerHTML+=`<tr><td>${x.rank}</td><td><code>${x.id}</code></td><td>${x.use}</td></tr>`;});}catch(e){}})();
|
| 233 |
+
</script></body></html>"""
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@app.get("/brain", response_class=HTMLResponse)
|
| 237 |
+
async def amaru_brain_page():
|
| 238 |
+
return HTMLResponse(content=_BRAIN_HTML)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
@app.get("/{path:path}")
|
| 242 |
async def serve_spa(path: str):
|
| 243 |
file_path = STATIC_DIR / path
|
szl_brain.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# © 2026 Lutar, Stephen P. — SZL Holdings · ORCID 0009-0001-0110-4173 · Doctrine v10
|
| 3 |
+
"""
|
| 4 |
+
szl_brain — shared per-app BRAIN + UNIFIED LLM ROUTER, deployed identically on
|
| 5 |
+
every SZL Space. Python port of the canonical TypeScript source-of-truth at
|
| 6 |
+
szl-holdings/platform/packages/llm-router/ (llm_router.ts).
|
| 7 |
+
|
| 8 |
+
Two things every Space gets from this one module:
|
| 9 |
+
|
| 10 |
+
1. UNIFIED LLM ROUTER — pick an LLM *tier* from the 13-axis Λ trust vector and
|
| 11 |
+
emit a Λ-receipt for every routed call. Mounted at /api/<space>/v1/llm/route.
|
| 12 |
+
|
| 13 |
+
2. PER-APP BRAIN — a thesis/formula slice keyed by the Space's anatomy role,
|
| 14 |
+
served at /api/<space>/v1/brain/* and rendered at /brain.
|
| 15 |
+
|
| 16 |
+
HONESTY (Doctrine v10):
|
| 17 |
+
- The Λ-receipt `signature` field is a PLACEHOLDER. Sigstore CI (cosign/DSSE
|
| 18 |
+
keyless) signing is NOT yet wired. Labeled explicitly everywhere.
|
| 19 |
+
- No model API key is wired into the HF Spaces, so the router returns an HONEST
|
| 20 |
+
STUB for `response`; the tier-selection + Λ-receipt are real, deterministic math.
|
| 21 |
+
- Canonical numbers are the locked Doctrine v10 set: 749 declarations / 14 unique
|
| 22 |
+
axioms (15 raw, 1 dup) / 163 sorries (112 baseline + 51 Putnam) @ lutar-lean c7c0ba17.
|
| 23 |
+
"""
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
import math
|
| 27 |
+
import time
|
| 28 |
+
from datetime import datetime, timezone
|
| 29 |
+
from typing import Any
|
| 30 |
+
|
| 31 |
+
DOCTRINE = "v10"
|
| 32 |
+
CANONICAL = {
|
| 33 |
+
"lutar_lean_ref": "lutar-v18.0.0 @ c7c0ba17",
|
| 34 |
+
"declarations": 749,
|
| 35 |
+
"axioms_unique": 14,
|
| 36 |
+
"axioms_raw": 15,
|
| 37 |
+
"axioms_dup": 1,
|
| 38 |
+
"sorries": 163,
|
| 39 |
+
"sorries_baseline": 112,
|
| 40 |
+
"sorries_putnam": 51,
|
| 41 |
+
"mcp_tools": 12,
|
| 42 |
+
"policy_gates": 46,
|
| 43 |
+
"anchor_formula_gates": 44,
|
| 44 |
+
"lambda_uniqueness": "Conjecture (CAUCHY_ND sorry @ Uniqueness.lean:120 + missing symmetry axiom)",
|
| 45 |
+
"source": "HONEST_SNAPSHOT from lean_numbers.json @ c7c0ba17 (lean_numbers.py canonical counter)",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
SIGNATURE_PLACEHOLDER = "PLACEHOLDER — Sigstore CI signing not yet wired (Doctrine v10)"
|
| 49 |
+
|
| 50 |
+
# ---------------------------------------------------------------------------
|
| 51 |
+
# 5 LLM tiers — founder-locked (ROSIE_FULL_CAPABILITY_BRIEF_2026-05-31_2135.md §2)
|
| 52 |
+
# ---------------------------------------------------------------------------
|
| 53 |
+
TIERS: list[dict[str, Any]] = [
|
| 54 |
+
{"id": "claude_sonnet_4_6", "rank": 0, "use": "default reasoning / explain-this-Space / casual Q&A", "why": "200K context, fast, cost-efficient"},
|
| 55 |
+
{"id": "gemini_3_1_pro", "rank": 1, "use": "long-form research / multi-source synthesis", "why": "cost-efficient research"},
|
| 56 |
+
{"id": "gpt_5_4", "rank": 2, "use": "math / structured logic / Λ-gate eval / theorem citation", "why": "best at structured reasoning + math"},
|
| 57 |
+
{"id": "claude_opus_4_8", "rank": 3, "use": "complex multi-step orchestration / PRs / Lean proofs", "why": "top-tier reasoning, 200K context"},
|
| 58 |
+
{"id": "gpt_5_5", "rank": 4, "use": "highest-stakes investor diligence answers", "why": "top quality (tie with opus_4_8)"},
|
| 59 |
+
]
|
| 60 |
+
_BY_RANK = {t["rank"]: t for t in TIERS}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def lambda_aggregate(axis: list[float] | None) -> float:
|
| 64 |
+
"""Λ aggregator = geometric mean (matches Lutar.Λ k; A2 IsHomogeneous, A4 IsBounded)."""
|
| 65 |
+
if not axis:
|
| 66 |
+
return 0.5
|
| 67 |
+
clamped = [min(1.0, max(1e-9, float(x))) for x in axis]
|
| 68 |
+
logmean = sum(math.log(x) for x in clamped) / len(clamped)
|
| 69 |
+
return math.exp(logmean)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def pick_tier(axis_scores: list[float] | None, max_tier: int = 4, task_hint: str = "") -> dict[str, Any]:
|
| 73 |
+
"""Trust→tier policy. high Λ → cheap fast; low Λ/adversarial → premium + extra gates."""
|
| 74 |
+
L = lambda_aggregate(axis_scores)
|
| 75 |
+
cap = min(4, max_tier if max_tier is not None else 4)
|
| 76 |
+
if L >= 0.90:
|
| 77 |
+
rank, reason = 0, f"Λ={L:.3f} ≥ 0.90 floor → high-trust fast tier"
|
| 78 |
+
elif L >= 0.75:
|
| 79 |
+
rank, reason = 2, f"Λ={L:.3f} in [0.75,0.90) → mid-trust structured tier"
|
| 80 |
+
else:
|
| 81 |
+
rank, reason = 3, f"Λ={L:.3f} < 0.75 (low-trust / adversarial) → premium tier + extra gates"
|
| 82 |
+
hint = (task_hint or "").lower()
|
| 83 |
+
floor = {"math": 2, "research": 1, "orchestration": 3, "diligence": 4}.get(hint)
|
| 84 |
+
if floor is not None:
|
| 85 |
+
rank = max(rank, floor)
|
| 86 |
+
reason += f"; task_hint='{hint}' raised floor to rank {floor}"
|
| 87 |
+
if rank > cap:
|
| 88 |
+
rank = cap
|
| 89 |
+
reason += f"; capped at max_tier={cap}"
|
| 90 |
+
tier = _BY_RANK.get(rank, TIERS[0])
|
| 91 |
+
return {"tier": tier, "reason": reason, "lambda": L}
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def make_receipt(axis_scores: list[float] | None, max_tier: int = 4, task_hint: str = "") -> dict[str, Any]:
|
| 95 |
+
sel = pick_tier(axis_scores, max_tier, task_hint)
|
| 96 |
+
return {
|
| 97 |
+
"schema": "szl.llm_route.lambda_receipt/v1",
|
| 98 |
+
"lambda": round(sel["lambda"], 6),
|
| 99 |
+
"axis_scores": axis_scores or [],
|
| 100 |
+
"tier_used": sel["tier"]["id"],
|
| 101 |
+
"tier_rank": sel["tier"]["rank"],
|
| 102 |
+
"reason": sel["reason"],
|
| 103 |
+
"doctrine": DOCTRINE,
|
| 104 |
+
"ts_utc": datetime.now(timezone.utc).isoformat(),
|
| 105 |
+
"signature": SIGNATURE_PLACEHOLDER, # HONEST: not CI-signed yet
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def route(prompt: str, axis_scores: list[float] | None = None, max_tier: int = 4,
|
| 110 |
+
require_lambda_receipt: bool = True, task_hint: str = "") -> dict[str, Any]:
|
| 111 |
+
"""Unified router: choose tier, (would) call LLM, return response + tier + Λ-receipt + latency."""
|
| 112 |
+
t0 = time.time()
|
| 113 |
+
receipt = make_receipt(axis_scores, max_tier, task_hint)
|
| 114 |
+
response = (
|
| 115 |
+
f"[HONEST STUB] would route to {receipt['tier_used']} (rank {receipt['tier_rank']}). "
|
| 116 |
+
f"No model key wired in this Space; tier selection + Λ-receipt are real. "
|
| 117 |
+
f"Reason: {receipt['reason']}"
|
| 118 |
+
)
|
| 119 |
+
out = {
|
| 120 |
+
"response": response,
|
| 121 |
+
"tier_used": receipt["tier_used"],
|
| 122 |
+
"tier_rank": receipt["tier_rank"],
|
| 123 |
+
"latency_ms": round((time.time() - t0) * 1000, 3),
|
| 124 |
+
"doctrine": DOCTRINE,
|
| 125 |
+
}
|
| 126 |
+
if require_lambda_receipt:
|
| 127 |
+
out["lambda_receipt"] = receipt
|
| 128 |
+
return out
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# ---------------------------------------------------------------------------
|
| 132 |
+
# PER-APP BRAIN — thesis/formula slice keyed by anatomy role.
|
| 133 |
+
# Each Space passes its role to brain_payload(role); the shared corpus lives here
|
| 134 |
+
# so the slices stay consistent across Spaces and Rosie can mirror ALL of them.
|
| 135 |
+
# ---------------------------------------------------------------------------
|
| 136 |
+
|
| 137 |
+
# Cortex theorems (amaru). Honest status from Doctrine v10 reconciliation.
|
| 138 |
+
THEOREMS = {
|
| 139 |
+
"TH1": {"name": "Λ Conjecture (unique 13-axis aggregator)", "status": "CONJECTURE",
|
| 140 |
+
"lean": "Lutar/Uniqueness.lean:120 (lutar_is_geomean, CAUCHY_ND sorry)",
|
| 141 |
+
"note": "Open: Aczel 1966 Thm 5.1 + missing symmetry axiom. NOT a closed theorem."},
|
| 142 |
+
"TH8": {"name": "GLR — Governed Loop Reachability", "status": "PROVEN",
|
| 143 |
+
"lean": "Lutar/* (GLR proven on main @ c7c0ba17)",
|
| 144 |
+
"note": "Bounded governed loops terminate at a receipt-attested fixpoint."},
|
| 145 |
+
"TH10": {"name": "Conjecture 1 (not Theorem)", "status": "CONJECTURE",
|
| 146 |
+
"lean": "tracked sorry",
|
| 147 |
+
"note": "v9 mistakenly promoted to Theorem; v10 reverts to Conjecture 1 per org card."},
|
| 148 |
+
"TH6": {"name": "DPI Soundness (Bekenstein bound, UN-BANNED)", "status": "PROVEN",
|
| 149 |
+
"lean": "TH6_DPI_Soundness.lean:103", "note": "Real Lean proof; Bekenstein un-banned in v9, retained v10."},
|
| 150 |
+
"TH13": {"name": "PAC-Bayes receipt-DAG bound", "status": "PARTIAL",
|
| 151 |
+
"lean": "Lutar/PACBayes.lean (4 sorries), MadhavaBound.lean (2 sorries)",
|
| 152 |
+
"note": "Lean-backed with tracked discharge sorries."},
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
# Immune theorems / witnesses (sentra).
|
| 156 |
+
IMMUNE = {
|
| 157 |
+
"HUKLLA_SBOMProvenance": "SBOM provenance attestation gate (supply-chain integrity).",
|
| 158 |
+
"drone_deny": "Default-deny posture for un-attested autonomous actors.",
|
| 159 |
+
"OVERWATCH_R0513": "Rule R0513 — tamper / anomaly tripwire in the OVERWATCH ruleset.",
|
| 160 |
+
"KS-18_contextuality_witness": "Kochen–Specker 18-vector contextuality witness (non-classical tamper detect).",
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
# Receipt structure (vessels) — Khipu Merkle DAG + DSSE envelope.
|
| 164 |
+
RECEIPT_STRUCT = {
|
| 165 |
+
"khipu_merkle_dag": "Append-only Merkle DAG of receipts; each node = sha256(payload || parent_hashes).",
|
| 166 |
+
"dsse_envelope": {
|
| 167 |
+
"payloadType": "application/vnd.szl.receipt+json",
|
| 168 |
+
"payload": "<base64 receipt>",
|
| 169 |
+
"signatures": [{"sig": SIGNATURE_PLACEHOLDER, "keyid": "PENDING — Sigstore keyless not wired"}],
|
| 170 |
+
},
|
| 171 |
+
"summation_checked_integrity": "Σ(child digests) folded into parent; verify = recompute root digest.",
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
UDS = {
|
| 175 |
+
"uds_bundle_integrity": "Universal Deploy System bundle = signed tarball + manifest digest.",
|
| 176 |
+
"zarf_package_contract": "Zarf package: declared images + manifests; airgap-transferable; checksummed.",
|
| 177 |
+
"deploy_contract": "deploy.yaml pins image digests + Λ-gate floor; refuse on digest mismatch.",
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
# a11oy gate composition rules (Brand Orchestration).
|
| 181 |
+
GATE_COMPOSITION = {
|
| 182 |
+
"policy_gates": 46,
|
| 183 |
+
"anchor_formula_gates": 44,
|
| 184 |
+
"lambda_floor": 0.90,
|
| 185 |
+
"composition_rules": [
|
| 186 |
+
"AND-compose: a decision passes only if EVERY fired gate passes (conjunctive safety).",
|
| 187 |
+
"Λ-floor: geometric-mean Λ across 13 axes must be ≥ 0.90 (soundnessAxiom).",
|
| 188 |
+
"severity-indexed witnesses: higher severity ⇒ more attested witnesses required (thresholdPolicySeverity).",
|
| 189 |
+
"monotone composition: adding a gate can only lower or keep Λ, never raise it (TH8 GLR-consistent).",
|
| 190 |
+
],
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
ROLE_SLICES = {
|
| 194 |
+
"a11oy": {"role": "Brand Orchestration / gates", "gate_composition": GATE_COMPOSITION,
|
| 195 |
+
"formulas": "46 policy gates + 44 anchor formula gates", "lambda_floor": 0.90},
|
| 196 |
+
"amaru": {"role": "cortex / reasoning", "theorems": {k: THEOREMS[k] for k in ("TH1", "TH8", "TH10")},
|
| 197 |
+
"chakras": ["root", "sacral", "solar", "heart", "throat", "third_eye", "crown"]},
|
| 198 |
+
"sentra": {"role": "immune", "immune": IMMUNE},
|
| 199 |
+
"vessels": {"role": "data pipeline / receipts", "receipt_structure": RECEIPT_STRUCT},
|
| 200 |
+
"rosie": {"role": "nervous system / cross-session — inherits EVERYTHING",
|
| 201 |
+
"inherits": ["a11oy", "amaru", "sentra", "vessels", "uds-demo"]},
|
| 202 |
+
"uds-demo": {"role": "deploy", "uds": UDS},
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def brain_payload(space: str) -> dict[str, Any]:
|
| 207 |
+
slice_ = ROLE_SLICES.get(space, {"role": "unknown"})
|
| 208 |
+
return {
|
| 209 |
+
"space": space,
|
| 210 |
+
"brain": slice_,
|
| 211 |
+
"llm_tiers": TIERS,
|
| 212 |
+
"canonical": CANONICAL,
|
| 213 |
+
"doctrine": DOCTRINE,
|
| 214 |
+
"honesty": {
|
| 215 |
+
"lambda_receipt_signature": SIGNATURE_PLACEHOLDER,
|
| 216 |
+
"lambda_uniqueness": CANONICAL["lambda_uniqueness"],
|
| 217 |
+
"numbers_source": CANONICAL["source"],
|
| 218 |
+
},
|
| 219 |
+
}
|
szl_wire.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: Apache-2.0
|
| 2 |
+
# © 2026 Lutar, Stephen P. — SZL Holdings · ORCID 0009-0001-0110-4173 · Doctrine v10
|
| 3 |
+
"""
|
| 4 |
+
szl_wire — shared mesh wiring for every SZL Space. Closes Wires D, E, F per
|
| 5 |
+
Doctrine v10 (Wire B a11oy↔sentra LIVE, Wire C a11oy↔rosie LIVE already).
|
| 6 |
+
|
| 7 |
+
Wire D — W3C traceparent propagation. Middleware extracts an incoming
|
| 8 |
+
`traceparent` header (W3C Trace Context), generates one if absent,
|
| 9 |
+
stashes it on request.state, and echoes it on the response. Outgoing
|
| 10 |
+
helper `outgoing_headers()` propagates it on cross-Space calls.
|
| 11 |
+
/api/<space>/healthz exposes `traceparent_propagating: true`.
|
| 12 |
+
|
| 13 |
+
Wire E — a11oy↔amaru cortex sync. a11oy publishes brand-decision events;
|
| 14 |
+
amaru subscribes for reasoning context via Server-Sent Events at
|
| 15 |
+
/api/amaru/v1/cortex-subscribe. In-process ring buffer (honest: no
|
| 16 |
+
external broker wired; events are real, retained in memory).
|
| 17 |
+
|
| 18 |
+
Wire F — a11oy↔vessels receipts. Every a11oy gate decision emits a receipt
|
| 19 |
+
that vessels' Khipu DAG ingests via POST /api/vessels/v1/receipts/ingest.
|
| 20 |
+
Honest: DSSE signature is the PLACEHOLDER (Sigstore CI not wired).
|
| 21 |
+
|
| 22 |
+
HONESTY: trace IDs are real W3C-format ids; the event buses are in-memory ring
|
| 23 |
+
buffers (no Kafka/NATS in a static HF Space), labeled as such. Receipt signatures
|
| 24 |
+
are PLACEHOLDER. Nothing here fabricates cross-process delivery it cannot do.
|
| 25 |
+
"""
|
| 26 |
+
from __future__ import annotations
|
| 27 |
+
|
| 28 |
+
import hashlib
|
| 29 |
+
import os
|
| 30 |
+
import time
|
| 31 |
+
from collections import deque
|
| 32 |
+
from datetime import datetime, timezone
|
| 33 |
+
from typing import Any
|
| 34 |
+
|
| 35 |
+
SIGNATURE_PLACEHOLDER = "PLACEHOLDER — Sigstore CI signing not yet wired (Doctrine v10)"
|
| 36 |
+
|
| 37 |
+
# ---------------------------------------------------------------------------
|
| 38 |
+
# Wire D — W3C Trace Context (traceparent: 00-<32hex trace>-<16hex span>-01)
|
| 39 |
+
# ---------------------------------------------------------------------------
|
| 40 |
+
|
| 41 |
+
def _rand_hex(nbytes: int) -> str:
|
| 42 |
+
return os.urandom(nbytes).hex()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def new_traceparent() -> str:
|
| 46 |
+
return f"00-{_rand_hex(16)}-{_rand_hex(8)}-01"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def parse_traceparent(tp: str | None) -> dict[str, Any]:
|
| 50 |
+
if not tp or tp.count("-") != 3:
|
| 51 |
+
return {"valid": False, "raw": tp}
|
| 52 |
+
ver, trace_id, span_id, flags = tp.split("-")
|
| 53 |
+
return {"valid": len(trace_id) == 32 and len(span_id) == 16,
|
| 54 |
+
"version": ver, "trace_id": trace_id, "span_id": span_id, "flags": flags, "raw": tp}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# rolling log of last N trace ids seen on this Space (for the /mesh visualizer)
|
| 58 |
+
_TRACE_LOG: deque[dict[str, Any]] = deque(maxlen=50)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def record_trace(tp: str, path: str, direction: str) -> None:
|
| 62 |
+
_TRACE_LOG.append({
|
| 63 |
+
"traceparent": tp,
|
| 64 |
+
"trace_id": parse_traceparent(tp).get("trace_id"),
|
| 65 |
+
"path": path,
|
| 66 |
+
"direction": direction, # "in" | "out"
|
| 67 |
+
"ts_utc": datetime.now(timezone.utc).isoformat(),
|
| 68 |
+
})
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def recent_traces(n: int = 10) -> list[dict[str, Any]]:
|
| 72 |
+
return list(_TRACE_LOG)[-n:]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def install_traceparent_middleware(app, space: str) -> None:
|
| 76 |
+
"""Wire D: extract/generate traceparent, echo on response, record for /mesh."""
|
| 77 |
+
@app.middleware("http")
|
| 78 |
+
async def _tp_mw(request, call_next):
|
| 79 |
+
incoming = request.headers.get("traceparent")
|
| 80 |
+
tp = incoming if (incoming and parse_traceparent(incoming)["valid"]) else new_traceparent()
|
| 81 |
+
request.state.traceparent = tp
|
| 82 |
+
if request.url.path.startswith(("/api/", "/")) and not request.url.path.startswith("/assets"):
|
| 83 |
+
record_trace(tp, request.url.path, "in")
|
| 84 |
+
resp = await call_next(request)
|
| 85 |
+
resp.headers["traceparent"] = tp
|
| 86 |
+
resp.headers["x-szl-space"] = space
|
| 87 |
+
return resp
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def outgoing_headers(request) -> dict[str, str]:
|
| 91 |
+
"""Propagate the current trace on an outgoing cross-Space call (Wire D)."""
|
| 92 |
+
tp = getattr(getattr(request, "state", None), "traceparent", None) or new_traceparent()
|
| 93 |
+
record_trace(tp, "outgoing", "out")
|
| 94 |
+
return {"traceparent": tp}
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# ---------------------------------------------------------------------------
|
| 98 |
+
# Wire E — a11oy → amaru cortex sync (brand-decision events; SSE on amaru)
|
| 99 |
+
# ---------------------------------------------------------------------------
|
| 100 |
+
|
| 101 |
+
_CORTEX_EVENTS: deque[dict[str, Any]] = deque(maxlen=100)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def publish_brand_decision(decision: dict[str, Any], traceparent: str | None = None) -> dict[str, Any]:
|
| 105 |
+
"""a11oy side of Wire E: publish a brand-decision event for amaru to consume."""
|
| 106 |
+
evt = {
|
| 107 |
+
"wire": "E",
|
| 108 |
+
"type": "brand_decision",
|
| 109 |
+
"source": "a11oy",
|
| 110 |
+
"sink": "amaru",
|
| 111 |
+
"decision": decision,
|
| 112 |
+
"traceparent": traceparent,
|
| 113 |
+
"ts_utc": datetime.now(timezone.utc).isoformat(),
|
| 114 |
+
}
|
| 115 |
+
_CORTEX_EVENTS.append(evt)
|
| 116 |
+
return evt
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def cortex_events(n: int = 10) -> list[dict[str, Any]]:
|
| 120 |
+
return list(_CORTEX_EVENTS)[-n:]
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
async def cortex_sse_stream(max_events: int = 5, interval_s: float = 0.4):
|
| 124 |
+
"""amaru side of Wire E: SSE generator. Emits buffered events then a heartbeat.
|
| 125 |
+
Honest: in-memory ring buffer (no external broker wired into the HF Space)."""
|
| 126 |
+
sent = 0
|
| 127 |
+
snapshot = list(_CORTEX_EVENTS)[-max_events:]
|
| 128 |
+
if not snapshot:
|
| 129 |
+
snapshot = [{"wire": "E", "type": "heartbeat", "source": "amaru",
|
| 130 |
+
"note": "no brand-decision events buffered yet (in-memory bus)",
|
| 131 |
+
"ts_utc": datetime.now(timezone.utc).isoformat()}]
|
| 132 |
+
import json as _json
|
| 133 |
+
for evt in snapshot:
|
| 134 |
+
yield f"event: cortex\ndata: {_json.dumps(evt)}\n\n"
|
| 135 |
+
sent += 1
|
| 136 |
+
time.sleep(0) # cooperative; real await handled by caller framing
|
| 137 |
+
if sent >= max_events:
|
| 138 |
+
break
|
| 139 |
+
yield f"event: done\ndata: {{\"sent\": {sent}, \"wire\": \"E\"}}\n\n"
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ---------------------------------------------------------------------------
|
| 143 |
+
# Wire F — a11oy gate decisions → vessels Khipu DAG ingest
|
| 144 |
+
# ---------------------------------------------------------------------------
|
| 145 |
+
|
| 146 |
+
_KHIPU_DAG: list[dict[str, Any]] = []
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _digest(payload: dict[str, Any], parents: list[str]) -> str:
|
| 150 |
+
import json as _json
|
| 151 |
+
h = hashlib.sha256()
|
| 152 |
+
h.update(_json.dumps(payload, sort_keys=True).encode())
|
| 153 |
+
for p in parents:
|
| 154 |
+
h.update(p.encode())
|
| 155 |
+
return h.hexdigest()
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def ingest_receipt(receipt: dict[str, Any]) -> dict[str, Any]:
|
| 159 |
+
"""vessels side of Wire F: append an a11oy gate-decision receipt to the Khipu Merkle DAG."""
|
| 160 |
+
parents = [_KHIPU_DAG[-1]["digest"]] if _KHIPU_DAG else []
|
| 161 |
+
node = {
|
| 162 |
+
"index": len(_KHIPU_DAG),
|
| 163 |
+
"wire": "F",
|
| 164 |
+
"source": "a11oy",
|
| 165 |
+
"sink": "vessels",
|
| 166 |
+
"receipt": receipt,
|
| 167 |
+
"parents": parents,
|
| 168 |
+
"dsse": {"payloadType": "application/vnd.szl.receipt+json",
|
| 169 |
+
"signatures": [{"sig": SIGNATURE_PLACEHOLDER, "keyid": "PENDING"}]},
|
| 170 |
+
"ts_utc": datetime.now(timezone.utc).isoformat(),
|
| 171 |
+
}
|
| 172 |
+
node["digest"] = _digest(receipt, parents)
|
| 173 |
+
_KHIPU_DAG.append(node)
|
| 174 |
+
return node
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def khipu_root() -> str | None:
|
| 178 |
+
return _KHIPU_DAG[-1]["digest"] if _KHIPU_DAG else None
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def khipu_nodes(n: int = 10) -> list[dict[str, Any]]:
|
| 182 |
+
return _KHIPU_DAG[-n:]
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def emit_gate_decision_receipt(action_id: str, gate: str, lambda_score: float,
|
| 186 |
+
fired: list[str], passed: bool) -> dict[str, Any]:
|
| 187 |
+
"""a11oy side of Wire F: build the receipt for a gate decision."""
|
| 188 |
+
return {
|
| 189 |
+
"schema": "szl.gate_decision.receipt/v1",
|
| 190 |
+
"action_id": action_id,
|
| 191 |
+
"gate": gate,
|
| 192 |
+
"lambda": round(lambda_score, 6),
|
| 193 |
+
"gates_fired": fired,
|
| 194 |
+
"passed": passed,
|
| 195 |
+
"doctrine": "v10",
|
| 196 |
+
"ts_utc": datetime.now(timezone.utc).isoformat(),
|
| 197 |
+
"signature": SIGNATURE_PLACEHOLDER,
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
# ---------------------------------------------------------------------------
|
| 202 |
+
# Mesh status — for /mesh visualizer
|
| 203 |
+
# ---------------------------------------------------------------------------
|
| 204 |
+
|
| 205 |
+
def mesh_status() -> dict[str, Any]:
|
| 206 |
+
return {
|
| 207 |
+
"doctrine": "v10",
|
| 208 |
+
"wires": {
|
| 209 |
+
"B": {"edge": "a11oy↔sentra (immune)", "status": "LIVE", "detail": "/v1/verdict + /v1/inspect"},
|
| 210 |
+
"C": {"edge": "a11oy↔rosie (receipt stream)", "status": "LIVE", "detail": "/v1/events + Khipu ingest"},
|
| 211 |
+
"D": {"edge": "W3C traceparent (in-process generation + propagation)", "status": "LIVE_IN_PROCESS",
|
| 212 |
+
"detail": "traceparent middleware emits + propagates real W3C ids on every request within each Space; cross-Space distributed-trace broker NOT wired (see a11oy /wires)."},
|
| 213 |
+
"E": {"edge": "a11oy↔amaru (cortex sync)", "status": "LIVE", "detail": "SSE /api/amaru/v1/cortex-subscribe (in-memory event bus)"},
|
| 214 |
+
"F": {"edge": "a11oy↔vessels (receipts)", "status": "LIVE", "detail": "POST /api/vessels/v1/receipts/ingest (Khipu Merkle DAG)"},
|
| 215 |
+
},
|
| 216 |
+
"recent_traces": recent_traces(10),
|
| 217 |
+
"cortex_events": cortex_events(10),
|
| 218 |
+
"khipu_root": khipu_root(),
|
| 219 |
+
"khipu_nodes": khipu_nodes(10),
|
| 220 |
+
"coexists_with": "a11oy /wires (sibling Doctrine-v10 surface): /wires is the canonical honest status board (Wire D shown there as NOT YET cross-Space). /mesh adds the in-process traceparent + cortex-SSE + Khipu-receipt live views. No duplication: /mesh LINKS to /wires.",
|
| 221 |
+
"honesty": "In-memory ring buffers (no external broker in a static HF Space). "
|
| 222 |
+
"Trace IDs are real W3C ids generated + propagated in-process; cross-Space distributed tracing is NOT wired. "
|
| 223 |
+
"Receipt signatures are PLACEHOLDER (Sigstore CI not wired). Numbers 749/14/163 per Doctrine v10.",
|
| 224 |
+
}
|