File size: 6,689 Bytes
8cb741b
 
 
 
 
 
96ae7cc
 
8cb741b
 
 
 
 
 
 
 
96ae7cc
8cb741b
 
 
 
 
 
 
 
96ae7cc
 
 
8cb741b
 
 
 
 
 
96ae7cc
 
 
 
 
 
 
 
 
 
8cb741b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96ae7cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cb741b
 
 
 
 
 
 
 
 
 
 
 
96ae7cc
 
 
 
 
 
 
8cb741b
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 SZL Holdings
# Signed-off-by: Lutar, Stephen P. <stephenlutar2@gmail.com>
"""Command-lab fail-closed integrity kernel.

Stdlib only. Real SHA-256. Advisory Λ.
Energy joule MEASURED only when RAPL/NVML wraps a run. Never fabricated.
Locked-proven stays exactly 8. Λ uniqueness is Conjecture 1 OPEN.
proven_trust is False. Not a-11-oy.com. Not an ATO.
"""
from __future__ import annotations

import hashlib
import json
import math
import time
from datetime import datetime, timezone
from typing import Any, Sequence

LOCKED_EIGHT = ("F1", "F4", "F7", "F11", "F12", "F18", "F19", "F22")
YUYAY_FLOORS = (0.95, 0.95) + (0.90,) * 11
ZERO = "0" * 64
CHAIN_OPS = ("anatomy.brain", "anatomy.heart", "anatomy.skeleton")
proven_trust = False
BURN_MIN_S = 0.05
BURN_MAX_S = 3.0
BURN_DEFAULT_S = 1.0


def _sha256_hex(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def clamp_duration(duration_s: float | None) -> float:
    try:
        value = float(duration_s) if duration_s is not None else BURN_DEFAULT_S
    except (TypeError, ValueError):
        value = BURN_DEFAULT_S
    if not math.isfinite(value):
        value = BURN_DEFAULT_S
    return min(max(value, BURN_MIN_S), BURN_MAX_S)


def wgm(xs: Sequence[float], ws: Sequence[float]) -> float:
    if len(xs) != len(ws) or not xs:
        return 0.0
    if any((not math.isfinite(x)) or x <= 0.0 for x in xs):
        return 0.0
    if any((not math.isfinite(w)) or w < 0.0 for w in ws):
        return 0.0
    if abs(sum(ws) - 1.0) >= 1e-9:
        return 0.0
    value = math.exp(sum(w * math.log(x) for x, w in zip(xs, ws)))
    return value if math.isfinite(value) else 0.0


def evaluate_lambda(axes: Sequence[float]) -> dict[str, Any]:
    n = len(axes)
    weights = tuple(1.0 / n for _ in range(n)) if n else ()
    value = wgm(axes, weights)
    blocked = value == 0.0
    return {
        "value": float(value),
        "blocked": bool(blocked),
        "reason": "zero-routed" if blocked else "advisory pass — Conjecture 1 OPEN",
    }


def yawar_chain(seed: int, tamper: bool) -> dict[str, Any]:
    hops = []
    prev = ZERO
    for seq, op in enumerate(CHAIN_OPS):
        material = f"{seq}|{op}|{prev}|{int(seed)}"
        digest = _sha256_hex(material)
        hops.append({"seq": seq, "op": op, "prev": prev, "digest": digest})
        prev = digest
    if tamper and len(hops) > 1:
        hops[1] = dict(hops[1])
        hops[1]["prev"] = "deadbeef" + hops[1]["prev"][8:]
    walk = ZERO
    ok = True
    brk = None
    for hop in hops:
        expect = _sha256_hex(f"{hop['seq']}|{hop['op']}|{hop['prev']}|{int(seed)}")
        if hop["prev"] != walk or expect != hop["digest"]:
            ok = False
            brk = int(hop["seq"])
            break
        walk = hop["digest"]
    return {"hops": hops, "ok": ok, "head": hops[-1]["digest"] if hops else ZERO, "break_at": brk, "alg": "SHA-256"}


def evaluate_anatomy(*, zero_heart: bool = False, tamper_chain: bool = False, fabricate_joule: bool = False, seed: int = 11) -> dict[str, Any]:
    if proven_trust is True:
        raise RuntimeError("refusing proven_trust true")
    axes = list(YUYAY_FLOORS)
    if zero_heart:
        axes[0] = 0.0
    heart = evaluate_lambda(axes)
    chain = yawar_chain(int(seed), bool(tamper_chain))
    organs = [
        {"name": "BRAIN", "status": "LIVE", "honesty": "LIVE"},
        {"name": "HEART", "status": "DOWN" if heart["blocked"] else "LIVE", "honesty": "ADVISORY"},
        {"name": "CIRCULATORY", "status": "DOWN" if not chain["ok"] else "LIVE", "honesty": "LIVE"},
        {"name": "NERVOUS", "status": "DOWN" if fabricate_joule else "LIVE", "honesty": "UNAVAILABLE"},
        {"name": "SKELETON", "status": "LIVE", "honesty": "ADVISORY"},
    ]
    live = sum(1 for o in organs if o["status"] == "LIVE")
    blocked = any(o["status"] == "DOWN" for o in organs)
    return {
        "organs": organs,
        "live_count": live,
        "blocked": blocked,
        "verdict": "BLOCKED" if blocked else "ADVISORY_BODY",
        "energy": "UNAVAILABLE",
        "energy_j": None,
        "conjecture_1": "OPEN",
        "locked_proven": 8,
        "locked_ids": list(LOCKED_EIGHT),
        "proven_trust": False,
        "chain_head": chain["head"],
        "reason": (
            f"organ integrity {live}/5 LIVE · Λ advisory · energy UNAVAILABLE · Conjecture 1 OPEN"
            if not blocked
            else "organ integrity FAIL · fail closed"
        ),
        "checked_at": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
    }


def burn_kernel(*, duration_s: float = BURN_DEFAULT_S, seed: int = 11) -> dict[str, Any]:
    """Bounded SHA-256 storm so RAPL/NVML millijoule counters can tick.

    Board energy during the wrap is MEASURED. This is not isolated GPU FLOP
    joule and not a fabricated number. Organ cycle stays advisory.
    """
    target = clamp_duration(duration_s)
    digest = _sha256_hex(f"burn|{int(seed)}")
    rounds = 0
    t0 = time.perf_counter()
    while time.perf_counter() - t0 < target:
        digest = hashlib.sha256(f"{digest}|{rounds}|{seed}".encode()).hexdigest()
        rounds += 1
    dt = time.perf_counter() - t0
    anatomy = evaluate_anatomy(seed=int(seed))
    return {
        "ok": True,
        "kind": "sha256_storm",
        "rounds": rounds,
        "duration_s": dt,
        "digest": digest,
        "anatomy_head": anatomy["chain_head"],
        "anatomy_verdict": anatomy["verdict"],
        "proven_trust": False,
        "note": (
            "SHA-256 storm so NVML/RAPL can tick. Board energy during wrap, "
            "not isolated GPU FLOP. Never a fabricated joule."
        ),
    }


def selftest() -> dict[str, Any]:
    healthy = evaluate_anatomy(seed=11)
    assert healthy["live_count"] == 5
    assert healthy["blocked"] is False
    assert healthy["energy"] == "UNAVAILABLE"
    assert healthy["proven_trust"] is False
    z = evaluate_anatomy(zero_heart=True)
    assert z["blocked"] is True
    t = evaluate_anatomy(tamper_chain=True)
    assert t["blocked"] is True
    j = evaluate_anatomy(fabricate_joule=True)
    assert j["blocked"] is True
    burned = burn_kernel(duration_s=0.05, seed=11)
    assert burned["ok"] is True
    assert burned["rounds"] >= 1
    assert burned["kind"] == "sha256_storm"
    assert clamp_duration(99) == BURN_MAX_S
    assert clamp_duration(-1) == BURN_MIN_S
    return {"ok": True, "cases": 7, "healthy_head": healthy["chain_head"], "burn_rounds": burned["rounds"]}


if __name__ == "__main__":
    print(json.dumps(selftest(), indent=2))