# Kuanyin Domain — Architecture

> Named after Guanyin (觀音), the Bodhisattva of Compassion in East Asian
> Buddhist traditions — a guardian who remains accessible to guide all beings
> toward liberation rather than entering solitary nirvana.

---

## Overview

Kuanyin is the platform-wide ethics, safety, and moderation domain for the
entire Oshun ecosystem. Unlike a traditional content-moderation service that
focuses on detection and punishment, Kuanyin is designed as a **compassion-first
guidance system** grounded in Buddhist philosophy: every user carries innate
potential for wisdom and wholesome action, and the system's job is to create
conditions for that potential to flourish.

The domain is implemented as **14 TypeScript libraries with no standalone
applications or services**. Consuming applications — Lilith, Aphrodite, Hathor,
Yemaya, and the broader platform — embed these libraries directly. This
library-only design means Kuanyin's moderation logic runs in-process inside the
host application, with no extra network hop for every moderation decision.

The architecture reflects the full lifecycle of harm: **prevention** before
content is posted (precognition), **intervention** during posting (mindful
friction), **community healing** after an incident (community harmony), and
**restoration** of the violating user to full participation (rehabilitation) —
with a positive-reinforcement layer (merit and karma) running in parallel to
reward wholesome behavior throughout.

---

## Domain Architecture

The diagram below shows how the 14 libraries are organized into horizontal
layers, from the foundation at the bottom to the cross-domain ethics surface at
the top. Data and behavior flow upward: consuming applications use the SDK/API
or cross-domain integration layer and rely on the feature libraries, which in
turn draw on the persistence and foundation layers.

```
+───────────────────────────────────────────────────────────────────────────+
│                      CROSS-DOMAIN ETHICS LAYER                           │
│                       kuanyin-cross-domain                               │
│   (aphrodite, lilith, hathor, yemaya, platform-wide integrations)        │
+───────────────────────────────────────────────────────────────────────────+
                                    |
+───────────────────────────────────────────────────────────────────────────+
│                       INTELLIGENCE AND ANALYTICS                         │
│                                                                          │
│   kuanyin-ai-ml-models          kuanyin-dharma-analytics                 │
│   (classifiers, analyzers,      (community health, individual paths,     │
│    predictors, generators)       predictive wellness, wisdom reports)    │
+───────────────────────────────────────────────────────────────────────────+
                                    |
+───────────────────────────────────────────────────────────────────────────+
│                          FEATURE LIBRARIES                               │
│                                                                          │
│  PREVENTIVE                  REACTIVE                 RESTORATIVE        │
│  kuanyin-precognition        kuanyin-mindful-friction  kuanyin-rehabilitation │
│  (intent analysis,           (pause/breathe, samma-   (shadow work,     │
│   emotional detection,        vaca, reframing,          empathy training, │
│   typing dynamics,            perspective shift,         restorative     │
│   behavioral patterns,        compassion nudges,         circles,        │
│   context awareness,          alt. expression)           reintegration)  │
│   cascade prediction)                                                    │
│                                                                          │
│  COMMUNITY                   CREATOR PROTECTION       REPUTATION         │
│  kuanyin-community-harmony   kuanyin-performer-        kuanyin-merit-karma │
│  (temperature, conflict,      protection               (accumulation,    │
│   raid defense, healing,      (shield, parasocial,     privilege tiers,  │
│   culture cultivation)        NCII/deepfake,           karma, achievements) │
│                               wellness, dashboard)                      │
+───────────────────────────────────────────────────────────────────────────+
                                    |
+───────────────────────────────────────────────────────────────────────────+
│                       RESTORATIVE INTEGRATION                            │
│                   kuanyin-concordia-restorative                          │
│    (restorative-circle safety pre-flight checklist, Phase 179.7.3)       │
+───────────────────────────────────────────────────────────────────────────+
                                    |
+───────────────────────────────────────────────────────────────────────────+
│                         PERSISTENCE LAYER                                │
│                         kuanyin-database                                 │
│    (25 table schemas, migrations, 15 repositories, seed data)            │
+───────────────────────────────────────────────────────────────────────────+
                                    |
+───────────────────────────────────────────────────────────────────────────+
│                          FOUNDATION LAYER                                │
│                         kuanyin-foundation                               │
│    (BuddhaNature interface, 74 harm categories, six-level severity,      │
│     constants, utilities, error types, environment schema)               │
+───────────────────────────────────────────────────────────────────────────+
```

---

## Library Organization

Kuanyin's 14 libraries fall into six roles: a shared foundation that everything
else imports, a persistence layer, eight feature libraries that implement
distinct behavioral concerns, two intelligence libraries, a public API surface,
a UI component library, and a restorative-circle adapter.

### Foundation: `kuanyin-foundation`

The conceptual root of all Kuanyin libraries. Because every other library
imports from it, `kuanyin-foundation` is built with `@nx/esbuild:esbuild` (ESM,
`bundle: false`) for the fastest possible rebuild times.

Key exports:

- **`BuddhaNature` interface** — The philosophical core: numeric properties
  modeling a user's compassion, wisdom, mindfulness, karma, goodness, and
  awakening potential, plus identity and timestamp fields.
- **`RefugeStatus`** — Five-stage spiritual progress model
  (`seeking → taking_refuge → established → deepening → realized`) that tracks a
  user's engagement journey through the platform.
- **`HarmCategoryCode`** — A 74-code harm taxonomy organized across 10 domains
  (interpersonal, identity, safety, integrity, exploitation, manipulation,
  disruption, legal, platform, systemic).
- **`HarmCategorySeverity`** — Six-level scale
  (`negligible → low → moderate → high → severe → critical`) that determines
  which intervention systems activate.
- **`HarmCategoryDomain`** — The ten harm domains listed above.
- **Constants** — Ten configuration stores covering thresholds, timing, merit
  points, rehabilitation durations, performer protection, trust and community
  health, escalation, shadow work, karma decay, and comprehensive moderation
  settings.
- **Utilities** — Twelve lookup stores and 21 pure analysis functions covering
  everything from harm-potential scoring to restorative-circle scheduling.
- **Errors** — Domain-specific error hierarchy, a self-contained validation
  system, input sanitizers, and resilience primitives (rate limiter, circuit
  breaker, degradation handler).
- **Env schema** — 30 typed `KUANYIN_*` environment variables validated at
  startup.

### Persistence: `kuanyin-database`

Provides the data layer: 25 table schemas (all `kuanyin_`-prefixed), migration
metadata, 15 typed repository classes, and development seed data. The schemas
are modelled as `readonly` TypeScript interfaces backed by in-memory `Map`
stores with snapshot-based reset; the migration SQL describes the
PostgreSQL-backed deployment (a live database service is not wired up in this
tree).

### Feature Libraries

Eight libraries, each implementing a distinct stage in Kuanyin's compassionate
moderation lifecycle:

| Library                        | Lifecycle Stage       | Function                                    |
| ------------------------------ | --------------------- | ------------------------------------------- |
| `kuanyin-precognition`         | Preventive            | Detect harm before it occurs                |
| `kuanyin-mindful-friction`     | Preventive/Corrective | Slow and redirect potential harm            |
| `kuanyin-community-harmony`    | Reactive/Preventive   | Manage community health and conflict        |
| `kuanyin-performer-protection` | Reactive/Preventive   | Protect content creators                    |
| `kuanyin-rehabilitation`       | Restorative           | Guide violators toward wholesome engagement |
| `kuanyin-merit-karma`          | Reinforcement         | Reward positive behavior                    |
| `kuanyin-dharma-analytics`     | Measurement           | Measure community and individual health     |
| `kuanyin-cross-domain`         | Integration           | Extend ethics across other domains          |

### Intelligence: `kuanyin-ai-ml-models`

Provides interfaces and implementations for the AI/ML models that power
precognition, harm classification, and friction content generation. The
intelligence layer is deliberately decoupled from the feature libraries: model
implementations can be swapped (local model → external API → fine-tuned model)
without touching any feature library code.

### Public Surface: `kuanyin-sdk-api`

The unified public API for consuming applications. Provides the
`createKuanyinClient()` factory that applications use to integrate Kuanyin into
their service. Abstracts the internal library structure behind a clean, stable
API surface offering REST endpoints, a GraphQL layer, a TypeScript SDK, and a
typed event system.

### UI: `kuanyin-ui-components`

Reusable UI component descriptors — not React components themselves, but typed
configuration objects — for moderation interfaces: performer dashboards,
community health displays, rehabilitation journey progress, and moderation
transparency reports. Platform teams render these descriptors in their own
component framework.

### Restorative: `kuanyin-concordia-restorative`

The restorative-circle safety pre-flight adapter (Phase 179.7.3). It is the only
Kuanyin library built with `@nx/js:tsc` and the only one with runtime
dependencies (`zod`, `@concordia/contracts`). Its `circle-safety` module defines
seven circle kinds, eleven safety checks, the required-checks map per kind, and
the `canOpenCircle` decision that keeps a circle closed until every required
check has passed.

---

## Dependency Model

The layering below is **conceptual**, not a runtime import graph. In the current
code every Kuanyin library except `concordia-restorative` is self-contained:
each module re-declares the literal-union types and config shapes it needs and
ships its own in-memory `Map` stores, with no cross-library `@kuanyin/*`
imports. `concordia-restorative` is the only library with runtime dependencies
(`zod`, `@concordia/contracts`).

```
                          conceptual layering
─────────────────────────────────────────────────────────────────────
  cross-domain ───────────────────────── platform-wide ethics surface
  sdk-api ─────────────────────────────── REST/GraphQL/event/SDK surface
  ai-ml-models · dharma-analytics ─────── intelligence & analytics
  precognition · mindful-friction ·
  community-harmony · performer-protection ·
  rehabilitation · merit-karma ────────── feature libraries
  concordia-restorative ───────────────── restorative-circle pre-flight
  database ────────────────────────────── persistence schemas
  foundation ──────────────────────────── shared taxonomy & primitives
```

Each library is built and tested independently. `ui-components` provides UI
configuration descriptors that mirror the foundation and feature-library
taxonomies.

---

## Design Patterns

Understanding these six architectural decisions will help you reason about why
the libraries are shaped the way they are.

### 1. Compassion-First Architecture

Every design decision in Kuanyin follows a harm-response hierarchy that
prioritizes prevention over punishment:

1. **Precognition** — Can harm be prevented before it occurs?
2. **Mindful Friction** — If not, can the user be guided away from harm before
   posting?
3. **Community Harmony** — If harm occurred, how can the community heal?
4. **Rehabilitation** — How can the violating user be guided toward wholesome
   engagement?
5. **Merit/Karma** — What positive behaviors should be reinforced in parallel?

This ordering reflects the Buddhist principle of preventing harm (ahimsa) as
more valuable than punishing it after the fact.

### 2. Non-Blocking Friction

All friction patterns in `kuanyin-mindful-friction` implement a core
architectural principle: **friction slows but never blocks**. After a pause,
after a Right Speech prompt, after a rewrite suggestion — the user can always
proceed with their original content. This is both a philosophical and a legal
design choice:

- **Philosophically:** forcing a pause respects autonomy while creating space
  for reflection.
- **Legally:** blocking speech without a clear terms violation creates
  liability; friction creates documented evidence that the user had an
  opportunity to reconsider.

### 3. esbuild ESM Builds

All Kuanyin libraries except `concordia-restorative` build with the
`@nx/esbuild:esbuild` executor (ESM format, `bundle: false`) for fast, unbundled
output. The libraries are predominantly self-contained pure TypeScript — types,
constants, in-memory stores, and pure functions — which suits esbuild well.
`concordia-restorative` is the exception: it builds with `@nx/js:tsc` because it
depends on `zod` and `@concordia/contracts`, which require TypeScript's
declaration-emit for workspace interop.

### 4. Domain-Specific Integration Modules

Rather than requiring consuming domains to adapt to a generic moderation API,
`kuanyin-cross-domain` provides domain-specific integration modules. The
`lilith-integration` module is calibrated for adult content creator contexts.
The `aphrodite-integration` module understands relationship and dating
interaction patterns. Each module applies the same underlying Kuanyin
capabilities with domain-appropriate thresholds and terminology — a hate-raid in
a live streaming context is handled differently from consent coercion in a
dating app, even though both route through the same underlying harm taxonomy.

### 5. Immutable Karma Ledger

The karma and merit system uses an append-only event ledger rather than mutable
scores. A user's current karma is always computed by summing the event ledger,
never by reading a stored value. This design provides:

- Complete auditability of all karma changes, supporting dispute resolution.
- Ability to replay the karma ledger to reconstruct any historical state.
- Transparency to users about exactly what affected their karma and when.
- No possibility of silent karma manipulation — every change leaves a record.

### 6. Severity-Gated Interventions

The intervention pipeline is gated by harm severity, so that the volume of
low-severity events does not overwhelm the systems designed for high-severity
ones:

- **Negligible** detections log only — no user-visible action.
- **Low** severity triggers soft friction — a brief pause.
- **Critical** severity (CSAM, imminent violence, terrorism) triggers immediate
  removal and emergency escalation, bypassing all queues.

This gate-based design ensures human review resources are reserved for the cases
that need them, and that the most severe harms are never held in a queue.

---

## Technology Stack

The table below summarizes the technology choices and the rationale for each
component.

| Component                     | Technology                                                    |
| ----------------------------- | ------------------------------------------------------------- |
| Language                      | TypeScript (ESM, strict mode)                                 |
| Build (most libs)             | `@nx/esbuild:esbuild` — ESM format, `bundle: false`           |
| Build (concordia-restorative) | `@nx/js:tsc`                                                  |
| Testing                       | Vitest via the `@nx/vite:test` executor (per-library configs) |
| Type checking                 | Explicit `typecheck` target via `tsc --noEmit`                |
| Database                      | PostgreSQL (via `kuanyin-database`)                           |
| AI inference                  | Anthropic Claude (via `kuanyin-ai-ml-models`)                 |
| Target environments           | Node.js (server) + browser-compatible (foundation, UI)        |

All libraries define four Nx targets: `build`, `lint`, `test`, `typecheck`.

---

## Build and Development

The commands below cover the most common development tasks. Because Nx can fail
in worktree environments with duplicate project names, the worktree-safe
alternatives are listed alongside the standard Nx commands.

```bash
# Test a specific library
pnpm nx test kuanyin-foundation
pnpm nx test kuanyin-precognition

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

# Typecheck
pnpm nx typecheck kuanyin-foundation

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

# Worktree-safe type check (use when Nx reports duplicate projects)
cd libs/kuanyin/foundation && npx tsc --noEmit
```

---

## Service Topology

Kuanyin has no standalone services. It is a **pure library domain**.

The domain requires PostgreSQL for persistence (via `kuanyin-database`).
Consuming applications provision this database and pass the connection string
through the `KUANYIN_DATABASE_URL` environment variable. There is no
Kuanyin-specific HTTP server, event bus, or background worker — real-time
capabilities, if needed, are implemented by the consuming application using the
`kuanyin-sdk-api` client.

---

## Cross-Domain Integration

Kuanyin integrates with the rest of the Oshun platform through
`kuanyin-cross-domain`. Each integration module is domain-specific rather than
generic, because different domains have fundamentally different risk profiles
and community norms. The boundary exists because Kuanyin owns the ethics
taxonomy and intervention logic, while each domain owns its own content model
and user relationships. What crosses the boundary is context: harm scores,
severity assessments, intervention triggers, and behavioral patterns — not raw
content.

| Domain                               | Integration Module      | Key Concern                                                                       |
| ------------------------------------ | ----------------------- | --------------------------------------------------------------------------------- |
| **Aphrodite** (relationships/dating) | `aphrodite-integration` | Consent enforcement, exploitation detection, relationship boundary support        |
| **Lilith** (consciousness/content)   | `lilith-integration`    | Performer protection for adult content, age verification support, NCII protection |
| **Hathor** (worldbuilding)           | `hathor-integration`    | Dark creative content policies, fictional violence vs. genuine harm distinction   |
| **Yemaya** (creative studio)         | `yemaya-integration`    | Creator harassment, collaborative workspace conflicts, IP disputes                |

The `platform-wide-integration` module ensures cross-domain behavioral
correlation: harm patterns detected in one domain are visible when evaluating
behavior in another. A user with a harassment pattern in Yemaya carries that
context into their Aphrodite interactions — users cannot reset their moderation
history simply by switching to a different part of the platform.

---

## Domain Boundaries

Understanding what Kuanyin owns — and explicitly does not own — prevents
accidental duplication and keeps integrations clean.

**Kuanyin provides:**

- Platform-wide harm classification and severity assessment (74-category
  taxonomy across 10 domains)
- Predictive harm detection (precognition) before content is posted
- Mindful friction intervention patterns that slow but never block expression
- Community health monitoring and conflict resolution
- Performer and creator protection systems including NCII and deepfake defense
- Rehabilitation and restorative justice pathways
- Merit, karma, and achievement systems
- Dharma analytics and transparency reporting
- Domain-specific ethics integration for Aphrodite, Lilith, Hathor, and Yemaya

**Kuanyin does not provide:**

- Content delivery infrastructure (delegated to each domain's media system)
- Authentication or access control (delegated to consuming applications via
  `@oshun/auth`)
- Legal enforcement or law enforcement reporting (consuming applications are
  responsible for this)
- General user management (delegated to consuming applications)
- News fact-checking (Veritas domain)
- Governance and IP compliance (Themis domain)
- The broader Concordia restorative-mediation flow beyond the safety pre-flight
  checklist — full apology, restitution, and reintegration mediation remain
  planned (Phase 179)
