zephirum 2.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
battery_ci.py ADDED
@@ -0,0 +1,95 @@
1
+ # -*- coding: utf-8 -*-
2
+ """ZQ-GATE CI battery — the trivalent decision battery + receipt verification.
3
+
4
+ Runs entirely offline (noiseless kernel, no IBM account needed) so any CI can
5
+ use it. Modes via env ZQG_MODE (all | battery | verify-receipts):
6
+ battery -> run the trivalent decision battery: constant-1 => 1,
7
+ constant-0 => 0, balanced => REFUSED, 1 oracle call each.
8
+ verify-receipts-> recompute the SHA3-256 seal of every sealed receipt in
9
+ experiments/ (Z-QEA, clean canonical rule).
10
+ Exit code 0 = all pass. Any failure exits 1 — nothing passes silently.
11
+ """
12
+ import os, sys, json, hashlib, glob
13
+
14
+ HERE = os.path.dirname(os.path.abspath(__file__))
15
+ sys.path.insert(0, os.path.join(HERE, "..", "src"))
16
+
17
+ MODE = (os.environ.get("ZQG_MODE") or "all").strip().lower()
18
+ FAILED = []
19
+
20
+
21
+ def run_battery():
22
+ from zyql_quantum_gate import ZYQLQuantumGate
23
+ cases = [
24
+ ("constant-1", lambda x: 1, "1"),
25
+ ("constant-0", lambda x: 0, "0"),
26
+ ("balanced", lambda x: x ^ 1, "REFUSED"),
27
+ ]
28
+ print("== ZQ-GATE trivalent decision battery (noiseless, canonical) ==")
29
+ for name, oracle, expected in cases:
30
+ r = ZYQLQuantumGate(3, oracle).run_quantum()
31
+ ok = str(r["decision"]) == expected
32
+ print(f"[{'PASS' if ok else 'FAIL'}] {name}: decision={r['decision']} "
33
+ f"(expected {expected}) p0={r.get('p0')} calls={r.get('oracle_calls')}")
34
+ if not ok:
35
+ FAILED.append(f"battery:{name}")
36
+
37
+
38
+ def canon(payload):
39
+ return json.dumps(payload, sort_keys=True, ensure_ascii=True, default=str)
40
+
41
+
42
+ def verify_receipt(path):
43
+ try:
44
+ rec = json.load(open(path))
45
+ except Exception as e:
46
+ print(f"[FAIL] {os.path.basename(path)}: malformed ({e})")
47
+ FAILED.append(path)
48
+ return
49
+ declared = rec.get("selo_sha3_256")
50
+ if not declared:
51
+ print(f"[FAIL] {os.path.basename(path)}: no selo_sha3_256")
52
+ FAILED.append(path)
53
+ return
54
+ if isinstance(rec.get("payload"), dict) and "selo_sha3_256" in rec:
55
+ # formato aninhado (Rodada G em diante): o selo cobre rec["payload"]
56
+ payload = rec["payload"]
57
+ else:
58
+ payload = {k: v for k, v in rec.items() if k != "selo_sha3_256"}
59
+ recomputed = hashlib.sha3_256(canon(payload).encode()).hexdigest()
60
+ ok = declared == recomputed
61
+ print(f"[{'PASS' if ok else 'FAIL'}] {os.path.basename(path)}: "
62
+ f"{'SELO ÍNTEGRO' if ok else 'SELO ROMPIDO'}")
63
+ if not ok:
64
+ FAILED.append(path)
65
+
66
+
67
+ def run_verify():
68
+ print("== ZQ-GATE receipt verification (Z-QEA, SHA3-256) ==")
69
+ root = os.path.join(HERE, "..")
70
+ paths = sorted(glob.glob(os.path.join(root, "experiments", "**", "*.json"), recursive=True))
71
+ sealed = [p for p in paths if "job_meta" not in os.path.basename(p)]
72
+ any_sealed = False
73
+ for p in sealed:
74
+ try:
75
+ d = json.load(open(p))
76
+ if isinstance(d, dict) and d.get("selo_sha3_256"):
77
+ verify_receipt(p)
78
+ any_sealed = True
79
+ except Exception:
80
+ verify_receipt(p)
81
+ any_sealed = True
82
+ if not any_sealed:
83
+ print("(no sealed receipts found in experiments/ — nothing to verify)")
84
+
85
+
86
+ if MODE in ("all", "battery"):
87
+ run_battery()
88
+ if MODE in ("all", "verify-receipts"):
89
+ run_verify()
90
+
91
+ print()
92
+ if FAILED:
93
+ print("ZQ-GATE: FAIL —", len(FAILED), "failure(s). Nothing passes silently.")
94
+ sys.exit(1)
95
+ print("ZQ-GATE: ALL PASS — decisions sealed, receipts intact.")
oq3.py ADDED
@@ -0,0 +1,84 @@
1
+ """
2
+ Zephyron → OpenQASM 3 transpiler.
3
+ Zephyron is the circuit language of the Zephyrum ecosystem; OpenQASM 3 is
4
+ the interchange language IBM Quantum (Qiskit Runtime) ingests. This bridge
5
+ is the honest path to real IBM hardware: IBM will never run Zephyron
6
+ natively, but it accepts its compiled output.
7
+ """
8
+
9
+ def to_openqasm3(gates, nqubits):
10
+ """gates: list of strings as produced by QCircuit.gates_applied,
11
+ e.g. 'H(0)', 'X(1)', 'CNOT(0->1)', 'CZ(0,1)', 'T(1)'."""
12
+ lines = ["OPENQASM 3.0;", 'include "stdgates.inc";',
13
+ f"qubit[{nqubits}] q;", f"bit[{nqubits}] c;"]
14
+ for g in gates:
15
+ name, rest = g.split("(", 1)
16
+ args = rest.rstrip(")").replace(" ", "")
17
+ if name == "CNOT":
18
+ c, t = args.split("->")
19
+ lines.append(f"cx q[{c}], q[{t}];")
20
+ elif name == "CZ":
21
+ c, t = args.split(",")
22
+ lines.append(f"cz q[{c}], q[{t}];")
23
+ elif name == "Z":
24
+ q = args
25
+ lines.append(f"z q[{q}];")
26
+ else:
27
+ q = args
28
+ lines.append(f"{name.lower()} q[{q}];")
29
+ lines.append("c = measure q;")
30
+ return "\n".join(lines) + "\n"
31
+
32
+ if __name__ == "__main__":
33
+ from programs import bell, ghz, grover2
34
+ for name, prog in (("bell", bell), ("ghz", ghz), ("grover", grover2)):
35
+ qc, _ = prog(shots=1)
36
+ oq3 = to_openqasm3(qc.gates_applied, qc.n)
37
+ print(f"=== {name} ===")
38
+ print(oq3)
39
+
40
+
41
+ # --- OpenQASM 3 -> Zephyron importer (uses the reference parser) ---
42
+ def from_openqasm3(src):
43
+ """Parse valid OpenQASM 3 (e.g. produced by IBM tools or our own
44
+ transpiler) into a Zephyron QCircuit. Returns (circuit, gates)."""
45
+ import math
46
+ from openqasm3.parser import parse
47
+ from openqasm3.ast import (QuantumGate, QubitDeclaration,
48
+ IndexedIdentifier, IntegerLiteral, UnaryExpression)
49
+ from zquantum import QCircuit
50
+
51
+ nq = 0
52
+ gates = []
53
+ for st in parse(src).statements:
54
+ if isinstance(st, QubitDeclaration):
55
+ size = st.size
56
+ if isinstance(size, UnaryExpression):
57
+ nq = -size.expression.value
58
+ else:
59
+ nq = size.value
60
+ elif isinstance(st, QuantumGate):
61
+ name = st.name.name
62
+ qubits = []
63
+ for q in st.qubits:
64
+ if isinstance(q, IndexedIdentifier):
65
+ idx = q.indices[0][0]
66
+ v = idx.value if hasattr(idx, "value") else int(str(idx))
67
+ qubits.append(v)
68
+ angles = [a.value for a in st.arguments]
69
+ if name in ("cx", "cnot"):
70
+ gates.append(f"CNOT({qubits[0]}->{qubits[1]})")
71
+ elif name == "cz":
72
+ gates.append(f"CZ({qubits[0]},{qubits[1]})")
73
+ elif name == "swap":
74
+ gates.append(f"SWAP({qubits[0]},{qubits[1]})")
75
+ elif name == "ccx":
76
+ gates.append(f"TOFFOLI({qubits[0]},{qubits[1]}->{qubits[2]})")
77
+ elif name in ("rx", "ry", "rz"):
78
+ gates.append(f"{name.upper()}({qubits[0]},{angles[0]})")
79
+ elif name == "id":
80
+ continue
81
+ else:
82
+ gates.append(f"{name.upper()}({qubits[0]})")
83
+ qc = QCircuit.from_gates(nq, gates)
84
+ return qc, gates
quantum_types.py ADDED
@@ -0,0 +1,133 @@
1
+ """
2
+ ZEPHIRUM QUANTUM TYPES (v1.0.0, 12/10/2026) — qbit as a first-class type.
3
+ Prototype pre-parser: the type layer is real (wraps the state-vector kernel),
4
+ the Zephirum interpreter wiring is the next step (declared limitation).
5
+
6
+ What it enforces:
7
+ 1. qbit declarations, unitary application, entanglement, measurement
8
+ 2. NO-CLONING enforced by the type: assigning/copying a quantum value
9
+ raises CompileError at the type check, before any execution
10
+ 3. qif: quantum conditional via controlled operation (no collapse)
11
+ """
12
+ import sys, os, json, time
13
+ try:
14
+ from zquantum import QCircuit
15
+ except ImportError: # in-tree, no install
16
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
17
+ from zquantum import QCircuit
18
+
19
+ class CompileError(Exception):
20
+ pass
21
+
22
+ class QType:
23
+ """First-class quantum value. Lives in one circuit; cannot be copied."""
24
+ def __init__(self, circ, index, size=1):
25
+ self.circ, self.index, self.size = circ, index, size
26
+
27
+ # no-cloning enforced by the type: any copy attempt fails at compile time
28
+ def __copy__(self): raise CompileError("NO_CLONING: quantum value cannot be copied")
29
+ def __deepcopy__(self, m): raise CompileError("NO_CLONING: quantum value cannot be copied")
30
+ def clone(self): raise CompileError("NO_CLONING: quantum value cannot be copied")
31
+
32
+
33
+ class QuantumLang:
34
+ """Mini pre-parser layer: qbit / H / CNOT / qif / measure."""
35
+
36
+ def __init__(self, n):
37
+ self.circ = QCircuit(n)
38
+ self.n = n
39
+ self.vars = {}
40
+ self.classical_copies = [] # legal: measured (collapsed) results
41
+
42
+ def qbit(self, name):
43
+ if name in self.vars: raise CompileError("redeclaration of qbit " + name)
44
+ idx = len(self.vars)
45
+ self.vars[name] = QType(self.circ, idx)
46
+ return self.vars[name]
47
+
48
+ def h(self, name):
49
+ self.circ.h(self.vars[name].index)
50
+
51
+ def x(self, name):
52
+ self.circ.x(self.vars[name].index)
53
+
54
+ def cnot(self, a, b):
55
+ self.circ.cnot(self.vars[a].index, self.vars[b].index)
56
+
57
+ def qif(self, cond_name, then_op):
58
+ """Quantum conditional: controlled operation, NO measurement, NO collapse.
59
+ then_op is a single-qubit X for the prototype (control decomposition)."""
60
+ if then_op.upper() not in ("X",):
61
+ raise CompileError("qif prototype supports controlled-X only")
62
+ self.circ.cnot(self.vars[cond_name].index,
63
+ self._last_free_target(cond_name))
64
+
65
+ def _last_free_target(self, not_this):
66
+ targets = [v for k, v in self.vars.items() if v.index != self.vars[not_this].index]
67
+ return targets[-1].index
68
+
69
+ def measure(self, name, shots=4096, seed=11):
70
+ """Measurement collapses: the RESULT is classical and copyable."""
71
+ c = self.circ.measure_all(shots=shots, seed=seed)
72
+ self.classical_copies.append({name: c})
73
+ return c
74
+
75
+ def assign(self, dst, src):
76
+ """Type-checked assignment: quantum -> quantum is NO_CLONING (CompileError)."""
77
+ if src in self.vars:
78
+ raise CompileError("NO_CLONING: assignment of quantum value '%s' rejected by the type" % src)
79
+ raise CompileError("unknown assignment %s = %s" % (dst, src))
80
+
81
+
82
+ def main():
83
+ proof = {"module": "quantum_types.py", "version": "1.0.0",
84
+ "date": time.strftime("%Y-%m-%d %H:%M:%S"), "tests": []}
85
+
86
+ # 1. entanglement: Bell state 1/2 + 1/2
87
+ lang = QuantumLang(2)
88
+ a, b = lang.qbit("a"), lang.qbit("b")
89
+ lang.h("a"); lang.cnot("a", "b")
90
+ c = lang.measure("a", shots=4096, seed=42)
91
+ p00, p11 = c.get("|00>", 0) / 4096, c.get("|11>", 0) / 4096
92
+ ent = abs(p00 - 0.5) < 0.02 and abs(p11 - 0.5) < 0.02
93
+ proof["tests"].append({"name": "entanglement (Bell 1/2+1/2)",
94
+ "p00": round(p00, 4), "p11": round(p11, 4), "PASS": ent})
95
+
96
+ # 2. no-cloning enforced by the type
97
+ try:
98
+ lang2 = QuantumLang(2)
99
+ lang2.qbit("q"); lang2.qbit("r")
100
+ lang2.assign("r", "q") # must raise CompileError
101
+ nc = False
102
+ except CompileError as e:
103
+ nc = "NO_CLONING" in str(e)
104
+ proof["tests"].append({"name": "no-cloning rejected by type (assign)", "PASS": nc})
105
+ try:
106
+ lang3 = QuantumLang(2)
107
+ q = lang3.qbit("q")
108
+ q.clone() # must raise
109
+ nc2 = False
110
+ except CompileError as e:
111
+ nc2 = "NO_CLONING" in str(e)
112
+ proof["tests"].append({"name": "no-cloning rejected by type (clone)", "PASS": nc2})
113
+
114
+ # 3. qif: controlled operation without collapse
115
+ lang4 = QuantumLang(2)
116
+ lang4.qbit("ctrl"); lang4.qbit("tgt")
117
+ lang4.h("ctrl") # superposition on control
118
+ lang4.qif("ctrl", "X") # controlled-X: entangles, no measurement
119
+ st = lang4.circ.state
120
+ amps = [round(abs(x) ** 2, 4) for x in st]
121
+ qif_ok = abs(amps[0] - 0.5) < 0.01 and abs(amps[3] - 0.5) < 0.01 and amps[1] < 1e-9
122
+ proof["tests"].append({"name": "qif: controlled-X, no collapse (Bell from superposed ctrl)",
123
+ "probabilities": amps, "PASS": qif_ok})
124
+
125
+ proof["all_PASS"] = all(t["PASS"] for t in proof["tests"])
126
+ out = os.path.join(os.path.dirname(__file__), "..", "lab", "prova_quantum_types.json")
127
+ json.dump(proof, open(out, "w"), indent=1)
128
+ for t in proof["tests"]:
129
+ print("%-55s PASS=%s" % (t["name"], t["PASS"]))
130
+ print("ALL_PASS:", proof["all_PASS"])
131
+
132
+ if __name__ == "__main__":
133
+ main()
shot_auditor.py ADDED
@@ -0,0 +1,67 @@
1
+ # -*- coding: utf-8 -*-
2
+ """SHOT AUDITOR — controlador trivalente de continuacao de campanhas quanticas.
3
+
4
+ Decide CONTINUE / STOP / REFUSED apos cada profundidade de uma campanha,
5
+ com banda declarada (IC 95% do gradiente) e regra de parada selada ANTES
6
+ dos dados. Peeking em runtime => REFUSED (binding via stopping_rule_check).
7
+ """
8
+ import math
9
+
10
+ Z95 = 1.959963985 # quantil 95% (declarado, selado junto com a regra)
11
+
12
+ def gradiente_band(p_obs_counts, shots):
13
+ """Banda de ruido do gradiente a partir das contagens das DUAS energias.
14
+
15
+ p_obs_counts: (counts_mais, counts_menos) — histogramas de E(theta+pi/2)
16
+ e E(theta-pi/2). E = <Z0> + <Z1Z2> medido dos counts (bitstring q3q2q1q0).
17
+ Retorna (gradiente, sigma_g, banda_g): banda_g = Z95 * sigma_g.
18
+ """
19
+ def energia(counts):
20
+ tot = sum(counts.values())
21
+ e = 0.0
22
+ for bs, c in counts.items():
23
+ b = bs.replace(" ", "")
24
+ z0 = 1 - 2 * int(b[-1]) # Z0 (bit menos significativo)
25
+ z1 = 1 - 2 * int(b[-2]) # Z1
26
+ z2 = 1 - 2 * int(b[-3]) # Z2
27
+ e += c * (z0 + z1 * z2)
28
+ return e / tot
29
+
30
+ def var_energia(counts):
31
+ tot = sum(counts.values())
32
+ v = 0.0
33
+ for bs, c in counts.items():
34
+ b = bs.replace(" ", "")
35
+ z0 = 1 - 2 * int(b[-1])
36
+ z1 = 1 - 2 * int(b[-2])
37
+ z2 = 1 - 2 * int(b[-3])
38
+ v += c * (z0 + z1 * z2) ** 2
39
+ m = energia(counts)
40
+ return (v / tot - m * m) / tot
41
+
42
+ e_m, e_n = energia(p_obs_counts[0]), energia(p_obs_counts[1])
43
+ v_m, v_n = var_energia(p_obs_counts[0]), var_energia(p_obs_counts[1])
44
+ g = (e_m - e_n) / 2.0
45
+ sigma_g = math.sqrt(v_m + v_n) / 2.0
46
+ return g, sigma_g, Z95 * sigma_g
47
+
48
+ def audit_step(g, banda_g, shots_da_profundidade, selo):
49
+ """Decisao trivalente da profundidade atual. Regra SELADA antes dos dados:
50
+ |g| <= banda_g => STOP (gradiente indistinguivel de zero no IC 95%)
51
+ |g| > banda_g => CONTINUE (sinal acima da banda)
52
+ Incoerencia com o protocolo selado => REFUSED.
53
+ """
54
+ chk = stopping_rule_check(selo, {"shots_observed": shots_da_profundidade,
55
+ "decision_at_shot": shots_da_profundidade})
56
+ if chk["decision"] == "REFUSED":
57
+ return {"decisao": "REFUSED", "motivo": chk.get("refusal_reason", "?"),
58
+ "regra": chk.get("rule", ""), "g": g, "banda": banda_g}
59
+ if abs(g) <= banda_g:
60
+ return {"decisao": "STOP", "motivo": "GRADIENTE_DENTRO_DA_BANDA",
61
+ "regra": "IC 95% do gradiente contem zero: pagar mais shots "
62
+ "e estatistica de mais para um sinal que ja e ruido",
63
+ "g": g, "banda": banda_g}
64
+ return {"decisao": "CONTINUE", "motivo": "GRADIENTE_ACIMA_DA_BANDA",
65
+ "g": g, "banda": banda_g}
66
+
67
+ from zyql_robust import stopping_rule_check # noqa: E402 (selo/runtime binding)
@@ -0,0 +1,291 @@
1
+ Metadata-Version: 2.4
2
+ Name: zephirum
3
+ Version: 2.1.0
4
+ Summary: ZEPHIRUM: Lisp-style quantum programming language with the ZYQL trivalent decision core (1/0/REFUSED)
5
+ Author-email: Reginaldo Gonçalves <builderquantunxia@gmail.com>
6
+ License-Expression: MIT
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: numpy
11
+ Requires-Dist: lark
12
+ Requires-Dist: qiskit>=2.6
13
+ Provides-Extra: hardware
14
+ Requires-Dist: qiskit-aer>=0.17; extra == "hardware"
15
+ Requires-Dist: qiskit-ibm-runtime>=0.50; extra == "hardware"
16
+ Provides-Extra: interop
17
+ Requires-Dist: cirq>=1.4; extra == "interop"
18
+ Provides-Extra: test
19
+ Requires-Dist: qiskit-qasm3-import>=0.5; extra == "test"
20
+ Dynamic: license-file
21
+
22
+ <p align="center"><img src="assets/social-preview-1280x640.png" alt="ZYQL: Exact-decision language" width="640"></p>
23
+
24
+ # ZEPHIRUM
25
+
26
+ **The quantum programming language with receipts.** ZYQL, its decision core, returns one of three verdicts — `1` (permitted), `0` (forbidden) or `REFUSED` (insufficient confidence) — and seals every decision in a verifiable receipt.
27
+
28
+ ![version](https://img.shields.io/badge/version-2.1.0-6e46b8)
29
+ ![license](https://img.shields.io/badge/license-MIT-blue)
30
+ ![kernel](https://img.shields.io/badge/kernel-statevector%20%5Bre%2Cim%5D%20float64-cyan)
31
+ ![DOI](https://img.shields.io/badge/DOI-10.5281%2Fzenodo.23632019-gold)
32
+ [![CI](https://github.com/SerenaSolutions/zephirum-lang/actions/workflows/ci.yml/badge.svg)](https://github.com/SerenaSolutions/zephirum-lang/actions/workflows/ci.yml)
33
+ [![CodeQL](https://github.com/SerenaSolutions/zephirum-lang/actions/workflows/codeql.yml/badge.svg)](https://github.com/SerenaSolutions/zephirum-lang/actions/workflows/codeql.yml)
34
+ ![python](https://img.shields.io/badge/python-3.10%20%7C%203.11-blue)
35
+
36
+ **Contents** — [What it is](#what-it-is) · [Quickstart](#quickstart) · [Evidence](#evidence) · [Architecture](#architecture) · [Tests & reproducibility](#tests--reproducibility) · [Learn](#learn) · [Layout](#layout) · [Scope & honest limits](#honest-scope) · [Citation](#citation)
37
+
38
+ ---
39
+
40
+ ## What it is
41
+
42
+ ZEPHIRUM is a small quantum programming language. ZYQL is its decision algorithm:
43
+ every computational decision is trivalent — `1` (permitted), `0` (forbidden),
44
+ `REFUSED` (input-dependent or insufficient confidence) — and carries a sealed
45
+ receipt (SHA3-256 integrity seal, hash proves content integrity, not authorship).
46
+ ML-DSA-44 / FIPS 204 signatures are a DECLARED ROADMAP item — to be implemented
47
+ with an accredited module and HSM-held keys, never hand-rolled (see [docs/receipts.md](docs/receipts.md)).
48
+
49
+ Decisions are produced by Deutsch–Jozsa interference, one oracle call, with a
50
+ declared noise band (±0.15). Nothing executes silently: unknown syntax raises
51
+ an explicit error. Simulation mode is labeled as simulation.
52
+
53
+ - **Trivalent semantics** — refusal is a first-class verdict, not an exception.
54
+ - **Receipts by construction** — every decision can be sealed (Z-QEA, SHA3-256).
55
+ - **Hardware-verified** — measured on IBM Heron with job IDs published below.
56
+
57
+ ## Quickstart
58
+
59
+ ```bash
60
+ git clone https://github.com/SerenaSolutions/zephirum-lang.git && cd zephirum-lang
61
+ pip install -e . # or: PYTHONPATH=src
62
+ ```
63
+
64
+ ```python
65
+ from zyql_quantum_gate import ZYQLQuantumGate
66
+
67
+ gate = ZYQLQuantumGate(3, lambda x: x ^ 1) # balanced oracle
68
+ r = gate.run_quantum(shots=2048)
69
+ print(r["decision"], r.get("refusal_reason", "")) # REFUSED BALANCED_ORACLE
70
+ ```
71
+
72
+ ```bash
73
+ zyql-decide --oracle balanced --shots 512 # CLI runtime, Hoeffding error bound
74
+ python3 src/zyql_lisp.py examples/hello_world.zph # language front-end + sealed receipt
75
+ ```
76
+
77
+ The baptism of the language — a trivalent greeting, sealed by ZEPHIRUM itself:
78
+
79
+ ```lisp
80
+ ;; hello_world.zph — ZEPHIRUM v2 (Lisp)
81
+ (hello "Zephirum")
82
+ (seal "examples/hello_world.receipt.json")
83
+ ```
84
+
85
+ ```console
86
+ $ python3 src/zyql_lisp.py examples/hello_world.zph
87
+ Hello, Zephirum! | decisao = 1
88
+ SELO: <sha3-256 do recibo — carimbo temporal, varia por execucao>
89
+ ```
90
+
91
+ The `hello` form prints the greeting and returns the trivalent verdict `1`
92
+ (a greeting is always permitted). The `seal` form writes a Z-QEA receipt
93
+ (SHA3-256) of everything executed — the Hello World carries a sealed receipt,
94
+ as every decision in this house does. Source: [`examples/hello_world.zph`](examples/hello_world.zph).
95
+
96
+ ## Evidence
97
+
98
+ ![S3 fusion channels measured on IBM Heron](assets/proofs/s3-fusion-hardware.png)
99
+
100
+ *Real-data figure: theoretical braid curves (gold: B_R∘B_S, violet: B_S∘B_R) and the
101
+ points measured on IBM Heron `ibm_fez` — 98.1% vs 95.8%. The braid order is
102
+ distinguishable on silicon. Full detail: [docs/PROOFS.md](docs/PROOFS.md).*
103
+
104
+ ![Non-Abelian anyon braiding — AI art](assets/proofs/non-abelian-braids-art.png)
105
+
106
+ *Hero art (declared: AI-generated) — braided world-lines of non-Abelian anyons
107
+ converging into three fusion channels, the geometry the experiments probe.*
108
+
109
+ ### Proofs of concept — non-Abelian anyons (S3 qutrit miniature)
110
+
111
+ | Claim | Mode | Result | Receipt |
112
+ |-------|------|--------|---------|
113
+ | Fusion space is 3-dimensional (qutrit in 2 qubits) | noiseless | exact 1/3+1/3+1/3, forbidden channel vetoed | [sealed receipt](experiments/s3_qutrit_final_receipt.json) |
114
+ | Braiding is non-Abelian (order matters) | noiseless | commutator L1 = 6 exact; B_R∘B_S → ch2, B_S∘B_R → ch1 | same |
115
+ | Noiseless round | noiseless | exact-zero deviation vs theory (canonical rationals) | same |
116
+ | ZYQL trivalent decisions 1 / 0 / REFUSED | **IBM Heron** | **3/3 PASS** (job `dbbugbk24mrc73cif420`) | [battery receipt](experiments/zyql_hardware_battery.json) |
117
+ | Braid order measured on real hardware | **IBM Heron** | **98.1% vs 95.8%** (job `dbbueufi0auc73dtp7og`) | [master receipt](experiments/s3_qutrit_final_receipt.json) |
118
+ | **Shots-to-verdict efficiency** | **IBM Heron** | **256 shots** to a first-step verdict — **96.88% savings vs 8192** | receipt `28f406202e9d125a` (issue #40) |
119
+
120
+ Receipt seal (SHA3-256): `a44192463ea669564a3da51728c8577e59e5684c67cf2d48f7a95442d548476a` — verify it yourself: `python3 .github/actions/zqea-verify/zqea_verify.py experiments/s3_qutrit_final_receipt.json`
121
+ In language: [`examples/s3_qutrit.zph`](examples/s3_qutrit.zph).
122
+
123
+ Verified on real hardware (IBM Heron `ibm_fez`, cited as test laboratory with
124
+ verifiable job IDs; no endorsement claimed):
125
+
126
+ - Constant purpose: measured p(000)=0.9844 (job `db6ded84qg6s73c4jvug`)
127
+ - S3 qutrit miniature: fusion channels (qutrit-in-qubits) + braiding non-commutativity,
128
+ noiseless with exact-zero deviation and on hardware: ch2=98.1% (RS) vs ch1=95.8% (SR),
129
+ full ZYQL battery 3/3 PASS on `ibm_fez` (jobs `dbbueufi0auc73dtp7og`, `dbbugbk24mrc73cif420`;
130
+ Z-QEA receipt sealed, see `experiments/`)
131
+ - Balanced purpose: p(000)=0.0000, orthogonal outcome 93.9%
132
+ - Same-task confrontation vs textbook Qiskit (job `db6dklcvf2bc73d122t0`):
133
+ Zephyron transpiles to depth 2 / 0 two-qubit gates vs depth 10 / 3 CZ
134
+
135
+ Benchmark suite: [`benchmarks/`](benchmarks/) (public comparative benchmark, issue #28).
136
+
137
+ ## Architecture
138
+
139
+ ```
140
+ program (.zph, Lisp) ──► front-end parser ──► canonical decision form
141
+ │ │
142
+ │ Deutsch–Jozsa interference
143
+ │ (one oracle call, noise band ±0.15)
144
+ │ │
145
+ │ trivalent verdict: 1 / 0 / REFUSED
146
+ │ │
147
+ └──────────────► Z-QEA receipt ◄─────────────┘
148
+ (SHA3-256 seal + machine-readable refusal_reason)
149
+ ```
150
+
151
+ The repository ships the language heart only: kernel (state-vector, `[re,im]`
152
+ float64), OpenQASM 3 transpiler, trivalent gate, quantum types (no-cloning
153
+ enforced) and the receipt chain. See [Honest scope](#honest-scope).
154
+
155
+ The language:
156
+
157
+ ```
158
+ circuit bell {
159
+ qubit[2] q;
160
+ H q[0];
161
+ CNOT q[0] -> q[1];
162
+ }
163
+ ```
164
+
165
+ ## Tests & reproducibility
166
+
167
+ - **13 test suites** (`tests/`): canonical rational battery, certified decisions,
168
+ frontiers, KEM, Lisp regression, meta, multiple-testing correction,
169
+ runtime, shot auditor, Z-QEA verifier, hardware rounds.
170
+ - **CI matrix**: Python 3.10 and 3.11 on every push and pull request, with
171
+ `PYTHONHASHSEED=0` for reproducible runs; **CodeQL** static analysis;
172
+ **signed releases with build provenance** (SLSA attestation); a dedicated
173
+ **ZQ-GATE self-test** workflow.
174
+ - **Statistical discipline**: multiple-comparison correction is part of the test
175
+ battery — verdicts are not claimed on uncorrected p-values.
176
+ - **Verifiable by construction**: every hardware claim above points to a sealed
177
+ receipt and a job ID; receipts are re-verifiable with
178
+ `.github/actions/zqea-verify/zqea_verify.py`.
179
+ - Published testing roadmap (fuzzing the front-end, unitary-equivalence
180
+ assertions, executed notebooks, coverage gate): tracked in issues.
181
+
182
+ ## Learn
183
+
184
+ - [docs/LEARN.md](docs/LEARN.md) — progressive tutorial: first decision to sealed hardware receipts
185
+ - [docs/COOKBOOK.md](docs/COOKBOOK.md) — copy-paste recipes, every one executed and recorded
186
+ - [docs/MIGRATION.md](docs/MIGRATION.md) — embedding Zephirum in Python, C and CI pipelines
187
+ - [docs/PROOFS.md](docs/PROOFS.md) — hardware proofs, figures and receipts
188
+ - [docs/MATURITY.md](docs/MATURITY.md) — component-by-component maturity
189
+
190
+ ## Layout
191
+
192
+ - `src/` — kernel (state-vector), OpenQASM 3 transpiler, trivalent gate,
193
+ quantum types (no-cloning enforced), neural RAG layer, runtime (`zyql_runtime`)
194
+ - `tests/` — 13 suites (see above)
195
+ - `examples/` — `hello_world.zph`, `bell.zph`, `grover.zph`, `dj_constant.zph`, `s3_qutrit.zph`
196
+ - `benchmarks/` — public comparative benchmark suite
197
+ - `notebooks/` — scientific presentation layer
198
+ - `experiments/` — hardware rounds and sealed receipts (job IDs)
199
+ - `docs/` — language reference, receipt specification, proofs, maturity, dossier
200
+ - `playground/` — browser playground assets · `site/` — docs site · `paper/` — preprint sources
201
+ - `zephirum-vscode/` — VS Code extension for `.zph`
202
+ - `docker/` — reproducible container
203
+
204
+ ## Technical Dossier
205
+
206
+ A consolidated, receipt-cited dossier of the project — what it is, what has been measured on real quantum hardware, the public m50 commitment, Industry 5.0 applications and the declared honest limits: **[docs/DOSSIER.md](docs/DOSSIER.md)**
207
+
208
+
209
+ ## Self-verified device decision (new, 2026-10-29)
210
+
211
+ A decisão trivalente agora roda **na QPU** com a própria QPU certificando a execução:
212
+
213
+ - **Auto-verificação (espelho C†)** no mesmo job — taxa de zeros medida vira `selfcheck_p0` no recibo; abaixo do limiar ⇒ `REFUSED`.
214
+ - **Evidência sequencial** com regra de parada (alpha-spending) declarada **antes** da execução.
215
+ - **Recibo** com protocolo + contagens por lote + `job_id`, selado SHA3-256.
216
+
217
+ | Oráculo | Veredito | p0 | selfcheck | Shots | job_id (ibm_fez) |
218
+ |---|---|---|---|---|---|
219
+ | constante | **1** | 0.992 | 0.969 | 128 | `dbhm3ao1h92s73821mm0` |
220
+ | balanceado | **0** | 0.016 | 0.992 | 128 | `dbhm3ik2d77s739d10j0` |
221
+
222
+ Especificação completa: **[docs/SELFVERIFIED.md](docs/SELFVERIFIED.md)** · recibos em `experiments/selfcheck_ibm_fez_20261029/`.
223
+
224
+
225
+ ## Refusal witness — abstenção com prova (new, 2026-10-29)
226
+
227
+ `REFUSED` deixa de ser "não sei" e vira "não sei **porque** a evidência não fecha":
228
+ a TVD entre a distribuição ideal (referência exata) e a medida no dispositivo tem
229
+ intervalo de confiança declarado **antes** da execução.
230
+
231
+ | Dispositivo | Shots | TVD | Janela | ε | Veredito | job_id |
232
+ |---|---|---|---|---|---|---|
233
+ | ibm_fez | 4096 | 0.0317 | [0.000, 0.104] | 0.10 | **REFUSED** | `dbhn296ne4hc73bd7u1g` |
234
+ | ibm_marrakesh | 8192 | 0.0198 | [0.000, 0.071] | 0.10 | **1 CERTIFICADO** | `dbhn8hs2d77s739d32lg` |
235
+
236
+ O primeiro voo absteve; com o dobro de evidência, certificou. Especificação:
237
+ **[docs/WITNESS.md](docs/WITNESS.md)** · recibos em `experiments/witness_20261029/`.
238
+
239
+
240
+ ## Hardware protocols (2026-10-29)
241
+
242
+ Protocolos pré-declarados, executados no plano Open com recibo selado
243
+ (`docs/PROTOCOLS.md`):
244
+
245
+ | Protocolo | Medida | Resultado | job_id |
246
+ |---|---|---|---|
247
+ | P-10 fronteira clássica×hardware | TVD vs ideal, n=3..5 | 0.0139 / 0.0188 / 0.0183 | `dbhp6ks2d77s739d692g` |
248
+ | P-08 ZNE vs C† | p0 n=4, com/sem ZNE | 0.0197 → **0.0116** (−41%) | `dbhp6ok2d77s739d6990` |
249
+
250
+
251
+ ## Apps v1 (2026-10-29)
252
+
253
+ - **AuditKit (CPA-01)** — certificacao de entropia quantica com recibo: hardware
254
+ `ibm_marrakesh`, 4096 bits, veredito **1** (job `dbhpaomne4hc73bdbp7g`).
255
+ - **Quantum Regression Seal (QRS-01)** — gate de CI/CD que pega miscompilacao
256
+ silenciosa por comparacao unitaria; action reutilizavel no repo.
257
+
258
+ Detalhes: **[docs/APPS.md](docs/APPS.md)**
259
+
260
+ ## Honest scope
261
+
262
+ This repository contains the language heart only: kernel, types, gate, receipts.
263
+ It does not contain, and will never contain, the Zephirum OS distribution,
264
+ bootloader, installer, or activation keys. Simulations are labeled as
265
+ simulations; without error correction, useful executions are bounded well
266
+ under 20 qubits.
267
+
268
+ ## Runtime de produção (v1.8.0)
269
+
270
+ ```python
271
+ from zyql_runtime import decide, Verdict
272
+ r = decide(lambda x: x & 1, n=3, shots=512) # -> Verdict.REFUSED
273
+ r.error_bound # limite de erro Hoeffding declarado
274
+ ```
275
+ CLI: `zyql-decide --oracle balanced --shots 512`
276
+
277
+ ## ⚠️ Desambiguação / Disambiguation — no PyPI package exists
278
+
279
+ Instruções circulando na web citam `pip install zephirum-quantum-plugin` e um
280
+ repositório `SerenaSolutions/zephirum`. **Nenhum dos dois existe.** Este
281
+ (`zephirum-lang`) é o único repositório oficial. Nenhum pacote da ZEPHIRUM está
282
+ publicado no PyPI — qualquer instrução citando esse pacote não vem da casa.
283
+
284
+ ## Citation
285
+
286
+ See `CITATION.cff`. Software deposit: Zenodo concept DOI 10.5281/zenodo.23632019
287
+ (code MIT, companion thesis CC BY-NC-ND 4.0), (c) Serena Solutions.
288
+
289
+ ## License
290
+
291
+ MIT — see [LICENSE](LICENSE).