sequenceDiagram
    participant App as Your Code
    participant SDK as ProofTrailMonitor
    participant Q as Background Thread
    participant API as FastAPI Server
    participant DB as SQLite

    Note over App, DB: SETUP

    App->>SDK: ProofTrailMonitor(api_key="pt_live_...", api_url="...")
    SDK->>Q: Start daemon thread (httpx.Client)
    App->>SDK: @monitor.track_tool_call on query_db()

    Note over App, DB: SESSION

    App->>SDK: with monitor.session(agent_id="bot")
    SDK-->>SDK: Set active session (contextvar)

    Note over App, DB: TOOL CALL #1

    App->>SDK: query_db("cust_123")
    activate SDK
    SDK-->>SDK: query_hash = SHA256(args)
    SDK->>SDK: Execute real function
    SDK-->>SDK: response_hash = SHA256(result)
    SDK-->>SDK: record_hash = SHA256(ts + agent + tool + hashes + prev)
    SDK-->>SDK: Build Merkle tree from [h0]
    SDK-->>SDK: Generate proof (path=[], root=R0)
    SDK-->>SDK: Create Receipt, store in session
    SDK->>Q: Enqueue receipt (non-blocking)
    SDK->>App: Return original result unchanged
    deactivate SDK

    Q->>API: POST /receipts {index:0, proof:[], hashes...}
    activate API
    API->>DB: Lookup API key hash
    DB-->>API: Key valid, org="My Test Org"
    API->>API: Reconstruct MerkleProof from JSON
    API->>API: verify_proof(bytes.fromhex(record_hash), proof)
    Note right of API: Proof valid ✓
    API->>DB: INSERT INTO receipts
    API-->>Q: 201 {verified: true}
    deactivate API

    Note over App, DB: TOOL CALL #2

    App->>SDK: query_db("cust_456")
    activate SDK
    SDK-->>SDK: Chain: prev_hash = h0
    SDK-->>SDK: Merkle tree [h0, h1] → root R1
    SDK-->>SDK: Proof: [(LEFT, h0_leaf_hash)]
    SDK->>Q: Enqueue receipt (non-blocking)
    SDK->>App: Return original result unchanged
    deactivate SDK

    Q->>API: POST /receipts {index:1, proof:[{LEFT,sibling}]}
    activate API
    API->>API: verify_proof → valid ✓
    API->>DB: INSERT INTO receipts
    API-->>Q: 201 {verified: true}
    deactivate API

    Note over App, DB: QUERY RECEIPTS

    App->>API: GET /receipts
    activate API
    API->>DB: SELECT WHERE api_key_id = ? (org isolation)
    DB-->>API: 2 receipts
    API-->>App: 200 {receipts: [...], total: 2}
    deactivate API

    Note over App, DB: ANCHOR (snapshot chain state)

    App->>API: POST /anchors {root_hash: R1, count: 2}
    activate API
    API->>DB: INSERT INTO anchors
    API-->>App: 201 {root_hash, created_at}
    deactivate API

    Note over App, DB: VERIFY (prove receipt existed)

    App->>API: POST /verify {record_hash, proof, proof_root}
    activate API
    API->>API: verify_proof() → valid ✓
    API->>DB: SELECT anchors WHERE root_hash = ?
    DB-->>API: Found!
    API-->>App: 200 {valid: true, anchored: true}
    deactivate API
