# Kuanyin — Systems Deep Dive

> The `libs/kuanyin/` area: sixteen Nx libraries implementing **Kuan Yin**, the
> compassionate-guardianship moderation domain — intent precognition, mindful
> friction, performer protection, restorative rehabilitation, and merit/karma —
> as deterministic, dependency-free TypeScript.

## What this area is

Kuan Yin (觀音, the Bodhisattva of Compassion) is Oshun's **Phase-32**
contemplative-moderation domain: a deliberate inversion of punitive enforcement
toward what `libs/kuanyin/README.md` calls "transformative guardianship" —
intercept harmful intent before it manifests, turn moments of harm into growth,
protect vulnerable members (especially performers), and guide harm-doers through
rehabilitation. The whole area is built on a small set of shared philosophical
primitives that recur in the code: `BuddhaNature` (every entity carries innate
`compassionSeed` / `wisdomFactor` / `karmaBalance`, in
`libs/kuanyin/foundation/src/types.ts`), Samma Vaca right-speech gates, and
restorative-justice flows.

Structurally the area is sixteen separate Nx libraries, every one tagged
`scope:kuanyin` + `layer:domain`. Fifteen of them share one very consistent
engineering style, stated almost verbatim in their module headers: **"10 stores
with 7 items each, snapshot-based reset. Pure TypeScript, no external deps."**
That is, each library is a set of domain modules that compute real scores and
decisions from caller-supplied inputs over `Map`-backed in-memory stores, with a
`reset*Store()` seam for test isolation — deterministic functions, no network,
no I/O, no randomness in the result path (the only `Math.random()` is in
non-secret id suffixes, annotated as such). The implementations are
domain-specific, not CRUD: harm-potential weighting, sigmoid cascade models,
linear-regression trend detection, fairness/drift metrics, HPA replica formulas,
and so on. The sixteenth library, `@kuanyin/concordia-restorative`, is the
outlier — a small, Zod-schema-based Phase-179 module rather than a Phase-32
in-memory engine.

The libraries form a rough stack. `kuanyin-foundation` sits at the bottom
(shared types, constants, errors, env schema). `kuanyin-database` holds typed
schema + in-memory repository representations. On top sit the behavioural
engines — `kuanyin-precognition`, `kuanyin-mindful-friction`,
`kuanyin-performer-protection`, `kuanyin-rehabilitation`, `kuanyin-merit-karma`,
`kuanyin-community-harmony`, `kuanyin-ai-ml-models`, and the large
`kuanyin-dharma-analytics`. Then the surface/operational tier:
`kuanyin-sdk-api`, `kuanyin-ui-components`, `kuanyin-cross-domain`,
`kuanyin-deployment`, and the `kuanyin-evaluation` quality harness.

## How it fits the wider system

These are domain libraries, not a running service: the engines are pure
functions a Kuan Yin service (or the BFF) would call to score a message, gate a
post, route a crisis, or advance a rehabilitation journey. `kuanyin-sdk-api`
describes the REST/GraphQL/event/SDK surface those engines would be exposed
through; `kuanyin-ui-components` provides headless (framework-agnostic) data and
state models for the dashboards and friction UIs that render the results; and
`kuanyin-cross-domain` is the explicit boundary layer that integrates Kuan Yin's
moderation with other Oshun domains (Lilith, Yemaya, Hathor, Aphrodite, and a
platform-wide layer). Because the engines take inputs and return computed
verdicts with no side effects, the same module can be reused identically on a
server, in a worker, or in tests. `kuanyin-evaluation` is the gate that keeps
the models honest before they "touch a person."

## Entity reference

### kuanyin-foundation

The bottom of the stack (`libs/kuanyin/foundation/src`): shared types,
constants, utilities, errors, and an env schema, re-exported from `index.ts`.
`types.ts` defines the `BuddhaNature` root interface every entity derives from
and a 50+-code `HarmCategoryCode` taxonomy with severity/domain unions;
`constants.ts` holds the configuration stores (e.g. `HarmCategoryThreshold`
score floors/ceilings, escalation and appeal-window rules) as `Map`-backed
registries with register/get/getAll + snapshot reset. It is self-contained ("no
external imports") and is the vocabulary the rest of the area speaks.

### kuanyin-database

Typed persistence layer for the domain (`libs/kuanyin/database/src`).
`schemas.ts` carries TypeScript representations of ~25 table schemas (user
profiles, merit ledgers, intervention records, rehabilitation journeys,
restorative circles, …); `repositories.ts` provides ~15 repository classes with
CRUD plus specialized query methods; `migrations.ts` and `seeds.ts` round it
out. Honest scope: the header describes this as "Prisma Schema Design" but the
runtime is **`Map`-based in-memory stores**, not a live Prisma client — it
models the schema and repository contracts in pure TypeScript rather than
talking to Postgres.

### kuanyin-precognition

The intent-precognition engine (`libs/kuanyin/precognition/src`): six modules —
`intent-analysis`, `emotional-detection`, `typing-dynamics`,
`behavioral-patterns`, `context-awareness`, and `cascade-prediction`. These
score the _likelihood and shape of harm before a message is sent_; e.g.
`cascade-prediction.ts` (Phase 32.3.6) implements 15 functions for reply-chain
escalation, dogpiling, viral spread, network-effect and intervention-point
analysis using helpers like `sigmoid()` and keyword-match counting over
normalized text. Deterministic, ~300 top-level exports, Pure-TS in-memory
stores.

### kuanyin-mindful-friction

The "pause before harm" intervention layer
(`libs/kuanyin/mindful-friction/src`): `pause-breathe`, `samma-vaca`,
`cognitive-reframing`, `perspective-shift`, `compassion-nudges`, and
`alternative-expression`. `samma-vaca.ts` (Phase 32.4.2) implements the Buddhist
Right-Speech gates — truth / necessity / kindness evaluation, sequential gate
processing, reflection-question selection, fatigue/bypass prevention — with real
statistics helpers (`standardDeviation`, `linearRegression`) rather than
thresholds-only logic. Pure-TS, deterministic.

### kuanyin-performer-protection

Protection for creators/performers (`libs/kuanyin/performer-protection/src`):
`real-time-shield`, `parasocial-detection`, `boundary-enforcement`,
`ncii-deepfake-protection`, `performer-wellness`, and `performer-dashboard`.
`ncii-deepfake-protection.ts` (Phase 32.5.4) models 15 protection functions —
StopNCII/PhotoDNA-style hash integration, face-registry, synthetic-media /
face-swap / voice-clone detection, automated takedowns, evidence preservation,
and a hash-sharing network — as typed, deterministic logic over in-memory
stores. The external services are modelled, not live-integrated.

### kuanyin-rehabilitation

The restorative-justice / growth-journey engine
(`libs/kuanyin/rehabilitation/src`): `shadow-work-journeys`, `journey-progress`,
`empathy-training`, `restorative-circles`, `accountability-tracking`, and
`reintegration-pathways`. `shadow-work-journeys.ts` (Phase 32.7.1) implements 20
functions for therapeutic, growth-oriented exploration of harmful-behaviour root
causes, with weighted-mean scoring and the standard snapshot-reset store
pattern. Pure-TS, deterministic; ~214 top-level exports.

### kuanyin-merit-karma

The merit/karma reputation engine (`libs/kuanyin/merit-karma/src`):
`merit-accumulation`, `merit-calculation`, `privilege-tiers`,
`karma-visibility`, and `achievement-system`. `merit-calculation.ts` (Phase
32.8.2) is a real scoring engine — weighted scoring, context multipliers,
anti-gaming/inflation detection, peer validation, decay/recovery, and an
explicit transfer-prohibition — built on `calcWeightedMean`/`calcNormalizeScore`
helpers over in-memory stores. Deterministic, no external deps.

### kuanyin-community-harmony

Community-level health and de-escalation (`libs/kuanyin/community-harmony/src`):
`temperature-monitor`, `conflict-detection`, `raid-defense`,
`post-incident-healing`, and `culture-cultivation`. `conflict-detection.ts`
(Phase 32.6.2) detects argument escalation, personal attacks, polarizing
language, and named bad-faith patterns (strawmanning, whataboutism, sea-lioning,
concern-trolling, JAQing) and emits de-escalation/mediation suggestions, via
keyword-match counting and mean scoring over normalized text. Pure-TS,
deterministic.

### kuanyin-ai-ml-models

The scoring/classification model layer (`libs/kuanyin/ai-ml-models/src`): six
models — `intent-classification`, `emotional-state-detection`,
`harm-potential-scoring`, `cognitive-reframing`, `behavioral-pattern`, and
`community-health-model`. `harm-potential-scoring.ts` (Phase 32.11.3) implements
15 functions covering multi-label harm classification, severity, target
vulnerability, reversibility, cascade risk, fairness constraints, evasion
detection, and human-in-the-loop calibration, with weighted-mean/normalize/
clamp helpers. These are deterministic feature-driven scoring models in pure
TypeScript (no trained-weight binaries), not ML inference clients.

### kuanyin-dharma-analytics

By far the largest library (`libs/kuanyin/dharma-analytics/src`, ~498 top-level
exports across 31 modules): community-health metrics, individual dharma-path,
predictive wellness, transparency/explainability, algorithmic fairness, privacy
protection, multimodal & deepfake analysis, federated learning, crisis
intervention, CBT chatbot, Take-It-Down / regulatory compliance, and more.
`crisis-intervention.ts` (Phase 32.19.12) is representative — deterministic
risk-feature fusion into a `CrisisState` with a safe escalation workflow and a
50+-country helpline registry, "all logic DEFENSIVE and supportive." Pure-TS,
in-memory, no I/O.

### kuanyin-cross-domain

The integration boundary (`libs/kuanyin/cross-domain/src`): per-domain modules
`aphrodite-integration`, `lilith-integration`, `hathor-integration`,
`yemaya-integration`, plus `platform-wide-integration`. The platform-wide module
(Phase 32.10.5) covers cross-cutting concerns spanning every Oshun domain —
unified reputation, cross-domain moderation policy, emergency protocols, shared
safety profiles, universal appeals, data governance — with weighted-score and
normalize helpers over in-memory stores. It defines how Kuan Yin's moderation
composes with the rest of the platform; deterministic, Pure-TS.

### kuanyin-sdk-api

The API/SDK surface description (`libs/kuanyin/sdk-api/src`): `typescript-sdk`,
`rest-api-endpoints`, `graphql-api`, and `event-system`. `typescript-sdk.ts`
(Phase 32.12.1) models 20 functions for client factories, auth, caching,
real-time subscriptions, webhook processing, rate limiting, retry logic, and
docs generation. As with the rest of Phase 32 it is a deterministic in-memory
model of the surface ("10 stores, 7 items each, snapshot reset"), describing the
REST/GraphQL/event/SDK contracts rather than booting a live server.

### kuanyin-ui-components

Headless UI definitions (`libs/kuanyin/ui-components/src`): five modules —
`mindful-friction-components`, `performer-dashboard-components`,
`rehabilitation-journey-components`, `merit-karma-components`, and
`analytics-dashboard-components`. Its own header is explicit that these are
"**pure TypeScript logic/state/config objects that describe UI component
behavior — NOT React/DOM components**": data models, state machines, themes,
accessibility and analytics config for breathing overlays, Samma Vaca gates,
reflection prompts, etc. ~456 top-level exports; deterministic, framework-
agnostic.

### kuanyin-deployment

Deployment/operations as configuration-as-code (`libs/kuanyin/deployment/src`,
Phase 32.17): `infrastructure-setup`, `monitoring-observability`, and
`ci-cd-pipeline`. `infrastructure-setup.ts` carries the real operational
_algorithms_ — the HPA replica formula, grandfather-father-son backup retention,
lowest-latency region selection, certificate-renewal windows, RPO/RTO failover
decisions — over typed `Map` stores, "so they are testable against known values
rather than being inert config blobs." Deterministic, no I/O; timestamps are
passed in.

### kuanyin-evaluation

The model-quality harness (`libs/kuanyin/evaluation/src`, Phase 32.14). The
implemented source module is `model-evaluation.ts` — a dependency-free suite
computing real, verifiable classification/regression/fairness/drift/latency
metrics (e.g. `meRound`, precision over a fixed confusion matrix) so regressions
in the underlying models are caught "before they reach people." Honest scope:
the `index.ts` doc-comment also names integration / e2e / performance harnesses,
but those currently exist as test specs (`__tests__/integration-flows.spec.ts`,
`e2e-journeys.spec.ts`, `performance-benchmarks.spec.ts`) rather than separate
exported source modules — only `model-evaluation` is re-exported.

### @kuanyin/concordia-restorative

The outlier: a small **Phase-179** module
(`libs/kuanyin/concordia-restorative/src`, tagged `phase:179`, built with
`@nx/js:tsc` and the only kuanyin library that depends on `zod`).
`circle-safety.ts` implements a restorative-circle safety pre-flight (§179.7.3):
Zod schemas for `CircleKind`, `SafetyCheck`, and `CircleSafetyChecklist`, a
`REQUIRED_CHECKS_BY_KIND` table (child-related circles auto-add guardian-linkage
and child-safety gates), and `canOpenCircle` / `startSafetyChecklist` /
`recordCheckStatus` to gate whether a circle may open. A focused,
fully-implemented validation module — not one of the Phase-32 in-memory engines.

### @kuanyin/training-data

Phase 85–86 flywheel producer for guardianship
(`libs/kuanyin/training-data/src`): `KuanYinTrainingDataPipeline` normalizes
eleven `KuanYinTrainingKind` signals — `moderation-decision`,
`intent-classification`, `appeal-outcome`, `intervention-effectiveness`,
`mindful-friction`, `performer-protection`, `predictive-moderation`, and peers —
into governance-gated (`governanceGrantId`) `KuanYinTrainingRecord`s for a
pluggable `KuanYinTrainingSink`.
