# Kuanyin Domain — Features and Capabilities

> Named after Guanyin (觀音, also spelled Kuan Yin or Kannon), the Bodhisattva
> of Compassion revered across East Asian Buddhist traditions, Kuanyin is the
> platform-wide ethics, safety, and moderation domain for the entire Oshun
> ecosystem. A Bodhisattva is a being who has made a vow to attain full
> Buddhahood for the benefit of all sentient beings, choosing to remain
> accessible to guide others toward liberation rather than entering complete
> nirvana — appropriate for a moderation system that guides users toward
> wholesome expression rather than simply excluding or punishing them.

The core philosophical commitment of Kuanyin is that every user carries innate
potential for wisdom, compassion, and wholesome action — what Buddhist
philosophy calls "Buddha nature" (佛性, fóxìng). Moderation should create
conditions for that potential to flourish, not just defend against its
suppression. This means non-punitive interventions, restorative pathways back to
community, and recognition of positive contributions alongside detection of
harmful ones.

Kuanyin provides **16 libraries** covering predictive harm detection, mindful
friction, community harmony, performer protection, rehabilitation pathways,
merit and karma systems, dharma analytics, cross-domain ethics integration,
AI/ML models, SDK/API, user interface components, and a restorative-circle
safety pre-flight adapter. Kuanyin owns compassionate safety and restorative
intervention; Themis owns governance and IP policy; the broader Concordia
restorative-mediation flow remains planned.

---

## At a Glance

The table below maps each module to its primary purpose. Subsequent sections
explain each in detail.

| Module                          | Purpose                                                                       |
| ------------------------------- | ----------------------------------------------------------------------------- |
| `kuanyin-foundation`            | Harm taxonomy, severity classification, core constants                        |
| `kuanyin-precognition`          | Predictive harm detection before content is published                         |
| `kuanyin-mindful-friction`      | Non-punitive intervention patterns that create space for reflection           |
| `kuanyin-community-harmony`     | Community-level health monitoring, conflict detection, raid defense           |
| `kuanyin-performer-protection`  | Safety systems for creators and performers on live platforms                  |
| `kuanyin-rehabilitation`        | Pathways for violators to grow, take responsibility, and return to community  |
| `kuanyin-merit-karma`           | Positive behavior recognition, privilege tiers, achievement system            |
| `kuanyin-dharma-analytics`      | Community health metrics, predictive wellness, transparency reporting         |
| `kuanyin-cross-domain`          | Ethics integration adapters for each Oshun domain                             |
| `kuanyin-database`              | Table schemas, migrations, and repositories for moderation records            |
| `kuanyin-ai-ml-models`          | AI/ML model descriptors for harm detection, intent classification, prediction |
| `kuanyin-sdk-api`               | REST/GraphQL API, event system, and TypeScript SDK for integrations           |
| `kuanyin-ui-components`         | Reusable UI component descriptors for friction patterns and wellness features |
| `kuanyin-concordia-restorative` | Restorative-circle safety pre-flight checklist (Phase 179.7.3)                |

---

## 1. Foundation and Harm Classification (`kuanyin-foundation`)

The foundation library is the conceptual root of the entire domain. It defines
the shared vocabulary — harm categories, severity levels, intervention types,
and the BuddhaNature user model — that every other Kuanyin library builds on.

### 1.1 Buddha Nature Framework

Every user entity in the Kuanyin system carries a `BuddhaNature` interface — a
data structure representing the user's modeled potential for wholesome
engagement. This is not a moral judgment about who the user "really is" but a
probabilistic model that shapes how the system responds to them.

- **Innate goodness modeling** — Numeric properties: compassion seed (tendency
  to consider others' feelings), wisdom factor (tendency to reflect before
  acting), mindfulness level (present-moment awareness in communication), karma
  balance (running ledger of positive and negative actions), innate goodness
  (baseline wholesome tendency), and awakening potential (responsiveness to
  reflection prompts).
- **Refuge status tracking** — Five-stage spiritual progress model reflecting
  the user's engagement journey:
  - `seeking` — new user, exploring the platform
  - `taking_refuge` — committed community member
  - `established` — consistent positive contributor
  - `deepening` — community mentor or leader
  - `realized` — platform leader with governance rights Stage progression
    unlocks privileges and reduces friction.
- **Compassion-first moderation** — All moderation actions are designed around
  the assumption that users have the capacity for wholesome action. The system
  asks "how can this user be guided toward better expression?" before asking
  "should this user be excluded?"
- **Growth orientation** — Intervention design prioritizes guidance toward
  wholesome expression over punishment of unwholesome behavior. The goal is
  behavioral change, not exclusion.

### 1.2 Harm Category Taxonomy (74 Categories)

The harm taxonomy organizes 74 harm codes across 10 domains. The breadth of the
taxonomy ensures that detection logic can be specific — distinguishing, for
example, targeted harassment from mob harassment, or health misinformation from
coordinated disinformation — rather than relying on coarse categories that
produce false positives.

| Domain              | Example Categories                                                                                                                    |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| Interpersonal harm  | Targeted harassment, repeated harassment, sexual harassment, bullying, threats of violence, intimidation                              |
| Identity-based harm | Racial hate speech, ethnic hate speech, religious hate speech, gender-based hate speech, homophobia, transphobia, ableism, xenophobia |
| Safety harm         | CSAM (child sexual abuse material), grooming, self-harm promotion, suicide promotion, violence promotion, terrorism promotion         |
| Integrity harm      | Misinformation, disinformation, impersonation, fraud, intellectual property theft                                                     |
| Exploitation harm   | Sexual exploitation, labor exploitation, financial exploitation, emotional manipulation                                               |
| Manipulation harm   | Social engineering, coordinated inauthentic behavior, astroturfing, vote manipulation                                                 |
| Disruption harm     | Spam, flooding, vandalism, trolling, ban evasion                                                                                      |
| Legal harm          | Defamation, doxxing (publishing private information to enable harm), blackmail, extortion, illegal content distribution               |
| Platform harm       | Terms of service violations, abuse of reporting systems, ban evasion, multi-accounting                                                |
| Systemic harm       | Algorithmic bias, discriminatory patterns, structural inequality reinforcement through platform behavior                              |

### 1.3 Severity Classification

Six severity levels map harm categories to intervention types, ensuring that the
volume of minor events does not consume resources reserved for serious harms.
The `HarmCategorySeverity` union is
`negligible | low | moderate | high | severe | critical`.

| Level | Severity   | Automated Response                                                           |
| ----- | ---------- | ---------------------------------------------------------------------------- |
| 1     | Negligible | Logging only — no user-visible intervention                                  |
| 2     | Low        | Soft friction — a brief pause before posting                                 |
| 3     | Moderate   | Mindful friction — Right Speech prompts, rewrite suggestions                 |
| 4     | High       | Human review routing, community isolation from high-risk spaces              |
| 5     | Severe     | Immediate content hold, performer protection activation                      |
| 6     | Critical   | Immediate removal, emergency escalation (CSAM, imminent violence, terrorism) |

- **Context-sensitive severity** — Severity assessment considers not just
  content but intent, relationship between parties, audience, repetition
  history, and real-world impact potential.
- **Escalation thresholds** — Clear configurable thresholds for when automated
  responses must escalate to human review.
- **Severity-based routing** — Different intervention systems activate at each
  severity level, with higher levels bypassing low-priority queues.

### 1.4 Foundation Utilities

- **Platform constants** — Standardized moderation constants ensuring consistent
  enforcement across all platform contexts and domains.
- **Shared utilities** — 21 pure analysis functions for content analysis,
  severity scoring, harm assessment, cascade prediction, and restorative-circle
  scheduling — reused across all Kuanyin libraries.
- **Domain error types** — Specialized TypeScript error types for moderation
  failures, classification errors, and intervention exceptions. `KuanYinError`
  base class with subsystem-specific subtypes including resilience errors
  (`RateLimitError`, `CircuitBreakerOpenError`, `DegradationError`).

---

## 2. Precognition — Predictive Harm Detection (`kuanyin-precognition`)

Precognition is the predictive layer: it analyzes content and behavioral signals
before harmful content is published, enabling intervention at the most
beneficial moment — before harm lands, rather than after. Named after the
Buddhist concept that wisdom involves anticipating consequences before acting.

### 2.1 Intent Analysis

Intent analysis distinguishes what a message is trying to accomplish from its
surface content. Sarcasm, reclaimed language, and cultural expression can appear
harmful to surface-level pattern matching but carry benign intent, and the
intent analysis layer is specifically designed to handle this distinction.

- **Message intent classification** — Analyzes the underlying intent of user
  messages before they are published, classifying across intents such as:
  informing, asking, expressing, celebrating, criticizing, confronting,
  harassing, deceiving, manipulating, or harming.
- **Harmful intent detection** — Identifies messages crafted to harass, deceive,
  manipulate, or harm a specific target or group.
- **Benign intent recognition** — Distinguishes genuinely harmful intent from
  sarcasm, jokes, reclaimed language, and cultural expression that might
  superficially resemble harm.
- **Intent confidence scoring** — Assigns confidence scores to intent
  classifications, ensuring that low-confidence classifications trigger human
  review rather than automated action.
- **Multi-intent support** — Recognizes when a single message contains mixed
  intents (partly helpful criticism, partly personal attack), enabling
  proportional response.

### 2.2 Emotional Detection

Emotional state is a strong predictor of imminent harmful behavior. Detecting
distress, anger escalation, and emotional contagion enables protective
interventions before harm occurs rather than after.

- **Distress signal recognition** — Detects emotional distress in user content:
  despair, crisis, overwhelm, hopelessness. Triggers supportive resource
  surfacing (crisis hotlines, mental health resources) rather than punitive
  response.
- **Anger escalation detection** — Identifies escalating anger patterns in
  sequential messages before they result in harmful outbursts. Triggers
  cooling-off friction at the optimal moment.
- **Emotional state modeling** — Builds a real-time model of each user's
  emotional state from content and behavioral signals across a session.
- **Emotional contagion tracking** — Monitors when negative emotional states
  spread through community interactions — a phenomenon well-documented in online
  communities where one distressed user can destabilize many others.
- **Supportive intervention triggers** — Automatically surfaces supportive
  resources (peer support communities, professional resources, crisis lines)
  when distress signals are detected.

### 2.3 Typing Dynamics Analysis

Typing behavior patterns reveal emotional state in ways that message content
alone cannot. Frustration, rage, and anxiety all have characteristic typing
signatures that the precognition layer monitors in real time.

- **Typing speed monitoring** — Analyzes changes in typing speed that may
  indicate emotional escalation (rapid burst typing) or deliberate preparation
  of a harmful message.
- **Deletion pattern detection** — Detects excessive deletion and rewriting as a
  signal of frustration or self-censoring struggle — often indicating a user is
  oscillating between what they want to say and what they know they should say.
- **Draft analysis** — Analyzes drafted-but-not-yet-sent content for harmful
  patterns before the user decides to send or discard.
- **Cooling-off indicators** — Identifies when typing dynamics suggest the user
  is calming down versus continuing to escalate, enabling adaptive intervention
  timing.

### 2.4 Behavioral Pattern Tracking

Individual incidents are less predictive than trajectories. Kuanyin tracks
behavioral patterns over time to identify concerning trends before they cross
harm thresholds, which is especially important for detecting gradual escalation
that would be invisible in any single interaction.

- **Historical behavior profiling** — Builds behavioral profiles from each
  user's interaction history to identify concerning trends that wouldn't be
  visible from any single interaction.
- **Pattern deviation alerts** — Alerts when behavior deviates significantly
  from a user's established baseline — useful for detecting account compromise
  and sudden behavioral deterioration.
- **Escalation trajectories** — Identifies users on escalating trajectories
  (increasing severity of violations over time) before they cross into
  high-severity harm categories.
- **Positive behavior recognition** — Tracks positive behavioral patterns
  (helpful responses, welcome contributions, community support) to reinforce
  constructive engagement and feed the merit system.
- **Recidivism prediction** — Predicts the probability of repeat violations
  based on violation history, intervention response, and behavioral trajectory.

### 2.5 Context Awareness

The same words carry entirely different meaning in different contexts. A joke
among close friends, a community sharing reclaimed language, and a stranger
targeting a vulnerable person require entirely different responses — context
awareness is what makes the difference between fair moderation and blunt
over-filtering.

- **Conversation context** — Understands messages within the full context of the
  ongoing conversation, not as isolated utterances.
- **Relationship context** — Considers the established relationship between the
  parties: strangers, acquaintances, friends, romantic partners, community
  members.
- **Community context** — Factors in community norms, culture, and in-group
  language specific to each community space.
- **Temporal context** — Considers time of day, ongoing community events, and
  situational factors (e.g., community in distress after an incident).
- **Platform context** — Adapts detection thresholds to the specific platform
  context: adult content platform, children's educational platform, professional
  network, and public news comments all require different sensitivity settings.

### 2.6 Cascade Prediction

Some harmful messages are self-contained; others trigger broader community harm
through virality, pile-ons, or misinformation spread. Cascade prediction
specifically targets the latter — identifying messages likely to amplify into
community-wide harm before they do.

- **Viral harm prediction** — Predicts when a single harmful message could
  cascade into broader community harm through sharing, quote-posting, or
  community amplification.
- **Pile-on detection** — Detects early signs of coordinated pile-on behavior
  against a single user: multiple different users targeting the same person
  within a short time window.
- **Misinformation spread modeling** — Models how false information spreads
  through community networks based on the structure of the network and
  historical spread patterns.
- **Intervention timing optimization** — Determines the optimal intervention
  moment for maximum harm reduction with minimum disruption to legitimate
  discourse.
- **Cascade severity estimation** — Estimates the expected severity and reach of
  a harmful cascade before it fully develops, enabling proportional resource
  allocation for the response.

---

## 3. Mindful Friction (`kuanyin-mindful-friction`)

Mindful friction is the cornerstone of Kuanyin's non-punitive intervention
philosophy. Rather than blocking content or immediately escalating to punitive
action, mindful friction creates a brief space for reflection that allows users
to reconsider. The friction slows harmful actions without blocking expression —
users can always proceed after the reflection period. This respects user
autonomy while nudging toward more wholesome communication.

### 3.1 Pause and Breathe

The pause-and-breathe intervention is the most lightweight friction mechanism: a
momentary interruption that creates space without making any accusation.

- **Pre-posting pause** — A brief, configurable pause before potentially harmful
  content is published. The pause is presented as a moment for reflection, not a
  punishment or warning.
- **Breathing exercise integration** — Optional short guided breathing exercise
  during the pause period, reducing arousal and creating a more reflective
  mental state.
- **Cool-down timers** — Configurable cool-down periods proportional to detected
  emotional escalation level. An angry burst gets a longer pause than mild
  frustration.
- **Voluntary reflection** — Pause framed explicitly as an invitation to
  reflect: "You're about to send a message. Take a moment if you'd like." Not as
  an accusation or warning.
- **Bypass respect** — Users can always proceed immediately after the pause.
  Friction slows but never blocks expression.

### 3.2 Samma Vaca (Right Speech)

Samma Vaca (正語, sammā-vāca) is the Pali term for Right Speech — the third
element of the Noble Eightfold Path in Buddhism. It asks whether speech is true,
helpful, kind, and timely. Kuanyin presents these as gentle reflection
questions, not as gatekeeping criteria. The system never asserts that the
content fails these tests — it invites the user to consider them.

| Question                               | Check        |
| -------------------------------------- | ------------ |
| "Is what you're about to say true?"    | Truthfulness |
| "Is this helpful to the conversation?" | Helpfulness  |
| "Is this said with kindness?"          | Kindness     |
| "Is this the right time and place?"    | Timeliness   |

All prompts are presented as genuine invitations to reflection. The system does
not assert that the content fails these criteria — it asks the user to consider
them.

### 3.3 Cognitive Reframing

Cognitive reframing helps users recognize when their messages stem from
cognitive distortions — habitual thought patterns that misrepresent reality in
ways that often lead to conflict. This approach draws directly from
cognitive-behavioral therapy (CBT) techniques adapted for an online context.

- **Automatic thought identification** — Helps users recognize when messages
  stem from cognitive distortions common in online conflict situations.
- **Distortion labeling** — Gently identifies common cognitive distortions:
  all-or-nothing thinking ("you ALWAYS do this"), catastrophizing ("this is the
  worst thing ever"), personalizing (assuming everything is about you), mind
  reading (assuming you know others' motives).
- **Reframing suggestions** — Offers alternative interpretations of the
  situation that may be equally or more accurate and less distressing.
- **Perspective broadening** — Encourages consideration of multiple perspectives
  on the situation before responding.

### 3.4 Perspective Shift

Perspective-shift interventions interrupt the first-person tunnel vision that
often drives conflict, asking the user to imaginatively occupy other viewpoints.

- **Empathy prompts** — "How might the other person feel reading this?" —
  prompting users to imaginatively occupy the recipient's perspective.
- **Role reversal exercises** — Brief structured exercises where the user
  considers the situation from the other party's position.
- **Impact previews** — Shows predicted emotional impact of the message before
  it is sent, making consequences visible before they occur.
- **Third-party observer framing** — "How would a neutral observer view this
  exchange?" — shifting from participant to observer perspective.

### 3.5 Compassion Nudges

Compassion nudges are the lightest-touch interventions: brief reminders that
humanize the other party and encourage charitable interpretation before
responding.

- **Kindness reminders** — Brief reminders of the human on the other side of the
  screen: "There's a real person who will read this."
- **Positive intent assumption** — Encourages users to consider the most
  charitable interpretation of the other party's behavior before responding.
- **Common ground highlighting** — Surfaces what the conflicting parties have in
  common (shared community membership, similar values) during heated exchanges.
- **Gratitude redirects** — In some contexts, redirects energy from conflict
  toward appreciation of positive aspects of the relationship or community.

### 3.6 Alternative Expression

Alternative expression goes beyond friction to offer constructive help: concrete
rewrites and tone adjustments that let users express their genuine concern
without the harmful framing.

- **Rewrite suggestions** — Alternative phrasings that express the same
  underlying sentiment or concern without harmful content. For example: "This is
  stupid" → "I disagree with this approach because..."
- **Tone adjustment** — Tone-shifted versions of the same message: aggressive →
  assertive, passive-aggressive → direct, dismissive → critical.
- **Constructive criticism framing** — Helps users express valid criticism
  constructively: separating the critique from the person, focusing on specific
  behavior rather than character.
- **Frustration channels** — Suggests appropriate outlets for genuine
  frustration that don't involve targeting another person.

---

## 4. Community Harmony (`kuanyin-community-harmony`)

Community harmony systems operate at the collective level — monitoring the
emotional health of entire community spaces rather than individual users.
Healthy communities are resilient to individual conflicts; unhealthy communities
amplify them. These systems exist because individual-level moderation alone
cannot address collective dynamics like raids, pile-ons, or community-wide
emotional contagion.

### 4.1 Community Temperature Monitor

The temperature monitor aggregates emotional signal across all users in a space,
giving moderators a real-time sense of community health that individual-message
moderation cannot provide.

- **Real-time emotional temperature tracking** — Aggregated emotional state
  monitoring across all activity in a community space. Rising temperature
  indicates increasing conflict and distress across multiple users
  simultaneously.
- **Heat mapping** — Spatial heat maps showing which areas of a community (topic
  threads, live channels, comment sections) have elevated emotional temperature.
- **Community-wide trending alerts** — Alerts community moderators when
  temperature rises above configured thresholds, enabling proactive intervention
  before individual incidents escalate.

### 4.2 Conflict Detection

Conflict detection focuses on emerging interpersonal and group tensions — the
early warning signals that precede harassment incidents or community-wide
disruption.

- **Emerging conflict detection** — Identifies brewing conflicts between
  specific users before they escalate to harmful behavior, enabling moderator
  awareness and optional early intervention.
- **Interpersonal tension mapping** — Maps tension patterns across user
  relationships within the community to identify recurring conflict dyads or
  clusters.
- **Escalation prediction** — Predicts which tensions are likely to escalate to
  harmful behavior based on historical escalation patterns in similar community
  contexts.
- **Early intervention routing** — Routes detected conflicts to community
  moderators or appropriate resolution resources with sufficient context to
  enable informed intervention.

### 4.3 Raid Defense

A raid is a coordinated external attack: a group organized in one community
(typically a hostile or adversarial space) simultaneously floods a target
community with harmful content, harassment, or disruption. Raids are
qualitatively different from individual bad actors and require community-level
defenses.

- **Coordinated attack detection** — Detects sudden influx of coordinated
  harassment from accounts with similar behavioral fingerprints or external
  coordination signals.
- **Rapid response activation** — Automatically activates community protection
  measures: temporary slowmode, new account throttling, keyword filtering, and
  moderator alerts.
- **Attacker pattern fingerprinting** — Fingerprints the behavioral patterns of
  the attacking group for faster detection of subsequent raid attempts from the
  same community.
- **Post-raid community recovery** — Guides the affected community through
  emotional recovery after a raid: acknowledging the incident, supporting
  affected members, and restoring normal community culture.

### 4.4 Post-Incident Healing

After a serious incident — a raid, a viral harassment campaign, or a
high-profile conflict — the community itself needs support, not just the
individuals directly involved. Post-incident healing systems structure that
recovery.

- **Facilitated community healing conversations** — Structured community-wide
  conversations after harmful incidents, facilitated to acknowledge impact and
  restore trust.
- **Affected member support resources** — Surfaces appropriate support resources
  to community members most affected by incidents.
- **Community-wide acknowledgment** — Supports community leaders in
  acknowledging harmful incidents transparently to the community without
  amplifying harmful content.
- **Trust restoration pathways** — Structured approaches to restoring community
  trust after incidents that shook it.

### 4.5 Culture Cultivation

Culture cultivation is proactive rather than reactive: it reinforces positive
norms during normal operation, not just during incidents. Communities with
strong positive cultures are more resilient when conflicts arise.

- **Community norms reinforcement** — Proactively highlights and reinforces
  positive community culture norms during normal operation, not just during
  incidents.
- **Positive pattern amplification** — Amplifies and acknowledges constructive
  interactions and bridge-building behavior when detected.
- **Community value surfacing** — Surfaces shared community values during
  conflicts, reminding participants of what they have in common.
- **Onboarding norm integration** — Weaves community norms into the new member
  onboarding experience so new members understand the culture before
  encountering their first conflict.

---

## 5. Performer Protection (`kuanyin-performer-protection`)

Performers, streamers, and creators face distinctive moderation challenges: they
are public-facing, they interact with large numbers of strangers simultaneously,
and they are subject to coordinated campaigns by hostile audiences. Standard
community moderation is insufficient for their needs — they require specialized,
performer-controlled protection systems.

### 5.1 Real-Time Shield

- **Real-time content and chat filtering** — Live filtering of content and chat
  messages for live streams and performer-facing channels. Filters are applied
  before content reaches the performer, not just flagged after. Configurable
  sensitivity per performer.
- **Configurable sensitivity thresholds** — Performers configure their own
  protection sensitivity, trading off between over-filtering (blocking
  legitimate fans) and under-filtering (exposing themselves to harm).
- **Word, phrase, and pattern blocking** — Performer-defined and
  system-suggested word, phrase, and behavioral pattern blocking with regular
  expression support.

### 5.2 Parasocial Detection

Parasocial relationships are one-sided emotional attachments where an audience
member feels a personal connection with a performer who does not know them
personally. While healthy parasocial appreciation is normal and expected in
creator communities, pathological attachment can lead to boundary violations,
stalking, and serious harm. The parasocial detection system identifies the
transition from healthy fandom to concerning behavior.

- **Unhealthy attachment detection** — Identifies patterns indicating unhealthy
  parasocial attachment: excessive gifting, repeated attempts to establish
  personal contact, expressed belief in a personal relationship that does not
  exist.
- **Boundary violation tracking** — Tracks repeated attempts to violate
  performer-defined interaction boundaries across sessions.
- **Obsessive behavior indicators** — Flags escalating patterns of obsessive
  attention: following the performer across platforms, tracking their schedule,
  expressing entitlement over their behavior.
- **Graduated response** — Escalating interventions proportional to severity and
  trajectory: soft nudge (gentle redirect) → content filtering → shadow throttle
  → hard block.

### 5.3 Boundary Enforcement

- **Performer-defined rules** — Allows performers to define and manage their own
  interaction boundaries in plain language without requiring moderation
  expertise.
- **Boundary violation prevention** — Prevents messages that violate
  performer-defined rules from reaching the performer before delivery, not just
  flagging them after.
- **Topic and content rules** — Blocks specific topics, request types, or
  content categories per the performer's stated preferences. A performer may
  block discussion of their personal life, certain request types, or references
  to past content they no longer want discussed.

### 5.4 NCII and Deepfake Protection

NCII (Non-Consensual Intimate Imagery) is the distribution of intimate images of
a person without their consent, a form of sexual abuse. Deepfakes create fake
NCII using AI by inserting a person's face into intimate content they did not
participate in. Both are serious harms with specific legal frameworks, and
Kuanyin provides specialized detection and rapid response workflows for them.

- **NCII detection** — Non-consensual intimate imagery detection using image
  analysis models trained to identify intimate imagery and match it against
  performer-protected identities.
- **Deepfake detection** — AI-generated synthetic media detection, particularly
  face-swapped content replacing a performer's face in intimate material. Uses
  facial inconsistency detection and generation artifact recognition.
- **Streamlined report and removal** — Streamlined NCII/deepfake report and
  removal workflow ensuring rapid removal with minimal re-traumatization of the
  performer.
- **Legal framework reference** — References applicable legal frameworks
  (FOSTA-SESTA, UK Online Safety Act NCII provisions, Stop NCII tools) to
  support legal action where appropriate.

### 5.5 Performer Wellness

- **Emotional load monitoring** — Tracks cumulative emotional load from
  moderation activity: total number of filtered harmful messages, severity
  distribution, and trend over time.
- **Burnout risk detection** — Identifies performers showing signs of
  harassment-related burnout: escalating protective measures, declining
  engagement, and changed behavioral patterns.
- **Wellness check-ins** — Periodic automated wellness check-ins for active
  performers with high moderation loads, offering resources and adjusting
  protection levels.
- **Resource surfacing** — Surfaces mental health resources, peer support
  communities for creators, and professional support at appropriate moments.

### 5.6 Performer Dashboard

- **Safety analytics dashboard** — Comprehensive dashboard showing harassment
  volume trends over time, attack pattern summaries, boundary violation rates by
  category, a protective action log with decisions, and wellness indicators.
  Helps performers understand their safety landscape and make informed decisions
  about their interaction rules.

---

## 6. Rehabilitation Pathways (`kuanyin-rehabilitation`)

Kuanyin's most distinctive feature is its restorative rather than purely
punitive approach to users who have caused harm. Exclusion and punishment may
protect the community in the short term but do not help the violating user
become a better community member. Rehabilitation pathways offer structured
opportunities for growth and reintegration — the long-term investment in
community health that punitive systems cannot make.

### 6.1 Shadow Work Journeys

Shadow work is a concept from Jungian psychology referring to the process of
exploring and integrating the unconscious aspects of personality — including
impulses, fears, and patterns of behavior that the conscious self does not
acknowledge. Kuanyin adapts this framework for online conflict rehabilitation.

- **Guided self-reflection journeys** — Structured self-reflection experiences
  helping violators understand the impact of their behavior on others and
  themselves.
- **Shadow work exercises** — Carl Jung-inspired shadow integration exercises
  helping users recognize and work with the patterns driving harmful behavior,
  rather than simply suppressing them.
- **Non-punitive framing** — Journeys are presented explicitly as growth
  opportunities: "This is a chance to understand yourself better," not "you must
  do this or be banned."
- **Progress milestones** — Milestone achievements for completing reflection
  phases, providing a sense of forward momentum and accomplishment.

### 6.2 Empathy Training

- **Structured empathy-building exercises** — Formal exercises building the
  capacity to understand and share the feelings of others.
- **Perspective-taking scenarios** — Concrete scenarios involving community
  members affected by similar behavior, making abstract impact concrete.
- **Impact visualization** — Helps users visualize the emotional impact of their
  behavior on real people.
- **Graduated difficulty** — Exercises begin with less emotionally challenging
  scenarios and progress toward more difficult ones as the user demonstrates
  readiness.

### 6.3 Restorative Circles

A restorative circle is a facilitated conversation between the person who caused
harm and those affected, focused on understanding, accountability, and repairing
the relationship and community fabric. Restorative justice is an alternative to
purely punitive approaches originally developed in criminal justice and here
adapted for online community contexts. Participation by affected parties is
always entirely voluntary.

- **Facilitated conversations** — Structured restorative conversations between
  the violating user and affected parties when both consent to participate.
- **Consent-based participation** — The affected party's participation is always
  entirely voluntary. No affected party is ever required to participate in a
  restorative process.
- **AI facilitation option** — Optional AI facilitation for initial sessions,
  providing structure and preventing escalation when human facilitation is not
  available.
- **Closure protocols** — Structured protocols for reaching mutually acceptable
  resolution: acknowledgment of harm, agreed changes in behavior, and explicit
  closure.

### 6.4 Accountability Tracking

- **Commitment tracking** — Tracks accountability commitments made during
  restorative circles: specific behavioral changes the violating user agreed to
  make.
- **Follow-through prompts** — Reminder prompts at appropriate intervals to help
  users follow through on commitments.
- **Accountability partner matching** — Matches users undertaking rehabilitation
  with established community members who can serve as accountability partners
  and mentors.

### 6.5 Reintegration Pathways

Reintegration is the structured return to full community participation after a
rehabilitation journey. Rather than a binary excluded/included state, Kuanyin
uses graduated reintegration: each phase requires demonstrated positive behavior
before advancing to the next.

- **Graduated reintegration** — Phased return to community access: limited
  participation (read-only or specific channels only) → supervised participation
  (all actions visible to moderators) → full participation (normal community
  access).
- **Milestone-based trust restoration** — Each reintegration phase requires
  demonstrated positive behavior before advancing to the next.
- **Community sponsor model** — Established community members can voluntarily
  sponsor a returning user, vouching for them and supporting their reintegration
  with accountability.

---

## 7. Merit and Karma Systems (`kuanyin-merit-karma`)

The karma system provides positive reinforcement for constructive behavior,
creating an alternative to moderation-as-policing. Users who consistently
contribute positively to the community earn concrete benefits that recognize and
reward that contribution. This makes positive community behavior intrinsically
visible in a way that purely punitive systems never do.

### 7.1 Merit Accumulation

- **Positive action tracking** — Tracks merit-earning actions: helpful responses
  that received thanks, welcomed contributions, conflict de-escalation,
  community support, and effective mentorship.
- **Merit decay** — Gradual natural merit decay means scores must be maintained
  through ongoing contribution, not just past achievement. This prevents
  long-retired members from holding perpetual status based on historical work.
- **Merit events** — Specific configurable merit-earning events with
  configurable point values per platform context.

### 7.2 Privilege Tiers

Merit accumulation unlocks privilege tiers with meaningful benefits. The
`merit-karma` library's `privilege-tiers` module defines four tiers
(`PrivilegeTierLevel`) with progressively expanded capabilities:

| Tier        | Privileges                                              |
| ----------- | ------------------------------------------------------- |
| Basic       | Baseline participation with standard friction           |
| Trusted     | Reduced friction, expanded community access             |
| Guardian    | Lower friction, community-protection capabilities       |
| Bodhisattva | Minimal friction, full access, mentorship and analytics |

Three additional merit scales exist for different purposes. The `database`
library's `MeritLedger` records a growth-metaphor merit tier progression —
`seed`, `sprout`, `sapling`, `tree`, `grove`, `forest`, `ecosystem` — for ledger
display. The `foundation` constants store an additional `MeritTier` scale of
`newcomer → diamond` for point thresholds. The capability-gating tier list above
(four tiers: basic through bodhisattva) is the one the `privilege-tiers` module
enforces for access decisions.

### 7.3 Karma Visibility

- **Karma transparency controls** — Users control the visibility of their karma
  score to others, respecting privacy preferences.
- **Karma history** — Full visible history of karma-affecting actions so users
  understand what increased or decreased their score.
- **Karma explanation** — Clear human-readable explanations of why karma
  increased or decreased for each event.
- **Karma appeal** — Formal appeal process for karma adjustments the user
  believes were unfair, with human review.

### 7.4 Achievement System

Achievements recognize specific positive contributions, making extraordinary
community behavior visible and celebrated:

- First meaningful contribution to the community
- Sustained positive engagement over time
- Effective community mentorship of new members
- Rehabilitation journey completion
- Successful conflict de-escalation
- Cross-community bridge-building between different groups

---

## 8. Dharma Analytics (`kuanyin-dharma-analytics`)

Dharma (धर्म) in Buddhist philosophy refers to the natural law of things — the
way things actually are. Dharma analytics applies this concept to community
health: measuring the actual state of community wellbeing, not just surface
metrics like engagement volume. A community can show high engagement while
actually being in severe distress; dharma analytics is designed to see through
that distinction.

### 8.1 Community Health Metrics

- **Aggregate health dashboards** — Platform-wide and community-specific health
  score dashboards combining harm rates, positive engagement rates,
  rehabilitation outcomes, and temperature trends.
- **Health trend visualization** — Time-series visualization of community health
  trends enabling managers to see the long-term direction of community health.
- **Comparative community health** — Benchmark health metrics across different
  community spaces on the platform to identify best-practice communities and
  struggling ones.
- **Health alert thresholds** — Configurable alerts when health metrics cross
  configured warning or critical thresholds, enabling proactive intervention.

### 8.2 Individual Dharma Path

- **Per-user dharma path tracking** — Each user's individual progress: current
  refuge stage, merit accumulation history, rehabilitation journey status, and
  growth milestones.
- **Progress visualization** — Visual representation of the user's journey
  through the Kuanyin system, making growth tangible and motivating.

### 8.3 Predictive Wellness

- **Community wellness deterioration prediction** — Predictive models for
  community wellness deterioration based on early warning signal patterns
  observed in communities that subsequently declined.
- **Early warning indicators** — Leading behavioral indicators that precede
  measurable health deterioration: increasing negativity, decreasing positive
  interactions, rising conflict rates.
- **Proactive intervention recommendations** — Recommendations for community
  manager actions that have historically prevented deterioration in similar
  communities.

### 8.4 Wisdom Reports

- **Periodic wisdom reports** — Generated wisdom reports for community managers:
  key behavioral trends, emerging conflicts, rehabilitation outcomes, community
  culture observations, and recommended actions.
- **Executive summaries** — High-level summaries of platform-wide moderation
  health for platform leadership.

### 8.5 Moderation Transparency

Platform-level transparency about moderation operations is essential for
community trust. Without transparency, users cannot evaluate whether the system
is operating fairly or understand why actions were taken.

- **Action transparency reports** — Community-level reports on moderation
  volumes, action types, and outcomes without identifying individual users.
- **False positive tracking** — Systematic tracking and reporting of false
  positive moderation rates to drive continuous improvement.
- **Appeal outcome reporting** — Reporting on appeal volumes, outcomes, and
  resolution times.
- **Bias monitoring** — Continuous monitoring for demographic bias in moderation
  actions: are certain groups' content flagged at higher rates without
  corresponding harm? Active bias detection and correction.

---

## 9. Cross-Domain Ethics Integration (`kuanyin-cross-domain`)

Kuanyin's ethics and safety layer extends across the entire Oshun platform
through domain-specific integration modules. Each module adapts the core Kuanyin
capabilities to the specific context, user population, and risk profile of each
domain. A generic moderation API would force each domain to bend its model to
fit moderation logic; domain-specific modules apply the same underlying
capabilities with the domain's own vocabulary and calibration.

The following table shows each integration module, which domain it serves, and
the specific adaptations it provides:

| Integration Module          | Domain                  | Specific Adaptations                                                                                                      |
| --------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `aphrodite-integration`     | Relationships / Dating  | Consent enforcement, exploitation detection, boundary-setting support, coercive control detection                         |
| `lilith-integration`        | Consciousness / Content | Performer protection for adult content creators, age verification support, NCII priority response                         |
| `hathor-integration`        | Worldbuilding           | Dark creative content policies distinguishing legitimate dark fiction from harmful content, fictional violence guidelines |
| `yemaya-integration`        | Creative Studio         | Creator harassment protection, collaborative workspace safety, IP dispute moderation                                      |
| `platform-wide-integration` | All domains             | Unified ethical framework, cross-domain policy enforcement, escalation routing, aggregate harm monitoring                 |

The platform-wide integration ensures that harm detected in one domain informs
safety decisions in others: a user with a persistent harassment pattern in
Yemaya will have that context available when they interact in Aphrodite,
preventing domain-hopping to escape moderation history.

---

## 10. Data Foundation (`kuanyin-database`)

All Kuanyin data is persisted with appropriate access controls, retention
policies, and privacy safeguards. The 25 tables are organized around six major
data concerns:

- **Moderation event persistence** — All harm detections, intervention
  decisions, and outcomes recorded with full context for audit trails and system
  improvement.
- **Behavioral profile storage** — User behavioral profiles and escalation
  trajectories stored with privacy-preserving design: profiles inform moderation
  decisions but are not exposed to other users.
- **Rehabilitation journey tracking** — Progress through shadow work, empathy
  training, restorative circles, and reintegration phases, with milestone
  records.
- **Merit and karma ledger** — Append-only karma and merit event ledger ensuring
  historical integrity. Past karma events cannot be altered retroactively.
- **Community health time-series** — Historical community health metrics for
  trend analysis and predictive modeling.
- **Performer safety records** — Performer-specific protection rules, violation
  logs, and wellness data with performer-controlled access.

---

## 11. AI/ML Models (`kuanyin-ai-ml-models`)

The AI/ML models library provides typed model descriptors and inference records
for every classification and prediction task in Kuanyin, decoupled from the
feature libraries so that model implementations can be upgraded without touching
feature code.

- **Intent classification models** — Fine-tuned classification models for
  distinguishing harmful from benign intent across different content types,
  communities, and cultural contexts.
- **Emotion detection models** — Multi-class emotion recognition models
  calibrated for online communication patterns rather than formal speech.
- **Harm detection models** — Content harm classifiers trained on
  domain-specific labeled data with continuous improvement from human review
  outcomes.
- **Behavioral prediction models** — Sequential behavior prediction models for
  escalation trajectory detection and recidivism prediction.
- **Fairness and bias evaluation** — Regular bias evaluation across demographic
  groups to detect and correct demographic disparities in model behavior.
- **Cross-cultural models** — Community-specific and culture-specific model
  adaptations for communities with distinct communication norms.

---

## 12. SDK and API (`kuanyin-sdk-api`)

The `sdk-api` library is the stable public surface that consuming applications
use to integrate Kuanyin. It has four modules: `rest-api-endpoints`,
`graphql-api`, `event-system`, and `typescript-sdk`.

- **REST API** — 19 versioned `/v1` endpoints covering intent, emotion, and harm
  analysis; intervention triggering and completion; trust score and merit
  queries; rehabilitation and restorative-circle lifecycle; community health;
  performer protection; dharma analytics; transparency reporting; and appeals.
- **GraphQL API** — A GraphQL surface over the same capabilities, for consuming
  applications that prefer graph queries over REST.
- **Event system** — Ten event categories (`intervention`, `harm_detection`,
  `protection`, `rehabilitation`, `circle`, `merit`, `tier`, `community`,
  `analytics`, `system`) with dotted event names such as
  `intervention.triggered.gentle_nudge` and `harm.detected.harassment`. The REST
  surface also defines seven WebSocket push-event types for real-time updates.
- **TypeScript SDK** — A fully typed client for consuming the Kuanyin API, with
  retry and jitter helpers for reliability.

---

## 13. UI Components (`kuanyin-ui-components`)

The `ui-components` library provides typed configuration descriptors that
specify UI component behavior — it does not ship React or DOM components itself.
Platform teams consume these descriptors and render them in their own component
framework, ensuring consistent friction patterns and wellness displays across
all surfaces. Five module groups:

- **Mindful friction components** — Descriptors for pause-and-breathe
  interventions, Right Speech gate steps, and alternative-expression
  suggestions.
- **Karma and merit displays** — Descriptors for karma scores, merit badges, and
  tier progress.
- **Rehabilitation journey UI** — Descriptors for the shadow work journey,
  empathy training exercises, and reintegration progress tracking.
- **Analytics dashboard components** — Descriptors for community temperature,
  health scores, and moderation transparency reports.
- **Performer dashboard components** — Descriptors for the performer-facing
  safety analytics dashboard.

---

## 14. Restorative-Circle Safety Pre-Flight (`kuanyin-concordia-restorative`)

The `concordia-restorative` library (Phase 179.7.3) is the Kuanyin side of the
Concordia restorative-mediation integration. Before any restorative circle may
open, this library enforces a structured safety pre-flight checklist — ensuring
that the conditions for a safe, productive circle are in place before
participants are brought together. Rushing into a circle without these
preconditions risks re-traumatization and escalation rather than healing.

- **Circle kinds** — Seven kinds: community harm repair, moderation appeal,
  performer protection, creator protection, platform reintegration, school/youth
  program, and workplace restorative.
- **Safety checks** — Eleven Zod-validated checks covering harmed-party consent,
  responsible-party acknowledgment, absence of immediate danger,
  restraining-order status, power-imbalance assessment, facilitator training,
  language accessibility, a documented trauma-informed plan, child-safety
  review, guardian linkage, and active safety precautions.
- **Required-checks map** — Each circle kind has its own mandatory subset;
  child- and workplace-oriented circles add extra gates beyond the base
  requirements.
- **Opening decision** — `canOpenCircle` keeps a circle closed and returns the
  missing and failed checks until every required check has passed; helper
  functions build and update the checklist.

This library ships only the safety-checklist part of the restorative-mediation
flow; the broader Concordia integration remains planned (see below).

---

## 15. Planned Features

The following capabilities are not yet present in `libs/kuanyin/`:

- **Live service deployment** `(planned)` — The data layer is currently modelled
  as in-memory `Map` stores; a PostgreSQL-backed runtime and the API server
  implied by `KUANYIN_API_PORT` are not wired up in this tree.
- **AI model evaluation framework** `(planned)` — Systematic evaluation of
  intent classification, emotion detection, and harm detection model performance
  including precision/recall metrics, fairness evaluation across demographics,
  adversarial robustness tests, cross-cultural evaluation, and model drift
  detection.
- **Full restorative mediation** `(planned, Phase 179)` — Beyond the
  `concordia-restorative` safety pre-flight checklist (Section 14), the broader
  Concordia restorative-mediation flow — apology, restitution, reintegration,
  no-contact boundaries, content-takedown timelines, educational completion,
  monitoring windows, coercion detection, recurrence measurement, and safe
  escalation — remains planned.
- **Multimodal harm analysis** `(planned, Phase 32.18.1)` — Extending
  precognition beyond text and behavioral signals to image, video, and audio
  harm detection (visual threat and hate-symbol recognition, harmful audio and
  speech analysis, video-scene understanding), so every modality a platform
  carries passes through the same 74-category taxonomy and severity
  classification. Today only NCII image detection (Section 5.4) analyzes
  non-text media.
- **Moderator and facilitator wellness** `(planned, Phase 32.19.1, critical)` —
  Vicarious/secondary-trauma protection for the humans reviewing harmful content
  and facilitating circles: exposure budgeting and rotation, graded content
  blurring/desensitization controls, mandatory decompression windows, wellness
  check-ins, and burnout-trajectory monitoring — the same care Section 5.5 gives
  performers, applied to moderators and restorative-circle facilitators.
- **Bridging-based ranking and toxicity-scoring integration**
  `(planned, Phase 32.19.4)` — Integration with external toxicity scorers
  (Google Perspective API attributes) and bridging attributes that reward
  content which bridges divides between polarized groups, complementing the
  internal harm taxonomy with ecosystem-standard scores and pro-social ranking
  signals.
- **Federated learning** `(planned, Phase 32.18.5)` — Privacy-preserving
  federated training of harm-detection models across platforms and tenants, so
  models improve from distributed signals without centralizing raw user content.

V2 consumes `@kuanyin/concordia-restorative` through `@v2/concordia-substrate`
for high-impact anti-cheat appeal restorative preflight. Kuanyin owns the
`moderation_appeal` safety checklist and keeps the restorative circle closed
until consent, no-immediate-danger, facilitator, and safety-precaution gates
pass.

## Interpretability and Research Safety Gates (Phases 177–178)

Kuanyin is the safety-gate co-owner for the interpretability/continual-learning
track (Phase 177) and the autonomous-research substrate (Phase 178). Nous emits
interpretability safety reports (SAE side-channel signals, circuit-stability
metrics, forgetting watchdogs) and autonomous-research proposals; Kuanyin
consumes them as release and dual-use governance gates, applying the same
harm-taxonomy and human-in-the-loop review it applies to content. Nous owns the
models and the research loop; Kuanyin owns the safety verdict.
