# Graph Database Schema

This document describes the Neo4j knowledge graph schema for the Lilith
platform.

## Overview

Lilith consumes Sophia's graph layer for representing knowledge relationships
across spiritual traditions, texts, practices, figures, and concepts. The
canonical implementation now lives under `apps/sophia/knowledge-graph/`.

## Node Types

The knowledge graph contains 9 node types:

| Node Type   | Description                        | Key Properties                             |
| ----------- | ---------------------------------- | ------------------------------------------ |
| `Tradition` | Spiritual/philosophical traditions | origin_region, time_period, key_principles |
| `Text`      | Sacred and philosophical texts     | title, author, language, year, genre       |
| `Concept`   | Abstract ideas and teachings       | definition, category, complexity_level     |
| `Practice`  | Spiritual exercises and rituals    | difficulty, prerequisites, duration        |
| `Figure`    | Historical/religious figures       | birth_year, death_year, bio_summary        |
| `Place`     | Sacred sites and locations         | country, region, coordinates, significance |
| `School`    | Philosophical/spiritual schools    | (extends BaseNodeProperties)               |
| `Doctrine`  | Formal teachings and beliefs       | (extends BaseNodeProperties)               |
| `Event`     | Historical events                  | (extends BaseNodeProperties)               |

### Base Node Properties

All nodes share these properties:

```typescript
interface BaseNodeProperties {
  id: string; // Unique identifier
  name: string; // Human-readable name
  description?: string; // Description or summary
  created_at?: number; // Creation timestamp
  updated_at?: number; // Last update timestamp
  created_by?: string; // User who created the node
}
```

### Tradition Node

```typescript
interface TraditionProperties extends BaseNodeProperties {
  origin_region?: string; // Geographic origin
  time_period?: string; // Historical period
  key_principles?: string[]; // Core teachings
  founding_figures?: string[]; // Founders
  category?: string; // Classification
}
```

### Text Node

```typescript
interface TextProperties extends BaseNodeProperties {
  title: string; // Title of the text
  author?: string; // Author name
  language?: string; // Original language
  tradition?: string; // Associated tradition
  year?: number; // Year written/compiled
  source_url?: string; // Digital source
  content_hash?: string; // Hash for deduplication
  genre?: string; // Literary genre
}
```

### Concept Node

```typescript
interface ConceptProperties extends BaseNodeProperties {
  definition?: string; // Meaning/definition
  tradition?: string; // Primary tradition
  category?: string; // Concept category
  complexity_level?: 'basic' | 'intermediate' | 'advanced';
  related_terms?: string[]; // Alternative terms
}
```

### Practice Node

```typescript
interface PracticeProperties extends BaseNodeProperties {
  tradition?: string; // Associated tradition
  difficulty?: 'beginner' | 'intermediate' | 'advanced' | 'master';
  prerequisites?: string[]; // Required prior practices
  duration?: string; // Typical session length
  frequency?: string; // Recommended frequency
}
```

### Figure Node

```typescript
interface FigureProperties extends BaseNodeProperties {
  birth_year?: number; // Year of birth
  death_year?: number; // Year of death
  traditions?: string[]; // Associated traditions
  bio_summary?: string; // Biographical summary
  titles?: string[]; // Titles/honorifics
  location?: string; // Primary location
}
```

### Place Node

```typescript
interface PlaceProperties extends BaseNodeProperties {
  country?: string; // Country
  region?: string; // Region/state
  coordinates?: {
    latitude: number;
    longitude: number;
  };
  significance?: string; // Why it's sacred/important
  traditions?: string[]; // Associated traditions
}
```

## Relationship Types

The schema defines 26 relationship types organized by domain:

### Figure Relationships

| Relationship    | Description                  | Example                       |
| --------------- | ---------------------------- | ----------------------------- |
| `TAUGHT`        | Teacher-student relationship | Buddha TAUGHT Ananda          |
| `WROTE`         | Authorship                   | Patanjali WROTE Yoga Sutras   |
| `LIVED_IN`      | Residence                    | Rumi LIVED_IN Konya           |
| `STUDIED_UNDER` | Apprenticeship               | Disciple STUDIED_UNDER Master |
| `FOUNDED`       | Establishment                | Bodhidharma FOUNDED Zen       |

### Concept Relationships

| Relationship   | Description              | Example                      |
| -------------- | ------------------------ | ---------------------------- |
| `ALIGNS_WITH`  | Conceptual agreement     | Dharma ALIGNS_WITH Tao       |
| `CONTRADICTS`  | Conceptual opposition    | Nihilism CONTRADICTS Meaning |
| `DERIVES_FROM` | Origin/derivation        | Tantra DERIVES_FROM Vedas    |
| `REFINES`      | Refinement/clarification | Madhyamaka REFINES Emptiness |
| `EXTENDS`      | Extension/expansion      | Mahayana EXTENDS Buddhism    |

### Practice Relationships

| Relationship | Description          | Example                                       |
| ------------ | -------------------- | --------------------------------------------- |
| `BELONGS_TO` | Tradition membership | Zazen BELONGS_TO Zen                          |
| `REQUIRES`   | Prerequisites        | Advanced meditation REQUIRES Basic meditation |
| `PRECEDES`   | Ordering             | Concentration PRECEDES Insight                |
| `FOLLOWS`    | Sequence             | Jhana FOLLOWS Samatha                         |

### Text Relationships

| Relationship      | Description        | Example                                  |
| ----------------- | ------------------ | ---------------------------------------- |
| `DISCUSSES`       | Topic coverage     | Bhagavad Gita DISCUSSES Karma            |
| `REFERENCES`      | Citation           | Commentary REFERENCES Sutra              |
| `CITES`           | Direct citation    | Scholar CITES Text                       |
| `ORIGINATES_FROM` | Source tradition   | Tao Te Ching ORIGINATES_FROM Taoism      |
| `TRANSLATED_FROM` | Translation source | English version TRANSLATED_FROM Sanskrit |

### Place Relationships

| Relationship      | Description            | Example                       |
| ----------------- | ---------------------- | ----------------------------- |
| `ASSOCIATED_WITH` | General association    | Temple ASSOCIATED_WITH Figure |
| `SACRED_TO`       | Sacred significance    | Bodh Gaya SACRED_TO Buddhism  |
| `LOCATED_IN`      | Geographic containment | Monastery LOCATED_IN Mountain |

### Cross-Domain Relationships

| Relationship    | Description        | Example                           |
| --------------- | ------------------ | --------------------------------- |
| `EXEMPLIFIES`   | Example of concept | Story EXEMPLIFIES Wisdom          |
| `INFLUENCED_BY` | Influence          | Sufism INFLUENCED_BY Neoplatonism |
| `RELATED_TO`    | General relation   | Concept A RELATED_TO Concept B    |

### Relationship Properties

All relationships can have these properties:

```typescript
interface BaseRelationshipProperties {
  created_at?: number; // Creation timestamp
  updated_at?: number; // Last update timestamp
  weight?: number; // Confidence/strength score (0-1)
  context?: string; // Additional context or notes
}
```

## GraphStore Interface

The `GraphStore` interface provides operations for:

### Connection Management

```typescript
await graphStore.connect();
await graphStore.disconnect();
const connected = graphStore.isConnected();
const health = await graphStore.healthCheck();
```

### Node Operations

```typescript
// Create
const node = await graphStore.createNode<TraditionProperties>('Tradition', {
  name: 'Buddhism',
  origin_region: 'India',
  time_period: '6th century BCE',
});

// Read
const node = await graphStore.getNode('node-id');
const nodes = await graphStore.getNodes(['id1', 'id2']);
const buddhism = await graphStore.queryNodes({
  type: 'Tradition',
  properties: { name: 'Buddhism' },
});

// Update
await graphStore.updateNode('node-id', { description: 'Updated' });

// Delete
await graphStore.deleteNode('node-id', { cascade: true });
```

### Relationship Operations

```typescript
// Create relationship
const rel = await graphStore.createRelationship(
  'WROTE',
  'patanjali-id',
  'yoga-sutras-id',
  { weight: 1.0, context: 'Traditional attribution' }
);

// Query relationships
const relationships = await graphStore.getNodeRelationships('node-id', {
  direction: 'outgoing',
  types: ['TAUGHT', 'WROTE'],
});

// Check connection
const connected = await graphStore.areNodesConnected(
  'buddha-id',
  'ananda-id',
  'TAUGHT'
);
```

### Graph Traversal

```typescript
// Get neighbors
const students = await graphStore.getNeighbors('teacher-id', {
  direction: 'outgoing',
  types: ['TAUGHT'],
  depth: 1,
});

// Find shortest path
const path = await graphStore.findShortestPath('concept-a-id', 'concept-b-id', {
  maxDepth: 5,
});

// Find all paths
const paths = await graphStore.findAllPaths(
  'tradition-a-id',
  'tradition-b-id',
  { maxPaths: 10 }
);

// General traversal
const subgraph = await graphStore.traverse({
  startNodeId: 'buddhism-id',
  direction: 'both',
  maxDepth: 3,
  nodeTypes: ['Concept', 'Practice', 'Figure'],
});
```

### Cypher Queries

```typescript
// Execute raw Cypher
const result = await graphStore.executeCypher({
  query: `
    MATCH (t:Tradition)-[:FOUNDED]->(f:Figure)
    WHERE t.name = $tradition
    RETURN f.name as founder
  `,
  parameters: { tradition: 'Buddhism' },
});

// Pattern matching
const matches = await graphStore.match(
  '(c:Concept)-[:DERIVES_FROM]->(t:Tradition)',
  { limit: 100 }
);
```

### Batch Operations

```typescript
// Batch create nodes
const nodes = await graphStore.batchCreateNodes([
  { type: 'Concept', properties: { name: 'Karma' } },
  { type: 'Concept', properties: { name: 'Dharma' } },
]);

// Batch create relationships
const rels = await graphStore.batchCreateRelationships([
  { type: 'ALIGNS_WITH', fromNodeId: 'karma-id', toNodeId: 'dharma-id' },
]);
```

### Statistics

```typescript
const stats = await graphStore.getStatistics();
// {
//   totalNodes: 10000,
//   totalRelationships: 50000,
//   nodesByType: { Tradition: 50, Concept: 5000, ... },
//   relationshipsByType: { TAUGHT: 1000, WROTE: 500, ... }
// }
```

## Configuration

```typescript
interface GraphStoreConfig {
  type: 'neo4j' | 'memory';
  uri?: string; // neo4j://localhost:7687
  username?: string; // neo4j
  password?: string; // password
  database?: string; // neo4j (default)
  poolSize?: number; // Connection pool size
  encrypted?: boolean; // Enable TLS
  queryTimeout?: number; // Query timeout in ms
}
```

## Environment Variables

```bash
NEO4J_URI=neo4j://localhost:7687
NEO4J_USERNAME=neo4j
NEO4J_PASSWORD=your-password
NEO4J_DATABASE=lilith
NEO4J_POOL_SIZE=50
NEO4J_ENCRYPTED=false
NEO4J_QUERY_TIMEOUT=30000
```

## Index Strategy

Recommended indexes for optimal query performance:

```cypher
// Node property indexes
CREATE INDEX tradition_name FOR (t:Tradition) ON (t.name);
CREATE INDEX text_title FOR (t:Text) ON (t.title);
CREATE INDEX concept_name FOR (c:Concept) ON (c.name);
CREATE INDEX practice_name FOR (p:Practice) ON (p.name);
CREATE INDEX figure_name FOR (f:Figure) ON (f.name);
CREATE INDEX place_name FOR (p:Place) ON (p.name);

// Full-text search indexes
CREATE FULLTEXT INDEX search_nodes FOR (n:Tradition|Text|Concept|Practice|Figure|Place)
ON EACH [n.name, n.description];

// Constraint for unique IDs
CREATE CONSTRAINT unique_node_id FOR (n:Tradition|Text|Concept|Practice|Figure|Place)
REQUIRE n.id IS UNIQUE;
```

## Common Query Patterns

### Find All Concepts in a Tradition

```cypher
MATCH (t:Tradition {name: $tradition})<-[:BELONGS_TO|DERIVES_FROM]-(c:Concept)
RETURN c
```

### Find Teaching Lineage

```cypher
MATCH path = (teacher:Figure)-[:TAUGHT*1..5]->(student:Figure)
WHERE teacher.name = $teacherName
RETURN path
```

### Cross-Tradition Concept Alignment

```cypher
MATCH (c1:Concept)-[:ALIGNS_WITH]-(c2:Concept)
MATCH (c1)-[:BELONGS_TO]->(t1:Tradition)
MATCH (c2)-[:BELONGS_TO]->(t2:Tradition)
WHERE t1 <> t2
RETURN c1, c2, t1, t2
```

### Texts Discussing a Concept

```cypher
MATCH (t:Text)-[:DISCUSSES]->(c:Concept {name: $conceptName})
RETURN t ORDER BY t.year
```

## Related Documentation

- [Vector Database Usage Patterns](./vectordb-usage-patterns.md)
- [Lilith API Overview](../../domains/lilith/api/README.md)
- [Environment Variables](./environment-variables.md)
