Skip to main content
Glama
README.md
# Qecguard

Qecguard lints and inspects Stim `.dem` v1.15 detector error models, synthesizes rotated-surface and repetition DEMs, samples deterministic syndromes, benchmarks Union-Find and MWPM-approx decoders, sweeps multi-distance threshold curves, and audits QPU calibration drift. Version `0.1.0`; changes are listed in `CHANGELOG.md`.

## Quick Start

[Try Qecguard on Apify](https://apify.com/raydeoliveira/qecguard-mcp). Run the prefilled 2-detector Stim `.dem` v1.15 lint sample, then open the default dataset. The single row reports `data.valid` as **`true`**, `data.stats.numDetectors` as **`2`**, `data.stats.numObservables` as **`1`**, `data.stats.numErrors` as **`3`**, and `data.stats.errorCount` as **`0`**. This example uses zero paid Actor events.

Lint a 2-detector Stim `.dem` v1.15 model via the hosted Streamable HTTP MCP endpoint (`2025-03-26`). This free call needs only curl.

```bash
curl -sS https://qecguard-mcp.raymond-deoliveira.workers.dev/mcp \
  -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"qec_lint_dem","arguments":{"dem":"error(0.01) D0\nerror(0.01) D0 D1\nerror(0.01) D1 L0\ndetector(0, 0, 0) D0\ndetector(1, 0, 0) D1\nlogical_observable L0\n"}}}'
```

Under `result.structuredContent`, `qec_lint_dem` returns `valid: true`, `stats.numDetectors: 2`, `stats.numObservables: 1`, `stats.numErrors: 3`, and `stats.errorCount: 0`. Inspecting the same DEM with `qec_inspect_dem` returns `graphlikeEdges: 3`, `hyperedges: 0`, `graphlikeFraction: 1`, and `dEffLowerBound: 3`. To keep the example handy, star [Qecguard on GitHub](https://github.com/raydeoliveira/qecguard).

### Synthesize and benchmark a Willow distance-3 surface code

Synthesize a 3-round rotated-surface DEM calibrated to `willow-105` (`17` physical qubits, `24` detectors, `76` error mechanisms) and decode `1,000` seeded shots (`seed: 42`) with both Union-Find and MWPM-approx (`qec_decode_benchmark`, `$0.005`/call via x402 v2 or Polar Pro key, or free locally via CLI/stdio MCP):

| Metric | Value |
|---|---|
| `willow-105` `d=3` `physicalQubits` / `numDetectors` | `17` / `24` |
| Union-Find `logicalErrorRate` (`1,000` shots) | `0.009` (`avgDecodeUs: 1.5488`) |
| MWPM-approx `logicalErrorRate` (`1,000` shots) | `0.008` (`avgDecodeUs: 2.2207`) |
| Decoder agreement (`agreementRate`) | `0.999` (`speedupFactor: 1.4338`) |
| Threshold sweep `d=[3,5,7]` (`300` shots/pt) `lambdaSuppression` | `3.7804` (`belowThreshold: true`) |

## What It Does / What It Does Not Do

| Surface / Tool | Tier / Price | What It Does |
|---|---|---|
| `qec_lint_dem` / `qecguard lint-dem` | Free (`$0`) | Stim `.dem` v1.15 lexer, parser, and static validator ($p \in [0, 0.5]$, undeclared `D#`/`L#`, cancelling duplicates, orphaned `^` hyperedges, truncation sentinel at `256`) |
| `qec_inspect_dem` / `qecguard inspect-dem` | Free (`$0`) | Graph/hypergraph metrics: `numDetectors`, `numObservables`, `numErrors`, `graphlikeEdges`, `hyperedges`, `maxDegree`, `connectedComponents`, `coordBounds`, exact graphlike `dEffLowerBound` |
| `qec_synth_dem` / `qecguard synth-dem` | Free (`$0`) | Deterministic rotated-surface (`2d^2-1` physical qubits) and repetition (`2d-1`) `.dem` v1.15 generator for `d=3..11`, `rounds=1..100`, and `willow-105`, `sycamore-54`, `ibm-heron-133` |
| `qec_sample_syndromes` / `qecguard sample` | Free (`$0`) | Seeded Mulberry32 deterministic syndrome and observable-flip sampler (`<= 100,000` shots, optional raw vectors `<= 4,096` shots / `524,288` bits) |
| `qec_decode_benchmark` / `qecguard decode` | Metered (`$0.005`) | Deterministic Union-Find (`uf`) and lightweight MWPM-approx (`mwpm-approx` or `both`) decoder benchmark on DEM + explicit syndromes or seeded shots |
| `qec_threshold_sweep` / `qecguard threshold` | Metered (`$0.015`) | Multi-distance and multi-noise-scale sweep (`<= 36` points, `<= 50,000` shots) fitting `lambdaSuppression`, `thresholdEstimate`, `breakEvenMargin`, and Willow baseline comparison |
| `qec_drift_shield` / `qecguard shield` | Metered (`$0.010`) | Baseline vs current calibration snapshot drift audit (`PASS \| DEGRADED \| ABORT_BELOW_THRESHOLD`), supporting `cycleTimeUs`/`cycleUs`, per-coupler hotspots, and patch relocation guidance |
| HTTP `402` MCP & stdio MCP | MCP `2025-03-26` | Cloudflare Worker at `https://qecguard-mcp.raymond-deoliveira.workers.dev/mcp` (`GET`/`HEAD /health`, `/llms.txt`, `/.well-known/mcp/server-card.json`, `POST /mcp` with 1..64 JSON-RPC batches, Free, Bearer, Polar `/validate`, deferred x402 v2 `/verify`+`/settle`) plus `serve-mcp --stdio` |
| Apify Actor & Standby MCP | PPE / Standby | Single (`{ tool, arguments }`) and batch (`{ calls }`) Dataset/`OUTPUT` runs plus Standby HTTP `/mcp` with readiness probe and Pay-Per-Event charging |

**What It Does Not Do**:
- No physical QPU hardware drivers, pulse-level execution, or paid IBM/Braket/Google cloud quantum credentials (`$0` Day 1 stateless compute only).
- No remote `.dem` URL fetching (inline bounded payloads only; `<= 262,144` bytes per payload).
- No full arbitrary-hypergraph exponential solver: `qec_decode_benchmark` splits hyperedges cleanly onto graphlike edges (`dEffLowerBound` inspects exact shortest graphlike logical cycles).

## Install & Uninstall

Use the hosted endpoint with `curl` or any MCP client. The public GitHub repository contains documentation, skill metadata, and packaging manifests. The local CLI and tests require a source checkout.

The source checkout requires Node.js `>= 22.18.0` for native TypeScript type stripping (`0` runtime and `0` dev npm dependencies, `340,611` bytes / `332.6 KiB` source across `44` TypeScript files and `8,089` lines in `src/`, `412 KB` `src/` on disk, `888 KB` project total via `du -sk`):

```bash
node --test tests/*.test.ts
node --test e2e/*.test.ts
```

Measured runs on `node v25.9.0` (macOS):
- Unit & integration (`node --test tests/*.test.ts`): `80` tests across `20` suites in `12` test files (`80` pass, `0` fail, `0` skipped).
- End-to-end (`node --test e2e/*.test.ts`): `147` tests across `14` test files (`147` pass, `0` fail, `0` skipped).
- Total: `227` tests (`227` pass, `0` fail).
- Representative CLI latency (median of `5` runs after `1` warm-up on `node v25.9.0`): `156.2 ms` (`synth-dem --preset willow-105 --distance 3 --rounds 3 --seed 42 --json`, range `149.2–160.1 ms`).

Install the agent skill reference from GitHub:

```bash
npx skills add raydeoliveira/qecguard
```

Connect Claude Code to the hosted MCP endpoint (free tools work without credentials; pass `-H "X-Polar-License-Key: ..."` for metered tools):

```bash
claude mcp add --transport http qecguard https://qecguard-mcp.raymond-deoliveira.workers.dev/mcp
```

For clients using `mcpServers` JSON:

```json
{
  "mcpServers": {
    "qecguard": {
      "url": "https://qecguard-mcp.raymond-deoliveira.workers.dev/mcp"
    }
  }
}
```

Hosted & discovery links:
- **Live Cloudflare Worker**: `https://qecguard-mcp.raymond-deoliveira.workers.dev` (MCP endpoint `POST /mcp`, health `GET`/`HEAD /health`, agent summary `GET`/`HEAD /llms.txt`, discovery card `GET`/`HEAD /.well-known/mcp/server-card.json`; free tools run live with zero auth, and metered tools accept x402 v2 Base USDC via PayAI facilitator, Polar Pro license keys, or Bearer API keys, failing closed with HTTP `402`).
- **Live Browser Demo**: [raymonddeoliveira.com/software#qecguard-example](https://www.raymonddeoliveira.com/software#qecguard-example) (interactive Qecguard demo against the deployed Worker).
- **Polar Pro License (`$29` one-time, 3 activations)**: [Buy Qecguard Pro](https://buy.polar.sh/polar_cl_wR1HjdzKCoTLuPz0At9APGLuKvnQkTBMBJIZj0gNPG9).
- **Apify Store**: [raydeoliveira/qecguard-mcp](https://apify.com/raydeoliveira/qecguard-mcp).
- **Live Official MCP Registry & Glama**: [io.github.raydeoliveira/qecguard (v0.1.0)](https://registry.modelcontextprotocol.io/v0.1/servers/io.github.raydeoliveira%2Fqecguard/versions/latest) · [Glama Server](https://glama.ai/mcp/servers/raydeoliveira/qecguard) · [Glama Connector](https://glama.ai/mcp/connectors/io.github.raydeoliveira/qecguard).
- **Apify Actor / Standby container**: `FROM node:22-alpine` (`0` `npm install`, non-root `USER node`, port `4321`).

To uninstall locally, remove the directory (`rm -rf qecguard`).

## CLI and MCP Examples

### 1. Local CLI (source checkout)

Inspect capabilities and run DEM linting, synthesis, sampling, decoding, threshold sweeps, and calibration drift checks with `--json` output:

```bash
node src/adapters/cli.ts --describe --json
printf '%s\n' '{"dem":"error(0.01) D0\nerror(0.01) D0 D1\nerror(0.01) D1 L0\ndetector(0, 0, 0) D0\ndetector(1, 0, 0) D1\nlogical_observable L0\n"}' | node src/adapters/cli.ts lint-dem --json --input -
node src/adapters/cli.ts synth-dem --preset willow-105 --distance 3 --rounds 3 --seed 42 --json
node src/adapters/cli.ts threshold --code rotated-surface --preset willow-105 --distances 3,5,7 --noise-scales 0.5,1.0,2.0 --rounds 3 --shots-per-point 300 --seed 42 --json
printf '%s\n' '{"preset":"willow-105","baseline":{"error1Q":0.00035,"error2Q":0.0033,"readoutError":0.007,"cycleTimeUs":1.1},"current":{"error1Q":0.0007,"error2Q":0.014,"readoutError":0.02,"cycleTimeUs":1.1,"couplers":[{"edge":[0,1],"error2Q":0.018}]},"distance":5,"patchQubits":[0,1,2]}' | node src/adapters/cli.ts shield --input - --json
```

### 2. HTTP `402` & stdio MCP Server

Dry-run or start the local HTTP `402` server or stdio MCP server:

```bash
node src/adapters/cli.ts serve-mcp --dry-run --json
API_KEYS_CSV="demo-key" node src/adapters/cli.ts serve-mcp --host 127.0.0.1 --port 0
node src/adapters/cli.ts serve-mcp --stdio
```

### 3. Apify Actor & Standby MCP (source checkout)

Run offline Actor mode against `APIFY_LOCAL_STORAGE_DIR` (create `INPUT.json` first; without it the run exits `2` and writes `ERR_INVALID_INPUT` to `OUTPUT.json`):

```bash
mkdir -p storage/key_value_stores/default
printf '%s\n' '{"tool":"qec_lint_dem","arguments":{"dem":"error(0.01) D0\nerror(0.01) D0 D1\nerror(0.01) D1 L0\ndetector(0, 0, 0) D0\ndetector(1, 0, 0) D1\nlogical_observable L0\n"}}' > storage/key_value_stores/default/INPUT.json
APIFY_LOCAL_STORAGE_DIR=./storage node src/adapters/apify_main.ts
cat storage/key_value_stores/default/OUTPUT.json
```

Run Standby MCP mode (`PORT=0` for ephemeral bind):

```bash
APIFY_META_ORIGIN=STANDBY ACTOR_WEB_SERVER_PORT=0 node src/adapters/apify_main.ts
```

## Safety & Compute Bounds

- **Stateless `$0` compute**: Zero OS hardware mutation, zero physical QPU driver installation, and zero remote file fetching.
- **Fail-closed R7 bounds**: DEM payloads `<= 262,144` bytes, `<= 150,000` tokens, `<= 16` repeat depth, `<= 10,000` repeat iterations, `<= 100,000` expanded errors, `<= 65,536` detectors, `<= 256` observables, `<= 500,000` expand steps, `<= 100,000` sample shots, `<= 50,000` decode shots, `<= 36` threshold sweep points, HTTP MCP body `<= 262,144` bytes, JSON-RPC batch `1..64` messages, and strict prototype-chain key rejection (`__proto__`, `constructor`, `prototype`).
- **Fail-closed `402` & deferred x402 settlement**: Authorization runs before tool validation on metered calls; x402 `/settle` executes only after the tool succeeds (`QecValidationError` never settles or charges).
- **Apify Pay-Per-Event**: Results are pushed to the Dataset before charging; on `APIFY_IS_AT_HOME=1`, `chargeEvents: false` is ignored and runs stop before exceeding `ACTOR_MAX_TOTAL_CHARGE_USD`.

## Exit Codes

| Code | Meaning |
|---|---|
| `0` | Success (including `--help`, `--version`, `--describe`, `--dry-run`, and `serve-mcp --stdio` EOF) |
| `1` | Runtime error or `--strict` failure (`lint-dem --strict` warnings/errors) |
| `2` | CLI usage error or validation error (`QecValidationError`, malformed JSON, unknown flag) |
| `3` | I/O error or missing/unreadable `--input` / `--dem-file` path |
| `4` | Domain limit exceeded (`ERR_LIMIT_EXCEEDED`, `ERR_SHOT_LIMIT_EXCEEDED`, `ERR_SIZE_LIMIT_EXCEEDED`) |
| `5` | Internal error (or Apify PPE charge rejection / spending limit reached before any call succeeded) |
| `130` | `SIGINT` interrupted |

## License & Support

Proprietary commercial software. Copyright (c) 2026 Raymond de Oliveira. All rights reserved. See `LICENSE` and `SECURITY.md`.