Metadata-Version: 2.4
Name: qcode-lang
Version: 1.2.0
Summary: Q-Code — the participatory quantum coding language: write .qc programs, run them on a field, statevector, or real Qiskit backend
Author: Cameron Mooklal
License-Expression: MIT
Project-URL: Homepage, https://qcode-c7n.pages.dev/
Keywords: quantum,quantum-computing,programming-language,qiskit,statevector
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: qiskit
Requires-Dist: qiskit>=2.0; extra == "qiskit"
Requires-Dist: qiskit-aer>=0.18; extra == "qiskit"
Provides-Extra: ibm
Requires-Dist: qcode-lang[qiskit]; extra == "ibm"
Requires-Dist: qiskit-ibm-runtime; extra == "ibm"
Dynamic: license-file

# Q-Code — the language as a runnable thing

Write Q-Code in a `.qc` file, run it with the interpreter. No laptop
testing, no installs beyond the venv already here — everything is
verified on the VM: 276/276 tests green across thirty-four suites
(210 Python + 8 JavaScript, the JS engine cross-checked against
the Python one).

## Run it

    python3 qinterp.py examples/hello.qc            # field backend (stdlib only)
    venv/bin/python qinterp.py examples/bell.qc     # quantum backend (Qiskit/Aer)
    python3 qinterp.py --repl                       # interactive field session
    python3 qinterp.py examples/tutorial.qc         # the whole language in one file
    python3 qsynth.py --fields a:zero,one --fields b:zero,one \
        --target zero,zero:0.375 --target one,one:0.375 \
        --target zero,one:0.125 --target one,zero:0.125
                                                    # synthesizer CLI: state the
                                                    # reality you want, get the program
    python3 test_qinterp.py test_qwave.py test_qqec.py test_qstate.py \
        test_qfriend.py test_qmap.py test_qweighted.py test_qmechanics.py \
        test_qram.py test_qsynth.py test_qcontrol.py test_qcontrol2.py \
        test_qcontrol3.py test_qgrover.py test_qmedia.py test_qwaves2.py \
        test_qwifi.py test_qdb.py test_qstore.py test_qssid.py test_qaudio.py test_qbb84.py  # full suite: 210 tests
    node test_ghostdb_js.mjs                        # JS engine: 8 tests

## REPL (interactive, field backend)

    python3 qinterp.py --repl
    q> field coin = {left: 0.5, right: 0.5}
    q> attend coin left
    q> ask coin
    q> fields          # every field, its state, and its links
    q> help            # the statement list
    q> quit            # Ctrl-D works too

One persistent session: fields, links, observers, and waves all live
across lines, and a bad line prints an error without losing anything.

## Syntax (one statement per line, `#` comments)

    backend field | quantum | state   # first line if present; default field
    field coin = {left: 0.5, right: 0.5}
    become coin = {left: 0.9, right: 0.1}
    entangle a b                # identity correlation (same outcomes)
    entangle a b as {zero: zero@0.75|one@0.25, one: zero@0.25|one@0.75}
                                # weighted relation: exact 75% agreement,
                                # uniform marginals (field backend only)
    attend coin left [n]        # attention reweights x3 per attend
    ask coin                    # collapse; prints the outcome
    declare coin right          # write the ending; beginning conforms
    show coin                   # print current distribution
    separate a b                # break a link; separation is work (field only)
    check a == b                # assert two observed fields agree (field/state)
    check a == left             # assert an observed field equals a value
    print some text

Control flow (field/state only — the quantum backend builds one
circuit and cannot branch at runtime, so it rejects these loudly):
    if coin == left             # condition on an observed value;
      print left                # unobserved fields are asked first
    else                        # (asking makes them definite)
      print right
    end
    if a != b                   # field-field comparison also works
      print differ
    end
    repeat 3                    # repeat a block N times (N <= 10000)
      ask coin
    end
    func round                  # procedures: define before you call,
      ask a                     # no parameters in v1, and no field/
      check a == b              # wave/observer definitions inside bodies
    end
    call round

Rules, checked before anything executes (no half-runs): func
definitions are top-level only; backend statements are top-level
only; field/wave/observer definitions cannot appear inside
repeat/func bodies (they would redefine on the second run or call —
bodies operate on fields defined outside). Recursion is allowed up
to a call-depth cap of 100. No `while` yet: conditions over fields
that never change would loop forever, and the language has no
`break` — repeat-N is the safe loop for v1.

Wave 2 — parameters, variables, while, break (field/state only):
    func check_pair x y         # parameters bind FIELD or WAVE names
      ask x                     # at the call (substituted in field/
      ask y                     # wave positions only — outcome values,
      check x == y              # mappings, observers, print text are
    end                         # never touched; name params distinctly
    call check_pair a b         # to dodge the documented edge cases)
    let n = 0                   # integer variables: let defines once,
    set n = n + 1               # set reassigns; + - * ( ) expressions
    let m = 2 * (n + 3)         # with the usual precedence
    if n < 3                    # integer comparisons: == != < > <= >=
      print small
    end
    while n < 3                 # while loops on a VARIABLE condition
      set n = n + 1             # (a while condition on a field can
      if n == 2                 # never change — asking freezes the
        break                   # value — the 10000-iteration cap
      end                       # catches it loudly instead of hanging)
    end
`break` exits the innermost repeat/while; a break inside a function
cannot cross into the caller's loop. `let` definitions cannot appear
inside repeat/while/func bodies (same redefinition rule); `set`
reassignment inside bodies is fine, and functions share the outer
variables.

Wave 3 — value parameters (field/state only): a parameter's kind is
inferred from how the body uses it — field/wave position means a
field parameter (the argument must be a field or wave name);
expression, set target, or integer comparison means a value
parameter (the argument is a number, a variable, or an expression
written without spaces: `call count n+1`, `call count 3`). A
parameter used both ways is an error at definition time; an unused
parameter accepts either. Each call gets a frame, so value
parameters are true locals: `set` inside a function updates the
parameter, never the outer variable of the same name. Recursive
countdowns work now (`examples/value_params.qc`). Two rules to know:
value arguments cannot contain spaces, and a function that passes a
value through to another function must be defined after it.

## The two backends (same source, two substrates)

- **field**: Layer 1 participatory semantics (`qcode.py`). Ask collapses
  immediately; entangled partners conform; history editable until
  observed.
- **quantum**: the program compiles to one real Qiskit circuit and runs
  on Aer (1000 shots). field -> RY preparation, attend -> reset +
  re-prepare to the reweighted angle, entangle -> CX, ask -> measurement
  to a fresh classical bit, declare -> reset + prepare. Counts print in
  ASK ORDER.

## Verified results (test suite, this VM)

- Bell pair: counts `{'00': 493, '11': 507}` — zero 01, zero 10.
- Attention x1 on 50/50: peek 0.75/0.25, final ask 755/245.
- Attention x3 on 50/50 (field): 27/28 = 0.96 toward attended outcome.
- Declare then ask: 1000/1000 on circuits, exact on field.
- Entanglement conformance (field): declaring `a` collapses `b` to the
  consistent value before anyone asks it.
- Guard: attending half of an entangled pair fails cleanly with the
  reason (no local operation can reweight half of an entangled pair).

## Honest v1 limits

- Quantum backend needs 2-outcome fields (one qubit each).
- Attend / declare / become are forbidden on entangled or collapsed
  fields on the quantum backend — that is quantum mechanics, not a
  missing feature. The field backend permits it; the backends diverge
  there, and the interpreter says so.
- Aer runs real circuit math on classical hardware, not quantum
  hardware. IBM Quantum hardware is a later step (needs Cam's account).
- `declare` on circuits is state preparation, not retrocausality.
- On circuits, entangle correlates only when the target starts
  definite (Bell preparation; a definite outcomes[1] target gets an X
  first). Two superposed fields + CX stay independent, so the
  interpreter rejects that loudly instead of silently producing
  independence. The field backend correlates regardless.
- Layer 3 (mind-coupling / universe access) is still speculative, with
  kill conditions written before tests. This interpreter is the
  foundation those tests run against, not the proof.

## Wave memory — data stored INSIDE waves (`qwave.py`)

Two mechanisms, both driven from Q-Code (`wave` / `store` / `recall`):

- **Grid wave** (standing-wave memory): a message becomes a chord of
  standing waves on a string — one bit per mode (+1 / -1 amplitude).
  The pattern IS the data; there is no separate store. Verified:
  "hello waves" round-trips exactly; "hello" recovers exactly from a
  random 50% of the points (3 seeds); "hi" from 25%; two messages
  ("sun", "moon") in disjoint mode bands of ONE field both decode
  exactly. That is holographic, superposition-native storage.
- **Phase wave** (quantum circuits): one bit per qubit, stored in the
  wave's PHASE (|+> = 0, |-> = 1); reading is interference (final H
  turns phase into outcome). Verified: 10110011 and 00000000 return
  1000/1000 shots, exact.
- **Entangled wave** (quantum circuits, the classical-theory-breaking
  step): one bit per Bell pair, stored in the pair's RELATIVE PHASE
  (Phi+ = 0, Phi- = 1) — in the relationship, not in either qubit.
  Verified: joint (Bell-basis) read returns the bit 1000/1000,
  including multi-bit "101"; local reads return ~50/50 noise for BOTH
  bit values — neither part holds any information. Classical theory
  says information must live in parts; this stores it where no part
  can see it.
- **GHZ wave** (quantum circuits, one level deeper): 1 bit across N
  parties (GHZ+ = 0, GHZ- = 1). Verified: joint read exact 1000/1000
  for N = 3 and N = 5; local marginals ~50/50; any partial view
  (2 of 3, 3 of 5) returns {00..0: 50%, 11..1: 50%} for BOTH bit values
  — bit-independent, so no subset of parties holds anything. The
  information is irreducibly N-way.
- **Teleport wave** (quantum circuits): a bit that MOVES through a
  relation. Deferred-measurement teleportation: Alice's Bell-basis
  operations, quantum-controlled corrections, Bob reads the exact
  original bit. Verified: Bob 1000/1000 for both bits; Alice's qubit
  after her step random (~0.50) for both bits — her copy is destroyed;
  her two classical bits uniform over all four outcomes for both bits
  — they carry zero information alone. Nothing is copied; it moves.

## Error correction — the code protects itself (`qqec.py`)

This is what makes a quantum code REAL in the technical sense: Shor's
1995 insight that quantum information can survive physical errors at
all. A toy circuit works in ideal simulation; a real code detects an
error, corrects it in-circuit, and returns the exact logical value.

- **BitFlipCode** (3 data + 2 syndrome qubits): logical bit as
  |000>/|111>. One X error anywhere is detected by two parities and
  corrected by multi-controlled X gates keyed off the syndrome.
- **PhaseFlipCode** (same layout, X basis): logical bit as
  |+++>/|--->. One Z error detected by X-basis parities
  (ancilla-controlled CX checks) and corrected by multi-controlled Z
  gates (H-mcx-H).
- Verified: every error position (none, 0, 1, 2) x both bit values →
  corrected bit exact 1000/1000, syndrome pattern exact. Q-Code:
  `wave code = bitflip 3`, `store code 1`, `error code 1`,
  `recall code` (corrected), `recall code syndrome`.
- Next step, documented not built: concatenating these two codes IS
  Shor's 9-qubit code, which corrects ANY single-qubit error (X, Z,
  or Y). Hardware note: verification is on the ideal simulator (no
  noise model); the code structure is what was proven, not a
  hardware noise rate.

## State backend — Q-Code needs no IBM (`qstate.py`)

Q-Code is a relational field language, not a front end for someone
else's hardware. The `state` backend runs the same .qc programs on
exact statevectors with the standard library only — no Qiskit, no
IBM, no venv, no account, no cost, on any laptop with Python:
`backend state`, or `--backend state` to override a program's backend
line (the override test runs bell.qc on plain system Python).
- Exact, not sampled: `show` prints true probabilities (attention
  shows exactly 0.75/0.25, no shot noise); `ask` collapses
  immediately; seeded, so runs are reproducible.
- Same guard rules as the circuit backend: no local reweighting of
  entangled or collapsed fields.
- Verified: Bell correlation, attention exactness, declare exactness,
  10-qubit GHZ correlation (all three asks equal) — all on system
  Python.
- Honest limit: 2^n amplitudes, so small systems only. This is
  quantum STRUCTURE without hardware, not quantum speedup — a
  classical simulator cannot beat classical computers at scale, by
  definition. The thing that is new is the paradigm (relations,
  fields, attention), not a speed claim.

## Observers — Wigner's friend as code (`observer`, `ask ... as ...`)

The measurement problem is the biggest open question in quantum
foundations: what counts as an observer, when does collapse happen?
Q-Code makes the observer a variable — no other quantum language has
observer as a primitive at all.
- `observer friend`, `observer wigner`, then `ask coin as friend`
  collapses for friend and records friend's view.
- `show coin as wigner` still reads 50/50: Wigner's model is
  uncollapsed (the correct marginal) until Wigner asks.
- `ask coin as wigner` must equal friend's outcome: two observers,
  one reality, agreement on asking. Re-asking returns the same value.
- Field backend only in v1; the circuit and state backends reject
  observer statements loudly instead of ignoring them.
- Honest label: this models observer-relative DESCRIPTION, not a
  claim that Wigner sees physical superposition. The classical field
  model captures the epistemic structure — the marginal, the
  agreement — which is exactly what makes it a foundations lab: you
  can now write programs about the measurement problem itself.

## Synthesizer — the machine designs programs (`qsynth.py`)

The AI-native move: stop designing programs forward from intuition.
State the reality you want — a target distribution over joint
outcomes — and the machine searches program space (beam search over
entangle/attend/declare sequences, simulated on fresh Worlds) and
emits a real .qc program the interpreter runs.
- Attention compilation: target {red: 0.7, green: 0.2, blue: 0.1}
  → machine finds attend red twice, green once (weights 9:3:1),
  verified distance 0.028. No human derives that schedule by hand.
- Joint structure: 3-field all-equal target → machine finds the
  entanglement graph; every run agrees jointly, marginals 50/50.
- Boundary mapping, honestly told in full: 75% agreement between two
  fields sat 0.25 away with identity-only entangle, 0.125 with
  generalized maps (half-free map + attend) — and now ~0 with
  weighted relations: the machine finds the symmetric 0.75 map and
  emits a program carrying a weight. The boundary closed.
- Method guards, learned the hard way: no early stopping on noisy
  search scores — a 300-seed estimate once flattered a mediocre
  program past the threshold and killed the search before the true
  answer's depth. And no single global leaderboard: a 150-seed
  estimate once ranked a 0.6 map above the exact 0.75 map, and a
  global top-5 then evicted the true winner before verification.
  Now every depth's top candidates get ground-truth verification,
  and the best verified program wins.

## Relations — `entangle ... as {...}` (generalized mappings)

Relations are no longer just identity. Any mapping from one field's
outcomes to allowed sets of another's is now a relation:
- `entangle a b as {zero: one, one: zero}` — negation:
  anti-correlation, asks always differ. Runs on every backend:
  field (restriction), circuit (X+CX, needs a definite target),
  state (reset+X+CX, needs an unentangled target).
- `entangle a b as {zero: zero|one, one: one}` — partial: 75%
  agreement, verified statistically, with an honestly skewed b
  marginal (0.25 zero) — the skew is the remaining boundary.
- General mappings (anything else): field backend only; the circuit
  and state backends reject them loudly instead of miscompiling.
- Weighted relations (the boundary-closer):
  `entangle a b as {zero: zero@0.75|one@0.25, one: zero@0.25|one@0.75}`
  — a relation carrying its own weights. Forward: exact 75%
  agreement with uniform 50/50 marginals (the old half-free map
  bought 75% with a skewed 0.25 marginal; the skew is gone).
  Reverse: declaring `b` zero makes `a` 75% zero — the inverse link
  carries the same weights, which is exactly Bayesian conditioning
  (prior x likelihood, normalized). Weights normalize per key at
  parse time, so `zero@3|one@1` reads as 0.75/0.25.
- Weighted maps are field-only: circuits cannot yet express a
  weighted conditional without ancilla/controlled-rotation machinery
  — the next spec, stated not hidden. The synthesizer learned the
  weighted relations and closed its own boundary: the 75% target
  went 0.25 → 0.125 → ~0.

## Q-RAM — memory you can ask in superposition (`qram.py`)

Q-Code now has two memory families: holographic wave memory (data in
patterns) and addressable quantum RAM (data in cells, queryable in
superposition). Classical RAM answers one address. QRAM answers a
superposed address — the answer comes back entangled with the
question. That is the primitive quantum search and quantum
data-loading need, and no classical memory can do it.

    wave ram = qram 4           # 4 addresses x 1-bit cells
    wave wide = qram 4 2        # 4 addresses x 2-bit cells
    write ram 0 1               # classical write: cell 0 <- 1
    read ram 0                  # classical read
    query ram {0: 0.5, 1: 0.5}  # superposed query
    search ram 1                # Grover's search: find the address
                                # holding 1 (see below)

Grover's search over Q-RAM (see qgrover.py) is the first real
quantum-advantage demo inside Q-Code: find the address holding a
target value in about (pi/4)*sqrt(N/M) oracle calls, where classical
search needs (N+1)/2 probes on average. The circuit is real gates,
not a shortcut: address superposition, QRAM load (exact amplitude
permutation, self-inverse so it uncomputes), oracle (phase flip
where the data register equals the target, X-sandwich + MCZ),
diffusion (inversion about the mean, H X MCZ X H). Verified exact:
success probabilities match Grover's theory to 1e-9 (N=4: 1.0 after
1 call; N=16: 0.962 after 3; N=64: 0.997 after 6; N=256: 12 calls
vs 128.5 classical), and the gate circuit is checked against the
amplitude formula (up to a global phase, which no measurement sees).
Honest limit: the speedup is in the ORACLE CALL COUNT, not
wall-clock — a classical simulator cannot beat classical computers
at scale. What this proves is the algorithm.

Verified, exact (stdlib statevectors, no shot noise):
- Single address: the answer is just the cell, no entanglement.
- Addresses holding different cells: joint distribution exact, and
  address and data are entangled — the joint cannot be split into
  separate parts. Example: cells 1,0,1,1 queried uniformly →
  joint {(0,1): 0.25, (1,0): 0.25, (2,1): 0.25, (3,1): 0.25},
  data marginal {0: 0.25, 1: 0.75}, entangled: yes.
- Addresses holding equal cells: the answer factors cleanly,
  entangled: no. Entanglement appears exactly when cells differ —
  the contrast is the physics, not a bug.
- Entanglement reporting is exact, not heuristic: query states have
  nonnegative real amplitudes, and for such pure states the joint
  distribution factorizes iff the state is a product state.

Honest v1 limits: writes are classical (quantum writes are a later
build); the data register starts |0...0> per query; sizes capped at
20 qubits so a careless size cannot eat the VM. Next steps: quantum
writes, relational cells (no local content, data only in
correlations), and a Grover search demo running over QRAM.

## Quantum media vault (qmedia.py)

Real files in quantum memory — images, video frames, documents —
built on QRAM (see `examples/media_vault.qc`):

- **Image:** a bitmap is bits. Pixel (x, y) lives at QRAM address
  y*w+x, cell = 1 (lit) or 0 (dark). Verified: an 8x8 smiley, a
  16x16 block, and a 64x64 border frame (4096 pixels) all round-trip
  exactly — stored in Q-Code, read back, byte-identical.
- **Search on an image:** a 16x16 image with a 4x4 lit block —
  Grover finds a lit pixel in 3 oracle calls at 0.961 success
  (theory exact), vs 128.5 probes classical.
- **Video:** frames share one QRAM, frame f at offset f*w*h.
  Verified: 2-frame 8x8 video (smiley, then eyes-closed) round-trips
  both frames exactly.
- **Document:** text is bytes, one width-8 QRAM cell per character.
  Verified: "Q-CODE" and "hello waves" round-trip exactly.

The honest size line: a 1-bit QRAM maxes at 2**19 addresses = 64KB
under the 20-qubit cap, so a real photo (1MB) does not fit this
simulator — nor today's real quantum hardware, which has no QRAM
of that size either. Writing is classical; the quantum advantage
is searching and querying the data in superposition, not storing
it. Classical storage remains better at just holding files.

## Quantum-native storage: the image as one wave, text as pure relation

Two storages with no cells, no addresses, no table (see
`examples/frqi_demo.qc`, `examples/relational_demo.qc`):

- **FRQI image wave (`wave img = frqi 2`):** a 2^n x 2^n image lives
  in ONE state of 2n+1 qubits — every pixel in superposition, each
  brightness a rotation angle (theta = asin(sqrt(brightness))).
  A 4x4 image is 16 brightnesses in 5 qubits; an 8x8 is 64 in 7.
  Verified exact at 2x2, 4x4, 8x8 (recall returns the stored values
  to 1e-9, checked against the FRQI formula directly). Reads:
  `recall img` (exact brightnesses), `recall img measure` (one
  sampled pixel, like real hardware — position uniform, color 1 with
  probability = brightness), `hadamard img` (Walsh-Hadamard
  transform on positions; H twice is the identity, verified).
  Built on exact statevectors, stdlib only. V1 cap: n <= 5 (32x32).
- **Relational text (`wave msg = relational 16`):** text stored
  ONLY in correlations — each character is 8 bits, each bit one Bell
  pair's relative phase. Local read of any qubit: ~50/50 noise.
  Joint read: the text, exactly. Verified: "hi" (16 bits, 32
  qubits) and "hello waves" (88 bits) round-trip exact; all 32 local
  marginals land in [0.465, 0.514]. The circuits are all Clifford
  gates, so recall runs on Aer's stabilizer engine (venv python),
  which handles 32+ qubits instantly where the statevector engine
  would need 2^32 amplitudes.

## Piggyback: data hidden in ordinary radio traffic (qwifi.py)

No quantum hardware, no special hardware at all — the message rides
WiFi and Bluetooth traffic that is already in the air:

- **Split:** every bit becomes two shares (r, bit^r). Each share
  alone is uniform random noise. Share 1 rides one network's beacons,
  share 2 rides another's. One network alone yields nothing.
- **WiFi beacons:** one share byte per beacon, in a vendor-specific
  information element (OUI 00:50:F2, Microsoft — vendor IEs are
  routinely opaque bytes). A parity bit rides the beacon interval
  (100ms = 0, 102ms = 1), so tampering is detected on receipt.
- **BLE advertisements:** the same framing in manufacturer data
  (company 0x004C, Apple), interval 20ms/22ms for parity.
- **CSI phase channel:** the physical layer itself — bits as tiny
  +/-5-degree phase perturbations on a simulated channel estimate.
  Decoding needs the idle baseline (the key); without it the shifts
  sit inside normal channel variation and the message is invisible
  (verified: bit-1 vs bit-0 phase means differ by < 0.3 rad).

Verified: "hello waves" round-trips exact over WiFi (12 + 12
beacons) and BLE, both streams pass naive inspection (ordinary
SSIDs, valid BSSIDs, normal intervals, known vendor OUIs), one
stream alone decodes to noise, and flipping a payload byte or an
interval is caught by parity. The 5-degree CSI default is the
honest trade-off: at 3 degrees with 1 degree of phase noise, each
bit errs ~0.1% of the time, so a 272-bit message flips a bit about
a third of the time (caught by the long-message test); at 5 degrees
the per-bit error rate is ~3e-7.

Honest limits: this is a protocol + simulation, verified end to end
on the VM — there is no radio here, so the air interface is a model,
not a transmission. Real over-the-air needs a radio that can inject
frames (Linux + a supported adapter + hostapd/scapy for beacons;
BlueZ for BLE adverts). That path is documented, not built, and
nothing routes to Cam's laptop for testing. The shares are classical
2-of-2 secret sharing, not entanglement: anyone holding BOTH streams
AND knowing the scheme recovers the message. What the scheme buys is
invisibility in plain sight + nothing-from-one-stream. A third
carrier joined since: **FM RDS groups** — one share byte per group,
parity bit in the group type itself (0x0A = 0, 0x0B = 1, both
ordinary types). Receivers handed the wrong carrier's frames get a
clean error, not a traceback.

## GhostDB: a database that lives in signals and waves (qdb.py)

Three layers. Logical tables of string keys -> byte values
(1..255; 0 means empty). The values live in a Q-RAM (address =
slot, cell = value) — the key->slot index is classical metadata,
the VALUES are quantum, so content-based work runs on the quantum
side without the index. And a table serializes to bytes, splits
into two noise shares, and hides in radio traffic — WiFi beacons,
BLE adverts, FM RDS groups. Collect both streams and the table
rebuilds itself, index included.

Processing is real but narrow — the query engine is Grover search
and superposed aggregation, verified exact:
- `search(table, value)`: find a record holding a value in
  ~sqrt(N) oracle calls instead of scanning N slots. Verified: a
  4-slot table finds its one 42 at success probability 1.0; a
  16-slot table with two 42s finds one at 0.945 (theory exact).
- `aggregate(table)`: ONE superposed query returns the whole
  table's value distribution (the QRAM query marginal). Verified:
  {42: 0.125, 7: 0.0625, 99: 0.0625, empty: 0.75} exact.
- `hide_table` / `reveal_table`: a 4-record table hides in 32
  WiFi beacons + 32 BLE adverts (or RDS), both streams pass naive
  inspection, one stream alone cannot rebuild it.

Honest limits: values are single bytes in v1 (scores, status
codes, categories — not prose); tables cap at 256 slots; the
classical index reveals WHICH keys exist (not their values).
There is no general-purpose quantum compute here and no wall-clock
speedup in simulation — a classical simulator cannot beat classical
computers at scale. What this builds is the architecture real
quantum databases would use (QRAM + Grover is the actual
literature), running end to end, so the only missing piece for
real hardware is hardware.

## GhostDB in Q-Code (storage statements, qinterp.py)

The database is part of the language now — `table` / `put` /
`get` / `scan` / `search` / `aggregate` / `hide` / `reveal` /
`hide_text` / `reveal_text` / `dump` / `load`. Backend-independent:
tables keep their own QRAM, separate from the active backend, so
the same program runs under field, state, and quantum alike
(verified: `examples/ghostdb_store.qc` runs clean on all three).
`search` resolves by name — a table name means Grover over the
table, a wave name means Grover over that QRAM. Tables can be
function parameters (`put t eve 5` inside a func taking `t`);
`table` and `load` cannot appear inside repeat/while/func bodies,
like other definitions. `dump`/`load` persist all tables as JSON.
Verified (test_qstore.py 13/13): put/get/scan exact; search
probability == theory (0.945 for 16 slots, two 42s) with landing
retried; aggregate marginals exact; hide/reveal round-trips on
wifi+ble and wifi+rds; single stream cannot rebuild; dump/load
round-trip; clean QErrors for bad values, unknown tables, and
reveal-before-hide.

What "storing data quantumly" means here, plainly: the values
live in real quantum states (a QRAM whose address register is in
superposition, data entangled with the question) and the search
is a real quantum algorithm — but those states are simulated,
the math running on a classical CPU. Quantum mathematics,
classical substrate: no qubits, no hardware, no speedup. When
the app saves, it's classical bytes again; the quantum part is
the live in-memory state.

Name carriers — real transmission with no new hardware
(qwifi.py `hide_in_ssid` / `hide_in_btname`, test_qssid.py 12/12):
the shares ride in NAMES you already control — a WiFi network
name (SSID) your router broadcasts, or a Bluetooth device name
your phone broadcasts. Each name holds one 32-char chunk (share
tag A/B, chunk index, 2-char checksum, 28 base32 data chars —
~17 bytes per name). `hide users ssid ssid` prints four names;
set them as your router's four SSIDs (2.4GHz, 5GHz, guest 2.4,
guest 5GHz) and any WiFi scan reads them back; `reveal users
from <names...>` rebuilds the table (the tag in each chunk says
which share it is). The checksum catches a mistyped name; a
2-byte length prefix inside the payload catches a missing final
chunk (a real bug the tests caught — indices alone can't).
Honest limits: OVERT, not stealthy — anyone scanning sees
encoded-looking network names (the content is still hidden: one
share alone is noise, but the existence of data is obvious);
capacity is tiny; setting names is manual; renaming your main
SSID drops every device off until they rejoin (use the guest
network first); the data lives only while the name is set — the
durable copy is the dump file. The console picks new carriers
up automatically (it runs the workspace interpreter).
Note: `web/ghostdb.js` predates the name carriers — Q-Code is
the source of truth, the JS file is reference only.

Audio carrier — data over sound, no radio at all (qaudio.py,
test_qaudio.py 11/11; player page `audio/audio-link.html`):
the shares ride as near-ultrasonic tones — 17.0 kHz = 0,
18.5 kHz = 1, 50ms a tone, one frame per share (~15.5s), with
a 250ms wake burst at 16 kHz (a third tone data never uses, so
the ear finds it unambiguously), a 16-bit preamble, a 16-bit
length and a CRC-16. `hide users audio audio` prints the tone
strings; paste them into the player page and it plays them out
of a speaker; a mic on another device hears them and the page
reports the tones it heard; `reveal users from audio <tones...>`
rebuilds the table (the tag bit inside each frame says which
share it is). ALL the modem intelligence (burst sync, preamble,
length, CRC, the decode) lives in Q-Code — the page is a dumb
ear and mouth and holds no framing or checksum logic (a JS
modem was started first and DELETED on Cam's correction:
everything is built with Q-Code). The modem is verified in
software: round-trips exact through synthesized PCM, under
noise stronger than the signal, with f1 rolled off 6dB, with
the window grid misaligned 15ms, and a flipped bit or a
truncated frame fails loudly instead of corrupting. The page
is verified in headless Chrome with a fake mic (Play runs,
mic acquires, no console errors). Honest limits: the acoustic
path (speaker -> air -> mic) is hardware and untested until
the page's test tone runs — the page shows a live spectrum so
the user can SEE the tone arriving; range is one room; the
burst is 16 kHz because data never uses it, and laptop speakers
pass 16 kHz better than 20 kHz. Two real bugs the tests caught:
a fixed window grid reports every symbol one late (the
preamble scan cannot catch it — alternating shifted by one is
still alternating), fixed by burst-edge locking; and a long f0
burst is indistinguishable from the length field's zeros, fixed
by the third tone.

The home quantum network — BB84 key distribution (qbb84.py,
test_qbb84.py 11/11): the carriers were the transport; the
network is what rides on them. Nodes are his devices (laptop
Alice, phone Bob); the links are entanglement (pre-shared Bell
pairs, simulated) plus the signals as the classical channel.
First protocol: BB84. Alice sends Bob qubits in random bits and
bases (exact single-qubit states, real measurement collapse);
they announce their bases over the audio carrier — the bases ride
as tone strings, the same frames GhostDB hides in — and keep the
matching half. Then they publicly compare half the sifted key:
`qkd home 256` establishes a key at 0.0% error; `qkd home 256 eve`
catches the eavesdropper at ~25% error and aborts. The key is
stored under a name and never printed in full (length + a SHA-256
fingerprint only — a printed key is a leaked key). Verified: clean
0.0% error, Eve 24.2% (theory 25%), abort across five seeds, and
the bases survive a simulated audio round-trip intact. Honest
limits: simulated qubits, not photons; no privacy amplification
in v1; the 11% abort threshold is the standard BB84 bound. The
roadmap from here: use the key to lock the shares (one-time pad),
teleport a table value (the data never travels — only the
correction bits cross the air), a CHSH Bell test to prove the
link is really quantum, and entanglement swapping to extend the
network past one hop.

Usable surface: the GhostDB app is a Q-Code console (built as a
Muse artifact, slug `ghostdb`) — write Q-Code storage programs
and run them, on Cam's own device, no server he owns or runs.
The VM itself cannot host anything on his home network (it
joins his Tailscale as a client only, accepts no connections),
which is why the app runs on his device instead. A JavaScript
port of the engine exists at `web/ghostdb.js` (verified 8/8 in
Node, cross-engine exact against Python) as a reference only —
the storage itself is Q-Code, per Cam's call.
- Known field-model edge, stated: preparation constraints do not
  back-propagate through links, so asking a 50/50 field linked
  anti to a definite field can raise a contradiction instead of
  constraining the ask. The synthesizer treats contradictory
  programs as invalid (worst score) rather than crashing.

Limits: grid stores ASCII text; partial reads need more samples than
bits; phase waves need the venv python (Qiskit). Wave memory is a
storage mechanism — it does not by itself prove universe access (L3
kill-condition tests still apply).

## Quantum compression — store as much as possible (qcompress.py, qamp.py, qautoenc.py)

The hard limit is Holevo's bound (a theorem): n qubits can only ever
give back n bits. Random data does not compress at all, quantum or
classical. What compresses is STRUCTURE. Three real ways, all built
and verified:

- **Schumacher compression (1995).** A biased source (P(0) = p) has
  entropy H(p) per qubit, so n qubits compress to ~n*H(p). Verified:
  p=0.9, n=16 → 10 qubits (1.60x), fidelity 0.9316 (the atypical tail
  is the loss); p=0.5 → 1.00x, exactly as theory says for random data.
  `schumacher 0.9 16`. v1 covers a diagonal (computational-basis)
  source; a fully-quantum (non-diagonal) source is v2.
- **Amplitude encoding.** N values as the amplitudes of log2(N)
  qubits — 1024 values in 10 qubits of state. The aggregates
  (v^2-weighted mean, total, sum of squares, the max) are readable in
  one shot; reading every value out takes N measurements (Holevo).
  It is a query engine, not a hard drive. `wave data = amplitude 1024`,
  `store data ...`, `recall data`, `recall data measure`. Two bugs
  the tests caught and fixed: the "mean" is v^2-weighted, not the
  plain average (it was mislabeled), and sampling finds the max only
  when the distribution is peaked.
- **Quantum autoencoder (Romero et al. 2017).** A variational circuit
  learns to squeeze a 1-parameter family of 2-qubit states into 1
  qubit and rebuild it: trash |1> probability 0.00000,
  reconstruction fidelity 1.00000. The trained params recover the
  inverse tilt (-pi/6, -pi/5). The fidelity measure includes the
  compression step (the trash qubit is discarded) — without the
  discard, encode-then-decode is the identity and the fidelity is
  trivially 1, which measures nothing. The limit is the family: a
  generic 2-qubit state (6 parameters) cannot be compressed into 1
  qubit. `autoencode`.
- **entropy FILE.** The first-order bound and the actual zlib number
  for any file. Zlib beats the first-order bound by exploiting
  repeated substrings — that is expected, not a contradiction; the
  first-order bound is not the floor, the true entropy rate is lower
  still, and no method (quantum or classical) beats it.

**test_qcompress.py 7/7, test_qamp.py 5/5, test_qautoenc.py 4/4.**

## Quantum JPEG — compress an image to super small (qqft.py, qimgcompress.py)

The image is amplitude-encoded, the QFT piles almost all the energy
into a few low-frequency coefficients, the tiny ones are thrown
away, and the inverse QFT rebuilds it. That is JPEG's idea
(transform, discard small coefficients), running on the image's
amplitude state in log2(N) qubits. The QFT is a real circuit (H +
controlled-phase gates — `cphase` was added to qstate.State for
it) and is verified against a direct DFT to ~1e-15. Verified:
a 16x16 gradient (256 pixels, 8 qubits) keeps 32 coefficients
(100% of the energy) -> 8x fewer values, 8 -> 5 qubits, PSNR
308 dB (essentially exact — the repeating gradient is exactly
sparse in frequency); keep 8 coefficients -> 32x fewer values,
8 -> 3 qubits, PSNR 19.9 dB. A blob holds 100% of its energy in
32 coefficients (PSNR 53.9 dB); a checkerboard is a single high
frequency (PSNR 306 dB). Random noise is the honest control:
84% of the energy in 32 coefficients, PSNR 13 dB — noise does
not compress. `compress_image gradient 16`, `compress_image blob
16 0.03125`. The engine caps at 16 qubits (64K values): the QFT
is O(n^2 * 2^n) gate operations in pure Python, and a 10MB file
(24 qubits) would be ~5 billion of them — that cap is the
simulator's, not the method's (on hardware the QFT is O(n^2)
gates). One run was killed mid-flight for exactly that mistake
(pointing the QFT at a 10MB file) before the cap was added.
`compress_file PATH` runs the same engine on a file's bytes, and
it proves the boundary: it is LOSSY. A repeated 1KB pattern keeps
99.6% of its energy but only 17% of its bytes come back exact
(close in value, wrong as bytes); README.md keeps 92.1% of its
energy but 1.9% of its bytes exact. So this engine is for images
(PSNR is the metric), not files — lossless file compression is
Schumacher / the autoencoder.

**test_qqft.py 5/5, test_qimgcompress.py 8/8.**

## Quantum sound compression (qsound.py)

The same engine in 1D. Sound is mostly a few notes at a time, so
its spectrum is sparse and the QFT concentrates it hard (this is
why MP3 works). The metric is SNR (dB): above 40 dB is excellent,
above 20 dB is good. Verified on 1024 samples, keep 1/8: a pure
tone and a 3-note chord rebuild essentially exactly (SNR ~300 dB,
8x fewer values, 10 -> 7 qubits); a sweeping chirp is good
(35.2 dB); an abrupt tone switch is good (45.4 dB); white noise is
the honest control (1.2 dB — noise does not compress). A windowed
STFT version (Hann windows, 50% overlap) is also built for real
audio that changes over time, but the comparison is reported
honestly: on these clean integer-cycle tones the global version
wins (tone SNR 40 dB windowed vs 300 dB global; chirp 21.5 dB vs
35.2 dB; switch 28.6 dB vs 45.4 dB) — the tones have no spectral
leakage for the window to fix, and the Hann window spreads them.
The windowed version is the right tool for real recordings
(non-integer frequencies, transients), not for these test tones.
`compress_sound tone 1024`, `compress_sound_windowed chirp 1024 256`.

**test_qsound.py 6/6.**

## Quantum WiFi — what quantum can and cannot do to wireless (qsuperdense.py, qbb84.py)

The honest limit first: quantum does NOT make WiFi radio faster.
A radio link's rate is Shannon's capacity (bandwidth x
log2(1+SNR)), and no quantum effect changes that for classical
data over a classical channel. What quantum does do for wireless
is two real things: (1) security — BB84 key distribution over the
link (`qkd`), provably secure keys, not faster data; (2) bit
efficiency — superdense coding (Bennett & Wiesner 1992): with one
pre-shared entangled Bell pair, Alice sends 2 classical bits by
transmitting 1 qubit (she applies I, X, Z, or XZ to her qubit;
Bob measures both in the Bell basis). Verified: all four bit pairs
round-trip exactly, 2 bits per 1 transmitted qubit (2x). The
catch, stated plainly: the pair must be pre-shared (entanglement
is the resource and it is consumed), and the qubit travels over a
QUANTUM channel (a photon), not a WiFi radio. It doubles the
classical capacity of a quantum link that already has
entanglement; it does not speed up a classical radio link. One
bug the tests caught: the decode must read qubit 0 first — the
other order swaps the two middle outcomes. `superdense 10`,
`superdense` (runs all four pairs).

**test_qsuperdense.py 3/3.**

## A quantum photon (qphoton.py)

The physical thing behind the qubit. A photon carries a qubit
in its POLARIZATION: |H> = horizontal = |0>, |V> = vertical =
|1>, |D> = diagonal 45 deg = |+>, |A> = anti-diagonal = |->.
A half-wave plate at angle t rotates the polarization by 2t —
that IS the gates: HWP at 0 deg = Z, at 22.5 deg = H, at 45 deg
= X. A quarter-wave plate adds a phase and makes circular
polarization (the S gate). A polarizing beamsplitter transmits
H and reflects V — that is a Z-basis measurement; a HWP at
22.5 deg before it measures the X basis. The BB84 bases ARE
polarizer angles, so qbb84.py is literally a photon protocol:
a photon prepared in one basis and measured in the other is
exactly 50/50, and in its own basis it is exact. How you make
a real one: SPDC (a pump laser into a nonlinear crystal makes
entangled pairs, detecting one heralds the other), a quantum
dot (one photon at a time, needs cryogenics), or an attenuated
laser (cheap, but sometimes 2 photons). Send it through
optical fiber or free space, line of sight — NOT a radio
antenna, which is why "quantum WiFi" over radio does not
exist. Read it with a single-photon detector (SPAD or SNSPD).
Honest: this module is the exact math of the photon, not the
light — no optics hardware exists on this VM or on Cam's
laptop, and a simulation cannot make a real photon.
`photon`.

**test_qphoton.py 4/4.**

## Many worlds (qworlds.py)

What quantum "reality shifting" actually is, and is not. The
many-worlds interpretation (Everett, 1957) says a measurement
does not collapse the wavefunction into one outcome — it
BRANCHES it. A 50/50 coin, measured, becomes two worlds
(heads and tails); both happen, and you branch too. Where it
stops: you cannot CHOOSE the branch. The branch you land in
is random, weighted by the Born rule. Attention moves the
WEIGHTS (attend toward heads and the heads-world is 75%
instead of 50%), but it does not let you PICK the world — the
steering test (100 measurements on a 75/25 coin) lands 78/22,
random, never 100/0. And the branches do not interact
(decoherence): no door, no signal, no way to move between
them. The "shifting" people feel is real as an EXPERIENCE —
lucid dreaming and dissociation, in the brain, not the
multiverse — and that is trainable, but it is not a physical
move between worlds. Branching, not steering. `worlds`.

**test_qworlds.py 4/4.**

## Shared QRAM (qshare.py)

One quantum RAM, two holders, no classical query. Alice holds
a QRAM (the data). Bob wants to query it. If Bob sent the
address classically, Alice would learn what he asked about.
Instead the query travels by teleportation: Bob prepares his
address superposition, teleports the address qubits to Alice
(pre-shared Bell pairs + two classical correction bits per
qubit), Alice runs the QRAM load on the teleported address +
her data register — coherently, without measuring, so she
never learns which address Bob asked about — then she
teleports the address + data qubits back to Bob, who reads
the joint (address, data) distribution. Verified: the result
matches a local query exactly (joint, marginal, and
entanglement), and the correction bits — the only classical
traffic — are uniform random (200 seeds, each bit ~50/50),
carrying no information. Two bugs the tests caught: the Bell
pairs must start AFTER the address register (a hardcoded
qubit 2 overlapped the high address bit for k > 2 and the
address came back wrong), and the state must be zeroed before
setting the query amplitudes (State() starts with amps[0] =
1.0, so a query without address 0 kept a spurious component).
Limits: width 1 bit per cell in v1; total qubits 5k+3, capped
at 20, so k <= 3 (8 addresses); a 16-address RAM needs 23
qubits and is refused. The "network" is one statevector — the
protocol is real, the link is simulated. `share ram {0: 0.5, 1: 0.5}`.

**test_qshare.py 6/6.**

## A Q-Code server (qserver.py)

What a real quantum server is: IBM Quantum, AWS Braket, Google,
Azure Quantum — real quantum hardware you rent time on. What
this is: a classical server that runs Q-Code — the simulator —
and serves it over HTTP, so a phone can send a program to a
laptop and get the transcript back. Stdlib only, no dependencies.
`GET /health` (no token) and `POST /run` (JSON: source, backend,
seed, token; returns exit/output/error). Each request writes the
source to its OWN temp file and deletes it after the run —
deliberately avoiding the GhostDB console's known flaw
(concurrent runs sharing one temp file and swapping source).
Security, stated plainly: this endpoint executes arbitrary code.
It binds to localhost (127.0.0.1) by default, the token is a
shared secret set with QCODE_TOKEN (a random one is generated
and printed if unset), and each run is capped at 60 seconds.
Never expose it to the internet; use --host 0.0.0.0 only on a
trusted home network. The VM cannot host it for Cam's network
(Tailscale client-only, accepts no connections) — it runs on
his laptop, verified here first. `QCODE_TOKEN=secret python3
qserver.py` (localhost:8793).

**test_qserver.py 6/6.**

## Parked

- `laptop-kit/` (field-browser.html, run_field.py): parked 2026-11-04.
  Cam's rule — nothing that needs him to externally test. The kit stays
  on disk but no lane routes him to it.
- `qvault.py` + `vault store/retrieve` + `test_qvault.py` (4/8, unfinished):
  parked 2026-11-05. Cam redirected the goal to quantum compression —
  the vault stores the bulk as classical chunks and only the lock
  quantumly, which is not the goal. The module, the Q-Code wiring,
  and its tests stay on disk; the vault is not part of the live suite
  and nothing builds on it.
