# Kuanyin Domain

> **Kuanyin** - Compassionate Guardianship and Ethics Platform

Kuanyin is a library-only domain implementing a Buddha Nature-aligned
contemplative moderation system. Its core philosophy is that every user carries
innate potential for wisdom, compassion, and wholesome action; moderation guides
toward wholesome expression rather than punitive suppression. The domain
provides comprehensive harm prevention, community safety, performer protection,
mindful friction patterns, rehabilitation pathways, and cross-domain ethics
integration across the entire Oshun platform.

The foundation library defines an extensive type system with 50+ harm categories
spanning interpersonal, identity, safety, integrity, exploitation, manipulation,
disruption, legal, platform, and systemic domains, each with 6-level severity
classifications.

---

## Architecture

```
              @kuanyin/foundation
        (types, constants, utilities, errors)
                    |
             @kuanyin/database
        (schemas, migrations, repos, seeds)
           /    |    |    |    \
          /     |    |    |     \
  precognition  |  community  |  performer-protection
       mindful-friction   rehabilitation
                |
       merit-karma  dharma-analytics
                |
         cross-domain
  (aphrodite, lilith, hathor, yemaya integrations)
```

`@kuanyin/foundation` is the root dependency providing all core types and the
`BuddhaNature` base interface. The database layer builds on top of it. All
feature libraries consume foundation types, and `@kuanyin/cross-domain`
integrates Kuanyin ethics across Aphrodite, Lilith, Hathor, and Yemaya domains.

---

## Libraries (10)

### `kuanyin-foundation` - Core Types and Utilities

The root library defining the entire type system for the Kuanyin domain.

**Key exports:**

- **`BuddhaNature` interface** - Base interface for all domain entities with
  fields: `compassionSeed`, `wisdomFactor`, `mindfulnessLevel`, `karmaBalance`,
  `innateGoodness`, `awakeningPotential`, `refugeStatus`
- **`RefugeStatus` type** - 5 stages: `seeking`, `taking_refuge`, `established`,
  `deepening`, `realized`
- **50+ `HarmCategoryCode` types** across 10 domains (interpersonal, identity,
  safety, integrity, exploitation, manipulation, disruption, legal, platform,
  systemic) including: targeted/repeated/sexual harassment, bullying, threats,
  racial/ethnic/religious/gender hate speech, CSAM, grooming, doxxing,
  misinformation, scams, spam, and more
- **6-level `HarmCategorySeverity`** - `negligible` through `critical`
- **`HarmCategoryDomain` classification** - 10 domains for categorizing harm
- **Constants** - Platform-wide moderation constants
- **Utilities** - Shared moderation utility functions
- **Errors** - Domain-specific error types

**Build:** `@nx/esbuild:esbuild` (ESM format, unbundled)

---

### `kuanyin-database` - Persistent Data Layer

Database schema definitions, migrations, repositories, and seed data for
persisting all Kuanyin moderation state.

**Key exports:**

- `schemas` - Database schema definitions
- `migrations` - Schema migration utilities
- `repositories` - Data access repositories
- `seeds` - Seed data for development/testing

---

### `kuanyin-precognition` - Predictive Harm Detection

6 modules for proactive harm detection before content is published.

| Module                | Description                                      |
| --------------------- | ------------------------------------------------ |
| `intent-analysis`     | Analyze user intent behind messages              |
| `emotional-detection` | Detect emotional state and distress signals      |
| `typing-dynamics`     | Analyze typing patterns for emotional escalation |
| `behavioral-patterns` | Track behavioral patterns over time              |
| `context-awareness`   | Contextual understanding of conversations        |
| `cascade-prediction`  | Predict harmful cascade effects                  |

This library enables the platform to intervene mindfully _before_ harm occurs by
analyzing intent, emotional signals, and behavioral patterns in real time.

---

### `kuanyin-community-harmony` - Community Health

5 modules for maintaining healthy community dynamics.

| Module                  | Description                                         |
| ----------------------- | --------------------------------------------------- |
| `temperature-monitor`   | Track community emotional temperature               |
| `conflict-detection`    | Detect emerging conflicts between users             |
| `raid-defense`          | Defense against coordinated harassment raids        |
| `post-incident-healing` | Community healing after harmful events              |
| `culture-cultivation`   | Proactive cultivation of positive community culture |

---

### `kuanyin-mindful-friction` - Intentional Friction Patterns

6 modules implementing mindful friction that slows harmful actions without being
punitive, giving users space to reconsider.

| Module                   | Description                                      |
| ------------------------ | ------------------------------------------------ |
| `pause-breathe`          | Pause-and-breathe interventions before posting   |
| `samma-vaca`             | Right Speech (Buddhist framework) gentle prompts |
| `cognitive-reframing`    | Help users reframe harmful thoughts              |
| `perspective-shift`      | Encourage perspective-taking before responding   |
| `compassion-nudges`      | Compassion-based nudges toward kindness          |
| `alternative-expression` | Suggest alternative ways to express frustration  |

The `samma-vaca` module is named after the Pali term for Right Speech from the
Noble Eightfold Path, reflecting the domain's Buddhist-informed design.

---

### `kuanyin-performer-protection` - Creator and Performer Safety

6 modules for protecting content creators and performers from harassment,
parasocial behavior, and exploitation.

| Module                     | Description                                            |
| -------------------------- | ------------------------------------------------------ |
| `real-time-shield`         | Real-time content and chat filtering for performers    |
| `parasocial-detection`     | Detect unhealthy parasocial attachment patterns        |
| `boundary-enforcement`     | Enforce performer-defined interaction boundaries       |
| `ncii-deepfake-protection` | Non-consensual intimate imagery and deepfake detection |
| `performer-wellness`       | Performer mental health and wellness monitoring        |
| `performer-dashboard`      | Analytics dashboard for performer safety metrics       |

---

### `kuanyin-rehabilitation` - Rehabilitation Pathways

6 modules providing paths back for users who have committed violations,
emphasizing rehabilitation over permanent punishment.

| Module                    | Description                                   |
| ------------------------- | --------------------------------------------- |
| `shadow-work-journeys`    | Guided self-reflection journeys for violators |
| `journey-progress`        | Track rehabilitation journey progress         |
| `empathy-training`        | Structured empathy-building exercises         |
| `restorative-circles`     | Facilitated restorative justice conversations |
| `accountability-tracking` | Track accountability commitments              |
| `reintegration-pathways`  | Gradual reintegration into community          |

---

### `kuanyin-merit-karma` - Merit and Karma Systems

5 modules for tracking positive contributions and platform reputation.

| Module               | Description                                       |
| -------------------- | ------------------------------------------------- |
| `merit-accumulation` | Track merit earned through positive actions       |
| `merit-calculation`  | Calculate merit scores across activities          |
| `privilege-tiers`    | Merit-based privilege tiers and access levels     |
| `karma-visibility`   | Karma visibility and transparency controls        |
| `achievement-system` | Achievements for positive community participation |

---

### `kuanyin-dharma-analytics` - Spiritual and Community Metrics

5 modules for analytics on community health and individual dharma paths.

| Module                     | Description                                |
| -------------------------- | ------------------------------------------ |
| `community-health-metrics` | Aggregate community health dashboards      |
| `individual-dharma-path`   | Per-user dharma path and growth tracking   |
| `predictive-wellness`      | Predictive models for community wellness   |
| `wisdom-reports`           | Generated wisdom reports and insights      |
| `moderation-transparency`  | Transparency reports on moderation actions |

---

### `kuanyin-cross-domain` - Cross-Domain Ethics Integration

5 modules that integrate Kuanyin's ethics and moderation capabilities across the
entire Oshun platform.

| Module                      | Description                                                         |
| --------------------------- | ------------------------------------------------------------------- |
| `aphrodite-integration`     | Ethics integration with Aphrodite (relationships/dating) domain     |
| `lilith-integration`        | Ethics integration with Lilith (consciousness/adult content) domain |
| `hathor-integration`        | Ethics integration with Hathor (worldbuilding) domain               |
| `yemaya-integration`        | Ethics integration with Yemaya (creative studio) domain             |
| `platform-wide-integration` | Platform-wide ethical framework and policy enforcement              |

This library ensures consistent ethical standards across all Oshun domains, with
domain-specific adaptations for each platform's unique content and interaction
patterns.

---

## Technology Stack

| Layer              | Technology                                     |
| ------------------ | ---------------------------------------------- |
| Language           | TypeScript (ESM)                               |
| Build (foundation) | `@nx/esbuild:esbuild` (ESM format, unbundled)  |
| Build (others)     | `@nx/js:tsc`                                   |
| Testing            | Vitest (per-library configs)                   |
| Type checking      | Explicit `typecheck` target via `tsc --noEmit` |

The foundation library uses esbuild for ESM output, which provides faster
builds. All other libraries use the standard tsc build.

---

## Configuration

**Project tags:** `["scope:kuanyin", "layer:domain"]`

**Build executors:**

- `kuanyin-foundation`: `@nx/esbuild:esbuild`
- All others: `@nx/js:tsc`

**Targets:** All libraries include `build`, `lint`, `test`, and `typecheck`
targets.

---

## Design Philosophy

The domain is designed around Buddhist principles:

1. **Buddha Nature** - Every entity carries innate goodness and potential for
   awakening. The `BuddhaNature` interface encodes this as numeric properties.
2. **Right Speech (Samma Vaca)** - Mindful friction patterns draw from the Noble
   Eightfold Path.
3. **Compassionate Guardianship** - Moderation guides rather than punishes.
4. **Rehabilitation over Punishment** - Shadow work journeys, restorative
   circles, and reintegration pathways offer paths back.
5. **Precognition over Reaction** - Proactive detection of harmful intent before
   harm occurs.

---

## Development

```bash
# Test foundation
pnpm nx test kuanyin-foundation

# Build foundation
pnpm nx build kuanyin-foundation

# Typecheck foundation
pnpm nx typecheck kuanyin-foundation

# Run all kuanyin tests
pnpm nx run-many --target=test --projects=tag:scope:kuanyin

# Build all kuanyin libraries
pnpm nx run-many --target=build --projects=tag:scope:kuanyin
```

---

## Related Domains

- **Arete** - Personal development domain with complementary wellness features
- **Aphrodite** - Relationships/dating domain receiving ethics integration
- **Lilith** - Consciousness/content domain receiving performer protection
- **Hathor** - Worldbuilding domain receiving content moderation
- **Yemaya** - Creative studio domain receiving safety features
