# API

#### Appendix F. Core API Schemas (OpenAPI / gRPC / JSON Schema)

This appendix specifies the **core API schema patterns** that underpin the Nexus Ecosystem. It does **not** attempt to exhaustively document all endpoints; instead it defines:

* The **canonical schema families** and their responsibilities.
* The **representation formats** (OpenAPI/REST, gRPC, JSON Schema) and versioning patterns.
* **Security, identity, and SDZ hooks** that must be present across all public interfaces.

Concrete, implementation-ready OpenAPI and protobuf files are maintained in the **NXSS reference repositories** and are versioned in lockstep with Nexus protocol releases.

***

### F.1 Design Principles for Nexus APIs

All Nexus APIs (NXSR, NXOBS, NXSTUDIO, NXAPP, NXHIVE) conform to the following principles:

1. **Semantic-first design**
   * Every resource is grounded in **GRIx** classes and NXSS vocabularies.
   * Resource names and fields must be mappable to ontology entities/relations.
2. **Format-agnostic, transport-flexible**
   * Logical APIs are specified once, then surfaced as:
     * **OpenAPI/REST** (HTTP/JSON) for broad compatibility.
     * **gRPC** for low-latency, strongly-typed internal calls.
     * **JSON Schema** for message-level validation and tooling.
3. **SDZ & lawful-basis aware**
   * Every request and response must carry **SDZ tags**, **purpose-of-use**, and **actor identity** hooks sufficient to evaluate Policy DSL rules.
4. **Versioned, evolvable, backward-compatible where possible**
   * APIs use semantic versioning (`v1`, `v1beta`, etc.).
   * Deprecations and breaking changes follow the change-management regime in Part XI.
5. **Observability and traceability built-in**
   * All calls carry a **correlation/trace ID** and **audit context** to feed Chronotope & Episodic Memory fabrics.

***

### F.2 Core API Families

At minimum, the Nexus Ecosystem defines the following **canonical API families**:

1. **Catalog APIs**
   * List and retrieve **rails**, **packs**, **AEPs**, **indices**, **NRM Profiles**, **agents**, **playbooks**, and **INT modules**.
2. **Observatory APIs (NXOBS)**
   * Retrieve **indices**, **AEPs**, and **raw/derived INT streams** under SDZ and EQL constraints.
3. **Evidence & AEP APIs**
   * Create, validate, publish, and retrieve **AEPs**, including GRF assurance metadata and NVM authorisation.
4. **Scenario & Simulation APIs**
   * Define, execute, and analyse **NRM scenarios**, including parameterisation, ensemble runs, and outputs.
5. **Decision & Episode APIs**
   * Record **decisions**, **episodes**, and **outcome metrics**, and link them to AEPs and indices.
6. **Governance & NVM APIs**
   * Manage **Rail DAOs**, **NVM quorum templates**, **votes**, **resolutions**, and **protocol events**.
7. **Identity & Credential APIs**
   * Resolve **DIDs**, manage **VC presentations**, and query **role/competence profiles**.
8. **Agent & Playbook APIs**
   * Register, inspect, and control **agents**, **swarms**, and **playbooks** (start/stop, status, logs).
9. **RailOps & Telemetry APIs**
   * Query **SLOs**, health, performance, security posture, and operational incidents across rails.

Each family is broken into **modules** with its own OpenAPI and protobuf specs, but all share common **envelopes** and **metadata** structures.

***

### F.3 OpenAPI Schemas – Illustrative Patterns

#### F.3.1 Example: AEP Retrieval API (OpenAPI Snippet)

```yaml
openapi: 3.1.0
info:
  title: Nexus AEP API
  version: 1.0.0
  description: |
    API for querying Assurance & Evidence Packs (AEPs) on a Nexus Rail.

servers:
  - url: https://api.nexus.example.org

paths:
  /rails/{rail_id}/aeps:
    get:
      summary: List AEPs on a rail
      operationId: listAeps
      parameters:
        - name: rail_id
          in: path
          required: true
          schema:
            type: string
        - name: eql_min
          in: query
          schema:
            type: string
            enum: [EQL1, EQL2, EQL3, EQL4, EQL5]
        - name: nrm_profile_id
          in: query
          schema:
            type: string
        - name: status
          in: query
          schema:
            type: string
            enum: [draft, issued, deprecated]
      responses:
        "200":
          description: A list of AEP summaries
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AepListResponse"
        "401":
          $ref: "#/components/responses/Unauthorized"
        "403":
          $ref: "#/components/responses/Forbidden"

  /rails/{rail_id}/aeps/{aep_id}:
    get:
      summary: Retrieve an AEP by ID
      operationId: getAep
      parameters:
        - name: rail_id
          in: path
          required: true
          schema:
            type: string
        - name: aep_id
          in: path
          required: true
          schema:
            type: string
      responses:
        "200":
          description: Full AEP document
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Aep"
        "404":
          description: AEP not found or access denied

components:
  schemas:
    AepListResponse:
      type: object
      properties:
        items:
          type: array
          items:
            $ref: "#/components/schemas/AepSummary"
        next_page_token:
          type: string
          nullable: true

    AepSummary:
      type: object
      properties:
        aep_id:
          type: string
        title:
          type: string
        eql_level:
          type: string
          enum: [EQL1, EQL2, EQL3, EQL4, EQL5]
        nrm_profile_id:
          type: string
        rail_id:
          type: string
        status:
          type: string
          enum: [draft, issued, deprecated]
        issued_at:
          type: string
          format: date-time

    Aep:
      $ref: "schemas/aep.schema.json"

  responses:
    Unauthorized:
      description: Authentication failed
    Forbidden:
      description: Policy/SRZ/GeoGuard constraints prevent access
```

Notes:

* The **Aep** object is externalised into a reusable JSON Schema (`aep.schema.json`), see F.5.
* **401/403** semantics explicitly include Policy DSL/SDZ enforcement.

***

#### F.3.2 Example: Index API (Streaming-Friendly)

```yaml
paths:
  /rails/{rail_id}/indices/{index_id}/timeseries:
    get:
      summary: Query index timeseries
      operationId: getIndexTimeseries
      parameters:
        - name: rail_id
          in: path
          required: true
          schema: { type: string }
        - name: index_id
          in: path
          required: true
          schema: { type: string }
        - name: start
          in: query
          schema:
            type: string
            format: date-time
        - name: end
          in: query
          schema:
            type: string
            format: date-time
        - name: chronotope_scope_id
          in: query
          schema:
            type: string
      responses:
        "200":
          description: Index values over time
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/IndexTimeseries"
```

`IndexTimeseries` aligns with the **index event** format in Appendix D and with the GRIx ontology.

***

### F.4 gRPC Schemas – Illustrative Patterns

For internal calls (NXSTUDIO↔NXOBS, NXSR↔NXHIVE, agents↔NXSOS), gRPC is preferred.

#### F.4.1 Example: AEP Service (protobuf)

```proto
syntax = "proto3";

package nexus.aep.v1;

import "google/protobuf/timestamp.proto";
import "google/protobuf/struct.proto";

service AepService {
  rpc ListAeps (ListAepsRequest) returns (ListAepsResponse);
  rpc GetAep   (GetAepRequest)   returns (Aep);
}

message ListAepsRequest {
  string rail_id = 1;
  string nrm_profile_id = 2;
  string eql_min = 3;  // EQL1...EQL5
  string page_token = 4;
  int32  page_size  = 5;
  NexusContext ctx = 99;
}

message ListAepsResponse {
  repeated AepSummary items = 1;
  string next_page_token = 2;
}

message GetAepRequest {
  string rail_id = 1;
  string aep_id  = 2;
  NexusContext ctx = 99;
}

message AepSummary {
  string aep_id = 1;
  string title  = 2;
  string eql_level = 3;
  string nrm_profile_id = 4;
  string rail_id = 5;
  string status = 6;
  google.protobuf.Timestamp issued_at = 7;
}

message Aep {
  google.protobuf.Struct body = 1; // Validated against aep.schema.json
  NexusContext ctx  = 99;
}

message NexusContext {
  string requester_did      = 1;
  string requester_role     = 2;
  string purpose_of_use     = 3;
  string sdz_context        = 4;
  string trace_id           = 5;
}
```

Key points:

* **`NexusContext`** is mandatory and carries everything the Policy DSL/GeoGuard/safety fabrics require.
* The AEP body is a **JSON-typed struct** validated against **JSON Schema**, so protobuf and OpenAPI share semantics.

***

### F.5 JSON Schemas – Canonical Data Definitions

JSON Schema provides the canonical definition of:

* **AEPs**
* **Indices and events** (indices, alerts, decisions, episodes)
* **NRM Profiles, rail.yaml and pack.yaml structures**
* **Playbooks (Playbook DSL) and Agent specs (Agent DSL)**

#### F.5.1 Example: AEP JSON Schema (Fragment)

```json
{
  "$id": "https://schemas.nexus.org/aep.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "Assurance & Evidence Pack (AEP)",
  "type": "object",
  "required": ["api_version", "kind", "metadata", "data_sources", "models_used"],
  "properties": {
    "api_version": {
      "type": "string",
      "const": "aep.v1"
    },
    "kind": {
      "type": "string",
      "const": "AEP"
    },
    "metadata": {
      "type": "object",
      "required": ["aep_id", "title", "rail_id", "nrm_profile_id", "eql_level"],
      "properties": {
        "aep_id": { "type": "string" },
        "title": { "type": "string" },
        "rail_id": { "type": "string" },
        "nrm_profile_id": { "type": "string" },
        "eql_level": {
          "type": "string",
          "enum": ["EQL1", "EQL2", "EQL3", "EQL4", "EQL5"]
        },
        "cl_target": {
          "type": "string",
          "enum": ["CL1", "CL2", "CL3", "CL4"]
        },
        "chronotope_scope_id": { "type": "string" }
      }
    },
    "data_sources": {
      "type": "array",
      "items": {
        "type": "object",
        "required": ["source_id", "provider", "sdz_class"],
        "properties": {
          "source_id": { "type": "string" },
          "provider": { "type": "string" },
          "sdz_class": { "type": "string" }
        }
      }
    },
    "models_used": {
      "type": "array",
      "items": {
        "type": "object",
        "required": ["model_id", "version"],
        "properties": {
          "model_id": { "type": "string" },
          "version": { "type": "string" },
          "model_card_ref": { "type": "string", "format": "uri" }
        }
      }
    },
    "uncertainty_characterisation": {
      "type": "object",
      "properties": {
        "narrative": { "type": "string" }
      }
    }
  }
}
```

Other schemas follow similar patterns and are cross-linked:

* **Index events** schemas align with Appendix D envelopes.
* **Decision/episode** schemas embed foreign keys to AEPs and NRM Profiles.

***

### F.6 Versioning, Namespaces, and Compatibility

1. **Namespace conventions**
   * OpenAPI: `nexus.{domain}.v1` (e.g., `nexus.aep.v1`, `nexus.obs.v1`).
   * gRPC: `package nexus.aep.v1;` etc.
   * JSON Schemas: `$id` under `https://schemas.nexus.org/{domain}/{name}.schema.json`.
2. **Versioning**
   * Major version increments (`v1 → v2`) imply breaking changes and require NXSS / NXSOS governance.
   * Minor/patch changes are backward-compatible (new optional fields, clarifications).
3. **Backward compatibility and deprecation**
   * Old versions MUST be supported during defined deprecation windows, especially for APIs underpinning capital facilities or regulatory reliance.
   * Deprecation metadata is published in the **NXUNIV catalogs** and enforced via RailOps policies.

***

### F.7 Security, Identity & SDZ Hooks in APIs

All APIs must:

* Use **mutual TLS** or equivalent channel protections.
* Authenticate clients via **NXIdentity** (DID/VC, OAuth2/OIDC wrappers where needed).
* Attach **NexusContext** (or equivalent HTTP headers) carrying:
  * `x-nexus-did`
  * `x-nexus-role`
  * `x-nexus-purpose`
  * `x-nexus-sdz-context`
  * `x-nexus-trace-id`

Policy DSL is evaluated using this context; access decisions are logged for audit.

***

### F.8 API Discovery, Documentation, and Tooling

1. **Discovery**
   * `/.well-known/nexus/openapi` returns OpenAPI documents per rail.
   * `nxuniv` catalogs hold machine-readable metadata about API endpoints per pack/rail.
2. **Documentation**
   * Human-facing docs (Swagger UI, ReDoc) are generated from OpenAPI specs;
   * Protobuf and JSON Schema docs are integrated into the **NXFOUNDRY developer portal**.
3. **Toolchain integration**
   * CI/CD pipelines enforce conformance to JSON Schemas and OpenAPI/gRPC linting.
   * Contract tests validate that deployed services adhere to **NXSS Core API schemas**.

***

In summary, the **Core API Schemas** provide a **unified, semantically anchored, and security-aware interface layer** for the Nexus Ecosystem. By grounding OpenAPI, gRPC, and JSON Schema in a common ontology and governance model, NRM can be integrated into heterogeneous national systems, vendor stacks, and agent frameworks without sacrificing **rigour, traceability, or lawful-basis control**.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.therisk.global/organization/standardization/nexus-rail/nexus-based-risk-management-nrm/technology/appendices/api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
