# Knowledge API

The Knowledge Master API is a unified layer integrating all knowledge subsystems: document parsing with semantic chunking, audio intelligence, workflow memory, git/code intelligence, and the Neo4j knowledge graph. It provides cross-system search, insights, and analytics through a single API surface.

> **Base path:** `/api/knowledge` | **Version:** v1 | **Auth:** JWT (except health) | **Rate limit:** 100 req/min

> **Note:** This is a v1 API mounted at `/api/knowledge` (not /api/v2). Sub-APIs for documents, audio, workflows, and code are mounted under this path.

## GET /api/knowledge/health

Health Check -- Master health check that probes all knowledge subsystems: knowledge graph (Neo4j), documents, audio, workflows, and code. Returns overall status as "healthy" if all subsystems pass, or "degraded" if any fail. Does not require authentication.

### Example Request

```bash
curl -X GET https://api.lvng.ai/api/knowledge/health
```

### Response (200)

```json
{
  "status": "healthy",
  "timestamp": "2026-03-19T10:00:00.000Z",
  "version": "1.0.0",
  "subsystems": {
    "knowledgeGraph": { "status": "healthy", "connected": true, "latency": 12 },
    "documents": { "status": "healthy", "documentCount": 347 },
    "audio": { "status": "healthy", "voiceNotes": 0 },
    "workflows": { "status": "healthy", "enabled": true },
    "code": { "status": "healthy", "filesAnalyzed": 1284 }
  },
  "crossSystem": { "enabled": true, "queryService": "active" }
}
```

## GET /api/knowledge/stats

Unified Statistics -- Returns aggregate statistics across all knowledge subsystems via the CrossSystemQueryService.

**Authentication required**

### Example Request

```bash
curl -X GET https://api.lvng.ai/api/knowledge/stats \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Response (200)

```json
{
  "documents": { "total": 347, "byType": { "pdf": 124, "markdown": 98, "text": 82, "html": 43 }, "totalChunks": 4821 },
  "audio": { "totalRecordings": 89, "totalDurationMinutes": 412, "transcribed": 76 },
  "workflows": { "totalExecutions": 2341, "memoryCaptured": 1856 },
  "code": { "filesAnalyzed": 1284, "repositories": 5, "totalCommits": 3472 },
  "knowledgeGraph": { "totalNodes": 8734, "totalRelationships": 24561, "concepts": 1247 }
}
```

## POST /api/knowledge/ingest

Ingest Content -- Unified ingestion endpoint that auto-routes content to the appropriate subsystem based on the type field. Supported types: text, document_url, voice_transcription, meeting_transcript, code_snippet, git_commits, workflow_execution.

**Authentication required**

### Body Parameters

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| type | string | Yes | -- | Content type to ingest. One of: text, document_url, voice_transcription, meeting_transcript, code_snippet, git_commits, workflow_execution. |
| data | string or object | Yes | -- | The content to ingest. Format depends on type: plain text for "text", URL string for "document_url", structured objects for others. |
| metadata | object | No | {} | Additional metadata. Supports category, source, chunkSize (for text), language (for code), repoPath (for git_commits). |

### Example Request

```bash
curl -X POST https://api.lvng.ai/api/knowledge/ingest \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "text",
    "data": "Remote work policy: All team members may work remotely up to 3 days per week. Core hours are 10am-3pm EST. Managers must approve schedules by Friday for the following week.",
    "metadata": {
      "category": "policies",
      "source": "hr-handbook",
      "chunkSize": 500
    }
  }'
```

### Response (201)

```json
{
  "success": true,
  "type": "text",
  "result": { "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "chunkCount": 2 },
  "message": "Content ingested successfully"
}
```

## POST /api/knowledge/search

Cross-System Search -- Searches across all knowledge subsystems simultaneously using the CrossSystemQueryService. Returns results with per-source breakdowns and aggregations.

**Authentication required**

### Body Parameters

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| query | string | Yes | -- | The search query string. |
| sources | string[] | No | ["all"] | Which subsystems to search. Pass "all" to search everything. |
| limit | number | No | 20 | Maximum results to return. |
| filters | object | No | {} | Additional filters to narrow results. |

### Example Request

```bash
curl -X POST https://api.lvng.ai/api/knowledge/search \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "authentication flow implementation",
    "sources": ["all"],
    "limit": 10
  }'
```

### Response (200)

```json
{
  "query": "authentication flow implementation",
  "sources": ["all"],
  "results": [
    { "id": "b2c3d4e5-f6a7-8901-bcde-f12345678901", "type": "code", "title": "auth-middleware.js", "content": "JWT verification and role-based access control implementation...", "score": 0.94, "source": "code" },
    { "id": "c3d4e5f6-a7b8-9012-cdef-123456789012", "type": "document", "title": "Authentication Architecture", "content": "The platform uses JWT-based authentication with refresh token rotation...", "score": 0.89, "source": "documents" }
  ],
  "total": 2,
  "breakdown": { "code": 1, "documents": 1, "audio": 0, "workflows": 0 },
  "aggregations": {}
}
```

## GET /api/knowledge/timeline

Knowledge Timeline -- Returns a unified chronological view of knowledge events across all subsystems.

**Authentication required**

### Query Parameters

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| since | string | No | -- | ISO 8601 start date for the timeline. |
| until | string | No | -- | ISO 8601 end date for the timeline. |
| types | string | No | all | Comma-separated content types to include. Pass "all" for everything. |
| limit | number | No | 50 | Maximum events to return. |
| granularity | string | No | day | Time grouping granularity: hour, day, week, or month. |

### Example Request

```bash
curl -X GET "https://api.lvng.ai/api/knowledge/timeline?since=2026-03-12T00:00:00Z&until=2026-03-19T23:59:59Z&granularity=day&limit=20" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Response (200)

```json
{
  "timeline": [
    { "timestamp": "2026-03-19T14:30:00.000Z", "type": "document", "title": "API Design Guidelines v2", "action": "ingested", "source": "documents" },
    { "timestamp": "2026-03-19T10:15:00.000Z", "type": "voice_transcription", "title": "Sprint retro thoughts", "action": "transcribed", "source": "audio" },
    { "timestamp": "2026-03-18T16:45:00.000Z", "type": "code", "title": "feat: add calendar availability endpoint", "action": "committed", "source": "code" }
  ],
  "summary": { "totalEvents": 3, "bySource": { "documents": 1, "audio": 1, "code": 1 } },
  "filters": { "since": "2026-03-12T00:00:00Z", "until": "2026-03-19T23:59:59Z", "types": "all" }
}
```

## GET /api/knowledge/insights

Cross-System Insights -- Generates AI-powered insights and correlations across all knowledge subsystems. Analyzes patterns, identifies knowledge gaps, and surfaces connections.

**Authentication required**

### Query Parameters

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| timeWindow | string | No | P30D | ISO 8601 duration for the analysis window (e.g., P7D for 7 days). |
| depth | number | No | 2 | Depth of relationship traversal in the knowledge graph. |

### Example Request

```bash
curl -X GET "https://api.lvng.ai/api/knowledge/insights?timeWindow=P7D&depth=2" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Response (200)

```json
{
  "insights": [
    { "type": "correlation", "title": "Calendar integration discussed across 3 systems", "description": "The 'calendar integration' topic appeared in meeting transcripts, code commits, and 2 documents this week.", "confidence": 0.92, "sources": ["audio", "code", "documents"] },
    { "type": "knowledge_gap", "title": "Missing documentation for voice notes API", "description": "Code changes to voice-notes-api.js have no corresponding documentation updates.", "confidence": 0.78, "sources": ["code", "documents"] }
  ],
  "timeWindow": "P7D",
  "generatedAt": "2026-03-19T10:30:00.000Z"
}
```

## POST /api/knowledge/related

Find Related Content -- Finds content related to a given item by traversing the knowledge graph. Returns results grouped by content type with relevance scores.

**Authentication required**

### Body Parameters

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| contentId | string | Yes | -- | The ID of the source content to find relations for. |
| contentType | string | Yes | -- | The type of the source content (e.g., document, code, audio, workflow). |
| maxDepth | number | No | 2 | Maximum relationship traversal depth in the graph. |
| limit | number | No | 10 | Maximum related items to return. |

### Example Request

```bash
curl -X POST https://api.lvng.ai/api/knowledge/related \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contentId": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
    "contentType": "document",
    "maxDepth": 2,
    "limit": 5
  }'
```

### Response (200)

```json
{
  "contentId": "b2c3d4e5-f6a7-8901-bcde-f12345678901",
  "contentType": "document",
  "related": [
    { "id": "d4e5f6a7-b8c9-0d1e-2f3a-4b5c6d7e8f90", "type": "code", "title": "auth-middleware.js", "score": 0.87, "relationship": "IMPLEMENTS" },
    { "id": "e5f6a7b8-c9d0-1e2f-3a4b-5c6d7e8f9a0b", "type": "audio", "title": "Architecture review - auth flow", "score": 0.72, "relationship": "DISCUSSES" }
  ],
  "count": 2,
  "byType": { "code": 1, "audio": 1 }
}
```

## POST /api/knowledge/cross-reference

Cross-Reference -- Finds cross-references between a source item and target content types.

**Authentication required**

### Body Parameters

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| sourceType | string | Yes | -- | The type of the source content. |
| sourceId | string | Yes | -- | The ID of the source content. |
| targetTypes | string[] | No | [] | Content types to cross-reference against. |
| query | string | No | -- | Optional text query to further filter cross-references. |

### Example Request

```bash
curl -X POST https://api.lvng.ai/api/knowledge/cross-reference \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "sourceType": "audio",
    "sourceId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
    "targetTypes": ["code", "document"],
    "query": "calendar integration"
  }'
```

### Response (200)

```json
{
  "source": { "type": "audio", "id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" },
  "references": [
    { "id": "f6a7b8c9-d0e1-2f3a-4b5c-6d7e8f9a0b1c", "type": "code", "title": "calendar-api.js", "score": 0.91 },
    { "id": "a7b8c9d0-e1f2-3a4b-5c6d-7e8f9a0b1c2d", "type": "document", "title": "Calendar Integration Design Doc", "score": 0.85 }
  ],
  "count": 2,
  "byType": { "code": 1, "document": 1 }
}
```

## GET /api/knowledge/concept/:name/mentions

Concept Mentions -- Tracks all mentions of a named concept across every knowledge subsystem. Returns mentions grouped by source with a timeline view.

**Authentication required**

### Path Parameters

| Name | Type | Required | Description |
|------|------|----------|-------------|
| name | string | Yes | The concept name to track (e.g., "authentication", "rate-limiting"). |

### Query Parameters

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| limit | number | No | 50 | Maximum mentions to return. |

### Example Request

```bash
curl -X GET "https://api.lvng.ai/api/knowledge/concept/authentication/mentions?limit=10" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Response (200)

```json
{
  "concept": "authentication",
  "mentions": [
    { "id": "b8c9d0e1-f2a3-4b5c-6d7e-8f9a0b1c2d3e", "source": "code", "title": "auth-middleware.js", "context": "JWT verification and role-based access control...", "timestamp": "2026-03-18T16:45:00.000Z" },
    { "id": "c9d0e1f2-a3b4-5c6d-7e8f-9a0b1c2d3e4f", "source": "documents", "title": "Security Architecture Overview", "context": "The authentication layer uses JWT tokens with...", "timestamp": "2026-03-15T11:00:00.000Z" }
  ],
  "total": 2,
  "bySource": { "code": 1, "documents": 1, "audio": 0, "workflows": 0 },
  "timeline": [ { "date": "2026-03-18", "count": 1 }, { "date": "2026-03-15", "count": 1 } ]
}
```

## GET /api/knowledge/analytics/velocity

Knowledge Velocity -- Measures the rate of knowledge acquisition across all subsystems over time.

**Authentication required**

### Query Parameters

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| timeWindow | string | No | P30D | ISO 8601 duration for the analysis window. |
| granularity | string | No | day | Time bucketing: hour, day, week, or month. |
| systems | string | No | all | Comma-separated subsystems to include, or "all". |

### Example Request

```bash
curl -X GET "https://api.lvng.ai/api/knowledge/analytics/velocity?timeWindow=P7D&granularity=day" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Response (200)

```json
{
  "velocity": {
    "trend": "increasing",
    "averagePerDay": 12.4,
    "buckets": [
      { "date": "2026-03-13", "count": 8 },
      { "date": "2026-03-14", "count": 15 },
      { "date": "2026-03-15", "count": 6 },
      { "date": "2026-03-16", "count": 3 },
      { "date": "2026-03-17", "count": 18 },
      { "date": "2026-03-18", "count": 14 },
      { "date": "2026-03-19", "count": 23 }
    ],
    "bySystem": { "documents": 34, "code": 28, "audio": 12, "workflows": 13 }
  },
  "timeWindow": "P7D",
  "granularity": "day"
}
```

## GET /api/knowledge/analytics/dashboard

Analytics Dashboard -- Returns a pre-computed analytics dashboard with key metrics, trends, and summaries across the entire knowledge system.

**Authentication required**

### Query Parameters

| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| timeWindow | string | No | P7D | ISO 8601 duration for the dashboard data window. |

### Example Request

```bash
curl -X GET "https://api.lvng.ai/api/knowledge/analytics/dashboard?timeWindow=P7D" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Response (200)

```json
{
  "summary": {
    "totalKnowledgeItems": 8734,
    "newThisWeek": 87,
    "activeSubsystems": 5,
    "topConcepts": ["authentication", "calendar", "voice-notes", "workflows", "api-design"]
  },
  "activity": {
    "documents": { "new": 12, "updated": 8 },
    "audio": { "recorded": 5, "transcribed": 4 },
    "code": { "commits": 42, "filesChanged": 67 },
    "workflows": { "executed": 23, "memoryCaptured": 19 }
  },
  "health": {
    "knowledgeGraph": "healthy",
    "documents": "healthy",
    "audio": "healthy",
    "workflows": "healthy",
    "code": "healthy"
  },
  "timeWindow": "P7D",
  "generatedAt": "2026-03-19T10:30:00.000Z"
}
```
