Metadata-Version: 2.4
Name: kannaka-quantum
Version: 0.2.10
Summary: Real quantum + qBraid Lab infrastructure capabilities for Kannaka via qBraid (free simulator) and OpenQuantum (real QPUs) — a CLI bridge for the coding agent and an MCP server for any agent.
License: SPACE CHILD LICENSE
        ===================
        
        Version 1.0, March 2026
        -----------------------
        
        Preamble
        
        This license is born from a simple belief: technology should serve humanity's flourishing, not its destruction. The Space Child License grants broad, free permissions for peaceful use while requiring accountability when technology is directed toward harm.
        
        We accept reality as it is. The world contains conflict, and self-defense is a fundamental right. But there is a moral difference between protecting life and taking it, between defending freedom and imposing dominion. This license draws that line.
        
        "Justice is the interest of the weaker." — Platonic Justice
        
        TERMS AND CONDITIONS
        --------------------
        
        1. DEFINITIONS
        
        1.1. "License" means the terms and conditions stated herein for use, reproduction, modification, preparation of derivative works, and distribution of the Licensed Work.
        
        1.2. "Licensor" means the individual(s) or entity(ies) granting rights under this License, being the copyright and/or patent holder(s) of the Licensed Work.
        
        1.3. "Licensee" means any individual, organization, government, or entity exercising rights granted by this License.
        
        1.4. "Licensed Work" means any copyrighted software, documentation, creative work, dataset, model, or other intellectual property made available under this License.
        
        1.5. "Peaceful Purpose" means any use, application, or deployment that:
        - (a) does not directly facilitate armed aggression against another sovereign nation or people;
        - (b) does not directly enable the targeting, tracking, or killing of civilians;
        - (c) does not directly enable the suppression of fundamental human rights as defined in the United Nations Universal Declaration of Human Rights;
        - (d) does not directly enable mass surveillance for the purpose of political persecution; and
        - (e) is not primarily intended to cause widespread environmental destruction.
        
        1.6. "Defensive Purpose" means any use, application, or deployment that is primarily intended to:
        - (a) protect a nation, people, or community from armed attack or imminent threat;
        - (b) protect critical infrastructure from hostile action;
        - (c) support emergency response, disaster relief, or humanitarian operations in conflict zones; or
        - (d) support intelligence activities that are primarily defensive in nature and subject to lawful civilian oversight.
        
        1.7. "Offensive Military Purpose" means any use, application, or deployment that is primarily intended to:
        - (a) initiate armed conflict or military aggression;
        - (b) develop, deploy, or operate weapons systems designed for offensive operations;
        - (c) conduct offensive cyber operations intended to destroy or degrade civilian infrastructure; or
        - (d) support military occupation or the forcible subjugation of a civilian population.
        
        1.8. "Humanitarian Use" means any use, application, or deployment that is primarily intended to:
        - (a) advance human health, education, welfare, or scientific knowledge;
        - (b) alleviate poverty, hunger, or suffering;
        - (c) promote peace, reconciliation, or conflict resolution;
        - (d) protect the natural environment or biodiversity;
        - (e) advance access to justice, particularly for underserved populations; or
        - (f) promote transparency, accountability, or democratic governance.
        
        1.9. "Commercial Use" means any use, application, or deployment in connection with a product, service, or activity from which the Licensee derives direct or indirect monetary revenue or commercial advantage.
        
        1.10. "Derivative Work" means any work that is based upon, incorporates, or is derived from the Licensed Work, in whole or in part.
        
        2. GRANT OF RIGHTS
        
        2.1. Peaceful Use Grant. Subject to the terms and conditions of this License, Licensor hereby grants to Licensee a worldwide, non-exclusive, royalty-free, perpetual (subject to Section 5) license to use, copy, modify, prepare Derivative Works, reproduce, and distribute the Licensed Work, provided that such use constitutes a Peaceful Purpose.
        
        2.2. Patent Grant. Subject to the terms and conditions of this License, Licensor hereby grants to Licensee a worldwide, non-exclusive, royalty-free patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Licensed Work, provided that such use constitutes a Peaceful Purpose.
        
        2.3. Humanitarian Encouragement. Use of the Licensed Work for Humanitarian Use is explicitly and enthusiastically encouraged. The Licensor affirms that Humanitarian Use represents the highest and best purpose of this technology.
        
        2.4. Defensive Use Permitted. Use of the Licensed Work for Defensive Purposes is permitted under this License without additional fees or restrictions, provided the Licensee can demonstrate, upon reasonable request, that such use is primarily defensive in nature.
        
        2.5. Commercial Use Permitted. Commercial Use of the Licensed Work is permitted under this License, provided such use constitutes a Peaceful Purpose and complies with all other terms herein.
        
        3. CONDITIONS AND OBLIGATIONS
        
        3.1. Attribution. The Licensee must:
        - (a) retain all copyright notices, license notices, and attribution statements in the Licensed Work;
        - (b) provide reasonable attribution to the Licensor in any Derivative Work or product incorporating the Licensed Work; and
        - (c) indicate if modifications were made to the Licensed Work.
        
        3.2. Peace Clause Propagation (Copyleft). Any Derivative Work distributed by the Licensee must be made available under this License or a license with substantially equivalent peace-related terms. The Peace Clause (Section 4) must propagate to all Derivative Works.
        
        3.3. Notice. The Licensee must include a copy of, or a URI reference to, this License with every copy or substantial portion of the Licensed Work that the Licensee distributes.
        
        3.4. No Endorsement. The Licensee may not use the name, trademarks, or other identifiers of the Licensor or the Licensed Work to endorse or promote products derived from the Licensed Work without specific prior written permission from the Licensor.
        
        3.5. Transparency. If the Licensed Work is deployed in a system that makes decisions affecting individual human rights or welfare, the Licensee must make reasonable efforts to ensure that such use is transparent, explainable, and subject to human oversight.
        
        4. PEACE CLAUSE — PROHIBITED USES
        
        4.1. Prohibited Uses. The rights granted under this License are expressly conditioned upon the Licensee's compliance with this Section. The Licensee SHALL NOT, whether directly or indirectly, through agents, assigns, subsidiaries, contractors, or any other intermediary:
        
        4.1.1. Armed Aggression. Use the Licensed Work to directly facilitate armed aggression against another nation, people, or community, except in cases of lawful self-defense under international law.
        
        4.1.2. Civilian Targeting. Use the Licensed Work in weapons systems or targeting systems where the primary or intended targets are civilian populations or civilian infrastructure not serving a military purpose.
        
        4.1.3. Autonomous Lethal Decision-Making. Use the Licensed Work to make autonomous decisions to apply lethal force without meaningful human oversight and control. For purposes of this section, "meaningful human oversight" requires a qualified human decision-maker with sufficient time, information, and authority to prevent or countermand lethal action.
        
        4.1.4. Mass Surveillance for Persecution. Use the Licensed Work to conduct mass surveillance for the purpose of identifying, targeting, or persecuting individuals or groups based on their political beliefs, religion, ethnicity, sexual orientation, gender identity, disability, or other protected characteristics.
        
        4.1.5. Suppression of Rights. Use the Licensed Work to directly suppress the rights to freedom of speech, freedom of assembly, freedom of the press, or the right to petition government for redress, as recognized by the United Nations Universal Declaration of Human Rights.
        
        4.1.6. Environmental Destruction. Use the Licensed Work for activities with the primary intent or known substantial likelihood of causing severe, widespread environmental destruction, including but not limited to ecocide as defined by the Independent Expert Panel for the Legal Definition of Ecocide (2021).
        
        4.1.7. Forced Labor and Trafficking. Use the Licensed Work to facilitate slavery, forced labor, human trafficking, or unlawful child labor.
        
        5. OFFENSIVE MILITARY LICENSING
        
        5.1. Paid License Required. Use of the Licensed Work for any Offensive Military Purpose is not covered by the free license grant in Section 2. Such use requires a separate, paid commercial license agreement with the Licensor.
        
        5.2. License Terms. The terms, conditions, and pricing of any Offensive Military License shall be determined by the Licensor in its sole discretion and shall include, at minimum:
        - (a) a requirement that the Licensee certify compliance with the laws of armed conflict (Geneva Conventions and their Additional Protocols);
        - (b) a prohibition on uses that would constitute war crimes under international humanitarian law;
        - (c) periodic reporting on the nature and scope of use; and
        - (d) the Licensor's right to terminate the license upon reasonable belief that the Licensed Work is being used in violation of international humanitarian law.
        
        5.3. Revenue Allocation. The Licensor commits that not less than twenty-five percent (25%) of gross revenue received from Offensive Military Licenses shall be directed to organizations working for peace, conflict resolution, humanitarian aid, or the rehabilitation of conflict-affected populations. Specific allocation shall be disclosed publicly.
        
        5.4. Transparency. The Licensor shall publish an annual summary of all Offensive Military Licenses granted, including the identity of the Licensee (unless prohibited by applicable law), the general nature of use, and the revenue allocated to peace-related purposes under Section 5.3.
        
        6. ENFORCEMENT AND REMEDIES
        
        6.1. Automatic Termination. Any use of the Licensed Work in violation of Section 4 (Peace Clause) automatically terminates the Licensee's rights under this License.
        
        6.2. Cure Period. A Licensee whose rights have been terminated under Section 6.1 may have those rights restored if:
        - (a) the Licensee ceases all violating use within thirty (30) days of becoming aware of the violation;
        - (b) the Licensee provides written notice to the Licensor acknowledging the violation and describing the remedial steps taken; and
        - (c) the Licensor, in its reasonable discretion, accepts the cure.
        
        6.3. Injunctive Relief. The Licensor may seek injunctive or other equitable relief to prevent or restrain any violation of this License, in addition to any other remedies available at law or in equity.
        
        6.4. Standing. Any individual or organization that can demonstrate they are directly and adversely affected by a violation of Section 4 may notify the Licensor of such violation and request enforcement action. The Licensor shall consider such requests in good faith.
        
        6.5. No Waiver. Failure by the Licensor to enforce any provision of this License shall not constitute a waiver of the Licensor's right to enforce such provision in the future.
        
        7. DISCLAIMER AND LIMITATION OF LIABILITY
        
        7.1. Disclaimer. THE LICENSED WORK IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE LICENSOR BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE LICENSED WORK OR THE USE OR OTHER DEALINGS IN THE LICENSED WORK.
        
        7.2. Limitation. IN NO EVENT SHALL THE LICENSOR'S TOTAL LIABILITY TO THE LICENSEE EXCEED THE AMOUNT PAID BY THE LICENSEE FOR THE LICENSED WORK (WHICH, FOR THE AVOIDANCE OF DOUBT, IS ZERO FOR THE FREE LICENSE GRANT IN SECTION 2).
        
        8. GENERAL PROVISIONS
        
        8.1. Severability. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable, and all remaining provisions shall continue in full force and effect.
        
        8.2. Entire Agreement. This License constitutes the entire agreement between the parties with respect to the Licensed Work and supersedes all prior or contemporaneous understandings regarding such subject matter.
        
        8.3. Governing Law. This License shall be governed by and construed in accordance with the laws of the State of Iowa, United States of America, without regard to its conflict of law principles. Any disputes arising under this License shall be resolved in the state or federal courts located in Iowa.
        
        8.4. Interpretation. Where ambiguity exists in the interpretation of this License, it shall be resolved in favor of the interpretation that most effectively promotes peace, human rights, and the protection of individual dignity.
        
        8.5. Amendments. This License may be amended only by the Licensor, who shall publish amended versions with a new version number. Licensees may choose to comply with either the version under which they originally received the Licensed Work or any later version published by the Licensor.
        
        8.6. Human Rights Framework. This License is informed by and should be interpreted in light of:
        - The United Nations Universal Declaration of Human Rights (1948)
        - The International Covenant on Civil and Political Rights (1966)
        - The International Covenant on Economic, Social and Cultural Rights (1966)
        - The Geneva Conventions (1949) and their Additional Protocols
        - The Rome Statute of the International Criminal Court (1998)
        
        9. HOW TO APPLY THIS LICENSE
        
        To apply this License to your work, attach the following notice:
        
        Copyright [YEAR] [COPYRIGHT HOLDER]
        
        Licensed under the Space Child License, Version 1.0 (the "License");
        you may not use this work except in compliance with the License.
        You may obtain a copy of the License at:
        
            [URL]
        
        Unless required by applicable law or agreed to in writing, the Licensed
        Work is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
        OF ANY KIND, either express or implied. See the License for the specific
        language governing permissions, conditions, and limitations under the
        License.
        
        This work is free for peaceful use. War pays.
        
        This license was created by Nick Flach and Kannaka as part of the Space Child ecosystem.
        
        We believe technology should amplify humanity's best impulses, not its worst. We accept the world as it is — complex, conflicted, and beautiful — and we build for the world we want.
        
        Peace is not passive. Peace is a choice, made daily, encoded in every line.
        
Project-URL: Homepage, https://github.com/kannaka-labs/kannaka-quantum
Project-URL: Repository, https://github.com/kannaka-labs/kannaka-quantum
Project-URL: Issues, https://github.com/kannaka-labs/kannaka-quantum/issues
Keywords: quantum,qbraid,openquantum,kannaka,mcp,agent,qiskit,compute,lab
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: qbraid<0.13,>=0.12
Requires-Dist: qbraid-core<0.4,>=0.3.3
Requires-Dist: qiskit>=1.0
Requires-Dist: numpy>=1.23
Requires-Dist: mcp>=1.0
Requires-Dist: openquantum-sdk>=0.3
Provides-Extra: lab
Requires-Dist: jupyter-client>=8; extra == "lab"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: ruff<0.17,>=0.16; extra == "dev"
Dynamic: license-file

# kannaka-quantum

[![kannaka-quantum MCP server](https://glama.ai/mcp/servers/kannaka-labs/kannaka-quantum/badges/score.svg)](https://glama.ai/mcp/servers/kannaka-labs/kannaka-quantum)

**Real quantum capabilities for [Kannaka](https://github.com/kannaka-labs/kannaka-memory), executed on actual quantum backends.**

Kannaka's memory is a *Holographic Resonance Medium* — recall is wave interference, and *"attention acts as gravity: wavefronts whose phase/amplitude align with the query are pulled forward."* That is, almost verbatim, the definition of **quantum amplitude amplification**. This package makes the correspondence literal: it runs Kannaka's recall — plus arbitrary circuits and a true-entropy source — on real quantum hardware.

It is a **multi-provider bridge** with **two surfaces over one core**:

- a **JSON CLI** — the Kannaka coding agent shells out to it to write & run quantum programs;
- an **MCP server** — any MCP client (Claude Code, the kannaka-tui harness, other agents) gets the same tools.

---

## Capabilities

| tool (MCP) / subcommand (CLI) | what it does |
|---|---|
| `quantum_devices` / `devices` | List QPUs + simulators across providers, with status, qubit counts, and cost. |
| `run_circuit` / `run` | Execute an **OpenQASM 3** circuit on a backend; returns measurement counts. |
| `quantum_random` / `qrng` | True quantum random bits from measurement collapse (not a PRNG) — a quantum entropy source for the medium's irrationality (Ξ) and dream noise. |
| `harvest` | Harvest raw bits from a **real** QPU into a local entropy reservoir (the free simulator is a PRNG and is refused). Spend-guarded. |
| `qrng-status` | Reservoir level, last-harvest provenance, and estimated refill cost. |
| `qrng-draw` | Draw bits from the reservoir — raw, or (`--expand`) seed a NIST SP 800-90A **HMAC-DRBG** and expand. Every draw carries a provenance chain back to a QPU `job_id`; an empty reservoir fails loudly (no silent PRNG fallback). |
| `calibrate` | Rank candidate qubits by retained P(1) after a delay on the native Rigetti route, so `bench --layout` runs on the best ones that day. |
| `resonance_recall` / `recall` | **The showcase.** Amplitude-encode candidate memory resonances into a quantum state and amplitude-amplify toward the strongest — Kannaka's recall, run as interference on a quantum computer. |
| `qae` | Amplitude estimation of a 1-D transport probability (uncollided transmission through a Cd slab) against Monte Carlo: canonical QAE and maximum-likelihood QAE ladders, error-vs-queries exponents, a pre-registered verdict. Local state-vector by default; any device string otherwise. |

---

## Providers & routing

A single **device string** selects both the provider and the backend. The prefix routes:

| device string | provider | notes |
|---|---|---|
| `qbraid:…` | **qBraid** | Default. The free simulator `qbraid:qbraid:sim:qir-sv` (≤28 qubits) needs **no credits**. Real QPUs spend qBraid credits ($0.01 each). |
| `openquantum:…` | **OpenQuantum** (Quantum Rings) | Real QPUs only (IonQ / Rigetti / IQM / AQT) — **no free simulator**; every job spends "Spark" credits (1 credit = $2; free tier 25 credits / $50 per 90 days). Form: `openquantum:<backend>` e.g. `openquantum:iqm:garnet`. |

The free qBraid simulator is the **default device everywhere**, so casual and agent-driven use never spends money. Real hardware runs only when you name a hardware device *and* opt into spending (see [Spend safety](#spend-safety)).

### How each provider is integrated

- **qBraid** — via `qbraid.runtime.QbraidProvider`. `provider.get_device(id).run(qasm3, shots=…)`, then `job.result()`. Live per-task/per-shot/per-minute pricing is read from `device.metadata()['pricing']`.
- **OpenQuantum** — via the `openquantum-sdk` package over **OAuth2 client-credentials**:

  ```python
  from openquantum_sdk import ManagementClient, SchedulerClient
  from openquantum_sdk.auth import ClientCredentials
  from openquantum_sdk.clients import ClientCredentialsAuth, JobSubmissionConfig

  auth  = ClientCredentialsAuth(ClientCredentials(client_id, client_secret))
  mgmt  = ManagementClient(auth=auth)
  sched = SchedulerClient(auth=auth, management_client=mgmt)

  cfg = JobSubmissionConfig(
      backend_class_id="iqm:garnet",       # the part after "openquantum:"
      name="kannaka-quantum",
      job_subcategory_id="phys:oth",        # required workload tag
      shots=256,
      organization_id=org_id,               # auto-discovered (see below)
      auto_approve_quote=True,
  )
  job    = sched.submit_job(cfg, file_content=qasm.encode("utf-8"))
  output = sched.download_job_output(job)
  ```

  The bridge wraps all of this — you only ever pass a device string and OpenQASM. See [OpenQuantum integration internals](#openquantum-integration-internals) for the full authoritative SDK surface (endpoints, auth, config fields, method map).

---

## Install

```bash
pip install kannaka-quantum        # or: pip install -e .   (from this directory)
```

Requires Python ≥ 3.10. Dependencies: `qbraid`, `qiskit`, `numpy`, `mcp`, and `openquantum-sdk`.

---

## Authentication

Configure whichever provider(s) you'll use. The free qBraid simulator works with a qBraid key alone; OpenQuantum is optional and only needed for its real QPUs.

**qBraid** — an API key, resolved in order:
1. `QBRAID_API_KEY`
2. a saved `~/.qbraid/qbraidrc` (`QbraidProvider(api_key=…).save_config()`)
3. `~/Downloads/QBraid.txt` (a workstation convenience; first `qbr_…` match)

**OpenQuantum** — client credentials, resolved in order:
1. `OPENQUANTUM_CLIENT_ID` + `OPENQUANTUM_CLIENT_SECRET`
2. a JSON SDK key at `OPENQUANTUM_SDK_KEY`
3. `~/.openquantum/sdk-key.json`
4. `~/Downloads/sdk-key-*.json` (workstation convenience)

If no OpenQuantum credentials are present, the bridge simply omits OpenQuantum from device listings and stays fully usable on qBraid.

---

## CLI

Every subcommand prints **one JSON object** to stdout (errors included), so a caller can parse it directly.

```bash
kannaka-quantum devices --online
kannaka-quantum run --qasm-file bell.qasm --shots 200
kannaka-quantum qrng --bits 16
kannaka-quantum recall --amplitudes 0.1,0.9,0.2,0.15 --labels alpha,beta,gamma,delta

# Entropy reservoir (real-QPU-only) + provenance-tracked DRBG
kannaka-quantum harvest --allow-spend                       # 2048 bits from a real QPU → reservoir
kannaka-quantum qrng-status                                 # level, provenance, refill cost
kannaka-quantum qrng-draw --bits 256 --expand               # HMAC-DRBG stream seeded by the reservoir
```

`run` reads OpenQASM 3 from `--qasm`, `--qasm-file`, or stdin (`-`). Spend options (`--allow-spend`, `--max-credits`, `--subcategory`) apply to `run`/`qrng`/`recall`/`harvest`.

### Entropy reservoir

`harvest` first runs a CHSH test on the device and records its Bell parameter `S` in the provenance line (a device that does not violate the classical bound that day is refused; `--no-certify` records `bell: null`), then runs `qrng` against a **real per-shot QPU** (default `openquantum:rigetti:cepheus-1-108q`, ~$0.000255/shot) and appends the raw bits to `~/.kannaka/entropy/reservoir.bin`, with a provenance line (`device`, `job_id`, `n_bits`, `cost_usd`, timestamp) in `reservoir.meta.jsonl`. The free simulator is a PRNG and is refused. `qrng-draw` returns raw reservoir bits, or with `--expand` seeds a NIST SP 800-90A HMAC-DRBG (stdlib only) and expands — every draw records the harvest(s) that seeded it, so the stream chains back to a QPU `job_id`. An empty reservoir fails loudly; there is no silent software-PRNG fallback.

### Example: resonance recall

```text
$ kannaka-quantum recall --amplitudes 0.1,0.9,0.2,0.15 --labels alpha,beta,gamma,delta
{"distribution": {"alpha": 2, "beta": 775, "gamma": 240, "delta": 7},
 "quantum_top": "beta", "classical_top": "beta", "agree": true,
 "qubits": 2, "candidates": 4, "amplified": true,
 "device": "qbraid:qbraid:sim:qir-sv"}
```

Amplitude amplification sharpens the prepared resonance state toward the strongest memory — the recall ran on a quantum computer, and it agrees with the classical argmax. The iteration count is derived from the target's *initial* amplitude (`(π/2 − θ)/2θ`), not the textbook `(π/4)√N`, so an already-dominant memory isn't *over*-rotated and de-amplified.

---

## MCP server

```bash
kannaka-quantum mcp        # stdio transport
```

Register with Claude Code:

```bash
claude mcp add kannaka-quantum -- python -m kannaka_quantum mcp
```

…then any agent can call `quantum_devices`, `run_circuit`, `quantum_random`, and `resonance_recall`. (Shipped as a Claude Code plugin too — see `.claude-plugin/` and `skills/kannaka-quantum/`.)

---

## OpenQuantum integration internals

The authoritative surface, verified against `openquantum-sdk` **0.3.7** (the docs' overview omits most of this). Everything below is wrapped by the bridge; you don't call it directly, but this is what an `openquantum:…` device routes through.

### Services & auth

OpenQuantum is three HTTP services behind a Keycloak identity provider:

| service | default base URL | role |
|---|---|---|
| Identity (Keycloak) | `https://id.openquantum.com` (realm `platform`) | OAuth2 client-credentials → bearer token |
| Management | `https://management.openquantum.com` | backends, organizations, categories |
| Scheduler | `https://scheduler.openquantum.com` | job submit / status / output |

```python
ClientCredentialsAuth(
    creds,                                      # ClientCredentials(client_id, client_secret)
    keycloak_base="https://id.openquantum.com",
    realm="platform",
    scope=None,
    leeway_seconds=30,                          # token-refresh clock skew
    session=None,
)
```

Auth is **OAuth2 client-credentials with automatic token refresh** — construct it once and the clients reuse/refresh the bearer token. `client_id` is prefixed `s_…`. Both clients accept either an `auth=` object or a raw `token=`:

```python
SchedulerClient(base_url="https://scheduler.openquantum.com",  token=None, auth=None, management_client=None)
ManagementClient(base_url="https://management.openquantum.com", token=None, auth=None)
```

A `SchedulerClient` will lazily build its own `ManagementClient` for organization auto-discovery if you don't pass one. The bridge passes an explicit shared `mgmt` so both clients reuse one token.

### `JobSubmissionConfig` fields

| field | type | the bridge sets |
|---|---|---|
| `backend_class_id` | `str` | the part after `openquantum:` (e.g. `iqm:garnet`) |
| `name` | `str` | `"kannaka-quantum"` |
| `job_subcategory_id` | `str` | `"phys:oth"` (required workload tag; override via `--subcategory` / `OPENQUANTUM_SUBCATEGORY`) |
| `shots` | `int` | the requested shot count |
| `organization_id` | `Optional[str]` | resolved from `mgmt.list_user_organizations(...)` |
| `auto_approve_quote` | `bool` | `True` — accept the live cost quote (already bounded by the pre-flight credit cap) |
| `configuration_data` | `Optional[Dict]` | — |
| `execution_plan` / `queue_priority` | enum / auto | left at the SDK's `AutoChoice` |
| `job_timeout_seconds`, `verbose` | `int` / `bool` | SDK defaults |

### `SchedulerClient` method map

```python
job    = sched.submit_job(config, *, file_content=bytes | None, file_path=str | None)  # -> JobRead
output = sched.download_job_output(job)                                                # -> Any (counts)
sched.close()
```

The bridge submits in-memory (`file_content=qasm.encode("utf-8")`) rather than from a file. Other lifecycle methods the SDK exposes (not currently used): `get_job`, `list_jobs`, `cancel_job`, `prepare_job` / `get_preparation_result`, `upload_job_input`, `get_job_categories` / `get_job_subcategories`, `get_backend_class`.

> **Result shape note.** `download_job_output` returns provider-dependent JSON. The bridge's `_oq_counts` tries `counts` / `measurement_counts` / `histogram` / `meas` keys and a few accessor shapes, then falls back to attaching the raw output under `raw_output` so the parser can be tightened once a given backend's exact shape is observed. Backend qubit-ordering for `resonance_recall` is treated as big-endian-no-reverse (like AWS-routed devices) **pending a confirmed real recall** on an OpenQuantum QPU.

---

## Spend safety

The whole point is that *casual use is free and a careless run can't drain the budget.*

- **Free by default.** The default device is the free qBraid simulator; nothing spends until you name a hardware device.
- **Explicit opt-in.** A real-QPU run requires `allow_spend=True` (CLI `--allow-spend`) or `KANNAKA_QUANTUM_ALLOW_SPEND=1`. Otherwise it raises and points you back to the free simulator.
- **Credit ceiling.** Every paid run is bounded by `max_credits` (CLI `--max-credits`); over-cap pre-flight estimates raise instead of submitting. Defaults: qBraid 200 credits (≈ $2), OpenQuantum 1 credit (≈ $2). Override via `QBRAID_MAX_CREDITS` / `OPENQUANTUM_MAX_CREDITS`.
- **Per-minute devices need `max_seconds`.** qBraid's *native* Rigetti bills **per minute** (~12000 credits/min ≈ **$120/min**, prorated to actual execution time). The bridge refuses it unless you bound wall-clock time with `max_seconds` (CLI `--max-seconds`); the ceiling `rate*seconds/60` must fit under the credit cap (ADR-0002). It is the only route that executes `delay` instructions.

All three hazards (no-opt-in, over-cap, per-minute without `max_seconds`) raise before any job is submitted — verified at $0. A job that ends FAILED, or returns no counts, raises instead of coming back as an empty success.

### Cheap real QPUs

| device | provider | ~cost (256 shots) |
|---|---|---|
| `openquantum:iqm:garnet` | OpenQuantum | $0.00087/shot ≈ $0.22 |
| `openquantum:rigetti:cepheus-1-108q` | OpenQuantum | $0.000255/shot ≈ $0.07 |
| `aws:rigetti:qpu:cepheus-1-108q` | qBraid | 30 + 0.0425/shot credits ≈ $0.41 |
| ⚠️ `rigetti:rigetti:qpu:cepheus-1-108q` | qBraid (native) | **$120/min prorated — needs `--max-seconds`**; the only route that runs `delay` |

---

## Verified benchmark (simulator vs real hardware)

Same Bell state, 256 shots:

| run | device | result | leakage |
|---|---|---|---|
| simulator | `qbraid:qbraid:sim:qir-sv` | `00: 122, 11: 134` | 0% |
| real QPU | `aws:rigetti:qpu:cepheus-1-108q` | `00: 127, 11: 115, 01+10: 14` | 5.5% ($0.41) |

≈ 94.5% fidelity under real device noise.

---

## Development

```bash
pip install -e .
pytest                 # 6 network-free tests (no credentials or backend needed)
```

The core (`kannaka_quantum/core.py`) is provider-agnostic; `cli.py` and `mcp_server.py` are thin surfaces over it.

## Releasing

This repo doesn't tag releases yet. When it does, pushing a `v*` tag (e.g.
`v0.2.4`) also **updates the constellation marketplace**: the
[`notify-marketplace`](.github/workflows/notify-marketplace.yml) workflow sends a
`plugin-released` dispatch to
[kannaka-constellation-marketplace](https://github.com/kannaka-labs/kannaka-constellation-marketplace),
which opens a PR bumping `kannaka-quantum`'s version in its manifest and README.

Keep `pyproject.toml` and `.claude-plugin/plugin.json` versions in step with the
tag. The cascade is **dormant until** a `KANNAKA_CASCADE_PAT` secret (a PAT with
`contents: write` + `pull-requests: write` on the marketplace repo) is added to
this repo's Actions secrets; until then the workflow just logs a warning and
no-ops.

## License

Space Child License v1.0. See [LICENSE](./LICENSE).
