# Kuanyin Domain — Technical Specifications

> Kuanyin (Kuan Yin / 觀音) is the platform-wide compassionate-moderation,
> safety, and restorative-justice domain. It is implemented as a set of
> TypeScript libraries with **no standalone applications or services** — host
> applications embed the libraries directly.

---

## Overview

This document is the authoritative technical reference for the Kuanyin domain.
It describes every entity, union type, constant store, table schema, endpoint,
and event that exists in `libs/kuanyin/` — all entries are traceable to a source
file in that tree.

The domain ships **14 Nx libraries** organized in layers from foundation to
public surface. The foundational layer (`kuanyin-foundation`) defines the shared
vocabulary — harm taxonomy, severity levels, BuddhaNature user model, constants,
utilities, and error types — that all other libraries depend on conceptually.
The persistence layer (`kuanyin-database`) describes 25 PostgreSQL table schemas
backed by in-memory `Map` stores for development. Eight feature libraries
implement the moderation lifecycle (precognition, mindful friction, community
harmony, performer protection, rehabilitation, merit and karma, dharma
analytics, and cross-domain integration). The intelligence layer provides AI/ML
model descriptors. The public surface layer (`kuanyin-sdk-api`,
`kuanyin-ui-components`) exposes the domain to consuming applications. The
restorative adapter (`kuanyin-concordia-restorative`) enforces the safety
pre-flight checklist for restorative circles.

A new engineer working in this domain should read Section 3 (Foundation Core
Types) first to understand the type vocabulary used throughout, then Section 8
(Database Schemas) for the persistence model, then Section 9 (SDK and API
Surface) to understand the integration points.

---

## 1. Library Inventory

All 16 libraries are listed below with their file paths, build executors, and
purposes. All publish as unscoped-private packages named `@kuanyin/<name>`
(`package.json` `name` fields) with the Nx project name `kuanyin-<name>` (except
`concordia-restorative`, whose Nx project name is
`@kuanyin/concordia-restorative`).

| Nx Project / Package             | Path                                 | Build executor        | Purpose                                                                    |
| -------------------------------- | ------------------------------------ | --------------------- | -------------------------------------------------------------------------- |
| `kuanyin-foundation`             | `libs/kuanyin/foundation`            | `@nx/esbuild:esbuild` | Core types, harm taxonomy, constants, utilities, errors, env               |
| `kuanyin-database`               | `libs/kuanyin/database`              | `@nx/esbuild:esbuild` | Table schemas, migrations, repositories, seed data                         |
| `kuanyin-precognition`           | `libs/kuanyin/precognition`          | `@nx/esbuild:esbuild` | Predictive harm detection (6 modules)                                      |
| `kuanyin-mindful-friction`       | `libs/kuanyin/mindful-friction`      | `@nx/esbuild:esbuild` | Non-punitive friction patterns (6 modules)                                 |
| `kuanyin-community-harmony`      | `libs/kuanyin/community-harmony`     | `@nx/esbuild:esbuild` | Community health and conflict (5 modules)                                  |
| `kuanyin-performer-protection`   | `libs/kuanyin/performer-protection`  | `@nx/esbuild:esbuild` | Creator and performer safety (6 modules)                                   |
| `kuanyin-rehabilitation`         | `libs/kuanyin/rehabilitation`        | `@nx/esbuild:esbuild` | Rehabilitation pathways (6 modules)                                        |
| `kuanyin-merit-karma`            | `libs/kuanyin/merit-karma`           | `@nx/esbuild:esbuild` | Merit accumulation and karma systems (5 modules)                           |
| `kuanyin-dharma-analytics`       | `libs/kuanyin/dharma-analytics`      | `@nx/esbuild:esbuild` | Community and individual analytics (5 modules)                             |
| `kuanyin-cross-domain`           | `libs/kuanyin/cross-domain`          | `@nx/esbuild:esbuild` | Cross-domain ethics integration (5 modules)                                |
| `kuanyin-ai-ml-models`           | `libs/kuanyin/ai-ml-models`          | `@nx/esbuild:esbuild` | AI/ML model interfaces and inference records (6 modules)                   |
| `kuanyin-sdk-api`                | `libs/kuanyin/sdk-api`               | `@nx/esbuild:esbuild` | REST/GraphQL API, event system, TypeScript SDK (4 modules)                 |
| `kuanyin-ui-components`          | `libs/kuanyin/ui-components`         | `@nx/esbuild:esbuild` | UI component descriptors for moderation interfaces (5 modules)             |
| `@kuanyin/concordia-restorative` | `libs/kuanyin/concordia-restorative` | `@nx/js:tsc`          | Restorative-circle safety pre-flight checklist (Phase 179.7.3)             |
| `kuanyin-deployment`             | `libs/kuanyin/deployment`            | `@nx/esbuild:esbuild` | CI/CD pipeline, infrastructure setup, monitoring/observability (3 modules) |
| `kuanyin-evaluation`             | `libs/kuanyin/evaluation`            | `@nx/esbuild:esbuild` | Model-evaluation harness (`model-evaluation`, ~1,460 lines)                |

All libraries carry the Nx tags `["scope:kuanyin", "layer:domain"]`.
`foundation`, `precognition`, `mindful-friction`, `community-harmony`,
`performer-protection`, and `concordia-restorative` additionally carry
`type:lib`. `concordia-restorative` also carries `phase:179`.

---

## 2. Technology Stack

The table below summarizes the full technology stack. The most important
distinction is between the build executors: all libraries except
`concordia-restorative` use esbuild for fast ESM output, while
`concordia-restorative` requires `tsc` because of its `zod` and
`@concordia/contracts` dependencies.

| Component      | Technology                                                                              |
| -------------- | --------------------------------------------------------------------------------------- |
| Language       | TypeScript (ESM, strict mode)                                                           |
| Build          | `@nx/esbuild:esbuild` (ESM, `bundle: false`); `concordia-restorative` uses `@nx/js:tsc` |
| Testing        | Vitest via the `@nx/vite:test` executor (per-library `vitest.config.ts`)                |
| Type checking  | Explicit `typecheck` Nx target running `tsc --noEmit`                                   |
| Linting        | `@nx/eslint:lint`                                                                       |
| Target runtime | Node.js; foundation and UI descriptors are browser-safe                                 |

Every library defines four Nx targets: `build`, `lint`, `test`, `typecheck`.

`foundation`, `precognition`, `database`, and most other libraries are
self-contained pure-TypeScript modules with no runtime `dependencies` in their
`package.json` (only `vitest` as a dev dependency where declared).
`concordia-restorative` is the only library with runtime dependencies:
`@concordia/contracts` (`workspace:*`) and `zod` (`catalog:`).

> Note: the data layer is modelled in `@kuanyin/database` as TypeScript
> interfaces backed by in-memory `Map` stores with snapshot-based reset. A live
> PostgreSQL deployment is described by the migration SQL but is not wired into
> a running service in this tree.

---

## 3. Foundation Core Types (`@kuanyin/foundation/src/types.ts`)

The foundation `types.ts` module is the vocabulary shared by all other Kuanyin
libraries. It defines 25 numbered domain entities (sections
`32.1.2.1`–`32.1.2.25`), 10 in-memory `Map` stores seeded with default items,
and a `resetFoundationTypesStores()` test-reset function. All entity fields are
`readonly`. The subsections below describe the most important interfaces; a new
engineer should read these in order, as later types build on earlier ones.

### 3.1 BuddhaNature

`BuddhaNature` is the root interface from which conceptually all entities
derive. It models the user's potential for wisdom and wholesome action through
numeric properties, and provides the identity and timing fields common to all
entities.

| Field                | Type             | Meaning                                         |
| -------------------- | ---------------- | ----------------------------------------------- |
| `id`                 | `string`         | Entity identifier                               |
| `createdAt`          | `string`         | ISO creation timestamp                          |
| `updatedAt`          | `string`         | ISO update timestamp                            |
| `isActive`           | `boolean`        | Whether the entity is active                    |
| `compassionSeed`     | `number`         | Capacity for compassion                         |
| `wisdomFactor`       | `number`         | Insight and discernment                         |
| `mindfulnessLevel`   | `number`         | Present-moment awareness                        |
| `karmaBalance`       | `number`         | Running ledger of wholesome vs. harmful actions |
| `innateGoodness`     | `number`         | Baseline wholesome tendency                     |
| `lastMindfulAction`  | `string \| null` | Timestamp of the last recorded mindful action   |
| `awakeningPotential` | `number`         | Capacity for growth and change                  |
| `refugeStatus`       | `RefugeStatus`   | Spiritual-progress stage                        |

`RefugeStatus` represents the user's journey through platform engagement:

```ts
type RefugeStatus =
  | 'seeking'
  | 'taking_refuge'
  | 'established'
  | 'deepening'
  | 'realized';
```

### 3.2 Harm Taxonomy

The harm taxonomy is the core classification system for the entire domain. Two
union types define the axes of classification — severity (how bad) and domain
(what kind of harm). Together they determine which intervention systems activate
and at what urgency.

```ts
type HarmCategorySeverity =
  | 'negligible'
  | 'low'
  | 'moderate'
  | 'high'
  | 'severe'
  | 'critical';

type HarmCategoryDomain =
  | 'interpersonal'
  | 'identity'
  | 'safety'
  | 'integrity'
  | 'exploitation'
  | 'manipulation'
  | 'disruption'
  | 'legal'
  | 'platform'
  | 'systemic';
```

`HarmCategoryCode` is a union of **74 codes** across the ten domains. A
selection of representative codes illustrates the specificity of the taxonomy:
`harassment_targeted`, `harassment_repeated`, `harassment_sexual`,
`harassment_mob`, `bullying_direct`, `bullying_cyberstalking`,
`threats_violence`, `threats_swatting`, `hate_speech_racial`,
`hate_speech_sexuality`, `dehumanization`, `dogwhistle_coded`, `csam`,
`csam_adjacent`, `sextortion`, `grooming`, `self_harm_promotion`,
`suicide_encouragement`, `doxxing`, `non_consensual_intimate`,
`misinformation_health`, `deepfake_malicious`, `fraud_romance`,
`spam_bot_network`, `revenge_porn`, `gaslighting`, `sealioning`,
`radicalization_pipeline`, `ban_evasion`, `terrorism_promotion`, and
`extremism_recruitment`.

The `HarmCategory` interface enriches each code with moderation metadata: `id`,
`code`, `name`, `description`, `domain`, `severity`, `requiresImmediateAction`,
`legalReportingRequired`, `rehabilitationEligible`, `compassionateFraming`,
`underlyingSuffering`, and `transformativePotential` (0–1). The store seeds 7
default categories (`hc-001`–`hc-007`): targeted harassment, racial hate speech,
CSAM, health misinformation, doxxing, self-harm promotion, and gaslighting.

### 3.3 Intent

Intent classification lets the system distinguish what a message is trying to
accomplish — which may differ significantly from its surface content. The 30-
value `IntentCode` union covers the full range from clearly wholesome to clearly
harmful:

`IntentCode` is a union of 30 intent classifications: `express_emotion`,
`connect_socially`, `seek_help`, `inform_others`, `vent_frustration`,
`humor_dark`, `sarcasm`, `provoke_reaction`, `attack_person`, `attack_group`,
`intimidate`, `manipulate`, `deceive`, `recruit`, `debate_constructive`,
`debate_adversarial`, `test_boundaries`, `cry_for_help`, `solidarity`, and more.

`IntentValence` simplifies intent to a four-way polarity:

```ts
type IntentValence = 'wholesome' | 'neutral' | 'unwholesome' | 'ambiguous';
```

The `Intent` interface carries `id`, `code`, `label`, `description`, `valence`,
`compassionateInterpretation`, `underlyingNeed`, `redirectionPossibility`,
`confidenceThreshold`, `requiresHumanReview`, and `commonMisclassifications`.
Seven default intents are seeded.

### 3.4 EmotionalState

Emotional state is a predictor of both harmful behavior and user distress.
`EmotionLabel` covers 20 emotions spanning the full affective spectrum: `joy`,
`sadness`, `anger`, `fear`, `disgust`, `surprise`, `contempt`, `trust`,
`anticipation`, `shame`, `guilt`, `envy`, `pride`, `love`, `grief`,
`loneliness`, `frustration`, `anxiety`, `hope`, and `equanimity`.

The `EmotionalState` interface uses an arousal / valence / dominance model
(three core psychological dimensions of emotion) plus additional fields:
`intensity`, `stability`, `volatilityIndex`, `triggerContext`,
`durationEstimate`, `mindfulnessAccessible`, `regulationCapacity`, and
`compassionReceptivity` (how open the user is to a compassion-based intervention
at this emotional state).

### 3.5 InterventionType

Intervention types define how the system responds when harm is detected. Two
union types control routing — category (what kind of intervention) and urgency
(how fast):

```ts
type InterventionCategory =
  | 'friction'
  | 'block'
  | 'transform'
  | 'guide'
  | 'pause'
  | 'breathe'
  | 'reflect'
  | 'escalate'
  | 'protect'
  | 'educate'
  | 'connect';

type InterventionUrgency =
  | 'deferred'
  | 'standard'
  | 'prompt'
  | 'immediate'
  | 'emergency';
```

`InterventionType` carries `id`, `category`, `name`, `description`, `urgency`,
`userFacingMessage`, `compassionateRationale`, `durationSeconds`,
`requiresAcknowledgment`, `escalatesTo`, `cooldownPeriod`,
`effectivenessWeight`, `preservesDignity`, and `rehabilitationIntegrated`. Seven
defaults are seeded (`iv-001`–`iv-007`): Mindful Pause, Samma Vaca Reflection,
Content Transformation, Compassionate Block, Guided Education, Vulnerable User
Shield, and Human Moderator Escalation.

### 3.6 Rehabilitation, Shadow Work, and Restorative Circle Types

These three type groups form the restorative backbone of Kuanyin, modeling a
violating user's journey from initial awareness of harm through behavioral
change to community reintegration.

**Rehabilitation phase types:**

`RehabilitationPhase` is a 10-value union covering the journey from first
awareness to mentorship: `awareness`, `acknowledgment`, `understanding`,
`empathy_building`, `accountability`, `restitution`, `behavioral_change`,
`community_service`, `reintegration`, and `mentorship`. The
`RehabilitationStage` interface carries required activities, assessment
criteria, minimum duration, progress and regression indicators, and a
`nextPhase` link that chains stages together. Seven default stages are seeded
(`rs-001`–`rs-007`).

**Shadow work types:**

`ShadowWorkStage` is a 7-value progression from `resistance` to `wholeness`,
reflecting the Jungian process of integrating unconscious patterns.
`ShadowArchetype` covers 10 archetypes: `the_critic`, `the_victim`, `the_bully`,
`the_perfectionist`, `the_martyr`, `the_rebel`, `the_shadow_trickster`,
`the_abandoned_child`, `the_controller`, and `the_judge`. `ShadowWorkJourney`
tracks journal entries, trigger patterns, insights, compassion meditations,
setbacks, breakthroughs, and `safetyChecksCleared`.

**Restorative circle types:**

`CircleRole` covers 6 roles and `CirclePhase` covers 9 phases from `preparation`
through `followup`. `RestorativeCircle` carries participants, ground rules,
talking-piece holder, agreements, `confidentialityLevel`
(`private | summary_shared | community_update`), and `completionStatus`.
`CircleParticipant` tracks `consentGiven`, `preparationCompleted`,
`safetyPlanInPlace`, and `voluntaryParticipation` — the latter because
affected-party participation is always voluntary.

### 3.7 Merit, Community Role, Protection, and Trust

These four type groups model the positive-reinforcement and safety-protection
sides of the system.

**Merit types:**

`MeritActionCode` covers 20 codes for merit-earning behaviors:
`helpful_response`, `mentoring_session`, `de_escalation`, `conflict_mediation`,
`defending_marginalized`, `acknowledgment_of_harm`, and others. `MeritAction`
carries `karmaPoints`, `compassionWeight`, `wisdomWeight`, `communityImpact`,
`repeatBonusDecay`, `minimumInterval`, `verificationRequired`,
`witnessesRequired`, `expirationDays`, and `stackable`. Seven defaults are
seeded.

**Community role types:**

`CommunityRoleCode` covers 11 roles ranging from `newcomer` to `steward`:
`newcomer`, `member`, `trusted_member`, `contributor`, `guardian`, `mentor`,
`elder`, `moderator`, `mediator`, `council_member`, and `steward`.
`CommunityRole` carries `hierarchyLevel`, `minimumKarma`, `minimumTenureDays`,
`permissions`, `responsibilities`, `electionRequired`, `mentoringCapacity`,
`protectionDuties`, and `removalCriteria`. Seven defaults are seeded.

**Protection level types:**

`ProtectionLevelCode` covers 7 levels: `standard`, `elevated`, `high`,
`maximum`, `performer_shield`, `minor_protection`, and `crisis_protection`.
`VulnerabilityFactor` covers 12 factors including `age_minor`, `crisis_state`,
`performer_creator`, `marginalized_identity`, and `neurodivergent_disclosed`.
The `ProtectionLevel` interface carries `contentFilterStrength`,
`notificationThreshold`, `autoHideThreshold`, `humanReviewPriority`,
`dmRestrictions`, `panicButtonEnabled`, `dedicatedSupportLine`, and
`periodicWellnessCheck`. Seven defaults are seeded.

**Trust score types:**

`TrustScore` carries `overallScore`, a `TrustFactorScore[]` breakdown across 12
`TrustFactor` values, `decayRate`, `rehabilitationBonus`, `veteranBonus`, and
`consistencyMultiplier`.

### 3.8 Mindful Friction, Behavior, Cascade, Parasocial, and Distortion Types

This group of types supports the friction, predictive, and protection feature
libraries. They model the specific behavioral signals, cognitive patterns, and
risk indicators that the system detects and responds to.

- **Samma Vaca types:** `SammaVacaGate` uses
  `SammaVacaGateCode = 'truth' | 'necessity' | 'kindness'` with
  `GateVerdict = 'passes' | 'fails' | 'uncertain' | 'requires_reflection'`, plus
  the `SammaVacaEvaluation` record that holds three per-gate verdicts and an
  overall verdict.

- **Mindful friction types:** `MindfulFriction` is keyed by `FrictionTrigger`
  (10 triggers) and `FrictionTechnique` (10 techniques: `breathing_pause`,
  `reflection_prompt`, `samma_vaca_check`, `body_scan_prompt`, and others).

- **Behavior pattern types:** `BehaviorPattern` is keyed by `PatternType` (10
  types) with
  `PatternConfidence = 'tentative' | 'moderate' | 'strong' | 'very_strong'`.

- **Cascade risk types:** `CascadeRisk` is keyed by `CascadeType` (10 types:
  `viral_harassment`, `hate_raid`, `self_harm_contagion`, `polarization_vortex`,
  `platform_exodus`, and others) and `CascadePhase` (`seed` → `aftermath`).

- **Parasocial types:** `ParasocialIndicator` is keyed by `ParasocialBehavior`
  (12 behaviors) with
  `ParasocialSeverity = 'mild' | 'moderate' | 'concerning' | 'alarming' | 'dangerous'`.

- **Cognitive distortion types:** `CognitiveDistortion` is keyed by
  `DistortionType` — 17 CBT distortions: `all_or_nothing`, `catastrophizing`,
  `mind_reading`, `emotional_reasoning`, `labeling`, `personalization`, and
  others. Each carries challenge questions, reframing examples, a
  `buddhistParallel`, a `mindfulnessExercise`, and journaling prompts. Seven
  defaults are seeded.

- **Additional types:** `PerspectiveShift`, `EmpathyTraining`
  (`EmpathyModuleCode` with 10 modules; `EmpathySkillLevel` with 5 levels —
  seven defaults seeded), `AccountabilityCommitment` (`CommitmentType` ×
  `CommitmentStatus`), `CommunityHealth` (`HealthDimension` × `HealthTrend`),
  `DharmaMetric` (`DharmaMetricCode` with 10 metrics; `MetricGranularity`),
  `PerformerShield` (`ShieldFeature` × `PerformerCategory`), and
  `ReintegrationPathway` (`ReintegrationStep` × `ReintegrationStatus`).

### 3.9 Foundation Type Stores

Ten `Map` stores are seeded on module load and snapshotted for test reset, one
per major type group. Each store exposes `register*`, `get*`, `getAll*`, and a
domain-specific query function. The stores hold: harm categories, intents,
intervention types, rehabilitation stages, community roles, protection levels,
cognitive distortions, merit actions, dharma metrics, and empathy trainings.

---

## 4. Foundation Constants (`@kuanyin/foundation/src/constants.ts`)

`constants.ts` is a self-contained module (no imports) with **10 `Map` stores**
of configuration objects, snapshot-based reset
(`resetFoundationConstantsStores()`), and per-store register/get/query
functions. Constants drive the thresholds, timing, and scoring logic used by
every feature library.

`ConstantSeverityLevel = 'warning' | 'minor' | 'moderate' | 'severe' | 'critical'`.

The ten stores and their subjects are:

| Store | Subject                          | Config interface / key types                                                                                                    |
| ----- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| 1     | Harm category thresholds         | `HarmCategoryThreshold` — score floor/ceiling, escalation, appeal window                                                        |
| 2     | Intervention timing              | `InterventionTimingConfig` — `InterventionTimingPhase` (6 phases), delays                                                       |
| 3     | Merit point values               | `MeritPointValue` — `MeritActionCategory` (6), base points, streak, caps                                                        |
| 4     | Rehabilitation durations         | `RehabilitationDurationConfig` — `RehabilitationStageName` (7), min/default/max days                                            |
| 5     | Performer protection + friction  | `PerformerProtectionConfig` — `ProtectionMechanism` (7), thresholds, FP %                                                       |
| 6     | Trust weights + community health | `TrustAndHealthConfig` — `TrustWeightFactor` (8), `HealthMetricDimension` (7)                                                   |
| 7     | Escalation + restorative circle  | `EscalationAndCircleConfig` — `EscalationAction` (7), circle requirements                                                       |
| 8     | Shadow work + merit tiers        | `ShadowWorkAndMeritConfig` — `ShadowWorkPhase` (6), `MeritTier` (6)                                                             |
| 9     | Karma decay + behavior lookback  | `KarmaCategory` (6), `BehavioralPatternKind`                                                                                    |
| 10    | Comprehensive moderation         | `DetectionDomain` (6), `PerspectiveShiftExercise` (6), `CooldownType` (6), `AppealSeverity` (5), `CommunityServiceActivity` (7) |

Two important union types defined in this module:

```ts
type MeritTier =
  | 'newcomer'
  | 'bronze'
  | 'silver'
  | 'gold'
  | 'platinum'
  | 'diamond';

type EscalationAction =
  | 'notify_moderator'
  | 'restrict_posting'
  | 'temporary_mute'
  | 'temporary_ban'
  | 'permanent_ban'
  | 'legal_referral'
  | 'restorative_circle';
```

Store 1 seeds five severity thresholds (`warning` → `critical`) plus two variant
rows. The `critical` threshold sets `maxResponseTimeMs: 1000`,
`allowAppeal: false`, `compassionateResponseRequired: false`, and
`logRetentionDays: 365`. Computational helpers derived from these constants
include `calculateMeritPoints`, `computeWeightedTrustScore`,
`getHarmCategoryThresholdForScore`, and `getTotalRehabilitationDurationDays`.

---

## 5. Foundation Utilities (`@kuanyin/foundation/src/utilities.ts`)

`utilities.ts` provides 12 lookup-table `Map` stores plus **21 pure analysis
functions**. Each function takes a typed `*Input` and returns a typed `*Result`,
making them composable across feature libraries without side effects.

The 12 lookup stores hold: harm keyword patterns, emotion lexicon, intervention
rules, merit formulas, trust weight configs, cascade models, distortion
patterns, reframe templates, protection profiles, and compliance rules.

The 21 analysis functions and their purposes:

| Function                          | Purpose                                               |
| --------------------------------- | ----------------------------------------------------- |
| `calculateHarmPotential`          | Score harmful potential of content                    |
| `assessEmotionalState`            | Derive arousal/valence emotional assessment           |
| `determineIntervention`           | Select an intervention given harm and emotion         |
| `calculateMerit`                  | Compute merit award for a positive action             |
| `assessTrustScore`                | Weighted trust-score computation                      |
| `predictCascadeRisk`              | Estimate cascade type, velocity, and reach            |
| `matchSammaVacaGate`              | Evaluate content against the three Right-Speech gates |
| `detectCognitiveDistortion`       | Identify CBT distortions in text                      |
| `suggestReframe`                  | Produce a cognitive-reframe suggestion                |
| `calculateRehabilitationProgress` | Compute progress through a rehabilitation journey     |
| `assessCommunityHealth`           | Composite community-health assessment                 |
| `determineProtectionLevel`        | Choose a protection level from vulnerability factors  |
| `matchBehaviorPattern`            | Match a behavior to a known pattern                   |
| `generateMindfulPrompt`           | Generate a friction prompt for a trigger              |
| `calculateParasocialRisk`         | Score parasocial-attachment risk                      |
| `assessPerformerRisk`             | Assess aggregate risk to a performer                  |
| `trackAccountability`             | Evaluate accountability-commitment progress           |
| `scheduleRestorativeCircle`       | Produce a restorative-circle schedule                 |
| `generateDharmaReport`            | Produce a dharma analytics report                     |
| `validateEthicalCompliance`       | Validate against compliance rules                     |

`resetFoundationUtilitiesStores()` restores all lookup stores from snapshot.

---

## 6. Foundation Errors and Resilience (`@kuanyin/foundation/src/errors.ts`)

`errors.ts` defines the domain error hierarchy, an internal validation-schema
system, input sanitizers, and resilience primitives. The resilience layer is
particularly important: Kuanyin runs in-process in host applications, and its
failures must be gracefully degradable rather than fatal.

### 6.1 Error Hierarchy

`KuanYinError` is the base class for all domain errors. Two unions classify
errors for routing and severity:

```ts
type ErrorDomain =
  | 'intervention'
  | 'rehabilitation'
  | 'protection'
  | 'analysis'
  | 'circle'
  | 'merit'
  | 'privacy'
  | 'consent'
  | 'bias'
  | 'general';

type ErrorSeverity = 'low' | 'medium' | 'high' | 'critical' | 'fatal';
```

Domain-specific subclasses, each with a `*FailureReason` union:
`InterventionError`, `RehabilitationError`, `ProtectionError`, `AnalysisError`,
`CircleError`, `MeritError`, `PrivacyError`, `ConsentError`, `BiasError`.
Resilience-specific errors: `RateLimitError`, `CircuitBreakerOpenError`,
`DegradationError`.

### 6.2 Validation System

A self-contained schema system that does not depend on Zod (keeping the
foundation free of runtime dependencies): `ValidationSchema<T>` with
`safeParse`, plus `stringSchema`, `numberSchema`, `booleanSchema`,
`arraySchema`, and `objectSchema` builders. Pre-built schemas cover the most
common input paths: `harmPotentialInputSchema`,
`emotionalAssessmentInputSchema`, `meritCalculationInputSchema`,
`circleSessionInputSchema`, and `protectionAssessmentInputSchema`.

### 6.3 Sanitizers and Resilience Primitives

**Input sanitizers** cover the common attack surfaces: `sanitizeText`,
`sanitizeHtml`, `sanitizeUserId`, `sanitizeNumericInput`, `sanitizeSqlInput`,
and `sanitizeEmail`.

**Resilience primitives** provide the reliability layer for production use:

- `RateLimiter` / `checkRateLimit` — token-bucket rate limiting
- `CircuitBreaker` with `CircuitBreakerState = 'closed' | 'open' | 'half_open'`
- `DegradationHandler` with `DegradationLevel` as a 5-value scale
- `withFallback` / `withMultiFallback` — graceful degradation wrappers
- `calculateRetryDelay` with `RetryStrategy` as a 7-value union

Error helper functions: `aggregateErrors`, `isKuanYinError`,
`isRecoverableError`, `isRetryableError`, `toKuanYinError`,
`formatErrorForUser`, and `formatErrorForLog`.

**Compliance standard types** are also defined here, supporting the
`validateCompliance` function:

```ts
type ComplianceStandard =
  | 'gdpr'
  | 'ccpa'
  | 'coppa'
  | 'hipaa'
  | 'ferpa'
  | 'dsa'
  | 'aia';
```

Additional configuration stores in this module cover: error-code definitions,
validation schema definitions, sanitization rules, rate-limit configs,
circuit-breaker configs, degradation configs, retry policies, error-handler
mappings, recovery strategies, and compliance validations — each with
register/get functions and restored by `resetFoundationErrorsStores()`.

---

## 7. Environment Configuration (`@kuanyin/foundation/src/env-schema.ts`)

The env schema validates 30 environment variables at startup and returns a typed
`KuanYinEnvConfig`. All variables are prefixed `KUANYIN_` to avoid collisions
with host application configuration. `validateKuanYinEnv()` parses and validates
them; `describeKuanYinEnv()` renders a human-readable summary for debugging.

The 30 variables are organized into eight categories:

| Variable                              | Required | Default                    | Category      |
| ------------------------------------- | -------- | -------------------------- | ------------- |
| `KUANYIN_DATABASE_URL`                | Yes      | —                          | database      |
| `KUANYIN_DATABASE_POOL_SIZE`          | No       | `10`                       | database      |
| `KUANYIN_DATABASE_SSL`                | No       | `false`                    | database      |
| `KUANYIN_REDIS_URL`                   | Yes      | —                          | cache         |
| `KUANYIN_REDIS_TTL`                   | No       | `3600`                     | cache         |
| `KUANYIN_AI_MODEL_ENDPOINT`           | No       | `http://localhost:8080/v1` | ai            |
| `KUANYIN_AI_MODEL_API_KEY`            | No       | (empty)                    | ai            |
| `KUANYIN_AI_MODEL_TIMEOUT`            | No       | `5000`                     | ai            |
| `KUANYIN_AI_CONFIDENCE_THRESHOLD`     | No       | `0.7`                      | ai            |
| `KUANYIN_ENCRYPTION_KEY`              | Yes      | —                          | security      |
| `KUANYIN_WEBHOOK_SECRET`              | No       | (empty)                    | security      |
| `KUANYIN_JWT_SECRET`                  | No       | (empty)                    | security      |
| `KUANYIN_RATE_LIMIT_MAX`              | No       | `100`                      | security      |
| `KUANYIN_RATE_LIMIT_WINDOW_MS`        | No       | `60000`                    | security      |
| `KUANYIN_API_PORT`                    | No       | `3200`                     | api           |
| `KUANYIN_API_HOST`                    | No       | `0.0.0.0`                  | api           |
| `KUANYIN_API_CORS_ORIGINS`            | No       | `http://localhost:3000`    | api           |
| `KUANYIN_LOG_LEVEL`                   | No       | `info`                     | logging       |
| `KUANYIN_LOG_FORMAT`                  | No       | `json`                     | logging       |
| `KUANYIN_LOG_SENSITIVE_DATA`          | No       | `false`                    | logging       |
| `KUANYIN_MOD_AUTO_ESCALATE_THRESHOLD` | No       | `0.85`                     | moderation    |
| `KUANYIN_MOD_MAX_FRICTION_DELAY_MS`   | No       | `30000`                    | moderation    |
| `KUANYIN_MOD_COOLDOWN_MS`             | No       | `60000`                    | moderation    |
| `KUANYIN_MOD_APPEAL_WINDOW_HOURS`     | No       | `72`                       | moderation    |
| `KUANYIN_FEATURE_PRECOGNITION`        | No       | `true`                     | feature_flags |
| `KUANYIN_FEATURE_SAMMA_VACA`          | No       | `true`                     | feature_flags |
| `KUANYIN_FEATURE_SHADOW_WORK`         | No       | `true`                     | feature_flags |
| `KUANYIN_FEATURE_PERFORMER_SHIELD`    | No       | `true`                     | feature_flags |
| `KUANYIN_FEATURE_RESTORATIVE_CIRCLES` | No       | `true`                     | feature_flags |
| `KUANYIN_FEATURE_MERIT_KARMA`         | No       | `true`                     | feature_flags |

Sensitive variables (`databaseUrl`, `redisUrl`, `aiModelApiKey`,
`encryptionKey`, `webhookSecret`, `jwtSecret`) are flagged so they can be
excluded from logs. Enabling `KUANYIN_LOG_SENSITIVE_DATA` emits a warning to
prevent accidental sensitive-data exposure in production log pipelines.

---

## 8. Database Schemas (`@kuanyin/database`)

`@kuanyin/database` models the persistence layer as TypeScript interfaces backed
by in-memory `Map` stores. It exports four modules: `schemas`, `migrations`,
`repositories`, and `seeds`. The schemas describe the PostgreSQL tables that a
live deployment would use; the in-memory stores allow the libraries to operate
and be tested without a running database.

### 8.1 Table Schemas (`schemas.ts`)

`schemas.ts` defines **25 table interfaces**, all named with the `kuanyin_`
prefix in the migration SQL. Every interface uses `readonly` fields and includes
`createdAt` / `updatedAt` (`Date`). The 25 tables are organized around the major
domain aggregates:

| #   | Interface                   | Table                                 | Notes                                               |
| --- | --------------------------- | ------------------------------------- | --------------------------------------------------- |
| 1   | `KuanYinUserProfile`        | `kuanyin_user_profile`                | Buddha-nature score, trust level, merit, role       |
| 2   | `MeritLedger`               | `kuanyin_merit_ledger`                | Append-only merit entries with running total        |
| 3   | `InterventionRecord`        | `kuanyin_intervention_record`         | Intervention type, harm score, user response        |
| 4   | `RehabilitationJourney`     | `kuanyin_rehabilitation_journey`      | Current phase, module progress, mentor, circle      |
| 5   | `ShadowWorkProgress`        | `kuanyin_shadow_work_progress`        | Checkpoint reflections and facilitator notes        |
| 6   | `RestorativeCircle`         | `kuanyin_restorative_circle`          | Initiator/respondent/facilitator, status, format    |
| 7   | `CircleOutcome`             | `kuanyin_circle_outcome`              | Resolution type, agreement text, satisfaction       |
| 8   | `PerformerProtectionConfig` | `kuanyin_performer_protection_config` | Shield level, boundary rules, blocked patterns      |
| 9   | `HarmIncident`              | `kuanyin_harm_incident`               | Reporter/target/content, severity, status           |
| 10  | `BehaviorPattern`           | `kuanyin_behavior_pattern`            | Pattern type, frequency, confidence, risk level     |
| 11  | `EmotionalStateLog`         | `kuanyin_emotional_state_log`         | Dominant emotion, arousal/valence/dominance         |
| 12  | `TrustScoreRecord`          | `kuanyin_trust_score_record`          | Composite score, factor breakdown, trend            |
| 13  | `AccountabilityCommitment`  | (`kuanyin_accountability_*`)          | Commitment text, deadline, status, witnesses        |
| 14  | `CommunityHealthSnapshot`   | `kuanyin_community_health_snapshot`   | Health score, interaction rates, retention          |
| 15  | `DharmaMetric`              | `kuanyin_dharma_metric`               | Metric value, dimension, trend vs. previous         |
| 16  | `MindfulFrictionConfig`     | (`kuanyin_mindful_friction_*`)        | Friction type, trigger, prompt template, cooldown   |
| 17  | `PerspectiveShiftExercise`  | (`kuanyin_perspective_shift_*`)       | Exercise type, scenario, reflection, quality score  |
| 18  | `EmpathyTrainingProgress`   | (`kuanyin_empathy_training_*`)        | Module progress, assessment score, practice hours   |
| 19  | `ReintegrationMilestone`    | `kuanyin_reintegration_milestone`     | Milestone status, evidence, due date                |
| 20  | `ParasocialAlert`           | `kuanyin_parasocial_alert`            | Alert level, indicators, risk score, fixation       |
| 21  | `BoundaryViolation`         | `kuanyin_boundary_violation`          | Boundary type, severity, status                     |
| 22  | `CascadeIncident`           | `kuanyin_cascade_incident`            | Cascade type, affected count, peak spread, reach    |
| 23  | `AppealRecord`              | `kuanyin_appeal_record`               | Appeal reason, evidence, review decision            |
| 24  | `ModeratorAction`           | `kuanyin_moderator_action`            | Action type, reason, automated flag, reversal       |
| 25  | `AuditLog`                  | `kuanyin_audit_log`                   | Component, action, actor/target, previous/new state |

Each table's enum-style columns are typed as literal unions. Key enum types and
their value counts: `RehabilitationStatusType` (8 values), `MeritTierType`
(`seed | sprout | sapling | tree | grove | forest | ecosystem`),
`InterventionTypeCode` (12 values), `CircleStatusType` (7 values),
`HarmIncidentStatusType` (8 values), `RiskLevelType` (6 values), `CascadeType`
(7 values), `AppealStatusType` (7 values), `ModeratorActionType` (12 values),
and `AuditActionType` (12 values).

`schemas.ts` keeps **10 `Map` stores** (one per major aggregate: user profiles,
merit ledger, intervention records, rehabilitation journeys, restorative
circles, harm incidents, behavior patterns, community health, moderator actions,
and protection configs). Each store is seeded with 7 sample items and is
snapshot-resettable. Stores expose `register*`, `get*`, `getAll*`, and `query*`
functions.

### 8.2 Migrations (`migrations.ts`)

`migrations.ts` models migration metadata. The first `MigrationRecord`
(`create_kuanyin_schema`) creates the `kuanyin` PostgreSQL schema and enables
the `pgcrypto`, `pg_trgm`, and `btree_gist` extensions. Subsequent migrations
create the per-table DDL. Eight migration records (`20250115_000001`–
`20250115_000007`, plus one) are seeded with `upSql` / `downSql`, `checksum`,
`executionTimeMs`, and a `dependsOn` chain.

The module also defines `IndexDefinition` (with an `IndexType` union) and keeps
separate index stores per table group — harm-pattern indexes, trust-score
indexes, and protection indexes — plus partition-strategy and foreign-key
descriptor types.

### 8.3 Repositories (`repositories.ts`)

`repositories.ts` exports **15 repository classes**, one per major data access
concern:

`UserKuanYinRepository`, `MeritRepository`, `InterventionRepository`,
`RehabilitationRepository`, `CircleRepository`, `ProtectionRepository`,
`IncidentRepository`, `PatternRepository`, `HealthRepository`,
`AnalyticsRepository`, `AuditRepository`, `CacheRepository`, `SearchRepository`,
`TimeSeriesRepository`, and `GraphRepository`.

Supporting types include `PaginationOptions` / `PaginatedResult<T>`,
`RepositoryConfig`, `QueryTemplate`, `CacheEntry`, `SearchIndexEntry`,
`TimeSeriesDataPoint`, `GraphEdge` / `GraphNode`, `AuditTrailEntry`,
`AggregationConfig`, and `PaginationState`, plus per-repository result types
such as `UserDashboardData`, `LeaderboardEntry`, `EffectivenessStats`, and
`ProgressSummary`. `seeds.ts` provides development seed data that populates
these repositories for local testing.

---

## 9. SDK and API Surface (`@kuanyin/sdk-api`)

`@kuanyin/sdk-api` is the stable integration surface for consuming applications.
It exports four modules — `typescript-sdk`, `rest-api-endpoints`, `graphql-api`,
and `event-system` — together providing REST, GraphQL, event-driven, and SDK
integration paths.

### 9.1 REST API (`rest-api-endpoints.ts`)

The REST surface defines **19 versioned `/v1` endpoints**. The endpoints cover
the full Kuanyin lifecycle: analysis, intervention, trust and merit,
rehabilitation, restorative circles, community health, performer protection,
analytics, transparency, and appeals.

| Method & Path                          | Purpose                                     |
| -------------------------------------- | ------------------------------------------- |
| `POST /v1/analyze-intent`              | Content intent classification + confidence  |
| `POST /v1/analyze-emotion`             | Emotional-state detection (arousal/valence) |
| `POST /v1/assess-harm`                 | Harm-potential scoring and severity         |
| `POST /v1/intervention/trigger`        | Initiate an intervention, select strategy   |
| `POST /v1/intervention/complete`       | Record intervention outcome / effectiveness |
| `GET /v1/user/{id}/trust-score`        | Trust-score retrieval with history          |
| `GET /v1/user/{id}/merit`              | Merit points, tier status, achievements     |
| `POST /v1/merit/award`                 | Award merit points (validated)              |
| `POST /v1/rehabilitation/enroll`       | Enroll a user in a rehabilitation program   |
| `GET /v1/rehabilitation/{id}/progress` | Rehabilitation progress and milestones      |
| `POST /v1/circle/request`              | Initiate a restorative circle               |
| `GET /v1/circle/{id}/status`           | Circle progress and outcomes                |
| `GET /v1/community/{id}/health`        | Community-health metrics                    |
| `GET /v1/performer/{id}/protection`    | Shield status and threat levels             |
| `POST /v1/performer/shield/configure`  | Update shield settings                      |
| `GET /v1/analytics/dharma`             | Dharma-path analytics                       |
| `GET /v1/reports/transparency`         | Transparency reporting                      |
| `POST /v1/appeal/submit`               | Submit a moderation appeal with evidence    |
| `GET /v1/appeal/{id}/status`           | Appeal progress and decisions               |

Each endpoint group has REST record interfaces for typed request/response
shapes: `RestApiIntentRecord`, `RestApiEmotionRecord`, `RestApiHarmAssessment`,
`RestApiInterventionRecord`, `RestApiTrustProfile`, `RestApiMeritRecord`,
`RestApiRehabEnrollment`, `RestApiCircleRecord`, `RestApiPerformerShield`, and
`RestApiAppealRecord`. Supporting literal-union types include
`RestApiHarmSeverity`, `RestApiInterventionStrategy`, `RestApiTrustTier`,
`RestApiRehabPhase`, `RestApiCircleStatus`,
`RestApiShieldLevel = 'basic' | 'enhanced' | 'fortified' | 'maximum' | 'emergency'`,
and `RestApiAppealDecision`. `validateRestApiEndpointsIntegrity()` and
`resetRestApiEndpointsStore()` support testing.

`RestApiWebSocketEventType` enumerates seven push-event types for real-time
updates: `intervention_triggered`, `protection_alert`, `merit_awarded`,
`circle_update`, `community_temperature`, `appeal_decision`, and
`system_health`.

### 9.2 Event System (`event-system.ts`)

The event system provides a typed, domain-specific event vocabulary for
event-driven integration. Events use a dotted naming convention to allow
consumers to subscribe at any level of specificity.

`EvtSysEventCategory` defines **10 event categories**: `intervention`,
`harm_detection`, `protection`, `rehabilitation`, `circle`, `merit`, `tier`,
`community`, `analytics`, and `system`. `EvtSysSeverityLevel` covers
`info | low | medium | high | critical | emergency`.

Event-definition interfaces carry a dotted `eventName`. The seeded event name
families include:

- **Intervention triggered:** `intervention.triggered.gentle_nudge`,
  `intervention.triggered.educational_prompt`,
  `intervention.triggered.cooling_period`,
  `intervention.triggered.mediated_dialogue`,
  `intervention.triggered.temporary_restriction`,
  `intervention.triggered.restorative_circle`,
  `intervention.triggered.elder_review`
- **Intervention completed:** `intervention.completed.acknowledged`,
  `…resolved`, `…escalated`, `…withdrawn`, `…timeout`, `…appealed`,
  `…transformed`
- **Harm detected:** `harm.detected.harassment`, `…hate_speech`,
  `…misinformation`, `…self_harm`, `…spam`, `…doxxing`, and others

Parallel event families exist for protection-activated, rehab-enrolled /
completed, circle-requested / completed, merit-awarded, and tier-unlocked
events. Supporting union types include `EvtSysInterventionStrategy` (7
strategies), `EvtSysHarmCategory` (8), `EvtSysProtectionShieldType` (7),
`EvtSysRehabilitationPhase` (7), `EvtSysCircleRole` (7), `EvtSysMeritReason`
(7), and `EvtSysTierLevel`
(`newcomer | bronze | silver | gold | platinum | diamond | elder`).

### 9.3 GraphQL API and TypeScript SDK

`graphql-api.ts` models the GraphQL surface as typed schema descriptors.
`typescript-sdk.ts` provides the typed client, with retry and jitter helpers for
reliable calls to the REST API and id-generation utilities.

---

## 10. Feature Library Module Maps

Each feature library is organized into modules that map directly to the
functional capabilities described in the features document. This section lists
the module names as the ground truth for what exists in each library.

### 10.1 `@kuanyin/precognition` (6 modules)

The 6 modules cover the predictive detection pipeline: `intent-analysis`,
`emotional-detection`, `typing-dynamics`, `behavioral-patterns`,
`context-awareness`, and `cascade-prediction`. Modules hold registries of
pattern configs (e.g. `PrimaryIntentPatternConfig`,
`SecondaryIntentPatternConfig`) with register/get/query functions and pure
scoring logic.

### 10.2 `@kuanyin/mindful-friction` (6 modules)

The 6 modules cover each friction technique: `pause-breathe`, `samma-vaca`,
`cognitive-reframing`, `perspective-shift`, `compassion-nudges`, and
`alternative-expression`. The `pause-breathe` module specifically keeps
`BreathingPattern`, `AnimationTemplate`, and `AudioGuide` registries for guiding
the user through the pause period.

### 10.3 `@kuanyin/community-harmony` (5 modules)

The 5 modules cover community-level monitoring and response:
`temperature-monitor`, `conflict-detection`, `raid-defense`,
`post-incident-healing`, and `culture-cultivation`.

### 10.4 `@kuanyin/performer-protection` (6 modules)

The 6 modules cover the performer protection lifecycle: `real-time-shield`,
`parasocial-detection`, `boundary-enforcement`, `ncii-deepfake-protection`,
`performer-wellness`, and `performer-dashboard`.

### 10.5 `@kuanyin/rehabilitation` (6 modules)

The 6 modules cover the rehabilitation journey: `shadow-work-journeys`,
`journey-progress`, `empathy-training`, `restorative-circles`,
`accountability-tracking`, and `reintegration-pathways`.

### 10.6 `@kuanyin/merit-karma` (5 modules)

The 5 modules cover the positive reinforcement system: `merit-accumulation`,
`merit-calculation`, `privilege-tiers`, `karma-visibility`, and
`achievement-system`. The `privilege-tiers` module defines:

```ts
type PrivilegeTierLevel = 'basic' | 'trusted' | 'guardian' | 'bodhisattva';
```

...and gates specific platform capabilities by tier.

### 10.7 `@kuanyin/dharma-analytics` (5 modules)

The 5 modules cover measurement and reporting: `community-health-metrics`,
`individual-dharma-path`, `predictive-wellness`, `wisdom-reports`, and
`moderation-transparency`.

### 10.8 `@kuanyin/cross-domain` (5 modules)

The 5 modules provide domain-specific ethics integration:
`aphrodite-integration`, `lilith-integration`, `hathor-integration`,
`yemaya-integration`, and `platform-wide-integration`. Each integration module
defines domain-prefixed literal unions (e.g. `LilIntegSeverityLevel`,
`LilIntegEmotionalState`, `LilIntegShadowWorkPhase`) and integration helper
functions, with snapshot/reset/integrity utilities per module. The domain-prefix
naming ensures that cross-domain types do not collide with the foundation
taxonomy.

### 10.9 `@kuanyin/ai-ml-models` (6 modules)

The 6 modules describe the AI/ML models that power the feature libraries:
`intent-classification`, `emotional-state-detection`, `harm-potential-scoring`,
`cognitive-reframing`, `behavioral-pattern`, and `community-health-model`.
Modules describe model architecture, training, calibration, and inference as
typed records (e.g. `IntentClassArchitectureRecord`,
`IntentClassInferenceRecord`, `IntentClassCalibrationRecord`) with
`inferenceLatencyMs` and related parameter types.

### 10.10 `@kuanyin/ui-components` (5 modules)

The 5 modules provide UI component descriptors for each major UI surface:
`mindful-friction-components`, `performer-dashboard-components`,
`rehabilitation-journey-components`, `merit-karma-components`, and
`analytics-dashboard-components`.

---

## 11. Competitive-Salt & Rage-Quit Cascade Class (V2 Consumer)

The V2 competitive product (ranked matches, Battle Hub crews, factions,
tournaments, and replay sharing) puts Kuanyin moderation under a failure mode
that does not exist in non-competitive chat: **competitive salt**. Salt is the
spike of frustration, blame, and aggression that follows a loss, a disconnect, a
perceived unfair matchup, or a controversial tournament result. Left untreated
it cascades — one salty player provokes the lobby, the lobby brigades the
opponent's replay, the rivalry hardens into targeted harassment, and a crew or
faction mobilizes around the grudge.

This class is **distinct from generic toxicity**. A generic toxicity model reads
"you're trash, uninstall" as harassment and applies a uniform sanction. That is
wrong for competitive contexts in two opposite directions at once: the same
words exchanged as ritual trash-talk between consenting rivals are _less_
harmful than the model assumes, while the same words aimed at a specific player
across multiple matches, or coordinated by a crew against one target, are _more_
harmful. The competitive-salt class therefore re-weights severity by match
context (the dampener) and by cross-match / cross-crew persistence (the
amplifier), and it adds a disconnect-attribution layer so that players are never
punished for losses caused by infrastructure rather than rage.

This section specifies the consumer-facing contract for that class. Kuanyin owns
the implementation; the forthcoming work is tracked as unchecked items in §
11.10. The class is built on the existing foundation taxonomy (§ 3.2),
precognition scoring, the mindful-friction patterns (§ 3.8, § 13.2), the
restorative remedy ladder in `@kuanyin/rehabilitation`, and the cross-domain
signals `@nous/safety` (cheat / anomaly verdicts) and `@themis/accountability`
(strikes, sanctions, and appeal-linked records). It feeds the V2 anti-cheat
classifier service (`@v2/nous-anti-cheat-classifiers`) and the dispute flows in
§ 13.5, but never gates match outcomes: like every V2 Kuanyin surface it is
`offRollback: true` / `mayInfluenceRollback: false` and has
`deterministicImpact: 'none'` on competitive results.

### 11.1 Competitive harm-category codes

The class extends the foundation `HarmCategoryCode` union (§ 3.2) with ten
competition-specific codes rather than reusing generic interpersonal codes. Each
carries the same `HarmCategory` metadata (`domain`, `severity`,
`requiresImmediateAction`, `rehabilitationEligible`, `compassionateFraming`,
`underlyingSuffering`, `transformativePotential`), so existing intervention and
rehabilitation machinery applies without a parallel taxonomy:

| Code                       | Domain        | What it captures                                                                                                                                                 |
| -------------------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `salt_threat`              | safety        | Post-loss message containing a threat ("I'll find you", "you're dead next queue") rather than mere insult.                                                       |
| `salt_targeted_harassment` | interpersonal | Salt aimed repeatedly at one named opponent across matches, distinct from in-match trash-talk.                                                                   |
| `rage_quit_pattern`        | disruption    | A pattern of abandoning matches to deny opponents a clean win or to grief teammates (see § 11.2 for the attribution gate).                                       |
| `boost_collusion`          | integrity     | Two or more accounts arranging wins/losses to inflate rank.                                                                                                      |
| `sandbagging`              | integrity     | Deliberately losing or under-performing to manipulate matchmaking rating.                                                                                        |
| `griefing_match`           | disruption    | In-match sabotage of teammates (feeding, blocking objectives, friendly interference).                                                                            |
| `replay_brigade`           | platform      | Coordinated mass-reporting, downvoting, or comment-flooding of an opponent's replay or profile.                                                                  |
| `tournament_collusion`     | integrity     | Pre-arranged results, soft-throwing, or prize-splitting deals inside a bracket.                                                                                  |
| `salt_chat`                | interpersonal | Generalized post-match venting in lobby/crew chat that is heated but not yet targeted; the lowest tier, usually routed to mindful friction rather than sanction. |
| `mirror_taunting`          | interpersonal | Mimicking, emote-spamming, or BM ("bad manners") rituals used to provoke; context-sensitive because it is consensual between some rivals.                        |

`salt_chat` and `mirror_taunting` are intentionally low-severity and
rehabilitation-eligible; `salt_threat`, `boost_collusion`, `sandbagging`, and
`tournament_collusion` carry `requiresImmediateAction` and route to human review
through the audit publication path in § 13.7.

### 11.2 Rage-quit cascade detector and disconnect attribution

The hardest correctness requirement of the class is **not punishing players for
disconnects they did not cause**. A naive rage-quit detector that counts early
match exits will sanction players whose ISP dropped, whose console crashed, or
who were kicked by a V2 server fault — exactly the players who are already
frustrated by an unfair loss. The detector therefore runs every candidate
early-exit through a disconnect-attribution classifier _before_ any
`rage_quit_pattern` code is assigned.

Attribution categories (each produces an evidence-backed verdict, not a guess;
infrastructure causes suppress the harm code entirely and instead credit a
loss-forgiveness / rank-protection signal):

- **ISP outage attribution** — correlated packet loss / RTT collapse on the
  player's connection consistent with carrier-side failure; corroborated by
  other players on the same ASN disconnecting in the same window.
- **VPN / proxy interruption attribution** — tunnel renegotiation or relay
  failure on a declared VPN/proxy path, distinguished from a deliberate pull of
  the cable.
- **Platform / hardware crash attribution** — client crash dump, GPU/driver
  fault, or thermal shutdown reported by the V2 client before the socket closed.
- **V2 server-side outage attribution** — the player's region/shard reported
  degraded health; the loss is voided platform-wide, never charged to the
  player.
- **Match-server crash attribution** — the specific game server instance
  faulted; all participants are credited and no rage-quit code is assigned to
  anyone.
- **Anti-cheat false-flag rebound** — `@nous/safety` later retracts a kick that
  ejected the player; the resulting early exit is reattributed to the platform
  and any provisional strike in `@themis/accountability` is reversed.
- **Opposing-peer disconnect** — in peer-hosted or P2P-influenced modes, the
  host or opposing peer dropped; the remaining player is not blamed for the
  resulting no-contest.
- **Wi-Fi flake** — a short, self-recovering wireless dropout (single-client RTT
  spike with fast recovery), treated as best-effort forgiven rather than
  intentional abandonment.
- **Power loss** — abrupt total loss of client heartbeat with no graceful
  shutdown, consistent with a power cut rather than a quit-to-menu.

Only after every attribution category returns "not infrastructure" does the
detector evaluate the behavioral pattern (repeated exits at losing positions,
exits timed to deny opponent rewards, exits correlated with salt chat) and
assign `rage_quit_pattern` with a confidence. Genuine rage-quits route to the
restorative remedy ladder in § 11.3; infrastructure disconnects are logged for
the player's loss-forgiveness ledger and never to their violation history.

### 11.3 Restorative remedy ladder

Competitive-salt outcomes use the same compassionate, non-punitive-first
philosophy as the rest of Kuanyin, implemented as a graduated ladder in
`@kuanyin/rehabilitation`:

1. **Cool-down + mindful friction** — `salt_chat` / `mirror_taunting` and a
   first `rage_quit_pattern` get a pre-send pause (§ 13.4) and a short ranked
   cool-down, not a strike.
2. **Reflection + acknowledgement** — repeated salt prompts a reflection task
   and an acknowledgement-of-impact step before requeue.
3. **Restorative micro-circle** — for `salt_targeted_harassment` between a
   stable rivalry, an opt-in restorative exchange (gated by the § 12 safety
   pre-flight, `moderation_appeal` circle kind) precedes any sanction.
4. **Sanction with appeal** — only integrity codes (`boost_collusion`,
   `sandbagging`, `tournament_collusion`) and `salt_threat` escalate directly to
   sanction, which is always appealable through the dispute flow in § 13.5.

### 11.4 Severity dampener and platform amplifier

The dampener and amplifier are two pure scoring adjustments layered onto the
precognition harm score before an intervention is chosen. They are what make the
competitive-salt class context-aware instead of a blunt toxicity filter:

- `competitiveContextDampener` — reduces severity when the exchange is
  symmetric, consensual, in-match-only, and between rivals with no prior
  targeting history (classic GG/BM banter). It can lower but never raise the
  base score.
- `platformContextAmplifier` — raises severity when the same actor's salt
  persists across matches against the same target, is echoed by crew/faction
  members (linking to the raid-defense signals in § 13.3), or attaches to a
  `replay_brigade`. It can raise but never silently clear the base score.

The two are applied in sequence and clamped to the foundation severity range so
that the dampener cannot mask a genuine `salt_threat` and the amplifier cannot
manufacture harm where none is targeted. Sections 11.5–11.8 are reserved for the
per-mode calibration tables (ranked, casual, tournament, crew) once the
classifier ships.

### 11.9 EU AI Act Model Card

The competitive-salt classifier is a regulated automated content-moderation
system under the EU AI Act and the DSA. A Model Card must be published and kept
current, covering: training-data provenance and the consented trash-talk corpus
used to calibrate the dampener; measured precision/recall per harm-category code
in § 11.1; the disconnect-attribution false-suppression and false-punishment
rates from § 11.2; the human-review routing thresholds; and the appeal path. The
card is published through the audit-platform path in § 13.7 so that every model
version is retained and exportable by Oshun for regulators.

### 11.10 V2 reciprocal task tracker

The contract above is specified; the implementation is Kuanyin-owned and
forthcoming. These items remain open and are the authoritative backlog for the
class — they are intentionally left unchecked until the code, tests, and Model
Card land:

- [ ] Add competitive harm-category codes per § 11.1 to `kuanyin-foundation`.
- [ ] Implement competitive-context severity dampener + platform amplifier per §
      11.4 in `@kuanyin/precognition`, with `competitiveContextDampener`
      lowering severity for consensual ritual trash-talk and
      `platformContextAmplifier` raising it for cross-match / cross-crew
      targeting.
- [ ] Implement rage-quit cascade detector per § 11.2 with full false-positive
      suppression across all nine disconnect-attribution categories so no player
      is sanctioned for ISP, VPN, hardware, server, peer, Wi-Fi, or power
      failures.
- [ ] Implement restorative remedy ladder in `@kuanyin/rehabilitation` per §
      11.3, reusing the § 12 restorative-circle safety pre-flight.
- [ ] Extend mindful-friction beyond the V2 pre-send adapter in § 13 to the full
      competitive cool-down + reflection flow described in § 11.3.
- [ ] Extend performer-protection to in-game NPC + licensed-fighter likeness
      coverage for salt aimed at licensed athletes, per § 13.6.
- [ ] Publish EU AI Act Model Card for the classifier per § 11.9 through
      `@oshun/audit-platform` so every model version is retained and exportable.

---

## 12. Concordia Restorative Adapter (`@kuanyin/concordia-restorative`)

`@kuanyin/concordia-restorative` (Phase 179.7.3) is the only Kuanyin library
built with `@nx/js:tsc` and the only one with Zod and `@concordia/contracts`
dependencies. Its single module `circle-safety.ts` enforces a restorative-
circle safety pre-flight checklist, ensuring that circles open only when all
required safety conditions have been verified.

### 12.1 Zod Schemas and Types

All types in this module are defined with Zod schemas for runtime validation, in
addition to TypeScript static types. This is the only Kuanyin module with
runtime input validation; the others use the foundation's internal schema
system.

The core Zod schemas:

- `CircleKindSchema` — seven circle kinds: `community_harm_repair`,
  `moderation_appeal`, `performer_protection`, `creator_protection`,
  `platform_reintegration`, `school_or_youth_program`, and
  `workplace_restorative`.
- `SafetyCheckSchema` — eleven safety checks:
  `harmed_party_consents_to_participate`, `responsible_party_acknowledges_harm`,
  `no_immediate_danger_present`, `no_active_restraining_order_violated`,
  `power_imbalance_assessed`, `trained_facilitator_engaged`,
  `language_accessibility_confirmed`, `trauma_informed_plan_documented`,
  `child_safety_review_passed`, `guardian_or_representative_linked`, and
  `safety_precautions_active`.
- `SafetyCheckStatusSchema` —
  `not_started | in_progress | passed | failed | not_applicable`.
- `CircleSafetyChecklistSchema` — `{ caseId, circleKind, checks[], updatedAt }`.

### 12.2 Required Checks and Opening Decision

`REQUIRED_CHECKS_BY_KIND` (frozen) maps each circle kind to its mandatory
checks. Different circle kinds require different subsets: `moderation_appeal`
requires four checks; child- and workplace-oriented circles require additional
gates (`child_safety_review_passed`, `guardian_or_representative_linked`,
`no_active_restraining_order_violated`) beyond the base requirements.

The public API for this module consists of four functions:

1. **`requiredChecksForCircleKind(kind)`** — returns the required checks for a
   given circle kind.
2. **`canOpenCircle(checklist)`** — returns `{ ok: true, note }` only when every
   required check is `passed`; otherwise returns
   `{ ok: false, missing, failed }` listing checks that are missing/in-progress
   and checks that failed. Keeps the circle closed until all gates pass.
3. **`startSafetyChecklist({ caseId, circleKind, now })`** — builds a starter
   checklist with every required check initialized to `not_started`.
4. **`recordCheckStatus(checklist, check, status, now, note?)`** — records a
   check's status, adding it if absent, and returns an updated checklist.

---

## 13. V2 Cross-Domain Contracts

The V2 competitive product consumes the Kuanyin libraries through thin binding
services under `V2/services/`. Each service is a deterministic composition
surface over a source-of-truth `@kuanyin/*` (or peer-domain) library: it adds no
new domain logic, declares its source package explicitly, and is marked
`offRollback: true` / `mayInfluenceRollback: false`. The subsections below are
the consumer-facing contracts that bind those services to the Kuanyin domain.
They are reciprocal references — the binding code, tests, and integration docs
live in `V2/`, and the substantive behavior lives in the libraries documented
above.

### 13.1 V2 Community Harmony Contract

**`@v2/kuanyin-community-harmony`** binds `@kuanyin/community-harmony` to the
three V2 social surfaces — `crew, faction, and Battle Hub`. The
`buildV2KuanyinCommunityHarmonySurface` entry point aggregates sentiment, scores
emotional temperature, detects tension and faction formation, measures
polarization, and tracks topic sensitivity, then chooses interventions (cooling
periods, topic quarantine, moderator/manager alerts) from the community-harmony
modules in § 10.3.

The contract additionally provides **raid defense**: traffic-spike,
new-account-flood, coordinated-messaging, cross-platform-coordination, and
shared-talking-point detectors feed a composite `raidSeverityScore` that can
activate defense mode, throttle new users, restrict posting, and — above a
surface-specific threshold — enable trusted-only mode, then document the raid
and run the recovery / reassurance / platform-report protocol. Because the
surface is community trust-and-safety only, it stays off rollback and has
`deterministicImpact: 'none'` on competitive results.

### 13.2 V2 First-Line Moderation Contract

**`@v2/kuanyin-first-line-moderation`** makes `@kuanyin/precognition` and
`@kuanyin/foundation` the _first line_ of text moderation for V2 chat, reports,
replay transcripts, names, and UGC captions. The legacy text vendors `Two Hat`
and `Community Sift` are fully retired (`twoHatAllowed: false`,
`communitySiftAllowed: false`); `buildV2KuanyinFirstLineModerationSurface`
classifies intent, scores harm potential, identifies the target, classifies
urgency, and detects coded language entirely through the Kuanyin libraries.

`Hive AI` and `AWS Rekognition` are retained **only as media fallback** for
image/video coverage gaps that the text-first Kuanyin pipeline cannot evaluate;
they never run on text. If Kuanyin text classification is unavailable the
surface degrades to `manual-review-no-text-fallback` (human review) rather than
silently reinstating a legacy vendor. Final moderation decisions are published
to the audit platform (§ 13.7).

### 13.3 V2 Pre-Send Mindful Friction Contract

**`@v2/kuanyin-mindful-friction`** binds `@kuanyin/mindful-friction` as a
_pre-send_ compassion layer in front of two surfaces: `flagged_content` (a
flagged outbound message) and `report_submitted` (a player report). Before a
flagged message sends, `buildV2KuanyinMindfulFrictionPreSendSurface` selects a
personalized gate, builds a breath-pause overlay, generates reflection questions
and a micro-compassion prompt, and offers a tone-preserving rewrite. When
pause-frequency limits are reached it switches to `passive-monitoring` instead
of stacking pauses, so friction never becomes punishment. The surface is
advisory and stays off rollback even when it recommends human review. The
competitive cool-down + reflection flow in § 11.3 extends this same adapter.

### 13.4 V2 Performer Protection Contract

**`@v2/kuanyin-performer-protection`** binds `@kuanyin/performer-protection` to
shield licensed fighters, creators, and commentary subjects on V2 chat, replay
comment, creator-suite upload, and commentary-mention surfaces. It
cross-references the Themis NIL ledger package `@themis/likeness` **without
taking a package dependency** on it: the request carries a Themis NIL ledger
stamp with `rightsManifestSha256`, `consentChainRefs`, allowed-use list, and a
`revocationEventType` of `themis.license.revoked`. The surface verifies the
manifest hash against the stamp, honors revoked/expired/paused license status,
and — when a likeness gate fails — sets `blocksBellonaCook: true` so a revoked
or mismatched likeness cannot be cooked into downstream Bellona assets. Allowed
likeness mentions pass through and stay off rollback.

### 13.5 V2 Dispute Resolution Contract (Themis)

The competitive-salt sanctions in § 11.3 and the moderation decisions in § 13.2
are appealable through **`@v2/themis-dispute-resolution`**, the V2 binding over
`@themis/dispute-resolution`. It issues a machine-readable DSA
`Statement-of-Reasons` for each adverse action, opens moderation appeals on a
seven-day Themis SLA, and routes tournament-result disputes to an auditor-backed
challenge review with a provisional result hold. Kuanyin emits the moderation
outcome and statement-of-reasons inputs; Themis owns the appeal and
tournament-dispute flows. The dispute surface is governance/audit only and stays
off rollback.

### 13.6 V2 Concordia Substrate Contract

Higher-stakes Kuanyin outcomes — anti-cheat appeals, tournament-result disputes,
and crew conflicts — can be mediated through the shared Concordia substrate
composed by **`@v2/concordia-substrate`**. The substrate wires the Nous
cooperative-bargaining, preference-inference, and agreement-search primitives
together with sealed private-party memory from `@nous/concordia-sealed-memory`,
appellant/arbiter dialogue scaffolding from `@iris/concordia-assistant`, event
routing through `@oshun/concordia-integration`, and the Kuanyin restorative
branch (`@kuanyin/concordia-restorative`, § 12) that stays closed until the
safety pre-flight passes. External exposure of the substrate is flag-gated
through `@oshun/config` (`ENABLE_V2_CONCORDIA_SUBSTRATE`) so it remains internal
until launch readiness. The composition is privacy-projected and off rollback.

### 13.7 V2 Audit Publication Contract (Oshun)

All V2 moderation, anti-cheat, and DSR outcomes are published to the canonical
audit platform through **`@oshun/audit-platform`** (the `v2-audit-publication`
entry point). The division of responsibility is fixed: **V2 publishes** the
canonical event (`v2.moderation.decision_published`,
`v2.anti_cheat.review_published`, `v2.dsr.workflow_published`) and **Oshun
retains and exports** it for investigations and regulators, under per-kind
retention tags. Concretely, the Kuanyin first-line moderation surface (§ 13.2)
publishes `moderation` decisions, the Nous anti-cheat classifier publishes
`anti-cheat` reviews (with `automatedDisciplineAllowed: false`), and the Themis
privacy router publishes `DSR` (data-subject-request) workflows. The
competitive-salt Model Card in § 11.9 is published through the same path so
every classifier version is retained and exportable.

---

## 14. Acceptance Criteria

A change to the Kuanyin domain is acceptable when all of the following
conditions are met:

1. All affected libraries pass `nx build`, `nx lint`, `nx test`, and
   `nx typecheck` (or the worktree-safe `npx tsc --noEmit` / `npx vitest run`
   equivalents).
2. New domain objects use `readonly` fields and literal-union types consistent
   with the patterns in `foundation/src/types.ts`.
3. New configuration is registered in a `Map` store with a matching snapshot and
   is restored by the relevant `reset*Stores()` function.
4. New environment variables are added to `env-schema.ts` with a category,
   `required` flag, default, sensitivity flag, and validation schema.
5. New harm categories, intents, intervention types, or events extend the
   existing unions rather than introducing parallel taxonomies.
6. Tests assert specific computed values, not just shape or truthiness.

---

## 15. Planned Work

The following is described in the domain backlog but is **not yet present** in
`libs/kuanyin/`:

- **Full Concordia restorative-mediation integration** `(planned, Phase 179)` —
  Beyond the `circle-safety` pre-flight, the broader restorative-mediation flow
  (apology, restitution, no-contact boundaries, content-takedown timelines,
  monitoring windows, recurrence measurement, and safe escalation) is planned.
  `@kuanyin/concordia-restorative` currently ships only the `moderation_appeal`
  and related circle-kind safety checklists.
- **Live service deployment** `(planned)` — The data layer is currently
  in-memory `Map` stores; a PostgreSQL-backed runtime and the API server implied
  by `KUANYIN_API_PORT` are not wired up in this tree.
- **Multimodal harm-detection model surface** `(planned, Phase 32.18.1)` —
  Image, video, and audio classifiers feeding the same harm-category taxonomy
  and severity model as the text pipeline, with per-modality calibration and the
  same fairness/adversarial evaluation requirements as the text models.
- **Federated learning** `(planned, Phase 32.18.5)` — Privacy-preserving
  federated training across platforms/tenants for harm-detection models:
  on-tenant gradient computation, secure aggregation, and differential-privacy
  budgets, so raw user content never leaves its platform boundary.
- **Moderator/facilitator wellness instrumentation** `(planned, Phase 32.19.1)`
  — Exposure budgets, rotation schedules, decompression windows, and
  burnout-trajectory metrics for human reviewers and restorative-circle
  facilitators.
- **External toxicity-scoring and bridging attributes**
  `(planned, Phase 32.19.4)` — Google Perspective API attribute integration and
  bridging-based ranking signals that reward divide-bridging content.
