# Knowledge Graph Documentation

## Overview

Lilith now relies on Sophia's knowledge graph as the canonical graph database
for relationships between spiritual traditions, philosophical concepts,
historical figures, practices, texts, and places. It enables intelligent
navigation, recommendation, and exploration of contemplative wisdom across
traditions.

## Table of Contents

1. [Architecture](#architecture)
2. [Node Types](#node-types)
3. [Relationship Types](#relationship-types)
4. [Schema Design](#schema-design)
5. [Query Patterns](#query-patterns)
6. [Data Quality](#data-quality)
7. [API Reference](#api-reference)

---

## Architecture

### Technology Stack

| Component      | Technology         | Purpose               |
| -------------- | ------------------ | --------------------- |
| Graph Database | Neo4j 5.x          | Primary graph storage |
| Query Language | Cypher             | Graph queries         |
| Connection     | Bolt Protocol      | Client connections    |
| Indexing       | Full-text + B-tree | Search optimization   |

### Storage Location

**Service**: `apps/sophia/knowledge-graph/src/graph/graph-service.ts`

### Connection Configuration

| Setting       | Default                 | Description            |
| ------------- | ----------------------- | ---------------------- |
| URI           | `bolt://localhost:7687` | Neo4j connection       |
| Pool Size     | 50                      | Maximum connections    |
| Query Timeout | 30s                     | Maximum query duration |
| Encryption    | TLS                     | Connection security    |

---

## Node Types

### TRADITION

Represents a spiritual, philosophical, or contemplative tradition.

| Property          | Type   | Required | Description                    |
| ----------------- | ------ | -------- | ------------------------------ |
| `id`              | string | Yes      | Unique identifier              |
| `name`            | string | Yes      | Tradition name                 |
| `origin`          | string | No       | Geographic/cultural origin     |
| `foundingDate`    | string | No       | Approximate founding           |
| `description`     | string | No       | Overview description           |
| `parentTradition` | string | No       | Parent tradition if sub-school |

**Examples:**

- Zen Buddhism
- Stoicism
- Advaita Vedanta
- Sufism
- Christian Mysticism

### CONCEPT

Represents a philosophical, spiritual, or psychological concept.

| Property       | Type   | Required | Description            |
| -------------- | ------ | -------- | ---------------------- |
| `id`           | string | Yes      | Unique identifier      |
| `name`         | string | Yes      | Concept name           |
| `tradition`    | string | No       | Primary tradition      |
| `definition`   | string | No       | Core definition        |
| `sanskritTerm` | string | No       | Sanskrit if applicable |
| `greekTerm`    | string | No       | Greek if applicable    |
| `arabicTerm`   | string | No       | Arabic if applicable   |

**Examples:**

- Mindfulness (sati)
- Virtue (arete)
- Non-duality (advaita)
- Divine love (ishq)
- Kenosis

### PRACTICE

Represents a contemplative, meditative, or spiritual practice.

| Property      | Type   | Required | Description                        |
| ------------- | ------ | -------- | ---------------------------------- |
| `id`          | string | Yes      | Unique identifier                  |
| `name`        | string | Yes      | Practice name                      |
| `tradition`   | string | No       | Primary tradition                  |
| `type`        | string | No       | meditation, prayer, movement, etc. |
| `difficulty`  | string | No       | beginner, intermediate, advanced   |
| `duration`    | string | No       | Typical duration                   |
| `description` | string | No       | Practice description               |

**Examples:**

- Zazen (Zen sitting)
- Centering Prayer
- Pranayama
- Lectio Divina
- Walking Meditation

### FIGURE

Represents a historical or contemporary teacher, philosopher, or saint.

| Property    | Type   | Required | Description        |
| ----------- | ------ | -------- | ------------------ |
| `id`        | string | Yes      | Unique identifier  |
| `name`      | string | Yes      | Full name          |
| `birthDate` | string | No       | Birth date/century |
| `deathDate` | string | No       | Death date/century |
| `tradition` | string | No       | Primary tradition  |
| `title`     | string | No       | Title or honorific |
| `biography` | string | No       | Brief biography    |

**Examples:**

- Gautama Buddha
- Marcus Aurelius
- Teresa of Avila
- Rumi
- Ramana Maharshi

### TEXT

Represents a scripture, book, or significant written work.

| Property    | Type   | Required | Description                   |
| ----------- | ------ | -------- | ----------------------------- |
| `id`        | string | Yes      | Unique identifier             |
| `title`     | string | Yes      | Work title                    |
| `author`    | string | No       | Author if known               |
| `date`      | string | No       | Date/century composed         |
| `tradition` | string | No       | Associated tradition          |
| `type`      | string | No       | scripture, commentary, manual |
| `language`  | string | No       | Original language             |

**Examples:**

- Dhammapada
- Meditations (Marcus Aurelius)
- Cloud of Unknowing
- Masnavi
- Yoga Sutras

### PLACE

Represents a significant geographic location or sacred site.

| Property       | Type   | Required | Description                       |
| -------------- | ------ | -------- | --------------------------------- |
| `id`           | string | Yes      | Unique identifier                 |
| `name`         | string | Yes      | Place name                        |
| `type`         | string | No       | monastery, temple, mountain, etc. |
| `location`     | string | No       | Geographic location               |
| `tradition`    | string | No       | Associated tradition              |
| `significance` | string | No       | Why significant                   |

**Examples:**

- Bodh Gaya
- Mount Athos
- Rishikesh
- Konya
- Assisi

---

## Relationship Types

### Teacher-Student Relationships

| Relationship | Direction          | Description                  |
| ------------ | ------------------ | ---------------------------- |
| `TAUGHT`     | FIGURE → FIGURE    | Teacher taught student       |
| `LINEAGE_OF` | FIGURE → FIGURE    | Spiritual lineage connection |
| `FOUNDED`    | FIGURE → TRADITION | Figure founded tradition     |

### Authorship Relationships

| Relationship   | Direction     | Description        |
| -------------- | ------------- | ------------------ |
| `WROTE`        | FIGURE → TEXT | Author wrote work  |
| `TRANSLATED`   | FIGURE → TEXT | Translator of work |
| `COMMENTED_ON` | TEXT → TEXT   | Commentary on text |

### Tradition Relationships

| Relationship   | Direction             | Description               |
| -------------- | --------------------- | ------------------------- |
| `BELONGS_TO`   | \* → TRADITION        | Belongs to tradition      |
| `DERIVES_FROM` | TRADITION → TRADITION | Historical derivation     |
| `INFLUENCED`   | TRADITION → TRADITION | Cross-tradition influence |

### Concept Relationships

| Relationship  | Direction          | Description               |
| ------------- | ------------------ | ------------------------- |
| `ALIGNS_WITH` | CONCEPT → CONCEPT  | Conceptual similarity     |
| `CONTRADICTS` | CONCEPT → CONCEPT  | Conceptual opposition     |
| `EXEMPLIFIES` | PRACTICE → CONCEPT | Practice embodies concept |
| `DISCUSSES`   | TEXT → CONCEPT     | Text addresses concept    |

### Practice Relationships

| Relationship      | Direction            | Description           |
| ----------------- | -------------------- | --------------------- |
| `REQUIRES`        | PRACTICE → PRACTICE  | Prerequisite practice |
| `PRECEDES`        | PRACTICE → PRACTICE  | Sequential ordering   |
| `VARIATION_OF`    | PRACTICE → PRACTICE  | Related variation     |
| `ORIGINATES_FROM` | PRACTICE → TRADITION | Practice origin       |

### Place Relationships

| Relationship      | Direction         | Description         |
| ----------------- | ----------------- | ------------------- |
| `LIVED_IN`        | FIGURE → PLACE    | Figure resided here |
| `SACRED_TO`       | PLACE → TRADITION | Sacred to tradition |
| `ASSOCIATED_WITH` | \* → PLACE        | General association |

### Cross-Domain Relationships

| Relationship      | Direction       | Description       |
| ----------------- | --------------- | ----------------- |
| `REFERENCES`      | TEXT → TEXT     | Cross-reference   |
| `INFLUENCED_BY`   | _ → _           | General influence |
| `CONTEMPORARY_OF` | FIGURE → FIGURE | Same time period  |

---

## Schema Design

### Constraints

```cypher
// Unique ID constraints
CREATE CONSTRAINT tradition_id IF NOT EXISTS
FOR (t:TRADITION) REQUIRE t.id IS UNIQUE;

CREATE CONSTRAINT concept_id IF NOT EXISTS
FOR (c:CONCEPT) REQUIRE c.id IS UNIQUE;

CREATE CONSTRAINT practice_id IF NOT EXISTS
FOR (p:PRACTICE) REQUIRE p.id IS UNIQUE;

CREATE CONSTRAINT figure_id IF NOT EXISTS
FOR (f:FIGURE) REQUIRE f.id IS UNIQUE;

CREATE CONSTRAINT text_id IF NOT EXISTS
FOR (t:TEXT) REQUIRE t.id IS UNIQUE;

CREATE CONSTRAINT place_id IF NOT EXISTS
FOR (p:PLACE) REQUIRE p.id IS UNIQUE;
```

### Indexes

```cypher
// Full-text indexes for search
CREATE FULLTEXT INDEX tradition_search IF NOT EXISTS
FOR (t:TRADITION) ON EACH [t.name, t.description];

CREATE FULLTEXT INDEX concept_search IF NOT EXISTS
FOR (c:CONCEPT) ON EACH [c.name, c.definition];

CREATE FULLTEXT INDEX figure_search IF NOT EXISTS
FOR (f:FIGURE) ON EACH [f.name, f.biography];

CREATE FULLTEXT INDEX text_search IF NOT EXISTS
FOR (t:TEXT) ON EACH [t.title, t.author];

// Property indexes for filtering
CREATE INDEX tradition_name IF NOT EXISTS FOR (t:TRADITION) ON (t.name);
CREATE INDEX figure_tradition IF NOT EXISTS FOR (f:FIGURE) ON (f.tradition);
CREATE INDEX practice_difficulty IF NOT EXISTS FOR (p:PRACTICE) ON (p.difficulty);
```

---

## Query Patterns

### Finding Related Concepts

```cypher
// Find concepts that align with a given concept
MATCH (c:CONCEPT {name: "mindfulness"})-[:ALIGNS_WITH]-(related:CONCEPT)
RETURN related.name, related.tradition
```

### Exploring Traditions

```cypher
// Get all practices in a tradition
MATCH (t:TRADITION {name: "Zen Buddhism"})<-[:BELONGS_TO]-(p:PRACTICE)
RETURN p.name, p.type, p.difficulty
ORDER BY p.difficulty
```

### Tracing Lineages

```cypher
// Find teaching lineage (up to 5 generations)
MATCH path = (student:FIGURE {name: "Dogen"})<-[:TAUGHT*1..5]-(teacher:FIGURE)
RETURN [n IN nodes(path) | n.name] AS lineage
```

### Cross-Tradition Connections

```cypher
// Find concepts that appear in multiple traditions
MATCH (c:CONCEPT)-[:BELONGS_TO]->(t:TRADITION)
WITH c, count(DISTINCT t) AS traditionCount
WHERE traditionCount > 1
RETURN c.name, traditionCount
ORDER BY traditionCount DESC
```

### Practice Prerequisites

```cypher
// Find prerequisite path for a practice
MATCH path = (p:PRACTICE {name: "Shikantaza"})<-[:REQUIRES*]-(prereq:PRACTICE)
RETURN [n IN nodes(path) | n.name] AS prerequisitePath
```

### Figure Connections

```cypher
// Find figures connected to a text
MATCH (t:TEXT {title: "Yoga Sutras"})
OPTIONAL MATCH (author:FIGURE)-[:WROTE]->(t)
OPTIONAL MATCH (commentator:FIGURE)-[:COMMENTED_ON]->(t)
RETURN t.title, author.name AS author,
       collect(DISTINCT commentator.name) AS commentators
```

### Semantic Path Finding

```cypher
// Find shortest path between two concepts
MATCH path = shortestPath(
  (c1:CONCEPT {name: "mindfulness"})-[*]-(c2:CONCEPT {name: "apatheia"})
)
RETURN path
```

---

## Data Quality

### Required Relationships

Each node type should have minimum relationships:

| Node Type | Required Relationships                        |
| --------- | --------------------------------------------- |
| TRADITION | At least 3 CONCEPT, 2 PRACTICE                |
| CONCEPT   | BELONGS_TO tradition, ALIGNS_WITH 1+ concepts |
| PRACTICE  | BELONGS_TO tradition, EXEMPLIFIES 1+ concepts |
| FIGURE    | BELONGS_TO tradition, WROTE or TAUGHT         |
| TEXT      | BELONGS_TO tradition, WROTE relationship      |
| PLACE     | SACRED_TO or ASSOCIATED_WITH                  |

### Validation Queries

```cypher
// Find orphan nodes (no relationships)
MATCH (n)
WHERE NOT (n)--()
RETURN labels(n), n.name

// Find traditions without practices
MATCH (t:TRADITION)
WHERE NOT (t)<-[:BELONGS_TO]-(:PRACTICE)
RETURN t.name

// Find concepts without tradition
MATCH (c:CONCEPT)
WHERE NOT (c)-[:BELONGS_TO]->(:TRADITION)
RETURN c.name
```

### Quality Metrics

| Metric                | Target  | Description                       |
| --------------------- | ------- | --------------------------------- |
| Node Connectivity     | > 3 avg | Average relationships per node    |
| Cross-Tradition Links | > 20%   | Concepts linked across traditions |
| Path Coverage         | > 80%   | Reachable from any tradition      |
| Property Completeness | > 90%   | Required properties filled        |

---

## API Reference

### Graph Store Interface

```typescript
interface GraphStore {
  // Node operations
  createNode(
    type: NodeType,
    properties: Record<string, any>
  ): Promise<GraphNode>;
  getNode(id: string): Promise<GraphNode | null>;
  updateNode(id: string, properties: Record<string, any>): Promise<GraphNode>;
  deleteNode(id: string): Promise<void>;

  // Relationship operations
  createRelationship(
    fromId: string,
    toId: string,
    type: RelationshipType,
    properties?: Record<string, any>
  ): Promise<GraphRelationship>;

  // Query operations
  query(cypher: string, params?: Record<string, any>): Promise<any>;

  // Traversal operations
  traverse(startId: string, options: TraversalOptions): Promise<GraphNode[]>;
}
```

### REST Endpoints

| Method | Endpoint                  | Description          |
| ------ | ------------------------- | -------------------- |
| POST   | `/v1/graph/nodes`         | Create node          |
| GET    | `/v1/graph/nodes/:id`     | Get node             |
| PUT    | `/v1/graph/nodes/:id`     | Update node          |
| DELETE | `/v1/graph/nodes/:id`     | Delete node          |
| POST   | `/v1/graph/relationships` | Create relationship  |
| GET    | `/v1/graph/search`        | Search nodes         |
| GET    | `/v1/graph/traverse/:id`  | Traverse from node   |
| POST   | `/v1/graph/query`         | Execute Cypher query |

### Search Parameters

```typescript
interface GraphSearchParams {
  query: string; // Full-text search query
  nodeTypes?: NodeType[]; // Filter by node types
  traditions?: string[]; // Filter by traditions
  limit?: number; // Max results (default 20)
  minScore?: number; // Minimum relevance score
}
```

### Traversal Options

```typescript
interface TraversalOptions {
  maxHops: number; // Maximum relationship depth
  relationshipTypes?: string[]; // Filter relationship types
  nodeTypes?: string[]; // Filter node types
  direction?: 'IN' | 'OUT' | 'BOTH';
}
```

---

## Usage Examples

### Building a Tradition Page

```typescript
async function getTraditionOverview(traditionName: string) {
  // Get tradition details
  const tradition = await graphStore.query(
    `
    MATCH (t:TRADITION {name: $name})
    RETURN t
  `,
    { name: traditionName }
  );

  // Get key figures
  const figures = await graphStore.query(
    `
    MATCH (t:TRADITION {name: $name})<-[:BELONGS_TO]-(f:FIGURE)
    RETURN f.name, f.birthDate, f.deathDate
    LIMIT 10
  `,
    { name: traditionName }
  );

  // Get core practices
  const practices = await graphStore.query(
    `
    MATCH (t:TRADITION {name: $name})<-[:BELONGS_TO]-(p:PRACTICE)
    RETURN p.name, p.type, p.difficulty
  `,
    { name: traditionName }
  );

  // Get foundational texts
  const texts = await graphStore.query(
    `
    MATCH (t:TRADITION {name: $name})<-[:BELONGS_TO]-(txt:TEXT)
    RETURN txt.title, txt.author, txt.date
  `,
    { name: traditionName }
  );

  return { tradition, figures, practices, texts };
}
```

### Finding Cross-Tradition Connections

```typescript
async function findCrossTraditonConnections(concept: string) {
  return graphStore.query(
    `
    MATCH (c:CONCEPT {name: $concept})-[:ALIGNS_WITH]-(related:CONCEPT)
    WHERE c.tradition <> related.tradition
    RETURN related.name, related.tradition, related.definition
  `,
    { concept }
  );
}
```

### Recommendation Engine

```typescript
async function recommendPractices(userId: string, currentPractice: string) {
  // Find related practices based on graph relationships
  return graphStore.query(
    `
    MATCH (p:PRACTICE {name: $practice})
    MATCH (p)-[:EXEMPLIFIES]->(:CONCEPT)<-[:EXEMPLIFIES]-(related:PRACTICE)
    WHERE related.name <> p.name
    WITH related, count(*) as sharedConcepts
    ORDER BY sharedConcepts DESC
    RETURN related.name, related.tradition, related.difficulty
    LIMIT 5
  `,
    { practice: currentPractice }
  );
}
```

---

## Related Documents

- [Content Ingestion Guide](./CONTENT_INGESTION.md)
- [Tradition-Specific Guidelines](./TRADITION_GUIDELINES.md)
- [Content Guidelines](./CONTENT_GUIDELINES.md)

---

_Last updated: January 2, 2026_
