# AIngle Córtex API

[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
[![Rust](https://img.shields.io/badge/rust-1.89%2B-orange.svg)](https://www.rust-lang.org)
[![Status](https://img.shields.io/badge/status-100%25-brightgreen.svg)]()

Complete REST/GraphQL/SPARQL API for querying and interacting with AIngle semantic graphs.

## Features (100%)

### Core APIs
- ✅ **REST API** - Full CRUD operations for RDF triples
- ✅ **GraphQL API** - Schema with queries, mutations, and subscriptions
- ✅ **SPARQL Engine** - Full SPARQL 1.1 query support with FILTER expressions

### Security & Performance
- ✅ **Authentication** - JWT-based auth with Argon2id password hashing
- ✅ **Rate Limiting** - Token bucket algorithm (100 req/min default)
- ✅ **CORS** - Configurable cross-origin resource sharing
- ✅ **Request Tracing** - Comprehensive logging and metrics

### Advanced Features
- ✅ **Proof System** - Zero-knowledge proof storage and verification
- ✅ **Real-time Subscriptions** - WebSocket-based GraphQL subscriptions
- ✅ **Pattern Queries** - Flexible triple pattern matching
- ✅ **API Versioning** - All endpoints use `/api/v1/` prefix
- ✅ **Error Handling** - Structured errors with codes and details
- ✅ **OpenAPI Spec** - Complete OpenAPI 3.1 documentation

## Quick Start

### Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
aingle_cortex = { version = "0.1", features = ["full"] }
```

### Basic Server

```rust
use aingle_cortex::{CortexServer, CortexConfig};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let config = CortexConfig::default();
    let server = CortexServer::new(config)?;
    server.run().await?;
    Ok(())
}
```

## Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                      Córtex API Server                       │
├─────────────────────────────────────────────────────────────┤
│  ┌──────────────────┐  ┌──────────────────┐                 │
│  │   REST API       │  │   GraphQL API    │                 │
│  │   /api/v1/*      │  │   /graphql       │                 │
│  └────────┬─────────┘  └────────┬─────────┘                 │
│           │                     │                            │
│  ┌────────┴─────────────────────┴─────────┐                 │
│  │              Query Router               │                 │
│  └────────┬─────────────────────┬─────────┘                 │
│           │                     │                            │
│  ┌────────▼─────────┐  ┌───────▼──────────┐                 │
│  │   SPARQL Engine  │  │  Proof Validator │                 │
│  └────────┬─────────┘  └───────┬──────────┘                 │
│           │                     │                            │
│  ┌────────▼─────────────────────▼─────────┐                 │
│  │    aingle_graph + aingle_logic         │                 │
│  └─────────────────────────────────────────┘                 │
└─────────────────────────────────────────────────────────────┘
```

## REST API

Base URL: `http://localhost:8080/api/v1`

### Triples

```bash
# Create triple
curl -X POST http://localhost:8080/api/v1/triples \
  -H "Content-Type: application/json" \
  -d '{"subject": "ex:Alice", "predicate": "foaf:name", "object": {"string": "Alice"}}'

# List triples
curl "http://localhost:8080/api/v1/triples?predicate=foaf:knows"
```

### SPARQL

```bash
curl -X POST http://localhost:8080/api/v1/sparql \
  -H "Content-Type: application/sparql-query" \
  -d 'SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 10'
```

### Proofs

```bash
# Submit proof
curl -X POST http://localhost:8080/api/v1/proofs \
  -d '{"proof_type": "plonk", "proof_data": "..."}'

# Verify proof
curl http://localhost:8080/api/v1/proofs/{id}/verify
```

## GraphQL API

Endpoint: `http://localhost:8080/graphql`

### Subscriptions

```graphql
subscription {
  tripleAdded(filter: { predicate: "foaf:knows" }) {
    hash
    subject
    predicate
    timestamp
  }
}

subscription {
  validationEvent(validOnly: true) {
    hash
    valid
    proofHash
  }
}

subscription {
  agentActivity(agentId: "did:key:...") {
    action
    tripleHash
    timestamp
  }
}
```

## Rate Limiting

All endpoints: **100 requests per minute per IP** (configurable)

Response headers:
```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 87
```

429 Response:
```json
{
  "error": "Rate limit exceeded. Retry after 30 seconds",
  "code": "RATE_LIMIT_EXCEEDED",
  "retry_after": 30
}
```

## Error Handling

Structured error responses:

```json
{
  "error": "Triple not found",
  "code": "NOT_FOUND",
  "details": null
}
```

Error codes: `NOT_FOUND`, `INVALID_INPUT`, `VALIDATION_ERROR`, `AUTH_ERROR`, `FORBIDDEN`, `RATE_LIMIT_EXCEEDED`, `QUERY_ERROR`, `SPARQL_PARSE_ERROR`, `PROOF_NOT_FOUND`, `TIMEOUT`, `CONFLICT`, `INTERNAL_ERROR`

## Testing

```bash
# All tests
cargo test --features full

# Specific suites
cargo test --test proof_system_test
cargo test --test graphql_subscriptions_test
cargo test --test rate_limiting_test
```

## Documentation

- **OpenAPI**: See `openapi.yaml` for complete REST API specification
- **API Docs**: https://docs.rs/aingle_cortex
- **GraphQL Schema**: Available at `/graphql` with GraphQL Playground

## License

Copyright 2019-2025 Apilium Technologies

Licensed under the Apache License, Version 2.0.
