betterwithage commited on
Commit
917b35d
·
1 Parent(s): dcc6325

Add evidence-bound Anatomy capability surface (#1)

Browse files

- Add evidence-bound Anatomy capability surface (88830514bfa124266cd8f618a5798b5739d33dd7)

README.md CHANGED
@@ -37,6 +37,36 @@ The governed-AI organ substrate shared by **a11oy** (governed-AI command body) a
37
  **killinchu** (maritime / drone C2 body): two bodies, one circulatory + nervous mesh,
38
  with the Λ heart at the center.
39
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  ## What's new in v5 — conscience, sovereign mesh, verifiable receipts (evolves v4)
41
 
42
  v5 **evolves** v4 (it does not replace it): the entire v4 engine (`data.js` / `app.js`,
@@ -251,11 +281,11 @@ HTTPS at the edge. **Embedding is deliberately left enabled** (no
251
  `X-Frame-Options: DENY`, no `disable_embedding`) so the Space keeps working inside
252
  the `huggingface.co` / `*.hf.space` iframe.
253
 
254
- **CORS:** the Space's static server exposes only read-only file GETs and owns no
255
- application endpoints — there is no `*` ACAO to tighten on our side. Its only
256
- network activity is **outbound, read-only** `fetch(..., { mode:'cors',
257
- credentials:'omit' })` GETs to the SZL product Spaces; no key, no cookie, no
258
- credentials are ever sent.
259
 
260
  ## Verify it yourself
261
 
@@ -265,8 +295,12 @@ live products it depicts:
265
  ```bash
266
  # Confirm the live doctrine posture the heart reports
267
  curl -s https://szlholdings-a11oy.hf.space/api/a11oy/v1/honest | jq .kernel_commit # => "c7c0ba17"
268
- # Pull a signed receipt from the edge organ and verify it offline
269
- curl -s https://szlholdings-killinchu.hf.space/cosign.pub -o cosign.pub
 
 
 
 
270
  ```
271
 
272
  Read the thesis → [szl-papers](https://github.com/szl-holdings/szl-papers) ·
@@ -274,7 +308,7 @@ run the kernel → [lutar-lean](https://github.com/szl-holdings/lutar-lean).
274
 
275
  ---
276
 
277
- Canonical source mirror: `szl-holdings/anatomy` (GitHub) `SZLHOLDINGS/anatomy` (HF Space) · **[a-11-oy.com](https://a-11-oy.com)**
278
 
279
  <sub>v5 (evolves v4) — WILLAY conscience · sovereign mesh · buyer-verifiable receipts · 8-proof→organ map · AI-assurance · yarqa+PINN (MODELED) · GPU-sovereign stack (SUBSTRATE) · Doctrine v11 LOCKED · 749/14/163 · kernel `c7c0ba17` · 8 locked-proven + experimental CI-green tier · Λ = Conjecture 1 · Khipu Conjecture 2 open · SLSA L1 honest (static viz) · Apache-2.0</sub>
280
 
 
37
  **killinchu** (maritime / drone C2 body): two bodies, one circulatory + nervous mesh,
38
  with the Λ heart at the center.
39
 
40
+ ## Evidence Bay — the proof boundary
41
+
42
+ The 3D organism now has a machine-readable evidence boundary without replacing its
43
+ visual language. Open **Evidence Bay** from the atlas to inspect every major surface
44
+ through the same five-part contract: **Purpose · Try · Evidence · Limits · Reproduce**.
45
+
46
+ - Transport, evidence, verification, and authority are separate dimensions. A
47
+ `RUNNING` Space is not treated as proof of model quality, freshness, or safety.
48
+ - The deployed bundle emits a deterministic SHA-256 integrity receipt. Its local
49
+ verifier recomputes every declared file and deliberately returns
50
+ `STRUCTURAL-ONLY` because the public visualization has no signing key.
51
+ - Live A11OY, Killinchu, and receipt-verifier dependencies are probed separately
52
+ and timestamped. Missing contracts stay `MISSING` or `UNAVAILABLE`; no green is
53
+ synthesized from an unrelated endpoint.
54
+ - Formula claims link to their source files. This Space presents a declared
55
+ snapshot—it does not run Lean—and Λ remains Conjecture 1.
56
+ - `/.well-known/szl-source.json` exposes the declared GitHub base, measured HF
57
+ revision, artifact-set digest, and the remaining GitHub-sync state.
58
+
59
+ Machine-readable routes:
60
+
61
+ | Route | Meaning |
62
+ |---|---|
63
+ | `/api/anatomy/v1/manifest` | Contract, state vocabulary, doctrine boundary |
64
+ | `/api/anatomy/v1/capabilities` | Five-part capability shell and provenance |
65
+ | `/api/anatomy/v1/evidence?refresh=1` | Fresh dependency contract probes |
66
+ | `/api/anatomy/v1/receipt` | Deterministic local artifact receipt |
67
+ | `POST /api/anatomy/v1/verify/receipt` | Replay local integrity; structural only |
68
+ | `/.well-known/szl-source.json` | GitHub ↔ HF deployment-source attestation |
69
+
70
  ## What's new in v5 — conscience, sovereign mesh, verifiable receipts (evolves v4)
71
 
72
  v5 **evolves** v4 (it does not replace it): the entire v4 engine (`data.js` / `app.js`,
 
281
  `X-Frame-Options: DENY`, no `disable_embedding`) so the Space keeps working inside
282
  the `huggingface.co` / `*.hf.space` iframe.
283
 
284
+ **CORS:** the evidence endpoints are public, read-only inspection contracts and
285
+ return `Access-Control-Allow-Origin: *` so A11OY and the wider estate can ingest
286
+ them. The only POST is a pure receipt recomputation; it cannot sign, store, fetch
287
+ user-controlled URLs, or mutate state. Outbound dependency probes use a fixed
288
+ allowlist in `server.py`; no key, cookie, or credential is sent.
289
 
290
  ## Verify it yourself
291
 
 
295
  ```bash
296
  # Confirm the live doctrine posture the heart reports
297
  curl -s https://szlholdings-a11oy.hf.space/api/a11oy/v1/honest | jq .kernel_commit # => "c7c0ba17"
298
+ # Inspect and replay the Anatomy bundle receipt (result is STRUCTURAL-ONLY, not signed)
299
+ curl -s https://szlholdings-anatomy.hf.space/api/anatomy/v1/receipt -o anatomy-receipt.json
300
+ curl -s -X POST -H "Content-Type: application/json" --data-binary @anatomy-receipt.json \
301
+ https://szlholdings-anatomy.hf.space/api/anatomy/v1/verify/receipt | jq .verdict
302
+ # Open the independent browser verifier for signed governed receipts
303
+ open https://huggingface.co/spaces/SZLHOLDINGS/governed-receipt-verifier
304
  ```
305
 
306
  Read the thesis → [szl-papers](https://github.com/szl-holdings/szl-papers) ·
 
308
 
309
  ---
310
 
311
+ Declared source base: `szl-holdings/anatomy` (GitHub) `SZLHOLDINGS/anatomy` (HF Space). The live source attestation reports the exact deployment revision and whether the HF overlay still needs GitHub synchronization. · **[a-11-oy.com](https://a-11-oy.com)**
312
 
313
  <sub>v5 (evolves v4) — WILLAY conscience · sovereign mesh · buyer-verifiable receipts · 8-proof→organ map · AI-assurance · yarqa+PINN (MODELED) · GPU-sovereign stack (SUBSTRATE) · Doctrine v11 LOCKED · 749/14/163 · kernel `c7c0ba17` · 8 locked-proven + experimental CI-green tier · Λ = Conjecture 1 · Khipu Conjecture 2 open · SLSA L1 honest (static viz) · Apache-2.0</sub>
314
 
favicon.svg ADDED
frontier_anatomy.js ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* SZL Living Anatomy — Evidence Bay.
2
+ * Clean-room, SZL-native industrial evidence surface. Zero CDN and read-only.
3
+ * Transport, evidence, verification, and authority remain separate dimensions.
4
+ */
5
+ (function (root) {
6
+ 'use strict';
7
+ var API = '/api/anatomy/v1';
8
+ var state = { manifest:null, capabilities:null, evidence:null, tab:'overview', busy:false };
9
+ var previousFocus = null;
10
+
11
+ function esc(value) {
12
+ return String(value == null ? '' : value).replace(/[&<>"']/g, function (c) {
13
+ return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];
14
+ });
15
+ }
16
+ function fetchJSON(url, opts, timeout) {
17
+ var ctl = typeof AbortController !== 'undefined' ? new AbortController() : null;
18
+ var timer = ctl ? setTimeout(function(){ ctl.abort(); }, timeout || 10000) : null;
19
+ opts = opts || {}; opts.cache = 'no-store'; if (ctl) opts.signal = ctl.signal;
20
+ return fetch(url, opts).then(function (r) {
21
+ if (timer) clearTimeout(timer);
22
+ return r.json().then(function (data) { return {ok:r.ok,status:r.status,data:data}; });
23
+ }).catch(function (error) {
24
+ if (timer) clearTimeout(timer);
25
+ return {ok:false,status:0,data:null,error:String(error && error.message || error)};
26
+ });
27
+ }
28
+
29
+ var css = [
30
+ '#fa-launch{position:fixed;z-index:197;right:18px;top:50%;transform:translateY(-50%);width:132px;text-align:left;background:rgba(7,11,16,.94);color:#dce8ea;border:1px solid rgba(101,169,174,.38);border-right:2px solid #63d4cf;box-shadow:0 18px 50px rgba(0,0,0,.42);padding:10px 12px;cursor:pointer;font-family:var(--font-m,monospace);text-transform:uppercase;letter-spacing:.10em;backdrop-filter:blur(14px)}',
31
+ '#fa-launch:hover,#fa-launch:focus-visible{border-color:#63d4cf;color:#fff;outline:none;box-shadow:0 0 0 2px rgba(99,212,207,.18),0 18px 50px rgba(0,0,0,.55)}',
32
+ '#fa-launch .fa-l1{display:flex;align-items:center;gap:8px;font-size:9px;font-weight:800}#fa-launch .fa-l2{display:block;margin-top:5px;color:#829195;font-size:8px;letter-spacing:.06em;text-transform:none}',
33
+ '.fa-signal{width:7px;height:7px;border-radius:1px;background:#63d4cf;box-shadow:0 0 12px rgba(99,212,207,.7)}',
34
+ '#fa-scrim{position:fixed;z-index:198;inset:0;background:rgba(0,0,0,.52);opacity:0;pointer-events:none;transition:opacity .2s ease}#fa-scrim.open{opacity:1;pointer-events:auto}',
35
+ '#fa-panel{position:fixed;z-index:199;right:0;top:0;height:100%;width:min(570px,100vw);display:flex;flex-direction:column;background:linear-gradient(180deg,#0b1015 0%,#070b0f 100%);color:#dce5e6;border-left:1px solid #273237;box-shadow:-30px 0 90px rgba(0,0,0,.62);transform:translateX(102%);transition:transform .24s cubic-bezier(.2,.8,.2,1);font-family:var(--font-d,system-ui);pointer-events:auto}#fa-panel.open{transform:translateX(0)}',
36
+ 'body.fa-open #ux-tabbar,body.fa-open #ux-more-menu,body.fa-open #dissect-fab{opacity:0!important;pointer-events:none!important}',
37
+ '.fa-top{padding:18px 20px 14px;border-bottom:1px solid #273237;background:#0d1318}.fa-kicker{display:flex;align-items:center;gap:8px;color:#78d9d4;font:800 9px/1 var(--font-m,monospace);letter-spacing:.20em;text-transform:uppercase}.fa-kicker:before{content:"";width:18px;height:1px;background:#78d9d4}',
38
+ '.fa-title-row{display:flex;justify-content:space-between;align-items:flex-start;gap:16px;margin-top:10px}.fa-title{margin:0;font-size:25px;line-height:1.05;font-weight:620;letter-spacing:-.025em;color:#f2f7f7}.fa-subtitle{margin:7px 0 0;color:#8e9da0;font:11px/1.5 var(--font-m,monospace);max-width:46ch}',
39
+ '.fa-close{flex:0 0 auto;width:34px;height:34px;color:#aebbbd;background:#11191e;border:1px solid #334047;cursor:pointer;font-size:18px}.fa-close:hover,.fa-close:focus-visible{color:#fff;border-color:#78d9d4;outline:none}',
40
+ '.fa-rail{display:grid;grid-template-columns:repeat(4,1fr);border-bottom:1px solid #273237;background:#080d11}.fa-dim{padding:10px 11px;border-right:1px solid #20292e;min-width:0}.fa-dim:last-child{border-right:0}.fa-dim-label{display:block;color:#647277;font:8px/1.2 var(--font-m,monospace);letter-spacing:.12em;text-transform:uppercase}.fa-dim-value{display:block;margin-top:5px;color:#c7d2d4;font:800 9px/1.2 var(--font-m,monospace);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
41
+ '.fa-dim-value.live,.fa-dim-value.computed,.fa-dim-value.reachable,.fa-dim-value.available{color:#78d9d4}.fa-dim-value.mixed,.fa-dim-value.structural_only,.fa-dim-value.snapshot,.fa-dim-value.modeled{color:#e1bd71}.fa-dim-value.unavailable,.fa-dim-value.failed,.fa-dim-value.unreachable,.fa-dim-value.missing{color:#e37d8f}',
42
+ '.fa-tabs{display:flex;padding:0 20px;border-bottom:1px solid #273237;background:#0b1015;overflow:auto}.fa-tab{appearance:none;border:0;border-bottom:2px solid transparent;background:transparent;color:#718086;padding:12px 11px 10px;font:800 9px/1 var(--font-m,monospace);letter-spacing:.12em;text-transform:uppercase;cursor:pointer;white-space:nowrap}.fa-tab:hover{color:#cad5d7}.fa-tab.active{color:#78d9d4;border-bottom-color:#78d9d4}.fa-tab:focus-visible{outline:1px solid #78d9d4;outline-offset:-3px}',
43
+ '.fa-body{flex:1;overflow:auto;padding:20px 20px 90px;scrollbar-color:#334047 #0b1015}.fa-section{margin:0 0 24px}.fa-section-head{display:flex;align-items:center;justify-content:space-between;gap:12px;margin:0 0 11px}.fa-section h3{margin:0;color:#aebbbd;font:800 9px/1.2 var(--font-m,monospace);letter-spacing:.15em;text-transform:uppercase}.fa-rule{height:1px;flex:1;background:#273237}',
44
+ '.fa-lede{margin:0;color:#d6dfe0;font-size:15px;line-height:1.55;letter-spacing:-.005em}.fa-callout{border-left:2px solid #78d9d4;background:#0d1519;padding:12px 13px;margin-top:14px;color:#9daaad;font:11px/1.55 var(--font-m,monospace)}',
45
+ '.fa-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}.fa-stat{background:#0d1318;border:1px solid #273237;padding:12px;min-height:88px}.fa-stat .k{color:#6f7e82;font:8px/1.2 var(--font-m,monospace);letter-spacing:.12em;text-transform:uppercase}.fa-stat .v{margin-top:9px;color:#edf3f3;font:800 12px/1.2 var(--font-m,monospace)}.fa-stat p{margin:8px 0 0;color:#79888c;font-size:10px;line-height:1.4}',
46
+ '.fa-actions{display:flex;flex-wrap:wrap;gap:7px;margin-top:14px}.fa-btn,.fa-link{display:inline-flex;align-items:center;justify-content:center;min-height:34px;padding:0 11px;border:1px solid #35444a;background:#10181d;color:#bdc9cb;text-decoration:none;cursor:pointer;font:800 9px/1 var(--font-m,monospace);letter-spacing:.08em;text-transform:uppercase}.fa-btn.primary{border-color:#2b8c8a;background:#12302f;color:#9ff1ec}.fa-btn:hover,.fa-link:hover,.fa-btn:focus-visible,.fa-link:focus-visible{border-color:#78d9d4;color:#fff;outline:none}.fa-btn:disabled{opacity:.45;cursor:wait}',
47
+ '.fa-cap{border:1px solid #273237;background:#0b1115;margin:0 0 9px}.fa-cap summary{list-style:none;display:grid;grid-template-columns:30px 1fr auto;align-items:center;gap:10px;padding:12px 13px;cursor:pointer}.fa-cap summary::-webkit-details-marker{display:none}.fa-cap summary:hover{background:#0f171c}.fa-num{color:#536267;font:800 9px/1 var(--font-m,monospace)}.fa-cap-name{color:#e4ebec;font-size:13px;font-weight:650}.fa-cap-id{display:block;margin-top:3px;color:#617075;font:8px/1.2 var(--font-m,monospace)}',
48
+ '.fa-badge{display:inline-block;border:1px solid #3c4a4f;color:#8e9c9f;padding:3px 6px;font:800 8px/1 var(--font-m,monospace);letter-spacing:.06em;text-transform:uppercase}.fa-badge.live,.fa-badge.computed,.fa-badge.available,.fa-badge.pass{border-color:#286d6b;color:#78d9d4;background:rgba(40,109,107,.13)}.fa-badge.snapshot,.fa-badge.mixed,.fa-badge.modeled,.fa-badge.structural-only,.fa-badge.structural_only,.fa-badge.unavailable,.fa-badge.read_only{border-color:#685937;color:#e1bd71;background:rgba(104,89,55,.12)}.fa-badge.fail,.fa-badge.failed,.fa-badge.missing,.fa-badge.unreachable{border-color:#663640;color:#e37d8f;background:rgba(102,54,64,.12)}',
49
+ '.fa-cap-body{border-top:1px solid #273237;padding:13px}.fa-field{display:grid;grid-template-columns:86px 1fr;gap:12px;padding:8px 0;border-bottom:1px solid #1e272b}.fa-field:last-child{border-bottom:0}.fa-field dt{color:#657378;font:800 8px/1.4 var(--font-m,monospace);letter-spacing:.12em;text-transform:uppercase}.fa-field dd{margin:0;color:#aebabc;font-size:11px;line-height:1.52;min-width:0}.fa-field ul,.fa-field ol{margin:0;padding-left:17px}.fa-field li+li{margin-top:5px}',
50
+ '.fa-code{display:block;margin-top:5px;padding:8px;background:#070b0e;border:1px solid #202b30;color:#8ed6d2;font:9px/1.5 var(--font-m,monospace);word-break:break-all}.fa-refs{display:flex;flex-wrap:wrap;gap:5px;margin-top:7px}.fa-ref{color:#8ec6c4;text-decoration:none;border-bottom:1px solid #31504f;font:9px/1.4 var(--font-m,monospace)}.fa-ref:hover{color:#fff;border-color:#78d9d4}',
51
+ '.fa-dep{display:grid;grid-template-columns:1fr auto;gap:10px;padding:12px 0;border-bottom:1px solid #20292e}.fa-dep:last-child{border-bottom:0}.fa-dep-name{color:#d8e1e2;font-size:12px;font-weight:650}.fa-dep-purpose{display:block;margin-top:4px;color:#718084;font-size:10px;line-height:1.4}.fa-dep-meta{display:block;margin-top:5px;color:#4f6065;font:8px/1.3 var(--font-m,monospace);word-break:break-all}.fa-dep-state{text-align:right;min-width:88px}.fa-http{display:block;margin-top:5px;color:#66757a;font:8px/1 var(--font-m,monospace)}',
52
+ '.fa-output{margin-top:12px;background:#070b0e;border:1px solid #273237;padding:11px;color:#9caaad;font:10px/1.55 var(--font-m,monospace);word-break:break-word}.fa-output.good{border-color:#286d6b;color:#9be2de}.fa-output.bad{border-color:#663640;color:#e3a0ab}',
53
+ '.fa-endpoint{padding:12px 0;border-bottom:1px solid #20292e}.fa-endpoint:last-child{border-bottom:0}.fa-endpoint a{color:#c8d5d6;text-decoration:none;font:700 10px/1.4 var(--font-m,monospace)}.fa-endpoint a:hover{color:#78d9d4}.fa-endpoint p{margin:5px 0 0;color:#6f7d81;font-size:10px;line-height:1.45}',
54
+ '.fa-loading{padding:28px 0;color:#6e7b7f;font:10px/1.5 var(--font-m,monospace);text-transform:uppercase;letter-spacing:.12em}.fa-loading:before{content:"";display:inline-block;width:7px;height:7px;margin-right:9px;background:#e1bd71;animation:fa-pulse .9s ease-in-out infinite}@keyframes fa-pulse{50%{opacity:.25}}',
55
+ '@media(max-width:760px){#fa-launch{right:8px;top:auto;bottom:76px;transform:none;width:auto;padding:9px 11px}#fa-launch .fa-l2{display:none}#fa-panel{width:100vw}.fa-grid{grid-template-columns:1fr}.fa-body{padding:16px 15px 100px}.fa-top{padding:16px 15px 13px}.fa-tabs{padding:0 10px}.fa-rail{grid-template-columns:repeat(2,1fr)}.fa-dim:nth-child(2){border-right:0}.fa-dim:nth-child(-n+2){border-bottom:1px solid #20292e}.fa-field{grid-template-columns:72px 1fr}}',
56
+ '@media(prefers-reduced-motion:reduce){#fa-panel,#fa-scrim{transition:none}.fa-loading:before{animation:none}}'
57
+ ].join('');
58
+
59
+ function injectStyle(){ if(document.getElementById('fa-style'))return; var s=document.createElement('style');s.id='fa-style';s.textContent=css;document.head.appendChild(s); }
60
+ function badge(value){var label=String(value||'UNKNOWN');return '<span class="fa-badge '+esc(label.toLowerCase())+'">'+esc(label.replace(/_/g,'-'))+'</span>';}
61
+ function dim(label,value){var v=String(value||'UNKNOWN');return '<div class="fa-dim"><span class="fa-dim-label">'+esc(label)+'</span><span class="fa-dim-value '+esc(v.toLowerCase())+'">'+esc(v.replace(/_/g,'-'))+'</span></div>';}
62
+ function list(values,ordered){if(!Array.isArray(values)||!values.length)return '<span>None declared.</span>';var tag=ordered?'ol':'ul';return '<'+tag+'>'+values.map(function(v){return '<li>'+esc(v)+'</li>';}).join('')+'</'+tag+'>';}
63
+ function links(values){if(!Array.isArray(values)||!values.length)return '';return '<div class="fa-refs">'+values.map(function(url,i){return '<a class="fa-ref" href="'+esc(url)+'" target="_blank" rel="noopener">source '+(i+1)+' ↗</a>';}).join('')+'</div>';}
64
+ function sectionHead(title){return '<div class="fa-section-head"><h3>'+esc(title)+'</h3><span class="fa-rule"></span></div>';}
65
+
66
+ function updateRail(){
67
+ var d=state.manifest&&state.manifest.state_dimensions||{};
68
+ if(state.evidence)d=Object.assign({},d,{evidence_state:state.evidence.evidence_state,verification_state:state.evidence.verification_state==='AVAILABLE'?'AVAILABLE':d.verification_state});
69
+ var rail=document.getElementById('fa-rail');if(rail)rail.innerHTML=dim('transport',d.transport_state)+dim('evidence',d.evidence_state)+dim('verification',d.verification_state)+dim('authority',d.authority_state);
70
+ var sub=document.querySelector('#fa-launch .fa-l2');if(sub)sub.textContent=(d.evidence_state||'loading')+' evidence · read-only';
71
+ }
72
+ function overviewHTML(){
73
+ var m=state.manifest||{},d=m.state_dimensions||{};
74
+ return '<section class="fa-section">'+sectionHead('Mission contract')+'<p class="fa-lede">'+esc(m.purpose||'Read-only spatial evidence map of the governed-agent substrate.')+'</p><div class="fa-callout">One green light is not enough. Transport, evidence, verification, and authority are independent dimensions; this console refuses to collapse them into a single “healthy” claim.</div></section>'+
75
+ '<section class="fa-section">'+sectionHead('Current posture')+'<div class="fa-grid"><div class="fa-stat"><div class="k">Transport</div><div class="v">'+esc(d.transport_state||'—')+'</div><p>Can this Space answer a request?</p></div><div class="fa-stat"><div class="k">Evidence</div><div class="v">'+esc(state.evidence&&state.evidence.evidence_state||d.evidence_state||'—')+'</div><p>Live, computed, snapshot, modeled, or unavailable?</p></div><div class="fa-stat"><div class="k">Verification</div><div class="v">'+esc(d.verification_state||'—')+'</div><p>The local receipt is unsigned and structural-only.</p></div><div class="fa-stat"><div class="k">Authority</div><div class="v">'+esc(d.authority_state||'—')+'</div><p>Anatomy reads and explains; it cannot actuate.</p></div></div><div class="fa-actions"><button class="fa-btn primary" id="fa-verify-bundle">Verify deployed bundle</button><button class="fa-btn" id="fa-refresh">Refresh live evidence</button><a class="fa-link" href="/.well-known/szl-source.json" target="_blank" rel="noopener">Source attestation ↗</a></div><div id="fa-overview-output" aria-live="polite"></div></section>'+
76
+ '<section class="fa-section">'+sectionHead('Honest boundary')+list(m.limits||[],false)+'</section>';
77
+ }
78
+ function capabilitiesHTML(){
79
+ var rows=state.capabilities&&state.capabilities.capabilities||[];if(!rows.length)return '<div class="fa-loading">Capability contract unavailable</div>';
80
+ return '<section class="fa-section">'+sectionHead('Five-part capability shell')+'<p class="fa-lede" style="font-size:12px">Every surface declares Purpose, Try, Evidence, Limits, and Reproduce before it earns a place in the body.</p></section>'+rows.map(function(cap,i){
81
+ var ev=cap.evidence||{},t=cap.try||{},r=cap.reproduce||{};
82
+ return '<details class="fa-cap"'+(i===0?' open':'')+'><summary><span class="fa-num">'+String(i+1).padStart(2,'0')+'</span><span class="fa-cap-name">'+esc(cap.name)+'<span class="fa-cap-id">'+esc(cap.id)+'</span></span>'+badge(ev.state)+'</summary><div class="fa-cap-body"><dl><div class="fa-field"><dt>Purpose</dt><dd>'+esc(cap.purpose)+'</dd></div><div class="fa-field"><dt>Try</dt><dd>'+esc(t.action||'')+'<code class="fa-code">'+esc((t.method||'')+' '+(t.path||''))+'</code></dd></div><div class="fa-field"><dt>Evidence</dt><dd>'+badge(ev.state)+' '+esc(ev.basis||'')+'</dd></div><div class="fa-field"><dt>Limits</dt><dd>'+list(cap.limits,false)+'</dd></div><div class="fa-field"><dt>Reproduce</dt><dd>'+list(r.steps,true)+'</dd></div><div class="fa-field"><dt>Authority</dt><dd>'+badge(cap.authority_state)+'</dd></div><div class="fa-field"><dt>Formula refs</dt><dd>'+(cap.formula_refs&&cap.formula_refs.length?esc(cap.formula_refs.join(' · ')):'None — visual capability only.')+links(cap.provenance)+'</dd></div></dl></div></details>';
83
+ }).join('');
84
+ }
85
+ function evidenceHTML(){
86
+ if(!state.evidence)return '<div class="fa-loading">Measuring declared dependencies</div>';var e=state.evidence;
87
+ return '<section class="fa-section">'+sectionHead('Measured dependency plane')+'<p class="fa-lede" style="font-size:12px">'+esc(e.scope)+'</p><div class="fa-callout">Observed '+esc(e.observed_at)+' · '+esc(e.summary&&e.summary.live)+'/'+esc(e.summary&&e.summary.total)+' declared contracts available.</div>'+(e.dependencies||[]).map(function(dep){return '<div class="fa-dep"><div><span class="fa-dep-name">'+esc(dep.id)+'</span><span class="fa-dep-purpose">'+esc(dep.purpose)+'</span><span class="fa-dep-meta">'+esc(dep.method+' '+dep.url)+'</span></div><div class="fa-dep-state">'+badge(dep.contract_state)+'<span class="fa-http">HTTP '+esc(dep.http_status==null?'—':dep.http_status)+'</span></div></div>';}).join('')+'<div class="fa-actions"><button class="fa-btn primary" id="fa-refresh">Re-probe now</button><a class="fa-link" href="https://huggingface.co/spaces/SZLHOLDINGS/governed-receipt-verifier" target="_blank" rel="noopener">Independent verifier ↗</a></div></section><section class="fa-section">'+sectionHead('Interpretation limits')+list(e.limits,false)+'</section>';
88
+ }
89
+ function reproduceHTML(){
90
+ var ep=state.manifest&&state.manifest.endpoints||{},desc={manifest:'Contract, vocabulary, doctrine boundary, and limits.',capabilities:'Purpose / Try / Evidence / Limits / Reproduce for each capability.',evidence:'Fresh server-side probes of declared upstream contracts.',receipt:'Deterministic SHA-256 receipt over the deployed artifact set.',verify_receipt:'POST a local anatomy receipt; structural integrity only.',source:'GitHub base, measured HF revision, artifact digest, and alignment state.'};
91
+ return '<section class="fa-section">'+sectionHead('Machine-readable contract')+Object.keys(ep).map(function(k){var p=ep[k];return '<div class="fa-endpoint"><a href="'+esc(p.replace('?refresh=1',''))+'" target="_blank" rel="noopener">'+esc(p)+' ↗</a><p>'+esc(desc[k]||'')+'</p></div>';}).join('')+'</section><section class="fa-section">'+sectionHead('Receipt replay')+'<p class="fa-lede" style="font-size:12px">Generate the receipt, then submit the unchanged object to the local verifier. A byte or digest mutation must produce FAIL.</p><code class="fa-code">GET /api/anatomy/v1/receipt<br>POST /api/anatomy/v1/verify/receipt</code><div class="fa-actions"><button class="fa-btn primary" id="fa-verify-bundle">Run replay now</button><a class="fa-link" href="https://github.com/szl-holdings/anatomy" target="_blank" rel="noopener">GitHub source ↗</a></div><div id="fa-overview-output" aria-live="polite"></div></section>';
92
+ }
93
+ function bodyHTML(){if(!state.manifest||!state.capabilities)return '<div class="fa-loading">Loading anatomy contract</div>';if(state.tab==='capabilities')return capabilitiesHTML();if(state.tab==='evidence')return evidenceHTML();if(state.tab==='reproduce')return reproduceHTML();return overviewHTML();}
94
+ function render(){updateRail();var body=document.getElementById('fa-body');if(body)body.innerHTML=bodyHTML();document.querySelectorAll('.fa-tab').forEach(function(b){b.classList.toggle('active',b.getAttribute('data-tab')===state.tab);b.setAttribute('aria-selected',b.classList.contains('active')?'true':'false');});wireBodyActions();}
95
+ function setOutput(html,kind){var out=document.getElementById('fa-overview-output');if(out)out.innerHTML='<div class="fa-output '+esc(kind||'')+'">'+html+'</div>';}
96
+ function verifyBundle(){
97
+ if(state.busy)return;state.busy=true;setOutput('Hashing the deployed artifact set and replaying the receipt…','');
98
+ fetchJSON(API+'/receipt').then(function(res){if(!res.ok)return res;return fetchJSON(API+'/verify/receipt',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(res.data)});}).then(function(res){state.busy=false;if(!res||!res.ok||!res.data){setOutput('Verifier unavailable. No verdict was inferred.','bad');return;}var checks=(res.data.checks||[]).map(function(c){return esc(c.name)+'='+esc(c.status);}).join(' · ');setOutput('<strong>'+esc(res.data.verdict)+'</strong><br>'+checks+'<br><span style="color:#66777a">'+esc(res.data.limits)+'</span>',res.data.verdict==='FAIL'?'bad':'good');});
99
+ }
100
+ function loadEvidence(force){fetchJSON(API+'/evidence'+(force?'?refresh=1':''),{},16000).then(function(res){state.evidence=res.ok?res.data:{evidence_state:'UNAVAILABLE',verification_state:'UNAVAILABLE',scope:'Evidence endpoint unavailable.',summary:{live:0,total:0},dependencies:[],limits:['No dependency state was inferred.']};render();});}
101
+ function wireBodyActions(){document.querySelectorAll('#fa-refresh').forEach(function(b){b.addEventListener('click',function(){b.disabled=true;if(state.tab==='evidence'){state.evidence=null;render();}loadEvidence(true);});});document.querySelectorAll('#fa-verify-bundle').forEach(function(b){b.addEventListener('click',verifyBundle);});}
102
+ function open(){previousFocus=document.activeElement;document.body.classList.add('fa-open');document.getElementById('fa-panel').classList.add('open');document.getElementById('fa-panel').setAttribute('aria-hidden','false');document.getElementById('fa-scrim').classList.add('open');document.getElementById('fa-launch').setAttribute('aria-expanded','true');document.getElementById('fa-close').focus();}
103
+ function close(){document.body.classList.remove('fa-open');document.getElementById('fa-panel').classList.remove('open');document.getElementById('fa-panel').setAttribute('aria-hidden','true');document.getElementById('fa-scrim').classList.remove('open');document.getElementById('fa-launch').setAttribute('aria-expanded','false');if(previousFocus&&previousFocus.focus)previousFocus.focus();}
104
+ function mount(){
105
+ if(document.getElementById('fa-panel'))return;injectStyle();
106
+ var launch=document.createElement('button');launch.id='fa-launch';launch.type='button';launch.setAttribute('aria-controls','fa-panel');launch.setAttribute('aria-expanded','false');launch.innerHTML='<span class="fa-l1"><i class="fa-signal"></i>Evidence bay</span><span class="fa-l2">loading contract · read-only</span>';
107
+ var scrim=document.createElement('div');scrim.id='fa-scrim';var panel=document.createElement('aside');panel.id='fa-panel';panel.setAttribute('role','dialog');panel.setAttribute('aria-modal','false');panel.setAttribute('aria-hidden','true');panel.setAttribute('aria-label','Anatomy evidence bay');panel.innerHTML='<header class="fa-top"><div class="fa-kicker">Anatomy contract 1.0</div><div class="fa-title-row"><div><h2 class="fa-title">Evidence Bay</h2><p class="fa-subtitle">Purpose · Try · Evidence · Limits · Reproduce</p></div><button class="fa-close" id="fa-close" type="button" aria-label="Close evidence bay">×</button></div></header><div class="fa-rail" id="fa-rail">'+dim('transport','LOADING')+dim('evidence','LOADING')+dim('verification','LOADING')+dim('authority','READ_ONLY')+'</div><nav class="fa-tabs" role="tablist" aria-label="Evidence Bay sections"><button class="fa-tab active" role="tab" data-tab="overview">Overview</button><button class="fa-tab" role="tab" data-tab="capabilities">Capabilities</button><button class="fa-tab" role="tab" data-tab="evidence">Evidence</button><button class="fa-tab" role="tab" data-tab="reproduce">Reproduce</button></nav><main class="fa-body" id="fa-body"><div class="fa-loading">Loading anatomy contract</div></main>';
108
+ document.body.appendChild(launch);document.body.appendChild(scrim);document.body.appendChild(panel);launch.addEventListener('click',open);scrim.addEventListener('click',close);document.getElementById('fa-close').addEventListener('click',close);document.querySelectorAll('.fa-tab').forEach(function(b){b.addEventListener('click',function(){state.tab=b.getAttribute('data-tab');render();document.getElementById('fa-body').scrollTop=0;});});document.addEventListener('keydown',function(e){if(e.key==='Escape'&&panel.classList.contains('open'))close();});
109
+ Promise.all([fetchJSON(API+'/manifest'),fetchJSON(API+'/capabilities')]).then(function(results){if(results[0].ok)state.manifest=results[0].data;if(results[1].ok)state.capabilities=results[1].data;render();loadEvidence(false);});
110
+ }
111
+ root.SZL_ANATOMY_EVIDENCE_BAY={mount:mount,open:open,close:close,refresh:function(){loadEvidence(true);},verifyBundle:verifyBundle};
112
+ if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',mount);else mount();
113
+ })(typeof window!=='undefined'?window:this);
index.html CHANGED
@@ -2,6 +2,7 @@
2
  <html lang="en">
3
  <head>
4
  <meta charset="utf-8" />
 
5
  <!-- SAFE-NOW hardening (R2). This Space is sdk:static on HF; HF's static serving
6
  only honors COOP/COEP/CORP via README custom_headers and does NOT pass through
7
  arbitrary response headers (no _headers file, no CSP/HSTS/Referrer at the edge).
@@ -18,8 +19,8 @@
18
  <meta http-equiv="X-Content-Type-Options" content="nosniff" />
19
  <meta name="referrer" content="strict-origin-when-cross-origin" />
20
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2" />
21
- <title>SZL Agent Body v5 (evolves v4) — Living Anatomy · WILLAY conscience · Sovereign Mesh · buyer-verifiable receipts</title>
22
- <meta name="description" content="The SZL Agent Body v4 a genuine anatomical organism. Two bodies (a11oy + killinchu) sharing one circulatory (YAWAR receipt bus) + nervous (span lineage) mesh, with proven formulas flowing through the organs and the Λ heart beating at the center." />
23
  <style>
24
  /* ============ DESIGN TOKENS — cinematic dark scientific ============ */
25
  :root{
@@ -1763,6 +1764,7 @@
1763
  <script src="./app.js"></script>
1764
  <!-- v5 (evolves v4): WILLAY · Sovereign Mesh · buyer-verifiable receipt · 8-proof map · assurance · physics. Additive, read-only, 0-CDN. -->
1765
  <script src="./v5_organs.js"></script>
 
 
1766
  </body>
1767
  </html>
1768
-
 
2
  <html lang="en">
3
  <head>
4
  <meta charset="utf-8" />
5
+ <link rel="icon" href="./favicon.svg" type="image/svg+xml" />
6
  <!-- SAFE-NOW hardening (R2). This Space is sdk:static on HF; HF's static serving
7
  only honors COOP/COEP/CORP via README custom_headers and does NOT pass through
8
  arbitrary response headers (no _headers file, no CSP/HSTS/Referrer at the edge).
 
19
  <meta http-equiv="X-Content-Type-Options" content="nosniff" />
20
  <meta name="referrer" content="strict-origin-when-cross-origin" />
21
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2" />
22
+ <title>SZL Living Anatomy Governed Agent Body · Evidence Bay</title>
23
+ <meta name="description" content="A navigable governed-agent anatomy with an evidence-bound capability contract: purpose, live or snapshot evidence, limits, provenance, receipts, and reproducible verification." />
24
  <style>
25
  /* ============ DESIGN TOKENS — cinematic dark scientific ============ */
26
  :root{
 
1764
  <script src="./app.js"></script>
1765
  <!-- v5 (evolves v4): WILLAY · Sovereign Mesh · buyer-verifiable receipt · 8-proof map · assurance · physics. Additive, read-only, 0-CDN. -->
1766
  <script src="./v5_organs.js"></script>
1767
+ <!-- Evidence Bay: industrial proof boundary + five-part capability contract. Read-only, zero CDN. -->
1768
+ <script src="./frontier_anatomy.js"></script>
1769
  </body>
1770
  </html>
 
lib/szl_verify_widget.js CHANGED
@@ -3,8 +3,8 @@
3
  * ----------------------------------------------------------------------------
4
  * 0 runtime CDN · system fonts only · AbortController · honest fallback.
5
  * Calls the REAL a11oy verify endpoint and renders its REAL honest verdict.
6
- * POST {base}/api/a11oy/v1/verify body = a receipt / DSSE envelope / in-toto stmt
7
- * GET {base}/api/a11oy/v1/verify?url=<public receipt url>
8
  *
9
  * Doctrine v11: this widget NEVER fabricates a verdict. It shows exactly what
10
  * the server returns (verdict: VERIFIED | STRUCTURAL-ONLY | FAILED | UNRECOGNISED).
@@ -19,14 +19,13 @@
19
  (function (global) {
20
  'use strict';
21
 
22
- var DEFAULT_BASE = 'https://a11oy.net'; // same fabric the estate already talks to
 
23
  var TIMEOUT_MS = 12000;
24
  var SAMPLE = {
25
- _type: 'https://in-toto.io/Statement/v1',
26
- subject: [{ name: 'szl-lake/homflyreceipt_gate',
27
- digest: { sha256: '0a2d153d81c00688b576e5a012ae6117465639807456d1bb72eb590cac3b1e9d' } }],
28
- predicateType: 'https://szlholdings.com/attestations/innovation/v1',
29
- predicate: { note: 'paste your own receipt JSON here, or a public receipt URL' }
30
  };
31
 
32
  function esc(s){ return String(s==null?'':s).replace(/[&<>"]/g,function(c){
@@ -55,10 +54,10 @@
55
  /* map an HONEST verdict string -> {label, cls, advisory} ---------------- */
56
  function verdictView(v){
57
  var s = String(v||'').toUpperCase();
58
- if(s==='VERIFIED') return {label:'VERIFIED', cls:'ok', advisory:false};
59
- if(s==='STRUCTURAL-ONLY') return {label:'STRUCTURAL-ONLY', cls:'warn', advisory:true};
60
- if(s==='FAILED') return {label:'FAILED', cls:'fail', advisory:false};
61
- if(s==='UNRECOGNISED') return {label:'UNRECOGNISED', cls:'muted',advisory:false};
62
  return {label: s||'—', cls:'muted', advisory:false};
63
  }
64
 
@@ -66,9 +65,10 @@
66
  if(!Array.isArray(checks) || !checks.length) return '';
67
  var rows = checks.map(function(c){
68
  var st = String(c.status||'').toLowerCase();
69
- var cls = st==='pass' ? 'ok' : (st==='fail' ? 'fail' : 'muted');
 
70
  return '<li class="szlv-chk"><span class="szlv-pill '+cls+'">'+esc(c.status||'?')+'</span>'+
71
- '<code>'+esc(c.name||'check')+'</code>'+
72
  (c.detail ? '<span class="szlv-det">'+esc(c.detail)+'</span>' : '')+'</li>';
73
  }).join('');
74
  return '<ul class="szlv-checks">'+rows+'</ul>';
@@ -96,7 +96,7 @@
96
  var kinds = (Array.isArray(d.kinds)&&d.kinds.length)
97
  ? '<p class="szlv-kinds">recognised as: '+d.kinds.map(esc).join(', ')+'</p>' : '';
98
  var checks = renderChecks(d.checks);
99
- var foot = '<p class="szlv-foot">engine '+esc(d.engine_version||'?')+
100
  ' · doctrine '+esc((d.doctrine&&d.doctrine.version)||'v11')+
101
  ' · Λ='+esc((d.doctrine&&d.doctrine.lambda)||'Conjecture 1')+
102
  (d.verified_at ? ' · '+esc(d.verified_at) : '')+
@@ -132,6 +132,7 @@
132
  '.szlv-pill{font-size:10px;text-transform:uppercase;letter-spacing:.4px;padding:2px 6px;border-radius:4px;font-weight:700}',
133
  '.szlv-pill.ok{background:rgba(109,170,69,.18);color:#6daa45}',
134
  '.szlv-pill.fail{background:rgba(209,99,167,.18);color:#d163a7}',
 
135
  '.szlv-pill.muted{background:#2a2927;color:#797876}',
136
  '.szlv-chk code{color:#cdccca}.szlv-det{color:#797876;font-size:11px}',
137
  '.szlv-foot{font-size:10px;color:#5a5957;margin:10px 0 0;line-height:1.5}',
@@ -180,17 +181,23 @@
180
 
181
  go.addEventListener('click', function(){
182
  go.disabled = true;
183
- out.innerHTML = '<span class="szlv-load">calling <code>'+esc(base)+'/api/a11oy/v1/verify</code>\u2026</span>';
184
  var p, u = url.value.trim(), body = ta.value.trim();
185
  if(u){
186
- p = pull(base+'/api/a11oy/v1/verify?url='+encodeURIComponent(u), {method:'GET'});
 
 
 
 
 
187
  } else if(body){
188
  var parsed = null;
189
  try{ parsed = JSON.parse(body); }catch(e){
190
  out.innerHTML = '<div class="szlv-state muted">input is not valid JSON — paste a receipt object or use a URL.</div>';
191
  go.disabled = false; return;
192
  }
193
- p = pull(base+'/api/a11oy/v1/verify', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(parsed)});
 
194
  } else {
195
  out.innerHTML = '<div class="szlv-state muted">paste a receipt JSON, or enter a public receipt URL.</div>';
196
  go.disabled = false; return;
@@ -201,7 +208,7 @@
201
  return { reload:function(){}, base:base };
202
  }
203
 
204
- var api = { mount: mount, pull: pull, _sample: SAMPLE, version: '1.0.0' };
205
  if (typeof module!=='undefined' && module.exports) module.exports = api;
206
  global.SZLVerify = api;
207
  })(typeof window!=='undefined' ? window : this);
 
3
  * ----------------------------------------------------------------------------
4
  * 0 runtime CDN · system fonts only · AbortController · honest fallback.
5
  * Calls the REAL a11oy verify endpoint and renders its REAL honest verdict.
6
+ * POST {base}/api/a11oy/v1/verify/receipt body = {envelope: <DSSE envelope>}
7
+ * Public receipt URLs are fetched in the browser and submitted to that endpoint.
8
  *
9
  * Doctrine v11: this widget NEVER fabricates a verdict. It shows exactly what
10
  * the server returns (verdict: VERIFIED | STRUCTURAL-ONLY | FAILED | UNRECOGNISED).
 
19
  (function (global) {
20
  'use strict';
21
 
22
+ var DEFAULT_BASE = 'https://szlholdings-a11oy.hf.space';
23
+ var VERIFY_PATH = '/api/a11oy/v1/verify/receipt';
24
  var TIMEOUT_MS = 12000;
25
  var SAMPLE = {
26
+ payloadType: 'application/vnd.szl.receipt+json',
27
+ payload: 'eyJib2R5Ijp7ImNsYWltIjoic3psLXdpZGdldC1jb250cmFjdCIsIm9yZ2FuIjoicHVibGljLXZlcmlmaWVyLXdpZGdldCIsInZhbHVlIjoic2FtcGxlIn0sInBheWxvYWRfZGlnZXN0IjoiMzU0YWZlZDZlMWQyODVjNDgxZTg4OWFlZGQzZDA4ODA3YzhhYTc5MjkyM2IzMThhMTc0YjNiNTg1OWI2N2FhMSJ9',
28
+ signatures: []
 
 
29
  };
30
 
31
  function esc(s){ return String(s==null?'':s).replace(/[&<>"]/g,function(c){
 
54
  /* map an HONEST verdict string -> {label, cls, advisory} ---------------- */
55
  function verdictView(v){
56
  var s = String(v||'').toUpperCase();
57
+ if(s==='PASS'||s==='VERIFIED') return {label:s, cls:'ok', advisory:false};
58
+ if(s==='PARTIAL'||s==='STRUCTURAL-ONLY'||s==='INCONCLUSIVE') return {label:s, cls:'warn', advisory:true};
59
+ if(s==='FAIL'||s==='FAILED'||s==='MISMATCH') return {label:'FAIL', cls:'fail', advisory:false};
60
+ if(s==='NO_INPUT'||s==='UNRECOGNISED') return {label:s, cls:'muted', advisory:false};
61
  return {label: s||'—', cls:'muted', advisory:false};
62
  }
63
 
 
65
  if(!Array.isArray(checks) || !checks.length) return '';
66
  var rows = checks.map(function(c){
67
  var st = String(c.status||'').toLowerCase();
68
+ var cls = (st==='pass'||st==='verified') ? 'ok' :
69
+ ((st==='fail'||st==='mismatch') ? 'fail' : (st==='unsigned-local' ? 'warn' : 'muted'));
70
  return '<li class="szlv-chk"><span class="szlv-pill '+cls+'">'+esc(c.status||'?')+'</span>'+
71
+ '<code>'+esc(c.name||c.check||'check')+'</code>'+
72
  (c.detail ? '<span class="szlv-det">'+esc(c.detail)+'</span>' : '')+'</li>';
73
  }).join('');
74
  return '<ul class="szlv-checks">'+rows+'</ul>';
 
96
  var kinds = (Array.isArray(d.kinds)&&d.kinds.length)
97
  ? '<p class="szlv-kinds">recognised as: '+d.kinds.map(esc).join(', ')+'</p>' : '';
98
  var checks = renderChecks(d.checks);
99
+ var foot = '<p class="szlv-foot">engine '+esc(d.engine_version||d.service||'?')+
100
  ' · doctrine '+esc((d.doctrine&&d.doctrine.version)||'v11')+
101
  ' · Λ='+esc((d.doctrine&&d.doctrine.lambda)||'Conjecture 1')+
102
  (d.verified_at ? ' · '+esc(d.verified_at) : '')+
 
132
  '.szlv-pill{font-size:10px;text-transform:uppercase;letter-spacing:.4px;padding:2px 6px;border-radius:4px;font-weight:700}',
133
  '.szlv-pill.ok{background:rgba(109,170,69,.18);color:#6daa45}',
134
  '.szlv-pill.fail{background:rgba(209,99,167,.18);color:#d163a7}',
135
+ '.szlv-pill.warn{background:rgba(232,175,52,.14);color:#e8af34}',
136
  '.szlv-pill.muted{background:#2a2927;color:#797876}',
137
  '.szlv-chk code{color:#cdccca}.szlv-det{color:#797876;font-size:11px}',
138
  '.szlv-foot{font-size:10px;color:#5a5957;margin:10px 0 0;line-height:1.5}',
 
181
 
182
  go.addEventListener('click', function(){
183
  go.disabled = true;
184
+ out.innerHTML = '<span class="szlv-load">calling <code>'+esc(base+VERIFY_PATH)+'</code>\u2026</span>';
185
  var p, u = url.value.trim(), body = ta.value.trim();
186
  if(u){
187
+ p = pull(u, {method:'GET'}).then(function(remote){
188
+ if(!remote.ok || !remote.data) return remote;
189
+ var env = remote.data.envelope || remote.data.dsse || remote.data;
190
+ return pull(base+VERIFY_PATH, {method:'POST', headers:{'Content-Type':'application/json'},
191
+ body: JSON.stringify({envelope:env})});
192
+ });
193
  } else if(body){
194
  var parsed = null;
195
  try{ parsed = JSON.parse(body); }catch(e){
196
  out.innerHTML = '<div class="szlv-state muted">input is not valid JSON — paste a receipt object or use a URL.</div>';
197
  go.disabled = false; return;
198
  }
199
+ var requestBody = parsed.envelope ? parsed : {envelope:parsed};
200
+ p = pull(base+VERIFY_PATH, {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify(requestBody)});
201
  } else {
202
  out.innerHTML = '<div class="szlv-state muted">paste a receipt JSON, or enter a public receipt URL.</div>';
203
  go.disabled = false; return;
 
208
  return { reload:function(){}, base:base };
209
  }
210
 
211
+ var api = { mount: mount, pull: pull, _sample: SAMPLE, version: '1.1.0' };
212
  if (typeof module!=='undefined' && module.exports) module.exports = api;
213
  global.SZLVerify = api;
214
  })(typeof window!=='undefined' ? window : this);
qa_yarqa.js CHANGED
@@ -102,7 +102,10 @@ async function runViewport(browser, url, vp){
102
  await new Promise(rr=>server.listen(0,rr));
103
  const port = server.address().port;
104
  const url = `http://localhost:${port}/index.html`;
105
- const browser = await chromium.launch({ args:['--use-gl=angle','--use-angle=swiftshader','--ignore-gpu-blocklist','--enable-unsafe-swiftshader'] });
 
 
 
106
 
107
  let totalErrors = 0;
108
  for(const vp of VIEWPORTS){
 
102
  await new Promise(rr=>server.listen(0,rr));
103
  const port = server.address().port;
104
  const url = `http://localhost:${port}/index.html`;
105
+ const browser = await chromium.launch({
106
+ executablePath: process.env.PLAYWRIGHT_EXECUTABLE_PATH || undefined,
107
+ args:['--use-gl=angle','--use-angle=swiftshader','--ignore-gpu-blocklist','--enable-unsafe-swiftshader']
108
+ });
109
 
110
  let totalErrors = 0;
111
  for(const vp of VIEWPORTS){
server.py CHANGED
@@ -1,54 +1,235 @@
1
  #!/usr/bin/env python3
2
- """Hardened static file server for the SZL Living Anatomy Space.
3
-
4
- Serves exactly the same files as the previous inline `http.server` (same /app
5
- directory, same port 7860) but adds security response headers on every response,
6
- while PRESERVING the Cross-Origin-Opener-Policy / Cross-Origin-Resource-Policy
7
- this Space already emitted (do not regress the embed posture).
8
-
9
- Additive / non-breaking:
10
- - Cross-Origin-Opener-Policy same-origin-allow-popups (PRESERVED, unchanged)
11
- - Cross-Origin-Resource-Policy cross-origin (PRESERVED, unchanged)
12
- - Content-Security-Policy (the exact origin allow-list the page already
13
- enforces via its own <meta http-equiv> CSP, now
14
- also as an HTTP header, plus frame-ancestors)
15
- - Strict-Transport-Security max-age=31536000; includeSubDomains
16
- - X-Content-Type-Options nosniff
17
- - Referrer-Policy strict-origin-when-cross-origin
18
- - Server clean "szl" banner (suppresses SimpleHTTP/Python
19
- version disclosure)
20
-
21
- The CSP mirrors the page's own vetted meta CSP: it keeps 'unsafe-inline' for
22
- script/style (the 3D atlas ships heavy inline JS + inline styles + a WebGL
23
- canvas), allows data:/blob: images, and an explicit connect-src allow-list for
24
- the live read-only fetches to a11oy / killinchu / amaru / sentra HF spaces, so
25
- the anatomy scene and live HUD keep working.
26
-
27
- Health contract:
28
- - GET /healthz -> 200 application/json health payload matching the fleet
29
- monitor contract (up{job="szl-flagship"} scrape target).
30
- Additive; all other paths fall through to static serving
31
- unchanged.
32
  """
 
 
 
33
  import functools
 
34
  import json
 
 
 
 
 
 
 
35
  from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- PORT = 7860
38
- DIRECTORY = "/app"
39
-
40
- # Doctrine v11 — LOCKED: 749 / 14 / 163 · locked_at c7c0ba17.
41
- HEALTHZ_PAYLOAD = {
42
- "status": "ok",
43
- "organ": "anatomy",
44
- "service": "anatomy-space",
45
- "doctrine": "v11",
46
- "lock": "749/14/163",
47
- "commit": "c7c0ba17",
48
- "role": "visualization", # embeddable 3D scene, not a governance console
49
- "note": "static bundle; live HUD fetches a11oy/killinchu read-only",
 
 
 
 
 
 
50
  }
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  CONTENT_SECURITY_POLICY = (
53
  "default-src 'self'; "
54
  "base-uri 'self'; "
@@ -62,50 +243,443 @@ CONTENT_SECURITY_POLICY = (
62
  "https://szlholdings-sentra.hf.space; "
63
  "form-action 'self'; "
64
  "frame-ancestors 'self' https://huggingface.co https://*.hf.space https://*.huggingface.co "
65
- # a11oy's own domains may embed the anatomy (the landing's living-body iframe).
66
  "https://a-11-oy.com https://*.a-11-oy.com https://a11oy.net https://*.a11oy.net"
67
  )
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  class HardenedHandler(SimpleHTTPRequestHandler):
71
  server_version = "szl"
72
  sys_version = ""
73
 
74
- def version_string(self):
75
  return "szl"
76
 
77
- def do_GET(self):
78
- # Additive health route for the fleet monitor. Everything else falls
79
- # through to normal static file serving, unchanged.
80
- if self.path.split("?", 1)[0] == "/healthz":
81
- body = json.dumps(HEALTHZ_PAYLOAD).encode("utf-8")
82
- self.send_response(200)
83
- self.send_header("Content-Type", "application/json")
84
- self.send_header("Content-Length", str(len(body)))
85
- self.send_header("Cache-Control", "no-store")
86
- self.end_headers()
87
- self.wfile.write(body)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  return
89
  super().do_GET()
90
 
91
- def end_headers(self):
92
- # PRESERVE the COOP/CORP this Space already sent (unchanged embed posture).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  self.send_header("Cross-Origin-Opener-Policy", "same-origin-allow-popups")
94
  self.send_header("Cross-Origin-Resource-Policy", "cross-origin")
95
- # ADD the previously-missing security headers.
96
  self.send_header("Content-Security-Policy", CONTENT_SECURITY_POLICY)
97
- self.send_header(
98
- "Strict-Transport-Security", "max-age=31536000; includeSubDomains"
99
- )
100
  self.send_header("X-Content-Type-Options", "nosniff")
101
  self.send_header("Referrer-Policy", "strict-origin-when-cross-origin")
 
102
  super().end_headers()
103
 
104
 
 
 
 
 
 
105
  if __name__ == "__main__":
106
- handler = functools.partial(HardenedHandler, directory=DIRECTORY)
107
- httpd = ThreadingHTTPServer(("0.0.0.0", PORT), handler)
108
- print(f"Serving hardened static site from {DIRECTORY} on 0.0.0.0:{PORT}", flush=True)
109
  try:
110
  httpd.serve_forever()
111
  except KeyboardInterrupt:
 
1
  #!/usr/bin/env python3
2
+ """SZL Living Anatomy server and evidence contract.
3
+
4
+ The visual bundle remains static and read-only. This thin server adds an honest
5
+ machine-readable boundary around it:
6
+
7
+ * ``/healthz`` reports transport health only.
8
+ * ``/.well-known/szl-source.json`` identifies the GitHub source and live HF
9
+ revision without pretending that the two revisions are identical.
10
+ * ``/api/anatomy/v1/manifest`` describes the contract and status vocabulary.
11
+ * ``/api/anatomy/v1/capabilities`` exposes Purpose / Try / Evidence / Limits /
12
+ Reproduce for each major surface.
13
+ * ``/api/anatomy/v1/evidence`` separately probes the live dependencies.
14
+ * ``/api/anatomy/v1/receipt`` hashes the files that make up the bundle.
15
+ * ``POST /api/anatomy/v1/verify/receipt`` recomputes that local integrity
16
+ receipt. The result is deliberately ``STRUCTURAL-ONLY`` because this Space
17
+ has no signing key; it never upgrades an unsigned receipt to cryptographically
18
+ VERIFIED.
19
+
20
+ No endpoint mutates state, signs data, runs a model, or claims that reachability
21
+ proves model quality. Lambda remains Conjecture 1 and the Space does not execute
22
+ Lean; formal claims are presented as a declared, linked snapshot.
 
 
 
 
 
 
 
 
 
23
  """
24
+
25
+ from __future__ import annotations
26
+
27
  import functools
28
+ import hashlib
29
  import json
30
+ import os
31
+ import threading
32
+ import time
33
+ import urllib.error
34
+ import urllib.request
35
+ from concurrent.futures import ThreadPoolExecutor
36
+ from datetime import datetime, timezone
37
  from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
38
+ from pathlib import Path
39
+ from urllib.parse import parse_qs, urlsplit
40
+
41
+
42
+ PORT = int(os.environ.get("PORT", "7860"))
43
+ # Resolve from this file, not from a generic /app existence check. The Docker
44
+ # image places server.py in /app already; local verification must never
45
+ # accidentally serve an unrelated host-level /app directory.
46
+ DIRECTORY = Path(os.environ.get("ANATOMY_ROOT", str(Path(__file__).resolve().parent))).resolve()
47
+ SPACE_ID = "SZLHOLDINGS/anatomy"
48
+ SOURCE_REPOSITORY = "szl-holdings/anatomy"
49
+ SOURCE_BASE_COMMIT = "9847b3031c1aacdcee9aa8e37ae33d573737a5c4"
50
+ DOCTRINE = "v11"
51
+ LOCK = "749/14/163"
52
+ KERNEL_COMMIT = "c7c0ba17"
53
+ LOCKED_FORMULAS = ["F1", "F4", "F7", "F11", "F12", "F18", "F19", "F22"]
54
 
55
+ ARTIFACT_PATHS = (
56
+ "index.html",
57
+ "favicon.svg",
58
+ "app.js",
59
+ "data.js",
60
+ "v5_organs.js",
61
+ "frontier_anatomy.js",
62
+ "live-body.html",
63
+ "live-body.js",
64
+ "lib/szl_verify_widget.js",
65
+ "server.py",
66
+ )
67
+
68
+ FORMULA_LINKS = {
69
+ "locked_spine": "https://github.com/szl-holdings/lutar-lean/tree/main/Lutar/Puriq/Formulas",
70
+ "proved_formulas": "https://github.com/szl-holdings/lutar-lean/blob/main/Lutar/Puriq/Formulas/ProvedFormulas.lean",
71
+ "puriq_formula": "https://github.com/szl-holdings/lutar-lean/blob/main/Lutar/Puriq/Formulas/PuriqFormulaLean.lean",
72
+ "quorum_safety": "https://github.com/szl-holdings/lutar-lean/blob/main/Lutar/Wave23/QuorumSafety.lean",
73
+ "hash_chain": "https://github.com/szl-holdings/lutar-lean/blob/main/Lutar/Wave8/HashChain.lean",
74
  }
75
 
76
+ CAPABILITIES = [
77
+ {
78
+ "id": "anatomy.atlas",
79
+ "name": "Living governed-system atlas",
80
+ "purpose": "Make system ownership, authority boundaries, and receipt flow spatially inspectable.",
81
+ "try": {"method": "GET", "path": "/", "action": "Open an organ or run the guided tour."},
82
+ "evidence": {
83
+ "state": "COMPUTED",
84
+ "basis": "The self-contained WebGL bundle and its local data model are hashed into the anatomy integrity receipt.",
85
+ },
86
+ "limits": [
87
+ "A visual map is not proof that every depicted remote service is healthy.",
88
+ "The atlas is read-only and has no actuation authority.",
89
+ ],
90
+ "reproduce": {
91
+ "steps": [
92
+ "GET /api/anatomy/v1/receipt",
93
+ "POST its JSON body to /api/anatomy/v1/verify/receipt",
94
+ "Compare the artifact_set_sha256 and per-file hashes.",
95
+ ]
96
+ },
97
+ "authority_state": "READ_ONLY",
98
+ "formula_refs": [],
99
+ "provenance": ["https://github.com/szl-holdings/anatomy"],
100
+ },
101
+ {
102
+ "id": "anatomy.formula-spine",
103
+ "name": "Formula-to-organ spine",
104
+ "purpose": "Trace declared formal and experimental formulas to the organs they inform.",
105
+ "try": {"method": "UI", "path": "/", "action": "Open Formula Atlas or Proofs to organs."},
106
+ "evidence": {
107
+ "state": "SNAPSHOT",
108
+ "basis": "The Space presents source-linked declarations; it does not run the Lean kernel in this container.",
109
+ "locked_declared": LOCKED_FORMULAS,
110
+ "kernel_reference": KERNEL_COMMIT,
111
+ },
112
+ "limits": [
113
+ "Exactly eight formulas are declared locked in this snapshot.",
114
+ "Lambda is Conjecture 1, not a theorem.",
115
+ "Current source links and the historical kernel reference are shown separately to avoid false revision equivalence.",
116
+ ],
117
+ "reproduce": {
118
+ "steps": [
119
+ "Open the linked Lean files.",
120
+ "Pin the intended toolchain and commit in lutar-lean.",
121
+ "Run lake build and inspect #print axioms before promoting a claim.",
122
+ ]
123
+ },
124
+ "authority_state": "READ_ONLY",
125
+ "formula_refs": LOCKED_FORMULAS,
126
+ "provenance": list(FORMULA_LINKS.values()),
127
+ },
128
+ {
129
+ "id": "anatomy.live-lens",
130
+ "name": "Live organ posture lens",
131
+ "purpose": "Project current reachability and contract responses from A11OY, Killinchu, and the verifier estate into the body.",
132
+ "try": {"method": "GET", "path": "/api/anatomy/v1/evidence?refresh=1", "action": "Refresh measured dependencies."},
133
+ "evidence": {
134
+ "state": "MIXED",
135
+ "basis": "Dependency states are measured at request time and kept separate from the static anatomy snapshot.",
136
+ },
137
+ "limits": [
138
+ "HTTP reachability does not certify correctness, freshness, safety, or business performance.",
139
+ "A dependency can change after observed_at.",
140
+ ],
141
+ "reproduce": {"steps": ["GET /api/anatomy/v1/evidence?refresh=1", "Probe each declared URL independently."]},
142
+ "authority_state": "READ_ONLY",
143
+ "formula_refs": ["F1", "F7", "F22"],
144
+ "provenance": [
145
+ "https://huggingface.co/spaces/SZLHOLDINGS/a11oy",
146
+ "https://huggingface.co/spaces/SZLHOLDINGS/killinchu",
147
+ "https://huggingface.co/spaces/SZLHOLDINGS/governed-receipt-verifier",
148
+ ],
149
+ },
150
+ {
151
+ "id": "anatomy.integrity-receipt",
152
+ "name": "Local bundle integrity receipt",
153
+ "purpose": "Turn the deployed anatomy bundle into a replayable, byte-level evidence object.",
154
+ "try": {"method": "GET", "path": "/api/anatomy/v1/receipt", "action": "Generate the current deterministic receipt."},
155
+ "evidence": {
156
+ "state": "COMPUTED",
157
+ "verification_state": "STRUCTURAL_ONLY",
158
+ "basis": "SHA-256 is recomputed over every declared artifact and over the canonical receipt body.",
159
+ },
160
+ "limits": [
161
+ "The local receipt is unsigned because the Space has no private signing key.",
162
+ "STRUCTURAL-ONLY is not a cryptographic identity attestation.",
163
+ ],
164
+ "reproduce": {
165
+ "steps": [
166
+ "GET /api/anatomy/v1/receipt",
167
+ "POST the response to /api/anatomy/v1/verify/receipt",
168
+ "Expect STRUCTURAL-ONLY unless an artifact or digest was changed, in which case expect FAIL.",
169
+ ]
170
+ },
171
+ "authority_state": "READ_ONLY",
172
+ "formula_refs": ["F1", "F22"],
173
+ "provenance": [FORMULA_LINKS["hash_chain"]],
174
+ },
175
+ {
176
+ "id": "anatomy.physics-overlays",
177
+ "name": "Physics and quantum-bio overlays",
178
+ "purpose": "Expose bounded exploratory models beside operational and formal layers without confusing them with measurements or locked theorems.",
179
+ "try": {"method": "UI", "path": "/", "action": "Open Physics, Quantum-bio, or Yarqa layers."},
180
+ "evidence": {
181
+ "state": "MODELED",
182
+ "basis": "The overlays run deterministic local equations and simulations from data.js; they do not ingest calibrated laboratory measurements.",
183
+ },
184
+ "limits": [
185
+ "Modeled is not measured.",
186
+ "Narrative and proposed claims remain labeled separately from verified formulas.",
187
+ "No clinical, biological, or quantum-computing performance claim is made.",
188
+ ],
189
+ "reproduce": {
190
+ "steps": [
191
+ "Inspect the formula card and its evidence label.",
192
+ "Record the input parameters.",
193
+ "Re-run the same local overlay and compare its integrity digest.",
194
+ ]
195
+ },
196
+ "authority_state": "READ_ONLY",
197
+ "formula_refs": ["QB-COH", "QB-PMF", "QB-COMPASS", "QB-Lambda-v5", "AG-LANDAUER"],
198
+ "provenance": ["https://github.com/szl-holdings/anatomy/blob/main/data.js"],
199
+ },
200
+ ]
201
+
202
+ DEPENDENCIES = (
203
+ {
204
+ "id": "a11oy.honesty",
205
+ "url": "https://szlholdings-a11oy.hf.space/api/a11oy/v1/honest",
206
+ "method": "GET",
207
+ "purpose": "Doctrine and runtime honesty posture",
208
+ "critical": True,
209
+ },
210
+ {
211
+ "id": "a11oy.public-verifier",
212
+ "url": "https://szlholdings-a11oy.hf.space/api/a11oy/v1/verify/receipt",
213
+ "method": "POST",
214
+ "purpose": "Canonical public DSSE/Khipu receipt-verifier contract",
215
+ "critical": True,
216
+ },
217
+ {
218
+ "id": "killinchu.experience-manifest",
219
+ "url": "https://szlholdings-killinchu.hf.space/api/killinchu/v1/experience/manifest",
220
+ "method": "GET",
221
+ "purpose": "Killinchu surface and evidence inventory",
222
+ "critical": False,
223
+ },
224
+ {
225
+ "id": "receipt-verifier.space",
226
+ "url": "https://szlholdings-governed-receipt-verifier.static.hf.space/",
227
+ "method": "GET",
228
+ "purpose": "Standalone browser verifier",
229
+ "critical": False,
230
+ },
231
+ )
232
+
233
  CONTENT_SECURITY_POLICY = (
234
  "default-src 'self'; "
235
  "base-uri 'self'; "
 
243
  "https://szlholdings-sentra.hf.space; "
244
  "form-action 'self'; "
245
  "frame-ancestors 'self' https://huggingface.co https://*.hf.space https://*.huggingface.co "
 
246
  "https://a-11-oy.com https://*.a-11-oy.com https://a11oy.net https://*.a11oy.net"
247
  )
248
 
249
+ _probe_lock = threading.Lock()
250
+ _probe_cache: dict[str, object] = {"at": 0.0, "value": None}
251
+ _revision_lock = threading.Lock()
252
+ _revision_cache: dict[str, object] = {"at": 0.0, "value": None}
253
+
254
+
255
+ def _utc_now() -> str:
256
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
257
+
258
+
259
+ def _canonical(value: object) -> bytes:
260
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
261
+
262
+
263
+ def _sha256(data: bytes) -> str:
264
+ return hashlib.sha256(data).hexdigest()
265
+
266
+
267
+ def _artifact_manifest() -> dict[str, object]:
268
+ artifacts: list[dict[str, object]] = []
269
+ for rel in ARTIFACT_PATHS:
270
+ path = DIRECTORY / rel
271
+ if path.is_file():
272
+ content = path.read_bytes()
273
+ artifacts.append({"path": rel, "bytes": len(content), "sha256": _sha256(content)})
274
+ else:
275
+ artifacts.append({"path": rel, "state": "MISSING"})
276
+ artifact_set_sha256 = _sha256(_canonical(artifacts))
277
+ return {
278
+ "algorithm": "sha256",
279
+ "artifact_count": len(artifacts),
280
+ "artifact_set_sha256": artifact_set_sha256,
281
+ "artifacts": artifacts,
282
+ }
283
+
284
+
285
+ def _local_receipt() -> dict[str, object]:
286
+ manifest = _artifact_manifest()
287
+ body: dict[str, object] = {
288
+ "schema": "szl.anatomy-integrity-receipt/v1",
289
+ "subject": {
290
+ "space": SPACE_ID,
291
+ "artifact_set_sha256": manifest["artifact_set_sha256"],
292
+ },
293
+ "claim": {
294
+ "purpose": "Byte-level integrity of the deployed Living Anatomy bundle",
295
+ "authority_state": "READ_ONLY",
296
+ "evidence_state": "COMPUTED",
297
+ "doctrine": DOCTRINE,
298
+ "kernel_reference": KERNEL_COMMIT,
299
+ "locked_proven_declared": len(LOCKED_FORMULAS),
300
+ "lambda_state": "CONJECTURE_1",
301
+ },
302
+ "evidence": manifest,
303
+ "signature": {
304
+ "state": "UNAVAILABLE",
305
+ "reason": "No private signing key is present in this public visualization Space.",
306
+ },
307
+ "limits": [
308
+ "Artifact integrity does not certify remote-service health or model quality.",
309
+ "Unsigned local receipt; verification is STRUCTURAL-ONLY.",
310
+ ],
311
+ }
312
+ return {
313
+ "receipt": body,
314
+ "receipt_id": _sha256(_canonical(body)),
315
+ "verification_state": "STRUCTURAL_ONLY",
316
+ }
317
+
318
+
319
+ def _check_local_receipt(candidate: object) -> tuple[int, dict[str, object]]:
320
+ wrapper = candidate if isinstance(candidate, dict) else {}
321
+ receipt = wrapper.get("receipt", wrapper) if isinstance(wrapper, dict) else {}
322
+ supplied_id = wrapper.get("receipt_id") if isinstance(wrapper, dict) else None
323
+ if not isinstance(receipt, dict):
324
+ receipt = {}
325
+
326
+ current = _artifact_manifest()
327
+ recomputed_id = _sha256(_canonical(receipt))
328
+ subject = receipt.get("subject") if isinstance(receipt.get("subject"), dict) else {}
329
+ evidence = receipt.get("evidence") if isinstance(receipt.get("evidence"), dict) else {}
330
+ checks = [
331
+ {
332
+ "name": "schema",
333
+ "status": "PASS" if receipt.get("schema") == "szl.anatomy-integrity-receipt/v1" else "FAIL",
334
+ "detail": "Expected szl.anatomy-integrity-receipt/v1.",
335
+ },
336
+ {
337
+ "name": "subject",
338
+ "status": "PASS" if subject.get("space") == SPACE_ID else "FAIL",
339
+ "detail": f"Expected {SPACE_ID}.",
340
+ },
341
+ {
342
+ "name": "receipt_digest",
343
+ "status": "PASS" if supplied_id and supplied_id == recomputed_id else "FAIL",
344
+ "detail": "SHA-256 over the canonical receipt body.",
345
+ },
346
+ {
347
+ "name": "artifact_set",
348
+ "status": "PASS"
349
+ if evidence.get("artifact_set_sha256") == current["artifact_set_sha256"]
350
+ and subject.get("artifact_set_sha256") == current["artifact_set_sha256"]
351
+ else "FAIL",
352
+ "detail": "Recomputed from the files currently served by this Space.",
353
+ },
354
+ {
355
+ "name": "signature",
356
+ "status": "UNAVAILABLE",
357
+ "detail": "This local integrity receipt is unsigned; no cryptographic identity green is asserted.",
358
+ },
359
+ ]
360
+ failed = any(item["status"] == "FAIL" for item in checks)
361
+ verdict = "FAIL" if failed else "STRUCTURAL-ONLY"
362
+ return (400 if failed else 200), {
363
+ "schema": "szl.receipt-verification/v1",
364
+ "ok": not failed,
365
+ "verdict": verdict,
366
+ "verification_state": "FAILED" if failed else "STRUCTURAL_ONLY",
367
+ "checks": checks,
368
+ "recomputed_receipt_id": recomputed_id,
369
+ "observed_at": _utc_now(),
370
+ "limits": "STRUCTURAL-ONLY is advisory and is not a signature verification.",
371
+ }
372
+
373
+
374
+ def _probe_dependency(dep: dict[str, object]) -> dict[str, object]:
375
+ method = str(dep["method"])
376
+ data = b"{}" if method == "POST" else None
377
+ headers = {
378
+ "User-Agent": "szl-anatomy-evidence/1.0",
379
+ "Accept": "application/json,text/html;q=0.8",
380
+ }
381
+ if data is not None:
382
+ headers["Content-Type"] = "application/json"
383
+ req = urllib.request.Request(str(dep["url"]), data=data, headers=headers, method=method)
384
+ status: int | None = None
385
+ error: str | None = None
386
+ try:
387
+ with urllib.request.urlopen(req, timeout=4) as response:
388
+ status = response.status
389
+ response.read(256)
390
+ except urllib.error.HTTPError as exc:
391
+ status = exc.code
392
+ error = f"HTTP {exc.code}"
393
+ except Exception as exc: # network state is evidence, not a server failure
394
+ error = type(exc).__name__
395
+
396
+ reachable = status is not None
397
+ if method == "POST":
398
+ contract_available = status in (200, 201, 400, 422, 429)
399
+ else:
400
+ contract_available = status is not None and 200 <= status < 400
401
+ if contract_available:
402
+ contract_state = "AVAILABLE"
403
+ evidence_state = "LIVE"
404
+ elif status == 404:
405
+ contract_state = "MISSING"
406
+ evidence_state = "UNAVAILABLE"
407
+ elif reachable:
408
+ contract_state = "DEGRADED"
409
+ evidence_state = "UNAVAILABLE"
410
+ else:
411
+ contract_state = "UNREACHABLE"
412
+ evidence_state = "UNAVAILABLE"
413
+ return {
414
+ **dep,
415
+ "transport_state": "REACHABLE" if reachable else "UNREACHABLE",
416
+ "contract_state": contract_state,
417
+ "evidence_state": evidence_state,
418
+ "http_status": status,
419
+ "error": error,
420
+ }
421
+
422
+
423
+ def _dependency_evidence(force: bool = False) -> dict[str, object]:
424
+ now = time.monotonic()
425
+ with _probe_lock:
426
+ cached = _probe_cache.get("value")
427
+ if not force and cached is not None and now - float(_probe_cache["at"]) < 30:
428
+ return cached # type: ignore[return-value]
429
+ with ThreadPoolExecutor(max_workers=len(DEPENDENCIES)) as pool:
430
+ rows = list(pool.map(_probe_dependency, DEPENDENCIES))
431
+ live_count = sum(row["evidence_state"] == "LIVE" for row in rows)
432
+ evidence_state = "LIVE" if live_count == len(rows) else ("MIXED" if live_count else "UNAVAILABLE")
433
+ verifier = next(row for row in rows if row["id"] == "a11oy.public-verifier")
434
+ value: dict[str, object] = {
435
+ "schema": "szl.anatomy-evidence/v1",
436
+ "observed_at": _utc_now(),
437
+ "scope": "Endpoint reachability and declared contract presence only.",
438
+ "transport_state": "REACHABLE",
439
+ "evidence_state": evidence_state,
440
+ "verification_state": "AVAILABLE" if verifier["contract_state"] == "AVAILABLE" else "UNAVAILABLE",
441
+ "authority_state": "READ_ONLY",
442
+ "summary": {"live": live_count, "total": len(rows)},
443
+ "dependencies": rows,
444
+ "limits": [
445
+ "Reachability does not certify quality, safety, freshness, or business performance.",
446
+ "The local anatomy integrity verifier remains STRUCTURAL_ONLY because it is unsigned.",
447
+ ],
448
+ }
449
+ with _probe_lock:
450
+ _probe_cache.update({"at": time.monotonic(), "value": value})
451
+ return value
452
+
453
+
454
+ def _hf_revision(force: bool = False) -> str | None:
455
+ env_revision = os.environ.get("SPACE_REPOSITORY_COMMIT")
456
+ if env_revision and len(env_revision) == 40:
457
+ return env_revision
458
+ now = time.monotonic()
459
+ with _revision_lock:
460
+ cached = _revision_cache.get("value")
461
+ if not force and cached and now - float(_revision_cache["at"]) < 60:
462
+ return str(cached)
463
+ req = urllib.request.Request(
464
+ "https://huggingface.co/api/spaces/SZLHOLDINGS/anatomy?expand[]=sha",
465
+ headers={"User-Agent": "szl-anatomy-source-attestation/1.0", "Accept": "application/json"},
466
+ )
467
+ revision: str | None = None
468
+ try:
469
+ with urllib.request.urlopen(req, timeout=4) as response:
470
+ data = json.load(response)
471
+ candidate = data.get("sha")
472
+ if isinstance(candidate, str) and len(candidate) == 40:
473
+ revision = candidate
474
+ except Exception:
475
+ revision = None
476
+ with _revision_lock:
477
+ _revision_cache.update({"at": time.monotonic(), "value": revision})
478
+ return revision
479
+
480
+
481
+ def _source_attestation(force: bool = False) -> dict[str, object]:
482
+ revision = _hf_revision(force=force)
483
+ manifest = _artifact_manifest()
484
+ return {
485
+ "schema": "szl.deployment-source/v1",
486
+ "source": {
487
+ "repository": SOURCE_REPOSITORY,
488
+ "commit": SOURCE_BASE_COMMIT,
489
+ "path": "",
490
+ "relation": "base-plus-hf-overlay",
491
+ },
492
+ "deployment": {
493
+ "hf_space": SPACE_ID,
494
+ "hf_revision": revision,
495
+ "artifact_set_sha256": manifest["artifact_set_sha256"],
496
+ },
497
+ "built_at": None,
498
+ "observed_at": _utc_now(),
499
+ "alignment_state": "PENDING_GITHUB_SYNC",
500
+ "limits": [
501
+ "source.commit is the declared GitHub base; deployment.hf_revision is the measured HF revision.",
502
+ "They are intentionally not presented as the same revision.",
503
+ ],
504
+ }
505
+
506
+
507
+ def _manifest() -> dict[str, object]:
508
+ return {
509
+ "schema": "szl.anatomy-manifest/v1",
510
+ "service": "anatomy-space",
511
+ "space": SPACE_ID,
512
+ "purpose": "Read-only spatial evidence map of the governed-agent substrate.",
513
+ "contract_version": "1.0.0",
514
+ "state_dimensions": {
515
+ "transport_state": "REACHABLE",
516
+ "evidence_state": "MIXED",
517
+ "verification_state": "STRUCTURAL_ONLY",
518
+ "authority_state": "READ_ONLY",
519
+ },
520
+ "status_vocabulary": {
521
+ "transport_state": ["REACHABLE", "UNREACHABLE"],
522
+ "evidence_state": ["LIVE", "COMPUTED", "SNAPSHOT", "MODELED", "MIXED", "UNAVAILABLE"],
523
+ "verification_state": ["VERIFIED", "STRUCTURAL_ONLY", "UNAVAILABLE", "FAILED"],
524
+ "authority_state": ["READ_ONLY", "PROPOSAL_ONLY", "MUTATING"],
525
+ },
526
+ "endpoints": {
527
+ "manifest": "/api/anatomy/v1/manifest",
528
+ "capabilities": "/api/anatomy/v1/capabilities",
529
+ "evidence": "/api/anatomy/v1/evidence?refresh=1",
530
+ "receipt": "/api/anatomy/v1/receipt",
531
+ "verify_receipt": "/api/anatomy/v1/verify/receipt",
532
+ "source": "/.well-known/szl-source.json",
533
+ },
534
+ "doctrine": {
535
+ "version": DOCTRINE,
536
+ "lock": LOCK,
537
+ "kernel_reference": KERNEL_COMMIT,
538
+ "locked_proven_declared": LOCKED_FORMULAS,
539
+ "lambda": "CONJECTURE_1",
540
+ },
541
+ "limits": [
542
+ "RUNNING or REACHABLE describes transport, not model quality.",
543
+ "This Space is a visualization and evidence reader, not an autonomous actuator.",
544
+ ],
545
+ }
546
+
547
 
548
  class HardenedHandler(SimpleHTTPRequestHandler):
549
  server_version = "szl"
550
  sys_version = ""
551
 
552
+ def version_string(self) -> str:
553
  return "szl"
554
 
555
+ def _send_json(
556
+ self,
557
+ payload: object,
558
+ *,
559
+ status: int = 200,
560
+ evidence_state: str = "SNAPSHOT",
561
+ extra_headers: dict[str, str] | None = None,
562
+ ) -> None:
563
+ body = json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")
564
+ self.send_response(status)
565
+ self.send_header("Content-Type", "application/json; charset=utf-8")
566
+ self.send_header("Content-Length", str(len(body)))
567
+ self.send_header("Cache-Control", "no-store")
568
+ self.send_header("Access-Control-Allow-Origin", "*")
569
+ self.send_header("X-SZL-Transport-State", "REACHABLE")
570
+ self.send_header("X-SZL-Evidence-State", evidence_state)
571
+ if extra_headers:
572
+ for key, value in extra_headers.items():
573
+ self.send_header(key, value)
574
+ self.end_headers()
575
+ self.wfile.write(body)
576
+
577
+ def do_OPTIONS(self) -> None: # noqa: N802
578
+ self.send_response(204)
579
+ self.send_header("Access-Control-Allow-Origin", "*")
580
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
581
+ self.send_header("Access-Control-Allow-Headers", "Content-Type")
582
+ self.send_header("Access-Control-Max-Age", "600")
583
+ self.end_headers()
584
+
585
+ def do_GET(self) -> None: # noqa: N802
586
+ parsed = urlsplit(self.path)
587
+ path = parsed.path
588
+ query = parse_qs(parsed.query)
589
+ force = query.get("refresh") == ["1"]
590
+ if path == "/healthz":
591
+ self._send_json(
592
+ {
593
+ "status": "ok",
594
+ "organ": "anatomy",
595
+ "service": "anatomy-space",
596
+ "transport_state": "REACHABLE",
597
+ "evidence_state": "SNAPSHOT",
598
+ "verification_state": "STRUCTURAL_ONLY",
599
+ "authority_state": "READ_ONLY",
600
+ "note": "Transport health only; quality and upstream freshness are not inferred.",
601
+ },
602
+ evidence_state="SNAPSHOT",
603
+ )
604
+ return
605
+ if path == "/.well-known/szl-source.json":
606
+ self._send_json(_source_attestation(force=force), evidence_state="COMPUTED")
607
+ return
608
+ if path == "/api/anatomy/v1/manifest":
609
+ self._send_json(_manifest(), evidence_state="SNAPSHOT")
610
+ return
611
+ if path in ("/api/anatomy/v1/capabilities", "/api/anatomy/v1/capability-matrix"):
612
+ self._send_json(
613
+ {
614
+ "schema": "szl.anatomy-capabilities/v1",
615
+ "state_dimensions": _manifest()["state_dimensions"],
616
+ "count": len(CAPABILITIES),
617
+ "capabilities": CAPABILITIES,
618
+ },
619
+ evidence_state="MIXED",
620
+ )
621
+ return
622
+ if path == "/api/anatomy/v1/evidence":
623
+ payload = _dependency_evidence(force=force)
624
+ self._send_json(payload, evidence_state=str(payload["evidence_state"]))
625
+ return
626
+ if path == "/api/anatomy/v1/receipt":
627
+ self._send_json(
628
+ _local_receipt(),
629
+ evidence_state="COMPUTED",
630
+ extra_headers={"X-SZL-Verification-State": "STRUCTURAL_ONLY"},
631
+ )
632
  return
633
  super().do_GET()
634
 
635
+ def do_POST(self) -> None: # noqa: N802
636
+ path = urlsplit(self.path).path
637
+ if path != "/api/anatomy/v1/verify/receipt":
638
+ self._send_json({"error": "not_found", "path": path}, status=404, evidence_state="UNAVAILABLE")
639
+ return
640
+ try:
641
+ length = int(self.headers.get("Content-Length", "0"))
642
+ except ValueError:
643
+ length = 0
644
+ if length <= 0 or length > 1_000_000:
645
+ self._send_json(
646
+ {"error": "invalid_body", "detail": "JSON body required; maximum 1,000,000 bytes."},
647
+ status=400,
648
+ evidence_state="UNAVAILABLE",
649
+ )
650
+ return
651
+ try:
652
+ candidate = json.loads(self.rfile.read(length))
653
+ except Exception:
654
+ self._send_json({"error": "invalid_json"}, status=400, evidence_state="UNAVAILABLE")
655
+ return
656
+ status, payload = _check_local_receipt(candidate)
657
+ self._send_json(
658
+ payload,
659
+ status=status,
660
+ evidence_state="COMPUTED",
661
+ extra_headers={"X-SZL-Verification-State": str(payload["verification_state"])},
662
+ )
663
+
664
+ def end_headers(self) -> None:
665
  self.send_header("Cross-Origin-Opener-Policy", "same-origin-allow-popups")
666
  self.send_header("Cross-Origin-Resource-Policy", "cross-origin")
 
667
  self.send_header("Content-Security-Policy", CONTENT_SECURITY_POLICY)
668
+ self.send_header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
 
 
669
  self.send_header("X-Content-Type-Options", "nosniff")
670
  self.send_header("Referrer-Policy", "strict-origin-when-cross-origin")
671
+ self.send_header("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=()")
672
  super().end_headers()
673
 
674
 
675
+ def make_server(host: str = "0.0.0.0", port: int = PORT) -> ThreadingHTTPServer:
676
+ handler = functools.partial(HardenedHandler, directory=str(DIRECTORY))
677
+ return ThreadingHTTPServer((host, port), handler)
678
+
679
+
680
  if __name__ == "__main__":
681
+ httpd = make_server()
682
+ print(f"Serving SZL Living Anatomy from {DIRECTORY} on 0.0.0.0:{PORT}", flush=True)
 
683
  try:
684
  httpd.serve_forever()
685
  except KeyboardInterrupt:
tests/qa_evidence_bay.js ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // End-to-end UI contract for the Anatomy Evidence Bay.
2
+ // Requires the real Python server to be running; does not mock evidence APIs.
3
+ const { chromium } = require('playwright');
4
+ const path = require('path');
5
+
6
+ const BASE = process.env.ANATOMY_BASE_URL || 'http://127.0.0.1:7860';
7
+ const EDGE = process.env.PLAYWRIGHT_EXECUTABLE_PATH || undefined;
8
+ const OUT = process.env.ANATOMY_QA_OUTPUT || __dirname;
9
+ const VIEWPORTS = [
10
+ { name:'desktop', width:1440, height:900 },
11
+ { name:'mobile', width:390, height:844 },
12
+ ];
13
+
14
+ async function run(browser, vp) {
15
+ const page = await browser.newPage({viewport:{width:vp.width,height:vp.height}});
16
+ const errors = [];
17
+ page.on('console', msg => { if (msg.type()==='error') errors.push(msg.text()); });
18
+ page.on('pageerror', err => errors.push('PAGEERROR: '+err.message));
19
+ await page.goto(BASE+'/', {waitUntil:'networkidle'});
20
+ await page.waitForSelector('#fa-launch');
21
+ await page.click('#fa-launch');
22
+ await page.waitForSelector('#fa-panel.open');
23
+
24
+ const overview = await page.evaluate(() => ({
25
+ title: document.querySelector('.fa-title')?.textContent,
26
+ dimensions: [...document.querySelectorAll('.fa-dim-value')].map(x=>x.textContent),
27
+ launcher: getComputedStyle(document.getElementById('fa-launch')).display,
28
+ panelWidth: document.getElementById('fa-panel').getBoundingClientRect().width,
29
+ viewport: window.innerWidth,
30
+ }));
31
+
32
+ await page.click('[data-tab="capabilities"]');
33
+ const capabilityCount = await page.locator('.fa-cap').count();
34
+ // textContent covers the complete declarative shell even when the browser
35
+ // collapses detail descendants during layout/animation.
36
+ const shellText = await page.locator('.fa-cap').first().textContent();
37
+
38
+ await page.click('[data-tab="evidence"]');
39
+ await page.waitForSelector('.fa-dep');
40
+ const dependencyCount = await page.locator('.fa-dep').count();
41
+ const dependencyStates = await page.locator('.fa-dep-state').allInnerTexts();
42
+
43
+ await page.click('[data-tab="overview"]');
44
+ await page.click('#fa-verify-bundle');
45
+ await page.waitForSelector('.fa-output.good');
46
+ const verification = await page.locator('.fa-output').innerText();
47
+
48
+ await page.screenshot({path:path.join(OUT,'anatomy-evidence-'+vp.name+'.png'),fullPage:true});
49
+ await page.close();
50
+
51
+ if (errors.length) throw new Error(vp.name+' console errors: '+errors.join(' | '));
52
+ if (overview.title !== 'Evidence Bay') throw new Error(vp.name+' missing Evidence Bay title');
53
+ if (overview.panelWidth > overview.viewport + 1) throw new Error(vp.name+' panel overflows viewport');
54
+ if (capabilityCount < 5) throw new Error(vp.name+' capability count '+capabilityCount);
55
+ for (const field of ['Purpose','Try','Evidence','Limits','Reproduce']) {
56
+ if (!shellText.includes(field)) throw new Error(vp.name+' missing '+field+' shell');
57
+ }
58
+ if (dependencyCount !== 4) throw new Error(vp.name+' dependency count '+dependencyCount);
59
+ if (!verification.includes('STRUCTURAL-ONLY')) throw new Error(vp.name+' receipt verdict '+verification);
60
+ return {viewport:vp.name, overview, capabilityCount, dependencyCount, dependencyStates, verification};
61
+ }
62
+
63
+ (async()=>{
64
+ const browser = await chromium.launch({executablePath:EDGE,headless:true,args:['--use-gl=angle','--use-angle=swiftshader','--ignore-gpu-blocklist','--enable-unsafe-swiftshader']});
65
+ const results=[];
66
+ for (const vp of VIEWPORTS) results.push(await run(browser,vp));
67
+ await browser.close();
68
+ console.log(JSON.stringify(results,null,2));
69
+ })().catch(err=>{ console.error(err); process.exit(1); });
tests/test_server_contract.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import json
5
+ import os
6
+ import sys
7
+ import threading
8
+ import unittest
9
+ import urllib.error
10
+ import urllib.request
11
+ from pathlib import Path
12
+
13
+
14
+ ROOT = Path(__file__).resolve().parents[1]
15
+ sys.path.insert(0, str(ROOT))
16
+ import server # noqa: E402
17
+
18
+
19
+ class AnatomyContractTest(unittest.TestCase):
20
+ @classmethod
21
+ def setUpClass(cls) -> None:
22
+ cls.httpd = server.make_server("127.0.0.1", 0)
23
+ cls.port = cls.httpd.server_address[1]
24
+ cls.base = f"http://127.0.0.1:{cls.port}"
25
+ cls.thread = threading.Thread(target=cls.httpd.serve_forever, daemon=True)
26
+ cls.thread.start()
27
+
28
+ @classmethod
29
+ def tearDownClass(cls) -> None:
30
+ cls.httpd.shutdown()
31
+ cls.httpd.server_close()
32
+ cls.thread.join(timeout=3)
33
+
34
+ def request(self, path: str, *, method: str = "GET", body=None):
35
+ data = None
36
+ headers = {}
37
+ if body is not None:
38
+ data = json.dumps(body).encode("utf-8")
39
+ headers["Content-Type"] = "application/json"
40
+ req = urllib.request.Request(self.base + path, data=data, headers=headers, method=method)
41
+ try:
42
+ with urllib.request.urlopen(req, timeout=5) as response:
43
+ return response.status, dict(response.headers), json.load(response)
44
+ except urllib.error.HTTPError as exc:
45
+ return exc.code, dict(exc.headers), json.load(exc)
46
+
47
+ def test_health_is_transport_only(self):
48
+ status, headers, body = self.request("/healthz")
49
+ self.assertEqual(200, status)
50
+ self.assertEqual("REACHABLE", body["transport_state"])
51
+ self.assertEqual("SNAPSHOT", body["evidence_state"])
52
+ self.assertEqual("STRUCTURAL_ONLY", body["verification_state"])
53
+ self.assertEqual("READ_ONLY", body["authority_state"])
54
+ self.assertIn("quality", body["note"])
55
+ self.assertEqual("REACHABLE", headers["X-SZL-Transport-State"])
56
+ self.assertEqual("nosniff", headers["X-Content-Type-Options"])
57
+
58
+ def test_static_bundle_is_served_from_the_anatomy_root(self):
59
+ for path, marker in (("/", "SZL Living Anatomy"), ("/frontier_anatomy.js", "Evidence Bay")):
60
+ with urllib.request.urlopen(self.base + path, timeout=5) as response:
61
+ body = response.read().decode("utf-8")
62
+ self.assertEqual(200, response.status)
63
+ self.assertIn(marker, body)
64
+
65
+ def test_manifest_separates_state_dimensions(self):
66
+ status, headers, body = self.request("/api/anatomy/v1/manifest")
67
+ self.assertEqual(200, status)
68
+ self.assertEqual("szl.anatomy-manifest/v1", body["schema"])
69
+ self.assertEqual(
70
+ {"transport_state", "evidence_state", "verification_state", "authority_state"},
71
+ set(body["state_dimensions"]),
72
+ )
73
+ self.assertEqual("CONJECTURE_1", body["doctrine"]["lambda"])
74
+ self.assertEqual(8, len(body["doctrine"]["locked_proven_declared"]))
75
+ self.assertEqual("*", headers["Access-Control-Allow-Origin"])
76
+
77
+ def test_every_capability_has_five_part_shell(self):
78
+ status, _, body = self.request("/api/anatomy/v1/capabilities")
79
+ self.assertEqual(200, status)
80
+ self.assertGreaterEqual(body["count"], 5)
81
+ for capability in body["capabilities"]:
82
+ for key in ("purpose", "try", "evidence", "limits", "reproduce"):
83
+ self.assertIn(key, capability, f"{capability['id']} lacks {key}")
84
+ self.assertEqual("READ_ONLY", capability["authority_state"])
85
+ formula = next(item for item in body["capabilities"] if item["id"] == "anatomy.formula-spine")
86
+ self.assertEqual("SNAPSHOT", formula["evidence"]["state"])
87
+ self.assertTrue(all(url.startswith("https://github.com/") for url in formula["provenance"]))
88
+
89
+ def test_receipt_replays_as_structural_only(self):
90
+ status, receipt_headers, receipt = self.request("/api/anatomy/v1/receipt")
91
+ self.assertEqual(200, status)
92
+ self.assertEqual("STRUCTURAL_ONLY", receipt["verification_state"])
93
+ self.assertEqual(64, len(receipt["receipt_id"]))
94
+ self.assertEqual("STRUCTURAL_ONLY", receipt_headers["X-SZL-Verification-State"])
95
+
96
+ verify_status, verify_headers, verified = self.request(
97
+ "/api/anatomy/v1/verify/receipt", method="POST", body=receipt
98
+ )
99
+ self.assertEqual(200, verify_status)
100
+ self.assertEqual("STRUCTURAL-ONLY", verified["verdict"])
101
+ self.assertEqual("STRUCTURAL_ONLY", verify_headers["X-SZL-Verification-State"])
102
+ checks = {item["name"]: item["status"] for item in verified["checks"]}
103
+ self.assertEqual("PASS", checks["artifact_set"])
104
+ self.assertEqual("UNAVAILABLE", checks["signature"])
105
+
106
+ def test_tampered_receipt_fails(self):
107
+ _, _, receipt = self.request("/api/anatomy/v1/receipt")
108
+ tampered = copy.deepcopy(receipt)
109
+ tampered["receipt"]["claim"]["purpose"] = "changed"
110
+ status, _, result = self.request(
111
+ "/api/anatomy/v1/verify/receipt", method="POST", body=tampered
112
+ )
113
+ self.assertEqual(400, status)
114
+ self.assertEqual("FAIL", result["verdict"])
115
+ checks = {item["name"]: item["status"] for item in result["checks"]}
116
+ self.assertEqual("FAIL", checks["receipt_digest"])
117
+
118
+ def test_source_attestation_matches_estate_schema(self):
119
+ previous = os.environ.get("SPACE_REPOSITORY_COMMIT")
120
+ os.environ["SPACE_REPOSITORY_COMMIT"] = "a" * 40
121
+ try:
122
+ status, _, body = self.request("/.well-known/szl-source.json")
123
+ finally:
124
+ if previous is None:
125
+ os.environ.pop("SPACE_REPOSITORY_COMMIT", None)
126
+ else:
127
+ os.environ["SPACE_REPOSITORY_COMMIT"] = previous
128
+ self.assertEqual(200, status)
129
+ self.assertEqual("szl.deployment-source/v1", body["schema"])
130
+ self.assertEqual("szl-holdings/anatomy", body["source"]["repository"])
131
+ self.assertEqual("SZLHOLDINGS/anatomy", body["deployment"]["hf_space"])
132
+ self.assertEqual("a" * 40, body["deployment"]["hf_revision"])
133
+ self.assertEqual("PENDING_GITHUB_SYNC", body["alignment_state"])
134
+
135
+ def test_frontend_and_public_verifier_use_current_contract(self):
136
+ index = (ROOT / "index.html").read_text(encoding="utf-8")
137
+ bay = (ROOT / "frontier_anatomy.js").read_text(encoding="utf-8")
138
+ widget = (ROOT / "lib" / "szl_verify_widget.js").read_text(encoding="utf-8")
139
+ self.assertIn('src="./frontier_anatomy.js"', index)
140
+ self.assertIn("Evidence Bay", bay)
141
+ self.assertIn("/api/anatomy/v1", bay)
142
+ self.assertIn("/api/a11oy/v1/verify/receipt", widget)
143
+ self.assertNotIn("base+'/api/a11oy/v1/verify'", widget)
144
+
145
+
146
+ if __name__ == "__main__":
147
+ unittest.main(verbosity=2)