# 02 · System Architecture & Tech Stack

> **SSOT Status**: Authoritative Specification  
> **Machine Source**: [`spec/fiderail.manifest.json`](../spec/fiderail.manifest.json) (`schemaVersion: 1.0.0`)  
> **Release**: `v2.3.5`

---

## 1. Hybrid Control Plane Architecture (Option C)

FideRail separates deterministic edge enforcement from cloud-side cross-chain indexing so agents evaluate spending caps and cryptographic mandates locally in microseconds while consuming live anti-sybil reputation intelligence over HTTP or MCP:

```mermaid
flowchart LR
    subgraph Edge["Edge / Client Execution Layer (SDK & MCP)"]
        Mandate["Attenuated Capability Mandate<br/>Offline Ed25519 Verification"]
        Core["@fiderail/core (Protocol-Agnostic Kernel)<br/>PaymentIntent -> Mandate -> Risk -> Verdict"]
        Adapters["Protocol Adapters<br/>x402 · MCP-Pay · A2A · SessionKey"]
        LocalStore["Embedded SQLite Ledger & TTL Cache<br/>node:sqlite / Python sqlite3"]
        Wallet["Client Wallet / Session Key<br/>Private Keys Stay 100% Local"]

        Mandate --> Core
        LocalStore --> Core
        Adapters <--> Core
        Core -->|"ALLOW + QuoteDigest"| Wallet
    end

    subgraph Cloud["Cloud Intelligence Plane (api.fiderail.com)"]
        API["REST API + Streamable HTTP MCP<br/>x402#2299 Hook + Open Bazaar Grader"]
        Engine["Pluggable Trust Engine (trust-v2)<br/>Deterministic Features + Ed25519 Signed stateRoot"]
        PG[("PostgreSQL 16 (Production)<br/>Monthly Partitioned Payments · NUMERIC(78,0)")]
        Workers["4-Chain Indexer Workers<br/>Base · Solana · Arbitrum · Polygon"]

        Workers --> PG --> Engine --> API
    end

    subgraph Crypto["Cryptographic Verification Artifacts"]
        SAR["fiderail-sar-v2<br/>RFC 8785 JCS + 128-bit Salt + Causal Hash"]
        Keys["/.well-known/fiderail-keys.json<br/>Ed25519 SPKI Public Key & keyId"]
    end

    LocalStore <-->|"Cache Miss / TTL Refresh"| API
    Core -.->|"Anonymous L2 SAR Telemetry"| SAR --> API
    Engine -->|"Ed25519 Signed Merkle Root"| Keys
```

---

## 2. Core Architectural Components

### 2.1 Protocol-Agnostic Control Pipeline
`@fiderail/core` has zero Node-specific dependencies and executes a 4-stage deterministic pipeline:

1. **`PaymentIntent`**: Normalized payment descriptor (`intentId`, `taskId`, `chain`, `assetContract`, `amountRaw`, `amountUsd`, `payee`, `domain`, `protocol`, `metadataHash`).
2. **`AttenuatedMandateVerification`**: Offline verification of mandate chain signatures, expiry, revocation status, monotonic attenuation bounds, and spent totals.
3. **`RiskAndIdentityEvaluation`**: Lookup of `TrustProfile`, `confidence`, `riskLevel`, `riskFlags`, isolated `associatedCredit`, and endpoint liveness diagnostics (via local TTL cache or `RemoteTrustClient`).
4. **`DeterministicVerdictAndAttestation`**: Deterministic `ALLOW` / `WARN` / `BLOCK` verdict with explicit reason codes and cryptographic receipts (`fiderail-sar-v2`).

> **Outbound Secret Scrubber Scope**: `scanOutboundSecrets()` in `@fiderail/core` is a deterministic **accidental-leakage guardrail** for plaintext secrets (API keys, PEM private keys, JWTs, labeled seed phrases), not an adversarial exfiltration sandbox against prompt-injection encoding or obfuscation. Never place high-privilege credentials inside LLM prompt context.

### 2.2 Attenuated Capability Delegation Chain
Implemented in [`packages/guard/src/mandate.ts`](../packages/guard/src/mandate.ts) and [`packages/core/src/policy.ts`](../packages/core/src/policy.ts):

- **Modes**: `SPECIFIED` (single scoped target) and `BOUNDED` (multi-call bounded task budget).
- **Monotonic Attenuation**: Child mandates derived by orchestrator agents can strictly narrow caps, expiry, chains, assets, payees, domains, service tags, or raise `minTrustScore`—never expand parent permissions.
- **Lifecycle & Concurrent Accounting**: `ACTIVE` -> `SUSPENDED` | `REVOKED` | `EXPIRED`, with automatic completion revocation (`autoRevokeMandateOnCompletion`) and concurrent SQLite WAL atomic budget reservations (`BEGIN IMMEDIATE`).

### 2.3 Deterministic Cryptographic Primitives
Implemented in [`packages/zk-types/src/index.ts`](../packages/zk-types/src/index.ts) and [`packages/db/src/state-root-signer.ts`](../packages/db/src/state-root-signer.ts):

- **RFC 8785 JCS**: Canonical JSON serialization paired with pure-TypeScript FIPS 180-4 SHA-256.
- **Salted Causal Receipts (`fiderail-sar-v2`)**: 128-bit cryptographic salt, `taskId` + `parentReceiptHash` chaining, `eventTime` vs `recordedAt` separation, and server-side JCS verification + `receiptHash` replay deduplication.
- **Ed25519-Signed Merkle `stateRoot`**: Deterministic binary SHA-256 Merkle root generated per chain recomputation epoch, signed with `fiderail-state-root-v1:{epochId}:{merkleRoot}` and verifiable offline via `GET /.well-known/fiderail-keys.json`.

---

## 3. Repository Package Layout (`v2.3.5`)

- [`spec/fiderail.manifest.json`](../spec/fiderail.manifest.json) & [`packages/spec`](../packages/spec/src/index.ts): Machine-readable SSOT manifest, 4-chain x 2-stablecoin registry, CAIP-2 & address validators (zero Node deps).
- [`packages/zk-types`](../packages/zk-types/src/index.ts): RFC 8785 JCS, pure SHA-256, `ProofEnvelope`, `fiderail-sar-v2`, and Merkle root builder (zero Node deps).
- [`packages/core`](../packages/core/src/index.ts): Protocol-agnostic control plane kernel (`PaymentIntent`, `validateMandateChain`, `clampPolicy`, outbound secret/PII scrubber, `trust-v2` scorer, isolated `ASSOCIATED_CREDIT`, `TrustEngine`, `RemoteTrustClient`; zero Node deps).
- [`packages/db`](../packages/db/src/index.ts): Unified async `FideRailRepository` supporting PostgreSQL 16 (monthly partitioned `payments`, `NUMERIC(78,0)`, indexed queries in [`sql/001_init_v2.sql`](../packages/db/sql/001_init_v2.sql)) and SQLite WAL for dev/CI, Ed25519 `stateRoot` signer/verifier, L2 SAR v2 deduplication, and lossless SQLite-to-PostgreSQL migrator.
- [`packages/indexer`](../packages/indexer/src/index.ts): Unified 4-chain EVM/SVM indexer workers, Bazaar capability sync, and SSRF/DNS-hardened L1 liveness prober & A-F x402 endpoint grader.
- [`packages/guard`](../packages/guard/src/index.ts) & [`packages/seller`](../packages/seller/src/index.ts): Ed25519 mandate issuer/delegator, concurrent SQLite WAL edge ledger, protocol adapters (`x402`, `mcp-pay`, `a2a`, `session-key`), and seller `x402#2299` `onBeforeSettle` middleware.
- [`apps/api`](../apps/api/src/index.ts) & [`apps/mcp`](../apps/mcp/src/index.ts): 13-endpoint REST API + Streamable HTTP MCP (`POST /mcp` supporting `2025-06-18` / `2025-03-26` / `2024-11-05`) + SSR Portal, plus 6-tool `stdio` MCP server.
- [`sdks/python`](../sdks/python/fiderail/__init__.py): Zero-dependency Python `>= 3.9` SDK synchronized with `spec/fiderail.manifest.json`.
