# Architecture

QubitOS is a **pulse-feedback runtime**: the kernel-shape layer between
compiler intent and quantum hardware that handles Hamiltonians,
calibrations, timing, noise, drift, and (in v0.6.0 onward)
measurement-conditioned dynamics.

Pulse-first, not gate-first. You specify the Hamiltonian and the target
unitary; QubitOS optimizes the control pulses and tracks the
calibration, timing, and error budget that surround them. Gate-level
abstractions discard physics that the kernel preserves: decoherence
during gates, crosstalk, leakage, and feedback latency.

## Repository layout

QubitOS is a monorepo at
[qubit-os/qubit-os](https://github.com/qubit-os/qubit-os):

| Module    | Purpose                                                 | Language |
|-----------|---------------------------------------------------------|----------|
| `core/`   | Python: GRAPE, SME, calibration, scheduling, CLI        | Python   |
| `hal/`    | Rust: gRPC server, backend dispatch, Lindblad and SME   | Rust     |
| `proto/`  | Protocol Buffer API contracts between core and HAL      | Protobuf |

The previous split repositories (`qubit-os-core`, `qubit-os-hardware`,
`qubit-os-proto`) are archived and redirect to the monorepo.

## Overview

```
       Python scripts        Jupyter notebooks       CLI (qubit-os)
              |                      |                      |
              +----------+-----------+----------+-----------+
                         |                      |
                         v                      v
+--------------------------------------------------------------+
|                            core/                              |
|                                                               |
|  pulsegen/     GRAPE optimizer, Hamiltonian construction,     |
|                pulse shapes (DRAG, Gaussian, square)          |
|  sme/          Stochastic master equation solver (v0.6.0)     |
|  feedback/     Lyapunov feedback controller, comparison       |
|                framework, visualization (v0.7.0)              |
|  lindblad/     Lindblad master equation solver                |
|  calibrator/   T1/T2 fitting, drift detection, fingerprinting |
|  temporal/     TimePoint, TemporalConstraint, PulseSequence,  |
|                DecoherenceBudget                              |
|  error_budget/ Cumulative error accounting                    |
|  provenance/   Merkle tree experiment provenance              |
|  compilation/  Native gate compilation traits                 |
|  validation/   Input validation; agentbible decoration        |
|  client/       gRPC client to HAL                             |
|  cli/          qubit-os entry point                           |
+--------------------------------------------------------------+
                              |
                              | gRPC / REST   (or --local: in-process)
                              v
+--------------------------------------------------------------+
|                             hal/                              |
|                                                               |
|  server/       tonic gRPC + axum REST                         |
|  grape/        Rust-native GRAPE (Pade [13/13]), ~10x Python  |
|  lindblad/     Rust-native Lindblad solver; FFI bridge for    |
|                the C fast path (stretch goal)                 |
|  sme/          Rust-native SME (Itô SDE), Rayon-parallel      |
|                ensemble                                        |
|  feedback/     Rust Lyapunov feedback law hot path (v0.7.0),  |
|                ~150x faster than the Python reference         |
|  backend/      Backend dispatch: QuTiP, IQM, IBM, AWS         |
|  temporal/     Rust mirror of core/temporal/ validation       |
+--------------------------------------------------------------+
                              |
                              v
                    Backend (see "Backend integration honesty")
```

## The five planes

The kernel is the union of five concerns. Each plane has its own module
boundaries in `core/` and `hal/`, and each is meant to be replaceable
without rewriting the others.

### 1. Control kernel

Hamiltonian in, optimized pulses out. GRAPE / DRAG / Gaussian /
Lyapunov feedback (v0.7.0). Pulse scheduling, timing constraints,
hardware-aware validation. Lives in `core/pulsegen/`, `core/feedback/`,
`hal/grape/`, and `hal/feedback/`.

### 2. Calibration / state plane

Device state as live runtime state, not static config. Calibration
loading, drift detection, T1/T2 fitting, error budgets, experiment
provenance. Lives in `core/calibrator/`, `core/error_budget/`, and
`core/provenance/`.

### 3. Backend ABI

A stable typed boundary for hardware and simulators. The
`QuantumBackend` trait in Rust, the gRPC contract in `proto/`, and the
Backend SDK in `hal/docs/BACKEND-SDK.txt`. Documentation deliverable,
not a maintenance commitment for arbitrary cloud backends.

### 4. Simulation / performance plane

A serious execution path, not notebook glue. Rust-native solvers as
production tier; QuTiP retained as validation oracle only. The C
bare-metal fast path (v0.6.0 stretch goal) and the FPGA
fast path (future work) extend the same propagator algorithm
through additional tiers. See `hal/grape/`, `hal/lindblad/`, `hal/sme/`.

### 5. Feedback plane

Stochastic master equation support, closed-loop controllers,
measurement-conditioned updates, reproducible crossover studies vs
open-loop control. v0.6.0 landed the SME runtime; v0.7.0 adds the
Lyapunov controller; v0.8.0 brings the 3-level transmon campaign.
Lives in `core/sme/` and `hal/sme/` today; `core/feedback/` and
`hal/feedback/` are added in v0.7.0.

## Backend integration honesty

IQM is the primary live integration and the only backend exercised
against real hardware. IBM Quantum, AWS Braket, and the QuTiP simulator
are mock-tested and demonstrate the backend abstraction; they are not
maintained as production cloud integrations. The README and the docs
landing page state this same way; the catalog metadata on each backend
adapter encodes it as well.

| Backend        | Status                                            |
|----------------|---------------------------------------------------|
| IQM Resonance  | Live; exercised against real hardware             |
| QuTiP simulator | Demonstrated through the abstraction (mock-tested) |
| IBM Quantum    | Demonstrated through the abstraction (mock-tested) |
| AWS Braket     | Demonstrated through the abstraction (mock-tested) |

## Data flow

### Open-loop pulse execution (v0.5.0 and earlier)

```
user                                  HamiltonianSpec
 |                                          |
 v                                          v
core.pulsegen.generate_pulse  --GRAPE-->  PulseShape
 |
 +-- core.validation.* (boundary checks; agentbible)
 |
 v
core.client.HALClient  --gRPC/REST-->  hal.server
                                         |
                                         v
                                       hal.backend (IQM / QuTiP / ...)
                                         |
                                         v
                                       MeasurementResult
                                         |
                                         v
                                       provenance hash on the way back
```

### Conditional pulse execution (v0.6.0 SME, no feedback)

```
user
 |
 v
core.sme.SMESolver.solve_trajectory(initial_rho, hamiltonians, ...)
 |
 +-- Euler-Maruyama Itô SDE integrator
 +-- core.validation.* on the conditional rho per step
 |
 v
SMEResult (final_rho, measurement_record, fidelity_trajectory, ...)
```

### Closed-loop pulse execution (v0.7.0 Lyapunov, forthcoming)

```
user
 |
 v
core.feedback.solve_with_feedback(solver, controller, ...)
 |
 +-- SME step
 +-- LyapunovController.correction(rho_c, rho_target)
 +-- Hamiltonian update H(t) += delta_Omega(t)
 +-- Feedback delay flows through core.temporal.TemporalConstraint
 |
 v
FeedbackResult (SMEResult + correction history + energy cost)
```

## Protocol contracts

The gRPC and Python boundaries are defined in `proto/quantum/pulse/v1/`.
Versioning is path-based; breaking changes require a new path version
(v2, v3, ...). Generated bindings are committed to the repository so
that consumers can `pip install` without the proto toolchain and CI
runs without `protoc` / `buf`.

Selected current messages:

```protobuf
message PulseShape          { ... }
message MeasurementResult   { ... provenance_hash, projected_fidelity ... }
message HamiltonianSpec     { ... }
message TimePoint           { nominal_ns, precision_ns, jitter_bound_ns }
message TemporalConstraint  { Simultaneous | Sequential | Aligned | MaxDelay }
message PulseSequence       { time-aware sequence of pulses }
message DecoherenceBudget   { cumulative T1/T2 consumption }
message ErrorBudget         { multiplicative infidelity + decoherence ... }
message ProvenanceTree      { Merkle node hashes per experiment input }
message SMEConfig           { v0.6.0 }
message SMEResult           { v0.6.0 }
```

## Extension points

The kernel is extensible without forking.

### Adding a new backend

1. Implement `QuantumBackend` in `hal/backend/<name>/`.
2. Pass the backend certification tests documented in
   [hal/docs/BACKEND-SDK.txt](https://github.com/qubit-os/qubit-os/blob/main/hal/docs/BACKEND-SDK.txt).
3. Register in the backend factory.

### Adding a new optimizer

1. Implement an optimizer class with an `optimize()` method returning
   a `GrapeResult`-compatible result.
2. Decorate numerical surfaces with agentbible at the module boundary.
3. Register in the optimizer factory if you want it CLI-reachable.

### Adding a new feedback controller (v0.7.0+)

1. Implement a controller class with a `correction(rho_c, rho_target)`
   method returning the per-axis Hamiltonian correction vector.
2. Decorate the controller's Lyapunov-function output with agentbible.
3. Wire into `core/feedback/controller.py` dispatch by name.

## Reproducibility and integrity

Three load-bearing properties:

- **Provenance Merkle tree**: every measurement result carries a hash
  that lets you `diff()` two experiment runs and identify what
  changed. Covers calibration fingerprint, pulse sequence, GRAPE
  config, software versions.
- **agentbible decoration**: numerical surfaces (density matrices,
  unitaries, probability vectors, Lyapunov functions in v0.7.0) are
  validated at the module boundary where they are emitted, not deep
  inside hot loops.
- **Golden file tests**: deterministic numerical code (GRAPE output,
  Lindblad results) has pinned golden files. Tolerances are tiered:
  strict (1e-10) for GRAPE goldens, looser (1e-8) for QuTiP-execution
  cross-validation where CI floating-point drift is real.

## Performance characteristics

| Component                   | Typical latency      | Notes                          |
|-----------------------------|----------------------|--------------------------------|
| GRAPE optimization (single-qubit) | 100 ms – 10 s   | Depends on fidelity target     |
| Rust GRAPE vs Python GRAPE  | ~10× speedup         | Measured on single-qubit gates |
| gRPC round-trip             | 1–10 ms              | Local network                  |
| SME single trajectory       | 10–100 ms            | Python; dimension-dependent    |
| SME ensemble (Rayon, N=1000) | 1–10 s              | Rust; scales linearly in cores |
| Pulse execution             | 10–1000 μs           | Gate duration                  |
| Readout / measurement       | 1–10 μs              | Hardware                       |

## Related documentation

- [API Reference](../api/index.txt) — Python, REST, gRPC surfaces
- [Quickstart](../guides/quickstart.txt) — getting started
- [CLI Reference](../api/cli.txt) — `qubit-os` subcommands
- [Backend SDK](https://github.com/qubit-os/qubit-os/blob/main/hal/docs/BACKEND-SDK.txt)
- [Design specs](../specs/README.txt) — per-subsystem design documents
- [Strategy](https://github.com/qubit-os/qubit-os/blob/main/README.txt) — the kernel claim, on the top-level README
