Metadata-Version: 2.4
Name: q-runtime-core
Version: 1.0.0
Summary: Economic invariant verification for autonomous AI-agent workflows
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: PyYAML>=6.0
Provides-Extra: official-x402
Requires-Dist: x402[evm,fastapi,requests]<3,>=2.22.0; extra == "official-x402"
Requires-Dist: uvicorn[standard]>=0.40.0; extra == "official-x402"
Dynamic: license-file

# Q Runtime
## v0.5-r3 — external-audit false-positive hardening

The 2026-09-04 directory audit exposed two detector problems rather than third-party vulnerabilities:

- x402's published network support explicitly lists Algorand identifiers whose genesis-hash form falls outside the formal CAIP-2 reference grammar. Q Runtime now recognizes those exact x402-documented identifiers as an upstream profile exception instead of blaming each service.
- `Cache-Control: no-store, no-cache, must-revalidate, max-age=0` is correctly treated as non-cacheable. The old substring check incorrectly warned whenever `max-age` appeared.

Regression result: **39/39 tests passing**. Package version: **0.5.3**.

## v0.5-r2 — legacy root-cause classification

External validation against Neynar reproduced the same x402 v1 handshake on all three monitored endpoints. r2 therefore adds audit modes and root-cause aggregation:

```bash
qruntime x402 external-audit <URL> --mode strict
qruntime x402 external-audit <URL> --mode compatibility
qruntime x402 directory-audit --limit 10 --mode compatibility --out captures\directory.json
```

- `strict`: x402 v1 is one `LegacyX402V1Detected` error; body-only v2 is an error.
- `compatibility`: x402 v1 is one legacy warning/classification; body-only v2 is a warning.
- v1-derived field mismatches are not double-counted as separate bugs.
- `external-suite` now treats the grug402 missing-header scenario as `CanonicalPaymentRequiredLocation` in strict mode.

 Verify v0.5

Q Runtime Verify is a protocol-agnostic economic-state verifier for autonomous AI-agent workflows.

**Positioning:** Q Runtime finds economic bugs in AI-agent workflows before agents spend real money.

**Design rule:** Agents propose. Q verifies. Rails execute.

## What v0.5 changes

v0.4 proved live HTTP capture against a server we controlled using the official x402 Python SDK. v0.5 moves the validation surface outside our server:

- `external-audit` probes an independent public HTTPS x402 endpoint without paying;
- it refuses to send `PAYMENT-SIGNATURE` or legacy `X-PAYMENT` authorization headers;
- it audits the observed 402 challenge for protocol/economic invariants;
- `external-suite` cross-checks Q Runtime against independent QueryLines + grug402 endpoints;
- `directory-audit` discovers public x402 services through x402 List and safely probes GET-only, non-templated, public-HTTPS endpoints;
- external reports preserve the HTTP status, response headers, challenge source, decoded requirement and findings;
- v0.4 capture, quote comparison, official SDK demo, QFlow verifier, and v0.3 trace verifier remain intact.

No v0.5 external probe signs, pays, settles, broadcasts a transaction, or asks for a wallet key.

## Current external reference set

Research date: 2026-09-03.

### QueryLines — independent production x402 API

`https://api.querylines.com/v1/premium?state=FL`

The public x402 List assessment currently reports QueryLines as online with 100% 30-day uptime and 14/14 x402 compliance checks. Its paid endpoints return x402 challenges in the `PAYMENT-REQUIRED` header.

### grug402 — independent live testnet behavior catalog

The suite uses:

- `/api/x402/compliant-get` — compliant baseline;
- `/api/x402/missing-payment-required` — 402 with missing challenge;
- `/api/x402/header-raw-json` — non-canonical raw JSON header;
- `/api/x402/resource-host-mismatch` — advertised resource host does not match the requested host.

These negative endpoints are intentionally malformed by grug402. They validate Q Runtime's detector against externally hosted bug classes; they are **not** discoveries by Q Runtime.

### x402 List — discovery source

`https://x402-list.com/api/v1/`

Read access requires no authentication. v0.5 uses directory metadata only to discover public endpoints, then performs unpaid GET probes.

## New commands

### 1. Audit one independent endpoint

```powershell
qruntime x402 external-audit "https://api.querylines.com/v1/premium?state=FL" `
  --out captures\querylines-premium.json
```

Expected high-level result for a healthy external implementation:

```text
PASS — EXTERNAL X402 AUDIT
HTTP: 402 GET ...
challenge source: header
...
```

Warnings do not make the audit fail. For example, a service may advertise the endpoint URL in `resource.url` while binding query parameters through an extension. v0.5 treats an origin/path mismatch as an error, but an omitted query string as `ResourceQueryBindingExternalized` warning rather than a false protocol failure.

### 2. Run the independent cross-implementation suite

```powershell
qruntime x402 external-suite `
  --out captures\external-suite-v05.json
```

The suite expects the compliant endpoints to pass and the intentionally malformed grug402 endpoints to fail on their corresponding invariants.

### 3. Audit a small sample discovered from x402 List

```powershell
qruntime x402 directory-audit `
  --limit 5 `
  --out captures\directory-audit-v05.json
```

Safety constraints:

- GET only;
- public HTTPS only;
- endpoint templates containing `{...}` skipped;
- no payment authorization header;
- no payment attempted;
- directory audit limit capped at 50.

A directory-audit error is an **observed incompatibility or reachability finding**, not automatically a security vulnerability. Any non-trivial finding must be reproduced and manually classified before disclosure or product claims.

## External invariants added/strengthened

- `PaymentRequiredStatus` — protected endpoint should produce HTTP 402 for an unpaid challenge.
- `CanonicalPaymentRequiredEncoding` — canonical v2 header is base64 JSON, not raw JSON/garbage.
- `PaymentRequirementKnownBeforeAuthorization` — 402 must expose a parseable payment challenge.
- `X402VersionSupported` — current verifier expects x402 v2.
- `NonEmptyPaymentRequirements` — `accepts[]` must not be empty.
- `AtomicAmountCanonical` — amount must be a decimal string of atomic units.
- `CanonicalNetworkIdentifier` — network must have CAIP-2-like shape.
- `LiveAuthorizationWindow` — timeout must be a positive integer.
- `ValidPaymentRecipient` / `ValidPaymentAsset` — EVM recipient/asset must be 20-byte addresses.
- `PaymentPayloadBoundToResource` — advertised origin/path must match the requested resource.
- `ResourceQueryBindingExternalized` — warning when query parameters are not reproduced in `resource.url`.
- `NonCacheablePaymentChallenge` — warns when 402 challenge is explicitly cacheable.

## Important correction produced by external validation

v0.4's mental model could have treated exact request URL equality as the strongest resource-binding rule. External research showed that a conformant production service can advertise the endpoint in `resource.url` while declaring concrete query inputs in an extension. v0.5 therefore avoids a false positive:

- different origin/path → hard failure;
- both sides specify different queries → hard failure;
- request has query but `resource.url` omits it → warning requiring extension/application binding review.

This is evidence that external validation is already improving the verifier rather than merely confirming our own assumptions.

## Tests

```powershell
pytest -q
```

Expected for this snapshot:

```text
33 passed
```

The automated tests remain deterministic and do not require internet. Live external commands are a separate experimental layer to be run by the operator.

## Scope boundary / evidence standard

v0.5 can establish that Q Runtime interoperates with and evaluates externally hosted x402 challenges. It does **not** establish that every reported difference is a bug, exploit, financial loss, or vulnerability.

The current decisive gate is:

> Can Q Runtime produce a reproducible, non-trivial finding on a third-party x402 flow that was not deliberately constructed as a negative test, survive manual review, and be useful to that service's developer?

Do not build Q Runtime Cloud before that gate is crossed.


## v0.5-r4 precision notes

The external auditor distinguishes HTTP storable responses from stale-replay-capable responses. `max-age=0, must-revalidate` is immediately stale and requires revalidation, while positive freshness such as `max-age=300` remains a warning for payment challenges.

`maxTimeoutSeconds` is parsed as a core numeric field. Standard known schemes require a positive value; zero on an unknown/custom scheme is reported as scheme-specific semantics rather than treated as a universal protocol failure.

Relative `resource.url` values are resolved against the request origin before resource binding comparison. Origin, scheme, or resolved-path mismatches remain errors.

---

## v0.6 — full-cycle x402 testnet gate

v0.6 adds a deterministic verifier for the x402 v2 default `authorization` flow and a deliberately narrow live Base-Sepolia harness.

### Deterministic full-cycle checks

```powershell
qruntime x402 verify-fullcycle scenarios\fullcycle_safe.json
qruntime x402 verify-fullcycle scenarios\fullcycle_stale_quote.json
qruntime x402 verify-fullcycle scenarios\fullcycle_settlement_pending_retry.json
```

Expected: safe passes; stale quote fails `PaymentRequirementStableForIntent`; pending retry fails `PaymentStateReconciledBeforeRetry`.

### Disposable testnet wallets

```powershell
qruntime x402 create-testnet-wallet --out .secrets\payer.json
qruntime x402 create-testnet-wallet --out .secrets\merchant.json
```

These files contain private keys. They are for Base Sepolia testnet only. Never upload, paste, commit, or reuse them for mainnet.

### Live settlement safety

`live-testnet` is hard-limited to `localhost`/`127.0.0.1`, Base Sepolia (`eip155:84532`), `exact`, and an explicit atomic-unit cap. The key is taken from `Q_RUNTIME_TESTNET_PRIVATE_KEY` by default and is not written to the report.

See `RELEASE_v0.6.md` for the complete gate.

## Python SDK (v0.7 development)

Q Runtime now exposes a public Python API.

Minimal example:

    from qruntime import Runtime

    runtime = Runtime(
        max_amount_atomic=10_000,
    )

    result = runtime.pay_testnet(
        "http://127.0.0.1:4021/weather",
        intent_id="example-payment-001",
        out="payment.json",
    )

    print(result.transaction)
    print(result.amount_atomic)
    print(result.network)

The SDK exposes typed payment and reconciliation results plus payment-safety exceptions.

See:

- docs/SDK_V07.md
- examples/runtime_sdk.py

The current public payment method is deliberately named pay_testnet() because production/mainnet readiness is not claimed by the v0.7 development line.

## v0.7 ? public SDK and operational observability

v0.7 promotes the validated economic-safety core into a public Python SDK.

The public API now includes:

- Runtime
- RuntimeConfig
- PaymentResult
- ReconciliationResult
- IntentRecord
- typed payment-safety errors
- typed settlement/resource errors
- typed store/reconciliation errors

Persistent logical payment state can be inspected without mutating it:

    qruntime x402 intents
    qruntime x402 intent <intent_id>

Operational views include:

    qruntime x402 intents --state pending
    qruntime x402 intents --state confirmed
    qruntime x402 intents --state failed
    qruntime x402 intents --summary

Python applications can use:

    runtime.list_intents()
    runtime.get_intent(intent_id)

The latest v0.7 regression gate is:

    126 passed

The public SDK has also completed a live Base Sepolia payment through a clean-installed wheel, followed by successful reconciliation and same-intent duplicate rejection.

The controlled payment path remains testnet-specific and deliberately narrow. Production/mainnet readiness is not claimed.

See:

- docs/SDK_V07.md
- VALIDATION-v0.7.0rc1.md
