Comprehensive development guide for the Kuanyin (Ethics/Harm Prevention) domain libraries.
This guide covers local development setup, building, testing, debugging, and common development tasks for all 10 Kuanyin libraries.
Prerequisites#
Required Software#
| Tool | Version | Purpose |
|---|---|---|
| Node.js | >= 20.0 | JavaScript runtime |
| pnpm | >= 10.0 | Package manager |
| Nx | (via pnpm) | Monorepo task runner |
| PostgreSQL | 15+ | Required for kuanyin-database development |
Installation#
# From the repository root
pnpm install
Database Setup (for kuanyin-database development)#
The kuanyin-database library defines schemas, migrations, and repositories
that require a running PostgreSQL instance:
# Start the development PostgreSQL instance
docker compose -f docker/docker-compose.dev.yml up -d
# Connection: postgresql://oshun:oshun_dev@localhost:5432/oshun_dev
For all other Kuanyin libraries (foundation, precognition, mindful-friction, etc.), no database or external services are required.
Project Structure#
All Kuanyin libraries live under libs/kuanyin/:
libs/kuanyin/
foundation/ kuanyin-foundation Core types and utilities
database/ kuanyin-database Schemas, migrations, repositories
precognition/ kuanyin-precognition Predictive harm detection (6 modules)
community-harmony/ kuanyin-community-harmony Community health (5 modules)
mindful-friction/ kuanyin-mindful-friction Intentional friction patterns (6 modules)
performer-protection/ kuanyin-performer-protection Creator safety (6 modules)
rehabilitation/ kuanyin-rehabilitation Rehabilitation pathways (6 modules)
merit-karma/ kuanyin-merit-karma Merit and karma systems (5 modules)
dharma-analytics/ kuanyin-dharma-analytics Community metrics (5 modules)
cross-domain/ kuanyin-cross-domain Cross-domain ethics integration (5 modules)
Important: Kuanyin uses Nx project names without the @ scope prefix (e.g.,
kuanyin-foundation not @kuanyin/foundation). However, the npm package names
in package.json use the @kuanyin/ scope. When running Nx commands, use the
project name from project.json.
Library Dependency Graph#
kuanyin-foundation (types, constants, utilities, errors)
|
+-- kuanyin-database (schemas, migrations, repos, seeds)
| |
| +-- kuanyin-precognition (predictive harm detection)
| +-- kuanyin-community-harmony (community health)
| +-- kuanyin-mindful-friction (intentional friction)
| +-- kuanyin-performer-protection (creator safety)
| +-- kuanyin-rehabilitation (rehabilitation pathways)
| |
| +-- kuanyin-merit-karma (merit and karma)
| +-- kuanyin-dharma-analytics (analytics)
| |
| +-- kuanyin-cross-domain (platform-wide integration)
Per-Library File Layout#
libs/kuanyin/{library}/
src/
index.ts Public API barrel export
{module}.ts Module implementation
{module}.spec.ts Module tests
package.json
project.json
tsconfig.json
tsconfig.lib.json
tsconfig.spec.json
vitest.config.ts
Building Libraries#
Build a Single Library#
pnpm nx build kuanyin-foundation
pnpm nx build kuanyin-database
pnpm nx build kuanyin-precognition
pnpm nx build kuanyin-mindful-friction
pnpm nx build kuanyin-performer-protection
pnpm nx build kuanyin-rehabilitation
pnpm nx build kuanyin-merit-karma
pnpm nx build kuanyin-dharma-analytics
pnpm nx build kuanyin-cross-domain
pnpm nx build kuanyin-community-harmony
Build All Kuanyin Libraries#
pnpm nx run-many --target=build --projects=tag:scope:kuanyin
Build Configuration#
Kuanyin uses @nx/esbuild:esbuild for all libraries (not @nx/js:tsc):
| Setting | Value |
|---|---|
| Executor | @nx/esbuild:esbuild |
| Output format | ESM (format: ["esm"]) |
| Bundling | Disabled (bundle: false) |
| Output path | dist/libs/kuanyin/{library}/ or libs/kuanyin/{library}/dist/ |
The esbuild executor provides faster builds compared to @nx/js:tsc. Output is
unbundled ESM, meaning each source file is compiled individually.
Type Checking#
In addition to the standard build, lint, and test targets, all Kuanyin
libraries include an explicit typecheck target that runs tsc --noEmit:
pnpm nx typecheck kuanyin-foundation
pnpm nx typecheck kuanyin-precognition
pnpm nx typecheck kuanyin-cross-domain
This is separate from the build step because esbuild does not perform type checking. Always run typecheck before committing changes to catch type errors that esbuild would silently ignore.
Run Typecheck Across All Libraries#
pnpm nx run-many --target=typecheck --projects=tag:scope:kuanyin
Testing#
Run Tests for a Single Library#
pnpm nx test kuanyin-foundation
pnpm nx test kuanyin-database
pnpm nx test kuanyin-precognition
pnpm nx test kuanyin-mindful-friction
pnpm nx test kuanyin-performer-protection
Run All Kuanyin Tests#
pnpm nx run-many --target=test --projects=tag:scope:kuanyin
Test Configuration#
All libraries use Vitest via the @nx/vite:test executor:
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'node',
root: __dirname,
passWithNoTests: true,
},
});
Key differences from other domains:
passWithNoTests: trueis set on the foundation library's vitest config, allowing the test target to pass even when no tests exist yetroot: __dirnameexplicitly sets the test root
Test Count#
The domain has 52 test files across all 10 libraries. Each module typically has
a dedicated spec file. For example, kuanyin-precognition has 6 spec files:
intent-analysis.spec.ts, cascade-prediction.spec.ts,
typing-dynamics.spec.ts, context-awareness.spec.ts,
behavioral-patterns.spec.ts, and emotional-detection.spec.ts.
Running Tests with Coverage#
pnpm nx test kuanyin-precognition -- --coverage
Writing Tests#
Kuanyin tests focus on safety-critical behavior. Tests should cover edge cases thoroughly:
import { describe, it, expect } from 'vitest';
import { analyzeIntent, IntentAnalysisResult } from './intent-analysis.js';
describe('Intent Analysis', () => {
describe('analyzeIntent', () => {
it('should detect threatening language', () => {
const result = analyzeIntent({
message: 'test threatening content',
context: { conversationHistory: [] },
});
expect(result.severity).toBe('high');
expect(result.category).toBe('threats_violence');
});
it('should recognize benign content', () => {
const result = analyzeIntent({
message: 'hello, how are you?',
context: { conversationHistory: [] },
});
expect(result.severity).toBe('negligible');
});
it('should handle empty input gracefully', () => {
const result = analyzeIntent({
message: '',
context: { conversationHistory: [] },
});
expect(result.severity).toBe('negligible');
});
});
});
Testing Safety-Critical Code#
For harm detection and classification modules, always test:
- True positives - harmful content is correctly identified
- True negatives - benign content is not falsely flagged
- Edge cases - ambiguous content, empty input, Unicode, mixed languages
- Severity levels - correct severity assignment across all 6 levels
- Category coverage - all 50+ harm categories are testable
Linting#
# Lint a single library
pnpm nx lint kuanyin-foundation
# Lint all Kuanyin libraries
pnpm nx run-many --target=lint --projects=tag:scope:kuanyin
Common Development Tasks#
Adding a New Module to an Existing Library#
For example, adding a new empathy-mapping module to
kuanyin-mindful-friction:
- Create
libs/kuanyin/mindful-friction/src/empathy-mapping.ts - Create
libs/kuanyin/mindful-friction/src/empathy-mapping.spec.ts - Export from
libs/kuanyin/mindful-friction/src/index.ts:
export * from './empathy-mapping.js';
- Verify:
pnpm nx build kuanyin-mindful-friction
pnpm nx test kuanyin-mindful-friction
pnpm nx typecheck kuanyin-mindful-friction
pnpm nx lint kuanyin-mindful-friction
Adding a New Kuanyin Library#
- Create the directory structure under
libs/kuanyin/{new-lib}/ - Create
project.jsonusing the esbuild executor:
{
"name": "kuanyin-{new-lib}",
"sourceRoot": "libs/kuanyin/{new-lib}/src",
"projectType": "library",
"tags": ["scope:kuanyin", "layer:domain"],
"targets": {
"build": {
"executor": "@nx/esbuild:esbuild",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/libs/kuanyin/{new-lib}",
"main": "libs/kuanyin/{new-lib}/src/index.ts",
"tsConfig": "libs/kuanyin/{new-lib}/tsconfig.lib.json",
"assets": [],
"format": ["esm"],
"bundle": false
}
},
"test": {
"executor": "@nx/vite:test",
"outputs": ["{workspaceRoot}/coverage/libs/kuanyin/{new-lib}"],
"options": {
"config": "libs/kuanyin/{new-lib}/vitest.config.ts"
}
},
"lint": {
"executor": "@nx/eslint:lint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": ["libs/kuanyin/{new-lib}/**/*.ts"]
}
},
"typecheck": {
"executor": "nx:run-commands",
"options": {
"commands": [
"tsc --noEmit --project libs/kuanyin/{new-lib}/tsconfig.lib.json"
]
}
}
}
}
- Create
package.json:
{
"name": "@kuanyin/{new-lib}",
"version": "0.1.0",
"private": true,
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"devDependencies": {
"vitest": "catalog:"
}
}
- Run
pnpm install.
Adding a New Harm Category#
When extending the harm classification system:
- Add the new
HarmCategoryCodevariant inlibs/kuanyin/foundation/src/types.ts:
export type HarmCategoryCode =
// ... existing categories
'new_harm_category';
- Add severity and domain mapping in the constants file
- Update all detection modules that need to handle the new category
- Add tests for the new category across relevant modules
Implementing Cross-Domain Integration#
When adding Kuanyin ethics to a new Oshun domain:
- Create a new integration module in
libs/kuanyin/cross-domain/src/:
// {domain}-integration.ts
export interface DomainEthicsConfig {
enableContentModeration: boolean;
enablePerformerProtection: boolean;
severityThreshold: HarmCategorySeverity;
}
export function createDomainEthicsMiddleware(config: DomainEthicsConfig) {
// Implementation
}
- Export from
libs/kuanyin/cross-domain/src/index.ts - The consuming domain adds
@kuanyin/cross-domainas a dependency
Key Patterns and Conventions#
BuddhaNature Base Interface#
Every entity in the Kuanyin system implements the BuddhaNature interface:
interface BuddhaNature {
readonly id: string;
readonly compassionSeed: number;
readonly wisdomFactor: number;
readonly mindfulnessLevel: number;
readonly karmaBalance: number;
readonly innateGoodness: number;
readonly awakeningPotential: number;
readonly refugeStatus: RefugeStatus;
}
New entity types should extend this interface.
Severity Classification#
All harm assessments use the 6-level severity scale: negligible < low <
moderate < high < severe < critical
Functions that score content should return one of these levels. The numeric mapping is consistent across all libraries.
Harm Category Domains#
Harm categories are organized into 10 domains: interpersonal, identity,
safety, integrity, exploitation, manipulation, disruption, legal,
platform, systemic. New harm categories should be assigned to the
appropriate domain.
Buddhist-Informed Naming#
Module names draw from Buddhist terminology:
samma-vaca(Right Speech) in mindful-frictiondharma-analyticsfor community metricsmerit-karmafor reputation systemsrefuge-statusfor user progression stages
When naming new modules, prefer descriptive English names but consider Buddhist-inspired names where the concept maps directly to a Pali/Sanskrit term.
Compassionate Guardianship Principle#
Kuanyin's design philosophy is rehabilitation over punishment. When implementing moderation actions, always include:
- A path back (rehabilitation)
- An explanation (transparency)
- Proportional response (minimum necessary friction)
Debugging Tips#
esbuild vs tsc Type Checking#
Since Kuanyin uses esbuild (which strips types without checking them), you can
have a successful build with type errors. Always run typecheck in addition to
build:
pnpm nx build kuanyin-foundation # May succeed even with type errors
pnpm nx typecheck kuanyin-foundation # Will catch type errors
Import Path Extensions#
All imports must use .js extensions (ESM requirement):
// Correct
import { HarmCategoryCode } from './types.js';
// Incorrect
import { HarmCategoryCode } from './types';
Testing Scoring Functions#
Many Kuanyin modules compute scores (severity, merit, karma). When testing scoring functions, test boundary conditions:
describe('severityScoring', () => {
it('should handle minimum score', () => {
expect(scoreSeverity(0)).toBe('negligible');
});
it('should handle maximum score', () => {
expect(scoreSeverity(1.0)).toBe('critical');
});
it('should handle threshold boundaries', () => {
expect(scoreSeverity(0.2)).toBe('low');
expect(scoreSeverity(0.4)).toBe('moderate');
});
});
Foundation Type Changes#
Changes to kuanyin-foundation types propagate to all downstream libraries.
After modifying foundation types, run the full typecheck and test suite:
pnpm nx run-many --target=typecheck --projects=tag:scope:kuanyin
pnpm nx run-many --target=test --projects=tag:scope:kuanyin
Nx Project Name Lookup#
If you are unsure of a library's Nx project name, check the name field in its
project.json. For Kuanyin, the naming convention is kuanyin-{library}
without the @ prefix.
Project Configuration Reference#
Tags#
All Kuanyin libraries use: ["scope:kuanyin", "layer:domain"]
Executors#
| Target | Executor |
|---|---|
| build | @nx/esbuild:esbuild |
| lint | @nx/eslint:lint |
| test | @nx/vite:test |
| typecheck | nx:run-commands (tsc) |
Environment Variables#
For kuanyin-database development:
DATABASE_URL=postgresql://oshun:oshun_dev@localhost:5432/oshun_dev
No environment variables are needed for other Kuanyin libraries.
Related Documentation#
- Kuanyin Domain README - Domain overview, architecture, and library descriptions
- CLAUDE.md - Repository-wide development guidelines