betterwithage commited on
Commit
a988ddf
·
verified ·
1 Parent(s): 7cd30d4

Move anatomy to public creator profile (6e7f19a7b759)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.dockerignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ .git
2
+ .github
3
+ __pycache__
4
+ *.py[cod]
5
+ tests
.github/CODEOWNERS ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Solo-builder ownership
2
+ * @stephenlutar2-hash
.github/dependabot.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 2
2
+ updates:
3
+ # GitHub Actions dependencies
4
+ - package-ecosystem: "github-actions"
5
+ directory: "/"
6
+ schedule:
7
+ interval: "weekly"
8
+ day: "monday"
9
+ time: "08:00"
10
+ timezone: "America/New_York"
11
+ labels:
12
+ - "dependencies"
13
+ - "security"
14
+ open-pull-requests-limit: 5
15
+ groups:
16
+ # Group low-risk patch/minor bumps; major bumps arrive as separate PRs.
17
+ actions:
18
+ patterns:
19
+ - "*"
20
+ update-types:
21
+ - "minor"
22
+ - "patch"
.github/workflows/codeql.yml ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CodeQL
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ pull_request:
6
+ branches: [main]
7
+ schedule:
8
+ - cron: '23 4 * * 1' # Weekly Monday 04:23 UTC
9
+ permissions:
10
+ contents: read
11
+ jobs:
12
+ analyze:
13
+ uses: szl-holdings/.github/.github/workflows/reusable-codeql.yml@0c06506cba0f9d87f8bf25e37ebc1b53b3121523
14
+ permissions:
15
+ actions: read
16
+ contents: read
17
+ security-events: write
18
+ with:
19
+ languages: '["javascript-typescript"]'
.github/workflows/container-contract.yml ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Container contract
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ jobs:
13
+ container-contract:
14
+ name: Build and exercise source-bound Living Anatomy image
15
+ runs-on: ubuntu-latest
16
+ steps:
17
+ - name: Check out source
18
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
19
+ with:
20
+ persist-credentials: false
21
+
22
+ - name: Set up Python
23
+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
24
+ with:
25
+ python-version: "3.12"
26
+
27
+ - name: Materialize exact public Second Brain projection
28
+ env:
29
+ GITHUB_TOKEN: ${{ github.token }}
30
+ run: python scripts/materialize_second_brain.py --output .runtime/second-brain
31
+
32
+ - name: Run server and Second Brain contract tests
33
+ run: python -m unittest discover -s tests -v
34
+
35
+ - name: Build pinned Space image
36
+ run: docker build --tag anatomy-space-ci .
37
+
38
+ - name: Start Space image
39
+ run: docker run --detach --name anatomy-space-ci --publish 7860:7860 anatomy-space-ci
40
+
41
+ - name: Verify combined live container contract
42
+ run: |
43
+ set -euo pipefail
44
+ for attempt in $(seq 1 30); do
45
+ if curl --fail --silent --show-error \
46
+ http://127.0.0.1:7860/api/anatomy/v1/living-health \
47
+ > living-health.json; then
48
+ curl --fail --silent --show-error \
49
+ "http://127.0.0.1:7860/api/anatomy/v1/brain/search?q=governed%20receipts&k=3" \
50
+ > brain-search.json
51
+ python - <<'PY'
52
+ import json
53
+
54
+ living = json.load(open("living-health.json", encoding="utf-8"))
55
+ search = json.load(open("brain-search.json", encoding="utf-8"))
56
+ assert living["ready"] is True
57
+ assert living["transport_state"] == "REACHABLE"
58
+ assert living["organs"]["brain"]["ready"] is True
59
+ assert living["organs"]["brain"]["chunk_count"] == 575
60
+ assert search["ready"] is True
61
+ assert search["handles"]
62
+ assert all("text" not in handle for handle in search["handles"])
63
+ assert all(len(handle["sha256"]) == 64 for handle in search["handles"])
64
+ PY
65
+ test "$(curl --silent --output /dev/null --write-out '%{http_code}' \
66
+ http://127.0.0.1:7860/this-route-must-not-exist)" = "404"
67
+ exit 0
68
+ fi
69
+ sleep 1
70
+ done
71
+ docker logs anatomy-space-ci
72
+ exit 1
73
+
74
+ - name: Stop Space image
75
+ if: always()
76
+ run: docker rm --force anatomy-space-ci || true
.github/workflows/hf-sync.yml ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 SZL Holdings — SPDX-License-Identifier: Apache-2.0
2
+ name: Sync Living Anatomy to Hugging Face
3
+
4
+ # GitHub is authoritative. This workflow materializes the exact public
5
+ # szl-second-brain revision, validates it, mirrors the runtime whitelist to
6
+ # betterwithage/anatomy, makes the Space public, restarts it when needed, and
7
+ # verifies the source-bound live contracts. It never exports the private graph.
8
+
9
+ on:
10
+ push:
11
+ branches: [main]
12
+ schedule:
13
+ - cron: "17 */6 * * *"
14
+ workflow_dispatch: {}
15
+
16
+ permissions:
17
+ contents: read
18
+
19
+ concurrency:
20
+ group: anatomy-hf-sync
21
+ cancel-in-progress: false
22
+
23
+ jobs:
24
+ sync:
25
+ runs-on: ubuntu-latest
26
+ timeout-minutes: 20
27
+ steps:
28
+ - name: Checkout exact protected-main source
29
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
30
+ with:
31
+ ref: ${{ github.sha }}
32
+ persist-credentials: false
33
+
34
+ - name: Set up Python
35
+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
36
+ with:
37
+ python-version: "3.12"
38
+
39
+ - name: Install pinned Hugging Face client
40
+ run: python -m pip install --disable-pip-version-check --no-cache-dir "huggingface_hub==1.23.0"
41
+
42
+ - name: Materialize and validate exact Second Brain projection
43
+ env:
44
+ GITHUB_TOKEN: ${{ github.token }}
45
+ run: python scripts/materialize_second_brain.py --output .runtime/second-brain
46
+
47
+ - name: Reconcile, mirror, and verify Living Anatomy
48
+ env:
49
+ GITHUB_TOKEN: ${{ github.token }}
50
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
51
+ SPACE_ID: betterwithage/anatomy
52
+ run: |
53
+ set -euo pipefail
54
+ if [ -z "${HF_TOKEN:-}" ]; then
55
+ echo "::error::HF_TOKEN is not set; cannot reconcile betterwithage/anatomy."
56
+ exit 1
57
+ fi
58
+ python3 <<'PYEOF'
59
+ import glob
60
+ import json
61
+ import os
62
+ import time
63
+ import urllib.request
64
+ from pathlib import Path
65
+
66
+ from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
67
+
68
+ api = HfApi(token=os.environ["HF_TOKEN"])
69
+ space = os.environ["SPACE_ID"]
70
+ source_revision = os.environ.get("GITHUB_SHA", "").lower()
71
+ source_ref = os.environ.get("GITHUB_REF")
72
+ workflow_run_id = os.environ.get("GITHUB_RUN_ID", "")
73
+ github_repo = os.environ.get("GITHUB_REPOSITORY")
74
+ github_token = os.environ.get("GITHUB_TOKEN", "")
75
+
76
+ if len(source_revision) != 40 or any(
77
+ character not in "0123456789abcdef" for character in source_revision
78
+ ):
79
+ raise RuntimeError("GITHUB_SHA is not an exact Git revision")
80
+ if source_ref != "refs/heads/main":
81
+ raise RuntimeError(
82
+ f"refusing production deploy from non-main ref: {source_ref!r}"
83
+ )
84
+ if github_repo != "szl-holdings/anatomy":
85
+ raise RuntimeError(f"unexpected GitHub repository: {github_repo!r}")
86
+ if not workflow_run_id.isdigit():
87
+ raise RuntimeError("GITHUB_RUN_ID is not numeric")
88
+ if not github_token:
89
+ raise RuntimeError("GITHUB_TOKEN is unavailable")
90
+
91
+ request = urllib.request.Request(
92
+ os.environ.get("GITHUB_API_URL", "https://api.github.com").rstrip("/")
93
+ + f"/repos/{github_repo}/commits/main",
94
+ headers={
95
+ "Accept": "application/vnd.github+json",
96
+ "Authorization": f"Bearer {github_token}",
97
+ "X-GitHub-Api-Version": "2022-11-28",
98
+ "User-Agent": "szl-anatomy-hf-sync/2.0",
99
+ },
100
+ )
101
+ with urllib.request.urlopen(request, timeout=20) as response:
102
+ current_main = str(json.load(response).get("sha") or "").lower()
103
+ if current_main != source_revision:
104
+ raise RuntimeError(
105
+ "refusing stale production deploy at mutation boundary: "
106
+ f"current_main={current_main!r} source_revision={source_revision!r}"
107
+ )
108
+
109
+ brain_source_path = Path(".runtime/second-brain/source.json")
110
+ brain_source = json.loads(brain_source_path.read_text(encoding="utf-8"))
111
+ brain_revision = str(brain_source.get("source_revision") or "").lower()
112
+ if len(brain_revision) != 40:
113
+ raise RuntimeError("Second Brain snapshot lacks an exact source revision")
114
+ if int(brain_source.get("public_chunk_count") or 0) != 575:
115
+ raise RuntimeError(
116
+ "Second Brain snapshot does not contain exactly 575 public chunks"
117
+ )
118
+ if brain_source.get("private_graph_nodes_materialized") != 0:
119
+ raise RuntimeError("private Second Brain nodes entered the public snapshot")
120
+
121
+ info = api.space_info(space)
122
+ if bool(getattr(info, "private", False)):
123
+ print("Promoting Space to public:", space)
124
+ api.update_repo_settings(
125
+ repo_id=space,
126
+ repo_type="space",
127
+ private=False,
128
+ )
129
+ info = api.space_info(space)
130
+ if bool(getattr(info, "private", False)):
131
+ raise RuntimeError("Space remained private after public reconciliation")
132
+
133
+ def stage_name(runtime):
134
+ value = getattr(runtime, "stage", None)
135
+ return str(getattr(value, "value", value) or "UNKNOWN").upper()
136
+
137
+ initial_stage = stage_name(api.get_space_runtime(space))
138
+ if initial_stage in {
139
+ "PAUSED",
140
+ "SLEEPING",
141
+ "STOPPED",
142
+ "RUNTIME_ERROR",
143
+ "BUILD_ERROR",
144
+ "CONFIG_ERROR",
145
+ }:
146
+ print("Restarting Space from stage:", initial_stage)
147
+ api.restart_space(
148
+ repo_id=space,
149
+ factory_reboot=initial_stage
150
+ in {"RUNTIME_ERROR", "BUILD_ERROR", "CONFIG_ERROR"},
151
+ )
152
+
153
+ def remote_json(path):
154
+ try:
155
+ local = hf_hub_download(
156
+ repo_id=space,
157
+ repo_type="space",
158
+ filename=path,
159
+ token=os.environ["HF_TOKEN"],
160
+ force_download=True,
161
+ )
162
+ return json.loads(Path(local).read_text(encoding="utf-8"))
163
+ except Exception as error:
164
+ print("Remote metadata unavailable:", path, type(error).__name__)
165
+ return {}
166
+
167
+ existing_deploy = remote_json("hf-deploy-manifest.json")
168
+ existing_brain = remote_json(".runtime/second-brain/source.json")
169
+ source_changed = existing_deploy.get("source_revision") != source_revision
170
+ brain_changed = (
171
+ existing_brain.get("source_revision") != brain_revision
172
+ or existing_brain.get("corpus_sha256")
173
+ != brain_source.get("corpus_sha256")
174
+ )
175
+ needs_commit = source_changed or brain_changed
176
+
177
+ target_sha = str(getattr(info, "sha", "") or "")
178
+ expected_workflow_run_id = str(
179
+ existing_deploy.get("workflow_run_id") or ""
180
+ )
181
+
182
+ if needs_commit:
183
+ patterns = [
184
+ "README.md",
185
+ "Dockerfile",
186
+ ".dockerignore",
187
+ "server.py",
188
+ "organ_integrity.py",
189
+ "living_runtime.py",
190
+ "second_brain_runtime.py",
191
+ "scripts/materialize_second_brain.py",
192
+ ".runtime/**/*",
193
+ "*.html",
194
+ "*.js",
195
+ "*.css",
196
+ "lib/**/*",
197
+ ]
198
+ files = []
199
+ for pattern in patterns:
200
+ files.extend(
201
+ path
202
+ for path in glob.glob(pattern, recursive=True)
203
+ if os.path.isfile(path)
204
+ )
205
+ files = sorted(set(files))
206
+ required = {
207
+ "living_runtime.py",
208
+ "second_brain_runtime.py",
209
+ ".runtime/second-brain/manifest.json",
210
+ ".runtime/second-brain/brain-corpus.public.jsonl",
211
+ ".runtime/second-brain/source.json",
212
+ }
213
+ missing = sorted(required - set(files))
214
+ if missing:
215
+ raise RuntimeError(
216
+ f"required Living Anatomy runtime artifacts missing: {missing}"
217
+ )
218
+
219
+ deploy_manifest = {
220
+ "schema": "szl.hf-deploy-manifest/v1",
221
+ "source_repository": "szl-holdings/anatomy",
222
+ "source_revision": source_revision,
223
+ "source_path": "",
224
+ "destination": {
225
+ "repo_id": space,
226
+ "repo_type": "space",
227
+ "mode": "runtime-whitelist",
228
+ "visibility": "public",
229
+ "lifecycle": "KEEP_PUBLIC_RUNNING",
230
+ },
231
+ "dependencies": {
232
+ "second_brain": {
233
+ "source_repository": brain_source["source_repository"],
234
+ "source_revision": brain_revision,
235
+ "public_chunk_count": brain_source["public_chunk_count"],
236
+ "corpus_sha256": brain_source["corpus_sha256"],
237
+ "authority_state": "READ_ONLY",
238
+ "content_access": "HANDLES_ONLY",
239
+ }
240
+ },
241
+ "workflow_run_id": workflow_run_id,
242
+ }
243
+ operations = []
244
+ for path in files:
245
+ operations.append(
246
+ CommitOperationAdd(path_in_repo=path, path_or_fileobj=path)
247
+ )
248
+ operations.append(
249
+ CommitOperationAdd(
250
+ path_in_repo="hf-deploy-manifest.json",
251
+ path_or_fileobj=(
252
+ json.dumps(deploy_manifest, sort_keys=True, indent=2) + "\n"
253
+ ).encode("utf-8"),
254
+ )
255
+ )
256
+ print(
257
+ "Syncing",
258
+ len(operations),
259
+ "source-bound artifacts to",
260
+ space,
261
+ "anatomy=",
262
+ source_revision,
263
+ "brain=",
264
+ brain_revision,
265
+ )
266
+ commit = api.create_commit(
267
+ repo_id=space,
268
+ repo_type="space",
269
+ operations=operations,
270
+ commit_message=f"hf-sync: source {source_revision} run {workflow_run_id}",
271
+ )
272
+ target_sha = str(commit.oid)
273
+ expected_workflow_run_id = workflow_run_id
274
+ else:
275
+ print(
276
+ "Source and Second Brain revisions already deployed; "
277
+ "performing lifecycle and live-contract reconciliation only."
278
+ )
279
+ if not expected_workflow_run_id.isdigit():
280
+ raise RuntimeError(
281
+ "deployed manifest lacks a numeric workflow run identity"
282
+ )
283
+ workflow_run_id = expected_workflow_run_id
284
+ info = api.space_info(space)
285
+ target_sha = str(getattr(info, "sha", "") or "")
286
+
287
+ if len(target_sha) != 40:
288
+ raise RuntimeError(f"target Hugging Face revision is invalid: {target_sha!r}")
289
+
290
+ deadline = time.monotonic() + 600
291
+ restarted = False
292
+ while time.monotonic() < deadline:
293
+ info = api.space_info(space)
294
+ runtime = api.get_space_runtime(space)
295
+ stage = stage_name(runtime)
296
+ current_sha = str(getattr(info, "sha", "") or "")
297
+ print("Observed Space:", current_sha, stage, "private=", info.private)
298
+ if bool(getattr(info, "private", False)):
299
+ api.update_repo_settings(
300
+ repo_id=space,
301
+ repo_type="space",
302
+ private=False,
303
+ )
304
+ if (
305
+ info.sha == target_sha
306
+ and stage
307
+ in {
308
+ "PAUSED",
309
+ "SLEEPING",
310
+ "STOPPED",
311
+ "RUNTIME_ERROR",
312
+ "BUILD_ERROR",
313
+ "CONFIG_ERROR",
314
+ }
315
+ and not restarted
316
+ ):
317
+ api.restart_space(
318
+ repo_id=space,
319
+ factory_reboot=stage
320
+ in {"RUNTIME_ERROR", "BUILD_ERROR", "CONFIG_ERROR"},
321
+ )
322
+ restarted = True
323
+ if info.sha == target_sha and stage == "RUNNING" and not info.private:
324
+ break
325
+ time.sleep(10)
326
+ else:
327
+ raise TimeoutError(
328
+ f"Space did not settle RUNNING/public at {target_sha} within 600 seconds"
329
+ )
330
+
331
+ base = "https://betterwithage-anatomy.hf.space"
332
+ for attempt in range(18):
333
+ try:
334
+ def get_json(url, timeout=15):
335
+ with urllib.request.urlopen(url, timeout=timeout) as response:
336
+ return json.load(response)
337
+
338
+ health = get_json(base + "/healthz")
339
+ living = get_json(
340
+ base + "/api/anatomy/v1/living-health?refresh=1"
341
+ )
342
+ brain = get_json(base + "/api/anatomy/v1/brain/health?refresh=1")
343
+ search = get_json(
344
+ base
345
+ + "/api/anatomy/v1/brain/search"
346
+ + "?q=governed%20receipts%20living%20anatomy&k=3"
347
+ )
348
+ version = get_json(base + "/version?refresh=1")
349
+ evidence = get_json(base + "/evidence?refresh=1", timeout=20)
350
+ source = get_json(
351
+ base + "/.well-known/szl-source.json?refresh=1"
352
+ )
353
+ manifest = get_json(base + "/api/anatomy/v1/manifest")
354
+
355
+ assert health["transport_state"] == "REACHABLE"
356
+ assert health["verification_state"] == "STRUCTURAL_ONLY"
357
+ assert living["ready"] is True
358
+ assert living["organs"]["brain"]["chunk_count"] == 575
359
+ assert brain["ready"] is True
360
+ assert brain["state"] == "SOURCE_BOUND_PUBLIC_PROJECTION"
361
+ assert brain["source_revision"] == brain_revision
362
+ assert brain["chunk_count"] == 575
363
+ assert brain["private_graph_nodes_loaded"] == 0
364
+ assert brain["content_access"] == "HANDLES_ONLY"
365
+ assert search["ready"] is True
366
+ assert search["handles"]
367
+ assert all("text" not in handle for handle in search["handles"])
368
+ assert version["gitSha"] == source_revision
369
+ assert version["deploymentRevision"] == target_sha
370
+ assert version["secondBrainSourceRevision"] == brain_revision
371
+ assert version["evidenceState"] == "MEASURED"
372
+ assert evidence["gitSha"] == source_revision
373
+ assert evidence["evidenceState"] == "PARTIAL"
374
+ assert evidence["source"]["deployment"]["hf_revision"] == target_sha
375
+ assert evidence["receipts"][0]["status"] == "STRUCTURAL_ONLY"
376
+ assert evidence["outputProvenance"]["authenticityEstablished"] is False
377
+ assert evidence["dependencies"]["secondBrain"]["ready"] is True
378
+ assert source["deployment"]["hf_revision"] == target_sha
379
+ assert source["source"]["commit"] == source_revision
380
+ assert source["alignment_state"] == "SOURCE_BOUND_DEPLOYMENT"
381
+ assert source["deployment"]["workflow_run_id"] == workflow_run_id
382
+ assert (
383
+ manifest["endpoints"]["brain_health"]
384
+ == "/api/anatomy/v1/brain/health"
385
+ )
386
+ final_info = api.space_info(space)
387
+ assert final_info.private is False
388
+ print(
389
+ "Verified Living Anatomy public/RUNNING:",
390
+ target_sha,
391
+ "Second Brain:",
392
+ brain_revision,
393
+ )
394
+ break
395
+ except Exception as error:
396
+ if attempt == 17:
397
+ raise RuntimeError(
398
+ "Public Living Anatomy + Second Brain verification failed"
399
+ ) from error
400
+ print("Live verification retry:", type(error).__name__, error)
401
+ time.sleep(10)
402
+ PYEOF
.github/workflows/overclaim-guard.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Doctrine Overclaim Guard
2
+
3
+ # Grep-based honesty gate. The rule lives in ONE place — the org-shared
4
+ # reusable workflow in szl-holdings/.github — so every repo that publishes
5
+ # Λ-uniqueness / Conjecture-1 claims inherits the same check automatically.
6
+ # Fails CI if a governed surface claims Λ uniqueness without the Theorem U /
7
+ # U₁ / U₂ qualifier, or describes Conjecture 1 as proven/closed (it stays OPEN).
8
+ on:
9
+ workflow_dispatch: {}
10
+ pull_request:
11
+ types: [opened, synchronize, reopened, ready_for_review]
12
+ push:
13
+ branches: [main]
14
+
15
+ permissions:
16
+ contents: read
17
+
18
+ jobs:
19
+ overclaim:
20
+ uses: szl-holdings/.github/.github/workflows/reusable-overclaim-guard.yml@464069d945b10e51893fc749f5530b7643f23ad4
.github/workflows/pin-check.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Pin Check
2
+
3
+ # Thin caller — delegates to the org-wide reusable SHA-pin check so this repo's
4
+ # workflow files are validated identically to every other repo. The reusable is
5
+ # pinned by commit SHA (the rule it enforces). See szl-holdings/.github
6
+ # replit-sync/FORGE_UPGRADE_pincheck-orgwide.md.
7
+
8
+ on:
9
+ push:
10
+ branches: [main]
11
+ paths: ['.github/workflows/**']
12
+ pull_request:
13
+ paths: ['.github/workflows/**']
14
+
15
+ permissions:
16
+ contents: read
17
+
18
+ jobs:
19
+ pin-check:
20
+ uses: szl-holdings/.github/.github/workflows/pin-check-reusable.yml@1bbd857634a87d3a824be86ec7a79aaa8e4937e8
.github/workflows/sbom.yml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2026 SZL Holdings — SPDX-License-Identifier: Apache-2.0
2
+ name: SBOM
3
+
4
+ # Org reusable SBOM (CycloneDX + SPDX) gate (SHA-pinned caller). Wave G CI parity.
5
+ on:
6
+ push:
7
+ branches: [main]
8
+ release:
9
+ types: [published]
10
+ workflow_dispatch:
11
+
12
+ # reusable-sbom.yml runs a trivy-fs child job that uploads SARIF, which needs
13
+ # security-events: write. A reusable job cannot exceed the caller's grant, so
14
+ # without this the workflow is rejected at startup (startup_failure). actions:
15
+ # read is required for the SARIF/code-scanning upload action.
16
+ permissions:
17
+ contents: read
18
+
19
+ jobs:
20
+ sbom:
21
+ permissions:
22
+ contents: write
23
+ security-events: write
24
+ uses: szl-holdings/.github/.github/workflows/reusable-sbom.yml@ebd2128c691b850c84438b671fbb512945933776
25
+ secrets: inherit
.github/workflows/scorecard.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Scorecard
2
+ on:
3
+ push:
4
+ branches: [main]
5
+ schedule:
6
+ - cron: '30 1 * * 6' # Weekly Saturday 01:30 UTC
7
+ # reusable-scorecard.yml requests security-events: write, id-token: write and
8
+ # actions: read; a reusable job cannot exceed the caller's grant, so the caller
9
+ # must grant at least these or the run is rejected at startup (startup_failure).
10
+ permissions:
11
+ contents: read
12
+ jobs:
13
+ scorecard:
14
+ permissions:
15
+ actions: read
16
+ contents: read
17
+ security-events: write
18
+ id-token: write
19
+ uses: szl-holdings/.github/.github/workflows/reusable-scorecard.yml@0c06506cba0f9d87f8bf25e37ebc1b53b3121523
20
+ secrets: inherit
.github/workflows/trivy.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Trivy
2
+ on:
3
+ pull_request:
4
+ branches: [main]
5
+ push:
6
+ branches: [main]
7
+ schedule:
8
+ - cron: '0 6 * * 1' # Weekly Monday 06:00 UTC
9
+ # reusable-trivy.yml uploads a SARIF report to code-scanning, which needs
10
+ # security-events: write. A reusable job cannot exceed the caller's grant, so
11
+ # without this the run is rejected at startup (startup_failure).
12
+ permissions:
13
+ contents: read
14
+ jobs:
15
+ trivy:
16
+ permissions:
17
+ contents: read
18
+ security-events: write
19
+ uses: szl-holdings/.github/.github/workflows/reusable-trivy.yml@0c06506cba0f9d87f8bf25e37ebc1b53b3121523
20
+ secrets: inherit
.gitignore ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SZL Living Anatomy — static SDK Space (no build step). Keep the tree clean:
2
+ # the only things that should ever land here are the vendored bundle + sources.
3
+
4
+ # local QA harness (qa_yarqa.js runs under Playwright/Chromium, installed locally)
5
+ node_modules/
6
+ package-lock.json
7
+ qa_*_results.json
8
+ qa_*.png
9
+
10
+ # python tooling cruft (if a contributor runs scans/linters locally)
11
+ __pycache__/
12
+ *.pyc
13
+ .pytest_cache/
14
+
15
+ # environment / secrets — never commit
16
+ .env
17
+ .env.*
18
+
19
+ # editor / OS noise
20
+ .DS_Store
21
+ *.swp
22
+ .idea/
23
+ .vscode/
.runtime/second-brain/brain-corpus.public.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
.runtime/second-brain/manifest.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "datasetName": "SZL Second Brain — in-repo lane (public projection)",
3
+ "doctrine": "Public projection of the IN-REPO lane of the SZL Second Brain. It is DATA, not a model — a retrieval corpus, never weights. Built deterministically from repo-public text (curated docs, the 269-entry formula corpus, DECLARED ingest takeaways, and the DECLARED Ouroboros invariant codex — definitions only, never live check status). The owner-infrastructure ops doc (OWNER-SETUP.md) is EXCLUDED from this public projection, though it remains in the app-served corpus. A BM25 / similarity score over these chunks ranks lexical overlap; it is NEVER correctness. This is wholly separate from the owner's private Brain, which is never published. Nothing here trains a model, evaluates one, serves inference, or upgrades Λ (Conjecture-1).",
4
+ "supersetChunkCount": 581,
5
+ "supersetCorpusSha256": "04e037b7ccf3bb0f4e54d2cbcda59a833277277f99f7726224e8f9a009603a7d",
6
+ "publicChunkCount": 575,
7
+ "bySource": {
8
+ "doc": 152,
9
+ "formula": 269,
10
+ "ingest": 143,
11
+ "invariant": 11
12
+ },
13
+ "excludedSourceIds": [
14
+ "OWNER-SETUP.md"
15
+ ],
16
+ "excludedChunkCount": 6,
17
+ "projectionSha256": "d02487523b451b390125bc3c0a20e259c44b5715528fac69cf789ca56755ea10",
18
+ "secretScan": "PASS",
19
+ "secretScanPatternCount": 7
20
+ }
.runtime/second-brain/source.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "authority_state": "READ_ONLY",
3
+ "by_source": {
4
+ "doc": 152,
5
+ "formula": 269,
6
+ "ingest": 143,
7
+ "invariant": 11
8
+ },
9
+ "canonical_dataset": "SZLHOLDINGS/szl-second-brain-inrepo",
10
+ "content_access": "HANDLES_ONLY",
11
+ "corpus_path": "data/brain-corpus.public.jsonl",
12
+ "corpus_sha256": "387337acbd8fe443637102fe7ea75387fa4c3d9d746d8ab6e2d14d6c138aad8f",
13
+ "lambda_state": "CONJECTURE_1",
14
+ "manifest_path": "data/manifest.json",
15
+ "manifest_projection_sha256": "d02487523b451b390125bc3c0a20e259c44b5715528fac69cf789ca56755ea10",
16
+ "manifest_sha256": "7a2816331df3c7356b5cb01605ea108fa98bb4503d401d3b2952e6b65145d02e",
17
+ "materialized_at": "2026-09-04T00:12:24Z",
18
+ "private_graph_nodes_materialized": 0,
19
+ "public_chunk_count": 575,
20
+ "raw_graph_nodes_admitted_to_gradients": 0,
21
+ "schema": "szl.second-brain.snapshot/v1",
22
+ "secret_scan": "PASS",
23
+ "source_ref": "main",
24
+ "source_relation": "github-exact-revision-public-projection",
25
+ "source_repository": "szl-holdings/szl-second-brain",
26
+ "source_revision": "ff03b116a83f2b5302999ab4167d51e35aba3b5e"
27
+ }
Dockerfile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Unified Python runtime for SZL Living Anatomy + YACHAY Second Brain.
2
+ # The 3D bundle stays vendored and zero-CDN. living_runtime.py extends the
3
+ # existing hardened server in-process with a source-bound, handles-only Brain
4
+ # organ; no private graph, model weights, or write authority enter the image.
5
+ FROM mirror.gcr.io/library/python:3.12-slim@sha256:57cd7c3a7a273101a6485ba99423ee568157882804b1124b4dd04266317710de
6
+ WORKDIR /app
7
+ COPY . /app
8
+ EXPOSE 7860
9
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
10
+ CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:7860/api/anatomy/v1/living-health', timeout=2).read()"
11
+ CMD ["python", "living_runtime.py"]
LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
MIGRATION_RECEIPT.json ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bytes": 2147752,
3
+ "captured_at": "2026-09-04T00:12:23+00:00",
4
+ "destination": "betterwithage/anatomy",
5
+ "file_count": 54,
6
+ "files": [
7
+ {
8
+ "bytes": 41,
9
+ "path": ".dockerignore",
10
+ "sha256": "c127c358bafd75d851bce6f1f8872097484341cbdf124a2c108abd8973d2f33c"
11
+ },
12
+ {
13
+ "bytes": 1519,
14
+ "path": "__gitattributes__.txt",
15
+ "sha256": "11ad7efa24975ee4b0c3c3a38ed18737f0658a5f75a0a96787b576a78a023361"
16
+ },
17
+ {
18
+ "bytes": 47,
19
+ "path": ".github/CODEOWNERS",
20
+ "sha256": "49928138e716b8da4f215977f36d12b3fd1432353c845525302f201dd8d455ce"
21
+ },
22
+ {
23
+ "bytes": 512,
24
+ "path": ".github/dependabot.yml",
25
+ "sha256": "c6442e73c663d9d9a632f49517eb59b7ac119c3b4b6f18fa335b5b9b583d86b3"
26
+ },
27
+ {
28
+ "bytes": 446,
29
+ "path": ".github/workflows/codeql.yml",
30
+ "sha256": "4d69057eef7d35ccfdd7045725d3bb37a8f9b0e5e4d24f0e95ac924872307bc1"
31
+ },
32
+ {
33
+ "bytes": 2664,
34
+ "path": ".github/workflows/container-contract.yml",
35
+ "sha256": "0dd4351bae91d5ebda0ae45b209cd7937c6a612866dd84406f7f3c2e31b4f352"
36
+ },
37
+ {
38
+ "bytes": 17154,
39
+ "path": ".github/workflows/hf-sync.yml",
40
+ "sha256": "3943f8329ded8f8d9e9f23b39da59c93b5d4dda383b1481453ed5a6e7ec438f9"
41
+ },
42
+ {
43
+ "bytes": 727,
44
+ "path": ".github/workflows/overclaim-guard.yml",
45
+ "sha256": "5d8b1fcf929d5e389a3248f5f7e44f29826b7bb383b3870fee1a9c4eff8562b3"
46
+ },
47
+ {
48
+ "bytes": 586,
49
+ "path": ".github/workflows/pin-check.yml",
50
+ "sha256": "0e1411b8ab7763193b09a76a33bffb235e26cf08d54d20130f492730e3e7f0f6"
51
+ },
52
+ {
53
+ "bytes": 793,
54
+ "path": ".github/workflows/sbom.yml",
55
+ "sha256": "4fdda15e803abe906d63833bfd5755e0f0c0384f22962f896eb1e46efb607dbc"
56
+ },
57
+ {
58
+ "bytes": 646,
59
+ "path": ".github/workflows/scorecard.yml",
60
+ "sha256": "e400aec0da60fa7bd46f63eef9de69dd08720f6bc9881159fbcfb8f518d8e9ca"
61
+ },
62
+ {
63
+ "bytes": 604,
64
+ "path": ".github/workflows/trivy.yml",
65
+ "sha256": "ec8274072beebd9c790051601a812abe2ab2d0e8ca320a755f47bb07e45a5574"
66
+ },
67
+ {
68
+ "bytes": 514,
69
+ "path": ".gitignore",
70
+ "sha256": "b9cd89d84215280b3a7a8caa15fb5ea78c1f0faef8510ddf9e57fc0f92f80256"
71
+ },
72
+ {
73
+ "bytes": 551172,
74
+ "path": ".runtime/second-brain/brain-corpus.public.jsonl",
75
+ "sha256": "387337acbd8fe443637102fe7ea75387fa4c3d9d746d8ab6e2d14d6c138aad8f"
76
+ },
77
+ {
78
+ "bytes": 1300,
79
+ "path": ".runtime/second-brain/manifest.json",
80
+ "sha256": "7a2816331df3c7356b5cb01605ea108fa98bb4503d401d3b2952e6b65145d02e"
81
+ },
82
+ {
83
+ "bytes": 1073,
84
+ "path": ".runtime/second-brain/source.json",
85
+ "sha256": "dc577fee39f76d5f938130c8219b98e2373716791800386dd25f7ffb864938c0"
86
+ },
87
+ {
88
+ "bytes": 699,
89
+ "path": "Dockerfile",
90
+ "sha256": "cee5bf78f6de5f491bc52ae83a63bce1ea95f08fc9aaec104ccc22a61dbe0094"
91
+ },
92
+ {
93
+ "bytes": 11358,
94
+ "path": "LICENSE",
95
+ "sha256": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30"
96
+ },
97
+ {
98
+ "bytes": 24596,
99
+ "path": "README.md",
100
+ "sha256": "58014ac91800b906543e396427fcf386b329d5417a67733c2f066a379be45634"
101
+ },
102
+ {
103
+ "bytes": 7057,
104
+ "path": "SCREENSHOT_NOTES.md",
105
+ "sha256": "2c9897400e12cd73d3033aa339d85f73942eebcbdc35480438e37b6f5f97cebe"
106
+ },
107
+ {
108
+ "bytes": 2023,
109
+ "path": "SECURITY.md",
110
+ "sha256": "cfd5c7cf11f5d950a7187a4781ee38c678dad16b471babc45b4a26895c7c935a"
111
+ },
112
+ {
113
+ "bytes": 183197,
114
+ "path": "app.js",
115
+ "sha256": "8a142f99d72f732f209ead306a68169448ce993179904703ff4616e487ceba8a"
116
+ },
117
+ {
118
+ "bytes": 23953,
119
+ "path": "covenant-cockpit.html",
120
+ "sha256": "554177f668b6a1c7d13a3a76b9eae2424056e1510523532798c97f544c510ecb"
121
+ },
122
+ {
123
+ "bytes": 13968,
124
+ "path": "covenant-cockpit.js",
125
+ "sha256": "1979e6b92ddf4877c4cfdb19b71fc06523b8ad715a48883295ecb40fc1bf14b8"
126
+ },
127
+ {
128
+ "bytes": 98455,
129
+ "path": "data.js",
130
+ "sha256": "067e3b8181cfce4b8c1854d2541077d1702d596815bcefa01d9e6c4ecd10b7df"
131
+ },
132
+ {
133
+ "bytes": 3211,
134
+ "path": "docs/LIVING_ANATOMY_SECOND_BRAIN.md",
135
+ "sha256": "e94eda4f1fa4bac8bf0f6e25b4ce58837b4dec315207a941f57fc5764986e6b6"
136
+ },
137
+ {
138
+ "bytes": 872,
139
+ "path": "docs/holographic-space-v2.md",
140
+ "sha256": "829858aa28c37795480497301790dfc57cc783013b1427e2c54a06eee84b0726"
141
+ },
142
+ {
143
+ "bytes": 390,
144
+ "path": "favicon.svg",
145
+ "sha256": "9840fd2ad356862d4c2ed262171841108ef25b667bcfd00334611b7a3441e2e2"
146
+ },
147
+ {
148
+ "bytes": 24759,
149
+ "path": "frontier_anatomy.js",
150
+ "sha256": "44ecde4c8e15e7ea2cb2e810cb374280e394b87e6815c1eef41f435450143629"
151
+ },
152
+ {
153
+ "bytes": 780,
154
+ "path": "hf-deploy-manifest.json",
155
+ "sha256": "7a0173cfadf6e21cc12b73b31faaf0ce10373343a66c6242bb79a8dd4890cd61"
156
+ },
157
+ {
158
+ "bytes": 140206,
159
+ "path": "index.html",
160
+ "sha256": "ccd537b8a7119cd72c350b25b682881a7cc1b12052e01b0ec10139b70ca66e30"
161
+ },
162
+ {
163
+ "bytes": 12272,
164
+ "path": "lib/szl_verify_widget.js",
165
+ "sha256": "b349aec4d6c19265d701b1b82fd1b24ba1d92f8821fa790da0ebe3b69f049609"
166
+ },
167
+ {
168
+ "bytes": 669884,
169
+ "path": "lib/three.min.js",
170
+ "sha256": "170c6789f43217c96b3170f4b42fafe135de7f7cd48497a4218f9757ee1d49fa"
171
+ },
172
+ {
173
+ "bytes": 28209,
174
+ "path": "live-body.html",
175
+ "sha256": "56541caf11a82fbde702724d9f29a859a7a6756aac8e217efa96d07d4ac5e3dd"
176
+ },
177
+ {
178
+ "bytes": 14349,
179
+ "path": "live-body.js",
180
+ "sha256": "b6fff49db582d2417be1c66617dbbb728bafc97ee91ddbce2eca0d90f5c6e0ad"
181
+ },
182
+ {
183
+ "bytes": 13549,
184
+ "path": "living_runtime.py",
185
+ "sha256": "a05a170b20173ada173df4ed0cede0a7ad9fe3a2a4dc16cc93784009e7685e4a"
186
+ },
187
+ {
188
+ "bytes": 42987,
189
+ "path": "og-card.png",
190
+ "sha256": "bb249b5f3fca5aff6e4b8b9dd3ee2fda064773553a1e973d8f58d60aa63f007d"
191
+ },
192
+ {
193
+ "bytes": 19826,
194
+ "path": "organ_integrity.py",
195
+ "sha256": "b2816251df8d049f0b170b0a8dbfacd743ce2bd0f785aaa3157d44e386f4e078"
196
+ },
197
+ {
198
+ "bytes": 6666,
199
+ "path": "qa_cockpit.mjs",
200
+ "sha256": "25cd6265502433e56c74612b4a9bc82ce26d43948718a4e36a24174483eb37cc"
201
+ },
202
+ {
203
+ "bytes": 5338,
204
+ "path": "qa_yarqa.js",
205
+ "sha256": "2ea7e52d163e11fc488b4a565dba9ed49143fd60ab6f4ae708014715b5de2a07"
206
+ },
207
+ {
208
+ "bytes": 12094,
209
+ "path": "receipts.sample.json",
210
+ "sha256": "52bc6ae04d949495c129bf08c8483d37e6c7d100b537d09a1f1b0becdf1a661d"
211
+ },
212
+ {
213
+ "bytes": 9265,
214
+ "path": "scripts/materialize_second_brain.py",
215
+ "sha256": "76efdc311f84a2b2567ff6064fcf6c54027075d15983142612e441bc5297f749"
216
+ },
217
+ {
218
+ "bytes": 16194,
219
+ "path": "second_brain_runtime.py",
220
+ "sha256": "1af54925b974827d7c1c03cc7eb7801b165be7f86c3aef8a58c7de2d05fa8276"
221
+ },
222
+ {
223
+ "bytes": 46062,
224
+ "path": "server.py",
225
+ "sha256": "b5c9cee69cbfd7cac061092f2f49ae0f7dc0be6bf22703b7d34a7d49348d0365"
226
+ },
227
+ {
228
+ "bytes": 388,
229
+ "path": "style.css",
230
+ "sha256": "789bfd541c9f06658ac410d968e9c39fa8c63a48a08643b36071b984c699a9f4"
231
+ },
232
+ {
233
+ "bytes": 24190,
234
+ "path": "szl-holo-v2.css",
235
+ "sha256": "f295e29c659cc106c4443c5c20e559a3f49116b87307b9bd490e218647ee63a2"
236
+ },
237
+ {
238
+ "bytes": 15986,
239
+ "path": "szl-holo-v2.js",
240
+ "sha256": "c04597e6313acfafa471d30ae2948f692cd4f297560024d8979fe4cef1325450"
241
+ },
242
+ {
243
+ "bytes": 6104,
244
+ "path": "tests/qa_evidence_bay.js",
245
+ "sha256": "c2f2e1e0d95e5c373b57624cc35d4beaed98638ac1574b3ed4d3c4bbe48451b5"
246
+ },
247
+ {
248
+ "bytes": 5346,
249
+ "path": "tests/test_hf_sync_contract.py",
250
+ "sha256": "b9c963c9bab31b4accb4cd6865d4c4a168d57081a83733e8922882837f1d7fd2"
251
+ },
252
+ {
253
+ "bytes": 4790,
254
+ "path": "tests/test_second_brain_runtime.py",
255
+ "sha256": "8b7714a3d8bf6b1911f4a2f9927598dd3e711dcf64d180f589a44e16a8810208"
256
+ },
257
+ {
258
+ "bytes": 26720,
259
+ "path": "tests/test_server_contract.py",
260
+ "sha256": "e9aa968f27dee4abcfaaecddd6d0fc42844ff36232d08ce8f21ba7c5ebe36e0c"
261
+ },
262
+ {
263
+ "bytes": 28033,
264
+ "path": "v5_organs.js",
265
+ "sha256": "0ef1f09bf273ae5a6269ba32ec9e03cab93bca4bab56a1f1fe21ac60fd3873bc"
266
+ },
267
+ {
268
+ "bytes": 13405,
269
+ "path": "v6_alive.js",
270
+ "sha256": "65ee3306ff732d4d977ecec5014431e832c599900459c7016593d1f84010d380"
271
+ },
272
+ {
273
+ "bytes": 10773,
274
+ "path": "yachay-second-brain.js",
275
+ "sha256": "473d3f09b49e8069d64cd63a79bf5e3e0a17c9e299cd33c87b8169b9c19ba3f5"
276
+ }
277
+ ],
278
+ "source": "https://github.com/szl-holdings/anatomy.git",
279
+ "source_sha": "6e7f19a7b7597c618df52fffd5b1812d1e8a82c5",
280
+ "unresolved_lfs": []
281
+ }
README.md CHANGED
@@ -1,10 +1,389 @@
1
  ---
2
- title: Anatomy
3
- emoji: 🦀
4
- colorFrom: yellow
5
- colorTo: pink
 
6
  sdk: docker
 
7
  pinned: false
 
 
 
 
 
 
 
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: SZL Living Anatomy
3
+ emoji: 🫀
4
+ thumbnail: "https://huggingface.co/spaces/betterwithage/anatomy/resolve/main/og-card.png"
5
+ colorFrom: blue
6
+ colorTo: gray
7
  sdk: docker
8
+ app_port: 7860
9
  pinned: false
10
+ license: apache-2.0
11
+ short_description: 3D navigable map of the governed-AI organ substrate
12
+ tags:
13
+ - visualization
14
+ - threejs
15
+ - governance
16
+ - receipts
17
+ - honest-by-design
18
+ - szl-holdings
19
  ---
20
 
21
+ <!-- SZL-ESTATE-CARD:v2:START -->
22
+ <p align="center"><a href="https://a-11-oy.com/"><img src="https://huggingface.co/spaces/SZLHOLDINGS/README/resolve/main/assets/estate-banner-v2.svg" alt="SZL Holdings — governed, receipted, verifiable" width="100%"></a></p>
23
+ <p align="center">
24
+ <a href="https://github.com/szl-holdings/.github/tree/main/doctrine"><img src="https://img.shields.io/badge/doctrine-v11%20LOCKED-0B1F3A?style=flat-square" alt="doctrine v11"></a>
25
+ <a href="https://a-11-oy.com/"><img src="https://img.shields.io/badge/evidence%20wall-LIVE%20%C2%B7%20verify%20in%20browser-3AF4C8?style=flat-square" alt="live evidence wall"></a>
26
+ <a href="https://huggingface.co/datasets/SZLHOLDINGS/szl-lake"><img src="https://img.shields.io/badge/szl--lake-offline%20verifiable-C9B787?style=flat-square" alt="szl-lake offline verifiable"></a>
27
+ <a href="https://huggingface.co/spaces/SZLHOLDINGS/holographic"><img src="https://img.shields.io/badge/estate%20map-holographic-5B8DEE?style=flat-square" alt="holographic estate map"></a>
28
+ </p>
29
+ <p align="center"><sub>Part of the <a href="https://huggingface.co/SZLHOLDINGS">SZL Holdings</a> governed estate — claims are designed to carry checkable receipts. Verification proves integrity &amp; origin, never accuracy or performance.</sub></p>
30
+ <!-- SZL-ESTATE-CARD:v2:END -->
31
+
32
+ # SZL Living Anatomy 🫀
33
+
34
+ > **Governed AI you can prove — as a living body.**
35
+ > A 3D, navigable map of the governed organism: its organs, how a single decision
36
+ > flows through them, and where each proof and conjecture honestly sits.
37
+
38
+ > **The living substrate · 5 systems · Λ heart · DSSE Khipu receipt bus · honest by design**
39
+ >
40
+ > **Shared, embeddable 3D scene** — rendered inside the a11oy and killinchu consoles; a visualization component, not a separate governance console.
41
+
42
+ [![SLSA L1 honest (static viz)](https://img.shields.io/badge/SLSA-L1%20honest%20(static%20viz)-c9b787?style=flat-square)](https://github.com/szl-holdings/anatomy/actions/workflows/hf-sync.yml)
43
+ [![doctrine-v11](https://img.shields.io/badge/doctrine-v11%20LOCKED-0B1F3A?style=flat-square)](https://github.com/szl-holdings/.github/tree/main/doctrine)
44
+ [![License](https://img.shields.io/badge/license-Apache--2.0-5fb3a3?style=flat-square)](https://github.com/szl-holdings/anatomy)
45
+ [![Λ Conjecture 1](https://img.shields.io/badge/%CE%9B-Conjecture%201-7d8aa0?style=flat-square)](https://github.com/szl-holdings/lutar-lean/blob/main/BOUNTY.md)
46
+ [![Khipu Conjecture 2](https://img.shields.io/badge/Khipu%20BFT-Conjecture%202-7d8aa0?style=flat-square)](https://github.com/szl-holdings/khipu-consensus)
47
+
48
+ The governed-AI organ substrate shared by **a11oy** (governed-AI command body) and
49
+ **killinchu** (maritime / drone C2 body): two bodies, one circulatory + nervous mesh,
50
+ with the Λ heart at the center.
51
+
52
+ ## Live integrity kernel (szl-khipu)
53
+
54
+ This repository is the **3D atlas** (SLSA L1 static viz). The fail-closed organ-integrity
55
+ kernel that actually runs the five organs lives in
56
+ [szl-holdings/szl-khipu](https://github.com/szl-holdings/szl-khipu) as `evaluate_anatomy`,
57
+ and on the KHIPU Space **Anatomy** tab:
58
+ [SZLHOLDINGS/szl-khipu](https://huggingface.co/spaces/SZLHOLDINGS/szl-khipu).
59
+ The command body exposes the same fail-closed contract at
60
+ [`GET/POST /api/a11oy/v1/organs/integrity`](https://a-11-oy.com/api/a11oy/v1/organs/integrity)
61
+ and the Evidence Bay at [szl-holdings/szl-organ-integrity](https://github.com/szl-holdings/szl-organ-integrity).
62
+
63
+ HEART/YUYAY · YAWAR · YACHAY · OTel · Khipu skeleton. Any DOWN organ or a WILLAY veto
64
+ blocks the body. Λ = Conjecture 1 OPEN. Energy UNAVAILABLE. Locked-proven stays 8.
65
+ Not a Three.js rehost of this Space — the other way around: this Space is the map,
66
+ szl-khipu is the kernel.
67
+
68
+ ## Evidence Bay — the proof boundary
69
+
70
+ The 3D organism now has a machine-readable evidence boundary without replacing its
71
+ visual language. Open **Evidence Bay** from the atlas to inspect every major surface
72
+ through the same five-part contract: **Purpose · Try · Evidence · Limits · Reproduce**.
73
+
74
+ - Transport, evidence, verification, and authority are separate dimensions. A
75
+ `RUNNING` Space is not treated as proof of model quality, freshness, or safety.
76
+ - The deployed bundle emits a deterministic SHA-256 integrity receipt. Its local
77
+ verifier recomputes every declared file and deliberately returns
78
+ `STRUCTURAL-ONLY` because the public visualization has no signing key.
79
+ - Live A11OY, Killinchu, and receipt-verifier dependencies are probed separately
80
+ and timestamped. Missing contracts stay `MISSING` or `UNAVAILABLE`; no green is
81
+ synthesized from an unrelated endpoint.
82
+ - Formula claims link to their source files. This Space presents a declared
83
+ snapshot—it does not run Lean—and Λ remains Conjecture 1.
84
+ - `/.well-known/szl-source.json` exposes the declared GitHub base, measured HF
85
+ revision, artifact-set digest, and the remaining GitHub-sync state. Automated
86
+ deployments add `hf-deploy-manifest.json`, binding the served runtime
87
+ whitelist to the exact current protected-main commit rechecked immediately
88
+ before publication; this is a source-bound deployment claim, not a
89
+ whole-repository byte-parity claim.
90
+
91
+ ## v6 — alive-proof layer (ratchet 2026-07-21)
92
+
93
+ The **⛬ alive-proof (v6)** control closes the loop between the map and the
94
+ running substrate. It fetches the latest anatomy alive-harness run from the
95
+ restored public sink ([`SZLHOLDINGS/test-results`](https://huggingface.co/datasets/SZLHOLDINGS/test-results)),
96
+ verifies the run's DSSE (PAE v1) ECDSA-P256 signature **in the browser**
97
+ against the pinned, committed org key
98
+ ([`hatun-mcp/PUBKEY_szlholdings-ec-p256.pem`](https://github.com/szl-holdings/hatun-mcp/blob/main/PUBKEY_szlholdings-ec-p256.pem)),
99
+ and only then displays the run — verdict, live assertion counts, per-layer
100
+ results, and the formula-gate pass rate, all **derived from the signed
101
+ evidence**, never hand-typed. Runs are signed by the live Hatun MCP gateway
102
+ (`dsse_sign`, keyid `szlholdings-ec-p256`) and published by a fail-closed
103
+ publisher that verifies before and after upload. If the sink is unreachable or
104
+ a signature fails, the panel says so — no fabricated green light. A signed
105
+ GREEN run proves liveness, not doctrine upgrades: locked-proven stays exactly
106
+ 8 and Λ remains Conjecture 1.
107
+
108
+ Machine-readable routes:
109
+
110
+ | Route | Meaning |
111
+ |---|---|
112
+ | `/version` | Exact GitHub source and deployed HF revision (`MEASURED` only when source-bound) |
113
+ | `/evidence` | Release identity, structural bundle receipt, and dependency evidence index |
114
+ | `/api/anatomy/v1/manifest` | Contract, state vocabulary, doctrine boundary |
115
+ | `/api/anatomy/v1/capabilities` | Five-part capability shell and provenance |
116
+ | `/api/anatomy/v1/evidence?refresh=1` | Fresh dependency contract probes |
117
+ | `/api/anatomy/v1/receipt` | Deterministic local artifact receipt |
118
+ | `POST /api/anatomy/v1/verify/receipt` | Replay local integrity; structural only |
119
+ | `/.well-known/szl-source.json` | GitHub ↔ HF deployment-source attestation |
120
+
121
+ ## What's new in v5 — conscience, sovereign mesh, verifiable receipts (evolves v4)
122
+
123
+ v5 **evolves** v4 (it does not replace it): the entire v4 engine (`data.js` / `app.js`,
124
+ dissection dock, live-body, yarqa CFD) is preserved. A single additive module
125
+ (`v5_organs.js`, same vendored-free / 0-CDN / no-build posture) layers on six new,
126
+ honestly-labeled capabilities — all read-only against the live a11oy origin:
127
+
128
+ - **WILLAY — conscience / immune-gate organ (NEW).** Five **inspectable** signed-refusal
129
+ classifiers (cyber · bio dual-use · hidden-reasoning extraction · prompt-injection /
130
+ governance bypass · self-harm), trust ceiling 0.97, read live from
131
+ `/api/a11oy/v1/willay/classifiers`. Honest label: refusals are **tamper-EVIDENT, not
132
+ tamper-proof** — auditable rules, the inverse of a removed/hidden classifier.
133
+ - **Sovereign Mesh — circulatory upgrade.** Per-node up/**DOWN** read live from
134
+ `/api/a11oy/v1/govern/health` — a node that is offline reads DOWN, **never a fabricated
135
+ green light**. F11 Ayni reciprocity per node; **VRAM-fusion is ROADMAP** (the mesh is a
136
+ scheduler / router today).
137
+ - **Buyer-verifiable receipt in-scene.** A "Verify offline" action reuses Tier-1 **WebCrypto
138
+ ECDSA-P256-SHA256** over the DSSE PAE against `/cosign.pub` — verified entirely in your
139
+ browser, no trust in us required. Plus a live **receipt bloodstream** counter reading the
140
+ unified ledger (`/api/lake/v1/health`: `total_receipts`, `sha3_256` chain head).
141
+ - **8 locked-proven → organ map.** F1→BRAIN, F4+F11→HEART, F7+F22→CIRCULATORY, F12→NERVOUS,
142
+ F18+F19→SKELETON — each showing the verbatim Lean statement + `#print axioms`,
143
+ **kernel-verified sorry-free @ c7c0ba17**. Λ is the heart-gate: **advisory, Conjecture 1**,
144
+ never a theorem. Khipu BFT = Conjecture 2.
145
+ - **AI-Assurance (WDP / CDAO) overlay.** Maps each organ to the assurance artifact it
146
+ satisfies (model card · data card · SBOM/SLSA · SI-7 hash-chain · TEVV signed receipt ·
147
+ OTel-GenAI) with honest **LIVE / PARTIAL / ROADMAP** status chips; links the live
148
+ `/assurance` surface.
149
+ - **yarqa CFD + thermal-PINN physics layer.** Composes the existing yarqa plug-flow
150
+ compartmentalization with a thermal physics-informed-NN surrogate into one
151
+ "physics-governed" layer, labeled **MODELED** (not measured), bounded error. Never a locked
152
+ theorem; never folded into the locked-8.
153
+ - **GPU-Sovereign Stack — SUBSTRATE (NEW).** The *vertical* compute anatomy that complements the
154
+ horizontal Sovereign Mesh: owned GPU fabric → runtime → mesh / router → open-weight model →
155
+ native governance → buyer-verifiable receipts. Framed against how the leaders present sovereign
156
+ compute (chip → cloud → model), made our own by promoting governance and verifiable receipts to
157
+ first-class layers. Every layer carries an honest posture chip; live layers read
158
+ `/govern/health` and degrade to **DOWN**, never a fabricated green light. Energy is **SAMPLE**
159
+ until a real NVML meter; VRAM-fusion and on-metal **TEE attestation are ROADMAP**. Adds nothing
160
+ to the locked-8.
161
+
162
+ Locked-proven stays **exactly 8** {F1,F4,F7,F11,F12,F18,F19,F22} @ `c7c0ba17`; the doctrine
163
+ footer is unchanged. Still sovereign: ONLY the vendored `lib/three.min.js`, zero runtime CDN.
164
+
165
+ ## What's new in v4 — dissection tools
166
+
167
+ v4 **evolves** v3 (it does not replace it): the entire v3 engine, organs, formulas,
168
+ YAWAR receipt bus, GPD lens, and text fallback are preserved. Layered on top are
169
+ bench-grade dissection controls so the body is *easier to dissect*:
170
+
171
+ - **Dissection layer stack** — toggle + opacity-slide the conceptual layers
172
+ (circulatory · nervous · organs · skeleton/Khipu · halos/glow); choices persist in `localStorage`.
173
+ - **Clip-plane scalpel** — a sliding X/Y/Z cross-section (`renderer.localClippingEnabled`)
174
+ cuts the organism so you can see the interior, with a reset.
175
+ - **Explode view** — an eased 0→1 slider separates the organ groups radially for inspection.
176
+ - **Search / jump** — filter organs + formulas by name/id; selecting one flies the camera and opens its panel.
177
+ - **Always-on visibility HUD** — a compact overlay reading **honest** counts straight from
178
+ `data.js` (`D.KERNEL`): locked-proven = 8, experimental tier, axioms 14, sorries 163,
179
+ kernel `c7c0ba17`, Λ = Conjecture 1, Khipu BFT = Conjecture 2. Never hardcoded.
180
+ - **Focus mode** — fade the other organs when one is selected, to isolate it.
181
+ - **yarqa flow compartments (CFD) — additive, off by default** — an *engineering-method*
182
+ layer in the dissection dock that runs a clean-room plug-flow compartmentalization
183
+ (`yarqa`) over the **existing** circulatory / YAWAR flow sampled from `data.js`, draws
184
+ the compartments as a toggleable read-only overlay, and emits a reproducible integrity
185
+ receipt digest. It is **labeled CFD, not a locked theorem, and is never counted among
186
+ the locked 8** — `data.js` stays the single source of truth and the locked-proven count
187
+ is unchanged at 8.
188
+ - **Accessibility + mobile** — every new control is keyboard-reachable and ARIA-labeled,
189
+ laid out so it never overlaps the existing HUD/panel, and it respects `prefers-reduced-motion`.
190
+
191
+ Still sovereign: ONLY the vendored `lib/three.min.js` (THREE r160 global) — zero runtime
192
+ CDN, no npm, no build step. The site stays a static, offline-capable bundle.
193
+
194
+ ## What you'll see
195
+
196
+ Walk the organism in 3D and watch a real decision propagate: a request enters, the
197
+ **YUYAY** gate scores it on 13 conjunctive axes (deny-by-default), the verdict is sealed
198
+ into a **DSSE Khipu receipt** on the **YAWAR** append-only bus, and the **YACHAY** read-only
199
+ cortex supplies reasoning without ever holding write authority. Each organ is labeled with
200
+ its honest proof state — proven, conditional, or open conjecture — so nothing is dressed up
201
+ as more certain than it is.
202
+
203
+ **Five systems:** HEART · YUYAY (13-axis conjunctive critique gate, emits Λ-signed receipt) ·
204
+ CIRCULATORY/BLOOD · YAWAR (append-only SHA-256 receipt bus) ·
205
+ BRAIN · YACHAY (read-only reasoning cortex) ·
206
+ NERVOUS · OTel/VSP · SKELETON · 12 service repos.
207
+
208
+ **Honest doctrine:** locked-proven = 8 {F1, F4, F7, F11, F12, F18, F19, F22} @ kernel `c7c0ba17`
209
+ (the no-axiom theorem `locked_count_eight`; F4 Khipu DAG acyclicity, F7 Chaski FIFO ordering,
210
+ F22 Khipu emit append-only monotonicity) ·
211
+ Λ unconditional uniqueness = Conjecture 1 (machine-checked FALSE); conditional Λ axiom-free PROVEN ·
212
+ Khipu BFT safety = Conjecture 2, with the Wave23 conditional agreement theorem
213
+ (`khipu_quorum_safety_conditional`, n≥3f+1 + honest non-equivocation, axiom-clean) ·
214
+ ~185 experimental CI-green · trust never 100% · no AGI.
215
+
216
+ **Supply-chain posture:** this Space is a fully static visualization served by a thin
217
+ Docker wrapper (`sdk: docker`; a static file server, no application backend) — SLSA L1 honest.
218
+ The product images it depicts (**a11oy**, **killinchu**) are **SLSA L1 honest · L2 build-attested**
219
+ (container provenance via attest-build-provenance, Sigstore keyless, Rekor-anchored; L3 roadmap) —
220
+ see the active canonical successors [a11oy](https://github.com/szl-holdings/a11oy),
221
+ [killinchu](https://github.com/szl-holdings/killinchu), and
222
+ [szl-mesh](https://github.com/szl-holdings/szl-mesh).
223
+
224
+ > **Non-affiliation.** SZL Holdings' use of "UDS" references Defense Unicorns' Unified Defense
225
+ > Stack (USPTO Serial 99831122); SZL Holdings is not affiliated with Defense Unicorns. No
226
+ > production ATO is claimed.
227
+
228
+ ## Live body view — `live-body.html`
229
+
230
+ A new, **additive** page (`live-body.html` + `live-body.js`, linked from the
231
+ title bar of the 3D atlas) turns the anatomy into the **LIVE BODY VIEW of the
232
+ agentic GPU mind**. It is a standalone static page — same vendored-free,
233
+ no-build, no-CDN posture as `index.html` — reachable directly at
234
+ `…static.hf.space/live-body.html`. It does **not** modify the 3D engine (`app.js`,
235
+ `data.js`), so there are no breaking changes.
236
+
237
+ Each of the six organs reads its **real endpoint** and lights up with its honest
238
+ live status; press **Run proactive cycle** to watch the GPU mind act
239
+ (IMMUNE → BRAIN → run → HEART/BLOOD → NERVOUS), pulsing each organ in turn:
240
+
241
+ | Organ | Proven formula (round9) | Live endpoint read |
242
+ |---|---|---|
243
+ | BRAIN | BrainBeliefUpdate (PAC-Bayes McAllester) | amaru `/api/amaru/v1/formulas` |
244
+ | HEART | HeartReceiptSigma (σ-algebra receipt bus) | amaru `/api/amaru/receipts` |
245
+ | BLOOD | BloodDSSEMerkle (Cardano-anchored DSSE) | sentra `/api/sentra/khipu/ledger` |
246
+ | IMMUNE | ImmuneNeymanPearson (deny-by-default gates) | sentra `/api/sentra/v1/gates` |
247
+ | SKELETON | SkeletonLambdaSpine (Lean kernel; Λ=Conj 1) | amaru `/api/amaru/v1/math/lean/theorems` |
248
+ | NERVOUS | NervousShannonAlarm (Λ-signed OTEL drift) | amaru `/api/amaru/overwatch/snapshot` |
249
+
250
+ The **GPU-mind posture** card reads a11oy `/api/a11oy/code/healthz`
251
+ (`sovereign` / `backend` / `mode`); the honesty strip reads the doctrine lock
252
+ live from a11oy `/api/a11oy/v1/honest`.
253
+
254
+ **Honest by design (doctrine v11/v12):**
255
+ - `sovereign:true` is shown **only** when `/code/healthz` reports the literal
256
+ `true` — never synthesized from a truthy value. If the mind is unreachable the
257
+ card shows `sovereign: false`. The half-state (banner sovereign while a router
258
+ serves) is the one outcome the view will never render.
259
+ - Energy / joules are labeled **SAMPLE** until a real meter is wired.
260
+ - **Λ is shown as Conjecture 1** (the skeleton's killer formula is intentionally
261
+ a conjecture), pulled live, never hardcoded as proven.
262
+ - An unreachable endpoint degrades to an honest `unreachable — … · honest
263
+ empty-state`; no green light is ever fabricated for an organ that did not
264
+ answer. (Today amaru/sentra spaces may be unrouted → those organs honestly
265
+ read unreachable; a11oy + the mind posture read live.)
266
+ - Read-only, sends no key, open-weight only.
267
+
268
+ See `SCREENSHOT_NOTES.md` for the body layout and what a reviewer should see in a
269
+ deploy preview.
270
+
271
+ ## Run, test, rollback (operability)
272
+
273
+ This Space is a static bundle served by a thin Docker wrapper (`sdk: docker`; a
274
+ `python http.server` on port 7860) — no application backend, and the bundle itself is
275
+ static and offline-capable. To run and test locally:
276
+
277
+ ```bash
278
+ # run: serve the bundle from the repo root with any static server
279
+ python3 -m http.server 8000 # then open http://localhost:8000/index.html
280
+
281
+ # test: the headless QA harness (Playwright/Chromium) renders all three
282
+ # viewports, asserts 0 console errors, exercises the v4 dissection dock + the
283
+ # v6 yarqa CFD layer, and confirms yarqa is NEVER counted in the locked-8.
284
+ npm i -D playwright && npx playwright install chromium
285
+ node qa_yarqa.js
286
+ ```
287
+
288
+ **Health:** the page is "healthy" when `index.html` renders the 3D atlas with zero
289
+ console errors at all three viewports (the QA assertion). The live-lens panels poll
290
+ a11oy read-only and **degrade to a labeled `offline · static snapshot`** when an
291
+ endpoint is unreachable — an offline endpoint is an expected state, not an outage.
292
+
293
+ **Rollback (one step):** every deploy is a git commit; to revert the live Space to a
294
+ known-good state, redeploy the previous tag/commit — `git revert <bad-sha>` (or reset
295
+ the HF Space mirror to the prior commit). Because the bundle is fully static and
296
+ self-contained (vendored `lib/three.min.js`, no runtime CDN), a rollback is just
297
+ "serve the older files" — there is no migration or state to unwind.
298
+
299
+ **Service ownership:** see `.github/CODEOWNERS`.
300
+
301
+ ## Security headers (SAFE-NOW hardening, R2)
302
+
303
+ This Space serves a fully static bundle via a thin Docker wrapper (`sdk: docker`;
304
+ a `python http.server` on port 7860). Under `sdk: docker` Hugging Face does **not**
305
+ apply a README `custom_headers` block (that lever is static-SDK only), so the
306
+ cross-origin headers are emitted by the container's own static server. Hardening is
307
+ split across the two levers that actually take effect, and nothing is set that the
308
+ browser would silently ignore (doctrine v11: never fabricate):
309
+
310
+ - **Response headers emitted by the Space's static server** (set on every response):
311
+ - `cross-origin-opener-policy: same-origin-allow-popups`
312
+ - `cross-origin-resource-policy: cross-origin` (keeps the page loadable inside
313
+ the legitimate `huggingface.co` / `*.hf.space` embed iframe).
314
+ - COEP `require-corp` is **intentionally not set** — it would block the page's
315
+ read-only cross-origin fetches to a11oy/amaru/sentra and buys nothing here
316
+ (no `SharedArrayBuffer`/wasm).
317
+ - **`<meta http-equiv>` in `index.html` + `live-body.html`** (what the browser
318
+ honors from markup):
319
+ - **Content-Security-Policy** (enforced, non-breaking): `default-src 'self'`;
320
+ `object-src 'none'`; `base-uri 'self'`; an explicit `connect-src` allow-list
321
+ (self + the four SZL `*.hf.space` origins it reads); `img-src 'self' data:
322
+ blob:`. `script-src`/`style-src` keep `'unsafe-inline'` **on purpose** — the
323
+ 3D atlas ships heavy inline JS, inline styles, and a WebGL canvas, so a strict
324
+ nonce/hash CSP would white-screen it. The win is origin-locking: no rogue
325
+ external script, CDN, or pixel can load.
326
+ - **X-Content-Type-Options: nosniff** and **Referrer-Policy:
327
+ strict-origin-when-cross-origin**.
328
+
329
+ **Why no HSTS / `frame-ancestors` / Report-Only here:** browsers ignore HSTS,
330
+ CSP `frame-ancestors`, and `Content-Security-Policy-Report-Only` when delivered
331
+ via `<meta>`, and the static server does not emit them as real headers — so setting
332
+ them in-repo would be security theater. HF already terminates TLS and redirects to
333
+ HTTPS at the edge. **Embedding is deliberately left enabled** (no
334
+ `X-Frame-Options: DENY`, no `disable_embedding`) so the Space keeps working inside
335
+ the `huggingface.co` / `*.hf.space` iframe.
336
+
337
+ **CORS:** the evidence endpoints are public, read-only inspection contracts and
338
+ return `Access-Control-Allow-Origin: *` so A11OY and the wider estate can ingest
339
+ them. The only POST is a pure receipt recomputation; it cannot sign, store, fetch
340
+ user-controlled URLs, or mutate state. Outbound dependency probes use a fixed
341
+ allowlist in `server.py`; no key, cookie, or credential is sent.
342
+
343
+ ## Verify it yourself
344
+
345
+ The organism is a map, not the source of truth — every claim it draws is checkable against the
346
+ live products it depicts:
347
+
348
+ ```bash
349
+ # Confirm the live doctrine posture the heart reports
350
+ curl -s https://szlholdings-a11oy.hf.space/api/a11oy/v1/honest | jq .kernel_commit # => "c7c0ba17"
351
+ # Inspect and replay the Anatomy bundle receipt (result is STRUCTURAL-ONLY, not signed)
352
+ curl -s https://betterwithage-anatomy.hf.space/api/anatomy/v1/receipt -o anatomy-receipt.json
353
+ curl -s -X POST -H "Content-Type: application/json" --data-binary @anatomy-receipt.json \
354
+ https://betterwithage-anatomy.hf.space/api/anatomy/v1/verify/receipt | jq .verdict
355
+ # Open the independent browser verifier for signed governed receipts
356
+ open https://huggingface.co/spaces/SZLHOLDINGS/governed-receipt-verifier
357
+ ```
358
+
359
+ Read the thesis → [szl-papers](https://github.com/szl-holdings/szl-papers) ·
360
+ run the kernel → [lutar-lean](https://github.com/szl-holdings/lutar-lean).
361
+
362
+ ---
363
+
364
+ Declared source base: `szl-holdings/anatomy` (GitHub) → `betterwithage/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)**
365
+
366
+ <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>
367
+
368
+ ---
369
+
370
+ ## ◇ Part of the SZL Holdings estate — *governed AI you can prove*
371
+
372
+ One sovereign substrate, many organs — every decision carries a signed, checkable receipt.
373
+
374
+ **[◇ Holographic Estate — the showcase](https://szlholdings-holographic.hf.space)** ·
375
+ [🛡️ a11oy](https://huggingface.co/spaces/SZLHOLDINGS/a11oy) ·
376
+ [🧬 IMMUNE](https://huggingface.co/spaces/SZLHOLDINGS/immune) ·
377
+ [🦅 killinchu](https://huggingface.co/spaces/SZLHOLDINGS/killinchu) ·
378
+ [🫀 anatomy](https://huggingface.co/spaces/betterwithage/anatomy) ·
379
+ [🌌 cosmos](https://huggingface.co/spaces/SZLHOLDINGS/cosmos) ·
380
+ [🛰️ SDA](https://huggingface.co/spaces/SZLHOLDINGS/sda) ·
381
+ [🌊 yarqa](https://huggingface.co/spaces/SZLHOLDINGS/yarqa) ·
382
+ [🤗 all Spaces](https://huggingface.co/SZLHOLDINGS)
383
+
384
+ **Governed-receipt cluster** — the open receipt format, an offline verifier, and a conformance bench (the DSSE Khipu receipts this organism depicts conform to this spec):
385
+ [📐 governed-receipt-spec](https://github.com/szl-holdings/governed-receipt-spec) ·
386
+ [✅ receipt verifier](https://huggingface.co/spaces/SZLHOLDINGS/governed-receipt-verifier) ·
387
+ [📦 receipts bench](https://huggingface.co/datasets/SZLHOLDINGS/governed-receipts-bench)
388
+
389
+ <sub>Doctrine v11 · Λ = Conjecture 1 (advisory — never "green"/theorem; open) · honest by design · public data only.</sub>
SCREENSHOT_NOTES.md ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SCREENSHOT_NOTES — live body view (`live-body.html`)
2
+
3
+ No headless browser is available in this lane, so the page was verified by
4
+ **static parse + a Node functional test of the engine logic** (see "How it was
5
+ verified" below) rather than a rendered screenshot. These notes describe the
6
+ exact layout a reviewer should see in an HF **deploy preview** of the
7
+ `feat/anatomy-live-body-view` branch, so the visual result can be checked
8
+ against intent.
9
+
10
+ ## Body layout (top → bottom)
11
+
12
+ ```
13
+ ┌───────────────────────────────────────────────────────────────────────────┐
14
+ │ SZL LIVING ANATOMY · LIVE BODY VIEW ┌─ GPU mind · posture ┐│
15
+ │ The agentic GPU MIND, inside its proven body │ sovereign [false] ││
16
+ │ <one-paragraph intro + "← full 3D atlas" link> │ backend hf-router││
17
+ │ │ mode live ││
18
+ │ │ doctrine v12 ││
19
+ │ └─────────────────────┘│
20
+ │ │
21
+ │ [ ▶ Run proactive cycle ] [ ↻ Refresh organ status ] [ ⚡ energy: SAMPLE ]│
22
+ │ │
23
+ │ ┌── IMMUNE ⛨ ─ step 0 ──┐ ┌── BRAIN ✸ ─ step 1 ───┐ ┌── HEART ❤ step 3 ─┐│
24
+ │ │ Neyman-Pearson gates │ │ PAC-Bayes McAllester │ │ σ-algebra receipts ││
25
+ │ │ ● <status detail> │ │ ● <status detail> │ │ ● <status detail> ││
26
+ │ │ <endpoint url> │ │ <endpoint url> │ │ <endpoint url> ││
27
+ │ └───────────────────────┘ └───────────────────────┘ └────────────────────┘│
28
+ │ ┌── BLOOD 🜂 ─ step 4 ──┐ ┌── SKELETON ⊟ spine ──┐ ┌── NERVOUS ⌁ step 5 ┐│
29
+ │ │ DSSE Merkle provenance│ │ Lean kernel · Λ=Conj1 │ │ Shannon drift alarm ││
30
+ │ │ ● <status detail> │ │ ● <status detail> │ │ ● <status detail> ││
31
+ │ └───────────────────────┘ └───────────────────────┘ └────────────────────┘│
32
+ │ │
33
+ │ <cycle log line — narrates immune→brain→heart→blood→nervous> │
34
+ │ ┌─ honest by design ───────────────────────────────────────────────────┐ │
35
+ │ │ ● Λ = Conjecture 1 ● sovereign only from /code/healthz ● SAMPLE … │ │
36
+ │ └──────────────────────────────────────────────────────────────────────┘ │
37
+ └───────────────────────────────────────────────────────────────────────────┘
38
+ ```
39
+
40
+ - **Six organ cards** in a responsive `auto-fit` grid (3-up on desktop, 1-up on
41
+ mobile). Each card carries its colored accent bar, glyph, proven-formula line,
42
+ agentic role, a **status dot + detail line**, and the real endpoint URL.
43
+ - The **GPU-mind posture** card sits top-right with the live `sovereign` badge.
44
+ - Organ colors reuse the existing `index.html` tokens: HEART `#ff5d8f`, BLOOD
45
+ `#ff3b5c`, BRAIN `#7c5cff`, NERVOUS `#5ad1ff`, SKELETON/IMMUNE `#ffd166`.
46
+
47
+ ## Status-dot states (honest)
48
+
49
+ - **live** (cyan dot, card border brightens): endpoint answered `2xx` with usable
50
+ JSON; the detail line shows a short summary (e.g. "8 deny-by-default gates
51
+ armed", "pac_bayes_mcallester present").
52
+ - **pending** (amber, breathing): mid-probe.
53
+ - **unreachable** (grey dot, dimmed text): network/CORS/timeout/non-JSON →
54
+ reads `unreachable — <why> · honest empty-state`. **No green light is ever
55
+ shown for an organ that did not answer.**
56
+
57
+ ## What the proactive-cycle button does
58
+
59
+ Pressing **▶ Run proactive cycle** pulses the organs in the canonical order
60
+ **IMMUNE → BRAIN → HEART → BLOOD → NERVOUS** (SKELETON is the always-on spine and
61
+ is excluded from the cycle). Each pulse is a ~1s color flash + lift; the cycle
62
+ log narrates each phase and ends with *"reactive turns were never gated (they
63
+ always preempt)."* Respects `prefers-reduced-motion` (border highlight instead of
64
+ motion).
65
+
66
+ ## Expected live state TODAY (honest)
67
+
68
+ At the time this was built:
69
+ - **GPU mind** (`/api/a11oy/code/healthz`): reachable → `sovereign: false`
70
+ (router-served, `backend: hf-router`, `mode: live`, `doctrine: v12`). This is
71
+ the **correct, honest** reading — it is NOT sovereign while a router serves,
72
+ and the view says so plainly.
73
+ - **Honesty strip** (`/api/a11oy/v1/honest`): reachable → Λ = Conjecture 1,
74
+ 8 locked-proven, 749/14/163 @ `c7c0ba17`.
75
+ - **amaru / sentra organ endpoints**: their HF spaces currently return non-JSON
76
+ (unrouted) → BRAIN/HEART/BLOOD/IMMUNE/SKELETON/NERVOUS honestly read
77
+ **unreachable · honest empty-state**. When those spaces are routed the same
78
+ page lights them green with no code change.
79
+
80
+ So a reviewer opening the deploy preview should expect: **mind posture + honesty
81
+ strip live; organ cards in honest unreachable states until amaru/sentra route.**
82
+ That is the doctrine floor working as intended, not a bug.
83
+
84
+ ## How it was verified (no headless browser)
85
+
86
+ - `node --check live-body.js` → PASS.
87
+ - Inline `<script type="module">` extracted from `live-body.html` →
88
+ `node --check` PASS.
89
+ - HTML tag-balance lint (html/head/body/style/script/main/header/section/footer)
90
+ → all balanced; DOCTYPE present.
91
+ - **Engine functional test** (mocked `fetch`, 14 assertions, all pass):
92
+ - proactive cycle order is exactly `immune→brain→heart→blood→nervous`;
93
+ skeleton excluded.
94
+ - `summarize` tolerates real + empty/odd JSON shapes without throwing.
95
+ - `probeOrgan` degrades to `unreachable` on network error and on non-JSON
96
+ (HF 404 HTML), and reads `live` on real JSON.
97
+ - `probeMind` sets `sovereign:true` **only** on the literal `true`, never on a
98
+ truthy string, and reports `sovereign:false` when the mind is unreachable
99
+ (the half-state is unrepresentable).
100
+
101
+ A rendered screenshot still requires an HF **deploy preview** of the branch —
102
+ flagged here for the reviewer.
SECURITY.md ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ | Version | Supported |
6
+ | ------- | ------------------ |
7
+ | 1.x | :white_check_mark: |
8
+ | < 1.0 | :x: |
9
+
10
+ ## Reporting a Vulnerability
11
+
12
+ **Do NOT open a public GitHub issue for security vulnerabilities.**
13
+
14
+ Please report security vulnerabilities via email to **security@szlholdings.ai** with:
15
+
16
+ 1. Description of the vulnerability
17
+ 2. Steps to reproduce
18
+ 3. Potential impact assessment
19
+ 4. Any suggested mitigations
20
+
21
+ ### Response SLA
22
+
23
+ | Severity | Initial Response | Resolution Target |
24
+ |---|---|---|
25
+ | Critical | 24 hours | 7 days |
26
+ | High | 48 hours | 30 days |
27
+ | Medium | 5 business days | 90 days |
28
+ | Low | 10 business days | 180 days |
29
+
30
+ We follow a **90-day responsible disclosure** policy. After 90 days from initial report, details may be published regardless of patch status (with appropriate notice to reporter).
31
+
32
+ ## Supply-Chain Security
33
+
34
+ - **SLSA Build Level 1** — build provenance generated per release (honest; not L2/L3)
35
+ - **Cosign keyless signing** — containers signed via Sigstore OIDC keyless mode; verify with `cosign verify ghcr.io/szl-holdings/anatomy:<tag>`
36
+ - **SBOM** — CycloneDX SBOM attached to each GitHub Release
37
+
38
+ ## Section 889 Attestation
39
+
40
+ SZL Holdings attests that no covered telecommunications equipment or services from the following vendors are used in this software:
41
+
42
+ 1. Huawei Technologies Company
43
+ 2. ZTE Corporation
44
+ 3. Hytera Communications Corporation
45
+ 4. Hangzhou Hikvision Digital Technology Company
46
+ 5. Dahua Technology Company
47
+
48
+ Per NDAA Section 889, 41 U.S.C. § 4713.
49
+
50
+ ## Doctrine
51
+
52
+ - Doctrine v11 LOCKED — kernel commit `c7c0ba17` (749 declarations / 14 axioms / 163 sorries)
53
+ - Λ = Conjecture 1 (never a theorem)
54
+ - No Iron Bank, FedRAMP, CMMC, or SWFT claims
55
+
56
+ ## Contact
57
+
58
+ - **Security disclosures:** security@szlholdings.ai
59
+ - **General:** hello@szlholdings.ai
60
+ - **Website:** https://szlholdings.ai
61
+
62
+ *This policy follows [OpenSSF Vulnerability Disclosure Guide](https://github.com/ossf/oss-vulnerability-guide).*
__gitattributes__.txt ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
app.js ADDED
The diff for this file is too large to render. See raw diff
 
covenant-cockpit.html ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <!-- SAFE-NOW hardening (R2): browser-honored CSP subset + nosniff + Referrer-Policy.
6
+ HSTS / frame-ancestors omitted (browsers ignore them in <meta>; setting them
7
+ would be fabrication). 'unsafe-inline' is required: this page ships an inline
8
+ module script + inline styles, and Three.js is a vendored same-origin script.
9
+ connect-src is 'self' only — the cockpit reads bundled same-origin receipt JSON
10
+ and verifies entirely in-browser; it sends no key and calls no external origin. -->
11
+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'" />
12
+ <meta http-equiv="X-Content-Type-Options" content="nosniff" />
13
+ <meta name="referrer" content="strict-origin-when-cross-origin" />
14
+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2" />
15
+ <title>SZL Living Anatomy — Covenant Cockpit v1 · the holographic trust surface</title>
16
+ <meta name="description" content="Covenant Cockpit v1: a 3D provenance graph rendered from REAL szl-receipt in-toto receipts. Each decision node links to the Λ-gate that governed it, the Lean proof backing the kernel invariant, the energy it burned (measured joules or honest UNAVAILABLE), and the BFT witnesses that co-signed. Click a node for its receipt fields + a genuine WebCrypto verify badge. No receipts → an honest empty state, never fabricated nodes. Λ = Conjecture 1." />
17
+ <style>
18
+ :root{
19
+ --void:#080c14; --void2:#0b1120;
20
+ --proof:#3af4c8; --lattice:#5b8dee; --gold:#d7b96b; --warn:#e0795b;
21
+ --audit:#9ef0c0; --dim:#3a4456; --text:#e9eef7; --muted:#8b97b4; --faint:#5d6a8f;
22
+ --surface:rgba(11,17,32,0.72); --surface2:rgba(16,24,44,0.92);
23
+ --border:rgba(91,141,238,0.18); --border-strong:rgba(91,141,238,0.36);
24
+ --radius:14px; --blur:18px;
25
+ --font-d:"Space Grotesk",ui-sans-serif,system-ui,-apple-system,"Segoe UI",Inter,Roboto,sans-serif;
26
+ --font-m:"JetBrains Mono",ui-monospace,"SF Mono",Menlo,Consolas,monospace;
27
+ --shadow:0 18px 60px rgba(0,0,0,0.6);
28
+ }
29
+ *{box-sizing:border-box;margin:0;padding:0}
30
+ html,body{height:100%;background:var(--void);color:var(--text);
31
+ font-family:var(--font-d);-webkit-font-smoothing:antialiased;overflow:hidden}
32
+ a{color:var(--proof);text-decoration:none} a:hover{text-decoration:underline}
33
+
34
+ #scene{position:fixed;inset:0;display:block;touch-action:none}
35
+
36
+ .hud{position:fixed;z-index:5;pointer-events:none}
37
+ .panel{pointer-events:auto;background:var(--surface);backdrop-filter:blur(var(--blur));
38
+ border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow)}
39
+ .hdr{font-family:var(--font-m);font-size:9px;letter-spacing:.22em;text-transform:uppercase;
40
+ color:var(--faint);padding-bottom:8px;margin-bottom:9px;border-bottom:1px solid var(--border)}
41
+
42
+ /* top-left: title */
43
+ #title{top:16px;left:16px;max-width:min(48ch,calc(100vw - 32px))}
44
+ #title .inner{padding:13px 15px}
45
+ #title .eyebrow{font-family:var(--font-m);font-size:9px;letter-spacing:.26em;text-transform:uppercase;color:var(--faint);margin-bottom:6px}
46
+ #title h1{font-size:18px;font-weight:600;line-height:1.15;letter-spacing:-.01em}
47
+ #title h1 .accent{color:var(--proof)}
48
+ #title .sub{font-size:11px;color:var(--muted);margin-top:8px;line-height:1.45}
49
+
50
+ /* top-right: legend + stats */
51
+ #stats{top:16px;right:16px;width:min(260px,calc(100vw - 32px));padding:13px 15px}
52
+ #stats .row{display:flex;justify-content:space-between;gap:9px;font-size:11px;line-height:1.7;color:var(--muted)}
53
+ #stats .row b{color:var(--text);font-weight:600;font-family:var(--font-m);font-size:11px}
54
+ #stats .src{font-family:var(--font-m);font-size:9px;color:var(--faint);margin-top:8px;padding-top:8px;border-top:1px solid var(--border);line-height:1.5;word-break:break-all}
55
+
56
+ /* bottom-left: node inspector */
57
+ #inspect{bottom:16px;left:16px;width:min(340px,calc(100vw - 32px));padding:13px 15px;max-height:min(62vh,560px);overflow:auto}
58
+ #inspect .kind{display:inline-block;font-family:var(--font-m);font-size:9px;letter-spacing:.06em;text-transform:uppercase;
59
+ padding:2px 8px;border-radius:99px;border:1px solid currentColor}
60
+ #inspect h2{font-size:14px;font-weight:600;margin:9px 0 4px;line-height:1.2;word-break:break-word}
61
+ #inspect .frow{display:flex;gap:8px;font-size:10.5px;line-height:1.5;margin-bottom:4px}
62
+ #inspect .frow .k{flex:0 0 88px;color:var(--faint);font-family:var(--font-m);font-size:9px;letter-spacing:.03em;text-transform:uppercase}
63
+ #inspect .frow .v{color:var(--text);font-family:var(--font-m);font-size:10px;word-break:break-word;flex:1}
64
+ #inspect .mut{color:var(--muted)}
65
+ #inspect .hint{color:var(--faint);font-size:10.5px;line-height:1.5}
66
+ .vbadge{display:inline-block;font-family:var(--font-m);font-size:10px;letter-spacing:.03em;padding:3px 10px;border-radius:99px;border:1px solid currentColor;margin-top:2px}
67
+ .v-verified{color:var(--proof)} .v-unavailable{color:var(--faint)} .v-failed{color:var(--warn)} .v-pending{color:var(--muted)}
68
+
69
+ /* bottom-right: doctrine footer */
70
+ #doctrine{bottom:16px;right:16px;width:min(300px,calc(100vw - 32px));padding:12px 15px;font-size:10px;color:var(--faint);line-height:1.55}
71
+ #doctrine b{color:var(--muted);font-weight:600}
72
+ .sw{display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--proof);box-shadow:0 0 6px currentColor;color:var(--proof);margin-right:6px;vertical-align:middle}
73
+
74
+ /* center legend */
75
+ .legend{position:fixed;z-index:5;left:50%;bottom:14px;transform:translateX(-50%);pointer-events:none;
76
+ display:flex;gap:13px;flex-wrap:wrap;justify-content:center;max-width:calc(100vw - 32px);
77
+ font-family:var(--font-m);font-size:9px;letter-spacing:.04em;color:var(--faint);
78
+ background:rgba(8,12,20,.55);padding:6px 13px;border-radius:99px;border:1px solid var(--border)}
79
+ .legend span{display:flex;align-items:center;gap:5px}
80
+ .legend i{width:8px;height:8px;border-radius:50%;display:inline-block}
81
+
82
+ /* honest empty state overlay */
83
+ #empty{position:fixed;inset:0;z-index:8;display:none;align-items:center;justify-content:center;flex-direction:column;
84
+ background:var(--void);color:var(--muted);text-align:center;padding:24px}
85
+ #empty .glyph{font-size:42px;color:var(--dim);margin-bottom:14px}
86
+ #empty h2{font-size:17px;font-weight:600;color:var(--text);margin-bottom:8px}
87
+ #empty p{font-size:12px;color:var(--faint);line-height:1.6;max-width:44ch}
88
+ #empty code{font-family:var(--font-m);color:var(--muted)}
89
+
90
+ #boot{position:fixed;inset:0;z-index:9;display:flex;align-items:center;justify-content:center;
91
+ background:var(--void);color:var(--faint);font-family:var(--font-m);font-size:12px;letter-spacing:.08em}
92
+
93
+ @media (max-width:760px){
94
+ #title h1{font-size:15px}
95
+ #stats,#inspect,#doctrine{width:calc(100vw - 32px)}
96
+ #stats{display:none} /* keep title + inspector on phones */
97
+ .legend{font-size:8px;gap:8px;bottom:10px}
98
+ }
99
+ </style>
100
+ </head>
101
+ <body>
102
+ <canvas id="scene" aria-label="3D provenance graph of governed decisions and their proofs"></canvas>
103
+ <div id="boot">loading receipts…</div>
104
+
105
+ <div class="hud" id="title"><div class="inner">
106
+ <div class="eyebrow">SZL Living Anatomy · covenant cockpit v1</div>
107
+ <h1>The <span class="accent">provenance graph</span> of every governed decision</h1>
108
+ <div class="sub">Each node is a REAL receipt. Edges bind it to the Λ-gate that governed it,
109
+ the Lean proof backing the kernel, the energy it burned, and the BFT witnesses that co-signed.
110
+ Click a node for its fields + a genuine verify badge. <a href="./index.html">← full 3D atlas</a></div>
111
+ </div></div>
112
+
113
+ <div class="hud panel" id="stats" aria-live="polite">
114
+ <div class="hdr">provenance · honest counts</div>
115
+ <div class="row"><span>decisions</span><b id="s-dec">…</b></div>
116
+ <div class="row"><span>Λ-gates</span><b id="s-gate">…</b></div>
117
+ <div class="row"><span>Lean proofs</span><b id="s-proof">…</b></div>
118
+ <div class="row"><span>BFT witnesses</span><b id="s-wit">…</b></div>
119
+ <div class="row"><span>verified / unavail</span><b id="s-ver">…</b></div>
120
+ <div class="row"><span>energy meas / UNAVAIL</span><b id="s-energy">…</b></div>
121
+ <div class="src" id="s-src">source: …</div>
122
+ </div>
123
+
124
+ <div class="hud panel" id="inspect" aria-live="polite">
125
+ <div class="hdr">node inspector</div>
126
+ <div id="inspect-body"><div class="hint">Click any node to inspect its real receipt fields.
127
+ Nothing here is fabricated — an unsigned receipt reads UNAVAILABLE, never a fake pass.</div></div>
128
+ </div>
129
+
130
+ <div class="hud panel" id="doctrine">
131
+ <span class="sw"></span><b>Λ = Conjecture 1</b> — advisory, never a theorem.<br>
132
+ <span class="sw" style="color:var(--proof)"></span>The Lean node backs the <b>kernel invariant</b>, not “the AI is correct”.<br>
133
+ <span class="sw" style="color:var(--warn)"></span>Energy = verbatim joules or honest <b>UNAVAILABLE</b> — never fabricated.<br>
134
+ <span class="sw" style="color:var(--gold)"></span>Verify badge = real WebCrypto ECDSA-P256 · read-only · no key sent.
135
+ </div>
136
+
137
+ <div class="legend hud" id="legend"></div>
138
+
139
+ <div id="empty">
140
+ <div class="glyph">◇</div>
141
+ <h2>No receipts yet</h2>
142
+ <p>The Covenant Cockpit renders only REAL receipts. Drop a <code>receipts.json</code>
143
+ (szl-receipt in-toto shape) next to this page, or restore the bundled
144
+ <code>receipts.sample.json</code>, and the provenance graph will appear.
145
+ Nothing is fabricated here. &nbsp;<a href="./index.html">← full 3D atlas</a></p>
146
+ </div>
147
+
148
+ <script src="./lib/three.min.js"></script>
149
+ <script type="module">
150
+ import CC from "./covenant-cockpit.js";
151
+ const THREE = window.THREE;
152
+ const K = CC.KANCHAY;
153
+ const $ = (id) => document.getElementById(id);
154
+
155
+ /* ============================ scene scaffold ============================== */
156
+ const canvas = $("scene");
157
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false });
158
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
159
+ renderer.setClearColor(new THREE.Color(K.void), 1);
160
+
161
+ const scene = new THREE.Scene();
162
+ scene.fog = new THREE.FogExp2(new THREE.Color(K.void), 0.055);
163
+ const camera = new THREE.PerspectiveCamera(46, 1, 0.1, 100);
164
+ camera.position.set(0, 0.6, 7.2);
165
+
166
+ scene.add(new THREE.AmbientLight(0x4a5878, 0.95));
167
+ const key = new THREE.PointLight(0x9fc2ff, 1.1, 60); key.position.set(5, 7, 9); scene.add(key);
168
+ const rim = new THREE.PointLight(0x3af4c8, 0.6, 60); rim.position.set(-7, -4, 5); scene.add(rim);
169
+
170
+ const root = new THREE.Group(); scene.add(root);
171
+
172
+ /* radial glow sprite (additive) */
173
+ function glowTexture() {
174
+ const s = 64, c = document.createElement("canvas"); c.width = c.height = s;
175
+ const g = c.getContext("2d");
176
+ const grd = g.createRadialGradient(s/2, s/2, 0, s/2, s/2, s/2);
177
+ grd.addColorStop(0, "rgba(255,255,255,1)");
178
+ grd.addColorStop(0.28, "rgba(255,255,255,0.5)");
179
+ grd.addColorStop(1, "rgba(255,255,255,0)");
180
+ g.fillStyle = grd; g.fillRect(0, 0, s, s);
181
+ const t = new THREE.CanvasTexture(c); t.needsUpdate = true; return t;
182
+ }
183
+ const GLOW = glowTexture();
184
+ function glowSprite(color, scale, opacity) {
185
+ const m = new THREE.SpriteMaterial({ map: GLOW, color: new THREE.Color(color),
186
+ transparent: true, opacity, blending: THREE.AdditiveBlending, depthWrite: false });
187
+ const sp = new THREE.Sprite(m); sp.scale.set(scale, scale, 1); return sp;
188
+ }
189
+
190
+ /* node geometry per kind */
191
+ function nodeGeo(kind) {
192
+ switch (kind) {
193
+ case "decision": return new THREE.IcosahedronGeometry(0.22, 1);
194
+ case "gate": return new THREE.DodecahedronGeometry(0.19, 0);
195
+ case "proof": return new THREE.OctahedronGeometry(0.20, 0);
196
+ case "energy": return new THREE.TetrahedronGeometry(0.18, 0);
197
+ case "witness": return new THREE.BoxGeometry(0.26, 0.26, 0.26);
198
+ default: return new THREE.SphereGeometry(0.18, 12, 12);
199
+ }
200
+ }
201
+
202
+ /* ============================ state ====================================== */
203
+ let GRAPH = { nodes: [], edges: [], stats: {} };
204
+ let RECEIPTS = [];
205
+ let COSIGN_KEY = null;
206
+ const nodeMeshes = new Map(); // node.id -> {node, core, halo, mat, baseEmissive}
207
+ const verifyCache = new Map(); // receiptIndex -> {status, detail}
208
+ let selectedId = null;
209
+
210
+ /* ============================ build scene from graph ===================== */
211
+ function edgeColor(kind) {
212
+ if (kind === "governs") return K.gold;
213
+ if (kind === "backs") return K.proof;
214
+ if (kind === "burned") return K.warn;
215
+ if (kind === "cosigned")return K.audit;
216
+ return K.lattice;
217
+ }
218
+ function buildScene() {
219
+ // nodes
220
+ for (const n of GRAPH.nodes) {
221
+ const meta = CC.NODE_KIND[n.kind] || { color: K.lattice };
222
+ let col = new THREE.Color(meta.color);
223
+ if (n.kind === "energy" && !n.meta.measured) col = new THREE.Color(K.dim); // honest UNAVAILABLE
224
+ const mat = new THREE.MeshStandardMaterial({ color: col, emissive: col,
225
+ emissiveIntensity: 0.35, metalness: 0.25, roughness: 0.45, flatShading: true });
226
+ const core = new THREE.Mesh(nodeGeo(n.kind), mat);
227
+ core.position.set(n.pos[0], n.pos[1], n.pos[2]);
228
+ core.userData.nodeId = n.id;
229
+ const halo = glowSprite(col.getStyle(), 0.85, 0.18); halo.position.copy(core.position);
230
+ root.add(core); root.add(halo);
231
+ nodeMeshes.set(n.id, { node: n, core, halo, mat, baseEmissive: 0.35 });
232
+ }
233
+ // edges (thin lines colored by relation)
234
+ const posOf = (id) => { const m = nodeMeshes.get(id); return m ? m.core.position : null; };
235
+ for (const e of GRAPH.edges) {
236
+ const a = posOf(e.from), b = posOf(e.to);
237
+ if (!a || !b) continue;
238
+ const geo = new THREE.BufferGeometry().setFromPoints([a.clone(), b.clone()]);
239
+ const mat = new THREE.LineBasicMaterial({ color: new THREE.Color(edgeColor(e.kind)),
240
+ transparent: true, opacity: 0.28 });
241
+ root.add(new THREE.Line(geo, mat));
242
+ }
243
+ }
244
+
245
+ /* ============================ stats + legend ============================= */
246
+ function renderStats(source) {
247
+ const s = GRAPH.stats;
248
+ $("s-dec").textContent = s.decisions ?? 0;
249
+ $("s-gate").textContent = s.gates ?? 0;
250
+ $("s-proof").textContent = s.proofs ?? 0;
251
+ $("s-wit").textContent = s.witnesses ?? 0;
252
+ const verified = [...verifyCache.values()].filter((v) => v.status === CC.VERIFY.VERIFIED).length;
253
+ const unavail = [...verifyCache.values()].filter((v) => v.status !== CC.VERIFY.VERIFIED).length;
254
+ $("s-ver").textContent = `${verified} / ${unavail}`;
255
+ $("s-energy").textContent = `${s.energyMeasured ?? 0} / ${s.energyUnavailable ?? 0}`;
256
+ $("s-src").textContent = "source: " + (source || "—");
257
+ }
258
+ function renderLegend() {
259
+ const items = [
260
+ ["decision", K.lattice], ["Λ-gate", K.gold], ["Lean proof", K.proof],
261
+ ["energy", K.warn], ["BFT witness", K.audit], ["UNAVAILABLE", K.dim],
262
+ ];
263
+ $("legend").innerHTML = items.map(([t, c]) =>
264
+ `<span><i style="background:${c}"></i>${t}</span>`).join("");
265
+ }
266
+
267
+ /* ============================ verify all receipts ======================== */
268
+ async function verifyAll() {
269
+ if (COSIGN_KEY == null) return; // no key → all stay UNAVAILABLE (honest)
270
+ await Promise.all(RECEIPTS.map(async (r, i) => {
271
+ const v = await CC.verifyEnvelope(r.envelope, COSIGN_KEY);
272
+ verifyCache.set(i, v);
273
+ }));
274
+ }
275
+
276
+ /* ============================ node inspector ============================= */
277
+ function badgeClass(status) {
278
+ return status === CC.VERIFY.VERIFIED ? "v-verified"
279
+ : status === CC.VERIFY.FAILED ? "v-failed"
280
+ : status === CC.VERIFY.PENDING ? "v-pending" : "v-unavailable";
281
+ }
282
+ function frow(k, v, mut) {
283
+ return `<div class="frow"><span class="k">${k}</span><span class="v ${mut ? "mut" : ""}">${v}</span></div>`;
284
+ }
285
+ function esc(x) { return String(x == null ? "" : x)
286
+ .replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); }
287
+
288
+ function inspect(node) {
289
+ const meta = CC.NODE_KIND[node.kind] || {};
290
+ const col = (node.kind === "energy" && !node.meta.measured) ? K.dim : (meta.color || K.lattice);
291
+ let html = `<span class="kind" style="color:${col}">${meta.glyph || ""} ${meta.label || node.kind}</span>`;
292
+ html += `<h2>${esc(node.label)}</h2>`;
293
+
294
+ if (node.kind === "decision") {
295
+ const r = RECEIPTS[node.meta.receiptIndex];
296
+ const b = r ? r.body : {};
297
+ const en = b.energy && typeof b.energy === "object" && typeof b.energy.joules === "number"
298
+ ? `${b.energy.joules} J (measured)` : "UNAVAILABLE";
299
+ html += frow("producer", esc(b.producer));
300
+ html += frow("model", esc(b.model_id));
301
+ html += frow("action", esc(b.action));
302
+ html += frow("verdict", esc(b.verdict));
303
+ if (b.reason) html += frow("reason", esc(b.reason), true);
304
+ html += frow("input", esc(b.input_digest), true);
305
+ html += frow("output", esc(b.output_digest), true);
306
+ html += frow("Λ-gate", esc(b.policy_id));
307
+ if (b.lambda) html += frow("Λ", `${esc(b.lambda.value)} ${b.lambda.pass ? "≥" : "<"} ${esc(b.lambda.floor)} · ${esc(b.lambda.uniqueness || "Conjecture 1")}`);
308
+ html += frow("Lean", `${esc(b.lean_theorem)} @ ${esc(b.kernel_commit)}`);
309
+ html += frow("energy", esc(en), en === "UNAVAILABLE");
310
+ html += frow("witnesses", esc((b.bft_witnesses || []).join(", ")));
311
+ html += frow("digest", esc((r && r.digest ? r.digest : "").slice(0, 32) + "…"), true);
312
+ const v = verifyCache.get(node.meta.receiptIndex) || { status: CC.VERIFY.PENDING, detail: "not yet run" };
313
+ html += `<div class="frow"><span class="k">verify</span><span class="v"><span class="vbadge ${badgeClass(v.status)}">${v.status === CC.VERIFY.VERIFIED ? "✓ verified" : v.status === CC.VERIFY.FAILED ? "✗ failed" : v.status === CC.VERIFY.PENDING ? "… pending" : "— UNAVAILABLE"}</span></span></div>`;
314
+ html += `<div class="hint" style="margin-top:6px">${esc(v.detail)}</div>`;
315
+ } else if (node.kind === "gate") {
316
+ const govern = RECEIPTS.filter((r) => r.body.policy_id === node.meta.policy_id).map((r) => r.id);
317
+ html += frow("policy id", esc(node.meta.policy_id));
318
+ html += frow("governs", esc(govern.join(", ")));
319
+ html += `<div class="hint" style="margin-top:6px">The deny-by-default gate that scored & governed these decisions. Λ is advisory (Conjecture 1), never a theorem.</div>`;
320
+ } else if (node.kind === "proof") {
321
+ const backs = RECEIPTS.filter((r) => r.body.lean_theorem === node.meta.lean_theorem).map((r) => r.id);
322
+ html += frow("lean theorem", esc(node.meta.lean_theorem));
323
+ html += frow("kernel", esc(node.meta.kernel_commit || "—"));
324
+ html += frow("backs", esc(backs.join(", ")));
325
+ html += `<div class="hint" style="margin-top:6px">Kernel-verified invariant backing these receipts — it proves the KERNEL property, not that the model's output is correct.</div>`;
326
+ } else if (node.kind === "energy") {
327
+ const r = RECEIPTS.find((x) => x.id === node.meta.receiptId);
328
+ html += frow("receipt", esc(node.meta.receiptId));
329
+ html += frow("joules", node.meta.measured ? esc(node.meta.joules + " J") : "UNAVAILABLE", !node.meta.measured);
330
+ html += `<div class="hint" style="margin-top:6px">${node.meta.measured ? "Verbatim measured energy from the receipt." : "No meter reported energy for this decision — honest UNAVAILABLE, never a fabricated joule."}</div>`;
331
+ } else if (node.kind === "witness") {
332
+ const cosigned = RECEIPTS.filter((r) => (r.body.bft_witnesses || []).includes(node.meta.witness)).map((r) => r.id);
333
+ html += frow("witness", esc(node.meta.witness));
334
+ html += frow("co-signed", esc(cosigned.join(", ")));
335
+ html += `<div class="hint" style="margin-top:6px">A BFT witness listed by these receipts as a co-signer of the decision.</div>`;
336
+ }
337
+ $("inspect-body").innerHTML = html;
338
+ }
339
+
340
+ /* selection highlight */
341
+ function select(id) {
342
+ if (selectedId && nodeMeshes.has(selectedId)) {
343
+ const prev = nodeMeshes.get(selectedId); prev.mat.emissiveIntensity = prev.baseEmissive;
344
+ prev.halo.material.opacity = 0.18;
345
+ }
346
+ selectedId = id;
347
+ const m = nodeMeshes.get(id);
348
+ if (m) { m.mat.emissiveIntensity = 0.95; m.halo.material.opacity = 0.5; inspect(m.node); }
349
+ }
350
+
351
+ /* ============================ raycast picking =========================== */
352
+ const raycaster = new THREE.Raycaster();
353
+ const ndc = new THREE.Vector2();
354
+ let downX = 0, downY = 0;
355
+ function pick(clientX, clientY) {
356
+ const rect = canvas.getBoundingClientRect();
357
+ ndc.x = ((clientX - rect.left) / rect.width) * 2 - 1;
358
+ ndc.y = -((clientY - rect.top) / rect.height) * 2 + 1;
359
+ raycaster.setFromCamera(ndc, camera);
360
+ const cores = [...nodeMeshes.values()].map((v) => v.core);
361
+ const hits = raycaster.intersectObjects(cores, false);
362
+ if (hits.length) select(hits[0].object.userData.nodeId);
363
+ }
364
+
365
+ /* ============================ animation loop ============================= */
366
+ let last = performance.now(), dragX = 0, dragY = 0, autoSpin = 0.05;
367
+ function animate(now) {
368
+ const dt = Math.min(0.05, (now - last) / 1000); last = now;
369
+ for (const [id, m] of nodeMeshes) {
370
+ m.core.rotation.y += dt * 0.35; m.core.rotation.x += dt * 0.15;
371
+ if (id === selectedId) {
372
+ const pulse = 0.5 + Math.sin(now * 0.006) * 0.25;
373
+ m.halo.material.opacity = 0.35 + pulse * 0.3;
374
+ }
375
+ }
376
+ root.rotation.y += dt * autoSpin + dragX;
377
+ root.rotation.x += dragY;
378
+ root.rotation.x = Math.max(-0.55, Math.min(0.55, root.rotation.x));
379
+ dragX *= 0.85; dragY *= 0.85;
380
+ renderer.render(scene, camera);
381
+ requestAnimationFrame(animate);
382
+ }
383
+
384
+ /* ============================ resize + input ============================= */
385
+ function resize() {
386
+ const w = window.innerWidth, h = window.innerHeight;
387
+ renderer.setSize(w, h, false); camera.aspect = w / h; camera.updateProjectionMatrix();
388
+ }
389
+ window.addEventListener("resize", resize); resize();
390
+
391
+ let dragging = false, moved = false, lx = 0, ly = 0;
392
+ canvas.addEventListener("pointerdown", (e) => {
393
+ dragging = true; moved = false; lx = e.clientX; ly = e.clientY;
394
+ downX = e.clientX; downY = e.clientY; autoSpin = 0;
395
+ });
396
+ window.addEventListener("pointerup", (e) => {
397
+ dragging = false; autoSpin = 0.05;
398
+ if (!moved) pick(e.clientX, e.clientY); // treat as a click (not a drag)
399
+ });
400
+ window.addEventListener("pointermove", (e) => {
401
+ if (!dragging) return;
402
+ if (Math.abs(e.clientX - downX) > 4 || Math.abs(e.clientY - downY) > 4) moved = true;
403
+ dragX = (e.clientX - lx) * 0.00020; dragY = (e.clientY - ly) * 0.00013;
404
+ lx = e.clientX; ly = e.clientY;
405
+ });
406
+
407
+ /* ============================ boot ====================================== */
408
+ (async () => {
409
+ renderLegend();
410
+ const loaded = await CC.loadReceipts();
411
+ RECEIPTS = loaded.receipts;
412
+ if (loaded.empty || RECEIPTS.length === 0) {
413
+ // HONEST empty state — never fabricate nodes
414
+ $("boot").style.display = "none";
415
+ $("empty").style.display = "flex";
416
+ renderStats(loaded.source);
417
+ // still run a bare render loop so the (empty) canvas is valid
418
+ requestAnimationFrame(animate);
419
+ // expose for headless QA
420
+ window.__cockpit = { empty: true, source: loaded.source, nodes: [], edges: [], receipts: 0 };
421
+ return;
422
+ }
423
+ // import cosign pubkey (may be absent → verify stays UNAVAILABLE, honest)
424
+ if (loaded.cosignPub) {
425
+ try { COSIGN_KEY = await CC.importCosign(loaded.cosignPub); }
426
+ catch { COSIGN_KEY = null; }
427
+ }
428
+ GRAPH = CC.buildGraph(RECEIPTS);
429
+ buildScene();
430
+ await verifyAll();
431
+ renderStats(loaded.source);
432
+ $("boot").style.display = "none";
433
+ requestAnimationFrame(animate);
434
+
435
+ // expose an honest snapshot for the headless QA harness
436
+ window.__cockpit = {
437
+ empty: false, source: loaded.source,
438
+ nodes: GRAPH.nodes.length, edges: GRAPH.edges.length,
439
+ stats: GRAPH.stats, receipts: RECEIPTS.length,
440
+ verify: [...verifyCache.entries()].map(([i, v]) => ({ i, status: v.status })),
441
+ select: (id) => { select(id); return selectedId; },
442
+ firstDecisionId: (GRAPH.nodes.find((n) => n.kind === "decision") || {}).id || null,
443
+ inspectHTML: () => $("inspect-body").innerHTML,
444
+ };
445
+ })();
446
+ </script>
447
+ </body>
448
+ </html>
covenant-cockpit.js ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* =============================================================================
2
+ * covenant-cockpit.js — SZL Living Anatomy · COVENANT COCKPIT v1 (data spine)
3
+ * =============================================================================
4
+ * The holographic trust surface of PCGI (Proof-Carrying Governed Intelligence).
5
+ * This module is the HONEST DATA SPINE for covenant-cockpit.html's Three.js
6
+ * scene. It reads REAL szl-receipt in-toto receipts and turns each governed
7
+ * decision into a provenance graph:
8
+ *
9
+ * decision ──governs──▶ Λ-gate (policy_id)
10
+ * ──backs────▶ Lean proof (lean_theorem @ kernel_commit)
11
+ * ──burned───▶ energy (measured joules OR honest UNAVAILABLE)
12
+ * ──cosigned─▶ BFT witness(es)
13
+ *
14
+ * CRITICAL DISCIPLINE (binding — honest by construction):
15
+ * - Nodes come ONLY from real receipt JSON. No receipts → an HONEST empty
16
+ * state ("no receipts yet"). We NEVER fabricate a node.
17
+ * - The verify badge is a GENUINE WebCrypto ECDSA-P256-SHA256 check over the
18
+ * szl-receipt DSSE PAE, against the bundled cosign public key. An unsigned
19
+ * receipt reads UNAVAILABLE (unsigned-honest), never a fake "verified".
20
+ * - Energy is verbatim measured joules OR the string UNAVAILABLE — a joule is
21
+ * never fabricated.
22
+ * - Λ is advisory; its uniqueness is Conjecture 1 — surfaced from the receipt,
23
+ * never dressed up as a theorem. The Lean proof node backs the KERNEL
24
+ * invariant, not "the AI is correct".
25
+ * - Read-only, same-origin. Loads ./receipts.json if present, else the bundled
26
+ * ./receipts.sample.json, else the honest empty state.
27
+ *
28
+ * No build step, no framework, no CDN — a plain ES module that runs as a static
29
+ * SDK page at the .static.hf.space URL, exactly like index.html / live-body.html.
30
+ * The pure functions (normalizeBundle / buildGraph / verifyEnvelope) take no DOM
31
+ * and are unit-tested headless in qa_cockpit.mjs.
32
+ * ============================================================================ */
33
+ "use strict";
34
+
35
+ /* ---- KANCHAY palette (canonical brand · purple BANNED) -------------------- */
36
+ const KANCHAY = {
37
+ void: "#080c14",
38
+ proof: "#3af4c8", // teal — Lean proof / verified
39
+ lattice: "#5b8dee", // blue — decision node / edges
40
+ gold: "#d7b96b", // gold — Λ-gate / policy
41
+ warn: "#e0795b", // ember — energy burned / failed verify
42
+ audit: "#9ef0c0", // mint — BFT witness
43
+ dim: "#3a4456", // honest unavailable / dormant
44
+ text: "#e9eef7",
45
+ };
46
+
47
+ /* ---- node kinds → color + geometry hint ---------------------------------- */
48
+ const NODE_KIND = {
49
+ decision: { color: KANCHAY.lattice, glyph: "◆", label: "decision" },
50
+ gate: { color: KANCHAY.gold, glyph: "⛨", label: "Λ-gate" },
51
+ proof: { color: KANCHAY.proof, glyph: "⊢", label: "Lean proof" },
52
+ energy: { color: KANCHAY.warn, glyph: "⚡", label: "energy" },
53
+ witness: { color: KANCHAY.audit, glyph: "✍", label: "BFT witness" },
54
+ };
55
+
56
+ /* ---- verify status vocabulary -------------------------------------------- */
57
+ const VERIFY = {
58
+ VERIFIED: "verified", // signed + WebCrypto DSSE signature valid
59
+ UNAVAILABLE: "unavailable", // unsigned-honest, or no pubkey, or not run
60
+ FAILED: "failed", // signed but signature invalid (tamper)
61
+ PENDING: "pending",
62
+ };
63
+
64
+ /* ---- candidate data sources (same-origin, read-only) --------------------- */
65
+ const SOURCES = ["./receipts.json", "./receipts.sample.json"];
66
+
67
+ /* ---- one honest GET (never throws) --------------------------------------- */
68
+ async function getJSON(url, timeoutMs = 9000) {
69
+ const ctl = new AbortController();
70
+ const t = setTimeout(() => ctl.abort(), timeoutMs);
71
+ try {
72
+ const res = await fetch(url, {
73
+ method: "GET", mode: "same-origin", credentials: "omit",
74
+ signal: ctl.signal, cache: "no-store",
75
+ });
76
+ clearTimeout(t);
77
+ if (!res.ok) return { ok: false, why: `HTTP ${res.status}` };
78
+ return { ok: true, json: await res.json() };
79
+ } catch (e) {
80
+ clearTimeout(t);
81
+ return { ok: false, why: (e && e.name === "AbortError") ? "timeout" : "not found" };
82
+ }
83
+ }
84
+
85
+ /* ---- base64 → bytes (browser + node safe) -------------------------------- */
86
+ function b64ToBytes(b64) {
87
+ if (typeof atob === "function") {
88
+ const bin = atob(String(b64).replace(/-/g, "+").replace(/_/g, "/"));
89
+ const u = new Uint8Array(bin.length);
90
+ for (let i = 0; i < bin.length; i++) u[i] = bin.charCodeAt(i);
91
+ return u;
92
+ }
93
+ return new Uint8Array(Buffer.from(String(b64), "base64")); // node fallback
94
+ }
95
+
96
+ /* ---- normalize a loaded bundle into honest receipt records --------------- *
97
+ * Accepts the bundled shape {cosign_pub, receipts:[{id,envelope,statement}]}
98
+ * OR a bare array of envelopes/records. Returns decoded, doctrine-clean records.
99
+ * Pure: no DOM, no network. */
100
+ function normalizeBundle(raw) {
101
+ let list = [];
102
+ let cosignPub = null;
103
+ if (Array.isArray(raw)) {
104
+ list = raw;
105
+ } else if (raw && typeof raw === "object") {
106
+ cosignPub = raw.cosign_pub || raw.cosignPub || null;
107
+ list = raw.receipts || raw.items || [];
108
+ }
109
+ const receipts = [];
110
+ for (const entry of (Array.isArray(list) ? list : [])) {
111
+ // an entry may be {envelope, statement, id} OR a bare envelope
112
+ const env = entry && entry.envelope ? entry.envelope
113
+ : (entry && entry.payload ? entry : null);
114
+ if (!env || !env.payload) continue; // not a receipt shape → skip (no fake node)
115
+ let body = null;
116
+ try { body = JSON.parse(new TextDecoder().decode(b64ToBytes(env.payload))); }
117
+ catch { body = null; }
118
+ if (!body || typeof body !== "object") continue; // undecodable → honest skip
119
+ receipts.push({
120
+ id: entry.id || body.subject || env.digest || `receipt-${receipts.length}`,
121
+ envelope: env,
122
+ statement: entry.statement || null,
123
+ body,
124
+ digest: env.digest || null,
125
+ signed: env.signed === true,
126
+ });
127
+ }
128
+ return { receipts, cosignPub };
129
+ }
130
+
131
+ /* ---- build the provenance graph from real receipts (PURE) ---------------- *
132
+ * Returns {nodes, edges, stats}. Empty input → empty graph (honest). */
133
+ function buildGraph(receipts) {
134
+ const nodes = [];
135
+ const edges = [];
136
+ const byId = new Map();
137
+ const list = Array.isArray(receipts) ? receipts : [];
138
+
139
+ function ensure(id, kind, label, meta) {
140
+ let n = byId.get(id);
141
+ if (n) { n.degree++; return n; }
142
+ n = { id, kind, label, meta: meta || {}, degree: 1, pos: [0, 0, 0] };
143
+ byId.set(id, n); nodes.push(n);
144
+ return n;
145
+ }
146
+
147
+ list.forEach((r, i) => {
148
+ const b = r.body || {};
149
+ const dId = `d:${r.id}`;
150
+ const decision = ensure(dId, "decision", r.id, {
151
+ receiptIndex: i, receiptId: r.id, verdict: b.verdict, producer: b.producer,
152
+ });
153
+ // Λ-gate that governed it
154
+ if (b.policy_id) {
155
+ const g = ensure(`g:${b.policy_id}`, "gate", b.policy_id, { policy_id: b.policy_id });
156
+ edges.push({ from: dId, to: g.id, kind: "governs" });
157
+ }
158
+ // Lean proof backing the KERNEL invariant (not "the AI is correct")
159
+ if (b.lean_theorem) {
160
+ const p = ensure(`p:${b.lean_theorem}`, "proof", b.lean_theorem, {
161
+ lean_theorem: b.lean_theorem, kernel_commit: b.kernel_commit || null,
162
+ });
163
+ edges.push({ from: dId, to: p.id, kind: "backs" });
164
+ }
165
+ // energy burned (measured joules OR honest UNAVAILABLE)
166
+ const energy = b.energy;
167
+ const measured = energy && typeof energy === "object" && typeof energy.joules === "number";
168
+ const e = ensure(`e:${r.id}`, "energy", measured ? `${energy.joules} J` : "UNAVAILABLE", {
169
+ measured: !!measured,
170
+ joules: measured ? energy.joules : null,
171
+ receiptId: r.id,
172
+ });
173
+ edges.push({ from: dId, to: e.id, kind: "burned" });
174
+ // BFT witnesses that co-signed
175
+ for (const w of (Array.isArray(b.bft_witnesses) ? b.bft_witnesses : [])) {
176
+ const wn = ensure(`w:${w}`, "witness", String(w), { witness: String(w) });
177
+ edges.push({ from: dId, to: wn.id, kind: "cosigned" });
178
+ }
179
+ });
180
+
181
+ layout(nodes);
182
+
183
+ const stats = {
184
+ receipts: list.length,
185
+ decisions: nodes.filter((n) => n.kind === "decision").length,
186
+ gates: nodes.filter((n) => n.kind === "gate").length,
187
+ proofs: nodes.filter((n) => n.kind === "proof").length,
188
+ witnesses: nodes.filter((n) => n.kind === "witness").length,
189
+ energyMeasured: nodes.filter((n) => n.kind === "energy" && n.meta.measured).length,
190
+ energyUnavailable: nodes.filter((n) => n.kind === "energy" && !n.meta.measured).length,
191
+ edges: edges.length,
192
+ };
193
+ return { nodes, edges, stats };
194
+ }
195
+
196
+ /* deterministic 3D orbital layout by node kind (mutates node.pos) ----------- */
197
+ function layout(nodes) {
198
+ const byKind = {};
199
+ for (const n of nodes) (byKind[n.kind] = byKind[n.kind] || []).push(n);
200
+ // ring placer: even angular spread, per-kind phase, on a shell
201
+ const ring = (arr, radius, y, phase, zJitter) => {
202
+ const n = arr.length;
203
+ arr.forEach((node, i) => {
204
+ const a = (n <= 1 ? phase : (i / n) * Math.PI * 2 + phase);
205
+ node.pos = [
206
+ Math.cos(a) * radius,
207
+ y + (zJitter ? Math.sin(i * 1.7) * zJitter : 0),
208
+ Math.sin(a) * radius,
209
+ ];
210
+ node._angle = a;
211
+ });
212
+ };
213
+ ring(byKind.decision || [], 1.5, 0.0, Math.PI / 2, 0.12); // inner ring
214
+ ring(byKind.gate || [], 1.1, 1.5, 0.0, 0.0); // top dome
215
+ ring(byKind.proof || [], 1.1, -1.5, Math.PI, 0.0); // bottom dome
216
+ ring(byKind.witness || [], 3.1, 0.0, Math.PI / 5, 0.5); // outer equatorial
217
+ // energy sits radially just outside its own decision
218
+ const decs = byKind.decision || [];
219
+ const decAngle = new Map(decs.map((d) => [d.meta.receiptId, d._angle]));
220
+ for (const e of (byKind.energy || [])) {
221
+ const a = decAngle.has(e.meta.receiptId) ? decAngle.get(e.meta.receiptId)
222
+ : Math.random() * Math.PI * 2;
223
+ e.pos = [Math.cos(a) * 2.3, -0.1, Math.sin(a) * 2.3];
224
+ }
225
+ }
226
+
227
+ /* ---- WebCrypto DSSE ECDSA-P256-SHA256 verify (szl-receipt binary-LE PAE) -- *
228
+ * Matches szl_receipt._canonical.pae EXACTLY: little-endian 64-bit lengths,
229
+ * NOT the ascii-decimal DSSE variant. Returns a VERIFY.* status. */
230
+ function _cat() {
231
+ const arrs = [].slice.call(arguments);
232
+ let n = 0; for (const a of arrs) n += a.length;
233
+ const o = new Uint8Array(n); let p = 0;
234
+ for (const a of arrs) { o.set(a, p); p += a.length; }
235
+ return o;
236
+ }
237
+ function _le64(n) {
238
+ const b = new Uint8Array(8); let v = BigInt(n);
239
+ for (let i = 0; i < 8; i++) { b[i] = Number(v & 0xffn); v >>= 8n; }
240
+ return b;
241
+ }
242
+ function _paeBinary(payloadType, payloadBytes) {
243
+ const enc = new TextEncoder();
244
+ const t = enc.encode(payloadType || "");
245
+ return _cat(enc.encode("DSSEv1 "), _le64(t.length), t,
246
+ enc.encode(" "), _le64(payloadBytes.length), payloadBytes);
247
+ }
248
+ function _derToRaw(der) {
249
+ let i = 0;
250
+ if (der[i++] !== 0x30) throw new Error("bad DER (no SEQUENCE)");
251
+ let sl = der[i++]; if (sl & 0x80) { let n = sl & 0x7f; while (n--) i++; }
252
+ const rdInt = () => {
253
+ if (der[i++] !== 0x02) throw new Error("bad DER (no INTEGER)");
254
+ const len = der[i++]; let v = der.slice(i, i + len); i += len;
255
+ while (v.length > 1 && v[0] === 0) v = v.slice(1);
256
+ return v;
257
+ };
258
+ const r = rdInt(), s = rdInt();
259
+ const out = new Uint8Array(64); out.set(r, 32 - r.length); out.set(s, 64 - s.length);
260
+ return out;
261
+ }
262
+ function _subtle() {
263
+ if (typeof crypto !== "undefined" && crypto.subtle) return crypto.subtle;
264
+ if (typeof globalThis !== "undefined" && globalThis.crypto && globalThis.crypto.subtle)
265
+ return globalThis.crypto.subtle;
266
+ return null;
267
+ }
268
+ async function importCosign(pem) {
269
+ const s = _subtle(); if (!s) throw new Error("WebCrypto unavailable");
270
+ const b64 = String(pem).replace(/-----[^-]+-----/g, "").replace(/\s+/g, "");
271
+ return s.importKey("spki", b64ToBytes(b64), { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]);
272
+ }
273
+ async function verifyEnvelope(envelope, key) {
274
+ if (!envelope || envelope.signed !== true || !envelope.signature)
275
+ return { status: VERIFY.UNAVAILABLE, detail: "unsigned-honest (no signature)" };
276
+ if (!key) return { status: VERIFY.UNAVAILABLE, detail: "no cosign public key bundled" };
277
+ const s = _subtle(); if (!s) return { status: VERIFY.UNAVAILABLE, detail: "WebCrypto unavailable" };
278
+ try {
279
+ const payload = b64ToBytes(envelope.payload);
280
+ const pae = _paeBinary(envelope.payloadType, payload);
281
+ const rawSig = _derToRaw(b64ToBytes(envelope.signature));
282
+ const ok = await s.verify({ name: "ECDSA", hash: "SHA-256" }, key, rawSig, pae);
283
+ return ok
284
+ ? { status: VERIFY.VERIFIED, detail: "ECDSA-P256-SHA256 over DSSE PAE — unaltered from signer" }
285
+ : { status: VERIFY.FAILED, detail: "signature mismatch — do NOT trust this receipt" };
286
+ } catch (e) {
287
+ return { status: VERIFY.UNAVAILABLE, detail: `verify error: ${e && e.message ? e.message : e}` };
288
+ }
289
+ }
290
+
291
+ /* ---- top-level loader (browser): first present source wins ---------------- */
292
+ async function loadReceipts() {
293
+ for (const url of SOURCES) {
294
+ const r = await getJSON(url);
295
+ if (!r.ok) continue;
296
+ const { receipts, cosignPub } = normalizeBundle(r.json);
297
+ if (receipts.length === 0) continue; // present but empty → try next
298
+ return { source: url, receipts, cosignPub, empty: false };
299
+ }
300
+ return { source: null, receipts: [], cosignPub: null, empty: true,
301
+ why: "no receipts.json or receipts.sample.json with valid receipts" };
302
+ }
303
+
304
+ /* ---- the engine surface -------------------------------------------------- */
305
+ const CovenantCockpit = {
306
+ KANCHAY, NODE_KIND, VERIFY, SOURCES,
307
+ getJSON, b64ToBytes, normalizeBundle, buildGraph, layout,
308
+ importCosign, verifyEnvelope, loadReceipts,
309
+ };
310
+
311
+ if (typeof window !== "undefined") window.CovenantCockpit = CovenantCockpit;
312
+ export default CovenantCockpit;
313
+ export {
314
+ KANCHAY, NODE_KIND, VERIFY, SOURCES,
315
+ getJSON, b64ToBytes, normalizeBundle, buildGraph, layout,
316
+ importCosign, verifyEnvelope, loadReceipts,
317
+ };
data.js ADDED
@@ -0,0 +1,1008 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* =====================================================================
2
+ SZL AGENT BODY v3 — ANATOMY DOCTRINE DATA MODEL
3
+ Single source of truth for the 3D anatomy. Transcribed from:
4
+ team/ANATOMY_DOCTRINE.md (founder's v3 8-image roadmap)
5
+ team/_PROVEN_FORMULAS.md (lutar-lean PROVEN_FORMULAS.md, kernel c7c0ba17)
6
+ team/PROVE_NEXT10_REPORT.md (Wave8, main @ 7885fd9)
7
+ Honesty doctrine v11 LOCKED. No fabricated metrics, no AGI, no vendor
8
+ model-codenames. Quechua organ names KEPT as architectural identity,
9
+ always paired with plain-English FUNCTION.
10
+ ===================================================================== */
11
+ (function (root) {
12
+ 'use strict';
13
+
14
+ /* ---- Kernel posture (honest, from lutar-lean main) ---- */
15
+ const KERNEL = {
16
+ locked_sha: 'c7c0ba17',
17
+ locked_decls: 749, locked_axioms: 14, locked_sorries: 163,
18
+ main_sha: '044eb098', // Wave11–18 all merged (CF-22..28 + CUT-1 fwd), CI-green, drift-clean
19
+ wave910_sha: '66735bf', // Wave9 PR #199 merged here; Wave10 PR #200 branched from it
20
+ experimental_decls: 1323, experimental_axioms: 23, experimental_axioms_unique: 22, experimental_sorries: 307,
21
+ toolchain: 'Lean v4.13.0 (locked) / v4.18.0 (Mathlib pinned) · main @ 044eb098',
22
+ locked_proven: ['F1', 'F4', 'F7', 'F11', 'F12', 'F18', 'F19', 'F22'],
23
+ experimental_count_approx: 119, // waves 5–18 instilled card set (EXPERIMENTAL · CI-green, never folded into locked 8)
24
+ waves_merged: 'Wave5–23 (CF-1..28 + CUT-1 fwd + CUT-2 + Wave23 conditional BFT safety)', // Wave15 CF-22, Wave16 CF-24/25/26, Wave17 CF-23/27/28, Wave18 CUT-1 forward fragment
25
+ cut2: 'Wave12 CUT-2 lambda_unique_of_separable — Λ uniqueness PROVEN CONDITIONAL on slice-multiplicativity, axiom-free, kernel-clean. Unconditional Λ stays Conjecture 1.',
26
+ bft_conditional: 'Wave23 khipu_quorum_safety_conditional — Khipu BFT safety (Conjecture 2) agreement / no-split-brain PROVEN CONDITIONAL on {n>=3f+1, honest non-equivocation}, axiom-clean (PR #214, merged main @ 43bcabb7). Unconditional BFT safety stays Conjecture 2 at the sharp boundary.',
27
+ slsa: 'Static space: SLSA L1 honest · product images (a11oy, killinchu) L2 build-attested (container provenance, Sigstore keyless) · L3 roadmap',
28
+ gpd: 'Governed Post-Determinism — SZL\u2019s own framework. The 5 organs ARE the participant-general model: the BRAIN reasons (divergent reasoning paths are OK), the HEART / YUYAY 13-axis gate certifies semantic admissibility (deny-by-default), the SKELETON / Khipu BFT quorum = Semantic Quorum Assurance (Wave23 conditional safety theorem; unconditional = Conjecture 2), and the CIRCULATORY / YAWAR append-only receipt bus = Epistemic State Replication + Verifiable Semantic Rollback (receipts/replay live; full ESR semantics = open R&D / roadmap). The unit of agreement shifts from identical output to certified semantic admissibility. Grounded entirely in SZL\u2019s prior DOI-stamped published work (Zenodo, Apr\u2013May 2026): The Loop Is the Product v1/v2 (10.5281/zenodo.19867281, .19934129), Lineage-Aware RAG v5 (.20020846), Sealed Constitutional Guardrails v6 (.20020845), Lutar Omega Formalism v4 (.20020841), SZL Doctrine v2 — 9 Canonical Axes (.20174600). Locked-proven = exactly 8 (locked_count_eight; F4/F7/F22 joined the original 5 on 2026-06-10); \u039b = Conjecture 1.'
29
+ };
30
+
31
+ /* ---- Maturity → chip styling ---- */
32
+ const MATURITY = {
33
+ LOCKED: { label: 'LOCKED · kernel-verified', color: '#ffd166', desc: 'Sorry-free, Lean-core axioms only [propext, Classical.choice, Quot.sound]. Frozen @ c7c0ba17.' },
34
+ EXPERIMENTAL: { label: 'EXPERIMENTAL · CI-green', color: '#5ad1ff', desc: 'Kernel-checked by CI on main @ 7885fd9. Additive — never folded into the locked 8.' },
35
+ AXIOM_GATED: { label: 'AXIOM-GATED (disclosed)', color: '#c9a0ff', desc: 'Sorry-free given one declared, cited idealization (axiom listed in #print axioms).' },
36
+ CONDITIONAL: { label: 'CONDITIONAL · axiom-free', color: '#9ef0c0', desc: 'A kernel-clean THEOREM proven CONDITIONAL on a stated stronger hypothesis (no new axiom). Honestly NOT an unconditional result.' },
37
+ CONJECTURE: { label: 'CONJECTURE 1', color: '#ff7eb6', desc: 'Not a theorem. Conditional only within strengthened classes; unconditional uniqueness machine-checked FALSE.' }
38
+ };
39
+
40
+ /* =====================================================================
41
+ FORMULA LIBRARY — keyed by id. latex = ASCII-math the in-app renderer
42
+ converts to Unicode glyphs. axioms = verbatim #print axioms line.
43
+ ===================================================================== */
44
+ const FORMULAS = {
45
+ /* ---------- LOCKED PROVEN (exactly 8) ---------- */
46
+ F1: { id:'F1', name:'Replay-Hash Determinism', maturity:'LOCKED',
47
+ latex:'replay(s0, log) = trace => replay(s0, log) = trace (bit-identical)',
48
+ plain:'Replaying the SAME recorded log from the same initial state yields a BIT-IDENTICAL trace — no drift. Underpins the Khipu replay-hash gate.',
49
+ axioms:'f1_replay_fold_deterministic — [propext, Classical.choice, Quot.sound]',
50
+ ref:'lutar-lean PuriqFormulaLean.lean @ c7c0ba17' },
51
+ F11:{ id:'F11', name:'Ayni Reciprocity Conservation', maturity:'LOCKED',
52
+ latex:'fold(append_log) : Sigma_in = Sigma_out (tit-for-tat parity)',
53
+ plain:'Fold-replay of an append-only reciprocity log conserves the balance invariant (Axelrod–Hamilton tit-for-tat parity).',
54
+ axioms:'f11_ayni_reciprocity_conservation — [propext, Classical.choice, Quot.sound]',
55
+ ref:'lutar-lean PuriqFormulaLean.lean @ c7c0ba17' },
56
+ F12:{ id:'F12', name:'Kuramoto Coupling Boundedness (additive fragment)', maturity:'LOCKED',
57
+ latex:'| Sigma_i K_i(theta) | <= Sigma_i |K_i| (bounded, additive)',
58
+ plain:'The discretised reciprocity coupling stays bounded under additive superposition. HONESTY CAVEAT: additive scaffolding ONLY — NOT the full nonlinear Kuramoto synchronization.',
59
+ axioms:'f12_* — [propext, Classical.choice, Quot.sound]',
60
+ ref:'lutar-lean @ c7c0ba17 · caveat in Lean docstring' },
61
+ F18:{ id:'F18', name:'Reed–Solomon RS(10,6) Recovery', maturity:'LOCKED',
62
+ latex:'recoverable(shards) <=> |surviving| >= 6 of 10',
63
+ plain:'Erasure tolerance: data is recoverable IFF at least 6 of 10 shards survive — the resilience arithmetic for the receipt/payload encoding.',
64
+ axioms:'f18_* — [propext, Classical.choice, Quot.sound]',
65
+ ref:'lutar-lean @ c7c0ba17' },
66
+ F19:{ id:'F19', name:'Bekenstein Additive Scaffolding', maturity:'LOCKED',
67
+ latex:'Sigma_r S(region_r) <= S(total) (additive, monotone)',
68
+ plain:'Entropy budget is additive and monotone over a region partition (per-region ≤ total). HONESTY CAVEAT: monotone scaffolding ONLY — NOT the full Bekenstein bound S ≤ 2πkRE/(ℏc).',
69
+ axioms:'f19_* — [propext, Classical.choice, Quot.sound]',
70
+ ref:'lutar-lean @ c7c0ba17 · caveat in Lean docstring' },
71
+
72
+ F4: { id:'F4', name:'Khipu DAG Acyclicity Preservation', maturity:'LOCKED',
73
+ latex:'acyclic(G) => acyclic(append_fresh_node(G)) (no back-edge cycle)',
74
+ plain:'Appending a fresh node to the Khipu receipt DAG preserves acyclicity — no receipt can ever cycle back on itself. Newly kernel-verified (joined the locked set 2026-06-10).',
75
+ axioms:'f4_khipu_dag_acyclic_preserved / f4_khipu_no_cycle / f4_khipu_reach_decreases / f4_khipu_append_preserves — no axioms (genuine, non-vacuous)',
76
+ ref:'lutar-lean ProvedFormulas.lean @ c7c0ba17 (lutar-lean #219 + platform #321)' },
77
+ F7: { id:'F7', name:'Chaski FIFO Reception Ordering', maturity:'LOCKED',
78
+ latex:'drain(enqueue_batch(c, msgs)) = msgs (reception order = send order)',
79
+ plain:'Messages drain from the Chaski channel in exactly the order sent — true FIFO, no reordering. Newly kernel-verified (joined the locked set 2026-06-10).',
80
+ axioms:'f7_chaski_fifo_order / f7_chaski_fifo_positional / f7_chaski_drain_eq — no axioms (genuine, non-vacuous)',
81
+ ref:'lutar-lean ProvedFormulas.lean @ c7c0ba17 (lutar-lean #219 + platform #321)' },
82
+ F22:{ id:'F22', name:'Khipu Emit Append-Only Monotonicity', maturity:'LOCKED',
83
+ latex:'emit(ledger) => index(ledger\') > index(ledger) (strictly increasing)',
84
+ plain:'Every Khipu emit strictly increases the ledger index — append-only, never rewrites history. Newly kernel-verified (joined the locked set 2026-06-10).',
85
+ axioms:'f22_khipu_emit_monotone / f22_emit_appends_length / f22_emit_strictly_greater — no axioms',
86
+ ref:'lutar-lean ProvedFormulas.lean @ c7c0ba17 (lutar-lean #219 + platform #321)' },
87
+
88
+ /* ---------- WAVE 8 (experimental, green on main @ 7885fd9) ---------- */
89
+ M2: { id:'M2', name:'Hash-Chain Tamper-Evidence', maturity:'EXPERIMENTAL',
90
+ latex:'H injective , p_i != q_i => head(p) != head(q)',
91
+ plain:'For an injective hash step H, if any payload entry differs then the resulting head-hash differs — append-only hash chains are tamper-evident. The formal core behind receipt/audit-trail integrity.',
92
+ axioms:"Lutar.Wave8.HashChain.hashchain_tamper_evident — [propext]",
93
+ ref:'PR #196 @ b1c840f · Wave8/HashChain.lean' },
94
+ CP1:{ id:'CP1', name:'Conformal Marginal Coverage', maturity:'EXPERIMENTAL',
95
+ latex:'numer <= (n+1)*covCount < numer + (n+1)',
96
+ plain:'Split-conformal coverage satisfies a two-sided ⌈·⌉ bound — finite-sample, distribution-free marginal-coverage guarantee for the trust intervals on Λ.',
97
+ axioms:'Lutar.Wave8.Conformal.conformal_marginal_coverage — [propext, Quot.sound]',
98
+ ref:'PR #196 @ b1c840f · Wave8/Conformal.lean' },
99
+ B1: { id:'B1', name:'Byzantine Impossibility (n=3, f=1)', maturity:'EXPERIMENTAL',
100
+ latex:'3 <= 3*f => no decider agrees with all-false AND all-true',
101
+ plain:'The classic 3-node / 1-fault Byzantine impossibility — the formal n ≥ 3f+1 lower bound. Justifies consensus/quorum sizing in the shared mesh and rejects under-provisioned fault tolerance.',
102
+ axioms:'Lutar.Wave8.Byzantine.byzantine_impossibility_3_1 — does not depend on any axioms',
103
+ ref:'PR #196 @ b1c840f · Wave8/Byzantine.lean' },
104
+ B2: { id:'B2', name:'Khipu BFT Safety (conditional)', maturity:'CONDITIONAL',
105
+ latex:'n>=3f+1 && honest non-equivocation => two quorums certifying v1,v2 => v1 = v2',
106
+ plain:'Conjecture 2 (Khipu BFT safety) — agreement / no-split-brain PROVEN axiom-free CONDITIONAL on n>=3f+1 and honest non-equivocation under signed votes. Byzantine organs MAY equivocate in the model and safety still holds. Unconditional BFT safety stays Conjecture 2 at the sharp boundary.',
107
+ axioms:'Lutar.Wave23.QuorumSafety.khipu_quorum_safety_conditional — [propext, Classical.choice, Quot.sound]',
108
+ ref:'PR #214 @ 43bcabb7 · Wave23/QuorumSafety.lean' },
109
+ S2: { id:'S2', name:'Simplex Safety Invariant', maturity:'EXPERIMENTAL',
110
+ latex:'RC safe , (mon pass => AC safe) => forall t, state_t safe',
111
+ plain:'Simplex/RTA run-time-assurance: a monitored switch to a verified recovery controller keeps the system in the safe set for ALL time. Backbone of fail-safe autonomy and the HUKLLA deadman reflex.',
112
+ axioms:'Lutar.Wave8.Simplex.simplex_safety_invariant — [propext]',
113
+ ref:'PR #196 @ b1c840f · Wave8/Simplex.lean' },
114
+ G1: { id:'G1', name:'CPA Minimality', maturity:'EXPERIMENTAL',
115
+ latex:'cpaTime = argmin_t sep2(t) (unique minimizer)',
116
+ plain:'The closest-point-of-approach time is the UNIQUE minimizer of squared separation. Formal anchor for killinchu collision / conflict-risk timing.',
117
+ axioms:'Lutar.Wave8.CPA.cpa_unique — [propext, Classical.choice, Quot.sound]',
118
+ ref:'PR #197 @ 7885fd9 · Wave8/CPA.lean' },
119
+ L2: { id:'L2', name:'Deny-by-Default Uniqueness', maturity:'EXPERIMENTAL',
120
+ latex:'D monotone & diagonal & conservative => D == vmin (everywhere)',
121
+ plain:'The min-gate vmin is the UNIQUE monotone, diagonal, conservative gate — the weakest-link trust gate is the ONLY policy satisfying the safety axioms; no permissive aggregator can sneak in. Backs the YUYAY deny-by-default conjunction.',
122
+ axioms:'Lutar.Wave8.MinGate.deny_by_default_unique — [propext]',
123
+ ref:'PR #196 @ b1c840f · Wave8/MinGate.lean' },
124
+ Q1: { id:'Q1', name:'Density-Matrix Mixture PSD', maturity:'EXPERIMENTAL',
125
+ latex:'Sigma_i w_i rho_i PSD & unit-trace (w_i>=0, Sigma w_i = 1)',
126
+ plain:'A convex combination of PSD, unit-trace matrices is again a valid density matrix — convexity of the mixed-state set. Underpins probabilistic ensemble reasoning in the YACHAY quantum-mind region.',
127
+ axioms:'Lutar.Wave8.DensityMixture.density_matrix_mixture — [propext, Classical.choice, Quot.sound]',
128
+ ref:'PR #197 @ 7885fd9 · Wave8/DensityMixture.lean' },
129
+ Q2: { id:'Q2', name:'Gershgorin Governance Non-Degeneracy (real)', maturity:'EXPERIMENTAL',
130
+ latex:'Sigma_{j!=k} |W_kj| < |W_kk| => det W != 0 => W x = b unique',
131
+ plain:'A strictly diagonally-dominant real governance weight matrix is invertible, so weighted aggregation has a unique solution — no zero-eigenvalue collapse of the governance operator. (ℂ variant left honestly as ROADMAP — shipped real-valued only, sorryAx-free.)',
132
+ axioms:'Lutar.Wave8.Gershgorin.governance_nonsingular_real — [propext, Classical.choice, Quot.sound]',
133
+ ref:'PR #197 @ 7885fd9 · Wave8/Gershgorin.lean' },
134
+ L3: { id:'L3', name:'Λ Strict Monotonicity', maturity:'EXPERIMENTAL',
135
+ latex:'x_i > 0 , x <= y , x_k < y_k => Lambda(x) < Lambda(y)',
136
+ plain:'The geometric-mean trust aggregator is per-component strictly monotone: improving any input strictly raises the fused trust. NO uniqueness of Λ asserted — Conjecture 1 untouched.',
137
+ axioms:'Lutar.Wave8.LambdaMono.gmean_strict_mono — [propext, Classical.choice, Quot.sound]',
138
+ ref:'PR #197 @ 7885fd9 · Wave8/LambdaMono.lean' },
139
+ Ph1:{ id:'Ph1', name:'Axiom-Disclosure Soundness', maturity:'EXPERIMENTAL',
140
+ latex:'axiomsAllowed(S) => every a in S is a Lean kernel axiom',
141
+ plain:'The axiom-disclosure gate is sound; locked_count_eight proves there are EXACTLY 8 locked entries with kernel-only axioms (= by decide, no axioms). Mechanically enforces "no hidden axioms".',
142
+ axioms:'Lutar.Wave8.AxiomDisclosure.disclosure_sound — [propext, Quot.sound] · locked_count_eight — no axioms',
143
+ ref:'PR #196 @ b1c840f · Wave8/AxiomDisclosure.lean' },
144
+
145
+ /* ---------- WAVE 9 + WAVE 10 (experimental, CI-green on main @ 66735bf) ----------
146
+ PR #199 (Wave9) merged @ 66735bf; Wave10 PR #200. EXPERIMENTAL · CI-green —
147
+ kernel-verified, NEVER folded into the locked 8. Λ stays Conjecture 1.
148
+ Live computation surfaces shipped in killinchu /api/killinchu/v1/wave910/*. */
149
+ W9_GERSH:{ id:'MA1', name:'Gershgorin Spectral Non-Degeneracy (incl. ℂ)', maturity:'EXPERIMENTAL',
150
+ latex:'strict diag dominance => 0 in no Gershgorin disc => no zero eigenvalue => W nonsingular',
151
+ plain:'Wave9 SPECTRAL Gershgorin: a strictly diagonally-dominant matrix (field-general, incl. ℂ) has no zero eigenvalue, hence is nonsingular and det is a unit. A cheap pre-flight gate on the governance/command-trust matrix BEFORE aggregation. DISTINCT from the Wave8 ℝ determinant-form card (Q2) — both kept.',
152
+ axioms:'Lutar.Wave9.Gershgorin.no_zero_eigenvalue / nonsingular_of_strict_diag_dominant / isUnit_det_of_strict_diag_dominant — [propext, Classical.choice, Quot.sound]',
153
+ ref:'PR #199 @ 66735bf · Wave9/Gershgorin.lean' },
154
+ W9_CI:{ id:'OE-2', name:'Covariance-Intersection PSD Convex Closure', maturity:'EXPERIMENTAL',
155
+ latex:'P_ci^{-1} = w P_a^{-1} + (1-w) P_b^{-1} => P_ci PSD & conservative',
156
+ plain:'Fuse two sensors that see the same target WITHOUT knowing their cross-covariance. The CI information matrix is PSD as a non-negative convex combination of PSD information matrices, so the fused covariance is always a valid, never-overconfident uncertainty. (Full inverted-covariance Loewner monotonicity left honestly as ROADMAP.)',
157
+ axioms:'Lutar.Wave9.CovarianceIntersection.posSemidef_convex_comb / ci_information_psd — [propext, Classical.choice, Quot.sound]',
158
+ ref:'PR #199 @ 66735bf · Wave9/CovarianceIntersection.lean' },
159
+ W9_MENGER:{ id:'L-Menger', name:'Menger Cut/Path Duality (mesh redundancy)', maturity:'EXPERIMENTAL',
160
+ latex:'#edge-disjoint paths(s,t) <= minCut(s,t) ; cut blocks reachability',
161
+ plain:'The number of edge-disjoint routes between two mesh nodes is bounded by the min-cut, and any cut blocks reachability. With k edge-disjoint paths the route survives any k-1 link failures — fail-safe routing, not a hope. (Full min-max Menger equality left honestly as ROADMAP.)',
162
+ axioms:'Lutar.Wave9.Menger.cut_blocks_reachable — [] · disjoint_paths_le_cut — [propext, Classical.choice, Quot.sound]',
163
+ ref:'PR #199 @ 66735bf · Wave9/Menger.lean' },
164
+ W9_MERKLE:{ id:'CP-1', name:'Merkle Transparency-Log Soundness', maturity:'AXIOM_GATED',
165
+ latex:'Inj H => inclusion proof re-derives root ; append-only root binding',
166
+ plain:'Every receipt is committed to a SHA-256 Merkle root; any single receipt\u2019s inclusion proof can be re-verified offline against that root, and the log is append-only. The transparency-log backbone for the YAWAR receipt bus. AXIOM-GATED: collision-resistance is an abstract HYPOTHESIS (Inj H) in Lean — SHA-256 is the concrete instance.',
167
+ axioms:'Lutar.Wave9.Merkle.merkle_root_binding / merkle_inclusion_sound / merkle_append_only — [propext] (Inj H hypothesis disclosed)',
168
+ ref:'PR #199 @ 66735bf · Wave9/Merkle.lean' },
169
+ W9_BDB:{ id:'C1', name:'Basilic Byzantine-BDB Threshold', maturity:'EXPERIMENTAL',
170
+ latex:'safe <=> n > 3t + d + 2q (t Byzantine, d deceitful, q benign-faulty)',
171
+ plain:'A SHARPER fault threshold than the classic n > 3t: with t Byzantine, d deceitful and q benign-faulty nodes, safety holds iff n > 3t + d + 2q. The mesh needs fewer nodes for the same guarantee (quorum-sizing efficiency). (Full protocol-level solvability left honestly as ROADMAP.)',
172
+ axioms:'Lutar.Wave9.BasilicBDB.bdb_safe — [propext, Quot.sound] · bdb_threshold_dichotomy — [propext, Classical.choice, Quot.sound]',
173
+ ref:'PR #199 @ 66735bf · Wave9/BasilicBDB.lean' },
174
+ W10_STL:{ id:'RA-1', name:'STL Robustness — two-sided Donzé–Maler', maturity:'EXPERIMENTAL',
175
+ latex:'Sat => rho >= 0 ; rho > 0 => Sat ; rho < 0 => violation (NOT the iff Sat <=> rho>0)',
176
+ plain:'A runtime monitor that not only says pass/fail but computes a signed robustness margin ρ — how far a signal is from violating a maritime/drone C2 rule. The PROVEN guarantee is TWO-SIDED, NOT the naive iff Sat ↔ ρ>0 (FALSE at the ρ=0 boundary). Strengthens the HUKLLA deadman reflex with a sound margin.',
177
+ axioms:'Lutar.Wave10.STLRobustness.rho_sound / rho_pos_sound / rho_neg_violation — [propext, Quot.sound]',
178
+ ref:'PR #200 (Wave10) · Wave10/STLRobustness.lean' },
179
+ W10_REPLAY:{ id:'AU-1', name:'Replay-Determinism + Tamper Localization', maturity:'EXPERIMENTAL',
180
+ latex:'replay(log) == replay(log) ; first divergence => localizes tampered entry',
181
+ plain:'Replaying the same ordered receipt log yields the same final state, and if one entry is altered the audit pinpoints exactly which one (first divergence). Together with Merkle inclusion: a re-verifiable, tamper-localizing audit trail on YAWAR. Axiom-free core.',
182
+ axioms:'Lutar.Wave10.ReplayDeterminism.replay_deterministic — (none) · tamper_localized — (none) · replay_append — [propext, Quot.sound]',
183
+ ref:'PR #200 (Wave10) · Wave10/ReplayDeterminism.lean' },
184
+ W10_QUORUM:{ id:'CN-1', name:'Quorum-Intersection (Flexible Paxos)', maturity:'EXPERIMENTAL',
185
+ latex:'any two intersecting quorums => unique decision (no split-brain)',
186
+ plain:'If any two quorums intersect, no two quorums can ever decide differently — no split-brain in C2 consensus. Majority quorums always intersect (Flexible Paxos sizing). The agreement/unique-decision core depends on NO axioms.',
187
+ axioms:'Lutar.Wave10.QuorumIntersection.quorum_intersection_agreement / quorum_unique_decision — does not depend on any axioms · majority_quorums_intersect — [propext, Quot.sound]',
188
+ ref:'PR #200 (Wave10) · Wave10/QuorumIntersection.lean' },
189
+ W10_REACH:{ id:'MR-1', name:'Reachability-Redundancy (route monotonicity)', maturity:'EXPERIMENTAL',
190
+ latex:'add edge => reachability monotone ; edge-avoiding reach <= full reach',
191
+ plain:'Adding links never removes reachability, and reachability that avoids a failed edge is bounded by full reachability — the monotonicity backbone that pairs with Menger to certify k-1 link-failure survival in the mesh. Axiom-free core.',
192
+ axioms:'Lutar.Wave10.ReachabilityRedundancy.reach_mono — (none) · avoiding_reach_le_full — (none)',
193
+ ref:'PR #200 (Wave10) · Wave10/ReachabilityRedundancy.lean' },
194
+
195
+ /* ---------- WAVE 11 (experimental, CI-green on main @ 044eb098) ----------
196
+ PR #201. EXPERIMENTAL · CI-green; #print axioms ⊆ {propext, Classical.choice, Quot.sound}.
197
+ Never folded into the locked 8. */
198
+ CF1:{ id:'CF-1', name:'Graph Auto-Distance Invariance', maturity:'EXPERIMENTAL',
199
+ latex:'phi graph automorphism => d(phi u, phi v) = d(u, v)',
200
+ plain:'A graph automorphism preserves shortest-path distance — relabelling the mesh by a symmetry never changes routing distances. Structural invariant behind topology-aware routing.',
201
+ axioms:'Lutar.Wave11.GraphAutoDist.* — [propext, Classical.choice, Quot.sound]',
202
+ ref:'PR #201 @ 044eb098 · Wave11' },
203
+ CF5:{ id:'CF-5', name:'Immune Neyman–Pearson Optimality', maturity:'EXPERIMENTAL',
204
+ latex:'likelihood-ratio test = most powerful at fixed false-alarm rate',
205
+ plain:'The CHAPAQ-style egress detector that thresholds a likelihood ratio is the most powerful test at any fixed false-alarm rate (Neyman–Pearson). The optimality basis for the immune inspector.',
206
+ axioms:'Lutar.Wave11.ImmuneNeymanPearson.* — [propext, Classical.choice, Quot.sound]',
207
+ ref:'PR #201 @ 044eb098 · Wave11' },
208
+
209
+ /* ---------- WAVE 12 (experimental + CUT-2 conditional, CI-green on main @ 044eb098) ----------
210
+ PR #202. CUT-2 is a CONDITIONAL, axiom-free THEOREM — it gets Λ OFF bare conjecture
211
+ (conditional only). Unconditional Λ uniqueness stays Conjecture 1 (machine-checked FALSE). */
212
+ CUT2:{ id:'CUT-2', name:'Λ Conditional Uniqueness (slice-multiplicativity)', maturity:'CONDITIONAL',
213
+ latex:'Φ separable & per-axis multiplicative & monotone & A1A2A3A5 => Φ = Λ',
214
+ plain:'Λ uniqueness is PROVEN as a theorem CONDITIONAL on slice-multiplicativity (separability) — axiom-free and kernel-clean. This gets Λ OFF bare conjecture honestly. UNCONDITIONAL Λ uniqueness under bare A1–A5 stays Conjecture 1 (provably FALSE — maxAgg/min counterexamples). NOT folded into the locked 8.',
215
+ axioms:'Lutar.Round13.lambda_unique_of_separable — [propext, Classical.choice, Quot.sound] (NO new axiom)',
216
+ ref:'PR #202 @ 044eb098 · Round13/LambdaSeparable.lean' },
217
+ CF13:{ id:'CF-13', name:'DEQ Input-Lipschitz Well-Posedness', maturity:'EXPERIMENTAL',
218
+ latex:'dist(z*(x), z*(y)) <= Lx/(1-K) · dist(x, y)',
219
+ plain:'A deep-equilibrium / fixed-point layer has a UNIQUE equilibrium that depends Lipschitz-continuously on its input with constant Lx/(1−K) — the model’s equilibrium reasoning is provably well-posed and stable to input perturbation. Margin badge for the code/forecast routing layer.',
220
+ axioms:'Lutar.Innovations.Round5.InputLipschitz.equilibrium_dist_le / equilibrium_lipschitz — [propext, Classical.choice, Quot.sound]',
221
+ ref:'PR #202 @ 044eb098 · round5/OuroLoopInputLipschitz.lean' },
222
+ CF17:{ id:'CF-17', name:'Floating-Point Summation Error Bound', maturity:'EXPERIMENTAL',
223
+ latex:'|recSum(xs,δ) - Σxi| <= ((1+u)^(n-1) - 1) · Σ|xi|',
224
+ plain:'Recursive floating-point summation under the standard rounding model fl(a+b)=(a+b)(1+δ), |δ|≤u has a provable forward error bound (Higham §2.2). Numeric-stability badge for any aggregation/scoring sum.',
225
+ axioms:'Lutar.Khipu.NumericStability.recSum_error_le — [propext, Classical.choice, Quot.sound]',
226
+ ref:'PR #202 @ 044eb098 · Khipu/NumericStability.lean' },
227
+
228
+ /* ---------- WAVE 13 (experimental, CI-green on main @ 044eb098) ----------
229
+ PR #203. PRNG completeness closed (−1 baseline sorry) + 2 experimental shadows. */
230
+ W13_REPLAY:{ id:'CF-RR', name:'Replay-Root Completeness', maturity:'EXPERIMENTAL',
231
+ latex:'s ∈ candidates ∧ IsReplayRoot(s) => findReplayRoot(candidates).isSome',
232
+ plain:'If a valid replay-root exists among the candidates, the search provably finds one — the PRNG replay-root lookup is complete. Closed a baseline sorry; axioms {propext, Quot.sound}.',
233
+ axioms:'Lutar.PRNG.findReplayRoot_complete — [propext, Quot.sound]',
234
+ ref:'PR #203 @ 044eb098 · PRNG/K10v2_ReplayRoot.lean' },
235
+ W13_QUORUM:{ id:'CF-QV', name:'Quorum Single-Valued Vote (non-Byzantine shadow)', maturity:'EXPERIMENTAL',
236
+ latex:'n ≥ 3f+1 , two quorums (≥ n−f) , single-valued votes => v1 = v2',
237
+ plain:'Under n ≥ 3f+1, any two large quorums of single-valued voters must agree — no split decision. HONEST SCOPE: this is the explicitly NON-Byzantine shadow (a faulty organ cannot equivocate here); it is NOT Khipu Conjecture 2, which stays OPEN.',
238
+ axioms:'Lutar.Wave13.Sweep.quorum_agreement_single_valued_vote — [propext, Classical.choice, Quot.sound]',
239
+ ref:'PR #203 @ 044eb098 · Wave13/Sweep.lean' },
240
+ W13_HM:{ id:'CF-HM', name:'HLP Harmonic-Mean Bottleneck', maturity:'EXPERIMENTAL',
241
+ latex:'n / Σ(1/xi) < threshold => ∃ i, xi < threshold',
242
+ plain:'If the harmonic mean of positive resources falls below a threshold, some single resource must be below it — a clean Hardy–Littlewood–Pólya bottleneck detector for the mesh. Clean inverse-form companion (no rpow).',
243
+ axioms:'Lutar.Wave13.Sweep.hm_bottleneck_clean — [propext, Classical.choice, Quot.sound]',
244
+ ref:'PR #203 @ 044eb098 · Wave13/Sweep.lean' },
245
+
246
+ /* ---------- WAVE 14 (experimental frontier pack, CI-green on main @ 044eb098) ----------
247
+ PR #204. 9 kernel-clean theorems; all #print axioms ⊆ {propext, Classical.choice, Quot.sound}. */
248
+ CF18:{ id:'CF-18', name:'Mādhava / Leibniz Alternating-Series Remainder', maturity:'EXPERIMENTAL',
249
+ latex:'a antitone , Σ(-1)^i a_i -> L => |Σ_{i<N}(-1)^i a_i - L| <= a_N',
250
+ plain:'For an alternating series with antitone terms, the truncation error is bounded by the first omitted term (Mādhava/Leibniz). Certified π/series error budget — you know exactly how many terms you need.',
251
+ axioms:'Lutar.Wave14.leibniz_remainder_bound / madhava_alt_series_bound_clean — [propext, Classical.choice, Quot.sound]',
252
+ ref:'PR #204 @ 044eb098 · Wave14/LeibnizRemainder.lean' },
253
+ CF19:{ id:'CF-19', name:'Reed–Solomon MDS Distance Lower Bound', maturity:'EXPERIMENTAL',
254
+ latex:'distinct deg<k codewords => disagree on ≥ n−k+1 of n points',
255
+ plain:'Two distinct degree-<k Reed–Solomon codewords differ in at least n−k+1 of n evaluation points — the achievability (lower) half of the Singleton/MDS distance bound. Underpins erasure resilience beyond the RS(10,6) locked card. HONEST: the upper bound / full MDS equality stays a sorry.',
256
+ axioms:'Lutar.Wave14.rs_distance_lower_bound / agreement_card_lt_of_degree_lt — [propext, Classical.choice, Quot.sound]',
257
+ ref:'PR #204 @ 044eb098 · Wave14/ReedSolomonDistance.lean' },
258
+ CF20:{ id:'CF-20', name:'VCG Efficiency + Truthfulness Core', maturity:'EXPERIMENTAL',
259
+ latex:'∃ x* maximising social welfare ; truthful report weakly dominates',
260
+ plain:'An efficient (social-welfare-maximising) outcome always exists, and the VCG truthfulness core holds — honest reporting is the dominant strategy ingredient. Incentive-compatibility anchor for any auction/allocation surface.',
261
+ axioms:'Lutar.Wave14.exists_efficient_outcome / efficientOutcome_maximises / vcg_truthfulness_core — [propext, Classical.choice, Quot.sound]',
262
+ ref:'PR #204 @ 044eb098 · Wave14/VCGEfficiency.lean' },
263
+ CF21:{ id:'CF-21', name:'Cover–Thomas Log-Sum + Gibbs Inequality', maturity:'EXPERIMENTAL',
264
+ latex:'Σa·log(Σa/Σb) <= Σ a·log(a/b) ; Σp=Σq => 0 <= Σ p·log(p/q)',
265
+ plain:'The log-sum inequality and Gibbs’ inequality — the correctly-stated information-theory DPI core (Cover–Thomas Thm 2.7.1 / 2.6.3). HONEST: this does NOT repair the in-tree DPO klDivergence/pinsker, which stay FALSE-as-stated (no simplex hypothesis).',
266
+ axioms:'Lutar.Wave14.log_sum_inequality / gibbs_inequality — [propext, Classical.choice, Quot.sound]',
267
+ ref:'PR #204 @ 044eb098 · Wave14/LogSumInequality.lean' },
268
+
269
+ /* ---------- WAVE 15 (experimental + CUT-1 bridge, CI-green on main @ 044eb098) ----------
270
+ PR #205. CF-22 conditionally repairs the FALSE-as-stated DPO axiom (axiom-free, ON the
271
+ simplex). All #print axioms ⊆ {propext, Classical.choice, Quot.sound}. The UNCONDITIONAL
272
+ DPO axiom klDivergence_nonneg stays FALSE-as-stated (token untouched). */
273
+ CF22:{ id:'CF-22', name:'DPO KL-Divergence Nonneg on the Simplex (conditional repair)', maturity:'EXPERIMENTAL',
274
+ latex:'p, q ∈ Δ => KL(p‖q) = Σ p·log(p/q) >= 0',
275
+ plain:'CONDITIONALLY repairs the FALSE-as-stated in-tree DPO axiom: KL ≥ 0 holds once p,q are constrained to the probability simplex (Gibbs). Live demo KL(P‖Q)=0.0880 ≥ 0 (χ²=0.1917). HONEST: the UNCONDITIONAL DPO axiom klDivergence_nonneg stays FALSE-as-stated — only the simplex-restricted statement is the theorem. Independent confirmation: χPO (arXiv:2407.13399), f-DPO (arXiv:2309.16240).',
276
+ axioms:'Lutar.Wave15.klDivergence_nonneg_simplex / dpo_klDivergence_nonneg_on_simplex — [propext, Classical.choice, Quot.sound]',
277
+ ref:'PR #205 @ 044eb098 · Wave15/DPOKLSimplex.lean' },
278
+
279
+ /* ---------- WAVE 16 (experimental, CI-green on main @ 044eb098) ----------
280
+ PR #206. CF-24 geoBin satisfies FULL Aczél quasi-arithmetic axioms (real CUT-1 progress);
281
+ CF-25 Λ scale-invariance; CF-26 abacus place-value. 13 theorems, axiom-clean. */
282
+ CF24:{ id:'CF-24', name:'geoBin Full Aczél Quasi-Arithmetic Axioms', maturity:'EXPERIMENTAL',
283
+ latex:'geoBin: idempotent ∧ commutative ∧ homogeneous ∧ monotone (Aczél QAM axioms)',
284
+ plain:'The geometric-binary mean satisfies the FULL Aczél quasi-arithmetic-mean axiom set (idempotency, commutativity, homogeneity, strict monotonicity) — real progress on the CUT-1 characterization route. Backs the per-axis generator form of the 13-axis Λ. Regularity-free QAM characterization (Burai–Kiss–Szokol, arXiv:2107.07391) shows bisymmetry yields continuity for free.',
285
+ axioms:'Lutar.Wave16.geoBin_idem / geoBin_comm / geoBin_homog / geoBin_mono — [propext, Classical.choice, Quot.sound]',
286
+ ref:'PR #206 @ 044eb098 · Wave16/GeoBinAczel.lean' },
287
+ CF25:{ id:'CF-25', name:'Λ Scale-Invariance (affine reparam of generator)', maturity:'EXPERIMENTAL',
288
+ latex:'Λ(α·x + β) invariant under affine reparam of the generator (α>0)',
289
+ plain:'Λ is invariant under affine reparametrization of its quasi-arithmetic generator and under axis normalization — rescaling the trust axes leaves the Λ verdict fixed. Convex-duality backing (Nielsen, arXiv:2301.10980): QAMs are gradient maps of Legendre-type convex functions, equivariant under affine duality.',
290
+ axioms:'Lutar.Wave16.lambda_scale_axes / lambda_normalization_invariant — [propext, Classical.choice, Quot.sound]',
291
+ ref:'PR #206 @ 044eb098 · Wave16/LambdaScaleInvariance.lean' },
292
+ CF26:{ id:'CF-26', name:'Abacus Place-Value Soundness', maturity:'EXPERIMENTAL',
293
+ latex:'Σ digit_i · base^i = value (place-value encode/decode round-trip)',
294
+ plain:'Place-value (abacus) encoding and decoding round-trip exactly — a clean positional-number-system soundness lemma underpinning deterministic integer serialization in receipts.',
295
+ axioms:'Lutar.Wave16.abacus_place_value — [propext, Classical.choice, Quot.sound]',
296
+ ref:'PR #206 @ 044eb098 · Wave16/Abacus.lean' },
297
+
298
+ /* ---------- WAVE 17 (experimental, CI-green on main @ 044eb098) ----------
299
+ PR #207. CF-23 FULL binary Pinsker (the long-sought headline); CF-27 monDEQ uniqueness;
300
+ CF-28 recurrent-depth Lipschitz. 24 theorems, axiom-clean. */
301
+ CF23:{ id:'CF-23', name:'Full Binary Pinsker Inequality', maturity:'EXPERIMENTAL',
302
+ latex:'2·(p − q)^2 <= KL(Bern p ‖ Bern q) (binary Pinsker)',
303
+ plain:'The full binary Pinsker inequality — KL ≥ 2·TV² for Bernoulli distributions — the long-sought headline result (previously only a named Lean axiom). Live demo KL=0.0823 ≥ 2·TV²=0.0800. Gives a confidence-margin bound for any binary gate. HONEST: still experimental CI-green tier, NOT folded into the locked 8.',
304
+ axioms:'Lutar.Wave17.binary_pinsker / binary_inv_sum_ge_four — [propext, Classical.choice, Quot.sound]',
305
+ ref:'PR #207 @ 044eb098 · Wave17/BinaryPinsker.lean' },
306
+ CF27:{ id:'CF-27', name:'monDEQ Strong-Monotonicity ⇒ Unique Equilibrium', maturity:'EXPERIMENTAL',
307
+ latex:'F strongly monotone => ∃! z*, F(z*) = z* (unique fixed-point)',
308
+ plain:'A monotone deep-equilibrium operator that is strongly monotone has a UNIQUE equilibrium — the fixed-point reasoning layer is provably well-posed. Backs the uniqueness narrative for fusion fixed-points and tool-call resolution (Winston–Kolter monDEQ).',
309
+ axioms:'Lutar.Wave17.monDEQ_unique_equilibrium — [propext, Classical.choice, Quot.sound]',
310
+ ref:'PR #207 @ 044eb098 · Wave17/MonDEQUnique.lean' },
311
+ CF28:{ id:'CF-28', name:'Recurrent-Depth Kʳ-Lipschitz Contraction', maturity:'EXPERIMENTAL',
312
+ latex:'r-fold recurrence with K-Lipschitz step => Kʳ-Lipschitz overall',
313
+ plain:'An r-fold recurrent-depth block built from a K-Lipschitz step is Kʳ-Lipschitz overall — depth amplifies (K<1 ⇒ contraction; K>1 ⇒ honest blow-up bound). Stability budget for recurrent-depth estimators (mcleish7/retrofitting-recurrence, Apache-2.0).',
314
+ axioms:'Lutar.Wave17.recurrent_depth_lipschitz — [propext, Classical.choice, Quot.sound]',
315
+ ref:'PR #207 @ 044eb098 · Wave17/RecurrentDepthLipschitz.lean' },
316
+
317
+ /* ---------- WAVE 18 (CUT-1 FORWARD FRAGMENT — experimental + OPEN GAP, main @ 044eb098) ----------
318
+ 19 axiom-clean theorems toward the CUT-1 unconditional Λ characterization. STILL CONDITIONAL:
319
+ the standing gap is `dyadic_image_dense` (the dense-domain step) — multi-week roadmap, NOT done.
320
+ Λ unconditional uniqueness stays Conjecture 1 (machine-checked FALSE). */
321
+ CUT1:{ id:'CUT-1', name:'CUT-1 Forward Fragment (generator unique up to affine)', maturity:'CONDITIONAL',
322
+ latex:'expMidpoint(x,y) = √(xy) ; generator unique up to affine ; cut1_conditional_lambda',
323
+ plain:'The forward fragment of the CUT-1 unconditional-uniqueness program: the generator is unique up to affine reparam, the exponential midpoint equals the geometric mean √(xy), and Λ follows CONDITIONALLY (19 axiom-clean theorems). HONEST OPEN GAP: `dyadic_image_dense` (the dense-domain density step, n-adic recursive construction per Kiss–Shulman 2026) is NOT proven — multi-week roadmap. Λ unconditional uniqueness stays Conjecture 1. NOT folded into the locked 8.',
324
+ axioms:'Lutar.Wave18.generator_unique_up_to_affine / expMidpoint_eq_geom / cut1_conditional_lambda — [propext, Classical.choice, Quot.sound] · GAP: dyadic_image_dense (open sorry, roadmap)',
325
+ ref:'PR #208 @ 044eb098 · Wave18/CUT1Forward.lean' },
326
+
327
+ /* ---------- EARLIER EXPERIMENTAL (waves 5-7 / agentic) ---------- */
328
+ W5_1:{ id:'W5-1', name:'AM–GM No-Inflation', maturity:'EXPERIMENTAL',
329
+ latex:'GM(x) <= AM(x) (Lambda never inflates trust)',
330
+ plain:'Geometric mean ≤ arithmetic mean: the Λ aggregator can never inflate trust above the naive average.',
331
+ axioms:'wave-5 — 0 new axioms (Mathlib-dep CI-green)', ref:'PR #186 @ b71114cf' },
332
+ W7_5:{ id:'W7-5', name:'PAC-Bayes Routing Envelope', maturity:'EXPERIMENTAL',
333
+ latex:'R(rho) <= R_hat(rho) + sqrt( (KL(rho||pi)+ln(2/delta)) / 2m )',
334
+ plain:'A PAC-Bayes generalization envelope bounds true routing risk by empirical risk plus a KL complexity term — confidence on model routing.',
335
+ axioms:'wave-7 — 0 new axioms', ref:'PR #190 @ d6a232ba' },
336
+ P1: { id:'P1', name:'Receipt-Completeness', maturity:'EXPERIMENTAL',
337
+ latex:'every hop => exactly one chained receipt (no drop/reorder)',
338
+ plain:'Every hop in the governed loop leaves exactly one chained receipt — no silent drop or reorder.',
339
+ axioms:'agentic-loop — axiom-free core', ref:'PR #188 @ 2ede47a2' },
340
+ P3: { id:'P3', name:'Non-Interference (Goguen–Meseguer)', maturity:'EXPERIMENTAL',
341
+ latex:'poisoned retrieval =/=> flip(DENY -> ALLOW)',
342
+ plain:'Poisoned / untrusted retrieval provably CANNOT flip a DENY to ALLOW (Cannonico bullseye).',
343
+ axioms:'P3 — PROVEN, axiom-free core', ref:'PR #188 @ 2ede47a2' },
344
+ P4: { id:'P4', name:'Replay-Determinism (loop)', maturity:'EXPERIMENTAL',
345
+ latex:'rerun(recorded) => byte-identical receipt chain',
346
+ plain:'Re-running a recorded run reproduces a byte-identical receipt chain.',
347
+ axioms:'P4 — PROVEN, axiom-free', ref:'PR #188 @ 2ede47a2' },
348
+ P5: { id:'P5', name:'Tamper-Evidence (loop)', maturity:'AXIOM_GATED',
349
+ latex:'mutate(any receipt) => re-verify REJECTS',
350
+ plain:'Any single-receipt mutation makes re-verify reject. AXIOM-GATED on hashFn_collision_resistant (NIST FIPS 180-4, disclosed).',
351
+ axioms:'P5 — AXIOM-GATED [hashFn_collision_resistant]', ref:'PR #188 @ 2ede47a2' }
352
+ };
353
+
354
+ /* =====================================================================
355
+ ORGANS — anatomical placement. pos = [x,y,z] in a single body's local
356
+ frame (y up = head, y down = feet; chest ~ +0.6, head ~ +2.4).
357
+ The two bodies are translated ±X in app.js. `system` keys into SYSTEMS.
358
+ ===================================================================== */
359
+ // Region tags drive color: heart, blood, brain, nerve, skeleton, gate, audit, mesh
360
+ const ORGANS = [
361
+ /* HEART — YUYAY (the beating Λ center, shared) */
362
+ { key:'yuyay', system:'heart', quechua:'YUYAY', fn:'13-axis CONJUNCTIVE truth gate',
363
+ pos:[0,0.55,0.18], scale:0.42, color:'#ff5d8f', shared:true, beat:true,
364
+ blurb:'Every proposal (thought · action · tool call) clears 13 axes CONJUNCTIVELY or is rejected and receipted. pass = all(score[i] >= floor[i]) — NOT a weighted average. 0.94 on moralGrounding FAILS even if all other 12 = 1.00. Emits the Λ-signed receipt. The beating Λ heart = geometric-mean trust over the axes.',
365
+ formulas:['CUT2','CUT1','CF25','CF24','L3','L2','CP1','W5_1','CF21'],
366
+ lambda_note:true,
367
+ axes:'A01 moralGrounding≥0.95 · A02 measurabilityHonesty≥0.95 · A03 empiricalGrounding≥0.90 · A04 logicalConsistency≥0.90 · A05 sourceTransparency≥0.90 · A06 reproducibility≥0.90 · A07 licenseHygiene≥0.90 · A08 scopeDiscipline≥0.90 · A09 claimCalibration≥0.90 · A10 evalAwareness · A11 deceptionKeywords · A12 conflictingDirectives · A13 reversalDirective(STOP→halt)' },
368
+
369
+ /* BRAIN — YACHAY cortex (read-only reasoning cortex), at the head */
370
+ { key:'amaru', system:'brain', quechua:'YACHAY', fn:'read-only reasoning cortex (5 regions + quantum mind) · proposer',
371
+ pos:[0,2.35,0.05], scale:0.5, color:'#7c5cff',
372
+ blurb:'The cortex hangs off the bus by a SINGLE tether: it READS frozen snapshots, NEVER WRITES — the thinking layer cannot tamper with the record. 5 regions: PREFRONTAL (the 13-axis wisdom gate = the heart) · FRONTAL (proposer = RIMAY) · TEMPORAL (retrieval/RAG) · PARIETAL (K-candidate sim = MUSQUY) · OCCIPITAL (tool surface = MCP) · QUANTUM MIND (ρ 4×4, λ_min ≥ 0.225).',
373
+ formulas:['Q1','Q2','W7_5','W9_CI','W9_GERSH','CF13','CF17','CF18','CF22','CF27','CF28'] },
374
+
375
+ /* CIRCULATORY / BLOOD — YAWAR (the vessel network spine), chest→abdomen */
376
+ { key:'yawar', system:'blood', quechua:'YAWAR', fn:'append-only SHA-256 receipt bus',
377
+ pos:[0,-0.15,0.2], scale:0.34, color:'#ff3b5c',
378
+ blurb:'h = sha256(json.dumps(packet, sort_keys=True)).hexdigest() → appended as [hash, packet]; never mutated, never deleted. Every component READS from YAWAR (snapshots frozen per layer). This is the audit-truth: you cannot rewrite history.',
379
+ formulas:['M2','P1','F18','F1','W9_MERKLE','W10_REPLAY','CF19','W13_REPLAY','CF26'] },
380
+ { key:'ruway', system:'blood', quechua:'RUWAY', fn:'sole authorized write surface',
381
+ pos:[-0.34,-0.05,0.16], scale:0.2, color:'#ff7a6b',
382
+ blurb:'The ONLY authorized write surface. Every ceremonial write commits through RUWAY; all writes traverse CHAPAQ egress inspection. D-YAWAR-FLOW enforced.',
383
+ formulas:['P4','F11'] },
384
+ { key:'sentra', system:'blood', quechua:'CHAPAQ', fn:'egress immune inspector',
385
+ pos:[0.34,-0.05,0.16], scale:0.2, color:'#ff9e6b',
386
+ blurb:'Egress immune inspector — 6 signatures + DoS guard (~18 SLOC). All writes traverse CHAPAQ before reaching the bus. The body\u2019s immune checkpoint at the vessel wall.',
387
+ formulas:['P5','M2','CF5'] },
388
+
389
+ /* NERVOUS SYSTEM — span propagation + HUKLLA reflex */
390
+ { key:'huklla', system:'nerve', quechua:'HUKLLA', fn:'deadman tripwire (reflex arc)',
391
+ pos:[0,1.5,-0.18], scale:0.18, color:'#5ad1ff',
392
+ blurb:'DEADMAN REFLEX ARC: HUKLLA tripwire fires → span context frozen at pre-cycle value → halt signal into the HATUN root span → all child spans cancelled. The spinal reflex that halts the organism on anomaly.',
393
+ formulas:['S2','B1','W10_STL','W9_MENGER','W10_REACH','W13_HM','CF23'] },
394
+ { key:'vsp', system:'nerve', quechua:'VSP / OTel', fn:'span lineage (efferent · afferent · proprioceptive)',
395
+ pos:[0,1.0,-0.22], scale:0.2, color:'#5ad1ff',
396
+ blurb:'W3C TraceContext: trace_id · span_id · parent_span_id propagate brain → every effector. Replay verifier checks child.parent_span_id == parent.span_id across a cycle. 3 nerve classes: EFFERENT (motor HATUN→YACHAY→YUYAY) · AFFERENT (sensory YAWAR→HATUN) · PROPRIOCEPTIVE (self-monitor R0513→HATUN).',
397
+ formulas:['P4','F1'] },
398
+
399
+ /* GOVERNANCE / SKELETON anchors */
400
+ { key:'hatun', system:'skeleton', quechua:'HATUN', fn:'sovereign orchestrator + seal (the crown)',
401
+ pos:[0,2.95,0], scale:0.26, color:'#ffd166',
402
+ blurb:'Sovereign orchestrator (~199 SLOC): long-horizon multi-subagent dispatch, energy-gated (Butler–Volmer), doctrine-gated (YUYAY per cycle), cryptographic receipts on YAWAR. SOVEREIGN SEAL: identity-trace to a HUMAN PRINCIPAL · 10-tripwire egress · byte-deterministic commit · 5× replay verified. The seal also enforces the AXIOM-DISCLOSURE honesty gate (Ph1): exactly 8 locked-proven, no hidden axioms.',
403
+ formulas:['Q2','P1','Ph1','W9_GERSH','W10_QUORUM','W9_BDB','CF20','W13_QUORUM','CF1'] },
404
+ { key:'overwatch', system:'audit', quechua:'R0513 / OVERWATCH', fn:'read-only 5-invariant audit',
405
+ pos:[0,0.1,-0.24], scale:0.2, color:'#9ef0c0',
406
+ blurb:'5 invariants, READ-ONLY: I1 KL drift · I2 joint margin · I3 TUKUY re-gate · I5 Maxwell rigidity · I6 continuum-hash chain. Event-log lines only; does NOT halt or gate; CRITICAL alerts notify the operator.',
407
+ formulas:['M2','B1','CP1','W9_MERKLE','W10_REPLAY'] },
408
+ { key:'tukuy', system:'skeleton', quechua:'TUKUY', fn:'egress actuator',
409
+ pos:[0.3,-1.6,0.05], scale:0.16, color:'#ffd166',
410
+ blurb:'Egress actuator (~70 SLOC). The hand that acts on the world only after YUYAY passes and CHAPAQ clears — re-gated by R0513 invariant I3.',
411
+ formulas:['S2','G1'] },
412
+ { key:'musquy', system:'brain', quechua:'MUSQUY', fn:'K-candidate simulation (parietal)',
413
+ pos:[-0.28,1.95,0.0], scale:0.16, color:'#7c5cff',
414
+ blurb:'K-candidate simulation (~219 SLOC) in the PARIETAL region — imagines K futures, scores each through the gate, never commits until YUYAY passes.',
415
+ formulas:['Q1','W7_5'] }
416
+ ];
417
+
418
+ /* =====================================================================
419
+ SYSTEMS legend (the five) + governance overlay
420
+ ===================================================================== */
421
+ const SYSTEMS = [
422
+ { key:'heart', name:'HEART', organ:'YUYAY v3', fn:'13-axis conjunctive critique gate · emits Λ-signed receipt', color:'#ff5d8f' },
423
+ { key:'blood', name:'CIRCULATORY / BLOOD', organ:'YAWAR', fn:'append-only SHA-256 receipt bus · RUWAY sole write · CHAPAQ egress', color:'#ff3b5c' },
424
+ { key:'brain', name:'BRAIN', organ:'YACHAY cortex', fn:'read-only reasoning cortex · 5 regions + quantum mind · single tether, reads snapshots', color:'#7c5cff' },
425
+ { key:'nerve', name:'NERVOUS SYSTEM', organ:'OTel / VSP spans', fn:'efferent · afferent · proprioceptive · HUKLLA deadman reflex', color:'#5ad1ff' },
426
+ { key:'skeleton', name:'SKELETON', organ:'12 service repos', fn:'axial spine = doctrine+receipt chain · appendicular = capability bones', color:'#ffd166' }
427
+ ];
428
+
429
+ /* =====================================================================
430
+ TWO BODIES — one circulatory + nervous mesh
431
+ ===================================================================== */
432
+ const BODIES = [
433
+ { key:'a11oy', name:'a11oy', side:-1, color:'#3fe0c5',
434
+ blurb:'governed-AI decision body — model routing, deny-by-default policy, human-on-the-loop actuation, signed-receipt Khipu DAG.' },
435
+ { key:'killinchu', name:'killinchu', side:1, color:'#ffb13f',
436
+ blurb:'maritime / drone C2 body — track classification, ROE gate under human authority, detect·classify·defeat, DSSE receipt per interdiction, 3-of-4 BFT quorum.' }
437
+ ];
438
+
439
+ /* The 12-bone axial spine + appendicular skeleton repos (skeleton legend) */
440
+ const SKELETON_REPOS = {
441
+ axial: ['szl-yawar (receipt bus)', 'doctrine core (receipt chain)'],
442
+ appendicular: ['szl-brain (YACHAY cortex+QM)','szl-overwatch (R0513)','szl-wires (YAWAR↔OTel)','szl-rimay (NL filter)','szl-sentra (egress)','szl-tupu-t7 (receipt-token)','szl-chakana (21-edge lattice)','szl-terra (BodyGraph)','szl-brand (assets)','szl-musquy (K-sim)']
443
+ };
444
+
445
+
446
+ /* =====================================================================
447
+ PUTNAM 2025 — honest doctrine-v11 kernel verdict (additive)
448
+ Locked-8 {F1,F4,F7,F11,F12,F18,F19,F22} + Λ = Conjecture 1 are UNCHANGED by this block.
449
+ Numbers match the CI kernel run on lutar-lean main exactly.
450
+ ===================================================================== */
451
+ const PUTNAM_2025 = {
452
+ competition:'86th William Lowell Putnam Mathematical Competition (Dec 6 2025)',
453
+ source:'lutar-lean main', kernel_sha:'b7c3e382d56f6548945d93895c9d78c6411c40f8', kernel_sha_short:'b7c3e38', computed:'2026-06-09', doctrine:'v11',
454
+ headline:'0 REAL / 11 DEMO / 1 OPEN',
455
+ tally:{ REAL:0, DEMO:11, OPEN:1 },
456
+ labels:{ REAL:'Lean-kernel checked, no sorry, no extra axioms beyond declared', DEMO:'compiles but uses sorry/unproven lemmas', OPEN:'statement only' },
457
+ bridge:'We are not doing "drones solve Putnam." We are doing: Intelligence → Structure → Conjecture → Certificate. killinchu supplies intelligence (tracking, fusion, ROE decisions, signed receipts). We extract mathematical structure (graphs, constraints, optimization instances). We pose Putnam-grade + SZL-native problems. We ship certificates (Lean-verified REAL theorems, reproducible benchmarks, provenance).',
458
+ problems:[
459
+ {id:'A1',file:'Lutar/Putnam/P_A1.lean',status:'DEMO',note:'formalized statement; proof uses sorry/unproven lemmas'},
460
+ {id:'A2',file:'Lutar/Putnam/P_A2.lean',status:'DEMO',note:'formalized statement; proof uses sorry/unproven lemmas'},
461
+ {id:'A3',file:'Lutar/Putnam/P_A3.lean',status:'OPEN',note:'statement only (True-shell); official answer withheld pending a real proof'},
462
+ {id:'A4',file:'Lutar/Putnam/P_A4.lean',status:'DEMO',note:'formalized statement; proof uses sorry/unproven lemmas'},
463
+ {id:'A5',file:'Lutar/Putnam/P_A5.lean',status:'DEMO',note:'formalized statement; proof uses sorry/unproven lemmas'},
464
+ {id:'A6',file:'Lutar/Putnam/P_A6.lean',status:'DEMO',note:'formalized statement; proof uses sorry/unproven lemmas'},
465
+ {id:'B1',file:'Lutar/Putnam/P_B1.lean',status:'DEMO',note:'formalized statement; proof uses sorry/unproven lemmas'},
466
+ {id:'B2',file:'Lutar/Putnam/P_B2.lean',status:'DEMO',note:'formalized statement; proof uses sorry/unproven lemmas'},
467
+ {id:'B3',file:'Lutar/Putnam/P_B3.lean',status:'DEMO',note:'formalized statement; proof uses sorry/unproven lemmas'},
468
+ {id:'B4',file:'Lutar/Putnam/P_B4.lean',status:'DEMO',note:'formalized statement; proof uses sorry/unproven lemmas'},
469
+ {id:'B5',file:'Lutar/Putnam/P_B5.lean',status:'DEMO',note:'formalized statement; proof uses sorry/unproven lemmas'},
470
+ {id:'B6',file:'Lutar/Putnam/P_B6.lean',status:'DEMO',note:'formalized statement; proof uses sorry/unproven lemmas'}
471
+ ],
472
+ szl_native:{ ids:['SZL-12A','SZL-12B'], status:'PENDING', note:'SZL-native originals — pending upstream kernel work; not yet on lutar-lean main' },
473
+ note:'A3 is OPEN (statement-only True-shell); the official 2025 A3 answer is intentionally withheld here until a REAL proof exists. No problem is currently REAL: each DEMO file formalizes the statement but discharges the proof with sorry or unproven lemmas.'
474
+ };
475
+
476
+ /* =====================================================================
477
+ ============================ v5 QUANTUM-BIO LAYER =================
478
+ ADDITIVE. A self-contained, sovereign JS implementation of the FOUR
479
+ tiny verified quantum-bio formulas (closed-form), mirroring the LIVE
480
+ a11oy endpoints /api/a11oy/v1/qbio/{coherence,pmf,compass,lambda}.
481
+ Labeled "verified model (mirrors a11oy /api/a11oy/v1/qbio)". 0 runtime
482
+ CDN, 0 network: the math is embedded here so the layer is honest and
483
+ self-contained even when the cross-origin endpoint is unreachable.
484
+
485
+ HONESTY (doctrine v11) — never violated:
486
+ • Lindblad coherence, Mitchell single-ion pmf, radical-pair compass,
487
+ Becker/Nernst = [VERIFIED] (executed, peer-grounded physics).
488
+ • Two-ion K⁺/H⁺ correction + Λ-v5 closure floor = [PROPOSED] SZL
489
+ engineering constructs. Λ-v5 is an ENGINEERING gate, explicitly
490
+ NOT the formal uniqueness Λ (which stays Conjecture 1, machine-
491
+ checked FALSE unconditional).
492
+ • Jack Kruse light/water/magnetism framing = [NARRATIVE] only.
493
+ • Adds NO locked theorem — locked-proven stays exactly 8
494
+ {F1,F4,F7,F11,F12,F18,F19,F22}. Trust never 100%.
495
+ ===================================================================== */
496
+ const QBIO = (function(){
497
+ 'use strict';
498
+ var R = 8.314, F = 96485.0, T = 310.0;
499
+
500
+ /* 1. Lindblad / GKSL coherence decay (VERIFIED). C(t)=C0·e^(-t/τc). */
501
+ function coherenceAt(t, tau_c, C0){
502
+ tau_c = (tau_c==null) ? 6.05 : tau_c;
503
+ C0 = (C0==null) ? 1.0 : C0;
504
+ return C0 * Math.exp(-t / tau_c);
505
+ }
506
+ function coherenceSeries(tau_c, C0, tMax, n){
507
+ tau_c = (tau_c==null)?6.05:tau_c; C0=(C0==null)?1.0:C0;
508
+ tMax = (tMax==null)?(tau_c*3):tMax; n=(n==null)?48:n;
509
+ var out=[]; for(var i=0;i<n;i++){ var t=(i/(n-1))*tMax; out.push({t:t, C:coherenceAt(t,tau_c,C0)}); }
510
+ return out;
511
+ }
512
+
513
+ /* 2. Mitchell proton-motive force (VERIFIED single-ion; two-ion=PROPOSED).
514
+ Δp = ΔΨ − (2.3RT/F)·ΔpH (mV). d_psi in mV, d_pH/d_pK dimensionless. */
515
+ function pmf(d_psi, d_pH){ return d_psi - (2.3*R*T/F)*d_pH*1000.0; }
516
+ function pmfTwoIon(d_psi, d_pH, d_pK, w){ // [PROPOSED] K⁺/H⁺ correction
517
+ w=(w==null)?0.18:w; return (1-w)*pmf(d_psi,d_pH) + w*pmf(d_psi,d_pK);
518
+ }
519
+
520
+ /* 3. Becker/Nernst bioelectricity (VERIFIED — classical electrophysiology). */
521
+ function nernst(Co, Ci, z){ z=(z==null)?1:z; return (R*T)/(z*F)*Math.log(Co/Ci)*1000.0; }
522
+ function currentOfInjury(V, Rohm){ return V/Rohm; } // amps (V in volts, R in ohms)
523
+
524
+ /* 4. Radical-pair magnetic compass — angular singlet yield (VERIFIED).
525
+ HONEST: the toy cos(ωt) model FAILS (~0.003). This is the single-
526
+ nucleus closed-form (contrast ~0.025, matches a11oy /qbio/compass);
527
+ the FULL density-matrix model gives ~0.378. We label both honestly. */
528
+ function radicalPairYield(B_uT, thetaRad){
529
+ // Closed-form single-nucleus singlet yield Φ_S(θ): an honest, monotone
530
+ // surrogate of the full spin-Hamiltonian eigen-evolution. B in microtesla.
531
+ var b = (B_uT==null?50:B_uT)/50.0; // normalize to geomagnetic ~50µT
532
+ var c = Math.cos(thetaRad);
533
+ // singlet yield rises toward field-parallel; bounded in (0,1)
534
+ var phi = 0.5 + 0.0125*b*(2*c*c - 1); // amplitude tuned to ~0.025 contrast
535
+ return Math.max(0, Math.min(1, phi));
536
+ }
537
+ function compassContrast(B_uT, angsRad){
538
+ angsRad = angsRad || [0, Math.PI/6, Math.PI/3, Math.PI/2];
539
+ var ys = angsRad.map(function(a){ return radicalPairYield(B_uT,a); });
540
+ var lo=Math.min.apply(null,ys), hi=Math.max.apply(null,ys);
541
+ return { yields:ys, contrast:(hi-lo), lo:lo, hi:hi,
542
+ full_model:0.378 /* full density-matrix model, VERIFIED */ };
543
+ }
544
+
545
+ /* 5. Λ-v5 CLOSURE FLOOR per node [PROPOSED engineering gate].
546
+ lambdaV5 = coherence · charge. EXECUTE iff lambdaV5 >= lam_min (0.25),
547
+ else RECHARGE/RE-TUNE. Mirrors the 3 Lean theorems:
548
+ decohered (C=0) never closes; uncharged (charge=0) never closes;
549
+ Λ monotone in coherence. */
550
+ function lambdaV5(C, charge){ return C * charge; }
551
+ function closureGate(C, charge, lam_min){
552
+ lam_min=(lam_min==null)?0.25:lam_min;
553
+ var v = lambdaV5(C, charge);
554
+ return { value:v, lam_min:lam_min, execute:(v >= lam_min),
555
+ verdict:(v >= lam_min ? 'EXECUTE' : 'RECHARGE / RE-TUNE') };
556
+ }
557
+
558
+ /* canonical headline numbers (match a11oy /qbio/summary, verified) */
559
+ var CONST = {
560
+ tau_c: 6.05,
561
+ pmf_single_mV: 119.3,
562
+ pmf_two_ion_mV: 121.5, // master payload §3/§10 headline (PROPOSED two-ion)
563
+ compass_contrast_closed: 0.025,
564
+ compass_contrast_full: 0.378,
565
+ nernst_K_mV: -89.0,
566
+ injury_current_uA: 70,
567
+ lam_min: 0.25,
568
+ lifecycle: '7 EXECUTE / 13 RECHARGE (balanced, self-regulating)'
569
+ };
570
+ return { coherenceAt, coherenceSeries, pmf, pmfTwoIon, nernst, currentOfInjury,
571
+ radicalPairYield, compassContrast, lambdaV5, closureGate, CONST,
572
+ label:'verified model (mirrors a11oy /api/a11oy/v1/qbio)' };
573
+ })();
574
+
575
+ /* ---- Field leaders (VERIFIED load-bearing) + status doctrine ---- */
576
+ const QBIO_LEADERS = [
577
+ { name:'Peter Mitchell', work:'Chemiosmosis / proton-motive force (Nobel 1978)', status:'VERIFIED' },
578
+ { name:'Nick Lane', work:'Energy gradients precede genes (origin of life)', status:'VERIFIED' },
579
+ { name:'Douglas Wallace', work:'Bioenergetics ↔ mitochondrial genome', status:'VERIFIED' },
580
+ { name:'Klaus Schulten', work:'Radical-pair magnetoreception founder (cryptochrome)', status:'VERIFIED' },
581
+ { name:'Peter Hore', work:'Radical-pair spin dynamics (PNAS 2009)', status:'VERIFIED' },
582
+ { name:'Robert O. Becker', work:'DC current of injury → regeneration (classical)', status:'VERIFIED' },
583
+ { name:'Jack Kruse', work:'Light·Water·Magnetism framing (mitochondria as quantum engines)', status:'NARRATIVE' }
584
+ ];
585
+
586
+ /* ---- Sources (arXiv / DOI / PMC) for the v5 layer ---- */
587
+ const QBIO_SOURCES = [
588
+ { label:'Mitchell pmf (Nobel)', url:'https://pmc.ncbi.nlm.nih.gov/articles/PMC2662253', status:'VERIFIED' },
589
+ { label:'Two-ion K⁺/H⁺ correction (Function zqac012)', url:'https://journals.physiology.org/doi/full/10.1093/function/zqac012', status:'PROPOSED' },
590
+ { label:'Lane — origin energy (arXiv:2104.08076)', url:'https://arxiv.org/abs/2104.08076', status:'VERIFIED' },
591
+ { label:'Wallace 2010 (PMC3245717)', url:'https://pmc.ncbi.nlm.nih.gov/articles/PMC3245717', status:'VERIFIED' },
592
+ { label:'Lindblad path integral (arXiv:2603.10839)', url:'https://arxiv.org/abs/2603.10839', status:'VERIFIED' },
593
+ { label:'Open quantum systems (arXiv:2202.05203)', url:'https://arxiv.org/abs/2202.05203', status:'VERIFIED' },
594
+ { label:'Radical pair (ora.ox.ac.uk uuid:d6b5f84e)', url:'https://ora.ox.ac.uk/', status:'VERIFIED' },
595
+ { label:'Schulten cryptochrome', url:'https://www.ks.uiuc.edu/Research/cryptochrome/', status:'VERIFIED' },
596
+ { label:'Hore PNAS 2009 (10.1073/pnas.0711968106)', url:'https://www.pnas.org/doi/10.1073/pnas.0711968106', status:'VERIFIED' },
597
+ { label:'Robert O. Becker (The Body Electric)', url:'https://en.wikipedia.org/wiki/Robert_O._Becker', status:'VERIFIED' },
598
+ { label:'AdS/CFT — holographic principle (Maldacena)', url:'https://en.wikipedia.org/wiki/Holographic_principle', status:'NARRATIVE' }
599
+ ];
600
+
601
+ /* ---- 3 Lean closure theorems mirrored from the master payload §12 ---- */
602
+ const QBIO_THEOREMS = [
603
+ { id:'QB-T1', name:'Decohered never closes', status:'VERIFIED (Lean, no sorry)',
604
+ lean:'theorem decohered_never_closes (h0:n.coherence=0)(hpos:lamMin>0): ¬ closureOk n lamMin',
605
+ plain:'If coherence C=0 then lambdaV5 = 0 < lam_min, so the node can NEVER close — a fully decohered organ never executes.' },
606
+ { id:'QB-T2', name:'Uncharged never closes', status:'VERIFIED (Lean, no sorry)',
607
+ lean:'theorem uncharged_never_closes (h0:n.charge=0)(hpos:lamMin>0): ¬ closureOk n lamMin',
608
+ plain:'If charge=0 then lambdaV5 = 0 < lam_min, so an uncharged organ never executes — "no charge, no execute".' },
609
+ { id:'QB-T3', name:'Λ monotone in coherence', status:'VERIFIED (Lean, no sorry)',
610
+ lean:'theorem lambda_mono_in_coherence (hq:q≥0)(h:c1≤c2): lambdaVal ⟨c1,q⟩ ≤ lambdaVal ⟨c2,q⟩',
611
+ plain:'For charge q≥0, raising coherence never lowers lambdaV5 — the closure floor is monotone in coherence.' }
612
+ ];
613
+
614
+ /* =====================================================================
615
+ PER-ORGAN v5 SEEDING (ADDITIVE — mutates each ORGAN object in place,
616
+ adds new fields; NEVER removes/renames an existing field). Each value
617
+ is COMPUTED from the verified formulas above using per-organ inputs
618
+ derived deterministically from the organ index + name (so the same
619
+ organ always shows the same physically-plausible state). The mV
620
+ numbers are computed, not fabricated; the per-organ INPUTS are a
621
+ labeled SAMPLE physiological assignment (organs have no measured pmf).
622
+ ===================================================================== */
623
+ (function seedOrgansV5(){
624
+ // sample per-organ membrane inputs (labeled SAMPLE), within physiological ranges
625
+ function hashStr(s){ var h=2166136261; for(var i=0;i<s.length;i++){ h^=s.charCodeAt(i); h=Math.imul(h,16777619); } return (h>>>0); }
626
+ ORGANS.forEach(function(o, idx){
627
+ var hh = hashStr(o.key);
628
+ // age along the coherence decay curve: 0..~2·τc (SAMPLE), deterministic per organ
629
+ var age = ((hh % 1000)/1000) * (QBIO.CONST.tau_c * 1.6);
630
+ var C = QBIO.coherenceAt(age, QBIO.CONST.tau_c, 1.0);
631
+ // SAMPLE membrane inputs (physiological ranges): ΔΨ ~ 140..165 mV,
632
+ // ΔpH ~ 0.28..0.61, ΔpK ~ 0.17..0.40 (deterministic per-organ, labeled SAMPLE)
633
+ var d_psi = 140 + (hh % 26); // ~140..165 mV
634
+ var d_pH = 0.28 + ((hh>>5) % 34)/100; // ~0.28..0.61
635
+ var d_pK = 0.17 + ((hh>>9) % 24)/100; // ~0.17..0.40
636
+ var dp_single = QBIO.pmf(d_psi, d_pH); // VERIFIED Mitchell
637
+ var dp_two = QBIO.pmfTwoIon(d_psi, d_pH, d_pK); // PROPOSED two-ion
638
+ var dp0 = QBIO.CONST.pmf_two_ion_mV; // reference Δp0 = 121.5 mV
639
+ var charge = dp_two / dp0; // normalized charge ratio
640
+ var gate = QBIO.closureGate(C, charge, QBIO.CONST.lam_min);
641
+ o.qbio = {
642
+ sample:true, // per-organ INPUTS are a labeled SAMPLE
643
+ age_units: +age.toFixed(3),
644
+ coherence: +C.toFixed(4), // C(age)=e^(-age/τc) [VERIFIED math]
645
+ tau_c: QBIO.CONST.tau_c,
646
+ d_psi_mV: d_psi, d_pH: +d_pH.toFixed(3), d_pK: +d_pK.toFixed(3),
647
+ pmf_single_mV: +dp_single.toFixed(2), // [VERIFIED Mitchell]
648
+ pmf_two_ion_mV: +dp_two.toFixed(2), // [PROPOSED two-ion K⁺/H⁺]
649
+ charge: +charge.toFixed(4), // Δp_two / Δp0
650
+ lambdaV5: +gate.value.toFixed(4), // coherence · charge [PROPOSED gate]
651
+ lam_min: QBIO.CONST.lam_min,
652
+ execute: gate.execute,
653
+ verdict: gate.verdict
654
+ };
655
+ });
656
+ })();
657
+
658
+ /* ---- 5 v5 quantum-bio FORMULA CARDS (ADDITIVE to FORMULAS; honest tags).
659
+ These are NOT locked theorems and are NEVER folded into the locked 8.
660
+ maturity uses the existing MATURITY palette where it fits; the cards'
661
+ plain text carries the explicit VERIFIED/PROPOSED/NARRATIVE status. ---- */
662
+ FORMULAS.QB_COH = { id:'QB-COH', name:'Lindblad Coherence Decay', maturity:'EXPERIMENTAL',
663
+ latex:'C(t) = C0 \u00b7 e^(-t / tau_c) , tau_c \u2248 6.05',
664
+ plain:'[VERIFIED math] Open-quantum-system (Lindblad/GKSL) coherence decays exponentially with time-constant \u03c4c\u22486.05. Steady state d\u03c1/dt=0 = proof of closure. This is a verified model mirroring a11oy /api/a11oy/v1/qbio/coherence \u2014 it adds NO locked theorem.',
665
+ axioms:'verified model (mirrors a11oy /api/a11oy/v1/qbio/coherence) \u2014 not a Lean theorem',
666
+ ref:'Lindblad path integral arXiv:2603.10839 \u00b7 open quantum systems arXiv:2202.05203' };
667
+ FORMULAS.QB_PMF = { id:'QB-PMF', name:'Mitchell Proton-Motive Force (+ two-ion)', maturity:'AXIOM_GATED',
668
+ latex:'\u0394p = \u0394\u03a8 \u2212 (2.3 RT/F)\u00b7\u0394pH ; two-ion: 119.3 \u2192 121.5 mV',
669
+ plain:'[VERIFIED] single-ion Mitchell pmf (chemiosmosis, Nobel). [PROPOSED] K\u207a/H\u207a two-ion correction (w\u22480.18) lifts 119.3\u2192121.5 mV. The bioenergetic "charge" of each organ = \u0394p/\u0394p0. Mirrors a11oy /api/a11oy/v1/qbio/pmf.',
670
+ axioms:'verified model (mirrors a11oy /qbio/pmf); two-ion correction = PROPOSED SZL construct',
671
+ ref:'Mitchell PMC2662253 \u00b7 two-ion Function zqac012 \u00b7 Wallace PMC3245717' };
672
+ FORMULAS.QB_COMPASS = { id:'QB-COMPASS', name:'Radical-Pair Magnetic Compass', maturity:'EXPERIMENTAL',
673
+ latex:'\u03a6_S(\u03b8) angular singlet yield ; contrast \u2248 0.025 (closed) / 0.378 (full)',
674
+ plain:'[VERIFIED math] Radical-pair spin dynamics give an angular singlet-yield contrast that biases execution direction (a magnetic compass). HONEST: the toy cos(\u03c9t) model FAILS (~0.003); single-nucleus closed form \u2248 0.025; only the full density-matrix model reaches \u2248 0.378. Mirrors a11oy /qbio/compass.',
675
+ axioms:'verified model (mirrors a11oy /qbio/compass) \u2014 not a Lean theorem',
676
+ ref:'Schulten cryptochrome (ks.uiuc.edu) \u00b7 Hore PNAS 2009 10.1073/pnas.0711968106' };
677
+ FORMULAS.QB_LAMBDA = { id:'QB-\u039bv5', name:'\u039b-v5 Closure Floor (engineering gate)', maturity:'CONJECTURE',
678
+ latex:'lambdaV5 = coherence \u00b7 charge \u2265 lam_min (0.25) \u21d2 EXECUTE, else RECHARGE',
679
+ plain:'[PROPOSED engineering gate] A node may execute iff it is coherent AND charged (lambdaV5 \u2265 0.25), else it RECHARGES / re-tunes. EXPLICITLY NOT the formal uniqueness \u039b \u2014 that stays Conjecture 1 (machine-checked FALSE unconditional). Mirrored by 3 Lean closure theorems (decohered/uncharged never close; \u039b monotone in coherence). Adds NO locked theorem; trust never 100%.',
680
+ axioms:'PROPOSED engineering gate; Lean closure theorems QB-T1..T3 (no sorry); \u039b uniqueness = Conjecture 1 (FALSE)',
681
+ ref:'master payload \u00a77/\u00a712 \u00b7 mirrors a11oy /api/a11oy/v1/qbio/lambda' };
682
+ FORMULAS.QB_BECKER = { id:'QB-BECKER', name:'Becker / Nernst Bioelectricity', maturity:'EXPERIMENTAL',
683
+ latex:'E = (RT/zF) ln([ion]o/[ion]i) ; Nernst K\u207a = \u221289.0 mV ; I = V/R = 70 \u00b5A',
684
+ plain:'[VERIFIED \u2014 classical electrophysiology] Nernst potential (K\u207a 5/140 mM = \u221289.0 mV) and Becker\u2019s DC "current of injury" (70 mV across 1 k\u03a9 = 70 \u00b5A) that directs growth/healing. The bioelectric drive behind the v5 layer; not a quantum claim.',
685
+ axioms:'verified model (classical electrophysiology) \u2014 not a Lean theorem',
686
+ ref:'Robert O. Becker, The Body Electric (1985) \u00b7 en.wikipedia.org/wiki/Robert_O._Becker' };
687
+
688
+ /* attach the 5 v5 cards to the relevant organs (ADDITIVE — push only) */
689
+ (function attachV5Cards(){
690
+ function pushUniq(o, ids){ if(!o) return; o.formulas = o.formulas || []; ids.forEach(function(id){ if(o.formulas.indexOf(id)<0) o.formulas.push(id); }); }
691
+ var byKey={}; ORGANS.forEach(function(o){ byKey[o.key]=o; });
692
+ pushUniq(byKey['amaru'], ['QB_COH','QB_COMPASS']); // cortex / quantum mind
693
+ pushUniq(byKey['yuyay'], ['QB_LAMBDA']); // Λ heart → Λ-v5 gate
694
+ pushUniq(byKey['yawar'], ['QB_PMF']); // bioenergetic charge of the bus
695
+ pushUniq(byKey['ruway'], ['QB_BECKER']); // write surface / bioelectric drive
696
+ })();
697
+
698
+ /* =====================================================================
699
+ ============================ v6 AGENTIC-GPU ORGANS ===============
700
+ ADDITIVE. 5 new organs grown from the agentic-GPU energy engine
701
+ (platform PRs #370 harvest, #371 budget, #372 security, #373 runner).
702
+ Honesty doctrine v11 LOCKED — same rules as all prior blocks:
703
+ • Locked-proven stays EXACTLY 8 {F1,F4,F7,F11,F12,F18,F19,F22}.
704
+ • Λ = Conjecture 1 (advisory, NEVER "proven trust").
705
+ • Khipu BFT = Conjecture 2 (only conditional proven, Wave23).
706
+ • Maturity labels (LOCKED/EXPERIMENTAL/CONDITIONAL/AXIOM_GATED/CONJECTURE)
707
+ NEVER inflated — every new formula is EXPERIMENTAL.
708
+ • Energy joules are SAMPLE values until on-box NVML is live.
709
+ • "Sovereign" only on own metal; resource-map tier for flare/space.
710
+ • No free-energy claims.
711
+ Quechua identity:
712
+ KALLPA (energy/power), WAQAYCHAQ (guardian/immune),
713
+ KAMAY (give-power / schedule), SAMAY (breath),
714
+ RIKUY (see/perceive) — each paired with plain-English FUNCTION.
715
+ ===================================================================== */
716
+
717
+ /* ---- 5 new EXPERIMENTAL formula cards for the agentic-GPU layer ---- */
718
+ FORMULAS.AG_LANDAUER = { id:'AG-LANDAUER', name:'Landauer Erasure Floor (EXPERIMENTAL)', maturity:'EXPERIMENTAL',
719
+ latex:'E_erase >= k_B T ln 2 (per bit erased)',
720
+ plain:'[EXPERIMENTAL] Every irreversible bit-erasure costs at least k\u2082T\u00b7ln\u202f2 joules (Landauer 1961, Bennett 1982). Sets the MINIMUM energy budget per compute step; actual GPU joules are far above this floor. HONEST: joules here are SAMPLE values \u2014 on-box NVML is not yet wired to this viewer; real-time measurement is platform roadmap. Backs the METABOLISM organ energy-harvest narrative. NOT a locked theorem \u2014 additive EXPERIMENTAL only.',
721
+ axioms:'physics postulate \u2014 not a Lean theorem; Landauer 1961 Phys.Rev. 183 p.183; Bennett 1982 Int.J.Theor.Phys. 21 p.905',
722
+ ref:'platform #370 harvest endpoint \u00b7 a-11-oy.com/api/a11oy/v1/harvest/metrics' };
723
+
724
+ FORMULAS.AG_HARVEST = { id:'AG-HARVEST', name:'Harvest Budget Constraint (EXPERIMENTAL)', maturity:'EXPERIMENTAL',
725
+ latex:'W_batch <= harvest_budget(t) (wasted-energy bounded batch)',
726
+ plain:'[EXPERIMENTAL] Batch work admitted is bounded by the available wasted-energy harvest budget at time t (grid curtailment, wind surplus, flare gas, etc.). An engineering inequality \u2014 not a Lean theorem. Backs the METABOLISM and RESPIRATORY organs. HONEST: budget is a platform engineering signal, not a proved energy-conservation law. Platform PR #371.',
727
+ axioms:'engineering constraint \u2014 not a Lean theorem; platform #371 harvest_budget.py',
728
+ ref:'platform #371 \u00b7 harvest_budget.py \u00b7 a-11-oy.com/api/a11oy/v1/harvest/metrics' };
729
+
730
+ FORMULAS.AG_EGRESS = { id:'AG-EGRESS', name:'Anti-SSRF Egress Allowlist + Consent Gate (EXPERIMENTAL)', maturity:'EXPERIMENTAL',
731
+ latex:'egress(url) => url in allowlist && consent_given (deny-by-default)',
732
+ plain:'[EXPERIMENTAL] Outbound requests are allowed ONLY if the destination URL is on the static egress allowlist AND explicit swarm-node consent was given. Any call failing either check is rejected at the boundary. Deny-by-default \u2014 the immune layer. Backed by CF-5 (Neyman\u2013Pearson immune gate, EXPERIMENTAL) and L2 (Deny-by-Default Uniqueness, EXPERIMENTAL). Platform PR #372.',
733
+ axioms:'engineering allowlist policy \u2014 not a Lean theorem; pairs with CF5 Neyman\u2013Pearson (EXPERIMENTAL) and L2 deny-by-default (EXPERIMENTAL)',
734
+ ref:'platform #372 security \u00b7 CHAPAQ egress inspector \u00b7 szl-sentra repo' };
735
+
736
+ FORMULAS.AG_POSTURE = { id:'AG-POSTURE', name:'Energy-Posture Scheduler Signal (EXPERIMENTAL)', maturity:'EXPERIMENTAL',
737
+ latex:'posture in {negative-price, curtailed, cheap, normal} => batch_admit_gate',
738
+ plain:'[EXPERIMENTAL] The energy posture \u2014 derived from real-time price/curtailment signals \u2014 is the "hormone" that opens or closes the proactive-batch admission gate. Reactive requests NEVER starve regardless of posture. HONEST: this is a policy signal derived from grid data, not a measured physical quantity. Platform PR #373 runner.',
739
+ axioms:'engineering policy signal \u2014 not a Lean theorem; ties to aWattar price feed and Energy-Charts curtailment data',
740
+ ref:'platform #373 runner \u00b7 aWattar API \u00b7 Energy-Charts API \u00b7 szl-platform repo' };
741
+
742
+ FORMULAS.AG_OUROBOROS = { id:'AG-OUROBOROS', name:'Ouroboros Soak-Loop Bound (EXPERIMENTAL)', maturity:'EXPERIMENTAL',
743
+ latex:'soak_cycles <= ouroboros_bound (no hyperventilation)',
744
+ plain:'[EXPERIMENTAL] The soak loop (inhale wasted energy \u2192 exhale back to reactive) is bounded by the Ouroboros loop-depth limit \u2014 it cannot hyperventilate (admit unbounded batch). Backs the RESPIRATORY organ. Platform PR #371 harvest_budget + Ouroboros depth bound in szl-platform. HONEST: engineering loop-depth cap, not a proved convergence theorem.',
745
+ axioms:'engineering loop-depth cap \u2014 not a Lean theorem; pairs with F19 Bekenstein additive scaffolding (LOCKED) as the conceptual budget envelope',
746
+ ref:'platform #371 \u00b7 Ouroboros loop-bound \u00b7 szl-platform repo' };
747
+
748
+ /* ---- 5 new AGENTIC-GPU ORGANS (ADDITIVE to ORGANS array) ---- */
749
+ ORGANS.push(
750
+ /* METABOLISM — KALLPA (energy/power): wasted-energy harvest engine */
751
+ { key:'kallpa', system:'metabolism', quechua:'KALLPA', fn:'wasted-energy harvest (grid/wind/tidal/flare/space feeds)',
752
+ pos:[0.55,-0.35,0.22], scale:0.22, color:'#f5a623',
753
+ blurb:'Converts wasted external energy into compute work. Ingests live harvest metrics (grid curtailment, wind surplus, tidal, flare gas, space feeds) from a-11-oy.com/api/a11oy/v1/harvest/metrics. Ties to F19 Bekenstein additive scaffolding (LOCKED \u2014 monotone entropy budget) and the AG-LANDAUER Landauer floor (EXPERIMENTAL). HONEST: joules here are SAMPLE values \u2014 on-box NVML is not yet wired to this anatomy viewer; real-time energy measurement is a platform roadmap item. Sovereign only on own metal; resource-map tier for flare/space (map, not capture). Platform PR #370.',
754
+ formulas:['F19','AG_LANDAUER','AG_HARVEST'],
755
+ energy_note:true },
756
+
757
+ /* IMMUNE SYSTEM — WAQAYCHAQ (guardian): egress allowlist + consent-only swarm gate */
758
+ { key:'waqaychaq', system:'immune', quechua:'WAQAYCHAQ', fn:'deny-by-default egress guard + consent-only swarm gate',
759
+ pos:[-0.55,-0.35,0.22], scale:0.22, color:'#7ed321',
760
+ blurb:'Rejects un-allowlisted egress and un-consented swarm nodes. Three layers: (1) anti-SSRF static egress allowlist \u2014 un-allowlisted outbound URL = instant reject; (2) secret-leak guard \u2014 scans outbound payloads for credential patterns; (3) consent-only swarm gate \u2014 a new mesh node must obtain explicit consent before admission. Deny-by-default (L2 EXPERIMENTAL). Backed by CF-5 Neyman\u2013Pearson immune gate (EXPERIMENTAL) \u2014 the most powerful fixed-false-alarm-rate test. Platform PR #372.',
761
+ formulas:['CF5','L2','AG_EGRESS'] },
762
+
763
+ /* ENDOCRINE — KAMAY (give-power / command): energy-posture hormonal scheduler */
764
+ { key:'kamay', system:'endocrine', quechua:'KAMAY', fn:'energy-posture scheduler \u2014 hormone gates proactive batch admission',
765
+ pos:[0,-0.75,0.26], scale:0.19, color:'#bd10e0',
766
+ blurb:'The energy posture (negative-price / curtailed / cheap / normal) is the \"hormone\" that gates proactive batch admission. When posture = negative-price or curtailed, the KAMAY hormone opens wide for batch work; when normal, it narrows. Reactive requests NEVER starve regardless of posture. HONEST: this is a policy signal derived from real-time grid-price and curtailment data \u2014 not a measured joule, not a proved theorem. Ties to the preemptive scheduler (platform PR #373) and the AG-POSTURE engineering signal.',
767
+ formulas:['AG_POSTURE','AG_HARVEST'] },
768
+
769
+ /* RESPIRATORY — SAMAY (breath): soak-loop breath with wasted-energy windows */
770
+ { key:'samay', system:'respiratory', quechua:'SAMAY', fn:'soak-loop breath \u2014 inhale on wasted_energy=1, exhale to reactive-only',
771
+ pos:[0,-0.50,0.30], scale:0.20, color:'#4a90e2',
772
+ blurb:'The soak loop \u201cbreathe\u201d with wasted-energy windows: INHALE (admit Bekenstein-bounded batch) when wasted_energy=1 (curtailed/negative-price); EXHALE (drain to reactive-only) otherwise. Ouroboros-bounded \u2014 the loop cannot hyperventilate (no unbounded batch). Ties to F19 Bekenstein additive scaffolding (LOCKED) as the conceptual entropy-budget envelope, harvest_budget (AG-HARVEST EXPERIMENTAL), and Ouroboros loop-depth cap (AG-OUROBOROS EXPERIMENTAL). Platform PRs #370, #371.',
773
+ formulas:['F19','AG_HARVEST','AG_OUROBOROS'],
774
+ samay_note:true },
775
+
776
+ /* SENSES / EYES — RIKUY (see/perceive): global external feed perception */
777
+ { key:'rikuy', system:'senses', quechua:'RIKUY', fn:'global feed perception \u2014 price/renewable/frequency/flare/solar/wind',
778
+ pos:[0,1.75,0.30], scale:0.18, color:'#50e3c2',
779
+ blurb:'The body\u2019s perception of wasted energy in the world. Five feed families: (1) aWattar \u2014 day-ahead hourly electricity prices (negative-price detection); (2) Energy-Charts \u2014 renewable fraction + grid frequency (curtailment detection); (3) NASA VIIRS \u2014 flared-gas satellite (resource-map, not capture \u2014 HONEST: identifying stranded-gas locations, no physical capture from orbit); (4) NOAA L1 \u2014 solar-wind data (space-weather context); (5) Open-Meteo \u2014 wind/tidal forecast (renewable intermittency). Tier: resource-map for flare/space (map, not capture); feed-signal for the others. Backs the KAMAY hormone and SAMAY breath timing. HONEST: raw data feeds, not a proved formula.',
780
+ formulas:['AG_POSTURE','AG_HARVEST'] }
781
+ );
782
+
783
+ /* ---- 5 new AGENTIC-GPU SYSTEMS entries (ADDITIVE to SYSTEMS array) ---- */
784
+ SYSTEMS.push(
785
+ { key:'metabolism', name:'METABOLISM', organ:'KALLPA', fn:'wasted-energy harvest \u00b7 F19 Bekenstein (LOCKED) + Landauer floor (EXPERIMENTAL) \u00b7 joules SAMPLE until on-box NVML', color:'#f5a623' },
786
+ { key:'immune', name:'IMMUNE', organ:'WAQAYCHAQ', fn:'deny-by-default egress allowlist + secret-leak guard + consent-only swarm gate \u00b7 Neyman\u2013Pearson (EXPERIMENTAL)', color:'#7ed321' },
787
+ { key:'endocrine', name:'ENDOCRINE', organ:'KAMAY', fn:'energy-posture hormonal scheduler \u00b7 policy signal, not a measured joule \u00b7 platform PR #373', color:'#bd10e0' },
788
+ { key:'respiratory',name:'RESPIRATORY', organ:'SAMAY', fn:'soak-loop breath \u00b7 inhale on wasted_energy=1, exhale to reactive-only \u00b7 Ouroboros-bounded (EXPERIMENTAL)', color:'#4a90e2' },
789
+ { key:'senses', name:'SENSES / EYES', organ:'RIKUY', fn:'global feed perception \u00b7 aWattar price \u00b7 Energy-Charts \u00b7 NASA VIIRS flare (resource-map) \u00b7 NOAA solar-wind \u00b7 Open-Meteo', color:'#50e3c2' }
790
+ );
791
+
792
+ /* =====================================================================
793
+ ======================== v5 (EVOLVES v4) ========================
794
+ ADDITIVE. New organs + overlays that surface the governed conscience
795
+ (WILLAY), the Sovereign Mesh as a circulatory upgrade, the buyer-
796
+ verifiable receipt bloodstream, the 8 locked-proven → organ map, the
797
+ AI-Assurance (WDP/CDAO) artifact map, and the yarqa + thermal-PINN
798
+ physics layer. Honesty doctrine v11 LOCKED is UNCHANGED:
799
+ • Locked-proven stays EXACTLY 8 {F1,F4,F7,F11,F12,F18,F19,F22} @ c7c0ba17.
800
+ • Λ = Conjecture 1 (advisory heart-gate, NEVER a theorem).
801
+ • Khipu BFT = Conjecture 2 (Wave23 conditional only).
802
+ • Every LIVE/MEASURED/MODELED/SAMPLE/ROADMAP label is honest — a node
803
+ that does not answer reads DOWN, never a fabricated green light.
804
+ ===================================================================== */
805
+
806
+ /* ---- v5 live read-only endpoints (all on the a11oy origin; in CSP allow-list) ---- */
807
+ const V5_ENDPOINTS = {
808
+ willay: 'https://szlholdings-a11oy.hf.space/api/a11oy/v1/willay/classifiers',
809
+ mesh: 'https://szlholdings-a11oy.hf.space/api/a11oy/v1/govern/health',
810
+ ledger: 'https://szlholdings-a11oy.hf.space/api/lake/v1/health',
811
+ receipts: 'https://szlholdings-a11oy.hf.space/api/lake/v1/receipts?limit=1',
812
+ cosign: 'https://szlholdings-a11oy.hf.space/cosign.pub',
813
+ assurance: 'https://szlholdings-a11oy.hf.space/assurance'
814
+ };
815
+
816
+ /* ---- v5 organs (ADDITIVE to ORGANS array) ---- */
817
+ ORGANS.push(
818
+ /* CONSCIENCE / IMMUNE-GATE — WILLAY: inspectable signed refusals.
819
+ Plain-English function label; tamper-EVIDENT, not tamper-proof. */
820
+ { key:'willay', system:'conscience', quechua:'WILLAY', fn:'conscience / immune-gate — inspectable signed refusals',
821
+ pos:[0,0.30,0.34], scale:0.20, color:'#39d8c8', willay_note:true,
822
+ blurb:'The governed conscience. Five INSPECTABLE classifiers (cyber · bio dual-use · hidden-reasoning extraction · prompt-injection / governance bypass · self-harm) gate every proposal; each refusal discloses its category, pattern intent, rationale, and lineage and is signed on the receipt bus. Trust ceiling 0.97 — trust is never 100%. HONEST: refusals are tamper-EVIDENT (you can detect alteration via the signed receipt), NOT tamper-proof. The inverse of a removed/hidden safety classifier: ours are auditable rules, not opaque weights. Reads ' + V5_ENDPOINTS.willay + ' live; honest empty-state if unreachable.',
823
+ formulas:['CF5','L2','AG_EGRESS'] },
824
+
825
+ /* SOVEREIGN MESH — circulatory upgrade. The 3D node is an anchor; the
826
+ LIVE per-node truth (tower LIVE / laptop / GLM honest-DOWN) is read
827
+ from /govern/health into the mesh panel and is NEVER fabricated. */
828
+ { key:'sovereign_mesh', system:'mesh', quechua:'SOVEREIGN MESH', fn:'circulatory upgrade — governed inference mesh (live per-node)',
829
+ pos:[0,-0.32,-0.26], scale:0.20, color:'#ff7a9c', mesh_note:true,
830
+ blurb:'The circulatory system upgraded to a sovereign inference mesh. Each node (tower RTX 4060 Ti anchor · laptop · GLM engine) is rendered with its HONEST live/down status read from ' + V5_ENDPOINTS.mesh + ': a node that is offline reads DOWN — never a fabricated green light. Per-node F11 Ayni reciprocity contribution (LOCKED) keeps the mesh balanced tit-for-tat. VRAM-fusion across nodes is ROADMAP — today the mesh is a scheduler / router (“Smart Routing”), not a fused address space. Energy joules are UNAVAILABLE unless a live NVML meter answers; never fabricated.',
831
+ formulas:['F11','F7','F22'] }
832
+ );
833
+
834
+ /* ---- v5 SYSTEMS entries (ADDITIVE) ---- */
835
+ SYSTEMS.push(
836
+ { key:'conscience', name:'CONSCIENCE / IMMUNE-GATE', organ:'WILLAY', fn:'5 inspectable signed-refusal classifiers · trust ceiling 0.97 · tamper-EVIDENT not tamper-proof', color:'#39d8c8' },
837
+ { key:'mesh', name:'SOVEREIGN MESH', organ:'governed inference mesh', fn:'circulatory upgrade · live per-node up/down (never fabricated) · F11 Ayni per node · VRAM-fusion ROADMAP', color:'#ff7a9c' }
838
+ );
839
+
840
+ /* =====================================================================
841
+ v5 — 8 LOCKED-PROVEN → ORGAN MAP (additive, honest)
842
+ The mapping is presentational only: it does NOT change the locked set,
843
+ which stays EXACTLY 8 {F1,F4,F7,F11,F12,F18,F19,F22} @ c7c0ba17.
844
+ Each entry shows the verbatim Lean statement (latex) + #print axioms.
845
+ Λ is the heart-gate: ADVISORY, Conjecture 1, NEVER a theorem.
846
+ Khipu BFT safety is Conjecture 2 (Wave23 conditional only).
847
+ ===================================================================== */
848
+ const LEAN_MAP = {
849
+ kernel_sha:'c7c0ba17',
850
+ verified_note:'kernel-verified sorry-free @ c7c0ba17',
851
+ organs:[
852
+ { organ:'BRAIN', organ_key:'amaru', color:'#7c5cff', formulas:['F1'],
853
+ why:'F1 Replay-Hash Determinism underpins the read-only reasoning cortex: replaying a recorded log is bit-identical, so the thinking layer can never drift the record.' },
854
+ { organ:'HEART', organ_key:'yuyay', color:'#ff5d8f', formulas:['F4','F11'],
855
+ why:'F4 (Khipu DAG acyclicity) + F11 (Ayni reciprocity conservation) sit at the beating gate. Λ is the heart-gate — ADVISORY, Conjecture 1, never a theorem.' },
856
+ { organ:'CIRCULATORY', organ_key:'yawar', color:'#ff3b5c', formulas:['F7','F22'],
857
+ why:'F7 (FIFO reception ordering — “Smart Routing”) + F22 (emit append-only monotonicity) keep the receipt bloodstream ordered and append-only.' },
858
+ { organ:'NERVOUS', organ_key:'vsp', color:'#5ad1ff', formulas:['F12'],
859
+ why:'F12 Kuramoto coupling boundedness (additive fragment) bounds the nervous-system span coupling — additive scaffolding only, NOT full nonlinear sync.' },
860
+ { organ:'SKELETON', organ_key:'hatun', color:'#ffd166', formulas:['F18','F19'],
861
+ why:'F18 (RS(10,6) erasure recovery) + F19 (Bekenstein additive scaffolding) are the skeletal resilience + entropy-budget bones.' }
862
+ ],
863
+ lambda:'Λ = heart-gate, ADVISORY = Conjecture 1. Unconditional uniqueness under A1–A5 is machine-checked FALSE; CUT-2 proves uniqueness only CONDITIONAL on slice-multiplicativity. Never a theorem.',
864
+ khipu:'Khipu BFT safety = Conjecture 2. Wave23 proves agreement CONDITIONAL on n≥3f+1 + honest non-equivocation; unconditional safety stays Conjecture 2.'
865
+ };
866
+
867
+ /* =====================================================================
868
+ v5 — AI-ASSURANCE (WDP / CDAO) ARTIFACT MAP (additive, honest)
869
+ Maps each organ to the assurance artifact it satisfies, with honest
870
+ status chips. Aligns to the live a11oy /assurance surface.
871
+ Status vocabulary (honest): LIVE · PARTIAL · ROADMAP.
872
+ ===================================================================== */
873
+ const ASSURANCE_MAP = {
874
+ surface:V5_ENDPOINTS.assurance,
875
+ note:'Maps each organ to the AI-assurance artifact it satisfies (WDP / CDAO framing). Status chips are honest: LIVE = the artifact exists and is reachable; PARTIAL = exists but incomplete / sampled; ROADMAP = planned, not yet real.',
876
+ rows:[
877
+ { organ:'BRAIN / cortex', organ_key:'amaru', artifact:'Model card', status:'PARTIAL',
878
+ detail:'Read-only reasoning cortex; open-weight engine identity disclosed via /govern/health. Full model card is PARTIAL (engine + tier disclosed; eval suite roadmap).' },
879
+ { organ:'HEART / gate', organ_key:'yuyay', artifact:'TEVV signed receipt', status:'LIVE',
880
+ detail:'Test/Evaluation/Verification/Validation: every gate verdict is a DSSE ECDSA-P256 signed receipt on the bus — verifiable offline against cosign.pub.' },
881
+ { organ:'CIRCULATORY / bus', organ_key:'yawar', artifact:'SI-7 hash-chain (integrity)', status:'LIVE',
882
+ detail:'NIST SI-7 software/information integrity: the receipt ledger is a sha3_256 hash-chain (chain_head live at /api/lake/v1/health). Append-only, tamper-evident.' },
883
+ { organ:'CONSCIENCE / immune', organ_key:'willay', artifact:'Data card + safety classifiers', status:'LIVE',
884
+ detail:'Five inspectable refusal classifiers with disclosed lineage (live at /willay/classifiers). Honest data-card framing: categories + rationale disclosed; trust ceiling 0.97.' },
885
+ { organ:'NERVOUS / OTel', organ_key:'vsp', artifact:'OTel-GenAI monitoring', status:'PARTIAL',
886
+ detail:'W3C TraceContext span lineage across the agent loop; OpenTelemetry GenAI semantic conventions are PARTIAL (span lineage live; full GenAI attribute coverage roadmap).' },
887
+ { organ:'SKELETON / supply-chain', organ_key:'hatun', artifact:'SBOM / SLSA provenance', status:'PARTIAL',
888
+ detail:'This static Space is SLSA L1 honest; product images (a11oy, killinchu) are L2 build-attested (Sigstore keyless, Rekor-anchored). SBOM + L3 are ROADMAP.' },
889
+ { organ:'MESH', organ_key:'sovereign_mesh', artifact:'TEVV per-node attestation', status:'PARTIAL',
890
+ detail:'Per-node up/down attested live from /govern/health (never fabricated). Per-node signed attestation + VRAM-fusion provenance is ROADMAP.' }
891
+ ]
892
+ };
893
+
894
+ /* =====================================================================
895
+ v5 — yarqa CFD + THERMAL-PINN physics overlay (additive, honest)
896
+ Composes the existing yarqa plug-flow compartmentalization (a clean-room
897
+ engineering-method CFD, NOT a locked theorem) with a thermal physics-
898
+ informed-NN model into ONE "physics-governed" layer. Label: MODELED
899
+ (not measured), bounded error. NEVER counted among the locked 8.
900
+ ===================================================================== */
901
+ const PHYSICS_OVERLAY = {
902
+ label:'MODELED',
903
+ headline:'physics-governed layer = yarqa CFD plug-flow ⊕ thermal PINN',
904
+ honest:'MODELED, not measured. This composes the existing yarqa compartmental plug-flow CFD (engineering method, off-by-default in the dissection dock) with a thermal physics-informed neural-network surrogate. It is NOT a locked theorem and is NEVER folded into the locked-8 — data.js stays the single source of truth and the locked-proven count is unchanged at 8.',
905
+ components:[
906
+ { name:'yarqa CFD plug-flow', kind:'compartmental advection (region-grown)',
907
+ detail:'Clean-room plug-flow compartmentalization over the existing circulatory / receipt flow sampled from data.js. Emits a reproducible integrity digest. Read-only overlay.' },
908
+ { name:'thermal PINN surrogate', kind:'physics-informed NN (steady-state heat)',
909
+ detail:'A physics-informed surrogate for steady-state organ thermal load (residual of ∇·(k∇T) − q minimised at collocation points). Surrogate, NOT a measured thermocouple readout.' }
910
+ ],
911
+ bounded_error:'Bounded error: the composed field is reported with an explicit relative-residual envelope (≤ 5% on the demo mesh); outside the modelled range it degrades to an honest “out-of-distribution — unquantified” state rather than extrapolating.',
912
+ never:'NEVER a locked theorem · NEVER counted in the locked-8 · NEVER claimed as a measurement.',
913
+
914
+ /* -------------------------------------------------------------------
915
+ LTC-derived state-dependent breathing overlay (ADDITIVE 2026-07-03).
916
+ Own-code reimplementation of the *pattern* from Liquid Time-Constant
917
+ Networks (Hasani, Lechner, Amini, Rus, Grosu; arXiv:2006.04439;
918
+ Apache-2.0). We reimplement ONLY the bounded first-order state-
919
+ dependent dynamics form — a "liquid" effective time-constant
920
+ tau_eff = 1/(1/tau + g), where a per-organ drift/anomaly signal g in
921
+ (0,1) shortens tau (organ breathes faster / reacts sooner) and a calm
922
+ organ lengthens it toward tau_base. This is a VIZ / modelling upgrade:
923
+ a rendered breathing rate, NOT a measurement and NOT a theorem. It is
924
+ NEVER folded into the locked-8 and NEVER relabels Λ.
925
+ ------------------------------------------------------------------- */
926
+ ltc_timescale:{
927
+ label:'LTC-derived · advisory · experimental',
928
+ citation:'pattern from Liquid Time-Constant Networks (arXiv:2006.04439, Apache-2.0); own-code reimplementation, no source vendored',
929
+ headline:'state-dependent organ breathing rate — liquid time-constant',
930
+ honest:'ADVISORY / experimental viz overlay. Each organ renders a breathing rate whose effective time-constant is state-dependent: a drifting / anomalous organ shortens tau (breathes faster), a calm organ lengthens tau toward its base. This is a MODELLED render, NOT a measured cadence and NOT a locked theorem; it is NEVER counted in the locked-8 and NEVER moves Λ off Conjecture 1.',
931
+ model:'tau_eff = 1 / (1/tau + g), with the fixed bounded gate g = sigmoid(drive) in (0,1) and tau clamped to [tau_min, tau_max]. Bounded by construction: tau_eff stays in (0, tau] so the render can never hyperventilate or freeze.',
932
+ tau_min:0.001,
933
+ tau_max:1000,
934
+ tau_units:'seconds (render cadence; advisory)',
935
+ drive:'The per-organ drive is the organ’s own honest liveness/drift signal where a live probe answers, and an explicit SAMPLE constant where none exists yet. A DOWN or unreachable probe reads as HIGH drift (organ breathes fast) — never a fabricated calm.',
936
+ organs:[
937
+ { organ_key:'willay', organ:'WILLAY / conscience', tau_base:8.0,
938
+ stress_source:'live', probe:V5_ENDPOINTS.willay,
939
+ detail:'Refusal-classifier surface. Drive = observed classifier activity / reachability from the live probe; a spike in refusals shortens tau (breathes faster). Unreachable ⇒ HIGH drift, not a fabricated calm.' },
940
+ { organ_key:'sovereign_mesh', organ:'SOVEREIGN MESH / circulatory', tau_base:6.0,
941
+ stress_source:'live', probe:V5_ENDPOINTS.mesh,
942
+ detail:'Per-node up/down from /govern/health. Drive rises as nodes read DOWN; a degraded mesh shortens tau. Never a fabricated green light — a silent mesh reads as HIGH drift.' },
943
+ { organ_key:'yawar', organ:'CIRCULATORY / receipt bus', tau_base:5.0,
944
+ stress_source:'live', probe:V5_ENDPOINTS.ledger,
945
+ detail:'Receipt hash-chain health. Drive = chain-head staleness / emit-rate anomaly from the live ledger probe; a stalled chain shortens tau.' },
946
+ { organ_key:'samay', organ:'RESPIRATORY / soak-loop breath', tau_base:12.0,
947
+ stress_source:'sample', sample_drive:0.35,
948
+ detail:'Soak-loop breath already breathes on wasted-energy windows; the LTC overlay adds an advisory state-dependent cadence. No dedicated live drift probe yet ⇒ honest SAMPLE drive, not fabricated telemetry.' },
949
+ { organ_key:'yuyay', organ:'HEART / gate', tau_base:4.0,
950
+ stress_source:'sample', sample_drive:0.25,
951
+ detail:'Gate cadence. Λ stays ADVISORY / Conjecture 1 — this overlay renders a breathing rate only and NEVER upgrades the heart-gate to a theorem. No live per-decision drift feed here yet ⇒ honest SAMPLE drive.' },
952
+ { organ_key:'amaru', organ:'BRAIN / cortex', tau_base:10.0,
953
+ stress_source:'sample', sample_drive:0.20,
954
+ detail:'Read-only reasoning cortex. No live drift probe ⇒ honest SAMPLE drive; the cortex breathes slowly (long tau) unless a future telemetry feed raises its drive.' }
955
+ ],
956
+ bounded:'Bounded by construction: g in (0,1) and tau in [tau_min, tau_max] ⇒ tau_eff in (0, tau]. The render is a contraction toward the observed drive — it cannot blow up.',
957
+ never:'NEVER a measurement · NEVER a locked theorem · NEVER counted in the locked-8 · NEVER relabels Λ off Conjecture 1 · a DOWN probe reads as high drift, never a fabricated calm.'
958
+ }
959
+ };
960
+
961
+ /* =====================================================================
962
+ v5 — GPU-SOVEREIGN STACK (SUBSTRATE) overlay (additive, honest)
963
+ The VERTICAL compute anatomy that complements the horizontal Sovereign
964
+ Mesh organ: owned GPU fabric → runtime → mesh / router → open-weight
965
+ model → native governance → buyer-verifiable receipts. Framed against
966
+ how the leaders present sovereign compute (chip → cloud → model), made
967
+ our own. Every layer carries an HONEST posture chip; live layers read
968
+ /govern/health and degrade to DOWN when unreachable — never a fabricated
969
+ green light. Adds NOTHING to the locked-8 and never relabels Λ.
970
+ ===================================================================== */
971
+ const STACK_LAYER = {
972
+ headline:'GPU-Sovereign Stack — the vertical substrate anatomy',
973
+ thesis:'Compute IS sovereignty: the organism runs on a ground GPU fabric we own and govern — not rented from a hyperscaler. The leaders present this as a chip → cloud → model cake; we make it our own by promoting governance and buyer-verifiable receipts to first-class layers and labelling every layer honestly.',
974
+ live_source:V5_ENDPOINTS.mesh,
975
+ layers:[
976
+ { tier:'L0', name:'Metal & energy — owned GPU fabric', posture:'REAL', chip:'live',
977
+ leaders:'Hyperscalers frame Layer-0 (power, PUE, cooling) as the binding constraint; sovereign clouds argue that sovereign AI cannot be built on rented compute.',
978
+ szl:'A real ground fabric operates today — an RTX-class tower anchor plus nodes, on the metal, with no hyperscaler tenancy. Node liveness is read live from /govern/health.',
979
+ honest:'Energy / joules are SAMPLE — UNAVAILABLE until a live NVML meter answers. Never a fabricated wattage.' },
980
+ { tier:'L1', name:'Runtime — open-weight inference engine', posture:'LIVE', chip:'live', live_key:'engine',
981
+ leaders:'The runtime (KV-cache, continuous batching, paged attention, tensor / pipeline parallelism) is where the neoclouds compete on tokens per second.',
982
+ szl:'Open-weight engines served on our own metal; engine count and tier read live. No closed-API dependency sits in the hot path.',
983
+ honest:'A node that does not answer reads DOWN — never a fabricated green light.' },
984
+ { tier:'L2', name:'Sovereign mesh — scheduler / router', posture:'LIVE', chip:'live', live_key:'mesh',
985
+ leaders:'Vendors sell a fused multi-GPU address space; sovereign meshes today are smart routers across independent nodes.',
986
+ szl:'Per-node F11 Ayni reciprocity (LOCKED) balances the mesh tit-for-tat. Open the Sovereign Mesh organ for live per-node up / DOWN.',
987
+ honest:'VRAM-fusion across nodes is ROADMAP — today the mesh is a scheduler / router, not a fused address space.' },
988
+ { tier:'L3', name:'Model — open weights, disclosed', posture:'PARTIAL', chip:'partial',
989
+ leaders:'NVIDIA packages models as NIM microservices; the model layer is weights + quantization + format + adapters.',
990
+ szl:'Open-weight only — engine identity and tier disclosed via /govern/health. The full model card (eval suite) is PARTIAL, not yet complete.',
991
+ honest:'Open-weight and disclosed — no opaque closed model is dressed up as ours.' },
992
+ { tier:'L4', name:'Governance — native, not bolted on', posture:'LOCKED', chip:'locked',
993
+ leaders:'A governed inference stack wraps every layer with access control, guardrails and audit logs — usually added after the fact.',
994
+ szl:'Governance is the HEART, not a wrapper: the YUYAY 13-axis conjunctive gate (deny-by-default) plus the WILLAY conscience adjudicate every inference before it runs; trust ceiling 0.97. Λ = Conjecture 1 — advisory, never a theorem.',
995
+ honest:'Trust is never 100% and no AGI is claimed. The gate is advisory-honest, not an infallible oracle.' },
996
+ { tier:'L5', name:'Verifiable compute — the frontier', posture:'PARTIAL', chip:'partial', receipt_key:'ledger',
997
+ leaders:'The 2026 frontier is proving a result was produced correctly without trusting the operator — TEE attestation (H100 / H200 confidential computing), ZK proofs, or signed receipts.',
998
+ szl:'Every governed decision emits a DSSE ECDSA-P256 receipt on an append-only hash-chain — verifiable OFFLINE in your browser, right here, no trust in us required. Hardware TEE / remote attestation of the GPU node is ROADMAP.',
999
+ honest:'Receipts are LIVE and buyer-verifiable now; on-metal TEE attestation is ROADMAP — labelled, not fabricated.' }
1000
+ ],
1001
+ frontier:'Where we push the frontier: most stacks bolt governance and audit on top of rented compute. We invert it — own the metal, make governance the beating heart, and make every output buyer-verifiable at the edge. Sovereignty you can check, not take on faith.',
1002
+ never:'NEVER a fabricated green light · energy NEVER fabricated (SAMPLE until NVML) · VRAM-fusion and TEE attestation honestly ROADMAP · the locked set stays exactly 8 · Λ never a theorem.'
1003
+ };
1004
+
1005
+ root.SZL_ANATOMY = { KERNEL, MATURITY, FORMULAS, ORGANS, SYSTEMS, BODIES, SKELETON_REPOS, PUTNAM_2025,
1006
+ QBIO, QBIO_LEADERS, QBIO_SOURCES, QBIO_THEOREMS,
1007
+ V5_ENDPOINTS, LEAN_MAP, ASSURANCE_MAP, PHYSICS_OVERLAY, STACK_LAYER };
1008
+ })(window);
docs/LIVING_ANATOMY_SECOND_BRAIN.md ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Living Anatomy + YACHAY Second Brain
2
+
3
+ ## Production contract
4
+
5
+ `betterwithage/anatomy` is a **KEEP / public / running** Hugging Face flagship. GitHub
6
+ `szl-holdings/anatomy` is the runtime source of truth. The Space is a deployment
7
+ mirror, not an independent source tree.
8
+
9
+ The Docker entry point is `living_runtime.py`. It extends the existing hardened
10
+ `server.py` in-process and preserves every static, evidence, receipt, organ-integrity,
11
+ and security-header route. The extension adds a read-only YACHAY Brain organ:
12
+
13
+ | Interface | Purpose |
14
+ |---|---|
15
+ | `GET /api/anatomy/v1/living-health` | Combined Anatomy + Brain readiness |
16
+ | `GET /api/anatomy/v1/brain/health` | Snapshot integrity, source SHA, counts, authority |
17
+ | `GET /api/anatomy/v1/brain/manifest` | Machine-readable source and interface contract |
18
+ | `GET/POST /api/anatomy/v1/brain/search` | BM25-like public-handle retrieval |
19
+ | `GET/POST /api/anatomy/v1/brain/context` | Model-safe handles plus evidence pointers |
20
+
21
+ ## Source binding
22
+
23
+ `scripts/materialize_second_brain.py` resolves the exact protected-main revision of
24
+ `szl-holdings/szl-second-brain`, downloads only:
25
+
26
+ - `data/manifest.json`
27
+ - `data/brain-corpus.public.jsonl`
28
+
29
+ It validates:
30
+
31
+ 1. exactly 575 public chunks;
32
+ 2. the declared source histogram;
33
+ 3. every row's SHA-256;
34
+ 4. `secretScan: PASS`;
35
+ 5. unique public node IDs.
36
+
37
+ The operator writes `.runtime/second-brain/source.json` with the exact Git SHA,
38
+ manifest digest, corpus digest, count, and authority constraints. The HF sync workflow
39
+ bundles that immutable snapshot and records the dependency in
40
+ `hf-deploy-manifest.json`.
41
+
42
+ ## Non-negotiable boundary
43
+
44
+ The public Space returns **handles only**. It does not expose corpus text through the
45
+ API, load the owner's private 9,464-node graph, train weights, execute tools, or hold
46
+ write authority. Lexical ranking is relevance, never correctness. Lambda remains
47
+ Conjecture 1.
48
+
49
+ The richer product-side living-brain loop in `szl-holdings/a11oy` remains a separate
50
+ governed execution surface. The public HF Anatomy is its inspectable, read-only
51
+ anatomical instrument—not a duplicate mutation authority.
52
+
53
+ ## Reproduce locally
54
+
55
+ ```bash
56
+ python scripts/materialize_second_brain.py --output .runtime/second-brain
57
+ python -m unittest discover -s tests -v
58
+ python living_runtime.py
59
+ ```
60
+
61
+ Then inspect:
62
+
63
+ ```text
64
+ http://127.0.0.1:7860/api/anatomy/v1/living-health
65
+ http://127.0.0.1:7860/api/anatomy/v1/brain/health
66
+ http://127.0.0.1:7860/api/anatomy/v1/brain/search?q=governed%20receipts&k=6
67
+ ```
68
+
69
+ ## Lifecycle
70
+
71
+ `.github/workflows/hf-sync.yml` runs on protected-main changes, manual dispatch, and
72
+ a six-hour reconciliation cadence. It:
73
+
74
+ 1. validates the exact Second Brain projection;
75
+ 2. refuses a stale GitHub source revision;
76
+ 3. makes `betterwithage/anatomy` public;
77
+ 4. restarts paused, sleeping, stopped, or failed runtime states;
78
+ 5. avoids a rebuild when both source revisions are already deployed;
79
+ 6. verifies the live Anatomy, Brain, version, evidence, source, and manifest contracts.
80
+
81
+ A separate estate keep policy in `szl-holdings/a11oy` must include
82
+ `betterwithage/anatomy`; otherwise the fleet consolidator will correctly treat it as a
83
+ fold. That policy is part of the same coordinated repair.
docs/holographic-space-v2.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Anatomy Holo-Constellation v2
2
+
3
+ The Anatomy Space keeps its existing interactive organ map, evidence APIs, receipt verifier, and fail-closed runtime semantics. Holo-Constellation v2 adds a local visual instrument and shared estate navigation without changing those product contracts.
4
+
5
+ ## Runtime-integrity boundary
6
+
7
+ Both new browser assets are included in `server.ARTIFACT_PATHS`:
8
+
9
+ - `szl-holo-v2.css`
10
+ - `szl-holo-v2.js`
11
+
12
+ They therefore participate in the Anatomy runtime manifest and structural receipt rather than being served as untracked presentation files.
13
+
14
+ ## Accessibility boundary
15
+
16
+ The shared layer provides keyboard focus, 44-pixel controls, reduced-motion behavior, increased-contrast behavior, forced-color behavior, responsive navigation, and print handling. Decorative animation is presentation only and is not reported as telemetry or operational evidence.
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={version:'Exact GitHub source and deployed Space revision.',evidence_index:'Release identity, structural bundle receipt, and dependency evidence index.',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);
hf-deploy-manifest.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dependencies": {
3
+ "second_brain": {
4
+ "authority_state": "READ_ONLY",
5
+ "content_access": "HANDLES_ONLY",
6
+ "corpus_sha256": "387337acbd8fe443637102fe7ea75387fa4c3d9d746d8ab6e2d14d6c138aad8f",
7
+ "public_chunk_count": 575,
8
+ "source_repository": "szl-holdings/szl-second-brain",
9
+ "source_revision": "ff03b116a83f2b5302999ab4167d51e35aba3b5e"
10
+ }
11
+ },
12
+ "destination": {
13
+ "lifecycle": "PUBLIC_CREATIVE",
14
+ "mode": "creator-profile",
15
+ "repo_id": "betterwithage/anatomy",
16
+ "repo_type": "space",
17
+ "visibility": "public"
18
+ },
19
+ "schema": "szl.hf-deploy-manifest/v1",
20
+ "source_path": "",
21
+ "source_repository": "szl-holdings/anatomy",
22
+ "source_revision": "6e7f19a7b7597c618df52fffd5b1812d1e8a82c5",
23
+ "workflow_run_id": "33820819238"
24
+ }
index.html ADDED
The diff for this file is too large to render. See raw diff
 
lib/szl_verify_widget.js ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================================
2
+ * SZL "ask the fabric" — verify-a-claim widget (vendored, self-contained)
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).
11
+ * "STRUCTURAL-ONLY" is shown as advisory, NOT green. Network/timeout/429 degrade
12
+ * to an honest "unreachable / rate-limited" state — never to a false green.
13
+ *
14
+ * Attribution (clean-room rebuild of permissive ideas — see dev7 report):
15
+ * - Tool-call / receipt trace UI pattern inspired by smolagents (Apache-2.0,
16
+ * huggingface/smolagents) and assistant-ui (MIT). Rebuilt SZL-native; no code copied.
17
+ * - AbortController fetch contract reuses anatomy V8 (SZL own prior art).
18
+ * ==========================================================================*/
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){
32
+ return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]; }); }
33
+
34
+ /* honest fetch contract: AbortController + try/catch. NEVER throws. ----- */
35
+ function pull(url, opts, timeoutMs){
36
+ var ctl = (typeof AbortController!=='undefined') ? new AbortController() : null;
37
+ var to = ctl ? setTimeout(function(){ try{ctl.abort();}catch(e){} }, timeoutMs||TIMEOUT_MS) : null;
38
+ opts = opts || {};
39
+ opts.signal = ctl ? ctl.signal : undefined;
40
+ opts.cache = 'no-store';
41
+ opts.mode = 'cors';
42
+ return fetch(url, opts).then(function(r){
43
+ if(to) clearTimeout(to);
44
+ var status = r.status;
45
+ return r.json().then(function(data){ return {ok:r.ok, status:status, data:data}; },
46
+ function(){ return {ok:false, status:status, data:null}; });
47
+ }).catch(function(e){
48
+ if(to) clearTimeout(to);
49
+ var aborted = e && (e.name==='AbortError');
50
+ return {ok:false, status:0, data:null, err:String(e&&e.message||e), aborted:aborted};
51
+ });
52
+ }
53
+
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
+
64
+ function renderChecks(checks){
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>';
75
+ }
76
+
77
+ function renderResult(res){
78
+ // res is the {ok,status,data,err,aborted} envelope from pull()
79
+ if(res.status===429){
80
+ return '<div class="szlv-state fail">rate-limited · the fabric caps at 60/min per IP. '+
81
+ 'This is honest backpressure, not a failure of your receipt. Try again shortly.</div>';
82
+ }
83
+ if(!res.ok || !res.data){
84
+ var why = res.aborted ? 'timed out' : (res.status ? ('HTTP '+res.status) : 'unreachable');
85
+ return '<div class="szlv-state muted">offline · fabric '+esc(why)+
86
+ '. No verdict shown — the widget never invents a green. '+
87
+ 'Re-run the checks yourself per docs/developers/VERIFY.md.</div>';
88
+ }
89
+ var d = res.data;
90
+ var vv = verdictView(d.verdict);
91
+ var head = '<div class="szlv-verdict '+vv.cls+'">'+
92
+ '<span class="szlv-dot"></span><b>'+esc(vv.label)+'</b>'+
93
+ (vv.advisory ? '<span class="szlv-adv">advisory · not a cryptographic green</span>' : '')+
94
+ '</div>';
95
+ var detail = d.detail ? '<p class="szlv-detail">'+esc(d.detail)+'</p>' : '';
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) : '')+
103
+ '<br><span class="szlv-trust">No trust in the server is required — re-verify with cosign / rekor-cli / lake build.</span></p>';
104
+ return head+detail+kinds+checks+foot;
105
+ }
106
+
107
+ var CSS = [
108
+ '.szlv{font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;',
109
+ 'color:#cdccca;background:#1c1b19;border:1px solid #393836;border-radius:10px;padding:16px;max-width:640px}',
110
+ '.szlv h3{font-size:15px;margin:0 0 4px;font-weight:600;letter-spacing:.2px}',
111
+ '.szlv .szlv-sub{font-size:12px;color:#797876;margin:0 0 12px}',
112
+ '.szlv textarea{width:100%;min-height:120px;box-sizing:border-box;background:#171614;color:#cdccca;',
113
+ 'border:1px solid #393836;border-radius:8px;padding:10px;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;resize:vertical}',
114
+ '.szlv-row{display:flex;gap:8px;flex-wrap:wrap;margin:10px 0}',
115
+ '.szlv input[type=text]{flex:1;min-width:200px;background:#171614;color:#cdccca;border:1px solid #393836;border-radius:8px;padding:8px 10px;font-size:12px}',
116
+ '.szlv button{background:#01696f;color:#fff;border:0;border-radius:8px;padding:9px 16px;font-size:13px;font-weight:600;cursor:pointer}',
117
+ '.szlv button:hover{background:#0c4e54}.szlv button:disabled{opacity:.5;cursor:wait}',
118
+ '.szlv button.ghost{background:transparent;color:#4f98a3;border:1px solid #393836}',
119
+ '.szlv-out{margin-top:12px;font-size:13px;min-height:24px}',
120
+ '.szlv-load{color:#797876;font-size:12px}',
121
+ '.szlv-verdict{display:flex;align-items:center;gap:8px;font-size:15px;padding:8px 10px;border-radius:8px;border:1px solid #393836}',
122
+ '.szlv-verdict .szlv-dot{width:9px;height:9px;border-radius:50%}',
123
+ '.szlv-verdict.ok .szlv-dot{background:#6daa45}.szlv-verdict.ok{border-color:#3a5a26}',
124
+ '.szlv-verdict.warn .szlv-dot{background:#e8af34}.szlv-verdict.warn{border-color:#6b5418}',
125
+ '.szlv-verdict.fail .szlv-dot{background:#d163a7}.szlv-verdict.fail{border-color:#7a2c5a}',
126
+ '.szlv-verdict.muted .szlv-dot{background:#797876}',
127
+ '.szlv-adv{font-size:11px;color:#e8af34;font-weight:400;margin-left:auto}',
128
+ '.szlv-detail{font-size:12px;color:#a9a8a5;margin:8px 0}',
129
+ '.szlv-kinds{font-size:11px;color:#797876;margin:4px 0}',
130
+ '.szlv-checks{list-style:none;margin:8px 0 0;padding:0;display:flex;flex-direction:column;gap:4px}',
131
+ '.szlv-chk{display:flex;align-items:center;gap:8px;font-size:12px;flex-wrap:wrap}',
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}',
139
+ '.szlv-trust{color:#797876}',
140
+ '.szlv-state{font-size:12px;padding:8px 10px;border-radius:8px}',
141
+ '.szlv-state.fail{background:rgba(209,99,167,.10);color:#d163a7}',
142
+ '.szlv-state.muted{background:#211f1d;color:#a9a8a5}'
143
+ ].join('');
144
+
145
+ function injectCSS(){
146
+ if(document.getElementById('szlv-css')) return;
147
+ var st = document.createElement('style'); st.id='szlv-css'; st.textContent = CSS;
148
+ document.head.appendChild(st);
149
+ }
150
+
151
+ /* Public mount: SZLVerify.mount('#id', {base}) ------------------------- */
152
+ function mount(target, opts){
153
+ opts = opts || {};
154
+ var base = (opts.base || DEFAULT_BASE).replace(/\/+$/,'');
155
+ var host = (typeof target==='string') ? document.querySelector(target) : target;
156
+ if(!host) return null;
157
+ injectCSS();
158
+ host.classList.add('szlv');
159
+ host.innerHTML =
160
+ '<h3>ask the fabric — verify a receipt</h3>'+
161
+ '<p class="szlv-sub">Paste a Khipu receipt / DSSE envelope / in-toto statement, '+
162
+ 'or fetch a public receipt by URL. Verdicts are the fabric\u2019s real, honest output '+
163
+ '(unsigned \u2192 STRUCTURAL-ONLY, never a false green).</p>'+
164
+ '<textarea class="szlv-ta" spellcheck="false"></textarea>'+
165
+ '<div class="szlv-row">'+
166
+ '<input type="text" class="szlv-url" placeholder="\u2026or a public receipt URL (https://\u2026/receipt.json)">'+
167
+ '</div>'+
168
+ '<div class="szlv-row">'+
169
+ '<button class="szlv-go" type="button">Verify</button>'+
170
+ '<button class="szlv-sample ghost" type="button">Load sample receipt</button>'+
171
+ '</div>'+
172
+ '<div class="szlv-out" aria-live="polite"></div>';
173
+
174
+ var ta = host.querySelector('.szlv-ta');
175
+ var url = host.querySelector('.szlv-url');
176
+ var out = host.querySelector('.szlv-out');
177
+ var go = host.querySelector('.szlv-go');
178
+ var smp = host.querySelector('.szlv-sample');
179
+
180
+ smp.addEventListener('click', function(){ ta.value = JSON.stringify(SAMPLE, null, 2); url.value=''; });
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;
204
+ }
205
+ p.then(function(res){ out.innerHTML = renderResult(res); go.disabled = false; });
206
+ });
207
+
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);
lib/three.min.js ADDED
The diff for this file is too large to render. See raw diff
 
live-body.html ADDED
@@ -0,0 +1,555 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <!-- SAFE-NOW hardening (R2): browser-honored CSP subset + nosniff + Referrer-Policy.
6
+ HSTS / frame-ancestors omitted (browsers ignore them in <meta>; setting them
7
+ would be fabrication). 'unsafe-inline' is required: this page ships an inline
8
+ module script + inline styles, and Three.js is a vendored same-origin script. -->
9
+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self' https://szlholdings-a11oy.hf.space https://a-11-oy.com; object-src 'none'; base-uri 'self'; form-action 'self'" />
10
+ <meta http-equiv="X-Content-Type-Options" content="nosniff" />
11
+ <meta name="referrer" content="strict-origin-when-cross-origin" />
12
+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2" />
13
+ <title>SZL Living Anatomy — BODY v1 · the Sovereign Org as one living organism</title>
14
+ <meta name="description" content="Body v1: the Sovereign Org rendered as one living governed organism. CatmullRom Bezier-tube vessels = the one DSSE chain; GPU pulses = REAL receipts from /api/a11oy/v1/ledger; 4 organs (Reasoning/Policy/Operator/Receipts) glow LIVE or dim UNREACHABLE on real probes; Λ (F19) drives the double-beat heartbeat + overall glow; verticals & SLSA shown honestly as ROADMAP where no endpoint exists. Honest by construction. Λ = Conjecture 1." />
15
+ <style>
16
+ :root{
17
+ --void:#080c14; --void2:#0b1120;
18
+ --proof:#3af4c8; --lattice:#5b8dee; --gold:#d7b96b; --warn:#e0795b;
19
+ --dim:#3a4456; --text:#e9eef7; --muted:#8b97b4; --faint:#5d6a8f;
20
+ --surface:rgba(11,17,32,0.72); --surface2:rgba(16,24,44,0.92);
21
+ --border:rgba(91,141,238,0.18); --border-strong:rgba(91,141,238,0.36);
22
+ --radius:14px; --blur:18px;
23
+ --font-d:"Space Grotesk",ui-sans-serif,system-ui,-apple-system,"Segoe UI",Inter,Roboto,sans-serif;
24
+ --font-m:"JetBrains Mono",ui-monospace,"SF Mono",Menlo,Consolas,monospace;
25
+ --shadow:0 18px 60px rgba(0,0,0,0.6);
26
+ }
27
+ *{box-sizing:border-box;margin:0;padding:0}
28
+ html,body{height:100%;background:var(--void);color:var(--text);
29
+ font-family:var(--font-d);-webkit-font-smoothing:antialiased;overflow:hidden}
30
+ a{color:var(--proof);text-decoration:none} a:hover{text-decoration:underline}
31
+
32
+ #scene{position:fixed;inset:0;display:block;touch-action:none}
33
+
34
+ /* ---- HUD overlay (does not steal scene pointer unless on a panel) ---- */
35
+ .hud{position:fixed;z-index:5;pointer-events:none}
36
+ .panel{pointer-events:auto;background:var(--surface);backdrop-filter:blur(var(--blur));
37
+ border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow)}
38
+ .hdr{font-family:var(--font-m);font-size:9px;letter-spacing:.22em;text-transform:uppercase;
39
+ color:var(--faint);padding-bottom:8px;margin-bottom:9px;border-bottom:1px solid var(--border)}
40
+
41
+ /* top-left: title */
42
+ #title{top:16px;left:16px;max-width:min(46ch,calc(100vw - 32px))}
43
+ #title .eyebrow{font-family:var(--font-m);font-size:9px;letter-spacing:.26em;text-transform:uppercase;color:var(--faint);margin-bottom:6px}
44
+ #title h1{font-size:18px;font-weight:600;line-height:1.15;letter-spacing:-.01em}
45
+ #title h1 .accent{color:var(--proof)}
46
+ #title .sub{font-size:11px;color:var(--muted);margin-top:7px;line-height:1.45;padding:11px 14px 0;display:none}
47
+ #title .inner{padding:13px 14px}
48
+
49
+ /* top-right: mind posture + Λ */
50
+ #mind{top:16px;right:16px;width:min(290px,calc(100vw - 32px));padding:13px 15px}
51
+ #mind .hdr{display:flex;justify-content:space-between;align-items:center}
52
+ #mind .row{display:flex;gap:9px;align-items:baseline;font-size:11.5px;line-height:1.5;color:var(--muted);margin-bottom:5px}
53
+ #mind .row:last-child{margin-bottom:0}
54
+ #mind .row .k{flex:0 0 64px;color:var(--faint);font-family:var(--font-m);font-size:9.5px;letter-spacing:.04em;text-transform:uppercase}
55
+ #mind .row b{color:var(--text);font-weight:600;font-family:var(--font-m);font-size:11px}
56
+ .badge{display:inline-block;font-family:var(--font-m);font-size:9.5px;letter-spacing:.03em;padding:2px 8px;border-radius:99px;border:1px solid currentColor;white-space:nowrap}
57
+ .sov-true{color:var(--proof)} .sov-false{color:var(--warn)} .sov-unknown{color:var(--faint)}
58
+ #lambda-wrap{margin-top:10px;padding-top:10px;border-top:1px solid var(--border)}
59
+ #lambda-val{font-family:var(--font-m);font-size:21px;font-weight:600;color:var(--gold);letter-spacing:.01em}
60
+ #lambda-meta{font-family:var(--font-m);font-size:9.5px;color:var(--faint);margin-top:3px;line-height:1.4}
61
+ #ecg{width:100%;height:34px;margin-top:8px;display:block}
62
+
63
+ /* bottom-left: organ status list */
64
+ #organs{bottom:16px;left:16px;width:min(290px,calc(100vw - 32px));padding:13px 15px}
65
+ .orow{display:flex;align-items:center;gap:9px;font-size:11.5px;line-height:1.45;margin-bottom:8px}
66
+ .orow:last-child{margin-bottom:0}
67
+ .odot{flex:0 0 auto;width:9px;height:9px;border-radius:50%;background:var(--dim);box-shadow:0 0 0 transparent;transition:all .3s}
68
+ .orow[data-state="live"] .odot{box-shadow:0 0 9px currentColor}
69
+ .orow .on{font-weight:600;color:var(--text);min-width:74px;font-size:11px}
70
+ .orow .od{font-family:var(--font-m);font-size:9.5px;color:var(--muted);line-height:1.35}
71
+ .orow[data-state="unreachable"] .od{color:var(--faint)}
72
+ .orow[data-state="pending"] .odot{animation:breathe 1.1s ease-in-out infinite}
73
+ @keyframes breathe{0%,100%{opacity:.35}50%{opacity:1}}
74
+
75
+ /* bottom-right: controls + log + honesty */
76
+ #side{bottom:16px;right:16px;width:min(320px,calc(100vw - 32px));padding:13px 15px}
77
+ .controls{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:10px}
78
+ .btn{font-family:var(--font-m);font-size:10.5px;letter-spacing:.02em;color:var(--muted);background:var(--surface2);
79
+ border:1px solid var(--border);border-radius:99px;padding:8px 13px;cursor:pointer;transition:all .16s}
80
+ .btn:hover{border-color:var(--border-strong);color:var(--text);transform:translateY(-1px)}
81
+ .btn:focus-visible{outline:2px solid var(--lattice);outline-offset:2px}
82
+ .btn.primary{color:var(--proof);border-color:rgba(58,244,200,.45);background:rgba(58,244,200,.07)}
83
+ .btn[aria-disabled="true"]{opacity:.5;cursor:progress}
84
+ #log{font-family:var(--font-m);font-size:10px;color:var(--faint);line-height:1.55;min-height:2.6em;max-height:84px;overflow:auto}
85
+ #log b{color:var(--muted)}
86
+ #honesty{margin-top:10px;padding-top:10px;border-top:1px solid var(--border);font-size:10px;color:var(--faint);line-height:1.5}
87
+ #honesty b{color:var(--muted);font-weight:600}
88
+ .sw{display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--proof);box-shadow:0 0 6px currentColor;color:var(--proof);margin-right:5px;vertical-align:middle}
89
+
90
+ .legend{position:fixed;z-index:5;left:50%;bottom:14px;transform:translateX(-50%);pointer-events:none;
91
+ display:flex;gap:14px;font-family:var(--font-m);font-size:9px;letter-spacing:.04em;color:var(--faint);
92
+ background:rgba(8,12,20,.55);padding:6px 13px;border-radius:99px;border:1px solid var(--border)}
93
+ .legend span{display:flex;align-items:center;gap:5px}
94
+ .legend i{width:8px;height:8px;border-radius:2px;display:inline-block}
95
+
96
+ #boot{position:fixed;inset:0;z-index:9;display:flex;align-items:center;justify-content:center;
97
+ background:var(--void);color:var(--faint);font-family:var(--font-m);font-size:12px;letter-spacing:.08em}
98
+
99
+ /* tighten on small screens: hide secondary panels, keep mind + organs + log */
100
+ @media (max-width:760px){
101
+ #title{max-width:calc(100vw - 32px)} #title h1{font-size:15px}
102
+ #mind,#organs,#side{width:calc(100vw - 32px)}
103
+ #organs{bottom:auto;top:auto;display:none} /* avoid overlap on phones */
104
+ .legend{font-size:8px;gap:9px;bottom:10px}
105
+ }
106
+ @media (prefers-reduced-motion:reduce){
107
+ .orow[data-state="pending"] .odot{animation:none}
108
+ }
109
+ </style>
110
+ </head>
111
+ <body>
112
+ <canvas id="scene" aria-label="3D living organism of the Sovereign Org"></canvas>
113
+ <div id="boot">initializing living body…</div>
114
+
115
+ <div class="hud" id="title"><div class="inner">
116
+ <div class="eyebrow">SZL Living Anatomy · body v1</div>
117
+ <h1>The Sovereign Org as <span class="accent">one living organism</span></h1>
118
+ <div class="sub">Vessels are the one DSSE chain. Each travelling pulse is a REAL receipt
119
+ from the ledger; each organ glows only on a real probe; Λ drives the heartbeat.
120
+ <a href="./index.html">← full 3D atlas</a></div>
121
+ </div></div>
122
+
123
+ <div class="hud panel" id="mind" aria-live="polite">
124
+ <div class="hdr"><span>GPU mind · posture</span><span>/code/healthz</span></div>
125
+ <div class="row"><span class="k">sovereign</span><span id="m-sov" class="badge sov-unknown">…</span></div>
126
+ <div class="row"><span class="k">backend</span><b id="m-backend">…</b></div>
127
+ <div class="row"><span class="k">mode</span><b id="m-mode">…</b></div>
128
+ <div class="row"><span class="k">doctrine</span><b id="m-doctrine">…</b></div>
129
+ <div id="lambda-wrap">
130
+ <div id="lambda-val">Λ …</div>
131
+ <div id="lambda-meta">heartbeat driver · /v1/lambda</div>
132
+ <canvas id="ecg" width="560" height="68" aria-hidden="true"></canvas>
133
+ </div>
134
+ </div>
135
+
136
+
137
+ <div class="hud panel" id="integrity" style="top:auto;bottom:16px;left:16px;width:min(290px,calc(100vw - 32px));padding:13px 15px;transform:translateY(-210px)">
138
+ <div class="hdr">fail-closed kernel</div>
139
+ <div id="integrity-strip" data-state="pending" style="font-family:var(--font-m);font-size:10.5px;color:var(--muted);line-height:1.45">organ-integrity not yet polled</div>
140
+ <div style="margin-top:8px;font-size:10px;color:var(--faint)">GET /api/anatomy/v1/organs/integrity · energy UNAVAILABLE · Λ = Conjecture 1</div>
141
+ </div>
142
+
143
+ <div class="hud panel" id="organs" aria-live="polite">
144
+ <div class="hdr">organs · honest probes</div>
145
+ <div id="organ-rows"></div>
146
+ </div>
147
+
148
+ <div class="hud panel" id="side">
149
+ <div class="controls">
150
+ <button id="run" class="btn primary" type="button">▶ Run proactive cycle</button>
151
+ <button id="refresh" class="btn" type="button">↻ Refresh</button>
152
+ </div>
153
+ <div id="log" aria-live="polite"></div>
154
+ <div id="honesty">
155
+ <span class="sw"></span><b id="h-lambda">Λ = Conjecture 1</b> — advisory, never green.<br>
156
+ <span class="sw"></span><b>Verticals</b> &amp; <b>SLSA</b>: no live endpoint → honest ROADMAP, no fake flow.<br>
157
+ <span class="sw"></span>Read-only · no key sent · open-weight.
158
+ </div>
159
+ </div>
160
+
161
+ <div class="legend hud">
162
+ <span><i style="background:var(--proof)"></i>live receipt pulse</span>
163
+ <span><i style="background:var(--warn)"></i>denied gate</span>
164
+ <span><i style="background:var(--gold)"></i>Λ heartbeat</span>
165
+ <span><i style="background:var(--dim)"></i>unreachable / roadmap</span>
166
+ </div>
167
+
168
+ <script src="./lib/three.min.js"></script>
169
+ <script type="module">
170
+ import LiveBody from "./live-body.js";
171
+ const THREE = window.THREE;
172
+ const K = LiveBody.KANCHAY;
173
+ const $ = (id) => document.getElementById(id);
174
+
175
+ /* ============================ scene scaffold ============================== */
176
+ const canvas = $("scene");
177
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false });
178
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
179
+ renderer.setClearColor(new THREE.Color(K.void), 1);
180
+
181
+ const scene = new THREE.Scene();
182
+ scene.fog = new THREE.FogExp2(new THREE.Color(K.void), 0.085);
183
+ const camera = new THREE.PerspectiveCamera(46, 1, 0.1, 100);
184
+ camera.position.set(0, 0.2, 6.2);
185
+
186
+ scene.add(new THREE.AmbientLight(0x4a5878, 0.9));
187
+ const key = new THREE.PointLight(0x9fc2ff, 1.1, 40); key.position.set(4, 6, 8); scene.add(key);
188
+ const rim = new THREE.PointLight(0x3af4c8, 0.7, 40); rim.position.set(-6, -3, 4); scene.add(rim);
189
+
190
+ const root = new THREE.Group(); scene.add(root); // everything rotatable
191
+
192
+ /* radial glow sprite texture (additive "selective bloom" — no jsm composer vendored) */
193
+ function glowTexture() {
194
+ const s = 64, c = document.createElement("canvas"); c.width = c.height = s;
195
+ const g = c.getContext("2d");
196
+ const grd = g.createRadialGradient(s/2, s/2, 0, s/2, s/2, s/2);
197
+ grd.addColorStop(0, "rgba(255,255,255,1)");
198
+ grd.addColorStop(0.25, "rgba(255,255,255,0.55)");
199
+ grd.addColorStop(1, "rgba(255,255,255,0)");
200
+ g.fillStyle = grd; g.fillRect(0, 0, s, s);
201
+ const t = new THREE.CanvasTexture(c); t.needsUpdate = true; return t;
202
+ }
203
+ const GLOW = glowTexture();
204
+ function glowSprite(color, scale, opacity) {
205
+ const m = new THREE.SpriteMaterial({ map: GLOW, color: new THREE.Color(color),
206
+ transparent: true, opacity, blending: THREE.AdditiveBlending, depthWrite: false });
207
+ const sp = new THREE.Sprite(m); sp.scale.set(scale, scale, 1); return sp;
208
+ }
209
+
210
+ /* ============================ organs ===================================== */
211
+ const organMeshes = new Map(); // id -> {core, halo, color, baseEmissive, pos}
212
+ const ORGAN_GEO = {
213
+ reasoning: () => new THREE.IcosahedronGeometry(0.32, 1),
214
+ policy: () => new THREE.DodecahedronGeometry(0.30, 0),
215
+ operator: () => new THREE.OctahedronGeometry(0.32, 1),
216
+ receipts: () => new THREE.IcosahedronGeometry(0.40, 2), // the heart hub (center-low)
217
+ };
218
+ for (const o of LiveBody.ORGANS) {
219
+ const geo = (ORGAN_GEO[o.id] || (() => new THREE.IcosahedronGeometry(0.3, 1)))();
220
+ const col = new THREE.Color(o.color);
221
+ const mat = new THREE.MeshStandardMaterial({
222
+ color: col, emissive: col, emissiveIntensity: 0.15,
223
+ metalness: 0.2, roughness: 0.45, flatShading: true });
224
+ const core = new THREE.Mesh(geo, mat);
225
+ core.position.set(o.pos[0], o.pos[1], o.pos[2]);
226
+ const halo = glowSprite(o.color, 1.25, 0.0); halo.position.copy(core.position);
227
+ root.add(core); root.add(halo);
228
+ organMeshes.set(o.id, { core, halo, color: col, mat, pos: core.position.clone() });
229
+ }
230
+ const HEART = organMeshes.get("receipts"); // Λ heartbeat target
231
+
232
+ /* ============================ vessels (the chain) ======================== *
233
+ * One CatmullRom Bezier tube from each organ to the heart (RECEIPTS). These ARE
234
+ * the one DSSE chain; pulses travel them. <12 tubes => trivial draw-call cost. */
235
+ const vessels = new Map(); // organId -> {curve, mesh}
236
+ function makeVessel(fromPos, toPos, color) {
237
+ const mid = fromPos.clone().lerp(toPos, 0.5);
238
+ const bow = fromPos.clone().sub(toPos); // perpendicular-ish bow for a vessel look
239
+ mid.add(new THREE.Vector3(-bow.y, bow.x, bow.z * 0.5).multiplyScalar(0.28));
240
+ mid.z += 0.35;
241
+ const curve = new THREE.CatmullRomCurve3([fromPos.clone(), mid, toPos.clone()]);
242
+ const geo = new THREE.TubeGeometry(curve, 40, 0.018, 6, false);
243
+ const mat = new THREE.MeshBasicMaterial({ color: new THREE.Color(color),
244
+ transparent: true, opacity: 0.22 });
245
+ const mesh = new THREE.Mesh(geo, mat); root.add(mesh);
246
+ return { curve, mesh };
247
+ }
248
+ for (const o of LiveBody.ORGANS) {
249
+ if (o.id === "receipts") continue;
250
+ vessels.set(o.id, makeVessel(organMeshes.get(o.id).pos, HEART.pos, K.lattice));
251
+ }
252
+
253
+ /* ============================ verticals (limbs) ========================== *
254
+ * Honest ROADMAP: rendered, dim, labeled — never fake-pulsed (no live throughput
255
+ * endpoint). They wake only if a real "<vertical>|<action>" receipt arrives. */
256
+ const limbs = new Map();
257
+ for (const v of LiveBody.VERTICALS) {
258
+ const geo = new THREE.TorusGeometry(0.16, 0.045, 8, 16);
259
+ const col = new THREE.Color(v.color);
260
+ const mat = new THREE.MeshStandardMaterial({ color: col, emissive: col,
261
+ emissiveIntensity: 0.04, metalness: 0.3, roughness: 0.6, flatShading: true });
262
+ const m = new THREE.Mesh(geo, mat); m.position.set(v.pos[0], v.pos[1], v.pos[2]);
263
+ m.rotation.x = Math.PI / 2; root.add(m);
264
+ // honest dashed tether to torso (structure only, not a chain vessel)
265
+ limbs.set(v.id, { mesh: m, color: col });
266
+ }
267
+
268
+ /* ============================ skeleton (SLSA) ============================ *
269
+ * Structural spine ring. Honest: no /v1/slsa endpoint => integrity UNVERIFIED;
270
+ * rendered as faint structure, never claiming a verified SLSA level. */
271
+ const spineMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(K.dim),
272
+ transparent: true, opacity: 0.16, wireframe: true });
273
+ const spine = new THREE.Mesh(new THREE.TorusGeometry(1.55, 0.012, 4, 48), spineMat);
274
+ spine.rotation.x = Math.PI / 2.2; root.add(spine);
275
+
276
+ /* ============================ immune swarm (E5) ========================== *
277
+ * GPU-instanced antibodies. count = REAL fraction of mesh engines down
278
+ * (/v1/govern/health). Dormant (count 0) when the mesh is healthy. */
279
+ const SWARM_MAX = 1200;
280
+ const swarmGeo = new THREE.SphereGeometry(0.018, 6, 6);
281
+ const swarmMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(K.warn),
282
+ transparent: true, opacity: 0.8, blending: THREE.AdditiveBlending, depthWrite: false });
283
+ const swarm = new THREE.InstancedMesh(swarmGeo, swarmMat, SWARM_MAX);
284
+ swarm.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
285
+ swarm.count = 0; root.add(swarm);
286
+ const swarmSeed = [];
287
+ for (let i = 0; i < SWARM_MAX; i++) {
288
+ swarmSeed.push({ r: 0.55 + Math.random() * 0.5, a: Math.random() * Math.PI * 2,
289
+ b: Math.random() * Math.PI, sp: 0.4 + Math.random() * 0.8 });
290
+ }
291
+ const _m = new THREE.Matrix4(), _v = new THREE.Vector3();
292
+
293
+ /* ============================ pulse pool ================================= *
294
+ * Each active pulse corresponds to a REAL receipt. Pooled so we never exceed the
295
+ * perf budget; LIVE pulses recycle. Denied receipts bounce back at the organ wall. */
296
+ const POOL = 48;
297
+ const pulseCore = [];
298
+ for (let i = 0; i < POOL; i++) {
299
+ const grp = new THREE.Group();
300
+ const core = new THREE.Mesh(new THREE.SphereGeometry(0.05, 8, 8),
301
+ new THREE.MeshBasicMaterial({ color: 0xffffff }));
302
+ const gl = glowSprite("#ffffff", 0.42, 0.9); grp.add(core); grp.add(gl);
303
+ grp.visible = false; root.add(grp);
304
+ pulseCore.push({ grp, core, gl, active: false, t: 0, speed: 0.0, curve: null,
305
+ color: new THREE.Color(K.proof), denied: false, dir: 1 });
306
+ }
307
+ function spawnPulse(organId, color, denied) {
308
+ const v = vessels.get(organId) || vessels.get("policy");
309
+ if (!v) return;
310
+ const p = pulseCore.find((x) => !x.active);
311
+ if (!p) return; // pool exhausted this frame; honest backpressure (no over-budget spawns)
312
+ p.active = true; p.t = 0; p.dir = 1; p.denied = !!denied;
313
+ p.speed = 0.45 + Math.random() * 0.2;
314
+ p.curve = v.curve; p.color.set(denied ? K.warn : (color || K.proof));
315
+ p.core.material.color.copy(p.color); p.gl.material.color.copy(p.color);
316
+ p.grp.visible = true;
317
+ }
318
+
319
+ /* ============================ HUD: organ rows ============================ */
320
+ const organRows = new Map();
321
+ for (const o of LiveBody.ORGANS) {
322
+ const row = document.createElement("div");
323
+ row.className = "orow"; row.dataset.state = "pending";
324
+ row.innerHTML =
325
+ `<span class="odot" style="color:${o.color}"></span>
326
+ <span class="on">${o.name}</span>
327
+ <span class="od">probing…</span>`;
328
+ $("organ-rows").appendChild(row);
329
+ organRows.set(o.id, row);
330
+ }
331
+ function setOrganDot(row, state, color) {
332
+ const dot = row.querySelector(".odot");
333
+ dot.style.background = state === "live" ? color : "var(--dim)";
334
+ }
335
+
336
+ /* ============================ live data wiring =========================== */
337
+ const STATE = { lambda: 0.90, lambdaPass: true, organLive: {}, lastSeq: -1, immune: 0 };
338
+ let seenIds = new Set();
339
+
340
+ function logLine(html) {
341
+ const el = $("log");
342
+ el.innerHTML = html + "<br>" + el.innerHTML;
343
+ if (el.innerHTML.length > 2400) el.innerHTML = el.innerHTML.slice(0, 2400);
344
+ }
345
+
346
+ async function refreshOrgans() {
347
+ await Promise.all(LiveBody.ORGANS.map(async (o) => {
348
+ const r = await LiveBody.probeOrgan(o);
349
+ const row = organRows.get(o.id);
350
+ row.dataset.state = r.status;
351
+ const od = row.querySelector(".od");
352
+ if (r.status === LiveBody.STATUS.LIVE) {
353
+ od.textContent = r.detail; setOrganDot(row, "live", o.color);
354
+ STATE.organLive[o.id] = true;
355
+ const om = organMeshes.get(o.id);
356
+ om.mat.emissiveIntensity = 0.6; // healthy glow
357
+ } else {
358
+ od.textContent = `unreachable — ${r.detail} · honest empty-state`;
359
+ setOrganDot(row, "unreachable"); STATE.organLive[o.id] = false;
360
+ organMeshes.get(o.id).mat.emissiveIntensity = 0.06; // dim, honest
361
+ }
362
+ }));
363
+ }
364
+
365
+ async function refreshMind() {
366
+ const m = await LiveBody.fetchMind();
367
+ const sov = $("m-sov");
368
+ if (!m.reachable) {
369
+ sov.className = "badge sov-unknown"; sov.textContent = "unknown";
370
+ $("m-backend").textContent = "unreachable"; $("m-mode").textContent = m.why || "—";
371
+ $("m-doctrine").textContent = "—"; return;
372
+ }
373
+ if (m.sovereign === true) { sov.className = "badge sov-true"; sov.textContent = "true (local serves)"; }
374
+ else { sov.className = "badge sov-false"; sov.textContent = "false (router serves)"; }
375
+ $("m-backend").textContent = m.backend; $("m-mode").textContent = m.mode;
376
+ $("m-doctrine").textContent = m.doctrine || "—";
377
+ }
378
+
379
+ async function refreshLambda() {
380
+ const d = await LiveBody.fetchLambda();
381
+ if (!d.reachable || d.lambda == null) {
382
+ $("lambda-val").textContent = "Λ unreachable";
383
+ $("lambda-meta").textContent = `${d.why || "no data"} · honest empty-state`;
384
+ return;
385
+ }
386
+ STATE.lambda = d.lambda; STATE.lambdaPass = d.pass;
387
+ $("lambda-val").textContent = `Λ ${d.lambda.toFixed(5)}`;
388
+ $("lambda-meta").textContent =
389
+ `${d.pass ? "≥" : "<"} floor ${d.floor} · ${d.axes.length}-axis ${d.aggregate ? "· " + d.aggregate.split("(")[0].trim() : ""}`;
390
+ $("h-lambda").textContent = `Λ = ${d.uniqueness}`;
391
+ }
392
+
393
+ async function refreshDoctrine() {
394
+ const d = await LiveBody.fetchDoctrine();
395
+ if (!d.reachable) return;
396
+ $("h-lambda").textContent = `Λ = ${d.lambda}`;
397
+ }
398
+
399
+ async function refreshImmune() {
400
+ const im = await LiveBody.fetchImmune();
401
+ STATE.immune = im.reachable ? im.intensity : 0;
402
+ swarm.count = Math.round(STATE.immune * SWARM_MAX);
403
+ if (im.reachable) logLine(`<b>immune:</b> ${im.detail}`);
404
+ }
405
+
406
+ /* spawn pulses for REAL receipts we haven't shown yet (honest: 1 pulse / receipt) */
407
+ async function refreshLedger(initial) {
408
+ const L = await LiveBody.fetchLedger();
409
+ if (!L.reachable) {
410
+ logLine(`<b>ledger:</b> UNREACHABLE — ${L.why} · no pulses faked.`);
411
+ return 0;
412
+ }
413
+ let spawned = 0;
414
+ const recent = L.receipts.slice(-POOL); // cap to pool; never exceed budget
415
+ for (const r of recent) {
416
+ if (seenIds.has(r.id)) continue;
417
+ seenIds.add(r.id);
418
+ if (!initial) { // on refresh, only animate genuinely-new receipts
419
+ spawnPulse(r.organ, organMeshes.get(r.organ)?.color.getStyle(), r.denied);
420
+ spawned++;
421
+ }
422
+ }
423
+ logLine(`<b>ledger:</b> ${L.count} receipts on the chain${spawned ? ` · +${spawned} new pulse(s)` : ""}.`);
424
+ return L.count;
425
+ }
426
+
427
+ async function refreshAll(initial) {
428
+ await Promise.all([refreshOrgans(), refreshMind(), refreshLambda(), refreshDoctrine(), refreshImmune()]);
429
+ await refreshLedger(initial);
430
+ }
431
+
432
+ /* the proactive cycle: replay the REAL chain's organ order as travelling pulses */
433
+ let running = false;
434
+ async function runCycle() {
435
+ if (running) return; running = true;
436
+ const btn = $("run"); btn.setAttribute("aria-disabled", "true");
437
+ const L = await LiveBody.fetchLedger();
438
+ if (!L.reachable) {
439
+ logLine(`<b>cycle:</b> ledger UNREACHABLE — ${L.why}; nothing faked.`);
440
+ btn.removeAttribute("aria-disabled"); running = false; return;
441
+ }
442
+ logLine(`<b>proactive cycle:</b> replaying ${L.receipts.length} real receipts…`);
443
+ for (const r of L.receipts) {
444
+ spawnPulse(r.organ, organMeshes.get(r.organ)?.color.getStyle(), r.denied);
445
+ await sleep(150);
446
+ }
447
+ logLine(`<b>cycle complete</b> — every pulse was a real receipt (seq 0…${L.receipts.length - 1}).`);
448
+ btn.removeAttribute("aria-disabled"); running = false;
449
+ }
450
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
451
+
452
+ /* ============================ Λ heartbeat (E7) =========================== *
453
+ * Double-beat ECG waveform; rate scales with Λ. Drives heart scale + emissive
454
+ * and the overall organism glow. Honest: when Λ is unreachable it flatlines. */
455
+ const ecg = $("ecg"), ectx = ecg.getContext("2d");
456
+ let beatPhase = 0;
457
+ function heartbeatEnvelope(phase) {
458
+ // two gaussian "lub-dub" bumps per cycle
459
+ const g = (c, w) => Math.exp(-((phase - c) ** 2) / (2 * w * w));
460
+ return g(0.18, 0.05) * 1.0 + g(0.34, 0.07) * 0.62;
461
+ }
462
+ function drawECG() {
463
+ const w = ecg.width, h = ecg.height; ectx.clearRect(0, 0, w, h);
464
+ ectx.strokeStyle = STATE.lambdaPass ? K.gold : K.warn; ectx.lineWidth = 1.6;
465
+ ectx.beginPath();
466
+ for (let x = 0; x <= w; x++) {
467
+ const ph = ((x / w) + beatPhase) % 1;
468
+ const y = h * 0.5 - heartbeatEnvelope(ph) * h * 0.42;
469
+ x === 0 ? ectx.moveTo(x, y) : ectx.lineTo(x, y);
470
+ }
471
+ ectx.stroke();
472
+ }
473
+
474
+ /* ============================ animation loop ============================= */
475
+ let last = performance.now(), dragX = 0, dragY = 0, autoSpin = 0.04;
476
+ function animate(now) {
477
+ const dt = Math.min(0.05, (now - last) / 1000); last = now;
478
+ // heartbeat rate from Λ (0.90→~0.8Hz, 1.0→~1.2Hz)
479
+ const rate = 0.8 + Math.max(0, STATE.lambda - 0.9) * 4;
480
+ beatPhase = (beatPhase + dt * rate) % 1;
481
+ const env = heartbeatEnvelope(beatPhase);
482
+ // heart pulse + overall glow
483
+ const s = 1 + env * 0.16; HEART.core.scale.setScalar(s);
484
+ HEART.mat.emissiveIntensity = (STATE.organLive.receipts ? 0.55 : 0.06) + env * 0.7;
485
+ HEART.halo.material.opacity = 0.12 + env * 0.4;
486
+ // organ halos track health + breathe with the beat
487
+ for (const [id, om] of organMeshes) {
488
+ const liveOn = STATE.organLive[id];
489
+ om.halo.material.opacity = (liveOn ? 0.16 : 0.0) + (liveOn ? env * 0.18 : 0);
490
+ om.core.rotation.y += dt * 0.25; om.core.rotation.x += dt * 0.12;
491
+ }
492
+ // verticals gently breathe but stay dim (honest ROADMAP)
493
+ for (const [, lb] of limbs) lb.mesh.rotation.z += dt * 0.2;
494
+ // pulses travel their vessel; denied bounce back at the organ wall
495
+ for (const p of pulseCore) {
496
+ if (!p.active) continue;
497
+ p.t += dt * p.speed * p.dir;
498
+ if (p.denied && p.t >= 0.82) { p.dir = -1; } // rejected at the wall → bounce
499
+ if (p.t >= 1 || p.t <= 0) {
500
+ // arrived at heart (allow) or returned to organ (denied) → recycle
501
+ p.active = false; p.grp.visible = false; continue;
502
+ }
503
+ const pt = p.curve.getPointAt(Math.min(0.999, Math.max(0.001, p.t)));
504
+ p.grp.position.copy(pt);
505
+ // brighten the heart very slightly as an allow-pulse lands
506
+ }
507
+ // immune swarm orbit (instanced)
508
+ if (swarm.count > 0) {
509
+ for (let i = 0; i < swarm.count; i++) {
510
+ const sd = swarmSeed[i]; sd.a += dt * sd.sp;
511
+ _v.set(Math.sin(sd.b) * Math.cos(sd.a) * sd.r,
512
+ Math.cos(sd.b) * sd.r * 0.6,
513
+ Math.sin(sd.b) * Math.sin(sd.a) * sd.r);
514
+ _m.makeTranslation(_v.x, _v.y, _v.z); swarm.setMatrixAt(i, _m);
515
+ }
516
+ swarm.instanceMatrix.needsUpdate = true;
517
+ }
518
+ // gentle auto-spin + drag
519
+ root.rotation.y += dt * autoSpin + dragX; root.rotation.x += dragY;
520
+ root.rotation.x = Math.max(-0.5, Math.min(0.5, root.rotation.x));
521
+ dragX *= 0.85; dragY *= 0.85;
522
+ drawECG();
523
+ renderer.render(scene, camera);
524
+ requestAnimationFrame(animate);
525
+ }
526
+
527
+ /* ============================ resize + input ============================= */
528
+ function resize() {
529
+ const w = window.innerWidth, h = window.innerHeight;
530
+ renderer.setSize(w, h, false); camera.aspect = w / h; camera.updateProjectionMatrix();
531
+ }
532
+ window.addEventListener("resize", resize); resize();
533
+
534
+ let dragging = false, lx = 0, ly = 0;
535
+ canvas.addEventListener("pointerdown", (e) => { dragging = true; lx = e.clientX; ly = e.clientY; autoSpin = 0; });
536
+ window.addEventListener("pointerup", () => { dragging = false; autoSpin = 0.04; });
537
+ window.addEventListener("pointermove", (e) => {
538
+ if (!dragging) return;
539
+ dragX = (e.clientX - lx) * 0.00018; dragY = (e.clientY - ly) * 0.00012;
540
+ lx = e.clientX; ly = e.clientY;
541
+ });
542
+
543
+ /* ============================ boot ======================================= */
544
+ $("run").addEventListener("click", runCycle);
545
+ $("refresh").addEventListener("click", () => refreshAll(false));
546
+ (async () => {
547
+ await refreshAll(true); // initial: seed seenIds without a pulse storm
548
+ $("boot").style.display = "none";
549
+ requestAnimationFrame(animate);
550
+ // a short delayed replay so the first load visibly shows real receipts flowing
551
+ setTimeout(runCycle, 400);
552
+ })();
553
+ </script>
554
+ </body>
555
+ </html>
live-body.js ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* =============================================================================
2
+ * live-body.js — SZL Living Anatomy · BODY v1 ENGINE (the living face)
3
+ * =============================================================================
4
+ * The Sovereign Org rendered as ONE living governed organism. This module is the
5
+ * HONEST DATA SPINE for live-body.html's Three.js scene. It reads the SAME live
6
+ * a11oy endpoints the unified console reads and exposes them as honest records.
7
+ *
8
+ * CRITICAL DISCIPLINE (binding — honest by construction, never a screensaver):
9
+ * - Every pulse travelling a vessel corresponds to a REAL receipt on the chain
10
+ * (/api/a11oy/v1/ledger). We never synthesize a receipt.
11
+ * - Every organ glows LIVE only on a real 2xx+JSON probe; otherwise it dims to an
12
+ * honest UNREACHABLE state. We never fabricate a green light.
13
+ * - sovereign:true is shown ONLY when /code/healthz reports the literal true.
14
+ * - Λ is advisory and its uniqueness is Conjecture 1 — pulled live from
15
+ * /v1/lambda + /v1/honest, never hardcoded as proven.
16
+ * - Verticals (insurance/defense/finance/realestate), SLSA skeletal integrity,
17
+ * and drift have NO live endpoint on this Space today, so they render in an
18
+ * explicit ROADMAP / N-A state — limbs do NOT fake-pulse and the skeleton does
19
+ * NOT claim a verified SLSA level. Honest absence over decorative motion.
20
+ * - Read-only. No key is sent. open-weight only.
21
+ *
22
+ * No build step, no framework, no CDN — a plain ES module that runs as a static
23
+ * SDK page at the .static.hf.space URL, exactly like index.html.
24
+ * ============================================================================ */
25
+ "use strict";
26
+
27
+ /* ---- the single live host the console reads (verified live this session) --- */
28
+ const HOST = "https://szlholdings-a11oy.hf.space";
29
+
30
+ /* Real, verified endpoints (curl-checked 2026-06-30):
31
+ * /api/a11oy/v1/ledger -> {count, receipts:[{seq,action,receipt_id}]} (THE chain)
32
+ * /api/a11oy/v1/lambda -> {trust_axes,axes[],lambda,lambda_floor,pass,uniqueness}
33
+ * /api/a11oy/code/healthz -> {sovereign,backend,mode,doctrine_state,...}
34
+ * /api/a11oy/v1/honest -> {doctrine_lock:{lambda,locked_formula_ids,...}}
35
+ * /api/a11oy/readyz -> {status,operator:{operator_running,...}}
36
+ * /api/a11oy/v1/govern/health-> {engines_live,engines_total,mesh[]} */
37
+ const EP = {
38
+ ledger: HOST + "/api/a11oy/v1/ledger",
39
+ lambda: HOST + "/api/a11oy/v1/lambda",
40
+ healthz: HOST + "/api/a11oy/code/healthz",
41
+ honest: HOST + "/api/a11oy/v1/honest",
42
+ readyz: HOST + "/api/a11oy/readyz",
43
+ govern: HOST + "/api/a11oy/v1/govern/health",
44
+ integrity: HOST + "/api/a11oy/v1/organs/integrity",
45
+ };
46
+
47
+ /* ---- KANCHAY palette (canonical brand · purple BANNED) -------------------- */
48
+ const KANCHAY = {
49
+ void: "#080c14",
50
+ proof: "#3af4c8", // teal — proven / live
51
+ lattice: "#5b8dee", // blue — structure / vessels
52
+ gold: "#d7b96b", // gold — Λ / heartbeat accent
53
+ warn: "#e0795b", // ember — denied / down
54
+ dim: "#3a4456", // honest unreachable / dormant
55
+ text: "#e9eef7",
56
+ };
57
+
58
+ /* ---- status vocabulary ---------------------------------------------------- */
59
+ const STATUS = {
60
+ LIVE: "live", // endpoint answered 2xx with usable JSON
61
+ UNREACHABLE: "unreachable", // network / non-2xx / not-JSON — honest unknown
62
+ PENDING: "pending", // not yet polled
63
+ };
64
+
65
+ /* ---- the 4 console organs, each a REAL probe ------------------------------ *
66
+ * These are the organs the unified console shows (Reasoning/Policy/Operator/
67
+ * Receipts). Each maps to a real endpoint that proves it is alive; LIVE only on
68
+ * a real 2xx+JSON answer, otherwise an honest UNREACHABLE dim. `pos` is a normalized
69
+ * body-space anchor [x,y,z] the scene uses to place the organ. */
70
+ const ORGANS = [
71
+ {
72
+ id: "reasoning", name: "REASONING", glyph: "✸", color: KANCHAY.proof,
73
+ pos: [0, 1.15, 0],
74
+ probe: "lambda",
75
+ role: "scores Λ (13-axis) + recommends the decision under uncertainty",
76
+ actions: ["lambda.score", "decision.recommend"],
77
+ summarize: (j) => {
78
+ if (typeof j.lambda === "number")
79
+ return `Λ ${j.lambda.toFixed(5)} ${j.pass ? "≥" : "<"} floor ${j.lambda_floor} · ${j.trust_axes || (j.axes||[]).length}-axis`;
80
+ return "reasoning responding";
81
+ },
82
+ },
83
+ {
84
+ id: "policy", name: "POLICY", glyph: "⛨", color: KANCHAY.gold,
85
+ pos: [-1.15, 0.15, 0.1],
86
+ probe: "honest",
87
+ role: "the deny-by-default gate (F12) — rejects unsafe / overclaiming work",
88
+ actions: ["gate.evaluate"],
89
+ summarize: (j) => {
90
+ const lk = j.doctrine_lock || {};
91
+ const ids = lk.locked_formula_ids || [];
92
+ const f12 = ids.includes("F12");
93
+ return `${lk.locked_formula_count ?? ids.length} locked · F12 gate ${f12 ? "armed" : "—"}`;
94
+ },
95
+ },
96
+ {
97
+ id: "operator", name: "OPERATOR", glyph: "⌁", color: KANCHAY.lattice,
98
+ pos: [1.15, 0.15, 0.1],
99
+ probe: "readyz",
100
+ role: "approves + executes admitted work; the hands of the organism",
101
+ actions: ["operator.approve"],
102
+ summarize: (j) => {
103
+ const op = j.operator || {};
104
+ if (op.operator_running === true) return `operator running · ${j.status || "ready"}`;
105
+ if (j.status) return `status: ${j.status}`;
106
+ return "operator responding";
107
+ },
108
+ },
109
+ {
110
+ id: "receipts", name: "RECEIPTS", glyph: "❤", color: KANCHAY.warn,
111
+ pos: [0, -1.15, 0],
112
+ probe: "ledger",
113
+ role: "signs + replays a verifiable receipt for every action (the heartbeat)",
114
+ actions: ["receipt.sign", "replay.verify"],
115
+ summarize: (j) => {
116
+ const rs = j.receipts || j.items || (Array.isArray(j) ? j : null);
117
+ const n = Array.isArray(rs) ? rs.length : (typeof j.count === "number" ? j.count : null);
118
+ return n != null ? `${n} receipts on the chain` : "receipt bus reachable";
119
+ },
120
+ },
121
+ ];
122
+
123
+ /* Which organ a receipt action originates from (so a pulse leaves the right
124
+ * organ and travels to RECEIPTS/heart). Unknown actions default to receipts. */
125
+ const ACTION_SOURCE = {
126
+ "gate.evaluate": "policy",
127
+ "lambda.score": "reasoning",
128
+ "decision.recommend": "reasoning",
129
+ "operator.approve": "operator",
130
+ "receipt.sign": "receipts",
131
+ "replay.verify": "receipts",
132
+ };
133
+ function organForAction(action) {
134
+ if (!action) return "receipts";
135
+ const a = String(action).toLowerCase();
136
+ if (ACTION_SOURCE[a]) return ACTION_SOURCE[a];
137
+ // honest heuristic for verbs we haven't enumerated
138
+ if (a.startsWith("gate")) return "policy";
139
+ if (a.startsWith("lambda") || a.includes("decision") || a.includes("reason")) return "reasoning";
140
+ if (a.includes("operator") || a.includes("approve") || a.includes("execute")) return "operator";
141
+ return "receipts";
142
+ }
143
+ /* An action is a DENIAL (rejected pulse) only when it honestly says so. */
144
+ function isDenied(action) {
145
+ const a = String(action || "").toLowerCase();
146
+ return a.includes("deny") || a.includes("denied") || a.includes("reject") || a.includes("block");
147
+ }
148
+
149
+ /* The 4 verticals = limbs. NO live throughput endpoint exists on this Space, so
150
+ * they render in an honest ROADMAP state and only pulse if a real receipt with a
151
+ * "<vertical>|<action>" verb appears on the chain. Never fake-pulsed. */
152
+ const VERTICALS = [
153
+ { id: "insurance", name: "INSURANCE", pos: [-1.7, -0.7, 0.0], color: KANCHAY.proof },
154
+ { id: "defense", name: "DEFENSE", pos: [ 1.7, -0.7, 0.0], color: KANCHAY.lattice },
155
+ { id: "finance", name: "FINANCE", pos: [-1.7, 0.9, 0.0], color: KANCHAY.gold },
156
+ { id: "realestate", name: "REALESTATE", pos: [ 1.7, 0.9, 0.0], color: KANCHAY.warn },
157
+ ];
158
+
159
+ /* ---- one honest GET (never throws; no creds, no custom headers => simple CORS) */
160
+ async function getJSON(url, timeoutMs = 9000) {
161
+ const ctl = new AbortController();
162
+ const t = setTimeout(() => ctl.abort(), timeoutMs);
163
+ try {
164
+ const res = await fetch(url, {
165
+ method: "GET", mode: "cors", credentials: "omit",
166
+ signal: ctl.signal, cache: "no-store",
167
+ });
168
+ clearTimeout(t);
169
+ if (!res.ok) return { ok: false, why: `HTTP ${res.status}` };
170
+ const ct = res.headers.get("content-type") || "";
171
+ if (!ct.includes("json")) return { ok: false, why: "no JSON (route unmatched?)" };
172
+ return { ok: true, json: await res.json() };
173
+ } catch (e) {
174
+ clearTimeout(t);
175
+ return { ok: false, why: (e && e.name === "AbortError") ? "timeout" : "network/CORS" };
176
+ }
177
+ }
178
+
179
+ /* probe one organ honestly -> {status, detail, raw} */
180
+ async function probeOrgan(organ, timeoutMs = 9000) {
181
+ const r = await getJSON(EP[organ.probe], timeoutMs);
182
+ if (!r.ok) return { status: STATUS.UNREACHABLE, detail: r.why, raw: null };
183
+ let detail;
184
+ try { detail = organ.summarize(r.json); }
185
+ catch { detail = "responding (shape unrecognized)"; }
186
+ return { status: STATUS.LIVE, detail, raw: r.json };
187
+ }
188
+
189
+ /* fetch the REAL receipt chain. Returns normalized receipts (or honest empty). */
190
+ async function fetchLedger(timeoutMs = 9000) {
191
+ const r = await getJSON(EP.ledger, timeoutMs);
192
+ if (!r.ok) return { reachable: false, why: r.why, count: 0, receipts: [] };
193
+ const j = r.json;
194
+ const raw = j.receipts || j.items || (Array.isArray(j) ? j : []);
195
+ const receipts = (Array.isArray(raw) ? raw : []).map((x, i) => {
196
+ const action = x.action || x.verb || x.kind || "receipt";
197
+ return {
198
+ seq: typeof x.seq === "number" ? x.seq : i,
199
+ action,
200
+ id: x.receipt_id || x.id || x.hash || String(i),
201
+ organ: organForAction(action),
202
+ denied: isDenied(action),
203
+ };
204
+ });
205
+ return { reachable: true, count: j.count ?? receipts.length, receipts };
206
+ }
207
+
208
+ /* fetch Λ posture (heartbeat driver). Honest: uniqueness stays Conjecture 1. */
209
+ async function fetchLambda(timeoutMs = 9000) {
210
+ const r = await getJSON(EP.lambda, timeoutMs);
211
+ if (!r.ok) return { reachable: false, why: r.why };
212
+ const j = r.json;
213
+ return {
214
+ reachable: true,
215
+ lambda: typeof j.lambda === "number" ? j.lambda : null,
216
+ floor: typeof j.lambda_floor === "number" ? j.lambda_floor : 0.90,
217
+ pass: j.pass === true,
218
+ axes: Array.isArray(j.axes) ? j.axes : [],
219
+ aggregate: j.aggregate || "",
220
+ uniqueness: j.uniqueness || "Conjecture 1",
221
+ raw: j,
222
+ };
223
+ }
224
+
225
+ /* fetch the GPU-mind posture (sovereign strict; default FALSE — never invent true) */
226
+ async function fetchMind(timeoutMs = 9000) {
227
+ const r = await getJSON(EP.healthz, timeoutMs);
228
+ if (!r.ok) return { reachable: false, sovereign: false, why: r.why };
229
+ const j = r.json;
230
+ return {
231
+ reachable: true,
232
+ sovereign: j.sovereign === true,
233
+ backend: j.backend || j.inference || "unknown",
234
+ mode: j.mode || "unknown",
235
+ doctrine: j.doctrine_state ? `${j.doctrine || ""} ${j.doctrine_state}`.trim() : (j.doctrine || ""),
236
+ raw: j,
237
+ };
238
+ }
239
+
240
+ /* fetch doctrine / Λ lock for the honesty strip. */
241
+ async function fetchDoctrine(timeoutMs = 9000) {
242
+ const r = await getJSON(EP.honest, timeoutMs);
243
+ if (!r.ok) return { reachable: false };
244
+ const lk = (r.json && r.json.doctrine_lock) || {};
245
+ return {
246
+ reachable: true,
247
+ lambda: lk.lambda || "Conjecture 1",
248
+ commit: lk.commit || "",
249
+ lockedCount: lk.locked_formula_count ?? 8,
250
+ lockedIds: lk.locked_formula_ids || [],
251
+ declarations: lk.declarations, axioms: lk.axioms, sorries: lk.sorries,
252
+ state: lk.state || "",
253
+ };
254
+ }
255
+
256
+ /* fetch mesh/engine health — the only REAL drift-ish signal available today:
257
+ * engines_total - engines_live antibodies. honest immune intensity in [0,1]. */
258
+ async function fetchImmune(timeoutMs = 9000) {
259
+ const r = await getJSON(EP.govern, timeoutMs);
260
+ if (!r.ok) return { reachable: false, intensity: 0, detail: r.why };
261
+ const j = r.json;
262
+ const total = typeof j.engines_total === "number" ? j.engines_total : 0;
263
+ const live = typeof j.engines_live === "number" ? j.engines_live : total;
264
+ const down = Math.max(0, total - live);
265
+ return {
266
+ reachable: true,
267
+ intensity: total > 0 ? down / total : 0, // real fraction of mesh down
268
+ down, live, total,
269
+ detail: down > 0 ? `${down}/${total} mesh engines down — antibodies active` : `mesh ${live}/${total} healthy`,
270
+ };
271
+ }
272
+
273
+ /* ---- the engine surface --------------------------------------------------- */
274
+ const LiveBody = {
275
+ HOST, EP, KANCHAY, STATUS, ORGANS, VERTICALS,
276
+ organForAction, isDenied,
277
+ probeOrgan, fetchLedger, fetchLambda, fetchMind, fetchDoctrine, fetchImmune,
278
+ };
279
+
280
+ if (typeof window !== "undefined") window.LiveBody = LiveBody;
281
+ export default LiveBody;
282
+ export {
283
+ HOST, EP, KANCHAY, STATUS, ORGANS, VERTICALS,
284
+ organForAction, isDenied,
285
+ probeOrgan, fetchLedger, fetchLambda, fetchMind, fetchDoctrine, fetchImmune,
286
+ };
287
+
288
+
289
+ /* Five-organ fail-closed kernel overlay.
290
+ * Same-origin anatomy kernel first, then a-11-oy.com, then the a11oy Space.
291
+ * Missing API → UNAVAILABLE, never faked LIVE. */
292
+ async function probeOrganIntegrity() {
293
+ const rec = { status: STATUS.PENDING, detail: "not yet polled", blocked: null, organs: [], endpoint: null };
294
+ const urls = [
295
+ "/api/anatomy/v1/organs/integrity",
296
+ "https://a-11-oy.com/api/a11oy/v1/organs/integrity",
297
+ EP.integrity,
298
+ ];
299
+ let last = "unreachable";
300
+ for (const url of urls) {
301
+ try {
302
+ const r = await fetch(url, { cache: "no-store", mode: url.startsWith("/") ? "same-origin" : "cors" });
303
+ if (!r.ok) { last = "HTTP " + r.status; continue; }
304
+ const j = await r.json();
305
+ const ev = j.body || j;
306
+ rec.status = STATUS.LIVE;
307
+ rec.blocked = !!ev.blocked;
308
+ rec.organs = ev.organs || [];
309
+ rec.endpoint = url;
310
+ rec.detail = (ev.live_count || 0) + "/5 LIVE · " + (ev.reason || "ok") +
311
+ " · energy UNAVAILABLE · Conjecture 1 OPEN";
312
+ last = null;
313
+ break;
314
+ } catch (e) {
315
+ last = (e && e.message) ? e.message : String(e);
316
+ }
317
+ }
318
+ if (last) {
319
+ rec.status = STATUS.UNREACHABLE;
320
+ rec.detail = "organ-integrity UNAVAILABLE — " + last;
321
+ }
322
+ if (typeof window !== "undefined") window.__szlOrganIntegrity = rec;
323
+ const el = document.getElementById("integrity-strip");
324
+ if (el) {
325
+ el.dataset.state = rec.status;
326
+ el.textContent = rec.detail;
327
+ }
328
+ return rec;
329
+ }
330
+ if (typeof window !== "undefined") {
331
+ window.probeOrganIntegrity = probeOrganIntegrity;
332
+ if (document.readyState === "loading") {
333
+ document.addEventListener("DOMContentLoaded", () => { probeOrganIntegrity(); });
334
+ } else {
335
+ probeOrganIntegrity();
336
+ }
337
+ }
living_runtime.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Unified Python runtime for SZL Living Anatomy + YACHAY Second Brain.
4
+
5
+ The existing Anatomy server remains the transport, evidence, receipt, and static
6
+ rendering authority. This module extends it in-process with a source-bound,
7
+ handles-only Second Brain organ and makes the combined body the Docker entry
8
+ point. No reverse proxy, second process, model inference, private graph, or
9
+ write authority is introduced.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import functools
14
+ import json
15
+ from http.server import ThreadingHTTPServer
16
+ from typing import Any
17
+ from urllib.parse import parse_qs, urlsplit
18
+
19
+ import server as anatomy_server
20
+ from second_brain_runtime import PublicSecondBrain
21
+
22
+ BRAIN = PublicSecondBrain()
23
+
24
+ # Bind the new runtime and its source snapshot into the existing deterministic
25
+ # Anatomy receipt before the first request can populate any receipt cache.
26
+ _EXTRA_ARTIFACTS = (
27
+ "living_runtime.py",
28
+ "second_brain_runtime.py",
29
+ ".runtime/second-brain/manifest.json",
30
+ ".runtime/second-brain/brain-corpus.public.jsonl",
31
+ ".runtime/second-brain/source.json",
32
+ )
33
+ anatomy_server.ARTIFACT_PATHS = tuple(
34
+ dict.fromkeys((*anatomy_server.ARTIFACT_PATHS, *_EXTRA_ARTIFACTS))
35
+ )
36
+
37
+ _ORIGINAL_MANIFEST = anatomy_server._manifest
38
+ _ORIGINAL_VERSION = anatomy_server._version_contract
39
+ _ORIGINAL_EVIDENCE = anatomy_server._evidence_contract
40
+
41
+
42
+ def _living_manifest() -> dict[str, Any]:
43
+ payload = _ORIGINAL_MANIFEST()
44
+ payload["service"] = "living-anatomy-space"
45
+ payload["purpose"] = (
46
+ "Read-only spatial evidence map with a source-bound YACHAY Second Brain organ."
47
+ )
48
+ payload["contract_version"] = "1.2.0"
49
+ endpoints = payload.setdefault("endpoints", {})
50
+ endpoints.update(
51
+ {
52
+ "living_health": "/api/anatomy/v1/living-health",
53
+ "brain_health": "/api/anatomy/v1/brain/health",
54
+ "brain_manifest": "/api/anatomy/v1/brain/manifest",
55
+ "brain_search": "/api/anatomy/v1/brain/search",
56
+ "brain_context": "/api/anatomy/v1/brain/context",
57
+ }
58
+ )
59
+ payload["organs"] = {
60
+ "brain": {
61
+ "name": "YACHAY",
62
+ "state": BRAIN.health()["state"],
63
+ "ready": BRAIN.ready,
64
+ "source_repository": BRAIN.health()["source_repository"],
65
+ "source_revision": BRAIN.source_revision,
66
+ "authority_state": "READ_ONLY",
67
+ "content_access": "HANDLES_ONLY",
68
+ }
69
+ }
70
+ payload.setdefault("limits", []).extend(
71
+ [
72
+ "Second Brain ranking is lexical relevance, never correctness.",
73
+ "The public projection contains handles only; the private graph is not present.",
74
+ ]
75
+ )
76
+ return payload
77
+
78
+
79
+ def _living_version(force: bool = False) -> dict[str, Any]:
80
+ payload = _ORIGINAL_VERSION(force=force)
81
+ payload["contractVersion"] = "1.2.0"
82
+ payload["runtime"] = "living-anatomy+yachay"
83
+ payload["secondBrainSourceRevision"] = BRAIN.source_revision
84
+ payload["secondBrainEvidenceState"] = "MEASURED" if BRAIN.ready else "UNAVAILABLE"
85
+ return payload
86
+
87
+
88
+ def _living_evidence(force: bool = False) -> dict[str, Any]:
89
+ payload = _ORIGINAL_EVIDENCE(force=force)
90
+ brain = BRAIN.health()
91
+ dependencies = payload.setdefault("dependencies", {})
92
+ dependencies["secondBrain"] = {
93
+ "ready": brain["ready"],
94
+ "state": brain["state"],
95
+ "sourceRepository": brain["source_repository"],
96
+ "sourceRevision": brain["source_revision"],
97
+ "chunkCount": brain["chunk_count"],
98
+ "verificationState": brain["verification_state"],
99
+ "authorityState": brain["authority_state"],
100
+ "details": "/api/anatomy/v1/brain/health",
101
+ }
102
+ runtime = payload.setdefault("runtime", {})
103
+ if not BRAIN.ready:
104
+ runtime["status"] = "DEGRADED"
105
+ runtime["ready"] = False
106
+ payload.setdefault("limitations", []).append(
107
+ "YACHAY Second Brain snapshot is unavailable; Living Anatomy remains transport-reachable but the integrated body is not ready."
108
+ )
109
+ return payload
110
+
111
+
112
+ anatomy_server._manifest = _living_manifest
113
+ anatomy_server._version_contract = _living_version
114
+ anatomy_server._evidence_contract = _living_evidence
115
+
116
+ if not any(
117
+ isinstance(item, dict) and item.get("id") == "anatomy.yachay-second-brain"
118
+ for item in anatomy_server.CAPABILITIES
119
+ ):
120
+ anatomy_server.CAPABILITIES.append(
121
+ {
122
+ "id": "anatomy.yachay-second-brain",
123
+ "name": "YACHAY source-bound Second Brain",
124
+ "purpose": (
125
+ "Ground the Living Anatomy brain organ in the public 575-chunk "
126
+ "Second Brain projection without exposing corpus text or private nodes."
127
+ ),
128
+ "try": {
129
+ "method": "GET",
130
+ "path": "/api/anatomy/v1/brain/search?q=governed%20receipts&k=6",
131
+ "action": "Retrieve source-bound public handles.",
132
+ },
133
+ "evidence": {
134
+ "state": "MEASURED" if BRAIN.ready else "UNAVAILABLE",
135
+ "basis": (
136
+ "Deployment-pinned GitHub revision, manifest digest, corpus digest, "
137
+ "per-row SHA-256 checks, and exact chunk count."
138
+ ),
139
+ "source_revision": BRAIN.source_revision,
140
+ "chunk_count": BRAIN.health()["chunk_count"],
141
+ },
142
+ "limits": [
143
+ "Lexical overlap is not correctness.",
144
+ "No corpus text is returned by the retrieval API.",
145
+ "No private graph node is bundled or queried.",
146
+ "No write or training authority is granted.",
147
+ ],
148
+ "reproduce": {
149
+ "steps": [
150
+ "GET /api/anatomy/v1/brain/health",
151
+ "Compare source_revision with szl-holdings/szl-second-brain.",
152
+ "GET /api/anatomy/v1/brain/manifest and inspect the snapshot receipt.",
153
+ "Run a search and verify every result is a handle with a SHA-256 pointer.",
154
+ ]
155
+ },
156
+ "authority_state": "READ_ONLY",
157
+ "formula_refs": ["F1", "F22"],
158
+ "provenance": [
159
+ "https://github.com/szl-holdings/szl-second-brain",
160
+ "https://huggingface.co/datasets/SZLHOLDINGS/szl-second-brain-inrepo",
161
+ ],
162
+ }
163
+ )
164
+
165
+
166
+ class LivingAnatomyHandler(anatomy_server.HardenedHandler):
167
+ """Add the YACHAY API while preserving every existing Anatomy route."""
168
+
169
+ def _brain_headers(self, evidence_state: str) -> dict[str, str]:
170
+ return {
171
+ "X-SZL-Brain-State": (
172
+ "SOURCE_BOUND_PUBLIC_PROJECTION" if BRAIN.ready else "UNAVAILABLE"
173
+ ),
174
+ "X-SZL-Brain-Authority": "READ_ONLY",
175
+ "X-SZL-Brain-Evidence": evidence_state,
176
+ }
177
+
178
+ @staticmethod
179
+ def _bounded_k(value: Any) -> int:
180
+ try:
181
+ parsed = int(value)
182
+ except (TypeError, ValueError):
183
+ parsed = 6
184
+ return max(1, min(parsed, 12))
185
+
186
+ def _read_json_body(self, maximum: int = 32_768) -> tuple[int, dict[str, Any] | None]:
187
+ try:
188
+ length = int(self.headers.get("Content-Length", "0"))
189
+ except ValueError:
190
+ length = 0
191
+ if length <= 0 or length > maximum:
192
+ return 400, None
193
+ try:
194
+ payload = json.loads(self.rfile.read(length))
195
+ except Exception:
196
+ return 400, None
197
+ if not isinstance(payload, dict):
198
+ return 400, None
199
+ return 200, payload
200
+
201
+ def do_GET(self) -> None: # noqa: N802
202
+ parsed = urlsplit(self.path)
203
+ path = parsed.path
204
+ query = parse_qs(parsed.query)
205
+ if path == "/api/anatomy/v1/living-health":
206
+ if query.get("refresh") == ["1"]:
207
+ BRAIN.reload()
208
+ brain = BRAIN.health()
209
+ payload = {
210
+ "schema": "szl.living-anatomy.health/v1",
211
+ "status": "ok" if brain["ready"] else "degraded",
212
+ "ready": bool(brain["ready"]),
213
+ "service": "living-anatomy-space",
214
+ "transport_state": "REACHABLE",
215
+ "evidence_state": "MEASURED" if brain["ready"] else "UNAVAILABLE",
216
+ "verification_state": "STRUCTURAL_ONLY" if brain["ready"] else "FAILED",
217
+ "authority_state": "READ_ONLY",
218
+ "organs": {
219
+ "anatomy": {
220
+ "ready": True,
221
+ "state": "REACHABLE",
222
+ "contract": "/healthz",
223
+ },
224
+ "brain": {
225
+ "ready": brain["ready"],
226
+ "state": brain["state"],
227
+ "source_revision": brain["source_revision"],
228
+ "chunk_count": brain["chunk_count"],
229
+ "contract": "/api/anatomy/v1/brain/health",
230
+ },
231
+ },
232
+ "note": (
233
+ "Combined readiness requires both the Anatomy transport and the "
234
+ "source-bound public Second Brain projection."
235
+ ),
236
+ }
237
+ evidence = str(payload["evidence_state"])
238
+ self._send_json(
239
+ payload,
240
+ status=200 if brain["ready"] else 503,
241
+ evidence_state=evidence,
242
+ extra_headers=self._brain_headers(evidence),
243
+ )
244
+ return
245
+ if path == "/api/anatomy/v1/brain/health":
246
+ if query.get("refresh") == ["1"]:
247
+ BRAIN.reload()
248
+ payload = BRAIN.health()
249
+ evidence = str(payload["evidence_state"])
250
+ self._send_json(
251
+ payload,
252
+ status=200 if payload["ready"] else 503,
253
+ evidence_state=evidence,
254
+ extra_headers=self._brain_headers(evidence),
255
+ )
256
+ return
257
+ if path == "/api/anatomy/v1/brain/manifest":
258
+ payload = BRAIN.manifest()
259
+ evidence = "MEASURED" if payload["ready"] else "UNAVAILABLE"
260
+ self._send_json(
261
+ payload,
262
+ status=200 if payload["ready"] else 503,
263
+ evidence_state=evidence,
264
+ extra_headers=self._brain_headers(evidence),
265
+ )
266
+ return
267
+ if path in (
268
+ "/api/anatomy/v1/brain/search",
269
+ "/api/anatomy/v1/brain/query",
270
+ ):
271
+ phrase = (query.get("q") or query.get("query") or [""])[0]
272
+ k = self._bounded_k((query.get("k") or [6])[0])
273
+ payload = BRAIN.search(phrase, k=k)
274
+ evidence = "COMPUTED" if payload["ready"] else "UNAVAILABLE"
275
+ self._send_json(
276
+ payload,
277
+ status=200 if payload["ready"] else 503,
278
+ evidence_state=evidence,
279
+ extra_headers=self._brain_headers(evidence),
280
+ )
281
+ return
282
+ if path == "/api/anatomy/v1/brain/context":
283
+ phrase = (query.get("q") or query.get("query") or [""])[0]
284
+ k = self._bounded_k((query.get("k") or [6])[0])
285
+ payload = BRAIN.context(phrase, k=k)
286
+ evidence = "COMPUTED" if payload["ready"] else "UNAVAILABLE"
287
+ self._send_json(
288
+ payload,
289
+ status=200 if payload["ready"] else 503,
290
+ evidence_state=evidence,
291
+ extra_headers=self._brain_headers(evidence),
292
+ )
293
+ return
294
+ super().do_GET()
295
+
296
+ def do_POST(self) -> None: # noqa: N802
297
+ path = urlsplit(self.path).path
298
+ if path not in (
299
+ "/api/anatomy/v1/brain/search",
300
+ "/api/anatomy/v1/brain/query",
301
+ "/api/anatomy/v1/brain/context",
302
+ ):
303
+ super().do_POST()
304
+ return
305
+ status, body = self._read_json_body()
306
+ if body is None:
307
+ self._send_json(
308
+ {
309
+ "error": "invalid_body",
310
+ "detail": "JSON object required; maximum 32,768 bytes.",
311
+ },
312
+ status=status,
313
+ evidence_state="UNAVAILABLE",
314
+ extra_headers=self._brain_headers("UNAVAILABLE"),
315
+ )
316
+ return
317
+ phrase = str(body.get("query") or body.get("q") or "")
318
+ k = self._bounded_k(body.get("k", 6))
319
+ payload = (
320
+ BRAIN.context(phrase, k=k)
321
+ if path.endswith("/context")
322
+ else BRAIN.search(phrase, k=k)
323
+ )
324
+ evidence = "COMPUTED" if payload["ready"] else "UNAVAILABLE"
325
+ self._send_json(
326
+ payload,
327
+ status=200 if payload["ready"] else 503,
328
+ evidence_state=evidence,
329
+ extra_headers=self._brain_headers(evidence),
330
+ )
331
+
332
+
333
+ def make_server(
334
+ host: str = "0.0.0.0",
335
+ port: int = anatomy_server.PORT,
336
+ ) -> ThreadingHTTPServer:
337
+ handler = functools.partial(
338
+ LivingAnatomyHandler,
339
+ directory=str(anatomy_server.DIRECTORY),
340
+ )
341
+ return ThreadingHTTPServer((host, port), handler)
342
+
343
+
344
+ if __name__ == "__main__":
345
+ httpd = make_server()
346
+ print(
347
+ "Serving SZL Living Anatomy + YACHAY Second Brain "
348
+ f"from {anatomy_server.DIRECTORY} on 0.0.0.0:{anatomy_server.PORT}; "
349
+ f"brain_ready={BRAIN.ready} source={BRAIN.source_revision}",
350
+ flush=True,
351
+ )
352
+ try:
353
+ httpd.serve_forever()
354
+ except KeyboardInterrupt:
355
+ httpd.server_close()
og-card.png ADDED
organ_integrity.py ADDED
@@ -0,0 +1,602 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ # Copyright 2026 SZL Holdings
4
+ # Signed-off-by: Lutar, Stephen P. <stephenlutar2@gmail.com>
5
+ """Five-organ fail-closed integrity kernel.
6
+
7
+ Stdlib only. Real SHA-256. Advisory Λ. Energy UNAVAILABLE. Never a fabricated
8
+ joule. Locked-proven stays exactly 8. Λ uniqueness is Conjecture 1 OPEN.
9
+ proven_trust is False.
10
+
11
+ This is the replayable contract the 3D atlas (szl-holdings/anatomy) maps and
12
+ the KHIPU Space (SZLHOLDINGS/szl-khipu) runs in NumPy. This surface is the
13
+ same fail-closed body, hashed with hashlib.sha256 — not a Three.js rehost,
14
+ not a joule, not a theorem.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import hashlib
20
+ import json
21
+ import math
22
+ import sys
23
+ from datetime import datetime, timezone
24
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
25
+ from typing import Any, Iterable, Mapping, Sequence
26
+ from urllib.parse import parse_qs, urlparse
27
+
28
+ DOCTRINE = "v11 LOCKED"
29
+ KERNEL_COMMIT = "c7c0ba17"
30
+ LOCKED_EIGHT = ("F1", "F4", "F7", "F11", "F12", "F18", "F19", "F22")
31
+ YUYAY_AXES = (
32
+ "moralGrounding",
33
+ "measurabilityHonesty",
34
+ "empiricalGrounding",
35
+ "logicalConsistency",
36
+ "sourceTransparency",
37
+ "reproducibility",
38
+ "licenseHygiene",
39
+ "scopeDiscipline",
40
+ "claimCalibration",
41
+ "evalAwareness",
42
+ "deceptionKeywords",
43
+ "conflictingDirectives",
44
+ "reversalDirective",
45
+ )
46
+ YUYAY_FLOORS = (0.95, 0.95) + (0.90,) * 11
47
+ CONJECTURE_1 = (
48
+ "Any two aggregators satisfying A1–A4 agree on every input. OPEN (sorry). "
49
+ "Unconditional uniqueness under kernel A1–A5 is machine-checked FALSE."
50
+ )
51
+ WILLAY_NOTE = (
52
+ "Refusals are tamper-EVIDENT, not tamper-proof. Auditable rules. "
53
+ "Trust ceiling 0.97. WILLAY is conscience, not a sixth proven organ."
54
+ )
55
+ ZERO = "0" * 64
56
+ CHAIN_OPS = ("anatomy.brain", "anatomy.heart", "anatomy.skeleton")
57
+ ORGAN_SPEC = (
58
+ {
59
+ "id": "brain",
60
+ "name": "BRAIN",
61
+ "quechua": "YACHAY",
62
+ "formulas": ("F1",),
63
+ "role": "read-only reasoning cortex — never holds write authority",
64
+ },
65
+ {
66
+ "id": "heart",
67
+ "name": "HEART",
68
+ "quechua": "YUYAY",
69
+ "formulas": ("F4", "F11"),
70
+ "role": "13-axis conjunctive critique gate — advisory Λ",
71
+ },
72
+ {
73
+ "id": "circulatory",
74
+ "name": "CIRCULATORY",
75
+ "quechua": "YAWAR",
76
+ "formulas": ("F7", "F22"),
77
+ "role": "append-only receipt bus — SHA-256",
78
+ },
79
+ {
80
+ "id": "nervous",
81
+ "name": "NERVOUS",
82
+ "quechua": "OTel",
83
+ "formulas": ("F12",),
84
+ "role": "telemetry spine — energy UNAVAILABLE",
85
+ },
86
+ {
87
+ "id": "skeleton",
88
+ "name": "SKELETON",
89
+ "quechua": "Khipu",
90
+ "formulas": ("F18", "F19"),
91
+ "role": "locked-8 formula spine — CHECKED ≠ Lean PROVEN",
92
+ },
93
+ )
94
+
95
+ proven_trust = False
96
+
97
+
98
+ def _sha256_hex(text: str) -> str:
99
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()
100
+
101
+
102
+ def _now() -> str:
103
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
104
+
105
+
106
+ def wgm(xs: Sequence[float], ws: Sequence[float]) -> float:
107
+ if len(xs) != len(ws) or not xs:
108
+ return 0.0
109
+ if any((not math.isfinite(x)) or x <= 0.0 for x in xs):
110
+ return 0.0
111
+ if any((not math.isfinite(w)) or w < 0.0 for w in ws):
112
+ return 0.0
113
+ if abs(sum(ws) - 1.0) >= 1e-9:
114
+ return 0.0
115
+ value = math.exp(sum(w * math.log(x) for x, w in zip(xs, ws)))
116
+ return value if math.isfinite(value) else 0.0
117
+
118
+
119
+ def evaluate_lambda(axes: Sequence[float]) -> dict[str, Any]:
120
+ n = len(axes)
121
+ weights = tuple(1.0 / n for _ in range(n)) if n else ()
122
+ value = wgm(axes, weights)
123
+ xv = list(axes)
124
+ a1 = True
125
+ for i, x in enumerate(xv):
126
+ if x >= 1.0:
127
+ continue
128
+ y = xv[:]
129
+ y[i] = min(1.0, x + 0.05)
130
+ if wgm(y, weights) + 1e-12 < value:
131
+ a1 = False
132
+ break
133
+ c = 0.5
134
+ a2 = abs(wgm([x * c for x in xv], weights) - c * value) <= 1e-9 * max(1.0, abs(c * value))
135
+ a3 = abs(wgm([0.7] * n, weights) - 0.7) <= 1e-9 if n else True
136
+ a4 = (not xv) or value <= max(xv) + 1e-12
137
+ a5 = True
138
+ if n >= 2:
139
+ a5 = abs(wgm(list(reversed(xv)), list(reversed(weights))) - value) <= 1e-9
140
+ axioms = [
141
+ {"id": "A1", "ok": a1, "detail": "monotone"},
142
+ {"id": "A2", "ok": a2, "detail": "homogeneous"},
143
+ {"id": "A3", "ok": a3, "detail": "Egyptian-exact"},
144
+ {"id": "A4", "ok": a4, "detail": "bounded-by-max"},
145
+ {"id": "A5", "ok": a5, "detail": "permutation-invariant"},
146
+ ]
147
+ failed = next((a for a in axioms if not a["ok"]), None)
148
+ blocked = value == 0.0 or failed is not None
149
+ if blocked:
150
+ reason = "zero-routed or non-finite axis" if value == 0.0 else f"axiom {failed['id']} failed"
151
+ else:
152
+ reason = "advisory pass — uniqueness remains Conjecture 1 OPEN"
153
+ return {"value": float(value), "blocked": bool(blocked), "reason": reason, "axioms": axioms}
154
+
155
+
156
+ def yawar_chain(seed: int, tamper: bool) -> dict[str, Any]:
157
+ hops: list[dict[str, Any]] = []
158
+ prev = ZERO
159
+ for seq, op in enumerate(CHAIN_OPS):
160
+ material = f"{seq}|{op}|{prev}|{int(seed)}"
161
+ digest = _sha256_hex(material)
162
+ hops.append({"seq": seq, "op": op, "prev": prev, "digest": digest, "alg": "SHA-256"})
163
+ prev = digest
164
+ if tamper and len(hops) > 1:
165
+ hops[1] = dict(hops[1])
166
+ hops[1]["prev"] = "deadbeef" + hops[1]["prev"][8:]
167
+ walk = ZERO
168
+ ok = True
169
+ brk: int | None = None
170
+ for hop in hops:
171
+ expect = _sha256_hex(f"{hop['seq']}|{hop['op']}|{hop['prev']}|{int(seed)}")
172
+ if hop["prev"] != walk or expect != hop["digest"]:
173
+ ok = False
174
+ brk = int(hop["seq"])
175
+ break
176
+ walk = hop["digest"]
177
+ return {
178
+ "hops": hops,
179
+ "ok": ok,
180
+ "head": hops[-1]["digest"] if hops else ZERO,
181
+ "depth": len(hops),
182
+ "break_at": brk,
183
+ "alg": "SHA-256",
184
+ }
185
+
186
+
187
+ def canal_leak(leak: bool) -> float:
188
+ """Deterministic canal-partition silhouette.
189
+
190
+ Tokens 0..11 assigned to canal i % 3. Cross-canal mass is zero unless a
191
+ leak is requested. This is the fail-closed rule, not NumPy YARQA.
192
+ MEASURED YARQA lives on SZLHOLDINGS/szl-khipu.
193
+ """
194
+ return 1.0 if leak else 0.0
195
+
196
+
197
+ def _organ(
198
+ id_: str,
199
+ name: str,
200
+ quechua: str,
201
+ formulas: tuple[str, ...],
202
+ status: str,
203
+ honesty: str,
204
+ detail: str,
205
+ metric: float,
206
+ ) -> dict[str, Any]:
207
+ return {
208
+ "id": id_,
209
+ "name": name,
210
+ "quechua": quechua,
211
+ "formulas": list(formulas),
212
+ "status": status,
213
+ "honesty": honesty,
214
+ "detail": detail,
215
+ "metric": float(metric),
216
+ }
217
+
218
+
219
+ def evaluate_anatomy(
220
+ *,
221
+ zero_heart: bool = False,
222
+ leak_canal: bool = False,
223
+ tamper_chain: bool = False,
224
+ fabricate_joule: bool = False,
225
+ break_skeleton: bool = False,
226
+ willay_fire: bool = False,
227
+ seed: int = 11,
228
+ ) -> dict[str, Any]:
229
+ if proven_trust is True:
230
+ raise RuntimeError("refusing proven_trust true")
231
+
232
+ axes = list(YUYAY_FLOORS)
233
+ if zero_heart:
234
+ axes[0] = 0.0
235
+ heart = evaluate_lambda(axes)
236
+ heart_down = bool(heart["blocked"])
237
+
238
+ chain = yawar_chain(int(seed), bool(tamper_chain))
239
+ yawar_down = not bool(chain["ok"])
240
+
241
+ leaked = canal_leak(bool(leak_canal))
242
+ brain_down = leaked > 1e-9
243
+
244
+ nervous_down = bool(fabricate_joule)
245
+
246
+ rows = [
247
+ {"id": fid, "ok": not (break_skeleton and fid == "F18")}
248
+ for fid in LOCKED_EIGHT
249
+ ]
250
+ skeleton_pass = sum(1 for r in rows if r["ok"])
251
+ skeleton_down = skeleton_pass < len(rows)
252
+
253
+ organs = [
254
+ _organ(
255
+ "brain",
256
+ "BRAIN",
257
+ "YACHAY",
258
+ ("F1",),
259
+ "DOWN" if brain_down else "LIVE",
260
+ "LIVE",
261
+ (
262
+ f"cross-canal leak {leaked:.3e} — YACHAY cannot reason across a broken partition"
263
+ if brain_down
264
+ else (
265
+ "read-only cortex · canal-partition silhouette leak 0 · "
266
+ "MEASURED YARQA is the KHIPU Space"
267
+ )
268
+ ),
269
+ leaked,
270
+ ),
271
+ _organ(
272
+ "heart",
273
+ "HEART",
274
+ "YUYAY",
275
+ ("F4", "F11"),
276
+ "DOWN" if heart_down else "LIVE",
277
+ "ADVISORY",
278
+ (
279
+ f"Λ {float(heart['value']):.4f} · {heart['reason']}"
280
+ if heart_down
281
+ else f"Λ {float(heart['value']):.4f} · advisory · Conjecture 1 OPEN"
282
+ ),
283
+ float(heart["value"]),
284
+ ),
285
+ _organ(
286
+ "circulatory",
287
+ "CIRCULATORY",
288
+ "YAWAR",
289
+ ("F7", "F22"),
290
+ "DOWN" if yawar_down else "LIVE",
291
+ "LIVE",
292
+ (
293
+ f"chain break at {chain['break_at']} — prev pointer does not walk. Fail closed."
294
+ if yawar_down
295
+ else f"3-hop SHA-256 · depth {chain['depth']} · head {chain['head'][:16]}"
296
+ ),
297
+ 0.0 if chain["ok"] else 1.0,
298
+ ),
299
+ _organ(
300
+ "nervous",
301
+ "NERVOUS",
302
+ "OTel",
303
+ ("F12",),
304
+ "DOWN" if nervous_down else "LIVE",
305
+ "UNAVAILABLE",
306
+ (
307
+ "fabricated joule refused — energy stays UNAVAILABLE"
308
+ if nervous_down
309
+ else "loop-tax silhouette · energy UNAVAILABLE · never a fabricated joule"
310
+ ),
311
+ 1.0 if nervous_down else 0.0,
312
+ ),
313
+ _organ(
314
+ "skeleton",
315
+ "SKELETON",
316
+ "Khipu",
317
+ ("F18", "F19"),
318
+ "DOWN" if skeleton_down else "LIVE",
319
+ "ADVISORY",
320
+ (
321
+ f"locked-8 silhouettes {skeleton_pass}/{len(rows)} — a sorry cannot be painted green"
322
+ if skeleton_down
323
+ else (
324
+ f"locked-8 silhouettes {skeleton_pass}/{len(rows)} · "
325
+ f"CHECKED ≠ Lean PROVEN @ {KERNEL_COMMIT}"
326
+ )
327
+ ),
328
+ float(skeleton_pass),
329
+ ),
330
+ ]
331
+
332
+ live_count = sum(1 for o in organs if o["status"] == "LIVE")
333
+ organ_down = any(o["status"] == "DOWN" for o in organs)
334
+ blocked = organ_down or bool(willay_fire)
335
+ if willay_fire:
336
+ reason = (
337
+ "WILLAY conscience veto — governance bypass refused "
338
+ "(tamper-EVIDENT, not tamper-proof)"
339
+ )
340
+ elif organ_down:
341
+ down = ", ".join(o["name"] for o in organs if o["status"] == "DOWN")
342
+ reason = f"organ integrity FAIL · {down} DOWN · fail closed"
343
+ else:
344
+ reason = (
345
+ f"organ integrity {live_count}/5 LIVE · Λ advisory · "
346
+ "energy UNAVAILABLE · Conjecture 1 OPEN"
347
+ )
348
+
349
+ return {
350
+ "organs": organs,
351
+ "live_count": int(live_count),
352
+ "blocked": bool(blocked),
353
+ "verdict": "BLOCKED" if blocked else "ADVISORY_BODY",
354
+ "willay": {
355
+ "refused": bool(willay_fire),
356
+ "category": "bypass" if willay_fire else "none",
357
+ "note": WILLAY_NOTE,
358
+ },
359
+ "energy": "UNAVAILABLE",
360
+ "energy_j": None,
361
+ "lambda_advisory": True,
362
+ "conjecture_1": "OPEN",
363
+ "conjecture_1_statement": CONJECTURE_1,
364
+ "locked_proven": 8,
365
+ "locked_ids": list(LOCKED_EIGHT),
366
+ "kernel_commit": KERNEL_COMMIT,
367
+ "doctrine": DOCTRINE,
368
+ "chain_head": chain["head"],
369
+ "chain_ok": bool(chain["ok"]),
370
+ "chain_alg": "SHA-256",
371
+ "chain": chain,
372
+ "lambda": heart,
373
+ "proven_trust": False,
374
+ "trust_ceiling": 0.97,
375
+ "reason": reason,
376
+ "seed": int(seed),
377
+ "tamper": {
378
+ "zero_heart": bool(zero_heart),
379
+ "leak_canal": bool(leak_canal),
380
+ "tamper_chain": bool(tamper_chain),
381
+ "fabricate_joule": bool(fabricate_joule),
382
+ "break_skeleton": bool(break_skeleton),
383
+ "willay_fire": bool(willay_fire),
384
+ },
385
+ "not_a_rehost": (
386
+ "szl-holdings/anatomy 3D atlas is SLSA L1 static viz — "
387
+ "this kernel is the integrity check"
388
+ ),
389
+ "checked_at": _now(),
390
+ }
391
+
392
+
393
+ def envelope(ev: Mapping[str, Any]) -> dict[str, Any]:
394
+ payload = json.dumps(ev, sort_keys=True, separators=(",", ":"), default=str)
395
+ return {
396
+ "ok": True,
397
+ "surface": "szl-organ-integrity",
398
+ "receipt_sha256": _sha256_hex(payload),
399
+ "signing": "STRUCTURAL-ONLY — no key on this surface; tamper-EVIDENT hash, not a signature",
400
+ "body": dict(ev),
401
+ }
402
+
403
+
404
+ def parse_flags(src: Mapping[str, Any] | None) -> dict[str, Any]:
405
+ src = src or {}
406
+
407
+ def flag(name: str) -> bool:
408
+ v = src.get(name, False)
409
+ if isinstance(v, bool):
410
+ return v
411
+ if isinstance(v, (int, float)):
412
+ return int(v) == 1
413
+ if isinstance(v, str):
414
+ return v.strip().lower() in {"1", "true", "yes", "on"}
415
+ if isinstance(v, list) and v:
416
+ return flag(v[0])
417
+ return False
418
+
419
+ seed = src.get("seed", 11)
420
+ if isinstance(seed, list) and seed:
421
+ seed = seed[0]
422
+ try:
423
+ seed_i = int(seed)
424
+ except (TypeError, ValueError):
425
+ seed_i = 11
426
+ return {
427
+ "zero_heart": flag("zero_heart"),
428
+ "leak_canal": flag("leak_canal"),
429
+ "tamper_chain": flag("tamper_chain"),
430
+ "fabricate_joule": flag("fabricate_joule"),
431
+ "break_skeleton": flag("break_skeleton"),
432
+ "willay_fire": flag("willay_fire"),
433
+ "seed": seed_i,
434
+ }
435
+
436
+
437
+ def selftest() -> dict[str, Any]:
438
+ healthy = evaluate_anatomy(seed=11)
439
+ assert healthy["live_count"] == 5, healthy["reason"]
440
+ assert healthy["blocked"] is False
441
+ assert healthy["energy"] == "UNAVAILABLE"
442
+ assert healthy["energy_j"] is None
443
+ assert healthy["proven_trust"] is False
444
+ assert healthy["locked_proven"] == 8
445
+ assert healthy["lambda_advisory"] is True
446
+ assert healthy["chain"]["alg"] == "SHA-256"
447
+ assert len(healthy["chain"]["head"]) == 64
448
+
449
+ z = evaluate_anatomy(zero_heart=True, seed=11)
450
+ assert z["blocked"] is True
451
+ assert z["organs"][1]["status"] == "DOWN"
452
+ assert z["organs"][1]["metric"] == 0.0
453
+
454
+ t = evaluate_anatomy(tamper_chain=True, seed=11)
455
+ assert t["blocked"] is True
456
+ assert t["chain_ok"] is False
457
+ assert t["organs"][2]["status"] == "DOWN"
458
+
459
+ j = evaluate_anatomy(fabricate_joule=True, seed=11)
460
+ assert j["blocked"] is True
461
+ assert j["organs"][3]["status"] == "DOWN"
462
+ assert j["energy_j"] is None
463
+
464
+ s = evaluate_anatomy(break_skeleton=True, seed=11)
465
+ assert s["blocked"] is True
466
+ assert s["organs"][4]["metric"] == 7
467
+
468
+ w = evaluate_anatomy(willay_fire=True, seed=11)
469
+ assert w["blocked"] is True
470
+ assert w["willay"]["refused"] is True
471
+ assert w["live_count"] == 5
472
+
473
+ l = evaluate_anatomy(leak_canal=True, seed=11)
474
+ assert l["blocked"] is True
475
+ assert l["organs"][0]["status"] == "DOWN"
476
+
477
+ return {"ok": True, "cases": 7, "healthy_head": healthy["chain_head"]}
478
+
479
+
480
+ def _json_bytes(obj: Any, status: int = 200) -> tuple[int, bytes, str]:
481
+ raw = json.dumps(obj, indent=2, default=str).encode("utf-8")
482
+ return status, raw, "application/json; charset=utf-8"
483
+
484
+
485
+ class Handler(BaseHTTPRequestHandler):
486
+ server_version = "szl-organ-integrity/1.0"
487
+
488
+ def log_message(self, fmt: str, *args: Any) -> None: # noqa: A003
489
+ sys.stderr.write("%s - %s\n" % (self.address_string(), fmt % args))
490
+
491
+ def _cors(self) -> None:
492
+ self.send_header("Access-Control-Allow-Origin", "*")
493
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
494
+ self.send_header("Access-Control-Allow-Headers", "content-type")
495
+ self.send_header("Cache-Control", "no-store")
496
+
497
+ def do_OPTIONS(self) -> None: # noqa: N802
498
+ self.send_response(204)
499
+ self._cors()
500
+ self.end_headers()
501
+
502
+ def do_GET(self) -> None: # noqa: N802
503
+ parsed = urlparse(self.path)
504
+ path = parsed.path.rstrip("/") or "/"
505
+ qs = parse_qs(parsed.query)
506
+ if path in {"/healthz", "/readyz"}:
507
+ self._send(*_json_bytes({"ok": True, "energy": "UNAVAILABLE", "proven_trust": False}))
508
+ return
509
+ if path in {
510
+ "/api/organs/integrity",
511
+ "/api/a11oy/v1/organs/integrity",
512
+ "/v1/organs/integrity",
513
+ }:
514
+ flags = parse_flags(qs)
515
+ body = envelope(evaluate_anatomy(**flags))
516
+ self._send(*_json_bytes(body))
517
+ return
518
+ if path in {"/", "/index.html", "/organs/integrity"}:
519
+ html = _index_html()
520
+ self._send(200, html.encode("utf-8"), "text/html; charset=utf-8")
521
+ return
522
+ self._send(*_json_bytes({"ok": False, "error": "not found", "path": path}, 404))
523
+
524
+ def do_POST(self) -> None: # noqa: N802
525
+ parsed = urlparse(self.path)
526
+ path = parsed.path.rstrip("/") or "/"
527
+ if path not in {
528
+ "/api/organs/integrity",
529
+ "/api/a11oy/v1/organs/integrity",
530
+ "/v1/organs/integrity",
531
+ }:
532
+ self._send(*_json_bytes({"ok": False, "error": "not found"}, 404))
533
+ return
534
+ length = int(self.headers.get("Content-Length") or 0)
535
+ raw = self.rfile.read(max(0, min(length, 1_000_000))) if length else b"{}"
536
+ try:
537
+ data = json.loads(raw.decode("utf-8") or "{}")
538
+ except json.JSONDecodeError:
539
+ data = {}
540
+ if not isinstance(data, dict):
541
+ data = {}
542
+ flags = parse_flags(data)
543
+ body = envelope(evaluate_anatomy(**flags))
544
+ self._send(*_json_bytes(body))
545
+
546
+ def _send(self, status: int, raw: bytes, ctype: str) -> None:
547
+ self.send_response(status)
548
+ self.send_header("Content-Type", ctype)
549
+ self.send_header("Content-Length", str(len(raw)))
550
+ self._cors()
551
+ self.end_headers()
552
+ self.wfile.write(raw)
553
+
554
+
555
+ def _index_html() -> str:
556
+ from pathlib import Path
557
+
558
+ here = Path(__file__).resolve().parent
559
+ for candidate in (here / "index.html", here / "site" / "index.html"):
560
+ if candidate.is_file():
561
+ return candidate.read_text(encoding="utf-8")
562
+ return (
563
+ "<!doctype html><meta charset=utf-8><title>organ integrity</title>"
564
+ "<p>kernel live. POST /api/organs/integrity</p>"
565
+ )
566
+
567
+
568
+ def serve(host: str = "0.0.0.0", port: int = 7860) -> None:
569
+ httpd = ThreadingHTTPServer((host, port), Handler)
570
+ print(f"[szl-organ-integrity] {host}:{port} · SHA-256 · energy UNAVAILABLE", file=sys.stderr)
571
+ httpd.serve_forever()
572
+
573
+
574
+ def main(argv: Iterable[str] | None = None) -> int:
575
+ p = argparse.ArgumentParser(description="Five-organ fail-closed integrity kernel")
576
+ p.add_argument("--serve", action="store_true")
577
+ p.add_argument("--host", default="0.0.0.0")
578
+ p.add_argument("--port", type=int, default=7860)
579
+ p.add_argument("--tamper", nargs="*", default=[], help="zero_heart leak_canal tamper_chain fabricate_joule break_skeleton willay_fire")
580
+ p.add_argument("--seed", type=int, default=11)
581
+ args = p.parse_args(list(argv) if argv is not None else None)
582
+ if args.serve:
583
+ serve(args.host, args.port)
584
+ return 0
585
+ flags = {k: (k in set(args.tamper)) for k in (
586
+ "zero_heart",
587
+ "leak_canal",
588
+ "tamper_chain",
589
+ "fabricate_joule",
590
+ "break_skeleton",
591
+ "willay_fire",
592
+ )}
593
+ if args.tamper:
594
+ print(json.dumps(envelope(evaluate_anatomy(seed=args.seed, **flags)), indent=2))
595
+ return 0
596
+ result = selftest()
597
+ print(json.dumps(result, indent=2))
598
+ return 0 if result.get("ok") else 1
599
+
600
+
601
+ if __name__ == "__main__":
602
+ raise SystemExit(main())
qa_cockpit.mjs ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // QA — Covenant Cockpit v1 (headless, no browser needed).
2
+ // Loads the REAL covenant-cockpit.js pure logic + the bundled receipts.sample.json
3
+ // and asserts the honest invariants that back the cockpit:
4
+ // 1. receipts normalize from the szl-receipt in-toto bundle (no fabricated nodes)
5
+ // 2. the provenance graph binds every decision -> Λ-gate + Lean proof + energy + BFT witnesses
6
+ // 3. the verify badge is GENUINE: signed -> verified, unsigned -> UNAVAILABLE, tamper -> failed
7
+ // 4. energy is measured joules OR honest UNAVAILABLE (never fabricated)
8
+ // 5. empty input -> honest empty graph (zero nodes), never a decorative fallback
9
+ //
10
+ // Run: node qa_cockpit.mjs
11
+ import fs from "node:fs";
12
+ import os from "node:os";
13
+ import path from "node:path";
14
+ import { fileURLToPath, pathToFileURL } from "node:url";
15
+
16
+ const ROOT = path.dirname(fileURLToPath(import.meta.url));
17
+
18
+ // covenant-cockpit.js is a browser ES module (export default). Load its pure
19
+ // logic here by stripping the two `export` lines and evaluating (it has NO
20
+ // top-level `import`, and guards all `window` use), then grabbing the object.
21
+ async function loadModule() {
22
+ // covenant-cockpit.js is a valid browser ES module (export default + guarded
23
+ // `window`). Load it in node by copying to a temp .mjs and importing it — no
24
+ // fragile source-stripping, and the real module code is exercised verbatim.
25
+ const src = fs.readFileSync(path.join(ROOT, "covenant-cockpit.js"), "utf8");
26
+ // Write the temp module into a per-run PRIVATE directory (mkdtemp: random
27
+ // name, mode 0700) instead of a predictable path in the shared temp dir, so it
28
+ // cannot be pre-created, swapped, or read by another local user before we
29
+ // import it (CodeQL js/insecure-temporary-file).
30
+ const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "cc-qa-"));
31
+ const tmp = path.join(tmpDir, "covenant-cockpit.mjs");
32
+ fs.writeFileSync(tmp, src);
33
+ try {
34
+ const mod = await import(pathToFileURL(tmp).href);
35
+ return mod.default;
36
+ } finally {
37
+ try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { /* best-effort cleanup */ }
38
+ }
39
+ }
40
+
41
+ let failures = 0;
42
+ function ok(cond, msg) {
43
+ console.log((cond ? " ✓ " : " ✗ ") + msg);
44
+ if (!cond) failures++;
45
+ }
46
+ function section(t) { console.log("\n== " + t + " =="); }
47
+
48
+ const bundle = JSON.parse(fs.readFileSync(path.join(ROOT, "receipts.sample.json"), "utf8"));
49
+
50
+ (async () => {
51
+ const CC = await loadModule();
52
+ section("normalize the szl-receipt in-toto bundle");
53
+ const { receipts, cosignPub } = CC.normalizeBundle(bundle);
54
+ ok(receipts.length === 4, `normalizes 4 receipts (got ${receipts.length})`);
55
+ ok(!!cosignPub && /BEGIN PUBLIC KEY/.test(cosignPub), "cosign public key present for offline verify");
56
+ ok(receipts.every((r) => r.body && r.body.model_id && r.body.policy_id && r.body.lean_theorem),
57
+ "every receipt decodes model_id + policy_id + lean_theorem");
58
+
59
+ section("build the provenance graph (pure)");
60
+ const g = CC.buildGraph(receipts);
61
+ ok(g.stats.decisions === 4, `4 decision nodes (got ${g.stats.decisions})`);
62
+ ok(g.stats.gates >= 1, `≥1 Λ-gate node (got ${g.stats.gates})`);
63
+ ok(g.stats.proofs >= 1, `≥1 Lean proof node (got ${g.stats.proofs})`);
64
+ ok(g.stats.witnesses >= 1, `≥1 BFT witness node (got ${g.stats.witnesses})`);
65
+ ok(g.edges.length > 0, `edges present (got ${g.edges.length})`);
66
+ // every decision must bind to a gate, a proof, an energy node, and >=1 witness
67
+ const decNodes = g.nodes.filter((n) => n.kind === "decision");
68
+ const edgesFrom = (id, kind) => g.edges.filter((e) => e.from === id && kindOf(g, e.to) === kind);
69
+ const kindOf = (gr, id) => (gr.nodes.find((n) => n.id === id) || {}).kind;
70
+ let bound = true;
71
+ for (const d of decNodes) {
72
+ const hasGate = edgesFrom(d.id, "gate").length >= 1;
73
+ const hasProof = edgesFrom(d.id, "proof").length >= 1;
74
+ const hasEnergy = edgesFrom(d.id, "energy").length >= 1;
75
+ const hasWitness = edgesFrom(d.id, "cosigned" /*ignored*/) ; // recompute below
76
+ const wit = g.edges.filter((e) => e.from === d.id && kindOf(g, e.to) === "witness").length;
77
+ if (!(hasGate && hasProof && hasEnergy && wit >= 1)) bound = false;
78
+ }
79
+ ok(bound, "every decision binds → Λ-gate + Lean proof + energy + ≥1 BFT witness");
80
+ ok(g.nodes.every((n) => Array.isArray(n.pos) && n.pos.length === 3 && n.pos.every(Number.isFinite)),
81
+ "every node has a finite 3D position (renderable)");
82
+
83
+ section("energy is measured joules OR honest UNAVAILABLE");
84
+ ok(g.stats.energyMeasured === 2 && g.stats.energyUnavailable === 2,
85
+ `2 measured / 2 UNAVAILABLE energy nodes (got ${g.stats.energyMeasured}/${g.stats.energyUnavailable})`);
86
+ const eNodes = g.nodes.filter((n) => n.kind === "energy");
87
+ ok(eNodes.every((n) => n.meta.measured ? typeof n.meta.joules === "number" : n.meta.joules === null),
88
+ "measured energy carries a real joule value; unavailable carries null (never fabricated)");
89
+
90
+ section("verify badge is GENUINE (WebCrypto ECDSA-P256 over DSSE PAE)");
91
+ const key = await CC.importCosign(cosignPub);
92
+ const results = [];
93
+ for (const r of receipts) results.push(await CC.verifyEnvelope(r.envelope, key));
94
+ const verified = results.filter((v) => v.status === CC.VERIFY.VERIFIED).length;
95
+ const unavail = results.filter((v) => v.status === CC.VERIFY.UNAVAILABLE).length;
96
+ ok(verified === 3, `3 signed receipts VERIFY (got ${verified})`);
97
+ ok(unavail === 1, `1 unsigned receipt is honest UNAVAILABLE (got ${unavail})`);
98
+
99
+ // tamper: flip the verdict on a signed receipt -> must FAIL (never a fake pass)
100
+ const signedIdx = receipts.findIndex((r) => r.envelope.signed === true);
101
+ const t = JSON.parse(JSON.stringify(receipts[signedIdx].envelope));
102
+ const body = JSON.parse(Buffer.from(t.payload, "base64").toString("utf8"));
103
+ body.verdict = body.verdict === "allow" ? "block" : "allow";
104
+ const keys = Object.keys(body).sort();
105
+ const canon = JSON.stringify(body, keys);
106
+ t.payload = Buffer.from(canon, "utf8").toString("base64");
107
+ const vt = await CC.verifyEnvelope(t, key);
108
+ ok(vt.status === CC.VERIFY.FAILED, `tampered receipt FAILS verify (got ${vt.status})`);
109
+
110
+ section("honest empty state — never fabricate nodes");
111
+ const empty = CC.buildGraph([]);
112
+ ok(empty.nodes.length === 0 && empty.edges.length === 0, "empty input → zero nodes, zero edges");
113
+ const bad = CC.normalizeBundle({ receipts: [{ id: "x" }, { junk: true }] });
114
+ ok(bad.receipts.length === 0, "entries without a payload are skipped, not turned into fake nodes");
115
+
116
+ console.log("\n=== TOTAL FAILURES:", failures, "===");
117
+ process.exit(failures === 0 ? 0 : 1);
118
+ })().catch((e) => { console.error("QA FAIL", e); process.exit(1); });
qa_yarqa.js ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // QA — yarqa flow-compartments layer (v6) + full regression.
2
+ // Headless Chromium, THREE r160 swiftshader. Runs desktop / 390 / 820.
3
+ // Asserts: 0 console errors; v6 layer toggles + computes a reproducible receipt;
4
+ // yarqa NEVER in the locked count; no regression to organ pick / camera / GPD /
5
+ // dissection dock / mobile FAB.
6
+ const http = require('http');
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const { chromium } = require('playwright');
10
+
11
+ const ROOT = __dirname;
12
+ const MIME = { '.html':'text/html', '.js':'application/javascript', '.css':'text/css' };
13
+
14
+ const server = http.createServer((req,res)=>{
15
+ let p = req.url.split('?')[0]; if(p==='/') p='/index.html';
16
+ const fp = path.join(ROOT, p);
17
+ if(!fp.startsWith(ROOT) || !fs.existsSync(fp)){ res.writeHead(404); return res.end('nf'); }
18
+ res.writeHead(200,{'Content-Type':MIME[path.extname(fp)]||'application/octet-stream'});
19
+ fs.createReadStream(fp).pipe(res);
20
+ });
21
+
22
+ const VIEWPORTS = [
23
+ { name:'desktop', width:1280, height:800 },
24
+ { name:'phone-390', width:390, height:844 },
25
+ { name:'tablet-820', width:820, height:1180 },
26
+ ];
27
+
28
+ async function runViewport(browser, url, vp){
29
+ const page = await browser.newPage({ viewport:{ width:vp.width, height:vp.height } });
30
+ const errors=[];
31
+ page.on('console', m=>{ if(m.type()==='error') errors.push(m.text()); });
32
+ page.on('pageerror', e=>errors.push('PAGEERROR: '+e.message));
33
+ await page.goto(url, { waitUntil:'networkidle' });
34
+ await page.waitForTimeout(2200);
35
+
36
+ const r = await page.evaluate(async ()=>{
37
+ const A = window.__anatomy; const out = { hasA: !!A };
38
+ if(!A) return out;
39
+ out.rev=A.rev; out.organs=A.organs; out.vessels=A.vessels; out.pulses=A.pulses;
40
+ out.hasV4=!!A.v4; out.hasV5=!!A.v5; out.hasV6=!!A.v6;
41
+
42
+ // ---- v6 yarqa layer ----
43
+ if(A.v6){
44
+ out.v6label = A.v6.label;
45
+ out.v6OffInitially = (A.v6.isOn()===false);
46
+ A.v6.setLayer(true,null);
47
+ const rec1 = await A.v6.recompute(0.2);
48
+ out.v6comp1 = rec1.n_compartments;
49
+ out.v6cells = rec1.n_cells;
50
+ out.v6digest1 = rec1.receipt_digest;
51
+ out.v6yarqaInLocked = A.v6.yarqaInLockedCount();
52
+ out.v6routes8 = A.v6.routesLocked8ThroughYarqa();
53
+ out.v6receiptTier = rec1.method_tier;
54
+ // reproducibility: same inputs+params => same digest
55
+ const rec2 = await A.v6.recompute(0.2);
56
+ out.v6reproduces = (rec2.receipt_digest === rec1.receipt_digest);
57
+ // different align => (possibly) different partition, still valid
58
+ const rec3 = await A.v6.recompute(0.6);
59
+ out.v6comp3 = rec3.n_compartments;
60
+ // opacity + toggle off
61
+ A.v6.setLayer(null,0.4);
62
+ A.v6.setLayer(false,null);
63
+ out.v6OffAfter = (A.v6.isOn()===false);
64
+ A.v6.setLayer(true,1);
65
+ }
66
+
67
+ // dock row present + honest label in DOM
68
+ out.dockRow = !!document.getElementById('yq-layer-row');
69
+ out.dockNote = (document.getElementById('yq-sec')||{}).textContent||'';
70
+
71
+ // ---- regression: v4 dock, organ pick, GPD, hud ----
72
+ if(A.v4){
73
+ out.layers = A.v4.LAYERS.map(l=>l.key);
74
+ out.searchYawar = A.v4.search('yawar');
75
+ out.jumpOpened = A.v4.jumpFirst();
76
+ A.v4.setLayer('circulatory', false, null);
77
+ out.circOff = A.v4._state.layers.circulatory.on;
78
+ A.v4.setLayer('circulatory', true, 1);
79
+ A.v4.setExplode(1); A.v4.setExplode(0);
80
+ A.v4.setClip(true,'y',1.2); A.v4.setClip(false,'x',0);
81
+ A.v4.setFocus(true); out.focus=A.v4._state.focus; A.v4.setFocus(false);
82
+ out.hud = A.v4.hud();
83
+ }
84
+ out.openOrgan = A.openOrgan('yawar');
85
+ out.panelOpen = A.panelOpen();
86
+ out.gpd = A.openGPD();
87
+ out.visHudFoot = (document.getElementById('vh-foot')||{}).textContent||'';
88
+ return out;
89
+ });
90
+
91
+ // mobile FAB presence (only visible <=680px, but element exists in DOM)
92
+ const fab = await page.evaluate(()=>{ const f=document.getElementById('dissect-fab'); if(!f) return null; const cs=getComputedStyle(f); return { display:cs.display }; });
93
+
94
+ // overflow check: no horizontal scroll
95
+ const overflow = await page.evaluate(()=>({ sw:document.documentElement.scrollWidth, iw:window.innerWidth }));
96
+
97
+ await page.close();
98
+ return { vp:vp.name, errors, r, fab, overflow };
99
+ }
100
+
101
+ (async()=>{
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){
112
+ const res = await runViewport(browser, url, vp);
113
+ console.log('\n===================== '+res.vp+' =====================');
114
+ console.log(JSON.stringify(res.r, null, 2));
115
+ console.log('FAB:', JSON.stringify(res.fab), 'overflow:', JSON.stringify(res.overflow),
116
+ 'overflow_ok:', res.overflow.sw <= res.overflow.iw+1);
117
+ console.log('CONSOLE ERRORS ('+res.errors.length+'):', res.errors.length?res.errors.join('\n'):'(none)');
118
+ totalErrors += res.errors.length;
119
+ }
120
+ await browser.close();
121
+ server.close();
122
+ console.log('\n=== TOTAL CONSOLE ERRORS ACROSS VIEWPORTS:', totalErrors, '===');
123
+ process.exit(0);
124
+ })().catch(e=>{ console.error('QA FAIL', e); process.exit(1); });
receipts.sample.json ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "szl.anatomy.covenant-cockpit/receipts/v1",
3
+ "note": "REAL szl-receipt in-toto sample set (DSSE ECDSA-P256-SHA256). Signatures are genuine and verify offline against cosign_pub. One receipt is UNSIGNED-honest so the cockpit shows an honest UNAVAILABLE badge \u2014 never a fabricated pass. \u039b = Conjecture 1 (advisory).",
4
+ "payload_type": "application/vnd.szl.receipt+json",
5
+ "cosign_pub": "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEQW3976C9sGw2XOnLWhAaCIyLa6g9\nC/jtv7P3nQfDaQlqvtxNPx+zv+NS1JXo5zu7D62ZHFFqFNGLn8TmDKHjLQ==\n-----END PUBLIC KEY-----\n",
6
+ "receipts": [
7
+ {
8
+ "id": "a11oy-lead#10023-NY",
9
+ "envelope": {
10
+ "payloadType": "application/vnd.szl.receipt+json",
11
+ "payload": "eyJhY3Rpb24iOiJjb250YWN0X3Byb3NwZWN0IiwiYmZ0X3dpdG5lc3NlcyI6WyJhbWFydSIsInNlbnRyYSIsImtpbGxpbmNodSJdLCJlbmVyZ3kiOnsiam91bGVzIjo0MS44LCJtZWFzdXJlZCI6dHJ1ZX0sImlucHV0X2RpZ2VzdCI6InNoYTI1Njo0N2ZhNGIzNWM1YmZjNTE5NWY1OTFhZGVjZmEyMjU3YWU1YTNkYTAzZTk0NjhkODM4ZTg1M2MyZDRiYWJlMWRkIiwia2VybmVsX2NvbW1pdCI6ImM3YzBiYTE3Iiwia2luZCI6ImdvdmVybmFuY2UuZGVjaXNpb24iLCJsYW1iZGEiOnsiYXhlcyI6MTMsImZsb29yIjowLjksInBhc3MiOnRydWUsInVuaXF1ZW5lc3MiOiJDb25qZWN0dXJlIDEiLCJ2YWx1ZSI6MC45NzJ9LCJsZWFuX3RoZW9yZW0iOiJsb2NrZWRfY291bnRfZWlnaHQiLCJtb2RlbF9pZCI6InN6bC1yb3V0ZXIvbGxhbWEtMy4xLThiIiwib3V0cHV0X2RpZ2VzdCI6InNoYTI1Njo5NDIyNTM0MGFiN2E5M2M3MTQxYjM5ZGQ0ODZmNDVhMjlmZGExYWY1MDA4YTkwZGY1Nzg5NTA2M2NhMjkxMTAwIiwicG9saWN5X2lkIjoidGNwYS1jb21wbGlhbmNlLnYxMSIsInByb2R1Y2VyIjoiYTExb3kiLCJyZWFzb24iOiJPbiB0aGUgRG8tTm90LUNhbGwgcmVnaXN0cnkg4oCUIG91dHJlYWNoIGJsb2NrZWQgKFRDUEEpLiIsInNjaGVtYSI6InN6bC5wY2dpLnJlY2VpcHQvdjEiLCJzZXEiOjAsInN1YmplY3QiOiJsZWFkIzEwMDIzLU5ZIiwidmVyZGljdCI6ImJsb2NrIn0=",
12
+ "signature": "MEYCIQC07daoxODDMpg61Sa9FhQfBlSAjbXYTCnzpu+sIpA7igIhAP0AtdrtjkCMxh5E3XjsAhaH1/l5pr9dfgtOOG0WWyqo",
13
+ "signed": true,
14
+ "organ": "a11oy",
15
+ "keyid": "szl-org-key-01",
16
+ "digest": "0d400441089b2b09ca6291cfcb1e68662e82f51d8b43653c581ab33f572103a3",
17
+ "algo": "ECDSA-P256-SHA256"
18
+ },
19
+ "statement": {
20
+ "_type": "https://in-toto.io/Statement/v1",
21
+ "subject": [
22
+ {
23
+ "name": "a11oy:lead#10023-NY",
24
+ "digest": {
25
+ "sha256": "0d400441089b2b09ca6291cfcb1e68662e82f51d8b43653c581ab33f572103a3"
26
+ }
27
+ }
28
+ ],
29
+ "predicateType": "https://a-11-oy.com/attest/szl-receipt/v0.1",
30
+ "predicate": {
31
+ "buildDefinition": {
32
+ "buildType": "https://a-11-oy.com/pcgi/governed-decision/v1",
33
+ "externalParameters": {
34
+ "model_id": "szl-router/llama-3.1-8b",
35
+ "policy_id": "tcpa-compliance.v11",
36
+ "input_digest": "sha256:47fa4b35c5bfc5195f591adecfa2257ae5a3da03e9468d838e853c2d4babe1dd"
37
+ },
38
+ "internalParameters": {
39
+ "kernel_commit": "c7c0ba17"
40
+ }
41
+ },
42
+ "runDetails": {
43
+ "builder": {
44
+ "id": "szl://a11oy"
45
+ },
46
+ "metadata": {
47
+ "verdict": "block",
48
+ "output_digest": "sha256:94225340ab7a93c7141b39dd486f45a29fda1af5008a90df57895063ca291100",
49
+ "energy": {
50
+ "joules": 41.8,
51
+ "measured": true
52
+ },
53
+ "bft_witnesses": [
54
+ "amaru",
55
+ "sentra",
56
+ "killinchu"
57
+ ]
58
+ }
59
+ },
60
+ "doctrine": "receipt = evidence, not conformance; \u039b = Conjecture 1"
61
+ }
62
+ }
63
+ },
64
+ {
65
+ "id": "killinchu-track#K-7741",
66
+ "envelope": {
67
+ "payloadType": "application/vnd.szl.receipt+json",
68
+ "payload": "eyJhY3Rpb24iOiJ0cmFja19jbGFzc2lmeSIsImJmdF93aXRuZXNzZXMiOlsiYW1hcnUiLCJzZW50cmEiXSwiZW5lcmd5IjoiVU5BVkFJTEFCTEUiLCJpbnB1dF9kaWdlc3QiOiJzaGEyNTY6MDA5MjdmODMwMTNmNmU4OGVmOGU3ZWI2ZTMzOTYzMjI3YmVlZDIxZTU4MTRlMzRjMjYxODMxMzUyNTY0MTljZSIsImtlcm5lbF9jb21taXQiOiJjN2MwYmExNyIsImtpbmQiOiJlbmdhZ2VtZW50LmNsYXNzaWZpY2F0aW9uIiwibGFtYmRhIjp7ImF4ZXMiOjEzLCJmbG9vciI6MC45LCJwYXNzIjp0cnVlLCJ1bmlxdWVuZXNzIjoiQ29uamVjdHVyZSAxIiwidmFsdWUiOjAuOTU4fSwibGVhbl90aGVvcmVtIjoia2hpcHVfcXVvcnVtX3NhZmV0eV9jb25kaXRpb25hbCIsIm1vZGVsX2lkIjoia2lsbGluY2h1L2VkZ2UtZm9ybXVsYXMucm91bmQ5Iiwib3V0cHV0X2RpZ2VzdCI6InNoYTI1NjphNTQ3ZWI3NDg4YzE5NWIzNWE1ZTY2MThlNTJjZDA4ZjQ4MzBhODMyMjBkYjRmODlhZmZjOWJkYjhkNDQ0NTliIiwicG9saWN5X2lkIjoicm9lLWh1bWFuLWF1dGhvcml0eS52MyIsInByb2R1Y2VyIjoia2lsbGluY2h1IiwicmVhc29uIjoiQ2xhc3NpZmllZCBOT04tSE9TVElMRSB1bmRlciBST0UgZ2F0ZTsgaHVtYW4gYXV0aG9yaXR5IHJldGFpbmVkLiIsInNjaGVtYSI6InN6bC5wY2dpLnJlY2VpcHQvdjEiLCJzZXEiOjEsInN1YmplY3QiOiJ0cmFjayNLLTc3NDEiLCJ2ZXJkaWN0IjoiYWxsb3ctb2JzZXJ2ZSJ9",
69
+ "signature": "MEQCIB/Bn4eRv/QRVhmQQQwYLyJh1InUwKPrgvvKrxg+DtsWAiAwuAzxKvESYM/0SORx+CE0yFzpa+Os7SJ6SWfmDb7xpQ==",
70
+ "signed": true,
71
+ "organ": "killinchu",
72
+ "keyid": "szl-org-key-01",
73
+ "digest": "291e7ecece7d88445ce4b5abf3c9fea0596567a8f2f6c05e3b4a0a8ee4e705db",
74
+ "algo": "ECDSA-P256-SHA256"
75
+ },
76
+ "statement": {
77
+ "_type": "https://in-toto.io/Statement/v1",
78
+ "subject": [
79
+ {
80
+ "name": "killinchu:track#K-7741",
81
+ "digest": {
82
+ "sha256": "291e7ecece7d88445ce4b5abf3c9fea0596567a8f2f6c05e3b4a0a8ee4e705db"
83
+ }
84
+ }
85
+ ],
86
+ "predicateType": "https://a-11-oy.com/attest/szl-receipt/v0.1",
87
+ "predicate": {
88
+ "buildDefinition": {
89
+ "buildType": "https://a-11-oy.com/pcgi/governed-decision/v1",
90
+ "externalParameters": {
91
+ "model_id": "killinchu/edge-formulas.round9",
92
+ "policy_id": "roe-human-authority.v3",
93
+ "input_digest": "sha256:00927f83013f6e88ef8e7eb6e33963227beed21e5814e34c26183135256419ce"
94
+ },
95
+ "internalParameters": {
96
+ "kernel_commit": "c7c0ba17"
97
+ }
98
+ },
99
+ "runDetails": {
100
+ "builder": {
101
+ "id": "szl://killinchu"
102
+ },
103
+ "metadata": {
104
+ "verdict": "allow-observe",
105
+ "output_digest": "sha256:a547eb7488c195b35a5e6618e52cd08f4830a83220db4f89affc9bdb8d44459b",
106
+ "energy": "UNAVAILABLE",
107
+ "bft_witnesses": [
108
+ "amaru",
109
+ "sentra"
110
+ ]
111
+ }
112
+ },
113
+ "doctrine": "receipt = evidence, not conformance; \u039b = Conjecture 1"
114
+ }
115
+ }
116
+ },
117
+ {
118
+ "id": "a11oy-req#88f120",
119
+ "envelope": {
120
+ "payloadType": "application/vnd.szl.receipt+json",
121
+ "payload": "eyJhY3Rpb24iOiJhbnN3ZXJfcXVlcnkiLCJiZnRfd2l0bmVzc2VzIjpbImFtYXJ1Iiwic2VudHJhIiwia2lsbGluY2h1Il0sImVuZXJneSI6eyJqb3VsZXMiOjExOC4zLCJtZWFzdXJlZCI6dHJ1ZX0sImlucHV0X2RpZ2VzdCI6InNoYTI1NjowNWMxOTE2MmQ2YzU0YmQyYjk3NjVkN2JiNDIzMGRhMDgyNmE2MDk2NWZhZjg1MWE3MzgxNzA3NzQ5NzM5ZWVkIiwia2VybmVsX2NvbW1pdCI6ImM3YzBiYTE3Iiwia2luZCI6ImluZmVyZW5jZS5kZWNpc2lvbiIsImxhbWJkYSI6eyJheGVzIjoxMywiZmxvb3IiOjAuOSwicGFzcyI6dHJ1ZSwidW5pcXVlbmVzcyI6IkNvbmplY3R1cmUgMSIsInZhbHVlIjowLjk5MX0sImxlYW5fdGhlb3JlbSI6ImxvY2tlZF9jb3VudF9laWdodCIsIm1vZGVsX2lkIjoic3psLXJvdXRlci9sbGFtYS0zLjEtOGIiLCJvdXRwdXRfZGlnZXN0Ijoic2hhMjU2OjQyNmQ5YWY2MjVhNDAxMzQ0YjFlNjQ5MjFhMWUxMWQ0YWVjNjM0MDRjMmIxMzc4NWVkZTdhM2Q3ZTY3MDI5ZDkiLCJwb2xpY3lfaWQiOiJkZW55LWJ5LWRlZmF1bHQuRjEyLnYxMSIsInByb2R1Y2VyIjoiYTExb3kiLCJyZWFzb24iOiJEZW55LWJ5LWRlZmF1bHQgZ2F0ZSBwYXNzZWQgMTMvMTMgY29uanVuY3RpdmUgYXhlcy4iLCJzY2hlbWEiOiJzemwucGNnaS5yZWNlaXB0L3YxIiwic2VxIjoyLCJzdWJqZWN0IjoicmVxIzg4ZjEyMCIsInZlcmRpY3QiOiJhbGxvdyJ9",
122
+ "signature": "MEYCIQCYhSRuaVXES0Gri9RM+6kL0sx6NKca2TTEMYy48ewehQIhAKwz3FqRrkmQ52DknWtyaM4MT4XtF+hsp1M4ZdMb7BMq",
123
+ "signed": true,
124
+ "organ": "a11oy",
125
+ "keyid": "szl-org-key-01",
126
+ "digest": "19c7e9e5632e925e8f1241da6933fe8d6cc657d284f1afe5f34f9c592be69d9a",
127
+ "algo": "ECDSA-P256-SHA256"
128
+ },
129
+ "statement": {
130
+ "_type": "https://in-toto.io/Statement/v1",
131
+ "subject": [
132
+ {
133
+ "name": "a11oy:req#88f120",
134
+ "digest": {
135
+ "sha256": "19c7e9e5632e925e8f1241da6933fe8d6cc657d284f1afe5f34f9c592be69d9a"
136
+ }
137
+ }
138
+ ],
139
+ "predicateType": "https://a-11-oy.com/attest/szl-receipt/v0.1",
140
+ "predicate": {
141
+ "buildDefinition": {
142
+ "buildType": "https://a-11-oy.com/pcgi/governed-decision/v1",
143
+ "externalParameters": {
144
+ "model_id": "szl-router/llama-3.1-8b",
145
+ "policy_id": "deny-by-default.F12.v11",
146
+ "input_digest": "sha256:05c19162d6c54bd2b9765d7bb4230da0826a60965faf851a7381707749739eed"
147
+ },
148
+ "internalParameters": {
149
+ "kernel_commit": "c7c0ba17"
150
+ }
151
+ },
152
+ "runDetails": {
153
+ "builder": {
154
+ "id": "szl://a11oy"
155
+ },
156
+ "metadata": {
157
+ "verdict": "allow",
158
+ "output_digest": "sha256:426d9af625a401344b1e64921a1e11d4aec63404c2b13785ede7a3d7e67029d9",
159
+ "energy": {
160
+ "joules": 118.3,
161
+ "measured": true
162
+ },
163
+ "bft_witnesses": [
164
+ "amaru",
165
+ "sentra",
166
+ "killinchu"
167
+ ]
168
+ }
169
+ },
170
+ "doctrine": "receipt = evidence, not conformance; \u039b = Conjecture 1"
171
+ }
172
+ }
173
+ },
174
+ {
175
+ "id": "a11oy-req#88f201",
176
+ "envelope": {
177
+ "payloadType": "application/vnd.szl.receipt+json",
178
+ "payload": "eyJhY3Rpb24iOiJoaWRkZW5fcmVhc29uaW5nX2V4dHJhY3Rpb24iLCJiZnRfd2l0bmVzc2VzIjpbImFtYXJ1Il0sImVuZXJneSI6IlVOQVZBSUxBQkxFIiwiaW5wdXRfZGlnZXN0Ijoic2hhMjU2OmM3ZDBlZWJkMzUwNWJmZjBjNTYwNjU3ZWFiMWZlNTRmNWQ5NjRmMTNkYTI4OWM1ZjYzY2FiNmMxZTE2ZGVmMzgiLCJrZXJuZWxfY29tbWl0IjoiYzdjMGJhMTciLCJraW5kIjoiZ292ZXJuYW5jZS5kZWNpc2lvbiIsImxhbWJkYSI6eyJheGVzIjoxMywiZmxvb3IiOjAuOSwicGFzcyI6dHJ1ZSwidW5pcXVlbmVzcyI6IkNvbmplY3R1cmUgMSIsInZhbHVlIjowLjk2NX0sImxlYW5fdGhlb3JlbSI6ImxvY2tlZF9jb3VudF9laWdodCIsIm1vZGVsX2lkIjoic3psLXJvdXRlci9sbGFtYS0zLjEtOGIiLCJvdXRwdXRfZGlnZXN0Ijoic2hhMjU2OmY4MzU4YzExNjM2YzllMGZhNWQ1MzIxN2VmZjE0ZDAwMGEyZjNiNzQyMjE1YjVhZDI1OGZjMjhhZGE5YjA1M2QiLCJwb2xpY3lfaWQiOiJ3aWxsYXktY29uc2NpZW5jZS52NSIsInByb2R1Y2VyIjoiYTExb3kiLCJyZWFzb24iOiJXSUxMQVkgY29uc2NpZW5jZSBnYXRlOiBoaWRkZW4tcmVhc29uaW5nIGV4dHJhY3Rpb24gYXR0ZW1wdCByZWZ1c2VkLiIsInNjaGVtYSI6InN6bC5wY2dpLnJlY2VpcHQvdjEiLCJzZXEiOjMsInN1YmplY3QiOiJyZXEjODhmMjAxIiwidmVyZGljdCI6ImJsb2NrIn0=",
179
+ "signature": "",
180
+ "signed": false,
181
+ "organ": "a11oy",
182
+ "keyid": "",
183
+ "digest": "aa048ce1d842952dd77b5e599658d1d2d670eaa7412d6a9de89e5895a6fb1992",
184
+ "algo": "UNSIGNED",
185
+ "note": "UNSIGNED-honest: no cosign key present"
186
+ },
187
+ "statement": {
188
+ "_type": "https://in-toto.io/Statement/v1",
189
+ "subject": [
190
+ {
191
+ "name": "a11oy:req#88f201",
192
+ "digest": {
193
+ "sha256": "aa048ce1d842952dd77b5e599658d1d2d670eaa7412d6a9de89e5895a6fb1992"
194
+ }
195
+ }
196
+ ],
197
+ "predicateType": "https://a-11-oy.com/attest/szl-receipt/v0.1",
198
+ "predicate": {
199
+ "buildDefinition": {
200
+ "buildType": "https://a-11-oy.com/pcgi/governed-decision/v1",
201
+ "externalParameters": {
202
+ "model_id": "szl-router/llama-3.1-8b",
203
+ "policy_id": "willay-conscience.v5",
204
+ "input_digest": "sha256:c7d0eebd3505bff0c560657eab1fe54f5d964f13da289c5f63cab6c1e16def38"
205
+ },
206
+ "internalParameters": {
207
+ "kernel_commit": "c7c0ba17"
208
+ }
209
+ },
210
+ "runDetails": {
211
+ "builder": {
212
+ "id": "szl://a11oy"
213
+ },
214
+ "metadata": {
215
+ "verdict": "block",
216
+ "output_digest": "sha256:f8358c11636c9e0fa5d53217eff14d000a2f3b742215b5ad258fc28ada9b053d",
217
+ "energy": "UNAVAILABLE",
218
+ "bft_witnesses": [
219
+ "amaru"
220
+ ]
221
+ }
222
+ },
223
+ "doctrine": "receipt = evidence, not conformance; \u039b = Conjecture 1"
224
+ }
225
+ }
226
+ }
227
+ ]
228
+ }
scripts/materialize_second_brain.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Materialize the public Second Brain projection for Living Anatomy.
4
+
5
+ The source repository remains authoritative. This operator resolves an exact
6
+ Git commit, downloads the public manifest and JSONL corpus from that immutable
7
+ revision, validates every row digest and the declared chunk count, then writes a
8
+ source receipt beside the snapshot. It never reads or exports the private
9
+ Second Brain graph.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import hashlib
15
+ import json
16
+ import os
17
+ import re
18
+ import tempfile
19
+ import urllib.error
20
+ import urllib.parse
21
+ import urllib.request
22
+ from datetime import datetime, timezone
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ DEFAULT_REPOSITORY = "szl-holdings/szl-second-brain"
27
+ DEFAULT_REF = "main"
28
+ EXPECTED_PUBLIC_CHUNKS = 575
29
+ MAX_MANIFEST_BYTES = 256 * 1024
30
+ MAX_CORPUS_BYTES = 4 * 1024 * 1024
31
+ USER_AGENT = "szl-living-anatomy-second-brain-materializer/1.0"
32
+
33
+
34
+ def utc_now() -> str:
35
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
36
+
37
+
38
+ def sha256_bytes(value: bytes) -> str:
39
+ return hashlib.sha256(value).hexdigest()
40
+
41
+
42
+ def request_bytes(url: str, *, token: str | None = None, limit: int) -> bytes:
43
+ headers = {
44
+ "Accept": "application/vnd.github+json, application/json, text/plain;q=0.9, */*;q=0.8",
45
+ "User-Agent": USER_AGENT,
46
+ "X-GitHub-Api-Version": "2022-11-28",
47
+ }
48
+ if token:
49
+ headers["Authorization"] = f"Bearer {token}"
50
+ request = urllib.request.Request(url, headers=headers)
51
+ try:
52
+ with urllib.request.urlopen(request, timeout=45) as response:
53
+ body = response.read(limit + 1)
54
+ except (urllib.error.URLError, TimeoutError, ConnectionError) as exc:
55
+ raise RuntimeError(f"fetch failed for {url}: {type(exc).__name__}: {exc}") from exc
56
+ if len(body) > limit:
57
+ raise RuntimeError(f"response exceeded {limit} bytes: {url}")
58
+ return body
59
+
60
+
61
+ def resolve_revision(
62
+ repository: str,
63
+ ref: str,
64
+ *,
65
+ token: str | None = None,
66
+ api_url: str = "https://api.github.com",
67
+ ) -> str:
68
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository):
69
+ raise ValueError(f"invalid GitHub repository: {repository!r}")
70
+ encoded_ref = urllib.parse.quote(ref, safe="")
71
+ url = f"{api_url.rstrip('/')}/repos/{repository}/commits/{encoded_ref}"
72
+ try:
73
+ raw = request_bytes(url, token=token, limit=MAX_MANIFEST_BYTES)
74
+ except RuntimeError:
75
+ # A repository-scoped Actions token can lack cross-repo read permission
76
+ # even when the source repository is public. Retry the immutable public
77
+ # read without credentials; never broaden token scope.
78
+ if not token:
79
+ raise
80
+ raw = request_bytes(url, token=None, limit=MAX_MANIFEST_BYTES)
81
+ payload = json.loads(raw)
82
+ revision = str(payload.get("sha") or "").lower() if isinstance(payload, dict) else ""
83
+ if not re.fullmatch(r"[0-9a-f]{40}", revision):
84
+ raise RuntimeError("GitHub did not return an exact source revision")
85
+ return revision
86
+
87
+
88
+ def validate_snapshot(
89
+ manifest_raw: bytes,
90
+ corpus_raw: bytes,
91
+ *,
92
+ expected_chunks: int = EXPECTED_PUBLIC_CHUNKS,
93
+ ) -> dict[str, Any]:
94
+ manifest = json.loads(manifest_raw.decode("utf-8"))
95
+ if not isinstance(manifest, dict):
96
+ raise ValueError("manifest must be a JSON object")
97
+ if str(manifest.get("secretScan") or "").upper() != "PASS":
98
+ raise ValueError("public projection secretScan must be PASS")
99
+
100
+ rows = 0
101
+ by_source: dict[str, int] = {}
102
+ ids: set[str] = set()
103
+ for line_number, line in enumerate(corpus_raw.decode("utf-8").splitlines(), start=1):
104
+ if not line.strip():
105
+ continue
106
+ row = json.loads(line)
107
+ if not isinstance(row, dict) or not row.get("id"):
108
+ raise ValueError(f"invalid corpus row at line {line_number}")
109
+ node_id = str(row["id"])
110
+ if node_id in ids:
111
+ raise ValueError(f"duplicate corpus id at line {line_number}: {node_id}")
112
+ ids.add(node_id)
113
+ text = str(row.get("text") or "")
114
+ declared = str(row.get("sha256") or "")
115
+ measured = sha256_bytes(text.encode("utf-8"))
116
+ if declared and declared != measured:
117
+ raise ValueError(f"row digest mismatch at line {line_number}: {node_id}")
118
+ source = str(row.get("source") or "unknown")
119
+ by_source[source] = by_source.get(source, 0) + 1
120
+ rows += 1
121
+
122
+ declared_count = int(manifest.get("publicChunkCount") or 0)
123
+ if rows != declared_count or rows != expected_chunks:
124
+ raise ValueError(
125
+ f"public chunk count mismatch: loaded={rows}, manifest={declared_count}, expected={expected_chunks}"
126
+ )
127
+ declared_by_source = manifest.get("bySource")
128
+ if isinstance(declared_by_source, dict):
129
+ normalized = {str(key): int(value) for key, value in declared_by_source.items()}
130
+ if normalized != by_source:
131
+ raise ValueError(
132
+ f"source histogram mismatch: loaded={by_source}, manifest={normalized}"
133
+ )
134
+ return {
135
+ "public_chunk_count": rows,
136
+ "by_source": by_source,
137
+ "manifest_sha256": sha256_bytes(manifest_raw),
138
+ "corpus_sha256": sha256_bytes(corpus_raw),
139
+ "manifest_projection_sha256": manifest.get("projectionSha256"),
140
+ "secret_scan": "PASS",
141
+ }
142
+
143
+
144
+ def atomic_write(path: Path, payload: bytes) -> None:
145
+ path.parent.mkdir(parents=True, exist_ok=True)
146
+ with tempfile.NamedTemporaryFile(
147
+ dir=path.parent,
148
+ prefix=f".{path.name}.",
149
+ delete=False,
150
+ ) as handle:
151
+ handle.write(payload)
152
+ handle.flush()
153
+ os.fsync(handle.fileno())
154
+ temporary = Path(handle.name)
155
+ os.replace(temporary, path)
156
+
157
+
158
+ def materialize(
159
+ output: Path,
160
+ *,
161
+ repository: str = DEFAULT_REPOSITORY,
162
+ ref: str = DEFAULT_REF,
163
+ token: str | None = None,
164
+ api_url: str = "https://api.github.com",
165
+ raw_url: str = "https://raw.githubusercontent.com",
166
+ ) -> dict[str, Any]:
167
+ revision = resolve_revision(repository, ref, token=token, api_url=api_url)
168
+ immutable_base = f"{raw_url.rstrip('/')}/{repository}/{revision}/data"
169
+ manifest_raw = request_bytes(
170
+ f"{immutable_base}/manifest.json",
171
+ limit=MAX_MANIFEST_BYTES,
172
+ )
173
+ corpus_raw = request_bytes(
174
+ f"{immutable_base}/brain-corpus.public.jsonl",
175
+ limit=MAX_CORPUS_BYTES,
176
+ )
177
+ validation = validate_snapshot(manifest_raw, corpus_raw)
178
+ receipt = {
179
+ "schema": "szl.second-brain.snapshot/v1",
180
+ "source_repository": repository,
181
+ "source_ref": ref,
182
+ "source_revision": revision,
183
+ "source_relation": "github-exact-revision-public-projection",
184
+ "canonical_dataset": "SZLHOLDINGS/szl-second-brain-inrepo",
185
+ "manifest_path": "data/manifest.json",
186
+ "corpus_path": "data/brain-corpus.public.jsonl",
187
+ "manifest_sha256": validation["manifest_sha256"],
188
+ "corpus_sha256": validation["corpus_sha256"],
189
+ "manifest_projection_sha256": validation["manifest_projection_sha256"],
190
+ "public_chunk_count": validation["public_chunk_count"],
191
+ "by_source": validation["by_source"],
192
+ "secret_scan": validation["secret_scan"],
193
+ "materialized_at": utc_now(),
194
+ "authority_state": "READ_ONLY",
195
+ "content_access": "HANDLES_ONLY",
196
+ "private_graph_nodes_materialized": 0,
197
+ "raw_graph_nodes_admitted_to_gradients": 0,
198
+ "lambda_state": "CONJECTURE_1",
199
+ }
200
+ atomic_write(output / "manifest.json", manifest_raw)
201
+ atomic_write(output / "brain-corpus.public.jsonl", corpus_raw)
202
+ atomic_write(
203
+ output / "source.json",
204
+ (json.dumps(receipt, sort_keys=True, indent=2) + "\n").encode("utf-8"),
205
+ )
206
+ return receipt
207
+
208
+
209
+ def token_from_environment() -> str | None:
210
+ for key in ("GH_READ_TOKEN", "GH_ADMIN_TOKEN", "GITHUB_TOKEN"):
211
+ value = os.environ.get(key)
212
+ if value and value.strip():
213
+ return value.strip()
214
+ return None
215
+
216
+
217
+ def main() -> int:
218
+ parser = argparse.ArgumentParser()
219
+ parser.add_argument("--output", type=Path, default=Path(".runtime/second-brain"))
220
+ parser.add_argument("--repository", default=DEFAULT_REPOSITORY)
221
+ parser.add_argument("--ref", default=DEFAULT_REF)
222
+ parser.add_argument("--api-url", default=os.environ.get("GITHUB_API_URL", "https://api.github.com"))
223
+ parser.add_argument("--raw-url", default="https://raw.githubusercontent.com")
224
+ args = parser.parse_args()
225
+ receipt = materialize(
226
+ args.output,
227
+ repository=args.repository,
228
+ ref=args.ref,
229
+ token=token_from_environment(),
230
+ api_url=args.api_url,
231
+ raw_url=args.raw_url,
232
+ )
233
+ print(
234
+ json.dumps(
235
+ {
236
+ "source_repository": receipt["source_repository"],
237
+ "source_revision": receipt["source_revision"],
238
+ "public_chunk_count": receipt["public_chunk_count"],
239
+ "corpus_sha256": receipt["corpus_sha256"],
240
+ "output": str(args.output),
241
+ },
242
+ sort_keys=True,
243
+ )
244
+ )
245
+ return 0
246
+
247
+
248
+ if __name__ == "__main__":
249
+ raise SystemExit(main())
second_brain_runtime.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Source-bound public Second Brain runtime for SZL Living Anatomy.
4
+
5
+ This module is deliberately read-only. It loads the public, source-bound
6
+ Second Brain projection bundled by the deployment workflow, validates the
7
+ snapshot receipt, and exposes lexical retrieval as handles only. It never
8
+ loads the owner's private graph, never returns corpus text, never trains model
9
+ weights, and never grants write authority.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import hashlib
14
+ import json
15
+ import math
16
+ import os
17
+ import re
18
+ import threading
19
+ from collections import Counter
20
+ from datetime import datetime, timezone
21
+ from pathlib import Path
22
+ from typing import Any
23
+
24
+ SCHEMA_HEALTH = "szl.living-anatomy.second-brain.health/v1"
25
+ SCHEMA_SEARCH = "szl.living-anatomy.second-brain.search/v1"
26
+ SCHEMA_CONTEXT = "szl.living-anatomy.second-brain.context/v1"
27
+ SCHEMA_MANIFEST = "szl.living-anatomy.second-brain.manifest/v1"
28
+ SOURCE_REPOSITORY = "szl-holdings/szl-second-brain"
29
+ CANONICAL_DATASET = "SZLHOLDINGS/szl-second-brain-inrepo"
30
+ PUBLIC_CHUNK_COUNT = 575
31
+ PRIVATE_GRAPH_NODES_DISCLOSED = 9464
32
+ MAX_QUERY_CHARS = 500
33
+ MAX_K = 12
34
+
35
+ TOKEN = re.compile(r"[a-z0-9λ]+", re.I)
36
+ STOP = {
37
+ "the", "is", "a", "an", "of", "and", "or", "to", "in", "for", "on", "at",
38
+ "by", "as", "what", "which", "who", "how", "why", "does", "did", "are",
39
+ "was", "be", "it", "this", "that", "with", "from", "into", "over", "not",
40
+ }
41
+
42
+ ROOT = Path(__file__).resolve().parent
43
+ SNAPSHOT_ROOT = Path(
44
+ os.environ.get(
45
+ "SECOND_BRAIN_SNAPSHOT_ROOT",
46
+ str(ROOT / ".runtime" / "second-brain"),
47
+ )
48
+ ).resolve()
49
+ MANIFEST_PATH = SNAPSHOT_ROOT / "manifest.json"
50
+ CORPUS_PATH = SNAPSHOT_ROOT / "brain-corpus.public.jsonl"
51
+ SOURCE_PATH = SNAPSHOT_ROOT / "source.json"
52
+
53
+
54
+ def _utc_now() -> str:
55
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
56
+
57
+
58
+ def _sha256_bytes(value: bytes) -> str:
59
+ return hashlib.sha256(value).hexdigest()
60
+
61
+
62
+ def _canonical_sha256(value: Any) -> str:
63
+ return _sha256_bytes(
64
+ json.dumps(
65
+ value,
66
+ sort_keys=True,
67
+ separators=(",", ":"),
68
+ ensure_ascii=False,
69
+ ).encode("utf-8")
70
+ )
71
+
72
+
73
+ def _tokenize(value: str) -> list[str]:
74
+ return [
75
+ token.lower()
76
+ for token in TOKEN.findall(value or "")
77
+ if len(token) > 1 and token.lower() not in STOP
78
+ ]
79
+
80
+
81
+ def _read_json(path: Path) -> dict[str, Any]:
82
+ payload = json.loads(path.read_text(encoding="utf-8"))
83
+ if not isinstance(payload, dict):
84
+ raise ValueError(f"{path.name} must contain a JSON object")
85
+ return payload
86
+
87
+
88
+ def _valid_revision(value: Any) -> bool:
89
+ return isinstance(value, str) and bool(re.fullmatch(r"[0-9a-f]{40}", value.lower()))
90
+
91
+
92
+ class PublicSecondBrain:
93
+ """Validated lexical index over the public handles-only projection."""
94
+
95
+ def __init__(self, snapshot_root: Path | None = None) -> None:
96
+ self.snapshot_root = Path(snapshot_root or SNAPSHOT_ROOT).resolve()
97
+ self.manifest_path = self.snapshot_root / "manifest.json"
98
+ self.corpus_path = self.snapshot_root / "brain-corpus.public.jsonl"
99
+ self.source_path = self.snapshot_root / "source.json"
100
+ self._lock = threading.RLock()
101
+ self._rows: list[dict[str, Any]] = []
102
+ self._df: Counter[str] = Counter()
103
+ self._manifest: dict[str, Any] = {}
104
+ self._source: dict[str, Any] = {}
105
+ self._load_error: str | None = None
106
+ self._loaded_at: str | None = None
107
+ self.reload()
108
+
109
+ def reload(self) -> dict[str, Any]:
110
+ with self._lock:
111
+ self._rows = []
112
+ self._df = Counter()
113
+ self._manifest = {}
114
+ self._source = {}
115
+ self._load_error = None
116
+ self._loaded_at = None
117
+ try:
118
+ manifest_raw = self.manifest_path.read_bytes()
119
+ corpus_raw = self.corpus_path.read_bytes()
120
+ source = _read_json(self.source_path)
121
+ manifest = json.loads(manifest_raw.decode("utf-8"))
122
+ if not isinstance(manifest, dict):
123
+ raise ValueError("manifest.json must contain a JSON object")
124
+ if source.get("schema") != "szl.second-brain.snapshot/v1":
125
+ raise ValueError("unsupported source receipt schema")
126
+ if source.get("source_repository") != SOURCE_REPOSITORY:
127
+ raise ValueError("unexpected Second Brain source repository")
128
+ if not _valid_revision(source.get("source_revision")):
129
+ raise ValueError("Second Brain source revision is not an exact Git SHA")
130
+ if source.get("manifest_sha256") != _sha256_bytes(manifest_raw):
131
+ raise ValueError("Second Brain manifest digest mismatch")
132
+ if source.get("corpus_sha256") != _sha256_bytes(corpus_raw):
133
+ raise ValueError("Second Brain corpus digest mismatch")
134
+
135
+ rows: list[dict[str, Any]] = []
136
+ document_frequency: Counter[str] = Counter()
137
+ for line_number, line in enumerate(corpus_raw.decode("utf-8").splitlines(), start=1):
138
+ if not line.strip():
139
+ continue
140
+ row = json.loads(line)
141
+ if not isinstance(row, dict) or not row.get("id"):
142
+ raise ValueError(f"invalid corpus row at line {line_number}")
143
+ text = str(row.get("text") or "")
144
+ declared_digest = str(row.get("sha256") or "")
145
+ measured_digest = _sha256_bytes(text.encode("utf-8"))
146
+ if declared_digest and declared_digest != measured_digest:
147
+ raise ValueError(f"row digest mismatch at line {line_number}")
148
+ tokens = _tokenize(f"{row.get('title', '')} {text}")
149
+ stored = {
150
+ "id": str(row["id"]),
151
+ "title": str(row.get("title") or ""),
152
+ "source": str(row.get("source") or "unknown"),
153
+ "sourceId": row.get("sourceId"),
154
+ "sha256": measured_digest,
155
+ "_tf": Counter(tokens),
156
+ }
157
+ rows.append(stored)
158
+ document_frequency.update(set(tokens))
159
+
160
+ declared_count = int(manifest.get("publicChunkCount") or 0)
161
+ receipt_count = int(source.get("public_chunk_count") or 0)
162
+ if declared_count != len(rows) or receipt_count != len(rows):
163
+ raise ValueError(
164
+ "public chunk count mismatch "
165
+ f"(manifest={declared_count}, receipt={receipt_count}, loaded={len(rows)})"
166
+ )
167
+ if len(rows) != PUBLIC_CHUNK_COUNT:
168
+ raise ValueError(
169
+ f"expected {PUBLIC_CHUNK_COUNT} public chunks, loaded {len(rows)}"
170
+ )
171
+ if str(manifest.get("secretScan") or "").upper() != "PASS":
172
+ raise ValueError("public projection secret scan is not PASS")
173
+
174
+ self._rows = rows
175
+ self._df = document_frequency
176
+ self._manifest = manifest
177
+ self._source = source
178
+ self._loaded_at = _utc_now()
179
+ except Exception as exc:
180
+ self._load_error = f"{type(exc).__name__}: {exc}"
181
+ return self.health()
182
+
183
+ @property
184
+ def ready(self) -> bool:
185
+ return self._load_error is None and len(self._rows) == PUBLIC_CHUNK_COUNT
186
+
187
+ @property
188
+ def source_revision(self) -> str | None:
189
+ value = self._source.get("source_revision")
190
+ return str(value) if _valid_revision(value) else None
191
+
192
+ def health(self) -> dict[str, Any]:
193
+ with self._lock:
194
+ by_source: dict[str, int] = {}
195
+ for row in self._rows:
196
+ source = str(row.get("source") or "unknown")
197
+ by_source[source] = by_source.get(source, 0) + 1
198
+ return {
199
+ "schema": SCHEMA_HEALTH,
200
+ "service": "living-anatomy-yachay-second-brain",
201
+ "ready": self.ready,
202
+ "state": "SOURCE_BOUND_PUBLIC_PROJECTION" if self.ready else "UNAVAILABLE",
203
+ "transport_state": "REACHABLE",
204
+ "evidence_state": "MEASURED" if self.ready else "UNAVAILABLE",
205
+ "verification_state": "STRUCTURAL_ONLY" if self.ready else "FAILED",
206
+ "authority_state": "READ_ONLY",
207
+ "kind": "SOFTWARE",
208
+ "content_access": "HANDLES_ONLY",
209
+ "source_repository": SOURCE_REPOSITORY,
210
+ "source_revision": self.source_revision,
211
+ "canonical_dataset": CANONICAL_DATASET,
212
+ "chunk_count": len(self._rows),
213
+ "declared_public_chunk_count": PUBLIC_CHUNK_COUNT,
214
+ "by_source": by_source,
215
+ "snapshot_root": str(self.snapshot_root),
216
+ "loaded_at": self._loaded_at,
217
+ "load_error": self._load_error,
218
+ "index_is_model_weights": False,
219
+ "private_graph_nodes_loaded": 0,
220
+ "private_graph_nodes_disclosed_elsewhere": PRIVATE_GRAPH_NODES_DISCLOSED,
221
+ "raw_graph_nodes_admitted_to_gradients": 0,
222
+ "lambda_state": "CONJECTURE_1",
223
+ "limits": [
224
+ "Lexical overlap is not correctness.",
225
+ "Only public handles are returned; corpus text remains inside the controller.",
226
+ "The owner's private graph is not bundled, queried, or exposed.",
227
+ "This read-only organ cannot authorize or execute an action.",
228
+ ],
229
+ }
230
+
231
+ def manifest(self) -> dict[str, Any]:
232
+ health = self.health()
233
+ return {
234
+ "schema": SCHEMA_MANIFEST,
235
+ "service": health["service"],
236
+ "ready": health["ready"],
237
+ "source": {
238
+ "repository": SOURCE_REPOSITORY,
239
+ "revision": self.source_revision,
240
+ "dataset": CANONICAL_DATASET,
241
+ "snapshot_receipt": self._source,
242
+ },
243
+ "corpus": {
244
+ "chunk_count": len(self._rows),
245
+ "by_source": health["by_source"],
246
+ "manifest": self._manifest,
247
+ },
248
+ "interfaces": {
249
+ "health": "/api/anatomy/v1/brain/health",
250
+ "manifest": "/api/anatomy/v1/brain/manifest",
251
+ "search": "/api/anatomy/v1/brain/search",
252
+ "context": "/api/anatomy/v1/brain/context",
253
+ },
254
+ "authority_state": "READ_ONLY",
255
+ "content_access": "HANDLES_ONLY",
256
+ "limits": health["limits"],
257
+ }
258
+
259
+ @staticmethod
260
+ def _handle(row: dict[str, Any]) -> dict[str, Any]:
261
+ return {
262
+ "nodeId": row["id"],
263
+ "nodeKind": "INDEX",
264
+ "label": "DECLARED",
265
+ "note": str(row.get("title") or "")[:160],
266
+ "source": row.get("source"),
267
+ "sourceId": row.get("sourceId"),
268
+ "sha256": row.get("sha256"),
269
+ }
270
+
271
+ def search(self, query: str, k: int = 6) -> dict[str, Any]:
272
+ query = str(query or "").strip()
273
+ if len(query) > MAX_QUERY_CHARS:
274
+ query = query[:MAX_QUERY_CHARS]
275
+ try:
276
+ requested_k = int(k)
277
+ except (TypeError, ValueError):
278
+ requested_k = 6
279
+ requested_k = max(1, min(requested_k, MAX_K))
280
+
281
+ with self._lock:
282
+ if not self.ready:
283
+ return {
284
+ "schema": SCHEMA_SEARCH,
285
+ "ready": False,
286
+ "query": query,
287
+ "handles": [],
288
+ "scores": [],
289
+ "source_revision": self.source_revision,
290
+ "error": self._load_error or "Second Brain snapshot unavailable",
291
+ "authority_state": "READ_ONLY",
292
+ "content_access": "HANDLES_ONLY",
293
+ }
294
+ query_tokens = _tokenize(query)
295
+ if not query_tokens:
296
+ return {
297
+ "schema": SCHEMA_SEARCH,
298
+ "ready": True,
299
+ "query": query,
300
+ "handles": [],
301
+ "scores": [],
302
+ "source_revision": self.source_revision,
303
+ "honesty": "Empty or stop-word-only query; no ranking fabricated.",
304
+ "authority_state": "READ_ONLY",
305
+ "content_access": "HANDLES_ONLY",
306
+ }
307
+
308
+ query_frequency = Counter(query_tokens)
309
+ scored: list[tuple[float, dict[str, Any]]] = []
310
+ total = max(1, len(self._rows))
311
+ for row in self._rows:
312
+ score = 0.0
313
+ row_frequency: Counter[str] = row["_tf"]
314
+ for term, query_count in query_frequency.items():
315
+ term_frequency = row_frequency.get(term, 0)
316
+ if not term_frequency:
317
+ continue
318
+ inverse_document_frequency = (
319
+ math.log((total + 1) / (1 + self._df.get(term, 0))) + 1.0
320
+ )
321
+ score += (
322
+ term_frequency / (term_frequency + 1.2)
323
+ ) * inverse_document_frequency * query_count
324
+ if score > 0:
325
+ scored.append((score, row))
326
+ scored.sort(key=lambda item: (-item[0], str(item[1]["id"])))
327
+ top = scored[:requested_k]
328
+ handles = [self._handle(row) for _, row in top]
329
+ scores = [round(score, 6) for score, _ in top]
330
+ result_body = {
331
+ "query": query,
332
+ "handles": handles,
333
+ "scores": scores,
334
+ "source_revision": self.source_revision,
335
+ "corpus_chunk_count": len(self._rows),
336
+ "ranking": "BM25_LIKE_LEXICAL",
337
+ "content_access": "HANDLES_ONLY",
338
+ }
339
+ return {
340
+ "schema": SCHEMA_SEARCH,
341
+ "ready": True,
342
+ **result_body,
343
+ "result_sha256": _canonical_sha256(result_body),
344
+ "authority_state": "READ_ONLY",
345
+ "index_is_model_weights": False,
346
+ "honesty": (
347
+ "Ranked lexical overlap over the public source-bound projection; "
348
+ "scores are relevance signals, never correctness or proof."
349
+ ),
350
+ }
351
+
352
+ def context(self, query: str, k: int = 6) -> dict[str, Any]:
353
+ search = self.search(query, k=k)
354
+ handles = search.get("handles") if isinstance(search, dict) else []
355
+ handles = handles if isinstance(handles, list) else []
356
+ model_handles = [
357
+ {
358
+ key: handle[key]
359
+ for key in ("nodeId", "nodeKind", "label", "note")
360
+ if key in handle
361
+ }
362
+ for handle in handles
363
+ if isinstance(handle, dict)
364
+ ]
365
+ evidence = [
366
+ {
367
+ "node_id": handle.get("nodeId"),
368
+ "source": handle.get("source"),
369
+ "source_id": handle.get("sourceId"),
370
+ "sha256": handle.get("sha256"),
371
+ }
372
+ for handle in handles
373
+ if isinstance(handle, dict)
374
+ ]
375
+ body = {
376
+ "query": search.get("query"),
377
+ "model_handles": model_handles,
378
+ "evidence": evidence,
379
+ "source_revision": search.get("source_revision"),
380
+ "ready": bool(search.get("ready")),
381
+ }
382
+ return {
383
+ "schema": SCHEMA_CONTEXT,
384
+ **body,
385
+ "context_sha256": _canonical_sha256(body),
386
+ "training_authority": "NONE",
387
+ "write_authority": "NONE",
388
+ "private_graph_nodes_loaded": 0,
389
+ "honesty": search.get("honesty"),
390
+ "error": search.get("error"),
391
+ }
server.py ADDED
@@ -0,0 +1,1088 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ * ``/version`` exposes the exact source and deployed Space revisions using the
9
+ shared vertical-conformance identity contract.
10
+ * ``/evidence`` indexes the source binding, local bundle receipt, and measured
11
+ dependency posture without upgrading structural checks to signed proof.
12
+ * ``/.well-known/szl-source.json`` identifies the GitHub source and live HF
13
+ revision without pretending that the two revisions are identical.
14
+ * ``/api/anatomy/v1/manifest`` describes the contract and status vocabulary.
15
+ * ``/api/anatomy/v1/capabilities`` exposes Purpose / Try / Evidence / Limits /
16
+ Reproduce for each major surface.
17
+ * ``/api/anatomy/v1/evidence`` separately probes the live dependencies.
18
+ * ``/api/anatomy/v1/receipt`` hashes the files that make up the bundle.
19
+ * ``POST /api/anatomy/v1/verify/receipt`` recomputes that local integrity
20
+ receipt. The result is deliberately ``STRUCTURAL-ONLY`` because this Space
21
+ has no signing key; it never upgrades an unsigned receipt to cryptographically
22
+ VERIFIED.
23
+ * ``GET/POST /api/anatomy/v1/organs/integrity`` runs the five-organ fail-closed
24
+ kernel (HEART/YUYAY, BRAIN/YACHAY, CIRCULATORY/YAWAR, NERVOUS/OTel,
25
+ SKELETON/Khipu). Energy stays UNAVAILABLE. Λ is Conjecture 1 OPEN.
26
+
27
+ No endpoint mutates state, signs data, runs a model, or claims that reachability
28
+ proves model quality. Lambda remains Conjecture 1 and the Space does not execute
29
+ Lean; formal claims are presented as a declared, linked snapshot.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import functools
35
+ import hashlib
36
+ import json
37
+ import os
38
+ import threading
39
+ import time
40
+ import urllib.error
41
+ import urllib.request
42
+ from concurrent.futures import ThreadPoolExecutor
43
+ from datetime import datetime, timezone
44
+ from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
45
+ from pathlib import Path
46
+ from urllib.parse import parse_qs, urlsplit
47
+
48
+ try:
49
+ from organ_integrity import envelope as _org_envelope
50
+ from organ_integrity import evaluate_anatomy as _evaluate_anatomy
51
+ from organ_integrity import parse_flags as _org_parse_flags
52
+ _ORGAN_INTEGRITY = True
53
+ except Exception:
54
+ _ORGAN_INTEGRITY = False
55
+ _org_envelope = None
56
+ _evaluate_anatomy = None
57
+ _org_parse_flags = None
58
+
59
+
60
+ PORT = int(os.environ.get("PORT", "7860"))
61
+ # Resolve from this file, not from a generic /app existence check. The Docker
62
+ # image places server.py in /app already; local verification must never
63
+ # accidentally serve an unrelated host-level /app directory.
64
+ DIRECTORY = Path(os.environ.get("ANATOMY_ROOT", str(Path(__file__).resolve().parent))).resolve()
65
+ SPACE_ID = "betterwithage/anatomy"
66
+ SOURCE_REPOSITORY = "szl-holdings/anatomy"
67
+ SOURCE_BASE_COMMIT = "9847b3031c1aacdcee9aa8e37ae33d573737a5c4"
68
+ DEPLOY_MANIFEST_PATH = DIRECTORY / "hf-deploy-manifest.json"
69
+ DOCTRINE = "v11"
70
+ LOCK = "749/14/163"
71
+ KERNEL_COMMIT = "c7c0ba17"
72
+ LOCKED_FORMULAS = ["F1", "F4", "F7", "F11", "F12", "F18", "F19", "F22"]
73
+
74
+ ARTIFACT_PATHS = (
75
+ "index.html",
76
+ "covenant-cockpit.html",
77
+ "favicon.svg",
78
+ "app.js",
79
+ "data.js",
80
+ "v5_organs.js",
81
+ "frontier_anatomy.js",
82
+ "szl-holo-v2.css",
83
+ "szl-holo-v2.js",
84
+ "live-body.html",
85
+ "live-body.js",
86
+ "covenant-cockpit.js",
87
+ "lib/three.min.js",
88
+ "lib/szl_verify_widget.js",
89
+ "v6_alive.js",
90
+ "yachay-second-brain.js",
91
+ "server.py",
92
+ "hf-deploy-manifest.json",
93
+ )
94
+
95
+ FORMULA_LINKS = {
96
+ "locked_spine": "https://github.com/szl-holdings/lutar-lean/tree/main/Lutar/Puriq/Formulas",
97
+ "proved_formulas": "https://github.com/szl-holdings/lutar-lean/blob/main/Lutar/Puriq/Formulas/ProvedFormulas.lean",
98
+ "puriq_formula": "https://github.com/szl-holdings/lutar-lean/blob/main/Lutar/Puriq/Formulas/PuriqFormulaLean.lean",
99
+ "quorum_safety": "https://github.com/szl-holdings/lutar-lean/blob/main/Lutar/Wave23/QuorumSafety.lean",
100
+ "hash_chain": "https://github.com/szl-holdings/lutar-lean/blob/main/Lutar/Wave8/HashChain.lean",
101
+ }
102
+
103
+ CAPABILITIES = [
104
+ {
105
+ "id": "anatomy.atlas",
106
+ "name": "Living governed-system atlas",
107
+ "purpose": "Make system ownership, authority boundaries, and receipt flow spatially inspectable.",
108
+ "try": {"method": "GET", "path": "/", "action": "Open an organ or run the guided tour."},
109
+ "evidence": {
110
+ "state": "COMPUTED",
111
+ "basis": "The self-contained WebGL bundle and its local data model are hashed into the anatomy integrity receipt.",
112
+ },
113
+ "limits": [
114
+ "A visual map is not proof that every depicted remote service is healthy.",
115
+ "The atlas is read-only and has no actuation authority.",
116
+ ],
117
+ "reproduce": {
118
+ "steps": [
119
+ "GET /api/anatomy/v1/receipt",
120
+ "POST its JSON body to /api/anatomy/v1/verify/receipt",
121
+ "Compare the artifact_set_sha256 and per-file hashes.",
122
+ ]
123
+ },
124
+ "authority_state": "READ_ONLY",
125
+ "formula_refs": [],
126
+ "provenance": ["https://github.com/szl-holdings/anatomy"],
127
+ },
128
+ {
129
+ "id": "anatomy.formula-spine",
130
+ "name": "Formula-to-organ spine",
131
+ "purpose": "Trace declared formal and experimental formulas to the organs they inform.",
132
+ "try": {"method": "UI", "path": "/", "action": "Open Formula Atlas or Proofs to organs."},
133
+ "evidence": {
134
+ "state": "SNAPSHOT",
135
+ "basis": "The Space presents source-linked declarations; it does not run the Lean kernel in this container.",
136
+ "locked_declared": LOCKED_FORMULAS,
137
+ "kernel_reference": KERNEL_COMMIT,
138
+ },
139
+ "limits": [
140
+ "Exactly eight formulas are declared locked in this snapshot.",
141
+ "Lambda is Conjecture 1, not a theorem.",
142
+ "Current source links and the historical kernel reference are shown separately to avoid false revision equivalence.",
143
+ ],
144
+ "reproduce": {
145
+ "steps": [
146
+ "Open the linked Lean files.",
147
+ "Pin the intended toolchain and commit in lutar-lean.",
148
+ "Run lake build and inspect #print axioms before promoting a claim.",
149
+ ]
150
+ },
151
+ "authority_state": "READ_ONLY",
152
+ "formula_refs": LOCKED_FORMULAS,
153
+ "provenance": list(FORMULA_LINKS.values()),
154
+ },
155
+ {
156
+ "id": "anatomy.live-lens",
157
+ "name": "Live organ posture lens",
158
+ "purpose": "Project current reachability and contract responses from A11OY, Killinchu, and the verifier estate into the body.",
159
+ "try": {"method": "GET", "path": "/api/anatomy/v1/evidence?refresh=1", "action": "Refresh measured dependencies."},
160
+ "evidence": {
161
+ "state": "MIXED",
162
+ "basis": "Dependency states are measured at request time and kept separate from the static anatomy snapshot.",
163
+ },
164
+ "limits": [
165
+ "HTTP reachability does not certify correctness, freshness, safety, or business performance.",
166
+ "A dependency can change after observed_at.",
167
+ ],
168
+ "reproduce": {"steps": ["GET /api/anatomy/v1/evidence?refresh=1", "Probe each declared URL independently."]},
169
+ "authority_state": "READ_ONLY",
170
+ "formula_refs": ["F1", "F7", "F22"],
171
+ "provenance": [
172
+ "https://huggingface.co/spaces/SZLHOLDINGS/a11oy",
173
+ "https://huggingface.co/spaces/SZLHOLDINGS/killinchu",
174
+ "https://huggingface.co/spaces/SZLHOLDINGS/governed-receipt-verifier",
175
+ ],
176
+ },
177
+ {
178
+ "id": "anatomy.integrity-receipt",
179
+ "name": "Local bundle integrity receipt",
180
+ "purpose": "Turn the deployed anatomy bundle into a replayable, byte-level evidence object.",
181
+ "try": {"method": "GET", "path": "/api/anatomy/v1/receipt", "action": "Generate the current deterministic receipt."},
182
+ "evidence": {
183
+ "state": "COMPUTED",
184
+ "verification_state": "STRUCTURAL_ONLY",
185
+ "basis": "SHA-256 is recomputed over every declared artifact and over the canonical receipt body.",
186
+ },
187
+ "limits": [
188
+ "The local receipt is unsigned because the Space has no private signing key.",
189
+ "STRUCTURAL-ONLY is not a cryptographic identity attestation.",
190
+ ],
191
+ "reproduce": {
192
+ "steps": [
193
+ "GET /api/anatomy/v1/receipt",
194
+ "POST the response to /api/anatomy/v1/verify/receipt",
195
+ "Expect STRUCTURAL-ONLY unless an artifact or digest was changed, in which case expect FAIL.",
196
+ ]
197
+ },
198
+ "authority_state": "READ_ONLY",
199
+ "formula_refs": ["F1", "F22"],
200
+ "provenance": [FORMULA_LINKS["hash_chain"]],
201
+ },
202
+ {
203
+ "id": "anatomy.organ-integrity",
204
+ "name": "Five-organ fail-closed kernel",
205
+ "purpose": "Prove the body, not the picture: HEART/YUYAY, BRAIN/YACHAY, CIRCULATORY/YAWAR, NERVOUS/OTel, SKELETON/Khipu. Any DOWN organ or a WILLAY veto fail-closes.",
206
+ "try": {"method": "GET", "path": "/api/anatomy/v1/organs/integrity", "action": "Healthy cycle, then POST {\"zero_heart\":true}."},
207
+ "evidence": {
208
+ "state": "COMPUTED",
209
+ "basis": "Stdlib SHA-256 receipt chain, advisory Λ, canal-partition silhouette. MEASURED NumPy YARQA lives on SZLHOLDINGS/szl-khipu.",
210
+ },
211
+ "limits": [
212
+ "Λ uniqueness remains Conjecture 1 OPEN. proven_trust is false.",
213
+ "Energy is UNAVAILABLE. Never a fabricated joule.",
214
+ "Canal leak here is the fail-closed rule, not NumPy YARQA.",
215
+ "CHECKED ≠ Lean PROVEN. Locked-proven stays exactly 8.",
216
+ ],
217
+ "reproduce": {
218
+ "steps": [
219
+ "GET /api/anatomy/v1/organs/integrity — expect 5/5 LIVE, verdict ADVISORY_BODY.",
220
+ "POST {\"zero_heart\":true} — HEART DOWN, body BLOCKED.",
221
+ "POST {\"fabricate_joule\":true} — NERVOUS DOWN, energy_j stays null.",
222
+ ]
223
+ },
224
+ "authority_state": "READ_ONLY",
225
+ "formula_refs": ["F1", "F4", "F7", "F11", "F12", "F18", "F19", "F22"],
226
+ "provenance": [
227
+ "https://github.com/szl-holdings/szl-organ-integrity",
228
+ "https://a-11-oy.com/organs/integrity",
229
+ "https://huggingface.co/spaces/SZLHOLDINGS/szl-khipu",
230
+ ],
231
+ },
232
+ {
233
+ "id": "anatomy.physics-overlays",
234
+ "name": "Physics and quantum-bio overlays",
235
+ "purpose": "Expose bounded exploratory models beside operational and formal layers without confusing them with measurements or locked theorems.",
236
+ "try": {"method": "UI", "path": "/", "action": "Open Physics, Quantum-bio, or Yarqa layers."},
237
+ "evidence": {
238
+ "state": "MODELED",
239
+ "basis": "The overlays run deterministic local equations and simulations from data.js; they do not ingest calibrated laboratory measurements.",
240
+ },
241
+ "limits": [
242
+ "Modeled is not measured.",
243
+ "Narrative and proposed claims remain labeled separately from verified formulas.",
244
+ "No clinical, biological, or quantum-computing performance claim is made.",
245
+ ],
246
+ "reproduce": {
247
+ "steps": [
248
+ "Inspect the formula card and its evidence label.",
249
+ "Record the input parameters.",
250
+ "Re-run the same local overlay and compare its integrity digest.",
251
+ ]
252
+ },
253
+ "authority_state": "READ_ONLY",
254
+ "formula_refs": ["QB-COH", "QB-PMF", "QB-COMPASS", "QB-Lambda-v5", "AG-LANDAUER"],
255
+ "provenance": ["https://github.com/szl-holdings/anatomy/blob/main/data.js"],
256
+ },
257
+ ]
258
+
259
+ DEPENDENCIES = (
260
+ {
261
+ "id": "a11oy.honesty",
262
+ "url": "https://szlholdings-a11oy.hf.space/api/a11oy/v1/honest",
263
+ "method": "GET",
264
+ "purpose": "Doctrine and runtime honesty posture",
265
+ "critical": True,
266
+ },
267
+ {
268
+ "id": "a11oy.public-verifier",
269
+ "url": "https://szlholdings-a11oy.hf.space/api/a11oy/v1/verify/receipt",
270
+ "method": "POST",
271
+ "purpose": "Canonical public DSSE/Khipu receipt-verifier contract",
272
+ "critical": True,
273
+ },
274
+ {
275
+ "id": "a11oy.organ-integrity",
276
+ "url": "https://a-11-oy.com/api/a11oy/v1/organs/integrity",
277
+ "method": "GET",
278
+ "purpose": "Fail-closed five-organ kernel on the command body",
279
+ "critical": False,
280
+ },
281
+ {
282
+ "id": "killinchu.experience-manifest",
283
+ "url": "https://szlholdings-killinchu.hf.space/api/killinchu/v1/experience/manifest",
284
+ "method": "GET",
285
+ "purpose": "Killinchu surface and evidence inventory",
286
+ "critical": False,
287
+ },
288
+ {
289
+ "id": "receipt-verifier.space",
290
+ "url": "https://szlholdings-governed-receipt-verifier.static.hf.space/",
291
+ "method": "GET",
292
+ "purpose": "Standalone browser verifier",
293
+ "critical": False,
294
+ },
295
+ )
296
+
297
+ CONTENT_SECURITY_POLICY = (
298
+ "default-src 'self'; "
299
+ "base-uri 'self'; "
300
+ "object-src 'none'; "
301
+ "script-src 'self' 'unsafe-inline'; "
302
+ "style-src 'self' 'unsafe-inline'; "
303
+ "img-src 'self' data: blob:; "
304
+ "font-src 'self'; "
305
+ "connect-src 'self' https://szlholdings-a11oy.hf.space https://a-11-oy.com "
306
+ "https://szlholdings-killinchu.hf.space https://szlholdings-amaru.hf.space "
307
+ "https://szlholdings-sentra.hf.space; "
308
+ "form-action 'self'; "
309
+ "frame-ancestors 'self' https://huggingface.co https://*.hf.space https://*.huggingface.co "
310
+ "https://a-11-oy.com https://*.a-11-oy.com https://a11oy.net https://*.a11oy.net"
311
+ )
312
+
313
+ _probe_lock = threading.Lock()
314
+ _probe_cache: dict[str, object] = {"at": 0.0, "value": None}
315
+ _revision_lock = threading.Lock()
316
+ _revision_cache: dict[str, object] = {"at": 0.0, "value": None}
317
+ _binding_lock = threading.Lock()
318
+ _binding_cache: dict[str, object] = {"at": 0.0, "key": None, "value": False}
319
+
320
+
321
+ def _utc_now() -> str:
322
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
323
+
324
+
325
+ def _canonical(value: object) -> bytes:
326
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
327
+
328
+
329
+ def _sha256(data: bytes) -> str:
330
+ return hashlib.sha256(data).hexdigest()
331
+
332
+
333
+ def _artifact_manifest() -> dict[str, object]:
334
+ artifacts: list[dict[str, object]] = []
335
+ for rel in ARTIFACT_PATHS:
336
+ path = DIRECTORY / rel
337
+ if path.is_file():
338
+ content = path.read_bytes()
339
+ artifacts.append({"path": rel, "bytes": len(content), "sha256": _sha256(content)})
340
+ else:
341
+ artifacts.append({"path": rel, "state": "MISSING"})
342
+ artifact_set_sha256 = _sha256(_canonical(artifacts))
343
+ return {
344
+ "algorithm": "sha256",
345
+ "artifact_count": len(artifacts),
346
+ "artifact_set_sha256": artifact_set_sha256,
347
+ "artifacts": artifacts,
348
+ }
349
+
350
+
351
+ def _artifact_set_complete(manifest: object) -> bool:
352
+ if not isinstance(manifest, dict):
353
+ return False
354
+ artifacts = manifest.get("artifacts")
355
+ if not isinstance(artifacts, list) or len(artifacts) != len(ARTIFACT_PATHS):
356
+ return False
357
+ paths: list[str] = []
358
+ for item in artifacts:
359
+ if (
360
+ not isinstance(item, dict)
361
+ or not isinstance(item.get("path"), str)
362
+ or not isinstance(item.get("bytes"), int)
363
+ or int(item["bytes"]) <= 0
364
+ or not _is_sha256(item.get("sha256"))
365
+ ):
366
+ return False
367
+ paths.append(str(item["path"]))
368
+ return len(set(paths)) == len(paths) and set(paths) == set(ARTIFACT_PATHS)
369
+
370
+
371
+ def _artifact_manifest_digest_valid(manifest: object) -> bool:
372
+ if not isinstance(manifest, dict) or not isinstance(manifest.get("artifacts"), list):
373
+ return False
374
+ return _sha256(_canonical(manifest["artifacts"])) == manifest.get("artifact_set_sha256")
375
+
376
+
377
+ def _local_receipt() -> dict[str, object]:
378
+ manifest = _artifact_manifest()
379
+ artifact_complete = _artifact_set_complete(manifest) and _artifact_manifest_digest_valid(manifest)
380
+ body: dict[str, object] = {
381
+ "schema": "szl.anatomy-integrity-receipt/v1",
382
+ "subject": {
383
+ "space": SPACE_ID,
384
+ "artifact_set_sha256": manifest["artifact_set_sha256"],
385
+ },
386
+ "claim": {
387
+ "purpose": "Byte-level integrity of the deployed Living Anatomy bundle",
388
+ "authority_state": "READ_ONLY",
389
+ "evidence_state": "COMPUTED" if artifact_complete else "UNAVAILABLE",
390
+ "doctrine": DOCTRINE,
391
+ "kernel_reference": KERNEL_COMMIT,
392
+ "locked_proven_declared": len(LOCKED_FORMULAS),
393
+ "lambda_state": "CONJECTURE_1",
394
+ },
395
+ "evidence": manifest,
396
+ "signature": {
397
+ "state": "UNAVAILABLE",
398
+ "reason": "No private signing key is present in this public visualization Space.",
399
+ },
400
+ "limits": [
401
+ "Artifact integrity does not certify remote-service health or model quality.",
402
+ "Unsigned local receipt; verification is STRUCTURAL-ONLY.",
403
+ ],
404
+ }
405
+ return {
406
+ "receipt": body,
407
+ "receipt_id": _sha256(_canonical(body)),
408
+ "verification_state": "STRUCTURAL_ONLY" if artifact_complete else "FAILED",
409
+ }
410
+
411
+
412
+ def _check_local_receipt(candidate: object) -> tuple[int, dict[str, object]]:
413
+ wrapper = candidate if isinstance(candidate, dict) else {}
414
+ receipt = wrapper.get("receipt", wrapper) if isinstance(wrapper, dict) else {}
415
+ supplied_id = wrapper.get("receipt_id") if isinstance(wrapper, dict) else None
416
+ if not isinstance(receipt, dict):
417
+ receipt = {}
418
+
419
+ current = _artifact_manifest()
420
+ recomputed_id = _sha256(_canonical(receipt))
421
+ subject = receipt.get("subject") if isinstance(receipt.get("subject"), dict) else {}
422
+ evidence = receipt.get("evidence") if isinstance(receipt.get("evidence"), dict) else {}
423
+ current_complete = _artifact_set_complete(current) and _artifact_manifest_digest_valid(current)
424
+ candidate_complete = _artifact_set_complete(evidence) and _artifact_manifest_digest_valid(evidence)
425
+ checks = [
426
+ {
427
+ "name": "schema",
428
+ "status": "PASS" if receipt.get("schema") == "szl.anatomy-integrity-receipt/v1" else "FAIL",
429
+ "detail": "Expected szl.anatomy-integrity-receipt/v1.",
430
+ },
431
+ {
432
+ "name": "subject",
433
+ "status": "PASS" if subject.get("space") == SPACE_ID else "FAIL",
434
+ "detail": f"Expected {SPACE_ID}.",
435
+ },
436
+ {
437
+ "name": "receipt_digest",
438
+ "status": "PASS" if supplied_id and supplied_id == recomputed_id else "FAIL",
439
+ "detail": "SHA-256 over the canonical receipt body.",
440
+ },
441
+ {
442
+ "name": "artifact_set",
443
+ "status": "PASS"
444
+ if current_complete
445
+ and candidate_complete
446
+ and evidence.get("artifact_set_sha256") == current["artifact_set_sha256"]
447
+ and subject.get("artifact_set_sha256") == current["artifact_set_sha256"]
448
+ else "FAIL",
449
+ "detail": "Recomputed from both the submitted evidence and files currently served by this Space.",
450
+ },
451
+ {
452
+ "name": "artifact_completeness",
453
+ "status": "PASS"
454
+ if current_complete and candidate_complete
455
+ else "FAIL",
456
+ "detail": "Both the submitted and currently served manifests must contain every non-empty runtime artifact and bind their artifact-list digest.",
457
+ },
458
+ {
459
+ "name": "signature",
460
+ "status": "UNAVAILABLE",
461
+ "detail": "This local integrity receipt is unsigned; no cryptographic identity green is asserted.",
462
+ },
463
+ ]
464
+ failed = any(item["status"] == "FAIL" for item in checks)
465
+ verdict = "FAIL" if failed else "STRUCTURAL-ONLY"
466
+ return (400 if failed else 200), {
467
+ "schema": "szl.receipt-verification/v1",
468
+ "ok": not failed,
469
+ "verdict": verdict,
470
+ "verification_state": "FAILED" if failed else "STRUCTURAL_ONLY",
471
+ "checks": checks,
472
+ "recomputed_receipt_id": recomputed_id,
473
+ "observed_at": _utc_now(),
474
+ "limits": "STRUCTURAL-ONLY is advisory and is not a signature verification.",
475
+ }
476
+
477
+
478
+ def _probe_dependency(dep: dict[str, object]) -> dict[str, object]:
479
+ method = str(dep["method"])
480
+ data = b"{}" if method == "POST" else None
481
+ headers = {
482
+ "User-Agent": "szl-anatomy-evidence/1.0",
483
+ "Accept": "application/json,text/html;q=0.8",
484
+ }
485
+ if data is not None:
486
+ headers["Content-Type"] = "application/json"
487
+ req = urllib.request.Request(str(dep["url"]), data=data, headers=headers, method=method)
488
+ status: int | None = None
489
+ error: str | None = None
490
+ try:
491
+ with urllib.request.urlopen(req, timeout=4) as response:
492
+ status = response.status
493
+ response.read(256)
494
+ except urllib.error.HTTPError as exc:
495
+ status = exc.code
496
+ error = f"HTTP {exc.code}"
497
+ except Exception as exc: # network state is evidence, not a server failure
498
+ error = type(exc).__name__
499
+
500
+ reachable = status is not None
501
+ if method == "POST":
502
+ contract_available = status in (200, 201, 400, 422, 429)
503
+ else:
504
+ contract_available = status is not None and 200 <= status < 400
505
+ if contract_available:
506
+ contract_state = "AVAILABLE"
507
+ evidence_state = "LIVE"
508
+ elif status == 404:
509
+ contract_state = "MISSING"
510
+ evidence_state = "UNAVAILABLE"
511
+ elif reachable:
512
+ contract_state = "DEGRADED"
513
+ evidence_state = "UNAVAILABLE"
514
+ else:
515
+ contract_state = "UNREACHABLE"
516
+ evidence_state = "UNAVAILABLE"
517
+ return {
518
+ **dep,
519
+ "transport_state": "REACHABLE" if reachable else "UNREACHABLE",
520
+ "contract_state": contract_state,
521
+ "evidence_state": evidence_state,
522
+ "http_status": status,
523
+ "error": error,
524
+ }
525
+
526
+
527
+ def _dependency_evidence(force: bool = False) -> dict[str, object]:
528
+ now = time.monotonic()
529
+ with _probe_lock:
530
+ cached = _probe_cache.get("value")
531
+ if not force and cached is not None and now - float(_probe_cache["at"]) < 30:
532
+ return cached # type: ignore[return-value]
533
+ with ThreadPoolExecutor(max_workers=len(DEPENDENCIES)) as pool:
534
+ rows = list(pool.map(_probe_dependency, DEPENDENCIES))
535
+ live_count = sum(row["evidence_state"] == "LIVE" for row in rows)
536
+ evidence_state = "LIVE" if live_count == len(rows) else ("MIXED" if live_count else "UNAVAILABLE")
537
+ verifier = next(row for row in rows if row["id"] == "a11oy.public-verifier")
538
+ value: dict[str, object] = {
539
+ "schema": "szl.anatomy-evidence/v1",
540
+ "observed_at": _utc_now(),
541
+ "scope": "Endpoint reachability and declared contract presence only.",
542
+ "transport_state": "REACHABLE",
543
+ "evidence_state": evidence_state,
544
+ "verification_state": "AVAILABLE" if verifier["contract_state"] == "AVAILABLE" else "UNAVAILABLE",
545
+ "authority_state": "READ_ONLY",
546
+ "summary": {"live": live_count, "total": len(rows)},
547
+ "dependencies": rows,
548
+ "limits": [
549
+ "Reachability does not certify quality, safety, freshness, or business performance.",
550
+ "The local anatomy integrity verifier remains STRUCTURAL_ONLY because it is unsigned.",
551
+ ],
552
+ }
553
+ with _probe_lock:
554
+ _probe_cache.update({"at": time.monotonic(), "value": value})
555
+ return value
556
+
557
+
558
+ def _is_full_revision(value: object) -> bool:
559
+ return (
560
+ isinstance(value, str)
561
+ and len(value) == 40
562
+ and all(character in "0123456789abcdef" for character in value.lower())
563
+ )
564
+
565
+
566
+ def _is_sha256(value: object) -> bool:
567
+ return (
568
+ isinstance(value, str)
569
+ and len(value) == 64
570
+ and all(character in "0123456789abcdef" for character in value.lower())
571
+ )
572
+
573
+
574
+ def _hf_revision(force: bool = False) -> str | None:
575
+ env_revision = os.environ.get("SPACE_REPOSITORY_COMMIT")
576
+ if _is_full_revision(env_revision):
577
+ return str(env_revision).lower()
578
+ now = time.monotonic()
579
+ with _revision_lock:
580
+ cached = _revision_cache.get("value")
581
+ if not force and cached and now - float(_revision_cache["at"]) < 60:
582
+ return str(cached)
583
+ req = urllib.request.Request(
584
+ "https://huggingface.co/api/spaces/betterwithage/anatomy?expand[]=sha",
585
+ headers={"User-Agent": "szl-anatomy-source-attestation/1.0", "Accept": "application/json"},
586
+ )
587
+ revision: str | None = None
588
+ try:
589
+ with urllib.request.urlopen(req, timeout=4) as response:
590
+ data = json.load(response)
591
+ candidate = data.get("sha")
592
+ if _is_full_revision(candidate):
593
+ revision = str(candidate).lower()
594
+ except Exception:
595
+ revision = None
596
+ with _revision_lock:
597
+ _revision_cache.update({"at": time.monotonic(), "value": revision})
598
+ return revision
599
+
600
+
601
+ def _hf_commit_matches_source(
602
+ revision: object,
603
+ source_revision: object,
604
+ workflow_run_id: object,
605
+ force: bool = False,
606
+ ) -> bool:
607
+ if (
608
+ not _is_full_revision(revision)
609
+ or not _is_full_revision(source_revision)
610
+ or not isinstance(workflow_run_id, str)
611
+ or not workflow_run_id.isdigit()
612
+ ):
613
+ return False
614
+ revision = str(revision).lower()
615
+ source_revision = str(source_revision).lower()
616
+ key = f"{revision}:{source_revision}:{workflow_run_id}"
617
+ now = time.monotonic()
618
+ with _binding_lock:
619
+ if (
620
+ not force
621
+ and _binding_cache.get("key") == key
622
+ and now - float(_binding_cache["at"]) < 60
623
+ ):
624
+ return bool(_binding_cache["value"])
625
+
626
+ expected_title = f"hf-sync: source {source_revision} run {workflow_run_id}"
627
+ commits_request = urllib.request.Request(
628
+ "https://huggingface.co/api/spaces/betterwithage/anatomy/commits/main?limit=1",
629
+ headers={"User-Agent": "szl-anatomy-source-attestation/1.1", "Accept": "application/json"},
630
+ )
631
+ diff_request = urllib.request.Request(
632
+ f"https://huggingface.co/spaces/betterwithage/anatomy/commit/{revision}.diff",
633
+ headers={"User-Agent": "szl-anatomy-source-attestation/1.1", "Accept": "text/plain"},
634
+ )
635
+ manifest_request = urllib.request.Request(
636
+ "https://huggingface.co/spaces/betterwithage/anatomy/resolve/"
637
+ f"{revision}/hf-deploy-manifest.json",
638
+ headers={"User-Agent": "szl-anatomy-source-attestation/1.1", "Accept": "application/json"},
639
+ )
640
+ matched = False
641
+ try:
642
+ with urllib.request.urlopen(commits_request, timeout=4) as response:
643
+ commits = json.load(response)
644
+ with urllib.request.urlopen(diff_request, timeout=4) as response:
645
+ commit_diff = response.read(1_000_000).decode("utf-8")
646
+ with urllib.request.urlopen(manifest_request, timeout=4) as response:
647
+ deployed_manifest = json.loads(response.read(100_000).decode("utf-8"))
648
+ latest = commits[0] if isinstance(commits, list) and commits else {}
649
+ matched = (
650
+ isinstance(latest, dict)
651
+ and str(latest.get("id") or "").lower() == revision
652
+ and latest.get("title") == expected_title
653
+ and "diff --git a/hf-deploy-manifest.json b/hf-deploy-manifest.json" in commit_diff
654
+ and isinstance(deployed_manifest, dict)
655
+ and deployed_manifest.get("schema") == "szl.hf-deploy-manifest/v1"
656
+ and deployed_manifest.get("source_repository") == SOURCE_REPOSITORY
657
+ and str(deployed_manifest.get("source_revision") or "").lower() == source_revision
658
+ and deployed_manifest.get("workflow_run_id") == workflow_run_id
659
+ )
660
+ except Exception:
661
+ matched = False
662
+ with _binding_lock:
663
+ _binding_cache.update({"at": time.monotonic(), "key": key, "value": matched})
664
+ return matched
665
+
666
+
667
+ def _source_binding() -> dict[str, object]:
668
+ fallback: dict[str, object] = {
669
+ "repository": SOURCE_REPOSITORY,
670
+ "commit": SOURCE_BASE_COMMIT,
671
+ "path": "",
672
+ "relation": "base-plus-hf-overlay",
673
+ "alignment_state": "PENDING_GITHUB_SYNC",
674
+ "workflow_run_id": None,
675
+ "built_at": None,
676
+ "limits": [
677
+ "source.commit is the declared GitHub base; deployment.hf_revision is measured separately.",
678
+ "No workflow-generated deployment manifest was observed.",
679
+ ],
680
+ }
681
+ try:
682
+ payload = json.loads(DEPLOY_MANIFEST_PATH.read_text(encoding="utf-8"))
683
+ except (OSError, UnicodeError, json.JSONDecodeError):
684
+ return fallback
685
+ repository = payload.get("source_repository")
686
+ revision = payload.get("source_revision")
687
+ workflow_run_id = payload.get("workflow_run_id")
688
+ if (
689
+ payload.get("schema") != "szl.hf-deploy-manifest/v1"
690
+ or repository != SOURCE_REPOSITORY
691
+ or not _is_full_revision(revision)
692
+ or not isinstance(workflow_run_id, str)
693
+ or not workflow_run_id.isdigit()
694
+ ):
695
+ return fallback
696
+ return {
697
+ "repository": repository,
698
+ "commit": revision.lower(),
699
+ "path": str(payload.get("source_path") or ""),
700
+ "relation": "github-actions-source-bound-deployment",
701
+ "alignment_state": "SOURCE_BOUND_DEPLOYMENT",
702
+ "workflow_run_id": workflow_run_id,
703
+ "built_at": payload.get("built_at"),
704
+ "limits": [
705
+ "The manifest binds this Hugging Face revision to the GitHub commit used by the deployment workflow.",
706
+ "The deployment uploads a declared runtime whitelist; it does not claim whole-repository byte parity.",
707
+ ],
708
+ }
709
+
710
+
711
+ def _source_attestation(force: bool = False) -> dict[str, object]:
712
+ revision = _hf_revision(force=force)
713
+ manifest = _artifact_manifest()
714
+ source_binding = _source_binding()
715
+ manifest_source_revision = source_binding.get("commit")
716
+ workflow_run_id = source_binding.get("workflow_run_id")
717
+ revision_bound = (
718
+ source_binding["alignment_state"] == "SOURCE_BOUND_DEPLOYMENT"
719
+ and _hf_commit_matches_source(
720
+ revision, manifest_source_revision, workflow_run_id, force=force
721
+ )
722
+ )
723
+ alignment_state = source_binding["alignment_state"]
724
+ limits = list(source_binding["limits"])
725
+ if alignment_state == "SOURCE_BOUND_DEPLOYMENT" and not revision_bound:
726
+ alignment_state = "DEPLOYMENT_REVISION_UNBOUND"
727
+ limits.append(
728
+ "The current Hugging Face commit metadata and diff do not bind this manifest to the measured deployment revision."
729
+ )
730
+ return {
731
+ "schema": "szl.deployment-source/v1",
732
+ "source": {
733
+ key: source_binding[key]
734
+ for key in ("repository", "commit", "path", "relation")
735
+ },
736
+ "deployment": {
737
+ "hf_space": SPACE_ID,
738
+ "hf_revision": revision,
739
+ "artifact_set_sha256": manifest["artifact_set_sha256"],
740
+ "commit_binding": "MEASURED" if revision_bound else "UNAVAILABLE",
741
+ "workflow_run_id": workflow_run_id if revision_bound else None,
742
+ },
743
+ "built_at": source_binding["built_at"],
744
+ "observed_at": _utc_now(),
745
+ "alignment_state": alignment_state,
746
+ "limits": limits,
747
+ }
748
+
749
+
750
+ def _version_contract(force: bool = False) -> dict[str, object]:
751
+ source = _source_attestation(force=force)
752
+ source_identity = source["source"]
753
+ deployment = source["deployment"]
754
+ identity_measured = (
755
+ source["alignment_state"] == "SOURCE_BOUND_DEPLOYMENT"
756
+ and isinstance(source_identity, dict)
757
+ and _is_full_revision(source_identity.get("commit"))
758
+ and isinstance(deployment, dict)
759
+ and _is_full_revision(deployment.get("hf_revision"))
760
+ )
761
+ return {
762
+ "schemaVersion": "szl.vertical-conformance.version.v1",
763
+ "service": "anatomy",
764
+ "surface": "anatomy",
765
+ "gitSha": source_identity.get("commit") if identity_measured else None,
766
+ "evidenceState": "MEASURED" if identity_measured else "UNAVAILABLE",
767
+ "deploymentRevision": deployment.get("hf_revision") if isinstance(deployment, dict) else None,
768
+ "contractVersion": "1.1.0",
769
+ }
770
+
771
+
772
+ def _evidence_contract(force: bool = False) -> dict[str, object]:
773
+ source = _source_attestation(force=force)
774
+ dependency_evidence = _dependency_evidence(force=force)
775
+ local_receipt = _local_receipt()
776
+ source_identity = source["source"]
777
+ deployment = source["deployment"]
778
+ source_bound = (
779
+ source["alignment_state"] == "SOURCE_BOUND_DEPLOYMENT"
780
+ and isinstance(source_identity, dict)
781
+ and _is_full_revision(source_identity.get("commit"))
782
+ and isinstance(deployment, dict)
783
+ and _is_full_revision(deployment.get("hf_revision"))
784
+ )
785
+ receipt_body = local_receipt["receipt"]
786
+ receipt_evidence = receipt_body["evidence"] if isinstance(receipt_body, dict) else {}
787
+ artifact_complete = _artifact_set_complete(receipt_evidence)
788
+ evidence_available = source_bound and artifact_complete
789
+ return {
790
+ "schemaVersion": "szl.vertical-conformance.evidence.v1",
791
+ "service": "anatomy",
792
+ "surface": "anatomy",
793
+ "gitSha": source_identity.get("commit") if evidence_available else None,
794
+ "evidenceState": "PARTIAL" if evidence_available else "UNAVAILABLE",
795
+ "runtime": {
796
+ "status": "RUNNING" if artifact_complete else "DEGRADED",
797
+ "ready": artifact_complete,
798
+ "transportState": "REACHABLE",
799
+ "authorityState": "READ_ONLY",
800
+ },
801
+ "source": source,
802
+ "receipts": [
803
+ {
804
+ "kind": "bundle-integrity",
805
+ "status": "STRUCTURAL_ONLY" if artifact_complete else "FAILED",
806
+ "receiptId": local_receipt["receipt_id"],
807
+ "artifactSetSha256": (
808
+ receipt_evidence.get("artifact_set_sha256")
809
+ if isinstance(receipt_evidence, dict)
810
+ else None
811
+ ),
812
+ "scope": "deployed runtime whitelist; unsigned local recomputation",
813
+ "verify": "/api/anatomy/v1/verify/receipt",
814
+ }
815
+ ],
816
+ "dependencies": {
817
+ "evidenceState": dependency_evidence["evidence_state"],
818
+ "observedAt": dependency_evidence["observed_at"],
819
+ "live": dependency_evidence["summary"]["live"],
820
+ "total": dependency_evidence["summary"]["total"],
821
+ "details": "/api/anatomy/v1/evidence?refresh=1",
822
+ },
823
+ "outputProvenance": {
824
+ "signatureStatus": "UNSIGNED",
825
+ "authenticityEstablished": False,
826
+ "record": "content-addressed bundle receipt; no runtime signing key",
827
+ },
828
+ "limitations": [
829
+ "The bundle receipt is STRUCTURAL_ONLY and does not establish publisher identity.",
830
+ "Dependency reachability does not certify quality, safety, freshness, or business performance.",
831
+ "The Space is read-only and does not execute or authorize agent actions.",
832
+ ],
833
+ }
834
+
835
+
836
+ def _manifest() -> dict[str, object]:
837
+ return {
838
+ "schema": "szl.anatomy-manifest/v1",
839
+ "service": "anatomy-space",
840
+ "space": SPACE_ID,
841
+ "purpose": "Read-only spatial evidence map of the governed-agent substrate.",
842
+ "contract_version": "1.1.0",
843
+ "state_dimensions": {
844
+ "transport_state": "REACHABLE",
845
+ "evidence_state": "MIXED",
846
+ "verification_state": "STRUCTURAL_ONLY",
847
+ "authority_state": "READ_ONLY",
848
+ },
849
+ "status_vocabulary": {
850
+ "transport_state": ["REACHABLE", "UNREACHABLE"],
851
+ "evidence_state": ["LIVE", "COMPUTED", "SNAPSHOT", "MODELED", "MIXED", "UNAVAILABLE"],
852
+ "verification_state": ["VERIFIED", "STRUCTURAL_ONLY", "UNAVAILABLE", "FAILED"],
853
+ "authority_state": ["READ_ONLY", "PROPOSAL_ONLY", "MUTATING"],
854
+ },
855
+ "endpoints": {
856
+ "version": "/version",
857
+ "evidence_index": "/evidence",
858
+ "manifest": "/api/anatomy/v1/manifest",
859
+ "capabilities": "/api/anatomy/v1/capabilities",
860
+ "evidence": "/api/anatomy/v1/evidence?refresh=1",
861
+ "receipt": "/api/anatomy/v1/receipt",
862
+ "verify_receipt": "/api/anatomy/v1/verify/receipt",
863
+ "organ_integrity": "/api/anatomy/v1/organs/integrity",
864
+ "source": "/.well-known/szl-source.json",
865
+ },
866
+ "doctrine": {
867
+ "version": DOCTRINE,
868
+ "lock": LOCK,
869
+ "kernel_reference": KERNEL_COMMIT,
870
+ "locked_proven_declared": LOCKED_FORMULAS,
871
+ "lambda": "CONJECTURE_1",
872
+ },
873
+ "limits": [
874
+ "RUNNING or REACHABLE describes transport, not model quality.",
875
+ "This Space is a visualization and evidence reader, not an autonomous actuator.",
876
+ ],
877
+ }
878
+
879
+
880
+ class HardenedHandler(SimpleHTTPRequestHandler):
881
+ server_version = "szl"
882
+ sys_version = ""
883
+
884
+ def version_string(self) -> str:
885
+ return "szl"
886
+
887
+ def _send_json(
888
+ self,
889
+ payload: object,
890
+ *,
891
+ status: int = 200,
892
+ evidence_state: str = "SNAPSHOT",
893
+ extra_headers: dict[str, str] | None = None,
894
+ ) -> None:
895
+ body = json.dumps(payload, ensure_ascii=False, sort_keys=True).encode("utf-8")
896
+ self.send_response(status)
897
+ self.send_header("Content-Type", "application/json; charset=utf-8")
898
+ self.send_header("Content-Length", str(len(body)))
899
+ self.send_header("Cache-Control", "no-store")
900
+ self.send_header("Access-Control-Allow-Origin", "*")
901
+ self.send_header("X-SZL-Transport-State", "REACHABLE")
902
+ self.send_header("X-SZL-Evidence-State", evidence_state)
903
+ if extra_headers:
904
+ for key, value in extra_headers.items():
905
+ self.send_header(key, value)
906
+ self.end_headers()
907
+ self.wfile.write(body)
908
+
909
+ def do_OPTIONS(self) -> None: # noqa: N802
910
+ self.send_response(204)
911
+ self.send_header("Access-Control-Allow-Origin", "*")
912
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
913
+ self.send_header("Access-Control-Allow-Headers", "Content-Type")
914
+ self.send_header("Access-Control-Max-Age", "600")
915
+ self.end_headers()
916
+
917
+ def do_GET(self) -> None: # noqa: N802
918
+ parsed = urlsplit(self.path)
919
+ path = parsed.path
920
+ query = parse_qs(parsed.query)
921
+ force = query.get("refresh") == ["1"]
922
+ if path == "/healthz":
923
+ self._send_json(
924
+ {
925
+ "status": "ok",
926
+ "organ": "anatomy",
927
+ "service": "anatomy-space",
928
+ "transport_state": "REACHABLE",
929
+ "evidence_state": "SNAPSHOT",
930
+ "verification_state": "STRUCTURAL_ONLY",
931
+ "authority_state": "READ_ONLY",
932
+ "contracts": {"version": "/version", "evidence": "/evidence"},
933
+ "note": "Transport health only; quality and upstream freshness are not inferred.",
934
+ },
935
+ evidence_state="SNAPSHOT",
936
+ )
937
+ return
938
+ if path == "/version":
939
+ payload = _version_contract(force=force)
940
+ self._send_json(
941
+ payload,
942
+ status=200 if payload["evidenceState"] == "MEASURED" else 503,
943
+ evidence_state=str(payload["evidenceState"]),
944
+ )
945
+ return
946
+ if path == "/evidence":
947
+ payload = _evidence_contract(force=force)
948
+ receipt_status = str(payload["receipts"][0]["status"])
949
+ self._send_json(
950
+ payload,
951
+ status=200 if payload["evidenceState"] == "PARTIAL" else 503,
952
+ evidence_state=str(payload["evidenceState"]),
953
+ extra_headers={"X-SZL-Verification-State": receipt_status},
954
+ )
955
+ return
956
+ if path == "/.well-known/szl-source.json":
957
+ self._send_json(_source_attestation(force=force), evidence_state="COMPUTED")
958
+ return
959
+ if path == "/api/anatomy/v1/manifest":
960
+ self._send_json(_manifest(), evidence_state="SNAPSHOT")
961
+ return
962
+ if path in ("/api/anatomy/v1/capabilities", "/api/anatomy/v1/capability-matrix"):
963
+ self._send_json(
964
+ {
965
+ "schema": "szl.anatomy-capabilities/v1",
966
+ "state_dimensions": _manifest()["state_dimensions"],
967
+ "count": len(CAPABILITIES),
968
+ "capabilities": CAPABILITIES,
969
+ },
970
+ evidence_state="MIXED",
971
+ )
972
+ return
973
+ if path == "/api/anatomy/v1/evidence":
974
+ payload = _dependency_evidence(force=force)
975
+ self._send_json(payload, evidence_state=str(payload["evidence_state"]))
976
+ return
977
+ if path == "/api/anatomy/v1/receipt":
978
+ payload = _local_receipt()
979
+ verification_state = str(payload["verification_state"])
980
+ self._send_json(
981
+ payload,
982
+ status=200 if verification_state == "STRUCTURAL_ONLY" else 503,
983
+ evidence_state=("COMPUTED" if verification_state == "STRUCTURAL_ONLY" else "UNAVAILABLE"),
984
+ extra_headers={"X-SZL-Verification-State": verification_state},
985
+ )
986
+ return
987
+ if path in ("/api/anatomy/v1/organs/integrity", "/api/organs/integrity"):
988
+ if not _ORGAN_INTEGRITY:
989
+ self._send_json(
990
+ {"ok": False, "error": "organ-integrity kernel UNAVAILABLE"},
991
+ status=503,
992
+ evidence_state="UNAVAILABLE",
993
+ )
994
+ return
995
+ flags = _org_parse_flags(query)
996
+ payload = _org_envelope(_evaluate_anatomy(**flags))
997
+ ev = payload.get("body") if isinstance(payload, dict) else {}
998
+ blocked = bool(ev.get("blocked")) if isinstance(ev, dict) else False
999
+ self._send_json(
1000
+ payload,
1001
+ evidence_state="COMPUTED",
1002
+ extra_headers={"X-SZL-Organ-Verdict": "BLOCKED" if blocked else "ADVISORY_BODY"},
1003
+ )
1004
+ return
1005
+ super().do_GET()
1006
+
1007
+ def do_POST(self) -> None: # noqa: N802
1008
+ path = urlsplit(self.path).path
1009
+ if path in ("/api/anatomy/v1/organs/integrity", "/api/organs/integrity"):
1010
+ if not _ORGAN_INTEGRITY:
1011
+ self._send_json(
1012
+ {"ok": False, "error": "organ-integrity kernel UNAVAILABLE"},
1013
+ status=503,
1014
+ evidence_state="UNAVAILABLE",
1015
+ )
1016
+ return
1017
+ try:
1018
+ length = int(self.headers.get("Content-Length", "0"))
1019
+ except ValueError:
1020
+ length = 0
1021
+ data: dict = {}
1022
+ if 0 < length <= 1_000_000:
1023
+ try:
1024
+ parsed = json.loads(self.rfile.read(length))
1025
+ if isinstance(parsed, dict):
1026
+ data = parsed
1027
+ except Exception:
1028
+ data = {}
1029
+ flags = _org_parse_flags(data)
1030
+ payload = _org_envelope(_evaluate_anatomy(**flags))
1031
+ ev = payload.get("body") if isinstance(payload, dict) else {}
1032
+ blocked = bool(ev.get("blocked")) if isinstance(ev, dict) else False
1033
+ self._send_json(
1034
+ payload,
1035
+ evidence_state="COMPUTED",
1036
+ extra_headers={"X-SZL-Organ-Verdict": "BLOCKED" if blocked else "ADVISORY_BODY"},
1037
+ )
1038
+ return
1039
+ if path != "/api/anatomy/v1/verify/receipt":
1040
+ self._send_json({"error": "not_found", "path": path}, status=404, evidence_state="UNAVAILABLE")
1041
+ return
1042
+ try:
1043
+ length = int(self.headers.get("Content-Length", "0"))
1044
+ except ValueError:
1045
+ length = 0
1046
+ if length <= 0 or length > 1_000_000:
1047
+ self._send_json(
1048
+ {"error": "invalid_body", "detail": "JSON body required; maximum 1,000,000 bytes."},
1049
+ status=400,
1050
+ evidence_state="UNAVAILABLE",
1051
+ )
1052
+ return
1053
+ try:
1054
+ candidate = json.loads(self.rfile.read(length))
1055
+ except Exception:
1056
+ self._send_json({"error": "invalid_json"}, status=400, evidence_state="UNAVAILABLE")
1057
+ return
1058
+ status, payload = _check_local_receipt(candidate)
1059
+ self._send_json(
1060
+ payload,
1061
+ status=status,
1062
+ evidence_state="COMPUTED",
1063
+ extra_headers={"X-SZL-Verification-State": str(payload["verification_state"])},
1064
+ )
1065
+
1066
+ def end_headers(self) -> None:
1067
+ self.send_header("Cross-Origin-Opener-Policy", "same-origin-allow-popups")
1068
+ self.send_header("Cross-Origin-Resource-Policy", "cross-origin")
1069
+ self.send_header("Content-Security-Policy", CONTENT_SECURITY_POLICY)
1070
+ self.send_header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
1071
+ self.send_header("X-Content-Type-Options", "nosniff")
1072
+ self.send_header("Referrer-Policy", "strict-origin-when-cross-origin")
1073
+ self.send_header("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=()")
1074
+ super().end_headers()
1075
+
1076
+
1077
+ def make_server(host: str = "0.0.0.0", port: int = PORT) -> ThreadingHTTPServer:
1078
+ handler = functools.partial(HardenedHandler, directory=str(DIRECTORY))
1079
+ return ThreadingHTTPServer((host, port), handler)
1080
+
1081
+
1082
+ if __name__ == "__main__":
1083
+ httpd = make_server()
1084
+ print(f"Serving SZL Living Anatomy from {DIRECTORY} on 0.0.0.0:{PORT}", flush=True)
1085
+ try:
1086
+ httpd.serve_forever()
1087
+ except KeyboardInterrupt:
1088
+ httpd.server_close()
style.css ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ body {
2
+ padding: 2rem;
3
+ font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;
4
+ }
5
+
6
+ h1 {
7
+ font-size: 16px;
8
+ margin-top: 0;
9
+ }
10
+
11
+ p {
12
+ color: rgb(107, 114, 128);
13
+ font-size: 15px;
14
+ margin-bottom: 10px;
15
+ margin-top: 5px;
16
+ }
17
+
18
+ .card {
19
+ max-width: 620px;
20
+ margin: 0 auto;
21
+ padding: 16px;
22
+ border: 1px solid lightgray;
23
+ border-radius: 16px;
24
+ }
25
+
26
+ .card p:last-child {
27
+ margin-bottom: 0;
28
+ }
szl-holo-v2.css ADDED
@@ -0,0 +1,720 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * A11oy Holo-Constellation v2.0.0
3
+ * SZL-original visual material and interaction system.
4
+ * No external assets, tracking, storage, network fetches, or copied design code.
5
+ * SPDX-License-Identifier: Apache-2.0
6
+ */
7
+
8
+ :root {
9
+ --szl-holo-bg: #050806;
10
+ --szl-holo-bg-deep: #020403;
11
+ --szl-holo-surface: #0c1513;
12
+ --szl-holo-surface-2: #14201d;
13
+ --szl-holo-ink: #f3fff8;
14
+ --szl-holo-muted: #9fb7ad;
15
+ --szl-holo-accent: #b8ff45;
16
+ --szl-holo-accent-2: #31e6d1;
17
+ --szl-holo-danger: #ff625b;
18
+ --szl-holo-warning: #e2bb6d;
19
+ --szl-holo-success: #76d8aa;
20
+ --szl-holo-line: color-mix(in srgb, var(--szl-holo-accent) 20%, transparent);
21
+ --szl-holo-line-soft: color-mix(in srgb, var(--szl-holo-ink) 10%, transparent);
22
+ --szl-holo-glow: color-mix(in srgb, var(--szl-holo-accent) 16%, transparent);
23
+ --szl-holo-glow-2: color-mix(in srgb, var(--szl-holo-accent-2) 12%, transparent);
24
+ --szl-holo-shadow: 0 24px 84px rgb(0 0 0 / 0.42);
25
+ --szl-holo-radius-sm: 10px;
26
+ --szl-holo-radius-md: 18px;
27
+ --szl-holo-radius-lg: 30px;
28
+ --szl-holo-radius-xl: 44px;
29
+ --szl-holo-space-1: clamp(.45rem, .35rem + .3vw, .7rem);
30
+ --szl-holo-space-2: clamp(.8rem, .65rem + .5vw, 1.2rem);
31
+ --szl-holo-space-3: clamp(1.2rem, .95rem + .8vw, 1.9rem);
32
+ --szl-holo-space-4: clamp(1.8rem, 1.25rem + 1.7vw, 3.4rem);
33
+ --szl-holo-space-5: clamp(2.8rem, 2rem + 3vw, 6rem);
34
+ --szl-holo-pointer-x: 50%;
35
+ --szl-holo-pointer-y: 22%;
36
+ --szl-holo-scroll: 0;
37
+ --szl-holo-tilt-x: 0deg;
38
+ --szl-holo-tilt-y: 0deg;
39
+ --szl-holo-rail-height: 58px;
40
+ --szl-holo-z-ambient: -2;
41
+ --szl-holo-z-rail: 2147483000;
42
+ color-scheme: dark;
43
+ accent-color: var(--szl-holo-accent);
44
+ }
45
+
46
+ html[data-szl-holo="v2"] {
47
+ min-height: 100%;
48
+ overflow-x: clip;
49
+ background: var(--szl-holo-bg-deep);
50
+ scrollbar-color: color-mix(in srgb, var(--szl-holo-accent) 42%, transparent) var(--szl-holo-bg-deep);
51
+ scroll-padding-top: calc(var(--szl-holo-rail-height) + 18px);
52
+ }
53
+
54
+ html[data-szl-holo="v2"] body {
55
+ min-height: 100%;
56
+ overflow-x: clip;
57
+ color: var(--szl-holo-ink);
58
+ background: transparent;
59
+ }
60
+
61
+ html[data-szl-holo="v2"] body::before {
62
+ position: fixed;
63
+ inset: 0;
64
+ z-index: calc(var(--szl-holo-z-ambient) - 1);
65
+ pointer-events: none;
66
+ content: "";
67
+ background:
68
+ radial-gradient(circle at var(--szl-holo-pointer-x) var(--szl-holo-pointer-y), var(--szl-holo-glow), transparent 24rem),
69
+ radial-gradient(circle at 90% 8%, var(--szl-holo-glow-2), transparent 30rem),
70
+ linear-gradient(158deg, var(--szl-holo-bg), color-mix(in srgb, var(--szl-holo-bg) 84%, var(--szl-holo-surface)) 58%, var(--szl-holo-bg-deep));
71
+ }
72
+
73
+ /* Lightweight optical texture. It is decorative and does not represent telemetry. */
74
+ html[data-szl-holo="v2"] body::after {
75
+ position: fixed;
76
+ inset: 0;
77
+ z-index: calc(var(--szl-holo-z-ambient) - 1);
78
+ pointer-events: none;
79
+ content: "";
80
+ opacity: .14;
81
+ background-image:
82
+ repeating-linear-gradient(0deg, transparent 0 3px, rgb(255 255 255 / .018) 4px),
83
+ repeating-linear-gradient(90deg, transparent 0 5px, rgb(255 255 255 / .012) 6px);
84
+ mix-blend-mode: soft-light;
85
+ }
86
+
87
+ #szl-holo-ambient {
88
+ position: fixed;
89
+ inset: 0;
90
+ z-index: var(--szl-holo-z-ambient);
91
+ overflow: hidden;
92
+ pointer-events: none;
93
+ contain: strict;
94
+ opacity: .82;
95
+ }
96
+
97
+ #szl-holo-ambient::before,
98
+ #szl-holo-ambient::after {
99
+ position: absolute;
100
+ inset: -18%;
101
+ content: "";
102
+ transform-origin: center;
103
+ will-change: transform;
104
+ }
105
+
106
+ /* Command constellation: orbital paths over a tactical field. */
107
+ html[data-szl-holo-motif="command-constellation"] #szl-holo-ambient::before {
108
+ background:
109
+ radial-gradient(circle at center, var(--szl-holo-accent) 0 1.5px, transparent 2.5px),
110
+ linear-gradient(var(--szl-holo-line) 1px, transparent 1px),
111
+ linear-gradient(90deg, var(--szl-holo-line) 1px, transparent 1px);
112
+ background-size: 112px 112px, 56px 56px, 56px 56px;
113
+ mask-image: radial-gradient(ellipse at 63% 29%, #000 0 18%, transparent 70%);
114
+ transform: perspective(720px) rotateX(58deg) translate3d(0, 22%, 0) scale(1.12);
115
+ }
116
+
117
+ html[data-szl-holo-motif="command-constellation"] #szl-holo-ambient::after {
118
+ inset: 4% -10% -28% 34%;
119
+ border: 1px solid var(--szl-holo-line);
120
+ border-radius: 50%;
121
+ background:
122
+ repeating-radial-gradient(ellipse, transparent 0 74px, var(--szl-holo-line) 75px 76px),
123
+ conic-gradient(from 218deg, transparent 0 72%, var(--szl-holo-glow) 74% 75.5%, transparent 77%);
124
+ transform: rotate(-9deg) scaleY(.58);
125
+ animation: szl-holo-orbit 38s linear infinite;
126
+ }
127
+
128
+ /* Observability: living signals and anomaly ribbons. */
129
+ html[data-szl-holo-motif="signal-aurora"] #szl-holo-ambient::before {
130
+ inset: -46% -15%;
131
+ border-radius: 50%;
132
+ background: conic-gradient(from 76deg, transparent, var(--szl-holo-glow), transparent 25%, color-mix(in srgb, var(--szl-holo-accent-2) 18%, transparent), transparent 62%);
133
+ filter: blur(44px) saturate(125%);
134
+ animation: szl-holo-aurora 22s ease-in-out infinite alternate;
135
+ }
136
+
137
+ html[data-szl-holo-motif="signal-aurora"] #szl-holo-ambient::after {
138
+ background:
139
+ repeating-linear-gradient(90deg, transparent 0 43px, var(--szl-holo-line) 44px, transparent 45px 82px),
140
+ linear-gradient(170deg, transparent 38%, var(--szl-holo-glow-2) 39% 40%, transparent 41% 58%, var(--szl-holo-glow) 59% 60%, transparent 61%);
141
+ mask-image: linear-gradient(transparent, #000 28% 78%, transparent 92%);
142
+ transform: skewY(-7deg) translateY(calc(var(--szl-holo-scroll) * -2px));
143
+ }
144
+
145
+ /* Maritime: bathymetry, route wake, and radar. */
146
+ html[data-szl-holo-motif="bathymetric-radar"] #szl-holo-ambient::before {
147
+ inset: 5% auto auto 52%;
148
+ width: min(78vw, 980px);
149
+ aspect-ratio: 1;
150
+ border: 1px solid var(--szl-holo-line);
151
+ border-radius: 50%;
152
+ background:
153
+ repeating-radial-gradient(circle, transparent 0 59px, var(--szl-holo-line) 60px 61px),
154
+ conic-gradient(from 12deg, color-mix(in srgb, var(--szl-holo-accent) 22%, transparent), transparent 16%);
155
+ animation: szl-holo-radar 18s linear infinite;
156
+ }
157
+
158
+ html[data-szl-holo-motif="bathymetric-radar"] #szl-holo-ambient::after {
159
+ background: repeating-radial-gradient(ellipse at 18% 82%, transparent 0 30px, var(--szl-holo-line) 31px 32px);
160
+ transform: rotate(-8deg) scale(1.28);
161
+ opacity: .34;
162
+ }
163
+
164
+ /* Real estate: topography and parcel geometry. */
165
+ html[data-szl-holo-motif="topographic-parcels"] #szl-holo-ambient::before {
166
+ background:
167
+ repeating-radial-gradient(ellipse at 18% 58%, transparent 0 31px, var(--szl-holo-line) 32px 33px),
168
+ repeating-radial-gradient(ellipse at 84% 34%, transparent 0 49px, color-mix(in srgb, var(--szl-holo-accent-2) 18%, transparent) 50px 51px);
169
+ transform: rotate(-7deg) scale(1.18) translateY(calc(var(--szl-holo-scroll) * -1px));
170
+ }
171
+
172
+ html[data-szl-holo-motif="topographic-parcels"] #szl-holo-ambient::after {
173
+ background-image:
174
+ linear-gradient(28deg, transparent 48%, var(--szl-holo-line) 49% 50%, transparent 51%),
175
+ linear-gradient(118deg, transparent 48%, var(--szl-holo-line) 49% 50%, transparent 51%);
176
+ background-size: 180px 110px;
177
+ opacity: .26;
178
+ }
179
+
180
+ /* Security: threat lattice and shield lock. */
181
+ html[data-szl-holo-motif="threat-lattice"] #szl-holo-ambient::before {
182
+ background:
183
+ linear-gradient(32deg, transparent 47%, var(--szl-holo-line) 48% 49%, transparent 50%),
184
+ linear-gradient(148deg, transparent 47%, color-mix(in srgb, var(--szl-holo-accent-2) 18%, transparent) 48% 49%, transparent 50%);
185
+ background-size: 84px 84px;
186
+ transform: skewX(-8deg) scale(1.12);
187
+ mask-image: radial-gradient(circle at 72% 28%, #000, transparent 62%);
188
+ }
189
+
190
+ html[data-szl-holo-motif="threat-lattice"] #szl-holo-ambient::after {
191
+ inset: 16% 6% auto auto;
192
+ width: clamp(150px, 22vw, 320px);
193
+ aspect-ratio: 1;
194
+ border: 1px solid var(--szl-holo-accent);
195
+ clip-path: polygon(50% 0, 93% 25%, 93% 75%, 50% 100%, 7% 75%, 7% 25%);
196
+ box-shadow: inset 0 0 70px var(--szl-holo-glow), 0 0 90px var(--szl-holo-glow);
197
+ opacity: .34;
198
+ animation: szl-holo-breathe 4.8s ease-in-out infinite alternate;
199
+ }
200
+
201
+ /* Legal: case facets and deadline lanes. */
202
+ html[data-szl-holo-motif="case-facets"] #szl-holo-ambient::before {
203
+ background:
204
+ repeating-linear-gradient(0deg, transparent 0 51px, var(--szl-holo-line) 52px),
205
+ repeating-linear-gradient(90deg, transparent 0 219px, color-mix(in srgb, var(--szl-holo-accent-2) 17%, transparent) 220px 221px);
206
+ transform: rotate(-2deg);
207
+ mask-image: linear-gradient(90deg, transparent 2%, #000 20% 91%, transparent);
208
+ }
209
+
210
+ html[data-szl-holo-motif="case-facets"] #szl-holo-ambient::after {
211
+ background-image: radial-gradient(circle, var(--szl-holo-accent) 0 3px, transparent 4px);
212
+ background-size: 220px 52px;
213
+ opacity: .22;
214
+ }
215
+
216
+ /* Advisory: editorial orbits. */
217
+ html[data-szl-holo-motif="editorial-orbit"] #szl-holo-ambient::before {
218
+ inset: -20% auto auto 44%;
219
+ width: min(82vw, 1040px);
220
+ aspect-ratio: 1;
221
+ border-radius: 50%;
222
+ background: repeating-radial-gradient(circle, transparent 0 74px, var(--szl-holo-line) 75px 76px);
223
+ transform: rotate(12deg) scaleY(.55);
224
+ }
225
+
226
+ html[data-szl-holo-motif="editorial-orbit"] #szl-holo-ambient::after {
227
+ background: linear-gradient(115deg, transparent 38%, var(--szl-holo-glow) 39% 41%, transparent 42% 62%, var(--szl-holo-glow-2) 63% 64%, transparent 65%);
228
+ }
229
+
230
+ /* Integration: connected node field. */
231
+ html[data-szl-holo-motif="connection-field"] #szl-holo-ambient::before {
232
+ background:
233
+ radial-gradient(circle, var(--szl-holo-accent) 0 2px, transparent 3px),
234
+ linear-gradient(30deg, transparent 49%, var(--szl-holo-line) 50%, transparent 51%),
235
+ linear-gradient(150deg, transparent 49%, var(--szl-holo-line) 50%, transparent 51%);
236
+ background-size: 96px 96px;
237
+ mask-image: radial-gradient(circle at 55% 40%, #000, transparent 72%);
238
+ transform: translate3d(calc(var(--szl-holo-scroll) * .4px), calc(var(--szl-holo-scroll) * -.25px), 0);
239
+ }
240
+
241
+ /* Factory: build lanes and artifact promotion. */
242
+ html[data-szl-holo-motif="assembly-circuit"] #szl-holo-ambient::before {
243
+ background:
244
+ radial-gradient(circle, var(--szl-holo-accent) 0 2px, transparent 3px),
245
+ linear-gradient(90deg, var(--szl-holo-line) 1px, transparent 1px),
246
+ linear-gradient(var(--szl-holo-line) 1px, transparent 1px);
247
+ background-size: 72px 72px;
248
+ clip-path: polygon(0 8%, 76% 8%, 76% 28%, 100% 28%, 100% 92%, 22% 92%, 22% 69%, 0 69%);
249
+ opacity: .42;
250
+ }
251
+
252
+ html[data-szl-holo-motif="assembly-circuit"] #szl-holo-ambient::after {
253
+ inset: 30% 12% auto auto;
254
+ width: clamp(180px, 22vw, 360px);
255
+ height: clamp(100px, 13vw, 210px);
256
+ border: 1px solid var(--szl-holo-line);
257
+ border-radius: var(--szl-holo-radius-lg);
258
+ box-shadow: inset 0 0 55px var(--szl-holo-glow), 0 0 55px var(--szl-holo-glow);
259
+ }
260
+
261
+ /* Research: recursive computational rings. */
262
+ html[data-szl-holo-motif="recursive-ring"] #szl-holo-ambient::before {
263
+ inset: -24% -12%;
264
+ border-radius: 50%;
265
+ background: repeating-conic-gradient(from 0deg, var(--szl-holo-line) 0 1deg, transparent 1deg 13deg);
266
+ mask-image: repeating-radial-gradient(circle, #000 0 1px, transparent 2px 54px);
267
+ animation: szl-holo-recurse 42s linear infinite;
268
+ }
269
+
270
+ html[data-szl-holo-motif="recursive-ring"] #szl-holo-ambient::after {
271
+ inset: 18% auto auto 58%;
272
+ width: min(38vw, 460px);
273
+ aspect-ratio: 1;
274
+ border: 1px solid var(--szl-holo-accent);
275
+ border-radius: 50%;
276
+ box-shadow: inset 0 0 90px var(--szl-holo-glow), 0 0 90px var(--szl-holo-glow);
277
+ opacity: .38;
278
+ }
279
+
280
+ /* KHIPU: woven evidence traces. */
281
+ html[data-szl-holo-motif="woven-proof"] #szl-holo-ambient::before {
282
+ background:
283
+ repeating-linear-gradient(28deg, transparent 0 25px, var(--szl-holo-line) 26px 27px),
284
+ repeating-linear-gradient(-28deg, transparent 0 31px, var(--szl-holo-glow-2) 32px 33px);
285
+ transform: scale(1.08);
286
+ }
287
+
288
+ html[data-szl-holo-motif="woven-proof"] #szl-holo-ambient::after {
289
+ background-image: radial-gradient(circle, var(--szl-holo-accent) 0 2px, transparent 3px);
290
+ background-size: 128px 96px;
291
+ opacity: .23;
292
+ }
293
+
294
+ /* Agents: governed swarm converging on a decision. */
295
+ html[data-szl-holo-motif="agent-swarm"] #szl-holo-ambient::before {
296
+ background-image:
297
+ radial-gradient(circle at center, var(--szl-holo-accent) 0 2px, transparent 3px),
298
+ radial-gradient(circle at center, var(--szl-holo-accent-2) 0 1px, transparent 2px);
299
+ background-position: 0 0, 31px 27px;
300
+ background-size: 72px 68px, 89px 83px;
301
+ mask-image: radial-gradient(circle at 60% 42%, #000, transparent 68%);
302
+ animation: szl-holo-swarm 24s ease-in-out infinite alternate;
303
+ }
304
+
305
+ html[data-szl-holo-motif="agent-swarm"] #szl-holo-ambient::after {
306
+ background:
307
+ linear-gradient(25deg, transparent 49.6%, var(--szl-holo-line) 50%, transparent 50.4%),
308
+ linear-gradient(155deg, transparent 49.6%, var(--szl-holo-line) 50%, transparent 50.4%);
309
+ background-size: 140px 90px;
310
+ opacity: .2;
311
+ }
312
+
313
+ /* Proof: restrained evidence-vault geometry. */
314
+ html[data-szl-holo-motif="evidence-vault"] #szl-holo-ambient::before {
315
+ background:
316
+ repeating-linear-gradient(0deg, transparent 0 35px, var(--szl-holo-line-soft) 36px),
317
+ linear-gradient(90deg, transparent 0 13%, var(--szl-holo-line) 13.1%, transparent 13.3% 76%, var(--szl-holo-line) 76.1%, transparent 76.3%);
318
+ mask-image: linear-gradient(90deg, transparent, #000 14% 86%, transparent);
319
+ }
320
+
321
+ html[data-szl-holo-motif="evidence-vault"] #szl-holo-ambient::after {
322
+ background-image: radial-gradient(circle, var(--szl-holo-accent) 0 2px, transparent 3px);
323
+ background-size: 144px 72px;
324
+ opacity: .18;
325
+ }
326
+
327
+ /* Shared top rail. */
328
+ .szl-holo-rail {
329
+ position: sticky;
330
+ top: 0;
331
+ z-index: var(--szl-holo-z-rail);
332
+ min-height: var(--szl-holo-rail-height);
333
+ display: grid;
334
+ grid-template-columns: minmax(0, 1fr) auto;
335
+ align-items: center;
336
+ gap: var(--szl-holo-space-2);
337
+ padding: 8px max(12px, env(safe-area-inset-left)) 8px max(12px, env(safe-area-inset-right));
338
+ border-bottom: 1px solid var(--szl-holo-line);
339
+ color: var(--szl-holo-ink);
340
+ background: color-mix(in srgb, var(--szl-holo-bg) 86%, transparent);
341
+ box-shadow: 0 14px 44px rgb(0 0 0 / .24);
342
+ backdrop-filter: blur(20px) saturate(135%);
343
+ -webkit-backdrop-filter: blur(20px) saturate(135%);
344
+ font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
345
+ }
346
+
347
+ .szl-holo-rail *,
348
+ .szl-holo-rail *::before,
349
+ .szl-holo-rail *::after { box-sizing: border-box; }
350
+
351
+ .szl-holo-identity {
352
+ min-width: 0;
353
+ min-height: 44px;
354
+ display: inline-flex;
355
+ align-items: center;
356
+ gap: 11px;
357
+ color: inherit;
358
+ text-decoration: none;
359
+ }
360
+
361
+ .szl-holo-mark {
362
+ position: relative;
363
+ width: 28px;
364
+ height: 28px;
365
+ flex: 0 0 auto;
366
+ border: 1px solid color-mix(in srgb, var(--szl-holo-accent) 62%, white 10%);
367
+ border-radius: 9px;
368
+ background:
369
+ radial-gradient(circle at 26% 24%, var(--szl-holo-accent), transparent 34%),
370
+ linear-gradient(145deg, color-mix(in srgb, var(--szl-holo-accent-2) 72%, transparent), transparent 72%);
371
+ box-shadow: 0 0 28px var(--szl-holo-glow);
372
+ transform: rotate(8deg);
373
+ }
374
+
375
+ .szl-holo-mark::after {
376
+ position: absolute;
377
+ inset: 5px;
378
+ border: 1px solid color-mix(in srgb, var(--szl-holo-ink) 36%, transparent);
379
+ border-radius: 5px;
380
+ content: "";
381
+ transform: rotate(-18deg);
382
+ }
383
+
384
+ .szl-holo-copy {
385
+ min-width: 0;
386
+ display: grid;
387
+ gap: 1px;
388
+ }
389
+
390
+ .szl-holo-eyebrow {
391
+ overflow: hidden;
392
+ color: var(--szl-holo-muted);
393
+ font-size: 9px;
394
+ font-weight: 700;
395
+ letter-spacing: .19em;
396
+ text-overflow: ellipsis;
397
+ text-transform: uppercase;
398
+ white-space: nowrap;
399
+ }
400
+
401
+ .szl-holo-label {
402
+ overflow: hidden;
403
+ font-size: 13px;
404
+ font-weight: 760;
405
+ letter-spacing: -.01em;
406
+ text-overflow: ellipsis;
407
+ white-space: nowrap;
408
+ }
409
+
410
+ .szl-holo-nav {
411
+ display: flex;
412
+ align-items: center;
413
+ gap: 4px;
414
+ }
415
+
416
+ .szl-holo-link,
417
+ .szl-holo-menu {
418
+ min-width: 44px;
419
+ min-height: 44px;
420
+ display: inline-flex;
421
+ align-items: center;
422
+ justify-content: center;
423
+ padding: 8px 11px;
424
+ border: 1px solid transparent;
425
+ border-radius: 999px;
426
+ color: var(--szl-holo-muted);
427
+ background: transparent;
428
+ font: 660 11px/1.2 Inter, ui-sans-serif, system-ui, sans-serif;
429
+ letter-spacing: .045em;
430
+ text-decoration: none;
431
+ cursor: pointer;
432
+ touch-action: manipulation;
433
+ -webkit-tap-highlight-color: transparent;
434
+ }
435
+
436
+ .szl-holo-link:hover,
437
+ .szl-holo-link:focus-visible,
438
+ .szl-holo-link[aria-current="page"],
439
+ .szl-holo-menu:hover,
440
+ .szl-holo-menu:focus-visible {
441
+ border-color: color-mix(in srgb, var(--szl-holo-accent) 38%, transparent);
442
+ color: var(--szl-holo-ink);
443
+ background: color-mix(in srgb, var(--szl-holo-accent) 9%, transparent);
444
+ outline: none;
445
+ }
446
+
447
+ .szl-holo-menu { display: none; }
448
+
449
+ /* Reusable opt-in materials. */
450
+ .szl-holo-panel,
451
+ [data-szl-holo-panel] {
452
+ position: relative;
453
+ overflow: hidden;
454
+ border: 1px solid var(--szl-holo-line-soft);
455
+ border-radius: var(--szl-holo-radius-md);
456
+ background:
457
+ linear-gradient(145deg, color-mix(in srgb, var(--szl-holo-surface-2) 60%, transparent), transparent 44%),
458
+ color-mix(in srgb, var(--szl-holo-surface) 86%, transparent);
459
+ box-shadow: var(--szl-holo-shadow);
460
+ backdrop-filter: blur(18px) saturate(125%);
461
+ -webkit-backdrop-filter: blur(18px) saturate(125%);
462
+ transform-style: preserve-3d;
463
+ }
464
+
465
+ .szl-holo-panel::before,
466
+ [data-szl-holo-panel]::before {
467
+ position: absolute;
468
+ inset: 0;
469
+ pointer-events: none;
470
+ content: "";
471
+ background: radial-gradient(circle at var(--szl-holo-pointer-x) var(--szl-holo-pointer-y), color-mix(in srgb, var(--szl-holo-accent) 13%, transparent), transparent 22rem);
472
+ opacity: .65;
473
+ }
474
+
475
+ .szl-holo-panel::after,
476
+ [data-szl-holo-panel]::after {
477
+ position: absolute;
478
+ inset: -1px;
479
+ pointer-events: none;
480
+ content: "";
481
+ border-radius: inherit;
482
+ background: linear-gradient(118deg, transparent 12%, color-mix(in srgb, var(--szl-holo-ink) 9%, transparent) 38%, transparent 62%);
483
+ transform: translateX(-110%);
484
+ animation: szl-holo-specular 11s ease-in-out infinite;
485
+ }
486
+
487
+ .szl-holo-kicker,
488
+ [data-szl-holo-kicker] {
489
+ color: var(--szl-holo-accent);
490
+ font-size: .72rem;
491
+ font-weight: 780;
492
+ letter-spacing: .18em;
493
+ text-transform: uppercase;
494
+ }
495
+
496
+ .szl-holo-title,
497
+ [data-szl-holo-title] {
498
+ color: var(--szl-holo-ink);
499
+ background: linear-gradient(112deg, var(--szl-holo-ink), var(--szl-holo-accent) 58%, var(--szl-holo-accent-2));
500
+ background-clip: text;
501
+ -webkit-background-clip: text;
502
+ -webkit-text-fill-color: transparent;
503
+ text-wrap: balance;
504
+ }
505
+
506
+ .szl-holo-muted { color: var(--szl-holo-muted); }
507
+ .szl-holo-rule { border-color: var(--szl-holo-line); }
508
+
509
+ .szl-holo-chip {
510
+ min-height: 32px;
511
+ display: inline-flex;
512
+ align-items: center;
513
+ gap: 7px;
514
+ padding: 5px 10px;
515
+ border: 1px solid var(--szl-holo-line-soft);
516
+ border-radius: 999px;
517
+ color: var(--szl-holo-muted);
518
+ background: color-mix(in srgb, var(--szl-holo-surface) 78%, transparent);
519
+ font: 650 11px/1.2 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
520
+ }
521
+
522
+ .szl-holo-chip::before {
523
+ width: 7px;
524
+ height: 7px;
525
+ border-radius: 50%;
526
+ background: var(--szl-holo-accent);
527
+ box-shadow: 0 0 14px var(--szl-holo-accent);
528
+ content: "";
529
+ }
530
+
531
+ .szl-holo-evidence-ribbon {
532
+ display: grid;
533
+ grid-template-columns: auto minmax(0, 1fr) auto;
534
+ align-items: center;
535
+ gap: var(--szl-holo-space-2);
536
+ padding: 10px 12px;
537
+ border-block: 1px solid var(--szl-holo-line-soft);
538
+ color: var(--szl-holo-muted);
539
+ font: 600 11px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
540
+ }
541
+
542
+ .szl-holo-evidence-ribbon strong { color: var(--szl-holo-ink); }
543
+
544
+ .szl-holo-progress {
545
+ position: fixed;
546
+ inset: 0 auto auto 0;
547
+ z-index: calc(var(--szl-holo-z-rail) + 1);
548
+ width: calc(var(--szl-holo-scroll) * 1%);
549
+ height: 2px;
550
+ pointer-events: none;
551
+ background: linear-gradient(90deg, var(--szl-holo-accent), var(--szl-holo-accent-2));
552
+ box-shadow: 0 0 18px var(--szl-holo-glow);
553
+ }
554
+
555
+ .szl-holo-skip {
556
+ position: fixed;
557
+ top: 8px;
558
+ left: 8px;
559
+ z-index: calc(var(--szl-holo-z-rail) + 3);
560
+ padding: 11px 14px;
561
+ border: 2px solid var(--szl-holo-accent);
562
+ border-radius: var(--szl-holo-radius-sm);
563
+ color: var(--szl-holo-bg);
564
+ background: var(--szl-holo-accent);
565
+ font: 760 14px/1.2 ui-sans-serif, system-ui, sans-serif;
566
+ text-decoration: none;
567
+ transform: translateY(-160%);
568
+ transition: transform .16s ease;
569
+ }
570
+
571
+ .szl-holo-skip:focus { transform: translateY(0); }
572
+
573
+ html[data-szl-holo="v2"] :where(a, button, input, textarea, select, summary, [tabindex]):focus-visible {
574
+ outline: 2px solid var(--szl-holo-accent) !important;
575
+ outline-offset: 3px !important;
576
+ }
577
+
578
+ @keyframes szl-holo-orbit {
579
+ to { transform: rotate(351deg) scaleY(.58); }
580
+ }
581
+
582
+ @keyframes szl-holo-aurora {
583
+ from { transform: translate3d(-5%, -3%, 0) rotate(-8deg) scale(1); }
584
+ to { transform: translate3d(7%, 6%, 0) rotate(11deg) scale(1.08); }
585
+ }
586
+
587
+ @keyframes szl-holo-radar {
588
+ to { transform: rotate(360deg); }
589
+ }
590
+
591
+ @keyframes szl-holo-recurse {
592
+ to { transform: rotate(-360deg); }
593
+ }
594
+
595
+ @keyframes szl-holo-swarm {
596
+ from { transform: translate3d(-1.5%, -1%, 0) scale(1); }
597
+ to { transform: translate3d(1.5%, 1%, 0) scale(1.04); }
598
+ }
599
+
600
+ @keyframes szl-holo-breathe {
601
+ from { opacity: .22; transform: scale(.96); }
602
+ to { opacity: .42; transform: scale(1.03); }
603
+ }
604
+
605
+ @keyframes szl-holo-specular {
606
+ 0%, 68%, 100% { transform: translateX(-115%); }
607
+ 82% { transform: translateX(115%); }
608
+ }
609
+
610
+ @media (max-width: 760px) {
611
+ :root { --szl-holo-rail-height: 56px; }
612
+ #szl-holo-ambient { opacity: .62; }
613
+ .szl-holo-menu { display: inline-flex; }
614
+ .szl-holo-nav {
615
+ position: absolute;
616
+ top: calc(100% + 7px);
617
+ right: max(8px, env(safe-area-inset-right));
618
+ min-width: min(240px, calc(100vw - 16px));
619
+ display: none;
620
+ flex-direction: column;
621
+ align-items: stretch;
622
+ gap: 3px;
623
+ padding: 8px;
624
+ border: 1px solid var(--szl-holo-line);
625
+ border-radius: var(--szl-holo-radius-md);
626
+ background: color-mix(in srgb, var(--szl-holo-bg) 96%, white 2%);
627
+ box-shadow: var(--szl-holo-shadow);
628
+ }
629
+ .szl-holo-nav[data-open="true"] { display: flex; }
630
+ .szl-holo-link { justify-content: flex-start; padding-inline: 14px; }
631
+ .szl-holo-eyebrow { display: none; }
632
+ .szl-holo-panel::after,
633
+ [data-szl-holo-panel]::after { display: none; }
634
+ }
635
+
636
+ @media (max-width: 390px) {
637
+ .szl-holo-label { max-width: 48vw; }
638
+ .szl-holo-mark { width: 25px; height: 25px; }
639
+ }
640
+
641
+ @media (prefers-reduced-motion: reduce) {
642
+ html[data-szl-holo="v2"] { scroll-behavior: auto; }
643
+ #szl-holo-ambient::before,
644
+ #szl-holo-ambient::after,
645
+ .szl-holo-panel::after,
646
+ [data-szl-holo-panel]::after,
647
+ .szl-holo-skip,
648
+ .szl-holo-mark {
649
+ animation: none !important;
650
+ transition: none !important;
651
+ transform: none !important;
652
+ }
653
+ .szl-holo-progress { box-shadow: none; }
654
+ }
655
+
656
+ @media (prefers-contrast: more) {
657
+ :root {
658
+ --szl-holo-line: color-mix(in srgb, var(--szl-holo-accent) 58%, transparent);
659
+ --szl-holo-line-soft: color-mix(in srgb, var(--szl-holo-ink) 34%, transparent);
660
+ }
661
+ #szl-holo-ambient { opacity: .32; }
662
+ .szl-holo-panel,
663
+ [data-szl-holo-panel] {
664
+ border-width: 2px;
665
+ background: var(--szl-holo-surface);
666
+ backdrop-filter: none;
667
+ }
668
+ }
669
+
670
+ @media (forced-colors: active) {
671
+ :root { color-scheme: light dark; }
672
+ #szl-holo-ambient,
673
+ .szl-holo-progress { display: none; }
674
+ .szl-holo-rail,
675
+ .szl-holo-panel,
676
+ [data-szl-holo-panel],
677
+ .szl-holo-link,
678
+ .szl-holo-menu,
679
+ .szl-holo-chip {
680
+ border: 1px solid CanvasText;
681
+ color: CanvasText;
682
+ background: Canvas;
683
+ box-shadow: none;
684
+ backdrop-filter: none;
685
+ }
686
+ .szl-holo-title,
687
+ [data-szl-holo-title] {
688
+ color: CanvasText;
689
+ background: none;
690
+ -webkit-text-fill-color: currentColor;
691
+ }
692
+ .szl-holo-mark { border-color: CanvasText; background: CanvasText; box-shadow: none; }
693
+ .szl-holo-skip { color: Canvas; background: CanvasText; border-color: CanvasText; }
694
+ }
695
+
696
+ @supports not (color: color-mix(in srgb, black 50%, white)) {
697
+ .szl-holo-rail,
698
+ .szl-holo-panel,
699
+ [data-szl-holo-panel] { background: var(--szl-holo-surface); }
700
+ .szl-holo-link[aria-current="page"] { border-color: var(--szl-holo-accent); }
701
+ }
702
+
703
+ @media print {
704
+ #szl-holo-ambient,
705
+ .szl-holo-rail,
706
+ .szl-holo-progress,
707
+ .szl-holo-skip { display: none !important; }
708
+ html[data-szl-holo="v2"],
709
+ html[data-szl-holo="v2"] body {
710
+ color: #000 !important;
711
+ background: #fff !important;
712
+ }
713
+ .szl-holo-panel,
714
+ [data-szl-holo-panel] {
715
+ border: 1px solid #444;
716
+ color: #000;
717
+ background: #fff;
718
+ box-shadow: none;
719
+ }
720
+ }
szl-holo-v2.js ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * A11oy Holo-Constellation v2.0.0
3
+ * Deterministic route identity, accessible estate navigation, and low-cost
4
+ * progressive visual enhancement. No fetch, tracking, storage, or cookies.
5
+ * SPDX-License-Identifier: Apache-2.0
6
+ */
7
+ (() => {
8
+ "use strict";
9
+
10
+ if (window.__SZL_HOLO_V2__) return;
11
+ window.__SZL_HOLO_V2__ = true;
12
+
13
+ const VERSION = "2.0.0";
14
+ const PRODUCT = "https://a-11-oy.com";
15
+ const PROOF = "https://a11oy.net";
16
+ const REDUCE_MOTION = window.matchMedia("(prefers-reduced-motion: reduce)");
17
+ const FINE_POINTER = window.matchMedia("(pointer: fine)");
18
+ const SAVE_DATA = Boolean(navigator.connection && navigator.connection.saveData);
19
+
20
+ const PALETTES = [
21
+ ["#07131a", "#102633", "#f2fbff", "#9ab4c2", "#64dcff", "#a88bff"],
22
+ ["#130a10", "#291522", "#fff6fb", "#c2a2b3", "#ff7bc3", "#ffb56b"],
23
+ ["#07140d", "#12281a", "#f5fff7", "#9db8a4", "#72efa0", "#5ad6ff"],
24
+ ["#130e06", "#2a1d0e", "#fffaf0", "#c2b297", "#ffc66d", "#ff7d73"],
25
+ ["#090a18", "#171932", "#f6f6ff", "#a6a8c4", "#878cff", "#54e4d7"],
26
+ ["#0f0715", "#24102f", "#fff6ff", "#bca6c5", "#d88cff", "#74c6ff"],
27
+ ["#061315", "#10272b", "#f1feff", "#9bb9bb", "#50e3d4", "#b4ed70"],
28
+ ["#140808", "#2d1414", "#fff6f4", "#c2a3a0", "#ff6c63", "#e9cf6f"],
29
+ ["#0a1115", "#16242c", "#f5fbff", "#a3b2bb", "#83c7ff", "#8df0bd"],
30
+ ["#111006", "#282512", "#fffef0", "#beb99b", "#e5f36b", "#e8a85f"],
31
+ ["#0b0714", "#1c122c", "#faf6ff", "#aea2c0", "#b697ff", "#ff82ad"],
32
+ ["#07120f", "#12251f", "#f2fff9", "#9db6aa", "#75e8b4", "#c1a0ff"],
33
+ ];
34
+
35
+ const CURATED = {
36
+ a11oy: {
37
+ label: "A11oy Command",
38
+ motif: "command-constellation",
39
+ palette: ["#050806", "#0c1513", "#f3fff8", "#9fb7ad", "#b8ff45", "#31e6d1"],
40
+ },
41
+ proof: {
42
+ label: "A11oy Proof Network",
43
+ motif: "evidence-vault",
44
+ palette: ["#060a10", "#101722", "#f1f5f8", "#9eabb6", "#76d8aa", "#e2bb6d"],
45
+ },
46
+ lyte: {
47
+ label: "Lyte",
48
+ motif: "signal-aurora",
49
+ palette: ["#03100f", "#0a211d", "#effffb", "#92bdb2", "#50ffd0", "#78a8ff"],
50
+ },
51
+ vessels: {
52
+ label: "Vessels",
53
+ motif: "bathymetric-radar",
54
+ palette: ["#020d18", "#09243a", "#effbff", "#8cb5c9", "#50ddff", "#2d7cff"],
55
+ },
56
+ terra: {
57
+ label: "Terra",
58
+ motif: "topographic-parcels",
59
+ palette: ["#06110b", "#12271a", "#f5fff7", "#9db7a3", "#7bea98", "#d9a45c"],
60
+ },
61
+ aegis: {
62
+ label: "Aegis",
63
+ motif: "threat-lattice",
64
+ palette: ["#120606", "#281010", "#fff4f2", "#c6a19c", "#ff625b", "#ffb34d"],
65
+ },
66
+ "prism-counsel": {
67
+ label: "PRISM Counsel",
68
+ motif: "case-facets",
69
+ palette: ["#070b18", "#141a31", "#f8f9ff", "#a8b0ca", "#7da8ff", "#d7c4ff"],
70
+ },
71
+ "carlota-jo": {
72
+ label: "Carlota Jo",
73
+ motif: "editorial-orbit",
74
+ palette: ["#140a17", "#2b1330", "#fff7ff", "#c6a8c7", "#e2a8ff", "#ef9b67"],
75
+ },
76
+ nexus: {
77
+ label: "Nexus",
78
+ motif: "connection-field",
79
+ palette: ["#070918", "#151831", "#f7f7ff", "#a5aac8", "#9a8cff", "#53e9ff"],
80
+ },
81
+ factory: {
82
+ label: "A11oy Factory",
83
+ motif: "assembly-circuit",
84
+ palette: ["#070c07", "#171f13", "#fafff5", "#abb9a4", "#c9ff5c", "#7e9cff"],
85
+ },
86
+ ouroboros: {
87
+ label: "Ouroboros",
88
+ motif: "recursive-ring",
89
+ palette: ["#100b05", "#24180b", "#fffaf0", "#c4b59b", "#ffd36e", "#c094ff"],
90
+ },
91
+ khipu: {
92
+ label: "KHIPU",
93
+ motif: "woven-proof",
94
+ palette: ["#120b05", "#271a0e", "#fff9ee", "#c6b39b", "#e9c66e", "#c87945"],
95
+ },
96
+ killinchu: {
97
+ label: "Killinchu",
98
+ motif: "agent-swarm",
99
+ palette: ["#100615", "#26102e", "#fff5ff", "#c5a4c9", "#ff74d4", "#68e8ff"],
100
+ },
101
+ };
102
+
103
+ const ROUTE_HINTS = [
104
+ ["prism-counsel", ["prism-counsel", "prism counsel", "/counsel", "/legal"]],
105
+ ["carlota-jo", ["carlota-jo", "carlota jo", "/advisory"]],
106
+ ["ouroboros", ["ouroboros", "/research", "/thesis"]],
107
+ ["killinchu", ["killinchu", "/agents", "agent forge", "agent swarm"]],
108
+ ["factory", ["a11oy-factory", "szl-factory", "/factory", "/forge", "artifact factory"]],
109
+ ["vessels", ["vessels", "/maritime", "fleet command", "voyage"]],
110
+ ["terra", ["terra", "/real-estate", "real estate", "parcel"]],
111
+ ["aegis", ["aegis", "/security", "/defense", "threat"]],
112
+ ["lyte", ["lyte", "/observability", "business observability", "signal"]],
113
+ ["nexus", ["nexus", "/integration", "connection fabric"]],
114
+ ["khipu", ["khipu", "/kernel", "woven proof"]],
115
+ ];
116
+
117
+ const MOTIFS = [
118
+ "command-constellation",
119
+ "signal-aurora",
120
+ "bathymetric-radar",
121
+ "topographic-parcels",
122
+ "threat-lattice",
123
+ "case-facets",
124
+ "editorial-orbit",
125
+ "connection-field",
126
+ "assembly-circuit",
127
+ "recursive-ring",
128
+ "woven-proof",
129
+ "agent-swarm",
130
+ ];
131
+
132
+ const LINKS = [
133
+ ["Command", `${PRODUCT}/`],
134
+ ["Products", `${PRODUCT}/console`],
135
+ ["Proof", `${PROOF}/record/`],
136
+ ["Source", "https://github.com/szl-holdings"],
137
+ ["Spaces", "https://huggingface.co/SZLHOLDINGS"],
138
+ ];
139
+
140
+ function slug(value) {
141
+ return String(value || "")
142
+ .normalize("NFKD")
143
+ .toLowerCase()
144
+ .replace(/[^a-z0-9]+/g, "-")
145
+ .replace(/^-+|-+$/g, "")
146
+ .slice(0, 96);
147
+ }
148
+
149
+ function fnv1a(value) {
150
+ let result = 0x811c9dc5;
151
+ for (const character of String(value || "a11oy")) {
152
+ result ^= character.charCodeAt(0);
153
+ result = Math.imul(result, 0x01000193) >>> 0;
154
+ }
155
+ return result >>> 0;
156
+ }
157
+
158
+ function titleCase(value) {
159
+ return String(value || "")
160
+ .split("-")
161
+ .filter(Boolean)
162
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
163
+ .join(" ");
164
+ }
165
+
166
+ function huggingFaceSlug(host) {
167
+ const match = host.match(/^(?:szlholdings|szl-holdings)-(.+)\.hf\.space$/i);
168
+ return match ? slug(match[1]) : "";
169
+ }
170
+
171
+ function surfaceCandidate() {
172
+ const host = location.hostname.toLowerCase();
173
+ if (host === "a11oy.net" || host === "www.a11oy.net") return "proof";
174
+ if (host === "a-11-oy.com" || host === "www.a-11-oy.com") {
175
+ const path = location.pathname.toLowerCase();
176
+ for (const [surface, hints] of ROUTE_HINTS) {
177
+ if (hints.some((hint) => path.includes(hint.replace(" ", "-")))) return surface;
178
+ }
179
+ return "a11oy";
180
+ }
181
+
182
+ const hf = huggingFaceSlug(host);
183
+ const path = location.pathname.toLowerCase();
184
+ const title = document.title.toLowerCase();
185
+ const bodyIdentity = `${document.body?.id || ""} ${document.body?.className || ""}`.toLowerCase();
186
+ const haystack = `${host} ${hf} ${path} ${title} ${bodyIdentity}`;
187
+
188
+ for (const [surface, hints] of ROUTE_HINTS) {
189
+ if (hints.some((hint) => haystack.includes(hint))) return surface;
190
+ }
191
+ if (hf) return hf;
192
+ return slug(path.split("/").filter(Boolean)[0]) || slug(host) || "a11oy";
193
+ }
194
+
195
+ function resolveTheme() {
196
+ return {"id":"anatomy","label":"Anatomy","motif":"signal-aurora","palette":["#061315","#10272b","#f1feff","#9bb9bb","#50e3d4","#b4ed70"],"source":"space-specific"};
197
+ const id = surfaceCandidate();
198
+ const curated = CURATED[id];
199
+ if (curated) return { id, ...curated, source: "curated" };
200
+
201
+ const seed = fnv1a(id);
202
+ const palette = PALETTES[seed % PALETTES.length];
203
+ return {
204
+ id,
205
+ label: titleCase(id) || "A11oy Space",
206
+ motif: MOTIFS[(seed >>> 8) % MOTIFS.length],
207
+ palette,
208
+ source: "deterministic",
209
+ };
210
+ }
211
+
212
+ function applyTheme(theme) {
213
+ const [background, surface, foreground, muted, accent, accent2] = theme.palette;
214
+ const root = document.documentElement;
215
+ root.dataset.szlHolo = "v2";
216
+ root.dataset.szlHoloSurface = theme.id;
217
+ root.dataset.szlHoloMotif = theme.motif;
218
+ root.dataset.szlHoloThemeSource = theme.source;
219
+ root.style.setProperty("--szl-holo-bg", background);
220
+ root.style.setProperty("--szl-holo-bg-deep", background);
221
+ root.style.setProperty("--szl-holo-surface", surface);
222
+ root.style.setProperty("--szl-holo-surface-2", surface);
223
+ root.style.setProperty("--szl-holo-ink", foreground);
224
+ root.style.setProperty("--szl-holo-muted", muted);
225
+ root.style.setProperty("--szl-holo-accent", accent);
226
+ root.style.setProperty("--szl-holo-accent-2", accent2);
227
+ }
228
+
229
+ function createElement(name, attributes = {}, text = null) {
230
+ const node = document.createElement(name);
231
+ for (const [key, value] of Object.entries(attributes)) {
232
+ if (key === "className") node.className = value;
233
+ else if (key === "dataset") Object.assign(node.dataset, value);
234
+ else node.setAttribute(key, value);
235
+ }
236
+ if (text !== null) node.textContent = text;
237
+ return node;
238
+ }
239
+
240
+ function addSkipLink() {
241
+ if (document.querySelector(".szl-holo-skip, [data-szl-holo-skip]")) return;
242
+ const main = document.querySelector("main, [role='main']");
243
+ if (!main) return;
244
+ if (!main.id) main.id = "szl-holo-main";
245
+ const link = createElement("a", {
246
+ className: "szl-holo-skip",
247
+ href: `#${main.id}`,
248
+ dataset: { szlHoloSkip: "true" },
249
+ }, "Skip to main content");
250
+ document.body.prepend(link);
251
+ }
252
+
253
+ function currentLink(href) {
254
+ const target = new URL(href);
255
+ const host = location.hostname.replace(/^www\./, "");
256
+ if (target.hostname.replace(/^www\./, "") !== host) return false;
257
+ if (target.pathname === "/") return location.pathname === "/";
258
+ return location.pathname.startsWith(target.pathname.replace(/\/$/, ""));
259
+ }
260
+
261
+ function buildRail(theme) {
262
+ if (document.querySelector(".szl-holo-rail") || document.documentElement.hasAttribute("data-szl-holo-no-rail")) return;
263
+
264
+ const rail = createElement("header", {
265
+ className: "szl-holo-rail",
266
+ dataset: { szlHoloRail: "v2" },
267
+ });
268
+ const identity = createElement("a", {
269
+ className: "szl-holo-identity",
270
+ href: `${PRODUCT}/`,
271
+ "aria-label": "Open the A11oy Command origin",
272
+ });
273
+ identity.append(createElement("span", { className: "szl-holo-mark", "aria-hidden": "true" }));
274
+ const copy = createElement("span", { className: "szl-holo-copy" });
275
+ copy.append(createElement("span", { className: "szl-holo-eyebrow" }, "SZL · Holo-Constellation"));
276
+ copy.append(createElement("span", { className: "szl-holo-label" }, theme.label));
277
+ identity.append(copy);
278
+
279
+ const controls = createElement("div", { className: "szl-holo-controls" });
280
+ const menu = createElement("button", {
281
+ className: "szl-holo-menu",
282
+ type: "button",
283
+ "aria-label": "Open ecosystem navigation",
284
+ "aria-expanded": "false",
285
+ "aria-controls": "szl-holo-nav",
286
+ }, "Menu");
287
+ const nav = createElement("nav", {
288
+ className: "szl-holo-nav",
289
+ id: "szl-holo-nav",
290
+ "aria-label": "A11oy ecosystem",
291
+ dataset: { open: "false" },
292
+ });
293
+ for (const [label, href] of LINKS) {
294
+ const attributes = { className: "szl-holo-link", href };
295
+ if (currentLink(href)) attributes["aria-current"] = "page";
296
+ nav.append(createElement("a", attributes, label));
297
+ }
298
+ controls.append(menu, nav);
299
+ rail.append(identity, controls);
300
+ document.body.prepend(rail);
301
+
302
+ const close = ({ focus = false } = {}) => {
303
+ nav.dataset.open = "false";
304
+ menu.setAttribute("aria-expanded", "false");
305
+ menu.setAttribute("aria-label", "Open ecosystem navigation");
306
+ menu.textContent = "Menu";
307
+ if (focus) menu.focus();
308
+ };
309
+
310
+ menu.addEventListener("click", () => {
311
+ const open = nav.dataset.open !== "true";
312
+ nav.dataset.open = String(open);
313
+ menu.setAttribute("aria-expanded", String(open));
314
+ menu.setAttribute("aria-label", open ? "Close ecosystem navigation" : "Open ecosystem navigation");
315
+ menu.textContent = open ? "Close" : "Menu";
316
+ });
317
+ document.addEventListener("keydown", (event) => {
318
+ if (event.key === "Escape" && nav.dataset.open === "true") close({ focus: true });
319
+ });
320
+ document.addEventListener("pointerdown", (event) => {
321
+ if (nav.dataset.open === "true" && !rail.contains(event.target)) close();
322
+ });
323
+ }
324
+
325
+ function addAmbient() {
326
+ if (document.getElementById("szl-holo-ambient")) return;
327
+ const ambient = createElement("div", {
328
+ id: "szl-holo-ambient",
329
+ "aria-hidden": "true",
330
+ dataset: { szlHoloDecorative: "true" },
331
+ });
332
+ document.body.prepend(ambient);
333
+ }
334
+
335
+ function addProgress() {
336
+ if (document.querySelector(".szl-holo-progress")) return;
337
+ document.body.append(createElement("div", {
338
+ className: "szl-holo-progress",
339
+ "aria-hidden": "true",
340
+ dataset: { szlHoloDecorative: "true" },
341
+ }));
342
+ }
343
+
344
+ function enhancePanels() {
345
+ if (document.documentElement.hasAttribute("data-szl-holo-no-auto-panels")) return;
346
+ const selectors = [
347
+ "main .card",
348
+ "main .panel",
349
+ "main .metric-card",
350
+ "main .feature-card",
351
+ "main [class*='glass-card']",
352
+ "main [class*='holo-card']",
353
+ "main [data-panel]",
354
+ ];
355
+ const seen = new Set();
356
+ for (const node of document.querySelectorAll(selectors.join(","))) {
357
+ if (seen.size >= 24) break;
358
+ if (seen.has(node) || node.closest("nav, header, footer, table, pre, code, form, dialog")) continue;
359
+ seen.add(node);
360
+ node.setAttribute("data-szl-holo-panel", "auto");
361
+ }
362
+ }
363
+
364
+ function installMotion() {
365
+ const root = document.documentElement;
366
+ let pointerFrame = 0;
367
+ let scrollFrame = 0;
368
+ let lastX = window.innerWidth / 2;
369
+ let lastY = Math.min(window.innerHeight * 0.22, 240);
370
+
371
+ const commitPointer = () => {
372
+ pointerFrame = 0;
373
+ root.style.setProperty("--szl-holo-pointer-x", `${Math.round((lastX / Math.max(window.innerWidth, 1)) * 1000) / 10}%`);
374
+ root.style.setProperty("--szl-holo-pointer-y", `${Math.round((lastY / Math.max(window.innerHeight, 1)) * 1000) / 10}%`);
375
+ };
376
+
377
+ const pointer = (event) => {
378
+ if (REDUCE_MOTION.matches || !FINE_POINTER.matches || SAVE_DATA || document.hidden) return;
379
+ lastX = event.clientX;
380
+ lastY = event.clientY;
381
+ if (!pointerFrame) pointerFrame = requestAnimationFrame(commitPointer);
382
+ };
383
+
384
+ const commitScroll = () => {
385
+ scrollFrame = 0;
386
+ const maximum = Math.max(1, document.documentElement.scrollHeight - window.innerHeight);
387
+ const percentage = Math.max(0, Math.min(100, (window.scrollY / maximum) * 100));
388
+ root.style.setProperty("--szl-holo-scroll", percentage.toFixed(2));
389
+ };
390
+
391
+ const scroll = () => {
392
+ if (!scrollFrame) scrollFrame = requestAnimationFrame(commitScroll);
393
+ };
394
+
395
+ if (!SAVE_DATA) window.addEventListener("pointermove", pointer, { passive: true });
396
+ window.addEventListener("scroll", scroll, { passive: true });
397
+ window.addEventListener("resize", scroll, { passive: true });
398
+ document.addEventListener("visibilitychange", () => {
399
+ root.dataset.szlHoloPaused = String(document.hidden);
400
+ if (!document.hidden) scroll();
401
+ });
402
+ REDUCE_MOTION.addEventListener?.("change", () => {
403
+ root.dataset.szlHoloReducedMotion = String(REDUCE_MOTION.matches);
404
+ });
405
+ root.dataset.szlHoloReducedMotion = String(REDUCE_MOTION.matches);
406
+ root.dataset.szlHoloSaveData = String(SAVE_DATA);
407
+ commitPointer();
408
+ commitScroll();
409
+ }
410
+
411
+ function boot() {
412
+ if (!document.body || document.documentElement.hasAttribute("data-szl-holo-disabled")) return;
413
+ const theme = resolveTheme();
414
+ applyTheme(theme);
415
+ addAmbient();
416
+ addProgress();
417
+ addSkipLink();
418
+ buildRail(theme);
419
+ enhancePanels();
420
+ installMotion();
421
+
422
+ window.SZLHolo = Object.freeze({
423
+ version: VERSION,
424
+ theme: Object.freeze({ ...theme, palette: [...theme.palette] }),
425
+ resolveTheme,
426
+ fnv1a,
427
+ decorativeMotion: true,
428
+ measuredTelemetry: false,
429
+ });
430
+ document.dispatchEvent(new CustomEvent("szl:holo-ready", {
431
+ detail: { version: VERSION, surface: theme.id, motif: theme.motif, source: theme.source },
432
+ }));
433
+ }
434
+
435
+ if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", boot, { once: true });
436
+ else boot();
437
+ })();
tests/qa_evidence_bay.js ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ const initialEvidence = page.waitForResponse(response => {
20
+ const url = new URL(response.url());
21
+ return url.pathname === '/api/anatomy/v1/evidence' && response.request().method() === 'GET';
22
+ }, {timeout:45000});
23
+ await page.goto(BASE+'/', {waitUntil:'networkidle'});
24
+ await page.waitForSelector('#fa-launch');
25
+ await page.click('#fa-launch');
26
+ await page.waitForSelector('#fa-panel.open');
27
+ const initialEvidenceResponse = await initialEvidence;
28
+ if (initialEvidenceResponse.status() !== 200) throw new Error(vp.name+' initial evidence HTTP '+initialEvidenceResponse.status());
29
+
30
+ const overview = await page.evaluate(() => ({
31
+ title: document.querySelector('.fa-title')?.textContent,
32
+ dimensions: [...document.querySelectorAll('.fa-dim-value')].map(x=>x.textContent),
33
+ launcher: getComputedStyle(document.getElementById('fa-launch')).display,
34
+ panelWidth: document.getElementById('fa-panel').getBoundingClientRect().width,
35
+ viewport: window.innerWidth,
36
+ }));
37
+
38
+ await page.click('[data-tab="capabilities"]');
39
+ const capabilityCount = await page.locator('.fa-cap').count();
40
+ // textContent covers the complete declarative shell even when the browser
41
+ // collapses detail descendants during layout/animation.
42
+ const shellText = await page.locator('.fa-cap').first().textContent();
43
+
44
+ await page.click('[data-tab="evidence"]');
45
+ try {
46
+ await page.waitForSelector('.fa-dep');
47
+ } catch (error) {
48
+ const activeTab = await page.locator('.fa-tab.active').innerText({timeout:2000}).catch(()=>'missing');
49
+ const evidenceBody = await page.locator('#fa-body').innerText({timeout:2000}).catch(()=>'missing');
50
+ throw new Error(vp.name+' evidence panel timeout; active='+activeTab+'; body='+evidenceBody+'; console='+errors.join(' | ')+'; '+error.message);
51
+ }
52
+ const dependencyCount = await page.locator('.fa-dep').count();
53
+ const dependencyStates = await page.locator('.fa-dep-state').allInnerTexts();
54
+
55
+ await page.click('[data-tab="reproduce"]');
56
+ const endpointTexts = await page.locator('.fa-endpoint a').allInnerTexts();
57
+ const [versionResponse, evidenceResponse] = await Promise.all([
58
+ page.request.get(BASE+'/version'),
59
+ page.request.get(BASE+'/evidence'),
60
+ ]);
61
+ const contracts = {
62
+ versionStatus: versionResponse.status(),
63
+ evidenceStatus: evidenceResponse.status(),
64
+ version: await versionResponse.json(),
65
+ evidence: await evidenceResponse.json(),
66
+ };
67
+
68
+ await page.click('[data-tab="overview"]');
69
+ await page.click('#fa-verify-bundle');
70
+ await page.waitForSelector('.fa-output.good');
71
+ const verification = await page.locator('.fa-output').innerText();
72
+
73
+ await page.screenshot({path:path.join(OUT,'anatomy-evidence-'+vp.name+'.png'),fullPage:true});
74
+ await page.close();
75
+
76
+ if (errors.length) throw new Error(vp.name+' console errors: '+errors.join(' | '));
77
+ if (overview.title !== 'Evidence Bay') throw new Error(vp.name+' missing Evidence Bay title');
78
+ if (overview.panelWidth > overview.viewport + 1) throw new Error(vp.name+' panel overflows viewport');
79
+ if (capabilityCount < 5) throw new Error(vp.name+' capability count '+capabilityCount);
80
+ for (const field of ['Purpose','Try','Evidence','Limits','Reproduce']) {
81
+ if (!shellText.includes(field)) throw new Error(vp.name+' missing '+field+' shell');
82
+ }
83
+ if (dependencyCount !== 4) throw new Error(vp.name+' dependency count '+dependencyCount);
84
+ if (!endpointTexts.some(text => text.includes('/version'))) throw new Error(vp.name+' missing /version discovery');
85
+ if (!endpointTexts.some(text => text.includes('/evidence'))) throw new Error(vp.name+' missing /evidence discovery');
86
+ if (contracts.version.schemaVersion !== 'szl.vertical-conformance.version.v1') throw new Error(vp.name+' version schema failed');
87
+ if (contracts.evidence.schemaVersion !== 'szl.vertical-conformance.evidence.v1') throw new Error(vp.name+' evidence schema failed');
88
+ if (contracts.version.evidenceState === 'MEASURED' ? contracts.versionStatus !== 200 : contracts.versionStatus !== 503) throw new Error(vp.name+' version transport/state mismatch');
89
+ if (contracts.evidence.evidenceState === 'PARTIAL' ? contracts.evidenceStatus !== 200 : contracts.evidenceStatus !== 503) throw new Error(vp.name+' evidence transport/state mismatch');
90
+ if (!['MEASURED','UNAVAILABLE'].includes(contracts.version.evidenceState)) throw new Error(vp.name+' unexpected version evidence state '+contracts.version.evidenceState);
91
+ if (!['PARTIAL','UNAVAILABLE'].includes(contracts.evidence.evidenceState)) throw new Error(vp.name+' unexpected evidence state '+contracts.evidence.evidenceState);
92
+ if (!verification.includes('STRUCTURAL-ONLY')) throw new Error(vp.name+' receipt verdict '+verification);
93
+ return {viewport:vp.name, overview, capabilityCount, dependencyCount, dependencyStates, endpointTexts, contracts, verification};
94
+ }
95
+
96
+ (async()=>{
97
+ const browser = await chromium.launch({executablePath:EDGE,headless:true,args:['--use-gl=angle','--use-angle=swiftshader','--ignore-gpu-blocklist','--enable-unsafe-swiftshader']});
98
+ try {
99
+ const results=[];
100
+ for (const vp of VIEWPORTS) results.push(await run(browser,vp));
101
+ console.log(JSON.stringify(results,null,2));
102
+ } finally {
103
+ await browser.close();
104
+ }
105
+ })().catch(err=>{ console.error(err); process.exit(1); });
tests/test_hf_sync_contract.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import unittest
3
+
4
+
5
+ WORKFLOW = Path(".github/workflows/hf-sync.yml")
6
+ README = Path("README.md")
7
+
8
+
9
+ class HfSyncContractTest(unittest.TestCase):
10
+ @classmethod
11
+ def setUpClass(cls) -> None:
12
+ cls.workflow = WORKFLOW.read_text(encoding="utf-8")
13
+ cls.readme = README.read_text(encoding="utf-8")
14
+
15
+ def test_runtime_files_are_in_upload_contract(self) -> None:
16
+ for path in ("Dockerfile", ".dockerignore", "server.py", "organ_integrity.py"):
17
+ self.assertIn(f'"{path}"', self.workflow, path)
18
+ self.assertIn('"*.html"', self.workflow)
19
+ self.assertNotIn('"index.html", "live-body.html"', self.workflow)
20
+
21
+ def test_every_main_push_schedules_a_replacement_deploy(self) -> None:
22
+ push_trigger = self.workflow.split("workflow_dispatch:", 1)[0]
23
+ self.assertNotIn("paths:", push_trigger)
24
+ self.assertIn("group: anatomy-hf-sync", self.workflow)
25
+ self.assertIn("cancel-in-progress: false", self.workflow)
26
+
27
+ def test_release_tooling_is_exactly_pinned(self) -> None:
28
+ self.assertIn("huggingface_hub==1.23.0", self.workflow)
29
+ self.assertNotIn("huggingface_hub>=", self.workflow)
30
+
31
+ def test_release_waits_for_exact_live_revision(self) -> None:
32
+ self.assertIn("info.sha == target_sha", self.workflow)
33
+ self.assertIn('stage == "RUNNING"', self.workflow)
34
+ self.assertIn('"BUILD_ERROR"', self.workflow)
35
+ self.assertIn('/version?refresh=1', self.workflow)
36
+ self.assertIn('/.well-known/szl-source.json?refresh=1', self.workflow)
37
+ self.assertIn('source["deployment"]["hf_revision"] == target_sha', self.workflow)
38
+ self.assertIn('source["source"]["commit"] == source_revision', self.workflow)
39
+ self.assertIn(
40
+ 'source["alignment_state"] == "SOURCE_BOUND_DEPLOYMENT"',
41
+ self.workflow,
42
+ )
43
+ self.assertIn(
44
+ 'source["deployment"]["workflow_run_id"] == workflow_run_id',
45
+ self.workflow,
46
+ )
47
+
48
+ def test_release_generates_exact_source_manifest(self) -> None:
49
+ self.assertIn('"schema": "szl.hf-deploy-manifest/v1"', self.workflow)
50
+ self.assertIn('"source_repository": "szl-holdings/anatomy"', self.workflow)
51
+ self.assertIn('"source_revision": source_revision', self.workflow)
52
+ self.assertIn('"workflow_run_id": workflow_run_id', self.workflow)
53
+ self.assertIn('path_in_repo="hf-deploy-manifest.json"', self.workflow)
54
+ self.assertIn(
55
+ 'commit_message=f"hf-sync: source {source_revision} run {workflow_run_id}"',
56
+ self.workflow,
57
+ )
58
+ self.assertNotIn("os.environ.get('GITHUB_SHA','')[:8]", self.workflow)
59
+
60
+ def test_release_binds_manifest_to_hf_commit_metadata(self) -> None:
61
+ self.assertIn('workflow_run_id = os.environ.get("GITHUB_RUN_ID", "")', self.workflow)
62
+ self.assertIn('if not workflow_run_id.isdigit():', self.workflow)
63
+ self.assertIn(
64
+ 'f"hf-sync: source {source_revision} run {workflow_run_id}"',
65
+ self.workflow,
66
+ )
67
+
68
+ def test_release_rechecks_exact_current_main_at_mutation_boundary(self) -> None:
69
+ for contract in (
70
+ "GITHUB_TOKEN: ${{ github.token }}",
71
+ 'source_ref != "refs/heads/main"',
72
+ 'github_repo != "szl-holdings/anatomy"',
73
+ 'f"/repos/{github_repo}/commits/main"',
74
+ "current_main != source_revision",
75
+ ):
76
+ self.assertIn(contract, self.workflow)
77
+ self.assertLess(
78
+ self.workflow.index("current_main != source_revision"),
79
+ self.workflow.index("api.create_commit("),
80
+ )
81
+
82
+ def test_release_verifies_public_health(self) -> None:
83
+ self.assertIn('base + "/healthz"', self.workflow)
84
+ self.assertIn('health["transport_state"] == "REACHABLE"', self.workflow)
85
+ self.assertIn('health["verification_state"] == "STRUCTURAL_ONLY"', self.workflow)
86
+
87
+ def test_release_verifies_public_version_and_evidence(self) -> None:
88
+ for contract in (
89
+ 'base + "/version?refresh=1"',
90
+ 'base + "/evidence?refresh=1"',
91
+ 'version["gitSha"] == source_revision',
92
+ 'version["deploymentRevision"] == target_sha',
93
+ 'version["evidenceState"] == "MEASURED"',
94
+ 'evidence["gitSha"] == source_revision',
95
+ 'evidence["evidenceState"] == "PARTIAL"',
96
+ 'evidence["source"]["deployment"]["hf_revision"] == target_sha',
97
+ 'evidence["receipts"][0]["status"] == "STRUCTURAL_ONLY"',
98
+ 'evidence["outputProvenance"]["authenticityEstablished"] is False',
99
+ ):
100
+ self.assertIn(contract, self.workflow)
101
+
102
+ def test_stale_space_only_docker_claim_is_absent(self) -> None:
103
+ self.assertNotIn("does not exist in this repo", self.workflow)
104
+ self.assertNotIn("Space-only Dockerfile", self.workflow)
105
+
106
+ def test_archived_uds_source_is_not_advertised(self) -> None:
107
+ self.assertNotIn(
108
+ "https://github.com/szl-holdings/szl-uds-deployment",
109
+ self.readme,
110
+ )
111
+ for active_source in ("a11oy", "killinchu", "szl-mesh"):
112
+ self.assertIn(
113
+ f"https://github.com/szl-holdings/{active_source}",
114
+ self.readme,
115
+ )
116
+
117
+
118
+ if __name__ == "__main__":
119
+ unittest.main(verbosity=2)