# Kuan Yin — Architecture Overview

> Technical doc 32.16.1.1. Companion to the user guides (`../user/`) and the
> philosophical framework (`../philosophical/`).

Kuan Yin is the compassionate-guardianship platform for the Oshun monorepo. It
replaces punitive moderation with a **precognition → friction → protection →
rehabilitation → merit** loop: harmful intent is surfaced before it manifests,
gentle friction gives the author a chance to choose differently, vulnerable
users (especially performers) are shielded, those who cause harm are guided
toward repair, and prosocial behaviour accrues durable reputation.

## Layered architecture

The domain is an Nx library cluster under `libs/kuanyin/`. Every library is a
pure TypeScript package (`@kuanyin/*`) with strict typing, exhaustive unit
tests, and **no runtime side effects** beyond in-memory stores — the engines are
deterministic functions over explicit inputs, which makes them testable,
portable to the edge, and safe to compose.

```
            ┌──────────────────────────────────────────────┐
   clients  │  sdk-api  (TS SDK · REST · GraphQL · events)  │
            └───────────────┬──────────────────────────────┘
                            │
            ┌───────────────▼──────────────────────────────┐
 behaviour  │  precognition  mindful-friction               │
  engines   │  performer-protection  rehabilitation          │
            │  merit-karma  community-harmony                │
            │  dharma-analytics  cross-domain  ai-ml-models  │
            └───────────────┬──────────────────────────────┘
                            │
            ┌───────────────▼──────────────────────────────┐
   core     │  foundation (types/constants/utilities/errors)│
            │  database  (schemas · migrations · repos)     │
            └──────────────────────────────────────────────┘
```

### Core layer

| Library      | Package               | Responsibility                                                                                                                                 |
| ------------ | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `foundation` | `@kuanyin/foundation` | `BuddhaNature` base types, 50+ `HarmCategory`, intervention rules, the 20 orchestration utilities, error hierarchy, Zod validation, env schema |
| `database`   | `@kuanyin/database`   | Schemas (25 tables), migrations + indexes, repository classes, seeds                                                                           |

`foundation/src/utilities.ts` holds the **orchestration layer** — the 20
cross-cutting functions (`calculateHarmPotential`, `assessEmotionalState`,
`determineIntervention`, `calculateMerit`, `assessTrustScore`,
`predictCascadeRisk`, `matchSammaVacaGate`, `detectCognitiveDistortion`,
`suggestReframe`, `calculateRehabilitationProgress`, `assessCommunityHealth`,
`determineProtectionLevel`, `matchBehaviorPattern`, `generateMindfulPrompt`,
`calculateParasocialRisk`, `assessPerformerRisk`, `trackAccountability`,
`scheduleRestorativeCircle`, `generateDharmaReport`,
`validateEthicalCompliance`). These are the seams every higher engine composes
against.

### Behaviour engines

| Library                | What it decides                                                                                                                                                                                                                                             |
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `precognition`         | Primary/secondary intent, emotional arousal-valence, typing dynamics, behavioural patterns, context, cascade risk                                                                                                                                           |
| `mindful-friction`     | Pause-and-breathe overlays, Samma Vaca gates, cognitive reframing, perspective shifts, compassion nudges, alternative expression                                                                                                                            |
| `performer-protection` | Real-time shield, parasocial detection, boundary enforcement, NCII/deepfake protection, wellness, dashboard                                                                                                                                                 |
| `rehabilitation`       | Shadow-work journeys, journey progress, empathy training, restorative circles, accountability, reintegration                                                                                                                                                |
| `merit-karma`          | Merit accumulation/calculation, privilege tiers, karma visibility, achievements                                                                                                                                                                             |
| `community-harmony`    | Temperature monitor, conflict detection, raid defense, post-incident healing, culture cultivation                                                                                                                                                           |
| `dharma-analytics`     | Community-health metrics, individual dharma path, predictive wellness, wisdom reports, transparency, plus the §32.18/§32.19 SOTA modules (privacy, fairness, multimodal, NLP, realtime, federated, threat detection, crisis intervention, deepfake, CBT, …) |
| `cross-domain`         | Integrations with Aphrodite, Lilith, Hathor, Yemaya, and platform-wide reputation                                                                                                                                                                           |
| `ai-ml-models`         | Model specs/evaluation harness wiring for the six model families                                                                                                                                                                                            |

### Client surface

`sdk-api` exposes the engines four ways: a typed TypeScript SDK
(`sdkImplement*`/`sdkCreate*` client builders, auth, retry, rate-limit, webhook,
realtime), 20 REST endpoints (`/v1/analyze-intent` … `/v1/realtime`), a GraphQL
schema with query/mutation/subscription resolvers, and a domain event catalog
(`evtDefine*`/`evtCreate*`, event bus, replay).

## Request lifecycle (mindful-friction path)

1. **Precognition** classifies intent (`classifyPrimaryIntent`) and emotional
   state (`detectArousalLevel`, `classifyValence`, `detectCrisisState`).
2. **Foundation** scores harm (`calculateHarmPotential`), assesses emotion
   (`assessEmotionalState`), and selects an intervention
   (`determineIntervention`) from the seeded rule table.
3. **Mindful friction** renders the chosen intervention — a breathing pause, a
   Samma Vaca gate (`matchSammaVacaGate`), a cognitive reframe, or a perspective
   shift — and verifies completion.
4. On harm to a vulnerable target, **performer-protection** raises a shield
   (`determineProtectionLevel` →
   `performer_shield`/`minor_shield`/`crisis_shield`) and the content never
   reaches the target.
5. Repair flows into **rehabilitation** (journeys, circles, accountability) and
   prosocial behaviour into **merit-karma**.

## Cross-cutting concerns

- **Determinism**: no `Date.now()`-dependent logic in scoring; randomness, where
  needed (federated DP noise), uses seeded PRNGs.
- **Privacy by design**: typing analysis reduces to features on-device, content
  analysis is ephemeral (hash fingerprint, no retention), aggregates use
  k-anonymity + differential privacy (`dharma-analytics/privacy-protection`).
- **Human-in-the-loop**: irreversible actions (bans, terminations) are gated by
  `requireHumanReviewForBan`; crises route to humans via `escalateCrisis`.
- **Fairness**: every model is gated through `@kuanyin/evaluation` (demographic
  parity, equalized odds, four-fifths rule) before it touches a person.

See `02-api-reference.md` for the surface, `04-database-schema.md` for
persistence, and `../philosophical/` for the design rationale behind each loop.
