betterwithage commited on
Commit
980edc2
·
verified ·
1 Parent(s): c2ae7b4

chore(sync): mirror backend .py + Dockerfile to Space (hf-sync-backend)

Browse files

Automated backend sync from szl-holdings/a11oy main via hf-sync-backend.
Updated (differed from the Space): Dockerfile, szl_scaling.py
Deleted (gone from the repo + Dockerfile COPY set): szl_conjecture_factory.py

Keeps the Space-built backend (serve.py + the Dockerfile-COPY'd .py
modules) identical to GitHub main so the Space never rebuilds from a
stale backend, new endpoints don't 404 there, and orphaned modules
removed from the repo don't linger in the Space tree.

Files changed (3) hide show
  1. Dockerfile +2 -2
  2. szl_conjecture_factory.py +0 -361
  3. szl_scaling.py +249 -0
Dockerfile CHANGED
@@ -82,7 +82,7 @@ COPY knowledge.json ./static/knowledge.json
82
  COPY knowledge.json szl_parity_gaps.py a11oy_warhacker_obs.py serve.py a11oy_wireA_metrics.py cathedral.html a11oy_operator_organ.py a11oy_hf_assets.py szl_b2_secdata.py gates_manifest.json a11oy_code_orchestrator.py a11oy_agent_loop.py a11oy_org_rag.py a11oy_mcp_client.py szl_rag.py a11oy_code_ide.html wayra_serve.py wayra_snapshot.json wayra_digests_7d.json szl_khipu_os_routes.py ./
83
  COPY szl_khipu_consensus.py szl_puriq_formulas.py ayni_os_serve.py szl_live_wires.py live_wires.html live_wires_3d.js szl_dsse.py szl_provenance.py szl_be_hardening.py szl_unay.py szl_khipu_lmdb.py szl_khipu_replicate.py szl_unay_routes.py szl_warhacker_aliases.py a11oy_v4_hickok.py szl_khipu.py szl_formulas.py a11oy_v4_formulas.py szl_anatomy_3d.py szl_anatomy_routes.py ./
84
  COPY _vendor_blobs.py szl_v4_fleet.py operator_shell_v4.py szl_bridge.py szl_bridge_schemas.py agent.html a11oy_bridge_cli.py szl_ken.py a11oy_formula_endpoints.py a11oy_formulas_page.py a11oy_frontier_patch.py a11oy_v4_agent.py szl_brain.py szl_wire.py szl_hub.py szl_rosie_companion.py szl_receipt_substrate.py szl_alloy_embed_fabric.py szl_ayni_quorum.py szl_agentic_loop.py ./
85
- COPY szl_formula_wiring.py a11oy_code_engine.py a11oy_code.py a11oy_seismic.py szl_warhacker_real.py szl_warhacker_demos.py NOTICE_warhacker_demos.txt szl_llm_registry.py szl_elite_console.py szl_alloy_models.py ./
86
 
87
  # Copy serve orchestrator and gates manifest
88
  # ADDITIVE (live-ops): orchestration + AI-observability module — per-file COPY Dockerfile
@@ -532,7 +532,7 @@ ENV A11OY_ALLOY_GGUF=/app/models/qwen2.5-coder-0.5b-instruct-q4_k_m.gguf
532
  # Signed-off-by: Yachay <yachay@szlholdings.ai>
533
  # ---------------------------------------------------------------------------
534
  COPY a11oy_live_feeds.py a11oy_signing_key.py a11oy_dev1_endpoints.py a11oy_vertical_feeds.py a11oy_deva_feeds.py a11oy_devb_endpoints.py a11oy_amaru_feeds.py szl_governance_gateway.py szl_abacus_verify.py szl_decision_uncertainty.py szl_gor_audit.py szl_sovereign_search.py szl_consensus_clusters.py szl_mission_ledger.py szl_budget_router.py szl_wave910_proofs.py szl_evidence_research.py szl_uds_fleet.py szl_readiness.py szl_quantum_bio.py ./
535
- COPY szl_unified_formulas.py szl_cuas_formulas.py szl_contracting.py szl_bounties.py szl_putnam.py szl_connectors_serve.py szl_connector_mcp.py szl_conjecture_factory.py ./
536
  COPY live_snapshots/ ./live_snapshots/
537
 
538
  # ADDITIVE (Investor-WOW Layer, 2026-06-08, Dev1): a11oy_dev1_endpoints.py exposes
 
82
  COPY knowledge.json szl_parity_gaps.py a11oy_warhacker_obs.py serve.py a11oy_wireA_metrics.py cathedral.html a11oy_operator_organ.py a11oy_hf_assets.py szl_b2_secdata.py gates_manifest.json a11oy_code_orchestrator.py a11oy_agent_loop.py a11oy_org_rag.py a11oy_mcp_client.py szl_rag.py a11oy_code_ide.html wayra_serve.py wayra_snapshot.json wayra_digests_7d.json szl_khipu_os_routes.py ./
83
  COPY szl_khipu_consensus.py szl_puriq_formulas.py ayni_os_serve.py szl_live_wires.py live_wires.html live_wires_3d.js szl_dsse.py szl_provenance.py szl_be_hardening.py szl_unay.py szl_khipu_lmdb.py szl_khipu_replicate.py szl_unay_routes.py szl_warhacker_aliases.py a11oy_v4_hickok.py szl_khipu.py szl_formulas.py a11oy_v4_formulas.py szl_anatomy_3d.py szl_anatomy_routes.py ./
84
  COPY _vendor_blobs.py szl_v4_fleet.py operator_shell_v4.py szl_bridge.py szl_bridge_schemas.py agent.html a11oy_bridge_cli.py szl_ken.py a11oy_formula_endpoints.py a11oy_formulas_page.py a11oy_frontier_patch.py a11oy_v4_agent.py szl_brain.py szl_wire.py szl_hub.py szl_rosie_companion.py szl_receipt_substrate.py szl_alloy_embed_fabric.py szl_ayni_quorum.py szl_agentic_loop.py ./
85
+ COPY szl_formula_wiring.py a11oy_code_engine.py a11oy_code.py a11oy_seismic.py szl_warhacker_real.py szl_warhacker_demos.py NOTICE_warhacker_demos.txt szl_llm_registry.py szl_elite_console.py szl_alloy_models.py szl_scaling.py ./
86
 
87
  # Copy serve orchestrator and gates manifest
88
  # ADDITIVE (live-ops): orchestration + AI-observability module — per-file COPY Dockerfile
 
532
  # Signed-off-by: Yachay <yachay@szlholdings.ai>
533
  # ---------------------------------------------------------------------------
534
  COPY a11oy_live_feeds.py a11oy_signing_key.py a11oy_dev1_endpoints.py a11oy_vertical_feeds.py a11oy_deva_feeds.py a11oy_devb_endpoints.py a11oy_amaru_feeds.py szl_governance_gateway.py szl_abacus_verify.py szl_decision_uncertainty.py szl_gor_audit.py szl_sovereign_search.py szl_consensus_clusters.py szl_mission_ledger.py szl_budget_router.py szl_wave910_proofs.py szl_evidence_research.py szl_uds_fleet.py szl_readiness.py szl_quantum_bio.py ./
535
+ COPY szl_unified_formulas.py szl_cuas_formulas.py szl_contracting.py szl_bounties.py szl_putnam.py szl_connectors_serve.py szl_connector_mcp.py ./
536
  COPY live_snapshots/ ./live_snapshots/
537
 
538
  # ADDITIVE (Investor-WOW Layer, 2026-06-08, Dev1): a11oy_dev1_endpoints.py exposes
szl_conjecture_factory.py DELETED
@@ -1,361 +0,0 @@
1
- """szl_conjecture_factory.py
2
-
3
- Read-only loader that surfaces the SZL Conjecture Factory's output for the
4
- a11oy /console and killinchu /elite consoles.
5
-
6
- It reads the conjecture-disclosure records the factory appends to the szl-lake
7
- DSSE Khipu ledger (NDJSON), and exposes them with an HONEST status convention
8
- ("live" / "cached" / "unreachable") identical to the other shared console
9
- modules.
10
-
11
- Honesty doctrine (do NOT weaken):
12
- * A factory-generated problem is a CONJECTURE, never a theorem. It stays OPEN
13
- until a solution is independently verified.
14
- * "novelty" is an advisory screen, not a proof of originality.
15
- * "difficulty"/"grade" come from a bounded solver run: OPEN means
16
- searched-to-budget (NOT proven true); VERIFIED-FINITE certifies only the
17
- finite enumerated domain; REFUTED carries a concrete witness.
18
- * The cosign/Rekor signature attests the timestamp + content, NOT the truth
19
- of the conjecture.
20
- * An unreachable source is reported as unreachable; it never confirms novelty
21
- and we never fabricate a value.
22
-
23
- Stdlib only (urllib/json) so it drops into the console containers with no extra
24
- dependency, mirroring szl_bounties.py / szl_evidence_research.py.
25
- """
26
-
27
- from __future__ import annotations
28
-
29
- import json
30
- import os
31
- import re
32
- import time
33
- import urllib.error
34
- import urllib.request
35
- from typing import Any, Dict, List, Optional, Tuple
36
-
37
- # --- status labels (shared honest convention) -------------------------------
38
- STATUS_LIVE = "live"
39
- STATUS_CACHED = "cached"
40
- STATUS_UNREACHABLE = "unreachable"
41
-
42
- # The factory anchors each disclosure under this receipt kind.
43
- CONJECTURE_KIND = "conjecture-disclosure-anchor"
44
- CONJECTURE_MILESTONE_KIND = "conjecture-disclosure"
45
-
46
- # Sources, in priority order. Overridable by env for the box/HF containers.
47
- # The factory anchors its disclosures into the szl-lake DSSE Khipu ledger.
48
- # NOTE: the two surfaces use DIFFERENT path prefixes for the same file --
49
- # HF dataset has no `data/` prefix, GitHub raw does. Probed live.
50
- _DEFAULT_SOURCES = [
51
- os.environ.get(
52
- "SZL_LAKE_NDJSON_HF",
53
- "https://huggingface.co/datasets/szlholdings/szl-lake/resolve/main/khipu/lutar_lean_receipts.ndjson",
54
- ),
55
- os.environ.get(
56
- "SZL_LAKE_NDJSON_GH",
57
- "https://raw.githubusercontent.com/szl-holdings/szl-lake/main/data/khipu/lutar_lean_receipts.ndjson",
58
- ),
59
- ]
60
-
61
- _CACHE_PATH = os.environ.get(
62
- "SZL_CONJECTURE_CACHE",
63
- os.path.join(os.path.dirname(os.path.abspath(__file__)), ".conjecture_factory_cache.ndjson"),
64
- )
65
-
66
- _HTTP_TIMEOUT = float(os.environ.get("SZL_CONJECTURE_HTTP_TIMEOUT", "6"))
67
-
68
- # Verdict tokens we recognise from the factory's own honesty prose when the
69
- # record does not carry discrete fields. We only read what the factory wrote;
70
- # we never invent a verdict.
71
- _NOVELTY_TOKENS = {"novel-candidate", "known-restatement", "duplicate", "inconclusive"}
72
- _DIFFICULTY_TOKENS = {"open-resistant", "hard", "moderate", "easy", "verified-finite", "refuted"}
73
- _GRADE_TOKENS = {"OPEN", "VERIFIED-FINITE", "REFUTED", "RETRACTED"}
74
- _RELEASE_STAGES = {"teaser", "statement", "solution"}
75
-
76
-
77
- def _first_match(text: Optional[str], allowed: set, lower: bool = True) -> Optional[str]:
78
- """Return the first single-quoted token in *text* that is in *allowed*."""
79
- if not text:
80
- return None
81
- for tok in re.findall(r"'([^']+)'", text):
82
- probe = tok.lower() if lower else tok
83
- bucket = {a.lower() for a in allowed} if lower else allowed
84
- if probe in bucket:
85
- return tok
86
- return None
87
-
88
-
89
- def _fetch(url: str) -> Optional[str]:
90
- if not url:
91
- return None
92
- try:
93
- req = urllib.request.Request(url, headers={"User-Agent": "szl-conjecture-factory/1.0"})
94
- with urllib.request.urlopen(req, timeout=_HTTP_TIMEOUT) as resp: # nosec - read-only public ledger
95
- if getattr(resp, "status", 200) != 200:
96
- return None
97
- return resp.read().decode("utf-8", "replace")
98
- except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError, ValueError):
99
- return None
100
-
101
-
102
- def _read_cache() -> Optional[str]:
103
- try:
104
- with open(_CACHE_PATH, "r", encoding="utf-8") as fh:
105
- data = fh.read()
106
- return data if data.strip() else None
107
- except OSError:
108
- return None
109
-
110
-
111
- def _write_cache(raw: str) -> None:
112
- try:
113
- tmp = _CACHE_PATH + ".tmp"
114
- with open(tmp, "w", encoding="utf-8") as fh:
115
- fh.write(raw)
116
- os.replace(tmp, _CACHE_PATH)
117
- except OSError:
118
- pass
119
-
120
-
121
- def _parse_ndjson(raw: str) -> List[Dict[str, Any]]:
122
- out: List[Dict[str, Any]] = []
123
- for line in raw.splitlines():
124
- line = line.strip()
125
- if not line:
126
- continue
127
- try:
128
- obj = json.loads(line)
129
- except json.JSONDecodeError:
130
- continue
131
- if isinstance(obj, dict):
132
- out.append(obj)
133
- return out
134
-
135
-
136
- def _is_conjecture(rec: Dict[str, Any]) -> bool:
137
- return (
138
- rec.get("kind") == CONJECTURE_KIND
139
- or rec.get("milestone_kind") == CONJECTURE_MILESTONE_KIND
140
- )
141
-
142
-
143
- def _normalize(rec: Dict[str, Any]) -> Dict[str, Any]:
144
- """Map one ledger record to a console-friendly, honesty-preserving item.
145
-
146
- Prefers discrete fields if the factory writes them; otherwise reads the
147
- factory's own honesty prose. Never fabricates a verdict.
148
- """
149
- honesty = rec.get("honesty") or {}
150
- signing = rec.get("signing") or {}
151
- source_run = rec.get("source_run") or {}
152
-
153
- novelty = (
154
- rec.get("novelty_verdict")
155
- or rec.get("novelty")
156
- or _first_match(honesty.get("novelty"), _NOVELTY_TOKENS)
157
- )
158
- difficulty = (
159
- rec.get("difficulty_grade")
160
- or rec.get("difficulty")
161
- or _first_match(honesty.get("difficulty"), _DIFFICULTY_TOKENS)
162
- )
163
- grade = (
164
- rec.get("grade")
165
- or rec.get("milestone_status")
166
- or _first_match(honesty.get("difficulty"), _GRADE_TOKENS, lower=False)
167
- )
168
- release_stage = (
169
- rec.get("release_stage")
170
- or rec.get("stage")
171
- or _first_match(honesty.get("status"), _RELEASE_STAGES)
172
- or "statement"
173
- )
174
-
175
- # Honesty guard: a conjecture is NEVER a theorem and is shown OPEN until
176
- # independently verified. Only the factory's own VERIFIED-FINITE / REFUTED
177
- # grades may change that; an absent grade defaults to OPEN, not "proved".
178
- if not grade:
179
- grade = "OPEN"
180
-
181
- return {
182
- "id": rec.get("receipt_id") or rec.get("milestone_id") or rec.get("chain_index"),
183
- "title": rec.get("milestone_title") or rec.get("title") or "(untitled conjecture)",
184
- "statement": rec.get("statement") or honesty.get("conjecture") or "",
185
- "novelty": novelty,
186
- "difficulty": difficulty,
187
- "grade": grade,
188
- "release_stage": release_stage,
189
- "is_open": grade not in ("VERIFIED-FINITE", "REFUTED"),
190
- "organ": rec.get("organ"),
191
- "kernel_commit_short": rec.get("kernel_commit_short") or (rec.get("kernel_commit") or "")[:12] or None,
192
- "timestamp": rec.get("timestamp"),
193
- "chain_index": rec.get("chain_index"),
194
- "prev_hash": rec.get("prev_hash"),
195
- "honesty": {
196
- "status": honesty.get("status"),
197
- "conjecture": honesty.get("conjecture"),
198
- "novelty": honesty.get("novelty"),
199
- "difficulty": honesty.get("difficulty"),
200
- "signing": honesty.get("signing"),
201
- "doctrine": honesty.get("doctrine") or rec.get("doctrine"),
202
- },
203
- "receipt": {
204
- "receipt_id": rec.get("receipt_id"),
205
- "chain_index": rec.get("chain_index"),
206
- "predicate_type": signing.get("predicate_type"),
207
- "signing_mode": signing.get("mode"),
208
- "rekor_log_index": signing.get("rekor_log_index"),
209
- "rekor_integrated_time": signing.get("rekor_integrated_time"),
210
- "verify_cmd": signing.get("verify_cmd"),
211
- "fulcio_identity": signing.get("fulcio_identity"),
212
- "source_run_url": source_run.get("url"),
213
- "source_run_workflow": source_run.get("workflow"),
214
- },
215
- }
216
-
217
-
218
- def load_conjectures(force_refresh: bool = True) -> Dict[str, Any]:
219
- """Load factory conjectures with an honest live/cached/unreachable status.
220
-
221
- Returns a dict::
222
-
223
- {
224
- "status": "live" | "cached" | "unreachable",
225
- "source": <url-or-cache-or-None>,
226
- "fetched_at": <iso8601 utc>,
227
- "count": <int>,
228
- "items": [ ...normalized conjecture items... ],
229
- "doctrine_banner": <str>, # honesty banner, always present
230
- }
231
- """
232
- fetched_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
233
- raw: Optional[str] = None
234
- source: Optional[str] = None
235
- status = STATUS_UNREACHABLE
236
-
237
- if force_refresh:
238
- for url in _DEFAULT_SOURCES:
239
- data = _fetch(url)
240
- if data is not None:
241
- raw, source, status = data, url, STATUS_LIVE
242
- _write_cache(data)
243
- break
244
-
245
- if raw is None:
246
- cached = _read_cache()
247
- if cached is not None:
248
- raw, source, status = cached, _CACHE_PATH, STATUS_CACHED
249
-
250
- items: List[Dict[str, Any]] = []
251
- if raw is not None:
252
- for rec in _parse_ndjson(raw):
253
- if _is_conjecture(rec):
254
- items.append(_normalize(rec))
255
-
256
- # Stable, newest-first ordering by chain_index when available.
257
- items.sort(key=lambda it: (it.get("chain_index") or 0), reverse=True)
258
-
259
- return {
260
- "status": status,
261
- "source": source,
262
- "fetched_at": fetched_at,
263
- "count": len(items),
264
- "items": items,
265
- "doctrine_banner": (
266
- "Factory output is a set of OPEN conjectures \u2014 generated, not proven. "
267
- "Each stays OPEN until a solution is independently verified; novelty is an "
268
- "advisory screen; signatures attest timestamp + content, not truth. "
269
- "Conjecture 1 (unconditional \u039b uniqueness) is and remains OPEN."
270
- ),
271
- }
272
-
273
-
274
- def load_conjecture(receipt_id: str, force_refresh: bool = True) -> Optional[Dict[str, Any]]:
275
- """Return a single normalized conjecture by receipt_id (or None)."""
276
- bundle = load_conjectures(force_refresh=force_refresh)
277
- for it in bundle["items"]:
278
- if it.get("id") == receipt_id or it.get("receipt", {}).get("receipt_id") == receipt_id:
279
- return {**it, "_envelope_status": bundle["status"], "_fetched_at": bundle["fetched_at"]}
280
- return None
281
-
282
-
283
- # --- registration (FastAPI, mirrors szl_bounties.register) -------------------
284
- def register(app, ns: str = "a11oy") -> None:
285
- """Attach the Conjecture Factory endpoints for namespace *ns*.
286
-
287
- Mounts (read-only)::
288
-
289
- GET /api/{ns}/v1/conjecture-factory -> honest bundle
290
- GET /api/{ns}/v1/conjecture-factory/{rid} -> single conjecture (404 if absent)
291
-
292
- Mirrors the szl_bounties.register() convention so the deploy is a one-line
293
- import + register() and the module ships byte-identical to both consoles.
294
- """
295
- try:
296
- from fastapi.responses import JSONResponse
297
- except Exception: # pragma: no cover - non-FastAPI host
298
- return
299
-
300
- base = "/api/%s/v1/conjecture-factory" % ns
301
-
302
- @app.get(base)
303
- async def _conjectures_index(): # noqa: ANN202
304
- bundle = load_conjectures(force_refresh=True)
305
- return JSONResponse({
306
- "layer": "%s conjecture factory" % ns,
307
- "honest": bundle["doctrine_banner"],
308
- "doctrine": "v11",
309
- "status": bundle["status"],
310
- "source": bundle["source"],
311
- "count": bundle["count"],
312
- "conjectures": bundle["items"],
313
- "checked_at": bundle["fetched_at"],
314
- })
315
-
316
- @app.get(base + "/{rid}")
317
- async def _conjecture_one(rid: str): # noqa: ANN202
318
- item = load_conjecture(rid, force_refresh=True)
319
- if item is None:
320
- return JSONResponse(
321
- {"error": "unknown conjecture", "receipt_id": rid},
322
- status_code=404,
323
- )
324
- return JSONResponse({
325
- "layer": "%s conjecture" % ns,
326
- "doctrine": "v11",
327
- "conjecture": item,
328
- })
329
-
330
-
331
- # --- offline self-test against a local ledger --------------------------------
332
- def _selftest(path: str) -> int:
333
- """Parse a local NDJSON ledger (no network) and print a summary."""
334
- with open(path, "r", encoding="utf-8") as fh:
335
- raw = fh.read()
336
- recs = _parse_ndjson(raw)
337
- conj = [_normalize(r) for r in recs if _is_conjecture(r)]
338
- print(f"records={len(recs)} conjectures={len(conj)}")
339
- for it in conj:
340
- print(
341
- f" - id={it['id'][:16] if it['id'] else None}... "
342
- f"title={it['title']!r} novelty={it['novelty']} "
343
- f"difficulty={it['difficulty']} grade={it['grade']} "
344
- f"stage={it['release_stage']} open={it['is_open']} "
345
- f"rekor={it['receipt']['rekor_log_index']}"
346
- )
347
- # honesty assertions
348
- assert it["grade"] != "PROVED", "conjecture must never be graded PROVED"
349
- assert "theorem" not in it["title"].lower() or it["is_open"], "conjecture mislabeled as theorem"
350
- return 0
351
-
352
-
353
- if __name__ == "__main__":
354
- import sys
355
-
356
- target = sys.argv[1] if len(sys.argv) > 1 else None
357
- if target:
358
- raise SystemExit(_selftest(target))
359
- out = load_conjectures()
360
- print(json.dumps({k: v for k, v in out.items() if k != "items"}, indent=2))
361
- print(f"items={out['count']}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
szl_scaling.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # © 2026 Lutar, Stephen P. Jr. — SZL Holdings · ORCID 0009-0001-0110-4173 · Doctrine v11
3
+ """
4
+ szl_scaling.py — SZL metabolic-scaling module. Real deterministic Python.
5
+ SHARED module: byte-identical in a11oy AND killinchu (and read by anatomy via API).
6
+
7
+ Implements Kleiber's law + the Metabolic Theory of Ecology temperature form + the
8
+ quantum-metabolism (PMF/coherence) bridge, and SZL's OWN unification Φ that couples
9
+ network scaling (M^3/4), thermodynamic activation (Boltzmann/PMF), and quantum
10
+ coherence (τc) — a combination no single source assembles. We CITE every classical
11
+ result and reclaim NONE; the SZL contribution is the unified Φ + the compute-allometry
12
+ analogue, both clearly labeled PROPOSED.
13
+
14
+ DOCTRINE: locked-proven = EXACTLY 8 {F1,F4,F7,F11,F12,F18,F19,F22} @ c7c0ba17 — this
15
+ module adds NOTHING to the locked 8 (EXPERIMENTAL-tier). Λ = Conjecture 1. The SZL Φ is
16
+ PROPOSED, NOT the formal Λ. Trust never 100%. No fabricated data (live dataset values
17
+ are labeled SAMPLE/attributed; nothing invented).
18
+
19
+ Citations (cited, NOT reclaimed):
20
+ - Kleiber 1932, Hilgardia (B = B0·M^3/4): https://pdodds.w3.uvm.edu/files/papers/others/1932/kleiber1932a.pdf
21
+ - West, Brown & Enquist 1997, Science 276:122 (fractal network): https://www.science.org/doi/10.1126/science.276.5309.122
22
+ - Banavar, Maritan & Rinaldo 1999, Nature (efficient network, B~M^{D/(D+1)}): https://www.nature.com/articles/20144
23
+ - Brown, Gillooly, Allen, Savage, West 2004, Ecology 85:1771 (MTE, Boltzmann factor): https://doi.org/10.1890/03-9000
24
+ - Demetrius & Tuszynski 2010, J R Soc Interface (quantum metabolism / PMF bridge): https://pmc.ncbi.nlm.nih.gov/articles/PMC2842802/
25
+ - Kaplan et al. 2020, arXiv:2001.08361 (neural scaling laws — compute analogue): https://arxiv.org/abs/2001.08361
26
+
27
+ Register: register(app, ns="a11oy") / register(app, ns="killinchu")
28
+ Routes: GET /api/<ns>/v1/scaling/{summary,kleiber,mte,unified,heart,compute,exponents}
29
+ """
30
+ from __future__ import annotations
31
+ import math
32
+ from typing import Any
33
+
34
+ # Physical constants
35
+ K_EV = 8.617333262e-5 # Boltzmann constant, eV/K
36
+ R_GAS = 8.314 # J/(mol·K)
37
+ F_FARADAY = 96485.0 # C/mol
38
+
39
+ STATUS_LEGEND = {
40
+ "VERIFIED": "deterministic computation reproduces a documented numeric on call",
41
+ "PROPOSED": "SZL construct (unified Φ / compute-allometry); NOT in locked 8; Λ stays Conjecture 1",
42
+ "SAMPLE": "illustrative values from public datasets (AnAge/PanTHERIA), attributed, not invented",
43
+ }
44
+
45
+ SOURCES = {
46
+ "Kleiber 1932 (B=B0·M^3/4)": "https://pdodds.w3.uvm.edu/files/papers/others/1932/kleiber1932a.pdf",
47
+ "West-Brown-Enquist 1997 (fractal network)": "https://www.science.org/doi/10.1126/science.276.5309.122",
48
+ "Banavar-Maritan-Rinaldo 1999 (efficient network)": "https://www.nature.com/articles/20144",
49
+ "Brown et al. 2004 MTE (Boltzmann factor)": "https://doi.org/10.1890/03-9000",
50
+ "Demetrius-Tuszynski 2010 (quantum metabolism/PMF)": "https://pmc.ncbi.nlm.nih.gov/articles/PMC2842802/",
51
+ "Kaplan et al. 2020 (neural scaling laws)": "https://arxiv.org/abs/2001.08361",
52
+ "AnAge / HAGR dataset": "https://genomics.senescence.info/species/",
53
+ }
54
+
55
+
56
+ # ---------------------------------------------------------------------------
57
+ # [K] Kleiber's law — B = B0 · M^β (β = 3/4)
58
+ # ---------------------------------------------------------------------------
59
+ def kleiber(M_kg: float, B0: float = 70.0, beta: float = 0.75) -> float:
60
+ """Kleiber's law metabolic rate B = B0 · M^β (kcal/day; B0≈70 for mammals, M in kg).
61
+ Cite Kleiber 1932. [VERIFIED model]"""
62
+ if M_kg <= 0:
63
+ return 0.0
64
+ return B0 * (M_kg ** beta)
65
+
66
+
67
+ def banavar_exponent(D: int = 3) -> float:
68
+ """Banavar-Maritan-Rinaldo dimensional exponent β = D/(D+1) (D=3 ⇒ 3/4).
69
+ Cite Banavar et al. 1999. [VERIFIED]"""
70
+ return D / (D + 1)
71
+
72
+
73
+ # ---------------------------------------------------------------------------
74
+ # [MTE] Temperature-corrected metabolic rate B = b0 · M^3/4 · e^(−E/kT)
75
+ # ---------------------------------------------------------------------------
76
+ def mte_rate(M_kg: float, T_kelvin: float, b0: float = 70.0,
77
+ E_eV: float = 0.65, beta: float = 0.75) -> float:
78
+ """Metabolic Theory of Ecology rate B = b0 · M^β · exp(−E/kT).
79
+ E≈0.65 eV activation energy, k=8.617e-5 eV/K. Cite Brown et al. 2004. [VERIFIED model]"""
80
+ if M_kg <= 0 or T_kelvin <= 0:
81
+ return 0.0
82
+ return b0 * (M_kg ** beta) * math.exp(-E_eV / (K_EV * T_kelvin))
83
+
84
+
85
+ def heart_rate_scaling(M_kg: float, f0: float = 241.0) -> float:
86
+ """Heart-rate allometry f ∝ M^(−1/4) (bpm; f0≈241 for M in kg, mammals).
87
+ Ties to anatomy HEART/YUYAY organ. The 'lifetime heartbeats ≈ constant' result
88
+ follows since lifespan ∝ M^(+1/4). Cite MTE/West. [VERIFIED model]"""
89
+ if M_kg <= 0:
90
+ return 0.0
91
+ return f0 * (M_kg ** -0.25)
92
+
93
+
94
+ def lifespan_scaling(M_kg: float, L0: float = 11.8) -> float:
95
+ """Lifespan allometry L ∝ M^(+1/4) (years; L0≈11.8 for M in kg, mammals)."""
96
+ if M_kg <= 0:
97
+ return 0.0
98
+ return L0 * (M_kg ** 0.25)
99
+
100
+
101
+ # ---------------------------------------------------------------------------
102
+ # PMF (our bioenergetics lineage) — Δp = ΔΨ − (2.303 RT/F) ΔpH
103
+ # ---------------------------------------------------------------------------
104
+ def proton_motive_force(delta_psi_mV: float, delta_pH: float,
105
+ T_kelvin: float = 310.0) -> float:
106
+ """Proton-motive force Δp = ΔΨ − (2.303 RT/F) ΔpH (mV). Mitchell chemiosmosis.
107
+ Reuses SZL's verified bioenergetics term. [VERIFIED model]"""
108
+ coeff_mV = 2.303 * R_GAS * T_kelvin / F_FARADAY * 1000.0 # → mV
109
+ return delta_psi_mV - coeff_mV * delta_pH
110
+
111
+
112
+ # ---------------------------------------------------------------------------
113
+ # [SZL-Φ] THE UNIFICATION (PROPOSED — our own construct)
114
+ # Φ = Φ0 · M^3/4 · exp(−(E − η·Δp_eV)/kT) · (τc/τ0)^(1/4)
115
+ # network scaling × (Boltzmann activation reduced by PMF) × coherence modulation
116
+ # ---------------------------------------------------------------------------
117
+ def szl_phi(M_kg: float, T_kelvin: float, delta_p_mV: float, tau_c: float,
118
+ Phi0: float = 70.0, E_eV: float = 0.65, eta: float = 1.0,
119
+ tau0: float = 6.05, beta: float = 0.75) -> dict[str, Any]:
120
+ """SZL unified metabolic-coherence scaling Φ (PROPOSED — our own; cites WBE+MTE+
121
+ Demetrius-Tuszynski). Couples: M^β network scaling, a Boltzmann-Arrhenius activation
122
+ whose barrier is LOWERED by the proton-motive force (η·Δp converted eV), and a
123
+ coherence modulation (τc/τ0)^(1/4) tying to our Lindblad τc / Λ-v5 lineage.
124
+
125
+ Δp is given in mV; converted to eV per elementary charge (mV/1000 = volts = eV/charge).
126
+ This is a PROPOSED engineering construct, NOT the formal Λ; Λ stays Conjecture 1. [PROPOSED]"""
127
+ if M_kg <= 0 or T_kelvin <= 0 or tau_c <= 0 or tau0 <= 0:
128
+ return {"phi": 0.0, "status": "out_of_domain"}
129
+ delta_p_eV = (delta_p_mV / 1000.0) * eta # mV→V→eV per unit charge × coupling η
130
+ barrier = (E_eV - delta_p_eV)
131
+ # Activation term as a PMF-ENHANCEMENT factor: the rate is lifted relative to the
132
+ # no-PMF baseline at the SAME operating temperature by exp(+ηΔp/kT). This isolates the
133
+ # PMF effect honestly (more PMF → lower barrier → higher rate) without the bare exp(-E/kT)
134
+ # underflow. exp(−barrier/kT)/exp(−E/kT) = exp(+ηΔp_eV/kT).
135
+ boltz = math.exp(delta_p_eV / (K_EV * T_kelvin))
136
+ coh = (tau_c / tau0) ** 0.25
137
+ phi = Phi0 * (M_kg ** beta) * boltz * coh
138
+ return {"phi": round(phi, 6),
139
+ "terms": {"network_M^beta": round(M_kg ** beta, 6),
140
+ "pmf_enhancement_exp(eta*dp/kT)": round(boltz, 6),
141
+ "coherence_(tau_c/tau0)^0.25": round(coh, 6),
142
+ "effective_barrier_eV": round(barrier, 6),
143
+ "delta_p_eV": round(delta_p_eV, 6)},
144
+ "inputs": {"M_kg": M_kg, "T_K": T_kelvin, "delta_p_mV": delta_p_mV, "tau_c": tau_c},
145
+ "status": "PROPOSED",
146
+ "note": "SZL unification (WBE network × MTE/PMF activation × coherence); Λ=Conjecture 1"}
147
+
148
+
149
+ # ---------------------------------------------------------------------------
150
+ # [SZL-COMPUTE] allometry analogue — neural/agent scaling as a 'metabolism'
151
+ # ---------------------------------------------------------------------------
152
+ def szl_compute_allometry(params_B: float, alpha: float = 0.076,
153
+ L0: float = 1.69) -> dict[str, Any]:
154
+ """SZL compute-allometry analogue: model loss L(N) ≈ L0 · N^(−α) (Kaplan et al. 2020,
155
+ α≈0.076 for params). We frame model 'capability metabolism' allometrically — compute
156
+ cost vs capability scales like a metabolic network. PROPOSED analogy, cited to Kaplan;
157
+ we claim only the allometric FRAMING, not the scaling law. [PROPOSED]"""
158
+ if params_B <= 0:
159
+ return {"loss": None, "status": "out_of_domain"}
160
+ N = params_B * 1e9
161
+ loss = L0 * (N ** -alpha)
162
+ return {"params_billions": params_B, "predicted_loss": round(loss, 6),
163
+ "exponent_alpha": alpha, "cite": "Kaplan et al. 2020 arXiv:2001.08361",
164
+ "framing": "compute capability as metabolic-network allometry (PROPOSED analogy)",
165
+ "status": "PROPOSED"}
166
+
167
+
168
+ # Universal scaling exponents across domains (for the comparator tab) — all CITED.
169
+ UNIVERSAL_EXPONENTS = [
170
+ {"domain": "biology", "quantity": "metabolic rate vs mass", "exponent": 0.75, "cite": "Kleiber 1932 / WBE 1997"},
171
+ {"domain": "biology", "quantity": "heart rate vs mass", "exponent": -0.25, "cite": "MTE 2004"},
172
+ {"domain": "biology", "quantity": "lifespan vs mass", "exponent": 0.25, "cite": "MTE 2004"},
173
+ {"domain": "urban", "quantity": "GDP vs population", "exponent": 1.15, "cite": "Bettencourt-West 2007"},
174
+ {"domain": "urban", "quantity": "infrastructure vs population", "exponent": 0.85, "cite": "Bettencourt-West 2007"},
175
+ {"domain": "compute", "quantity": "LM loss vs parameters", "exponent": -0.076, "cite": "Kaplan et al. 2020"},
176
+ ]
177
+
178
+
179
+ def summary() -> dict[str, Any]:
180
+ """Headline of the SZL scaling module + honest provenance/legend."""
181
+ return {
182
+ "title": "SZL Metabolic-Scaling — Kleiber/WBE/MTE + quantum-metabolism, unified (our own Φ)",
183
+ "status_legend": STATUS_LEGEND, "sources": SOURCES,
184
+ "doctrine": {"locked_proven": 8, "lambda": "Conjecture 1", "phi": "PROPOSED (not the formal Λ)",
185
+ "trust": "never 100%"},
186
+ "examples": {
187
+ "kleiber_70kg_human": round(kleiber(70.0), 2),
188
+ "heart_rate_70kg": round(heart_rate_scaling(70.0), 2),
189
+ "heart_rate_mouse_0.02kg": round(heart_rate_scaling(0.02), 2),
190
+ "szl_phi_demo": szl_phi(70.0, 310.0, 121.5, 6.05),
191
+ },
192
+ "universal_exponents": UNIVERSAL_EXPONENTS,
193
+ }
194
+
195
+
196
+ def register(app, ns: str) -> None:
197
+ """Attach the scaling routes under /api/<ns>/v1/scaling/* via add_api_route."""
198
+ base = f"/api/{ns}/v1/scaling"
199
+ app.add_api_route(f"{base}/summary", lambda: summary(), methods=["GET"])
200
+ app.add_api_route(f"{base}/kleiber", lambda M: {"M_kg": float(M), "B_kcal_day": kleiber(float(M))}, methods=["GET"])
201
+ app.add_api_route(f"{base}/mte",
202
+ lambda M, T="310": {"M_kg": float(M), "T_K": float(T), "B": mte_rate(float(M), float(T))},
203
+ methods=["GET"])
204
+ app.add_api_route(f"{base}/heart",
205
+ lambda M: {"M_kg": float(M), "bpm": round(heart_rate_scaling(float(M)), 2),
206
+ "lifespan_yr": round(lifespan_scaling(float(M)), 2),
207
+ "lifetime_beats_billion": round(heart_rate_scaling(float(M)) * 60 * 24 * 365 *
208
+ lifespan_scaling(float(M)) / 1e9, 3)},
209
+ methods=["GET"])
210
+ app.add_api_route(f"{base}/unified",
211
+ lambda M, T="310", dp="121.5", tau_c="6.05": szl_phi(float(M), float(T), float(dp), float(tau_c)),
212
+ methods=["GET"])
213
+ app.add_api_route(f"{base}/compute",
214
+ lambda params="70": szl_compute_allometry(float(params)), methods=["GET"])
215
+ app.add_api_route(f"{base}/exponents", lambda: {"exponents": UNIVERSAL_EXPONENTS}, methods=["GET"])
216
+
217
+
218
+ def _selftest() -> None:
219
+ # Kleiber: 70kg human ≈ 70 * 70^0.75 ≈ 1693 kcal/day (basal-ish ballpark)
220
+ h = kleiber(70.0)
221
+ assert 1500 < h < 1900, h
222
+ # Banavar D=3 -> 0.75
223
+ assert abs(banavar_exponent(3) - 0.75) < 1e-12
224
+ # MTE rate positive and increases with temperature
225
+ assert mte_rate(70.0, 310.0) > mte_rate(70.0, 300.0) > 0
226
+ # heart-rate scaling: mouse beats far faster than human
227
+ assert heart_rate_scaling(0.02) > heart_rate_scaling(70.0) > 0
228
+ # lifetime heartbeats ~ roughly invariant order of magnitude (mouse vs human within ~3x)
229
+ def beats(M): return heart_rate_scaling(M) * 60 * 24 * 365 * lifespan_scaling(M)
230
+ r = beats(0.02) / beats(70.0)
231
+ assert 0.3 < r < 3.0, r # near-constant lifetime beats (the famous result)
232
+ # pmf reproduces SZL verified two-ion value ballpark (121.5 mV at dΨ=150, dpH≈0.47)
233
+ p = proton_motive_force(150.0, 0.47, 310.0)
234
+ assert 110 < p < 135, p
235
+ # SZL Φ: PROPOSED, positive, PMF lowers barrier so Φ(with pmf) > Φ(no pmf)
236
+ phi_pmf = szl_phi(70.0, 310.0, 121.5, 6.05)["phi"]
237
+ phi_nopmf = szl_phi(70.0, 310.0, 0.0, 6.05)["phi"]
238
+ assert phi_pmf > phi_nopmf > 0, (phi_pmf, phi_nopmf)
239
+ # longer coherence -> higher Φ (coherence modulation monotone)
240
+ assert szl_phi(70.0, 310.0, 121.5, 12.0)["phi"] > szl_phi(70.0, 310.0, 121.5, 3.0)["phi"]
241
+ # compute allometry: bigger model -> lower loss
242
+ assert szl_compute_allometry(700)["predicted_loss"] < szl_compute_allometry(7)["predicted_loss"]
243
+ # out-of-domain guards
244
+ assert szl_phi(0, 310, 121.5, 6.05)["status"] == "out_of_domain"
245
+ print("szl_scaling: ALL OK (11 checks)")
246
+
247
+
248
+ if __name__ == "__main__":
249
+ _selftest()