# API Reference

Complete documentation for the Nexus Memory API endpoints.

## Base URL

```
https://api.adverant.ai
```

## Authentication

All requests require tenant context headers:

| Header | Required | Description |
|--------|----------|-------------|
| `X-Company-ID` | Yes | Organization identifier (e.g., `adverant`) |
| `X-App-ID` | Yes | Application identifier (e.g., `claude-code`) |
| `X-User-ID` | Yes | User identifier (defaults to system `$USER`) |
| `Content-Type` | Yes | Must be `application/json` |

---

## Endpoints

### Store Memory

Store a new memory in the knowledge graph.

**Endpoint:** `POST /api/memory/store`

**Request Body:**

```json
{
  "content": "string (required) - The memory content to store",
  "tags": ["string"] - Optional array of tags,
  "metadata": {
    "sessionId": "string - Session identifier",
    "eventType": "string - Event type classification",
    "projectDir": "string - Full project path",
    "projectName": "string - Project directory name",
    "timestamp": "string - ISO 8601 timestamp"
  }
}
```

**Example Request:**

```bash
curl -X POST "https://api.adverant.ai/api/memory/store" \
  -H "Content-Type: application/json" \
  -H "X-Company-ID: adverant" \
  -H "X-App-ID: claude-code" \
  -H "X-User-ID: alice" \
  -d '{
    "content": "Fixed CORS error by adding credentials: include",
    "tags": ["claude-code", "session:abc123", "type:fix", "project:nexus-api"],
    "metadata": {
      "sessionId": "abc123",
      "eventType": "fix",
      "projectDir": "/Users/alice/dev/nexus-api",
      "projectName": "nexus-api",
      "timestamp": "2024-12-28T12:00:00Z"
    }
  }'
```

**Response:**

```json
{
  "success": true,
  "id": "mem_abc123xyz",
  "message": "Memory stored successfully"
}
```

**Status Codes:**

| Code | Description |
|------|-------------|
| 200 | Memory stored successfully |
| 400 | Invalid request body |
| 401 | Unauthorized (missing/invalid headers) |
| 500 | Server error |

---

### Recall Memory

Search for relevant memories using semantic search.

**Endpoint:** `POST /api/memory/recall`

**Request Body:**

```json
{
  "query": "string (required) - Natural language search query",
  "limit": "number (optional, default: 10) - Maximum results to return"
}
```

**Example Request:**

```bash
curl -X POST "https://api.adverant.ai/api/memory/recall" \
  -H "Content-Type: application/json" \
  -H "X-Company-ID: adverant" \
  -H "X-App-ID: claude-code" \
  -H "X-User-ID: alice" \
  -d '{
    "query": "CORS authentication errors",
    "limit": 5
  }'
```

**Response:**

```json
{
  "memories": [
    {
      "id": "mem_abc123xyz",
      "content": "Fixed CORS error by adding credentials: include",
      "eventType": "fix",
      "projectName": "nexus-api",
      "timestamp": "2024-12-28T12:00:00Z",
      "relevanceScore": 0.95
    }
  ],
  "documents": [
    {
      "id": "doc_def456",
      "title": "API Security Guide",
      "excerpt": "...CORS configuration requires...",
      "relevanceScore": 0.72
    }
  ],
  "entities": [
    {
      "name": "CORS",
      "type": "technology",
      "relatedMemories": 3
    }
  ]
}
```

**Status Codes:**

| Code | Description |
|------|-------------|
| 200 | Search completed successfully |
| 400 | Invalid query |
| 401 | Unauthorized |
| 500 | Server error |

---

### Store Document

Upload and index a document for knowledge retrieval.

**Endpoint:** `POST /api/documents/store`

**Request Body:**

```json
{
  "title": "string (required) - Document title",
  "content": "string (required) - Full document content",
  "type": "string (optional) - Document type (default: 'text')",
  "format": "string (optional) - File format (e.g., 'md', 'txt')",
  "source": "string (optional) - Source identifier",
  "tags": ["string"] - Optional array of tags,
  "metadata": {
    "fileName": "string - Original filename",
    "fileSize": "number - File size in bytes",
    "uploadedAt": "string - ISO 8601 timestamp"
  }
}
```

**Example Request:**

```bash
curl -X POST "https://api.adverant.ai/api/documents/store" \
  -H "Content-Type: application/json" \
  -H "X-Company-ID: adverant" \
  -H "X-App-ID: claude-code" \
  -H "X-User-ID: alice" \
  -d '{
    "title": "API Design Guidelines",
    "content": "# API Design\n\nThis document covers...",
    "type": "text",
    "format": "md",
    "source": "upload:guidelines.md",
    "tags": ["document", "uploaded", "api", "guidelines"],
    "metadata": {
      "fileName": "guidelines.md",
      "fileSize": 4096,
      "uploadedAt": "2024-12-28T12:00:00Z"
    }
  }'
```

**Response:**

```json
{
  "success": true,
  "id": "doc_xyz789",
  "chunks": 5,
  "message": "Document stored and indexed"
}
```

**Status Codes:**

| Code | Description |
|------|-------------|
| 200 | Document stored successfully |
| 400 | Invalid request body |
| 401 | Unauthorized |
| 413 | Document too large |
| 500 | Server error |

---

## Data Types

### Memory Object

```typescript
interface Memory {
  id: string;                    // Unique identifier
  content: string;               // Memory content
  eventType: EventType;          // Classification
  projectName: string;           // Source project
  projectDir: string;            // Full project path
  sessionId: string;             // Session identifier
  timestamp: string;             // ISO 8601 timestamp
  tags: string[];                // Associated tags
  relevanceScore?: number;       // Search relevance (0-1)
}
```

### Document Object

```typescript
interface Document {
  id: string;                    // Unique identifier
  title: string;                 // Document title
  content: string;               // Full content
  excerpt?: string;              // Relevant excerpt (in search results)
  type: string;                  // Document type
  format: string;                // File format
  source: string;                // Source identifier
  tags: string[];                // Associated tags
  metadata: DocumentMetadata;    // Additional metadata
  relevanceScore?: number;       // Search relevance (0-1)
}
```

### Entity Object

```typescript
interface Entity {
  name: string;                  // Entity name
  type: EntityType;              // Entity classification
  relatedMemories: number;       // Count of related memories
  relationships: Relationship[]; // Connections to other entities
}
```

### Event Types

```typescript
type EventType =
  | 'fix'        // Bug fixes and solutions
  | 'decision'   // Architecture/design choices
  | 'learning'   // Discoveries while coding
  | 'pattern'    // Reusable code patterns
  | 'preference' // User/project preferences
  | 'context';   // Project-specific context
```

### Entity Types

```typescript
type EntityType =
  | 'technology'  // Programming languages, frameworks
  | 'concept'     // Abstract concepts
  | 'person'      // People (team members, authors)
  | 'project'     // Projects and repositories
  | 'file'        // Files and paths
  | 'error'       // Error types and messages
  | 'pattern';    // Design patterns
```

---

## Error Responses

All errors follow this format:

```json
{
  "error": true,
  "code": "ERROR_CODE",
  "message": "Human-readable error message",
  "details": {}
}
```

### Error Codes

| Code | HTTP Status | Description |
|------|-------------|-------------|
| `INVALID_REQUEST` | 400 | Malformed request body |
| `MISSING_CONTENT` | 400 | Required content field missing |
| `INVALID_EVENT_TYPE` | 400 | Unknown event type |
| `UNAUTHORIZED` | 401 | Missing or invalid auth headers |
| `FORBIDDEN` | 403 | Access denied to resource |
| `NOT_FOUND` | 404 | Resource not found |
| `RATE_LIMITED` | 429 | Too many requests |
| `DOCUMENT_TOO_LARGE` | 413 | Document exceeds size limit |
| `SERVER_ERROR` | 500 | Internal server error |

---

## Rate Limits

| Endpoint | Limit | Window |
|----------|-------|--------|
| Store Memory | 100 | 1 minute |
| Recall Memory | 60 | 1 minute |
| Store Document | 10 | 1 minute |

Rate limit headers are included in responses:

```
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1704067200
```

---

## Shell Hook Reference

### store-memory.sh

**Input:** JSON via stdin

```json
{
  "content": "Memory content (required)",
  "event_type": "fix|decision|learning|pattern|preference|context",
  "session_id": "Optional session identifier"
}
```

**Output:** None (fire-and-forget, runs async)

**Environment Variables:**

| Variable | Default | Description |
|----------|---------|-------------|
| `NEXUS_API_URL` | `https://api.adverant.ai` | API endpoint |
| `NEXUS_COMPANY_ID` | `adverant` | Company identifier |
| `NEXUS_APP_ID` | `claude-code` | Application identifier |
| `USER` | System user | User identifier |

### recall-memory.sh

**Input:** JSON via stdin

```json
{
  "query": "Search query (required)"
}
```

**Output:** JSON to stdout

```json
{
  "memories": [...],
  "documents": [...],
  "entities": [...]
}
```

### upload-document.sh

**Arguments:**

```bash
./upload-document.sh <file_path> [title] [tags]
```

| Argument | Required | Description |
|----------|----------|-------------|
| `file_path` | Yes | Path to file to upload |
| `title` | No | Document title (defaults to filename) |
| `tags` | No | Comma-separated tags |

**Output:** JSON response to stdout

---

## SDK Examples (Coming Soon)

### TypeScript

```typescript
import { NexusMemory } from '@nexus-cli/sdk';

const memory = new NexusMemory({
  apiUrl: 'https://api.adverant.ai',
  companyId: 'adverant',
  appId: 'my-app',
  userId: 'alice'
});

// Store
await memory.store({
  content: 'Fixed the CORS issue',
  eventType: 'fix'
});

// Recall
const results = await memory.recall({
  query: 'CORS issues',
  limit: 5
});
```

### Python

```python
from nexus_memory import NexusMemory

memory = NexusMemory(
    api_url="https://api.adverant.ai",
    company_id="adverant",
    app_id="my-app",
    user_id="alice"
)

# Store
memory.store(
    content="Fixed the CORS issue",
    event_type="fix"
)

# Recall
results = memory.recall(
    query="CORS issues",
    limit=5
)
```

---

## Webhooks (Planned)

Future support for real-time notifications:

```json
{
  "event": "memory.stored",
  "timestamp": "2024-12-28T12:00:00Z",
  "data": {
    "id": "mem_abc123",
    "content": "...",
    "eventType": "fix"
  }
}
```

---

## See Also

- [Architecture](architecture.md) — System design
- [Getting Started](getting-started.md) — Quick start guide
- [Use Cases](use-cases.md) — Real-world examples
