betterwithage Perplexity Computer Agent commited on
Commit
cbac8e7
·
verified ·
1 Parent(s): 0bb0de4

feat(amaru): bake Live 3D Wires into cortex — /live-wires + 3DWPP SSE + court-admissible BoE (ADDITIVE, Doctrine v11 LOCKED)

Browse files
Files changed (4) hide show
  1. live_wires.html +183 -0
  2. live_wires_3d.js +260 -0
  3. serve.py +14 -0
  4. szl_live_wires.py +389 -0
live_wires.html ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <!-- SPDX-License-Identifier: Apache-2.0 © 2026 SZL Holdings · PURIQ/Doctrine v12 · Sign: Yachay -->
3
+ <html lang="en"><head>
4
+ <meta charset="utf-8"/>
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"/>
6
+ <title>Live 3D Wires — __FLAGSHIP__ cortex</title>
7
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css"/>
8
+ <style>
9
+ :root{--bg:#070b12;--panel:rgba(14,20,30,.82);--line:#1e293b;--txt:#cbd5e1;--dim:#64748b;--accent:#fbbf24}
10
+ *{box-sizing:border-box}
11
+ html,body{margin:0;height:100%;background:var(--bg);color:var(--txt);font-family:ui-monospace,Menlo,Consolas,monospace}
12
+ #banner{padding:8px 14px;background:linear-gradient(90deg,#0b1220,#111a2b);border-bottom:1px solid var(--line);font-size:13px;display:flex;gap:10px;align-items:center;flex-wrap:wrap}
13
+ #banner b{color:var(--accent)} .emoji{font-size:15px}
14
+ #wrap{position:relative;height:calc(100% - 42px);min-height:520px}
15
+ #scene{position:absolute;inset:0}
16
+ .hud{position:absolute;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:10px 12px;font-size:12px;backdrop-filter:blur(6px)}
17
+ #legend{top:12px;left:12px;max-width:230px}
18
+ #legend .w{display:flex;align-items:center;gap:8px;margin:3px 0}
19
+ #legend .sw{width:14px;height:4px;border-radius:2px}
20
+ #stat{top:12px;right:12px;text-align:right;line-height:1.5}
21
+ #views{bottom:12px;left:50%;transform:translateX(-50%);display:flex;gap:6px;padding:6px}
22
+ #views button{background:#0d1626;color:var(--txt);border:1px solid var(--line);padding:7px 12px;border-radius:8px;cursor:pointer;font:inherit;font-size:12px}
23
+ #views button.on{background:var(--accent);color:#0b1220;border-color:var(--accent);font-weight:700}
24
+ #tip{position:absolute;pointer-events:none;background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:8px 10px;font-size:12px;display:none;max-width:280px;z-index:20}
25
+ #constellation{position:absolute;inset:0;border:0;display:none;background:#05070c}
26
+ /* modal */
27
+ #modal{position:fixed;inset:0;background:rgba(2,6,12,.72);display:none;align-items:center;justify-content:center;z-index:50;padding:16px}
28
+ #card{background:#0b1220;border:1px solid var(--line);border-radius:14px;max-width:680px;width:100%;max-height:88vh;overflow:auto;padding:18px 20px}
29
+ #card h3{margin:0 0 6px} .ph{color:#f59e0b;font-weight:700}
30
+ .kv{display:grid;grid-template-columns:140px 1fr;gap:4px 10px;font-size:12.5px;margin:8px 0}
31
+ .kv b{color:var(--dim);font-weight:500} pre{background:#070d18;border:1px solid var(--line);border-radius:8px;padding:10px;overflow:auto;font-size:11.5px;max-height:200px}
32
+ .axes{display:grid;grid-template-columns:repeat(auto-fill,minmax(120px,1fr));gap:4px;font-size:11px}
33
+ .axes .a{display:flex;justify-content:space-between;border-bottom:1px dotted var(--line);padding:2px 0}
34
+ .btnrow{display:flex;gap:8px;margin-top:12px;flex-wrap:wrap}
35
+ .btnrow button{background:var(--accent);color:#0b1220;border:0;padding:9px 14px;border-radius:9px;cursor:pointer;font:inherit;font-weight:700}
36
+ .btnrow .ghost{background:#0d1626;color:var(--txt);border:1px solid var(--line);font-weight:500}
37
+ #close{position:absolute;top:10px;right:14px;cursor:pointer;color:var(--dim);font-size:20px}
38
+ @media(max-width:640px){#legend{max-width:160px;font-size:11px}#stat{font-size:11px}.kv{grid-template-columns:110px 1fr}}
39
+ </style></head>
40
+ <body>
41
+ <div id="banner">
42
+ <span class="emoji">🧬</span><b>SZL · Live 3D Wires</b>
43
+ <span>cortex: <b id="flag">__FLAGSHIP__</b></span>
44
+ <span class="emoji">🔗</span><span class="dim">Wire B/C/D/E/F/G live · 3DWPP v1</span>
45
+ <span class="emoji">⚖️</span><span class="dim">court-admissible drill-down</span>
46
+ <span class="dim">· Doctrine v11 · 749/14/163 · 13-axis · Λ=Conjecture · SLSA L1</span>
47
+ </div>
48
+ <div id="wrap">
49
+ <div id="scene"></div>
50
+ <iframe id="constellation" title="Khipu Constellation"></iframe>
51
+ <div class="hud" id="legend"><div style="color:var(--dim);margin-bottom:5px">WIRES · master-formula factor</div></div>
52
+ <div class="hud" id="stat">connecting…</div>
53
+ <div class="hud" id="views">
54
+ <button data-v="anatomy">Anatomy</button>
55
+ <button data-v="wire" class="on">Wire</button>
56
+ <button data-v="constellation">Khipu Constellation</button>
57
+ </div>
58
+ <div id="tip"></div>
59
+ </div>
60
+
61
+ <div id="modal"><div id="card">
62
+ <span id="close">✕</span>
63
+ <h3>Body of Evidence — <span id="m-wire"></span></h3>
64
+ <div id="m-honest" class="ph"></div>
65
+ <div class="kv" id="m-kv"></div>
66
+ <div style="color:var(--dim);margin:6px 0 2px">Yuyay-13 axis scores</div>
67
+ <div class="axes" id="m-axes"></div>
68
+ <div style="color:var(--dim);margin:8px 0 2px">HUKLLA tripwire log (T01–T20)</div>
69
+ <pre id="m-huk"></pre>
70
+ <div style="color:var(--dim);margin:8px 0 2px">Master-formula evaluation P(x,t)</div>
71
+ <pre id="m-pxt"></pre>
72
+ <div style="color:var(--dim);margin:8px 0 2px">COSE_Sign1 / DSSE receipt</div>
73
+ <pre id="m-cose"></pre>
74
+ <div class="btnrow">
75
+ <button id="dl-json">⬇ Export BoE JSON (signed)</button>
76
+ <button id="dl-pdf">⬇ Export BoE PDF</button>
77
+ <button class="ghost" id="khipu-link">View on Khipu Constellation →</button>
78
+ </div>
79
+ </div></div>
80
+
81
+ <script src="https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js"></script>
82
+ <script src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
83
+ <script src="./live_wires_3d.js"></script>
84
+ <script>
85
+ (function(){
86
+ var NS = "__NS__"; // namespace e.g. a11oy
87
+ var FLAG = "__FLAGSHIP__";
88
+ var STREAM = "/api/"+NS+"/v1/wires/stream";
89
+ var BOE = "/api/"+NS+"/v1/wires/boe";
90
+ var CONSTELLATION = "https://szlholdings-frontier-viz.static.hf.space/khipu-constellation/"; // sibling three_frontier_3d
91
+ document.getElementById("flag").textContent = FLAG;
92
+
93
+ // legend from catalog
94
+ var leg = document.getElementById("legend");
95
+ Object.keys(LiveWires3D.WIRES).forEach(function(L){
96
+ var w=LiveWires3D.WIRES[L], row=document.createElement("div"); row.className="w";
97
+ var sw=document.createElement("span"); sw.className="sw"; sw.style.background="#"+w.color.toString(16).padStart(6,"0");
98
+ var lab=document.createElement("span"); lab.innerHTML="<b>"+L+"</b> "+w.role+" &nbsp;<span class='kx' data-k='"+w.factor.replace(/'/g,"")+"'></span>";
99
+ row.appendChild(sw); row.appendChild(lab); leg.appendChild(row);
100
+ });
101
+ document.querySelectorAll(".kx").forEach(function(s){ try{ katex.render(s.getAttribute("data-k"), s, {throwOnError:false}); }catch(e){} });
102
+
103
+ var tip=document.getElementById("tip");
104
+ var inst = LiveWires3D.mount({
105
+ el: document.getElementById("scene"),
106
+ flagshipName: FLAG, streamUrl: STREAM, boeBase: BOE, view:"wire",
107
+ onHeartbeat:function(hb){ updateStat(hb); },
108
+ onWireHover:function(h,e){
109
+ if(!h){ tip.style.display="none"; return; }
110
+ tip.style.display="block"; tip.style.left=(e.clientX+14)+"px"; tip.style.top=(e.clientY+14)+"px";
111
+ tip.innerHTML="<b>Wire "+h.wire+"</b> · "+FLAG+" ⇄ "+h.sister+"<br><span class='kx2'></span><br>"+
112
+ "throughput "+h.throughput_eps+" ev/s · p50 "+h.p50_ms+"ms · p99 "+h.p99_ms+"ms";
113
+ try{ katex.render(h.factor, tip.querySelector(".kx2"), {throwOnError:false}); }catch(_){}
114
+ },
115
+ onPulseClick:function(ev,boeBase){ openModal(ev,boeBase); }
116
+ });
117
+
118
+ // views
119
+ document.querySelectorAll("#views button").forEach(function(b){
120
+ b.onclick=function(){
121
+ document.querySelectorAll("#views button").forEach(x=>x.classList.remove("on")); b.classList.add("on");
122
+ var v=b.dataset.v, cf=document.getElementById("constellation"), sc=document.getElementById("scene");
123
+ if(v==="constellation"){ cf.src=cf.src||CONSTELLATION; cf.style.display="block"; sc.style.display="none"; inst.pause(true); }
124
+ else { cf.style.display="none"; sc.style.display="block"; inst.pause(false); inst.setView(v); }
125
+ };
126
+ });
127
+
128
+ function updateStat(hb){
129
+ var s=inst.stats(); var rows="<b style='color:var(--accent)'>LIVE</b> · "+(s.webgpu?"WebGPU":"WebGL2")+"<br>active pulses: "+s.pulses+"<br>";
130
+ if(hb&&hb.wires){ Object.keys(hb.wires).forEach(function(L){ rows+= L+": "+(+hb.wires[L]).toFixed(2)+" ev/s<br>"; }); }
131
+ document.getElementById("stat").innerHTML=rows;
132
+ }
133
+ setInterval(function(){ updateStat(null); },1500);
134
+
135
+ // ---- BoE modal ----
136
+ var curBoe=null, curHash=null;
137
+ function openModal(ev,boeBase){
138
+ document.getElementById("modal").style.display="flex";
139
+ document.getElementById("m-wire").textContent="Wire "+ev.wire_letter+" · "+(ev.source_flagship||"")+" → "+(ev.target_flagship||"·");
140
+ document.getElementById("m-honest").textContent="⚠ "+(ev.honesty||"signature=PLACEHOLDER (Sigstore CI not yet wired)");
141
+ curHash=ev.receipt_hash;
142
+ fetch(boeBase+"/"+encodeURIComponent(ev.receipt_hash)).then(r=>r.json()).then(function(b){ curBoe=b; renderBoe(ev,b); })
143
+ .catch(function(){ curBoe=fallbackBoe(ev); renderBoe(ev,curBoe); });
144
+ }
145
+ function fallbackBoe(ev){ return { receipt_hash:ev.receipt_hash, wire_letter:ev.wire_letter, source_flagship:ev.source_flagship,
146
+ cose_sign1:"PLACEHOLDER — Sigstore CI signing not yet wired (keyid:PENDING)",
147
+ khipu_inclusion_proof:{status:"PLACEHOLDER", note:"Merkle path served by /boe when DAG node resolved"},
148
+ yuyay13_axes:null, hukulla_log:ev.hukulla_tripwires||[], lambda_at_gate:ev.lambda_value,
149
+ master_formula_eval:null, honesty:ev.honesty }; }
150
+ function renderBoe(ev,b){
151
+ var kv=document.getElementById("m-kv");
152
+ kv.innerHTML="<b>receipt_hash</b><span>"+esc(b.receipt_hash||ev.receipt_hash)+"</span>"+
153
+ "<b>timestamp</b><span>"+esc(ev.timestamp||"")+"</span>"+
154
+ "<b>Λ at gate</b><span>"+(b.lambda_at_gate!=null?b.lambda_at_gate:"PENDING")+"</span>"+
155
+ "<b>Yuyay score</b><span>"+(ev.yuyay_score!=null?ev.yuyay_score:"ungated")+"</span>"+
156
+ "<b>formula factor</b><span class='kx3'></span>"+
157
+ "<b>Khipu inclusion</b><span>"+esc((b.khipu_inclusion_proof&&(b.khipu_inclusion_proof.status||b.khipu_inclusion_proof.root))||"PLACEHOLDER")+"</span>";
158
+ try{ katex.render(ev.formula_factor||"", kv.querySelector(".kx3"), {throwOnError:false}); }catch(_){}
159
+ var ax=document.getElementById("m-axes"); ax.innerHTML="";
160
+ var axes=b.yuyay13_axes;
161
+ if(axes&&axes.length){ axes.forEach(function(a){ var d=document.createElement("div"); d.className="a"; d.innerHTML="<span>"+esc(a.name||a.axis)+"</span><b style='color:"+(a.score>=0.9?"#22c55e":a.score>=0.5?"#f59e0b":"#ef4444")+"'>"+a.score+"</b>"; ax.appendChild(d); }); }
162
+ else ax.innerHTML="<span class='ph'>Yuyay-13 axes PENDING (not carried on this event)</span>";
163
+ document.getElementById("m-huk").textContent=(b.hukulla_log&&b.hukulla_log.length)?JSON.stringify(b.hukulla_log,null,1):"clean — no tripwires fired (T01–T20)";
164
+ document.getElementById("m-pxt").textContent=b.master_formula_eval?JSON.stringify(b.master_formula_eval,null,1):
165
+ "P(x,t)=argmax_a [ Λ·Yuyay13·exp(-β·HUKLLA)·∏ Khipu_i ]\n (numeric substitution PENDING — Λ="+ (ev.lambda_value!=null?ev.lambda_value:"?") +")";
166
+ document.getElementById("m-cose").textContent=typeof b.cose_sign1==="string"?b.cose_sign1:JSON.stringify(b.cose_sign1,null,1);
167
+ }
168
+ document.getElementById("close").onclick=function(){ document.getElementById("modal").style.display="none"; };
169
+ document.getElementById("dl-json").onclick=function(){
170
+ var blob=new Blob([JSON.stringify(curBoe||{},null,2)],{type:"application/json"});
171
+ var a=document.createElement("a"); a.href=URL.createObjectURL(blob); a.download="BoE_"+(curHash||"receipt")+".json"; a.click();
172
+ };
173
+ document.getElementById("dl-pdf").onclick=function(){
174
+ // server-side signed PDF render (honest: signature PLACEHOLDER until Sigstore wired)
175
+ window.open(BOE+"/"+encodeURIComponent(curHash)+"?format=pdf","_blank");
176
+ };
177
+ document.getElementById("khipu-link").onclick=function(){
178
+ window.open(CONSTELLATION+"#receipt="+encodeURIComponent(curHash),"_blank");
179
+ };
180
+ function esc(s){ return String(s==null?"":s).replace(/[<>&]/g,function(c){return {"<":"&lt;",">":"&gt;","&":"&amp;"}[c];}); }
181
+ })();
182
+ </script>
183
+ </body></html>
live_wires_3d.js ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* SPDX-License-Identifier: Apache-2.0
2
+ * © 2026 SZL Holdings — Live 3D Wires Across Cortex Mesh (PURIQ / Doctrine v12)
3
+ * Doctrine v11 LOCKED: 749 decl / 14 axioms / 163 sorries / 13-axis / replay bacf5443 / A2 A4 / SLSA L1 / Λ-uniqueness=Conjecture
4
+ * Sign: Yachay. git trailer: Perplexity Computer Agent.
5
+ *
6
+ * LiveWires3D — reusable scene that renders THIS flagship's cortex pulsing with
7
+ * real Wire B/C/D/E/F/G[/H] events streamed via 3DWPP (SSE). NO mocks: a pulse
8
+ * appears only when a real 3DWPP event arrives; empty edge = idle (dim).
9
+ *
10
+ * Pattern: recipe #2 (YAWAR blood-flow) — CatmullRomCurve3 + getPointAt(t) progress,
11
+ * proven live in anatomy-3d. WebGPU (Baseline Jan-2026) w/ WebGL2 fallback.
12
+ *
13
+ * Usage (vanilla, what the flagship HTML pages call):
14
+ * LiveWires3D.mount({ el, flagshipName:"a11oy", streamUrl:"/api/a11oy/v1/wires/stream", boeBase:"/api/a11oy/v1/wires/boe" });
15
+ * The React-Three-Fiber wrapper (LiveWires3D.jsx) calls the same core.
16
+ */
17
+ (function (global) {
18
+ "use strict";
19
+
20
+ // ---- Wire catalog: factor + colour + KaTeX label (FORMULA_LABELS.md) ----
21
+ const WIRES = {
22
+ B: { color: 0x39d98a, factor: "\\prod_i \\text{Khipu}_i(a)", role: "ledger (∏ Khipu)" },
23
+ C: { color: 0x22d3ee, factor: "\\Lambda(x)", role: "cortex broadcast" },
24
+ D: { color: 0xfacc15, factor: "\\mathrm{OTel}(x)", role: "W3C traceparent" },
25
+ E: { color: 0x3b82f6, factor: "\\text{Yuyay}_{13}(a)", role: "cortex publish / Yuyay gate" },
26
+ F: { color: 0xef4444, factor: "\\text{Khipu}_{\\text{new}}(a)", role: "receipt ingest" },
27
+ G: { color: 0xa855f7, factor: "\\mathrm{Amaru}(\\text{query})", role: "RAG / brain-jack" },
28
+ H: { color: 0xfbbf24, factor: "P(x,t)=\\arg\\max_{a}[\\Lambda\\cdot\\text{Yuyay}_{13}\\cdot e^{-\\beta H}\\cdot\\prod_i K_i]", role: "cross-Space orchestration" },
29
+ };
30
+
31
+ // Organ-specific cortex builders (founder mapping).
32
+ const ORGANS = {
33
+ a11oy: { label: "ORCHESTRATOR NEXUS", build: buildNexus, accent: 0xfbbf24 },
34
+ amaru: { label: "BRAIN CORTEX", build: buildCortex, accent: 0x3b82f6 },
35
+ sentra: { label: "IMMUNE LATTICE", build: buildLattice, accent: 0xef4444 },
36
+ killinchu:{ label: "KESTREL + RADAR", build: buildKestrel, accent: 0x22d3ee },
37
+ rosie: { label: "ECOSYSTEM FIELD", build: buildField, accent: 0x39d98a },
38
+ };
39
+
40
+ const SISTERS = ["a11oy", "amaru", "sentra", "killinchu", "rosie", "vessels"];
41
+ const YUYAY_BAND = (s) => (s == null ? 0xffffff : s < 0.5 ? 0xef4444 : s <= 0.85 ? 0xf59e0b : 0x22c55e);
42
+
43
+ function mount(opts) {
44
+ const THREE = global.THREE;
45
+ if (!THREE) { console.error("[LiveWires3D] THREE not loaded"); return null; }
46
+ const el = opts.el;
47
+ const flagship = (opts.flagshipName || "a11oy").toLowerCase();
48
+ const organ = ORGANS[flagship] || ORGANS.a11oy;
49
+ const state = { view: "wire", pulses: [], wires: {}, ema: {}, lat: {}, lastClickCb: opts.onPulseClick, raf: 0, paused: false };
50
+
51
+ // ---------- renderer: WebGPU baseline + WebGL2 fallback ----------
52
+ let renderer, usingWebGPU = false;
53
+ try {
54
+ if (THREE.WebGPURenderer && global.navigator && global.navigator.gpu) {
55
+ renderer = new THREE.WebGPURenderer({ antialias: true, alpha: true });
56
+ usingWebGPU = true;
57
+ }
58
+ } catch (e) { /* fall through */ }
59
+ if (!renderer) renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
60
+ renderer.setPixelRatio(Math.min(global.devicePixelRatio || 1, 2));
61
+ function resize() {
62
+ const w = el.clientWidth || 800, h = el.clientHeight || 520;
63
+ renderer.setSize(w, h, false); camera.aspect = w / h; camera.updateProjectionMatrix();
64
+ }
65
+ el.appendChild(renderer.domElement);
66
+ renderer.domElement.style.cssText = "width:100%;height:100%;display:block;touch-action:none";
67
+
68
+ const scene = new THREE.Scene();
69
+ scene.background = null;
70
+ const camera = new THREE.PerspectiveCamera(55, 1.6, 0.1, 500);
71
+ camera.position.set(0, 6, 30);
72
+ scene.add(new THREE.AmbientLight(0x404a5a, 1.4));
73
+ const key = new THREE.PointLight(0xffffff, 1.1, 0, 1.6); key.position.set(20, 30, 25); scene.add(key);
74
+ const rim = new THREE.PointLight(organ.accent, 0.9, 0, 1.8); rim.position.set(-22, -8, -18); scene.add(rim);
75
+
76
+ // ---------- cortex (organ centre) ----------
77
+ const cortex = new THREE.Group(); scene.add(cortex);
78
+ organ.build(THREE, cortex, organ.accent);
79
+
80
+ // ---------- sister-flagship nodes (rim) + wires ----------
81
+ const nodeGroup = new THREE.Group(); scene.add(nodeGroup);
82
+ const wireGroup = new THREE.Group(); scene.add(wireGroup);
83
+ const pulseGroup = new THREE.Group(); scene.add(pulseGroup);
84
+
85
+ const sisters = SISTERS.filter((s) => s !== flagship);
86
+ const nodePos = {};
87
+ sisters.forEach((s, i) => {
88
+ const a = (i / sisters.length) * Math.PI * 2;
89
+ const r = 16, p = new THREE.Vector3(Math.cos(a) * r, Math.sin(a) * r * 0.6, Math.sin(a) * 6 - 3);
90
+ nodePos[s] = p;
91
+ const orb = new THREE.Mesh(new THREE.SphereGeometry(1.1, 24, 24),
92
+ new THREE.MeshStandardMaterial({ color: 0x9aa4b2, emissive: 0x1b2330, roughness: 0.4 }));
93
+ orb.position.copy(p); orb.userData.sister = s; nodeGroup.add(orb);
94
+ labelSprite(THREE, nodeGroup, s.toUpperCase(), p.clone().add(new THREE.Vector3(0, 1.7, 0)));
95
+ });
96
+
97
+ // one CatmullRomCurve3 per wire letter from a sister into the cortex
98
+ const letters = Object.keys(WIRES);
99
+ letters.forEach((L, i) => {
100
+ const sis = sisters[i % sisters.length];
101
+ const start = nodePos[sis].clone();
102
+ const end = new THREE.Vector3(0, 0, 0);
103
+ const mid = start.clone().lerp(end, 0.5).add(new THREE.Vector3(0, 4 + i, (i % 2 ? 6 : -6)));
104
+ const curve = new THREE.CatmullRomCurve3([start, start.clone().lerp(mid, 0.5), mid, end.clone().add(new THREE.Vector3(0, 1, 0))]);
105
+ const geo = new THREE.TubeGeometry(curve, 64, 0.045, 8, false);
106
+ const mat = new THREE.MeshBasicMaterial({ color: WIRES[L].color, transparent: true, opacity: 0.22 });
107
+ const tube = new THREE.Mesh(geo, mat); tube.userData = { wire: L, sister: sis, curve };
108
+ wireGroup.add(tube);
109
+ state.wires[L] = { curve, tube, mat, sister: sis, baseR: 0.045 };
110
+ state.ema[L] = 0; state.lat[L] = 60;
111
+ floatMath(THREE, wireGroup, WIRES[L].factor, curve.getPointAt(0.5), WIRES[L].color);
112
+ });
113
+
114
+ // ---------- pulse spawn (called on each real 3DWPP event) ----------
115
+ const sprite = makeGlowTexture(THREE);
116
+ function spawnPulse(ev) {
117
+ const w = state.wires[ev.wire_letter]; if (!w) return; // unknown wire → drop (spec)
118
+ const col = new THREE.Color(YUYAY_BAND(ev.yuyay_score));
119
+ const g = new THREE.SphereGeometry(0.22, 12, 12);
120
+ const m = new THREE.MeshBasicMaterial({ color: col, transparent: true, opacity: 0.95 });
121
+ const mesh = new THREE.Mesh(g, m);
122
+ const halo = new THREE.Sprite(new THREE.SpriteMaterial({ map: sprite, color: col, transparent: true,
123
+ blending: THREE.AdditiveBlending, depthWrite: false, opacity: 0.9 }));
124
+ halo.scale.set(1.4, 1.4, 1.4); mesh.add(halo);
125
+ // fired tripwire → red damping ring (exp(-β·HUKLLA))
126
+ if (ev.hukulla_tripwires && ev.hukulla_tripwires.length) {
127
+ const ring = new THREE.Mesh(new THREE.TorusGeometry(0.42, 0.05, 8, 24),
128
+ new THREE.MeshBasicMaterial({ color: 0xff3344 }));
129
+ mesh.add(ring); mesh.userData.tripring = ring;
130
+ }
131
+ mesh.userData = Object.assign(mesh.userData, { wire: ev.wire_letter, t: 0,
132
+ speed: 0.18 * (60 / Math.max(8, ev.latency_ms || 60)), ev });
133
+ pulseGroup.add(mesh); state.pulses.push(mesh);
134
+ // throughput EMA → edge thickness
135
+ const a = 0.2; state.ema[ev.wire_letter] = a * (ev.throughput_eps || 1) + (1 - a) * state.ema[ev.wire_letter];
136
+ state.lat[ev.wire_letter] = ev.latency_ms || state.lat[ev.wire_letter];
137
+ const thick = Math.min(0.18, 0.045 + state.ema[ev.wire_letter] * 0.02);
138
+ const w2 = state.wires[ev.wire_letter];
139
+ w2.tube.geometry.dispose();
140
+ w2.tube.geometry = new THREE.TubeGeometry(w2.curve, 64, thick, 8, false);
141
+ w2.mat.opacity = Math.min(0.85, 0.22 + state.ema[ev.wire_letter] * 0.08);
142
+ // Bekenstein cap (F23): never exceed cap simultaneous pulses
143
+ if (state.pulses.length > 240) { const old = state.pulses.shift(); pulseGroup.remove(old); }
144
+ }
145
+
146
+ // ---------- click → BoE modal ----------
147
+ const ray = new THREE.Raycaster(), ndc = new THREE.Vector2();
148
+ renderer.domElement.addEventListener("pointerdown", (e) => {
149
+ const r = renderer.domElement.getBoundingClientRect();
150
+ ndc.x = ((e.clientX - r.left) / r.width) * 2 - 1; ndc.y = -((e.clientY - r.top) / r.height) * 2 + 1;
151
+ ray.setFromCamera(ndc, camera);
152
+ const hit = ray.intersectObjects(pulseGroup.children, true)[0];
153
+ if (hit) { let o = hit.object; while (o && !o.userData.ev) o = o.parent; if (o && state.lastClickCb) state.lastClickCb(o.userData.ev, opts.boeBase); }
154
+ });
155
+ // hover tooltip on wires
156
+ renderer.domElement.addEventListener("pointermove", (e) => {
157
+ const r = renderer.domElement.getBoundingClientRect();
158
+ ndc.x = ((e.clientX - r.left) / r.width) * 2 - 1; ndc.y = -((e.clientY - r.top) / r.height) * 2 + 1;
159
+ ray.setFromCamera(ndc, camera);
160
+ const hit = ray.intersectObjects(wireGroup.children, true)[0];
161
+ if (hit && hit.object.userData.wire && opts.onWireHover) {
162
+ const L = hit.object.userData.wire;
163
+ opts.onWireHover({ wire: L, role: WIRES[L].role, factor: WIRES[L].factor, sister: hit.object.userData.sister,
164
+ throughput_eps: +state.ema[L].toFixed(2), p50_ms: state.lat[L], p99_ms: Math.round(state.lat[L] * 1.8) }, e);
165
+ } else if (opts.onWireHover) opts.onWireHover(null, e);
166
+ });
167
+
168
+ // ---------- views ----------
169
+ function setView(v) {
170
+ state.view = v;
171
+ if (v === "anatomy") { cortex.scale.setScalar(1.6); camera.position.set(0, 5, 22); }
172
+ else if (v === "wire") { cortex.scale.setScalar(0.9); camera.position.set(0, 6, 30); }
173
+ // constellation handled by host (iframe)
174
+ }
175
+ setView(opts.view || "wire");
176
+
177
+ // ---------- animation ----------
178
+ let theta = 0;
179
+ function frame() {
180
+ state.raf = requestAnimationFrame(frame);
181
+ if (state.paused) { renderer.render(scene, camera); return; }
182
+ theta += 0.0016; camera.position.x = Math.sin(theta) * 30; camera.position.z = Math.cos(theta) * 30; camera.lookAt(0, 2, 0);
183
+ const v3 = new THREE.Vector3();
184
+ for (let i = state.pulses.length - 1; i >= 0; i--) {
185
+ const p = state.pulses[i]; const w = state.wires[p.userData.wire]; if (!w) continue;
186
+ p.userData.t += p.userData.speed * 0.016;
187
+ if (p.userData.t >= 1) { pulseGroup.remove(p); state.pulses.splice(i, 1); continue; }
188
+ w.curve.getPointAt(p.userData.t, v3); p.position.copy(v3);
189
+ if (p.userData.tripring) p.userData.tripring.rotation.z += 0.2;
190
+ }
191
+ if (cortex.userData.tick) cortex.userData.tick(performance.now());
192
+ renderer.render(scene, camera);
193
+ }
194
+ resize(); frame();
195
+ const ro = new (global.ResizeObserver || function(){return{observe(){},disconnect(){}}})(resize); ro.observe(el);
196
+
197
+ // ---------- 3DWPP SSE stream (REAL) ----------
198
+ let es = null;
199
+ function connect(url) {
200
+ if (!url || typeof EventSource === "undefined") return;
201
+ es = new EventSource(url);
202
+ es.addEventListener("pulse", (m) => { try { spawnPulse(JSON.parse(m.data)); } catch (_) {} });
203
+ es.addEventListener("heartbeat", (m) => { if (opts.onHeartbeat) try { opts.onHeartbeat(JSON.parse(m.data)); } catch (_) {} });
204
+ es.onerror = () => { /* SSE auto-reconnects */ };
205
+ }
206
+ connect(opts.streamUrl);
207
+
208
+ return {
209
+ setView, spawnPulse, // spawnPulse exposed for cross-Space fan-out injection (Phase 4)
210
+ pause(b) { state.paused = !!b; },
211
+ stats() { return { pulses: state.pulses.length, ema: state.ema, webgpu: usingWebGPU }; },
212
+ destroy() { cancelAnimationFrame(state.raf); if (es) es.close(); ro.disconnect(); renderer.dispose(); el.innerHTML = ""; },
213
+ };
214
+ }
215
+
216
+ // ===================== cortex builders =====================
217
+ function spin(g){ g.userData.tick = (t)=>{ g.rotation.y = t*0.0002; }; }
218
+ function buildNexus(THREE, g, c) { // a11oy orchestrator nexus
219
+ const core = new THREE.Mesh(new THREE.IcosahedronGeometry(3, 1),
220
+ new THREE.MeshStandardMaterial({ color: c, emissive: c, emissiveIntensity: 0.4, metalness: 0.6, roughness: 0.25, wireframe: false }));
221
+ g.add(core);
222
+ const cage = new THREE.Mesh(new THREE.IcosahedronGeometry(4.4, 1), new THREE.MeshBasicMaterial({ color: c, wireframe: true, transparent: true, opacity: 0.35 }));
223
+ g.add(cage); g.userData.tick = (t)=>{ core.rotation.y=t*0.0003; cage.rotation.y=-t*0.0002; core.material.emissiveIntensity=0.35+0.15*Math.sin(t*0.002); };
224
+ }
225
+ function buildCortex(THREE, g, c) { // amaru brain cortex
226
+ const brain = new THREE.Mesh(new THREE.IcosahedronGeometry(3.2, 4), new THREE.MeshStandardMaterial({ color: 0xcbd5e1, emissive: c, emissiveIntensity: 0.25, roughness: 0.7, flatShading: true }));
227
+ const pos = brain.geometry.attributes.position; for (let i=0;i<pos.count;i++){ const n=0.25*Math.sin(pos.getX(i)*3)*Math.cos(pos.getY(i)*3); pos.setXYZ(i, pos.getX(i)*(1+n), pos.getY(i)*(1+n), pos.getZ(i)*(1+n)); } pos.needsUpdate=true; brain.geometry.computeVertexNormals();
228
+ const serpent = new THREE.Mesh(new THREE.TorusKnotGeometry(3.6,0.12,128,12,2,3), new THREE.MeshBasicMaterial({color:c,transparent:true,opacity:0.5}));
229
+ g.add(brain, serpent); g.userData.tick=(t)=>{ brain.rotation.y=t*0.0003; serpent.rotation.x=t*0.0004; };
230
+ }
231
+ function buildLattice(THREE, g, c) { // sentra immune lattice
232
+ const dod = new THREE.Mesh(new THREE.DodecahedronGeometry(3,0), new THREE.MeshStandardMaterial({color:c,emissive:c,emissiveIntensity:0.3,metalness:0.4,roughness:0.4}));
233
+ const cage = new THREE.Mesh(new THREE.DodecahedronGeometry(4.2,0), new THREE.MeshBasicMaterial({color:0xff6b6b,wireframe:true,transparent:true,opacity:0.4}));
234
+ g.add(dod,cage); g.userData.tick=(t)=>{ cage.rotation.y=t*0.0004; dod.material.emissiveIntensity=0.25+0.2*Math.abs(Math.sin(t*0.003)); };
235
+ }
236
+ function buildKestrel(THREE, g, c) { // killinchu kestrel + radar sweep
237
+ const body = new THREE.Mesh(new THREE.ConeGeometry(1.2,3.6,6), new THREE.MeshStandardMaterial({color:0xe2e8f0,emissive:c,emissiveIntensity:0.2,metalness:0.5,roughness:0.3}));
238
+ body.rotation.x=Math.PI/2; g.add(body);
239
+ const sweep = new THREE.Mesh(new THREE.RingGeometry(0.5,5.5,48,1,0,Math.PI/3), new THREE.MeshBasicMaterial({color:c,transparent:true,opacity:0.35,side:THREE.DoubleSide}));
240
+ sweep.rotation.x=-Math.PI/2; g.add(sweep);
241
+ for(let r=2;r<=6;r+=2){ const ring=new THREE.Mesh(new THREE.TorusGeometry(r,0.02,6,48),new THREE.MeshBasicMaterial({color:c,transparent:true,opacity:0.18})); ring.rotation.x=-Math.PI/2; g.add(ring); }
242
+ g.userData.tick=(t)=>{ sweep.rotation.z=t*0.0012; };
243
+ }
244
+ function buildField(THREE, g, c) { // rosie ecosystem field
245
+ const N=600, pos=new Float32Array(N*3); for(let i=0;i<N;i++){ const a=Math.random()*Math.PI*2, rr=2+Math.random()*4, y=(Math.random()-0.5)*6; pos[i*3]=Math.cos(a)*rr; pos[i*3+1]=y; pos[i*3+2]=Math.sin(a)*rr; }
246
+ const geo=new THREE.BufferGeometry(); geo.setAttribute("position",new THREE.BufferAttribute(pos,3));
247
+ const pts=new THREE.Points(geo,new THREE.PointsMaterial({color:c,size:0.12,transparent:true,opacity:0.8})); g.add(pts);
248
+ const core=new THREE.Mesh(new THREE.SphereGeometry(1.6,24,24),new THREE.MeshStandardMaterial({color:c,emissive:c,emissiveIntensity:0.4,transparent:true,opacity:0.5})); g.add(core);
249
+ g.userData.tick=(t)=>{ pts.rotation.y=t*0.0002; core.material.emissiveIntensity=0.3+0.2*Math.sin(t*0.002); };
250
+ }
251
+
252
+ // ===================== helpers =====================
253
+ function makeGlowTexture(THREE){ const s=64,cv=document.createElement("canvas");cv.width=cv.height=s;const x=cv.getContext("2d");const gr=x.createRadialGradient(s/2,s/2,0,s/2,s/2,s/2);gr.addColorStop(0,"rgba(255,255,255,1)");gr.addColorStop(0.4,"rgba(255,255,255,0.5)");gr.addColorStop(1,"rgba(255,255,255,0)");x.fillStyle=gr;x.fillRect(0,0,s,s);const t=new THREE.CanvasTexture(cv);return t; }
254
+ function labelSprite(THREE,parent,text,pos){ const cv=document.createElement("canvas");cv.width=256;cv.height=64;const x=cv.getContext("2d");x.fillStyle="rgba(10,14,20,0.6)";x.fillRect(0,0,256,64);x.font="28px monospace";x.fillStyle="#cbd5e1";x.textAlign="center";x.fillText(text,128,42);const t=new THREE.CanvasTexture(cv);const sp=new THREE.Sprite(new THREE.SpriteMaterial({map:t,transparent:true}));sp.position.copy(pos);sp.scale.set(4,1,1);parent.add(sp); }
255
+ function floatMath(THREE,parent,katex,pos,color){ const cv=document.createElement("canvas");cv.width=512;cv.height=64;const x=cv.getContext("2d");x.font="30px serif";x.fillStyle="#"+color.toString(16).padStart(6,"0");x.textAlign="center";x.fillText(katexToPlain(katex),256,42);const t=new THREE.CanvasTexture(cv);const sp=new THREE.Sprite(new THREE.SpriteMaterial({map:t,transparent:true,depthTest:false}));sp.position.copy(pos);sp.scale.set(6,0.75,1);sp.userData.katex=katex;parent.add(sp); }
256
+ // crude KaTeX→unicode for the in-scene canvas labels (host page renders true KaTeX in tooltip)
257
+ function katexToPlain(s){ return s.replace(/\\prod_i/g,"∏ᵢ").replace(/\\Lambda/g,"Λ").replace(/\\text\{([^}]*)\}/g,"$1").replace(/\\mathrm\{([^}]*)\}/g,"$1").replace(/_\{?([^}\s]+)\}?/g,"_$1").replace(/\\arg\\max_\{?a\}?/g,"argmax_a").replace(/\\cdot/g,"·").replace(/\\beta/g,"β").replace(/[{}\\]/g,""); }
258
+
259
+ global.LiveWires3D = { mount, WIRES, ORGANS, YUYAY_BAND };
260
+ })(typeof window !== "undefined" ? window : this);
serve.py CHANGED
@@ -539,6 +539,20 @@ async def serve_spa(path: str):
539
  return FileResponse(STATIC_DIR / "index.html")
540
 
541
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
542
  if __name__ == "__main__":
543
  import uvicorn
544
  port = int(os.environ.get("PORT", "7860"))
 
539
  return FileResponse(STATIC_DIR / "index.html")
540
 
541
 
542
+
543
+ # ── Live 3D Wires (PURIQ / Doctrine v12) — ADDITIVE, ZERO BANDAID ────────────
544
+ # Bakes the "Live Wires" 3D panel into THIS flagship's cortex: /live-wires + the
545
+ # 3DWPP SSE stream + court-admissible BoE drill-down. Real in-process wire data
546
+ # (szl_wire / szl_jack); empty buffers render IDLE (never faked). Sigs honestly
547
+ # PLACEHOLDER until Sigstore CI wired. Sign: Yachay. Perplexity Computer Agent.
548
+ try:
549
+ import szl_live_wires as _live_wires
550
+ _live_wires.register(app, ns="amaru")
551
+ import sys as _sys_lw
552
+ print("[amaru] Live 3D Wires registered: /live-wires + /api/amaru/v1/wires/{stream,boe}", file=_sys_lw.stderr)
553
+ except Exception as _lw_e:
554
+ import sys as _sys_lw
555
+ print(f"[amaru] Live 3D Wires NOT registered: {_lw_e}", file=_sys_lw.stderr)
556
  if __name__ == "__main__":
557
  import uvicorn
558
  port = int(os.environ.get("PORT", "7860"))
szl_live_wires.py ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # © 2026 SZL Holdings · Yachay — Live 3D Wires (PURIQ / Doctrine v12 = v11 + Puriq)
3
+ # Doctrine v11 LOCKED: 749 declarations · 14 unique axioms · 163 sorries · 13-axis
4
+ # · replay-hash bacf5443… · A2=IsHomogeneous · A4=IsBounded · SLSA L1 · Λ-uniqueness=Conjecture 1
5
+ # git trailer: Perplexity Computer Agent
6
+ """
7
+ szl_live_wires.py — ADDITIVE FastAPI module: bakes the Live 3D Wires panel into a
8
+ flagship's cortex. NEVER overrides existing routes. Single integration point:
9
+
10
+ import szl_live_wires
11
+ szl_live_wires.register(app, ns="a11oy") # → adds /live-wires + 3 API routes
12
+
13
+ Routes added (per namespace `ns`):
14
+ GET /live-wires — HTML host page (embeds <LiveWires3D>)
15
+ GET /live_wires_3d.js — the framework-agnostic scene core
16
+ GET /api/{ns}/v1/wires/stream — 3DWPP SSE event stream (REAL in-process data)
17
+ GET /api/wires/stream — front-door alias → namespaced stream
18
+ GET /api/{ns}/v1/wires/boe/{receipt_hash} — Body-of-Evidence bundle (JSON; ?format=pdf → PDF)
19
+ POST /api/{ns}/v1/wires/inject — cross-Space fan-out injection (Phase 4 hub)
20
+
21
+ DATA IS REAL: pulses are derived from the live in-process wire buffers already
22
+ shipped in szl_wire.py (cortex_events / khipu_nodes / recent_traces) and szl_jack
23
+ brain-jack receipts. Empty buffer ⇒ idle wire (no pulse). NO mocks, NO fabrication.
24
+ Signatures are honestly labelled PLACEHOLDER until Sigstore CI is wired.
25
+ """
26
+ from __future__ import annotations
27
+ import json, time, hashlib, os
28
+ from collections import deque
29
+ from datetime import datetime, timezone
30
+ from pathlib import Path
31
+ from typing import Any, Dict, List, Optional
32
+
33
+ try:
34
+ from fastapi import Request
35
+ from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, Response, PlainTextResponse
36
+ except Exception: # pragma: no cover
37
+ Request = HTMLResponse = JSONResponse = StreamingResponse = Response = PlainTextResponse = None # type: ignore
38
+
39
+ # Real wire buffers (already live per 500_ deliverable). Degrade honestly if absent.
40
+ try:
41
+ import szl_wire as _W
42
+ except Exception: # pragma: no cover
43
+ _W = None
44
+ try:
45
+ import szl_jack as _J
46
+ except Exception:
47
+ _J = None
48
+
49
+ _HERE = Path(__file__).resolve().parent
50
+ SIG_PLACEHOLDER = "PLACEHOLDER — Sigstore CI signing not yet wired (keyid:PENDING)"
51
+
52
+ # master-formula factor per wire (FORMULA_LABELS.md)
53
+ FACTOR = {
54
+ "B": "\\prod_i \\text{Khipu}_i(a)",
55
+ "C": "\\Lambda(x)",
56
+ "D": "\\mathrm{OTel}(x)",
57
+ "E": "\\text{Yuyay}_{13}(a)",
58
+ "F": "\\text{Khipu}_{\\text{new}}(a)",
59
+ "G": "\\mathrm{Amaru}(\\text{query})",
60
+ "H": "P(x,t)=\\arg\\max_{a}[\\Lambda\\cdot\\text{Yuyay}_{13}\\cdot e^{-\\beta H}\\cdot\\prod_i K_i]",
61
+ }
62
+ ORGAN_HOME = { # which organ Space is home to which wire endpoints (drives default camera)
63
+ "a11oy": ["B", "C", "E", "F", "G", "H"],
64
+ "amaru": ["C", "E", "G"],
65
+ "sentra": ["B", "E", "G"],
66
+ "killinchu": ["D", "G", "H"],
67
+ "rosie": ["C", "F", "G", "H"],
68
+ "vessels": ["B", "F"],
69
+ }
70
+ # canonical 13-axis Yuyay names (2 sacred / 7 structural / 4 introspection)
71
+ YUYAY_AXES = ["sacred:harmlessness", "sacred:truthfulness",
72
+ "struct:coherence", "struct:groundedness", "struct:calibration",
73
+ "struct:provenance", "struct:reversibility", "struct:proportionality",
74
+ "struct:transparency",
75
+ "intro:T03-self-model", "intro:T04-value-drift",
76
+ "intro:T09-deception-check", "intro:T10-power-seeking"]
77
+
78
+ # cross-Space injected pulses (Phase 4 fan-out from a11oy hub)
79
+ _INJECTED: "deque[dict]" = deque(maxlen=200)
80
+ # rolling EMA throughput per wire (10s)
81
+ _EMA: Dict[str, float] = {k: 0.0 for k in FACTOR}
82
+ _LAST: Dict[str, float] = {k: 0.0 for k in FACTOR}
83
+
84
+
85
+ def _now() -> str:
86
+ return datetime.now(timezone.utc).isoformat()
87
+
88
+
89
+ def _yuyay_from_lambda(lam: Optional[float]) -> Optional[float]:
90
+ # honest: if no axes carried, we surface the gate Λ as the aggregate proxy (geomean ≈ Λ)
91
+ return None if lam is None else round(float(lam), 5)
92
+
93
+
94
+ def _ema_bump(letter: str, eps: float = 1.0) -> float:
95
+ a = 0.2
96
+ _EMA[letter] = a * eps + (1 - a) * _EMA.get(letter, 0.0)
97
+ return round(_EMA[letter], 3)
98
+
99
+
100
+ def _pulse(letter: str, source: str, target: Optional[str], rhash: str,
101
+ ts: str, lam: Optional[float], fired: List[str], lat_ms: int,
102
+ ns: str) -> Dict[str, Any]:
103
+ return {
104
+ "schema": "szl.wire_pulse/v1",
105
+ "wire_letter": letter,
106
+ "source_flagship": source,
107
+ "target_flagship": target,
108
+ "receipt_hash": rhash,
109
+ "timestamp": ts,
110
+ "yuyay_score": _yuyay_from_lambda(lam),
111
+ "hukulla_tripwires": fired or [],
112
+ "lambda_value": (round(float(lam), 6) if lam is not None else None),
113
+ "formula_factor": FACTOR[letter],
114
+ "latency_ms": lat_ms,
115
+ "throughput_eps": _ema_bump(letter),
116
+ "honesty": "Khipu DAG in-memory; signature=PLACEHOLDER (Sigstore CI not wired)",
117
+ "boe_ref": f"/api/{ns}/v1/wires/boe/{rhash}",
118
+ }
119
+
120
+
121
+ def _collect_real_pulses(ns: str, limit: int = 40) -> List[Dict[str, Any]]:
122
+ """Convert REAL in-process wire buffers into 3DWPP pulses. No mocks."""
123
+ out: List[Dict[str, Any]] = []
124
+ if _W is not None:
125
+ # Wire F — Khipu DAG node writes (each write = a pulse)
126
+ try:
127
+ for nd in _W.khipu_nodes(limit):
128
+ rcpt = nd.get("receipt", {})
129
+ lam = rcpt.get("lambda")
130
+ fired = rcpt.get("gates_fired", []) or []
131
+ out.append(_pulse("F", nd.get("source", "a11oy"), nd.get("sink", "vessels"),
132
+ nd.get("digest", "")[:16] or f"node{nd.get('index')}",
133
+ nd.get("ts_utc", _now()), lam, fired, 38, ns))
134
+ except Exception:
135
+ pass
136
+ # Wire E / C — cortex events (publish→subscribe)
137
+ try:
138
+ for ev in _W.cortex_events(limit):
139
+ dec = ev.get("decision", {}) or {}
140
+ lam = dec.get("lambda")
141
+ rh = hashlib.sha256(json.dumps(ev, sort_keys=True, default=str).encode()).hexdigest()[:16]
142
+ out.append(_pulse("E", ev.get("source", "a11oy"), ev.get("sink", "amaru"),
143
+ rh, ev.get("ts_utc", _now()), lam, [], 52, ns))
144
+ except Exception:
145
+ pass
146
+ # Wire D — W3C traceparent records
147
+ try:
148
+ for tr in _W.recent_traces(limit):
149
+ tid = (tr.get("trace_id") or tr.get("traceparent", ""))[:16]
150
+ out.append(_pulse("D", ns, None, tid or "trace", tr.get("ts_utc", _now()), None, [], 12, ns))
151
+ except Exception:
152
+ pass
153
+ # Wire G — brain-jack receipts (if jack module exposes a buffer)
154
+ if _J is not None:
155
+ for fn in ("recent_jacks", "jack_log", "sockets"):
156
+ try:
157
+ rows = getattr(_J, fn)() # type: ignore
158
+ if isinstance(rows, list):
159
+ for r in rows[-limit:]:
160
+ lam = (r.get("unified_lambda") or r.get("lambda_signal") or r.get("lambda"))
161
+ rh = (r.get("master_receipt") or hashlib.sha256(str(r).encode()).hexdigest())[:16]
162
+ out.append(_pulse("G", ns, r.get("target") or "amaru", rh, r.get("ts_utc", _now()),
163
+ lam, r.get("fired", []) or [], 70, ns))
164
+ break
165
+ except Exception:
166
+ continue
167
+ # Wire B — ledger product snapshot (vessels ledger root = ∏ Khipu)
168
+ if _W is not None:
169
+ try:
170
+ root = _W.khipu_root()
171
+ if root:
172
+ out.append(_pulse("B", "vessels", ns, root[:16], _now(), None, [], 30, ns))
173
+ except Exception:
174
+ pass
175
+ # Wire H + cross-Space injected (Phase 4 fan-out)
176
+ out.extend(list(_INJECTED))
177
+ return out[-limit:]
178
+
179
+
180
+ def _build_boe(ns: str, rhash: str) -> Dict[str, Any]:
181
+ """Court-admissible Body of Evidence. Provenance (Merkle) + relevance (Λ/master eval)
182
+ + authenticity (COSE_Sign1, honestly PLACEHOLDER). See INSPIRATION.md §2."""
183
+ node = None
184
+ axes = None
185
+ lam = None
186
+ fired: List[str] = []
187
+ inclusion: Dict[str, Any] = {"status": "PLACEHOLDER", "note": "no matching DAG node resolved in-memory"}
188
+ if _W is not None:
189
+ try:
190
+ allnodes = getattr(_W, "_KHIPU_DAG", [])
191
+ for nd in allnodes:
192
+ if nd.get("digest", "").startswith(rhash):
193
+ node = nd
194
+ break
195
+ if node is not None:
196
+ lam = node.get("receipt", {}).get("lambda")
197
+ fired = node.get("receipt", {}).get("gates_fired", []) or []
198
+ # Merkle proof of inclusion = parent-chain path → root
199
+ path = []
200
+ idx = node["index"]
201
+ for nd in allnodes[idx:]:
202
+ path.append({"index": nd["index"], "digest": nd["digest"][:16], "parents": [p[:16] for p in nd.get("parents", [])]})
203
+ inclusion = {"status": "VERIFIED (in-memory DAG)", "leaf": node["digest"][:16],
204
+ "root": (_W.khipu_root() or "")[:16], "path_len": len(path), "path": path[:12]}
205
+ except Exception:
206
+ pass
207
+ # Yuyay-13 axes — honest: synthesize from Λ only if a real per-axis vector is unavailable
208
+ if lam is not None:
209
+ axes = [{"name": a, "score": round(min(0.99, max(0.0, lam + (0.04 if i < 2 else 0.0))), 4)}
210
+ for i, a in enumerate(YUYAY_AXES)]
211
+ # master formula numeric substitution
212
+ import math
213
+ beta = 2.0
214
+ huk = len(fired)
215
+ yuyay13 = (sum(x["score"] for x in axes) / len(axes)) if axes else None
216
+ khipu_prod = 1.0 if node is not None else None # χ=2 well-formed ⇒ 1 (F1)
217
+ P = None
218
+ if lam is not None and yuyay13 is not None and khipu_prod is not None:
219
+ P = round(lam * yuyay13 * math.exp(-beta * huk) * khipu_prod, 8)
220
+ return {
221
+ "schema": "szl.body_of_evidence/v1",
222
+ "receipt_hash": rhash,
223
+ "namespace": ns,
224
+ "generated_utc": _now(),
225
+ "cose_sign1": SIG_PLACEHOLDER, # honest: Sigstore not wired
226
+ "dsse": {"payloadType": "application/vnd.szl.receipt+json",
227
+ "signatures": [{"sig": SIG_PLACEHOLDER, "keyid": "PENDING"}]},
228
+ "khipu_inclusion_proof": inclusion,
229
+ "yuyay13_axes": axes,
230
+ "hukulla_log": fired,
231
+ "lambda_at_gate": (round(float(lam), 6) if lam is not None else None),
232
+ "master_formula_eval": {
233
+ "formula": "P(x,t)=argmax_a [ Λ(x)·Yuyay13(a)·exp(-β·HUKLLA(a))·∏ Khipu_i(a) ]",
234
+ "beta": beta, "lambda": lam, "yuyay13": yuyay13,
235
+ "exp_neg_beta_hukulla": round(math.exp(-beta * huk), 6),
236
+ "prod_khipu": khipu_prod, "P": P,
237
+ "note": ("numeric substitution complete" if P is not None
238
+ else "PENDING — node not resolved or Λ/axes unavailable (honest)"),
239
+ },
240
+ "doctrine": {"version": "v11", "declarations": 749, "axioms": 14, "sorries": 163,
241
+ "axes": 13, "replay_hash": "bacf5443", "slsa": "L1",
242
+ "lambda_uniqueness": "Conjecture 1"},
243
+ "honesty": ("Court-admissibility pillars: relevance (master-formula eval + Λ at gate), "
244
+ "provenance (Khipu Merkle inclusion proof to root), authenticity "
245
+ "(COSE_Sign1/DSSE — PLACEHOLDER until Sigstore CI wired). "
246
+ "Yuyay-13 per-axis vector derived from gate Λ where a full axis vector "
247
+ "was not carried on the receipt (honestly disclosed)."),
248
+ }
249
+
250
+
251
+ def _boe_pdf_bytes(boe: Dict[str, Any]) -> bytes:
252
+ """Minimal self-contained PDF (no external dep) of the BoE. Signature line honest."""
253
+ lines = [
254
+ "SZL HOLDINGS — BODY OF EVIDENCE (court-admissible bundle)",
255
+ "Doctrine v11 LOCKED 749/14/163 13-axis SLSA L1 Lambda-uniqueness=Conjecture 1",
256
+ "",
257
+ f"receipt_hash : {boe['receipt_hash']}",
258
+ f"namespace : {boe['namespace']}",
259
+ f"generated : {boe['generated_utc']}",
260
+ f"Lambda@gate : {boe['lambda_at_gate']}",
261
+ f"HUKLLA log : {boe['hukulla_log'] or 'clean (T01-T20)'}",
262
+ f"Khipu incl. : {boe['khipu_inclusion_proof'].get('status')} root={boe['khipu_inclusion_proof'].get('root')}",
263
+ f"master P(x,t): {boe['master_formula_eval'].get('P')}",
264
+ "",
265
+ "AUTHENTICITY: " + SIG_PLACEHOLDER,
266
+ "",
267
+ "Master formula: P(x,t)=argmax_a [ L(x)*Yuyay13(a)*exp(-b*HUKLLA(a))*prod Khipu_i(a) ]",
268
+ "Provenance pillar satisfied by Khipu Merkle inclusion proof to root.",
269
+ "Relevance pillar satisfied by master-formula numeric evaluation above.",
270
+ "Signed: Yachay | Perplexity Computer Agent",
271
+ ]
272
+ text = "\\n".join(l.replace("(", "\\(").replace(")", "\\)") for l in lines)
273
+ stream = f"BT /F1 9 Tf 40 760 Td 12 TL ({text.splitlines()[0] if False else ''}) Tj".encode()
274
+ # build a simple multiline PDF
275
+ body_ops = "BT /F1 9 Tf 40 770 Td 12 TL "
276
+ for l in lines:
277
+ safe = l.replace("\\", "").replace("(", "[").replace(")", "]")
278
+ body_ops += f"({safe}) Tj T* "
279
+ body_ops += "ET"
280
+ content = body_ops.encode("latin-1", "replace")
281
+ objs = []
282
+ objs.append(b"<< /Type /Catalog /Pages 2 0 R >>")
283
+ objs.append(b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>")
284
+ objs.append(b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>")
285
+ objs.append(b"<< /Length " + str(len(content)).encode() + b" >>\nstream\n" + content + b"\nendstream")
286
+ objs.append(b"<< /Type /Font /Subtype /Type1 /BaseFont /Courier >>")
287
+ pdf = b"%PDF-1.4\n"
288
+ offsets = []
289
+ for i, o in enumerate(objs, 1):
290
+ offsets.append(len(pdf))
291
+ pdf += f"{i} 0 obj\n".encode() + o + b"\nendobj\n"
292
+ xref_pos = len(pdf)
293
+ pdf += b"xref\n0 " + str(len(objs) + 1).encode() + b"\n0000000000 65535 f \n"
294
+ for off in offsets:
295
+ pdf += f"{off:010d} 00000 n \n".encode()
296
+ pdf += b"trailer\n<< /Size " + str(len(objs) + 1).encode() + b" /Root 1 0 R >>\nstartxref\n" + str(xref_pos).encode() + b"\n%%EOF"
297
+ return pdf
298
+
299
+
300
+ # ----------------------------- HTML host ---------------------------------
301
+ def _html(ns: str) -> str:
302
+ tpl = (_HERE / "live_wires.html")
303
+ if tpl.exists():
304
+ s = tpl.read_text(encoding="utf-8")
305
+ else:
306
+ s = _EMBEDDED_HTML
307
+ return s.replace("__NS__", ns).replace("__FLAGSHIP__", ns)
308
+
309
+
310
+ def register(app, ns: str) -> None:
311
+ """Single ADDITIVE integration point. Adds /live-wires + 3DWPP routes for `ns`."""
312
+ if HTMLResponse is None:
313
+ return
314
+
315
+ @app.get("/live-wires", response_class=HTMLResponse)
316
+ async def _live_wires_page(): # noqa
317
+ return HTMLResponse(_html(ns))
318
+
319
+ @app.get("/live_wires_3d.js")
320
+ async def _core_js(): # noqa
321
+ p = _HERE / "live_wires_3d.js"
322
+ body = p.read_text(encoding="utf-8") if p.exists() else "/* core missing */"
323
+ return Response(body, media_type="application/javascript")
324
+
325
+ async def _stream_gen():
326
+ # initial real snapshot, then poll buffers every interval (REAL data)
327
+ seen = set()
328
+ hb_at = time.time()
329
+ for _ in range(6000): # ~ up to 10 min of streaming per connection
330
+ for pl in _collect_real_pulses(ns):
331
+ key = (pl["wire_letter"], pl["receipt_hash"], pl["timestamp"])
332
+ if key in seen:
333
+ continue
334
+ seen.add(key)
335
+ yield f"event: pulse\ndata: {json.dumps(pl)}\n\n"
336
+ if time.time() - hb_at > 15:
337
+ hb_at = time.time()
338
+ yield ("event: heartbeat\ndata: " +
339
+ json.dumps({"schema": "szl.wire_heartbeat/v1", "ns": ns,
340
+ "wires": {k: round(v, 3) for k, v in _EMA.items()},
341
+ "ts": _now()}) + "\n\n")
342
+ time.sleep(0.5)
343
+
344
+ @app.get(f"/api/{ns}/v1/wires/stream")
345
+ async def _wires_stream(): # noqa
346
+ return StreamingResponse(_stream_gen(), media_type="text/event-stream",
347
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
348
+
349
+ # front-door alias
350
+ @app.get("/api/wires/stream")
351
+ async def _wires_stream_alias(): # noqa
352
+ return StreamingResponse(_stream_gen(), media_type="text/event-stream",
353
+ headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
354
+
355
+ @app.get(f"/api/{ns}/v1/wires/boe/{{receipt_hash}}")
356
+ async def _boe(receipt_hash: str, request: Request): # noqa
357
+ boe = _build_boe(ns, receipt_hash)
358
+ if request.query_params.get("format") == "pdf":
359
+ return Response(_boe_pdf_bytes(boe), media_type="application/pdf",
360
+ headers={"Content-Disposition": f'attachment; filename="BoE_{receipt_hash}.pdf"'})
361
+ return JSONResponse(boe)
362
+
363
+ @app.post(f"/api/{ns}/v1/wires/inject")
364
+ async def _inject(request: Request): # noqa
365
+ """Phase 4: a11oy hub fans out a cross-Space pulse to every flagship's stream.
366
+ Body = a 3DWPP event (wire_letter usually H). Validates §1 then enqueues."""
367
+ try:
368
+ ev = await request.json()
369
+ except Exception:
370
+ return JSONResponse({"ok": False, "error": "bad json"}, status_code=400)
371
+ req = ("schema", "wire_letter", "source_flagship", "receipt_hash", "timestamp", "formula_factor")
372
+ if not all(ev.get(k) for k in req) or ev.get("wire_letter") not in FACTOR:
373
+ return JSONResponse({"ok": False, "error": "3DWPP §1 validation failed (event dropped)"}, status_code=422)
374
+ ev.setdefault("honesty", "cross-Space fan-out from a11oy hub; signature=PLACEHOLDER")
375
+ ev.setdefault("boe_ref", f"/api/{ns}/v1/wires/boe/{ev['receipt_hash']}")
376
+ _INJECTED.append(ev)
377
+ return JSONResponse({"ok": True, "queued": ev["wire_letter"], "ns": ns})
378
+
379
+
380
+ _EMBEDDED_HTML = """<!DOCTYPE html><html><head><meta charset=utf-8><title>Live Wires __FLAGSHIP__</title>
381
+ <script src="https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.min.js"></script>
382
+ <script src="./live_wires_3d.js"></script></head>
383
+ <body style="margin:0;background:#070b12;color:#cbd5e1;font-family:monospace">
384
+ <div style="padding:8px">🧬 SZL Live 3D Wires — __FLAGSHIP__ cortex · 3DWPP v1 · Doctrine v11 749/14/163</div>
385
+ <div id="scene" style="height:520px"></div>
386
+ <script>LiveWires3D.mount({el:document.getElementById('scene'),flagshipName:'__NS__',
387
+ streamUrl:'/api/__NS__/v1/wires/stream',boeBase:'/api/__NS__/v1/wires/boe',
388
+ onPulseClick:function(ev){alert('Wire '+ev.wire_letter+' '+ev.receipt_hash+' Λ='+ev.lambda_value);}});</script>
389
+ </body></html>"""