# Themis Domain - Developer Guide

> Comprehensive development guide for the Themis governance, democracy, and
> compliance infrastructure domain.

---

## Prerequisites

### Required Software

| Tool       | Version | Purpose                                  |
| ---------- | ------- | ---------------------------------------- |
| Node.js    | >= 20.0 | Runtime for all Themis libraries         |
| pnpm       | >= 10.0 | Package manager (workspace protocol)     |
| Git        | >= 2.40 | Version control                          |
| TypeScript | ^6.0.3  | Compile-time type checking (via catalog) |

### Database Requirements

The `@themis/core` library includes a PostgreSQL database schema with migration
support. For development involving the persistence layer:

| Service    | Port | Purpose                                 |
| ---------- | ---- | --------------------------------------- |
| PostgreSQL | 5432 | Governance data storage (with pgvector) |

### Environment Variables

For database development, the following variables are used from the root `.env`:

```bash
# Database (required for @themis/core database features)
DATABASE_URL=postgresql://oshun:oshun_dev@localhost:5432/oshun_dev
```

No environment variables are required for building or unit-testing libraries
that do not touch the database layer.

---

## Project Structure

The Themis domain contains 32 libraries under `libs/themis/`. In addition to the
individual library directories, the domain has shared configuration files at the
domain root:

```
libs/themis/
  eslint.config.js         # Domain-wide ESLint config (extends monorepo base)
  prettier.config.js       # Domain-wide Prettier config (extends monorepo base)
  tsconfig.domain.json     # Domain-wide TypeScript settings
  vitest.shared.ts         # Shared Vitest base config for all Themis libraries

  accountability/          # Governance integrity, whistleblower, promise tracking
  ai/                      # AI governance agents: delegate, analyst, facilitator
  analytics/               # Voter behavior, proposal outcome, health analytics
  arbitration/             # Decentralized arbitration, mediation, escalation
  civic/                   # Digital democracy, e-government, elections, budgeting
  community/               # Association, housing, labor union, sports governance
  constitutions/           # Charter authoring, AI drafting, clause library, versioning
  core/                    # Foundation: data models, database, events, graph, types
  corporate/               # Board management, ESG compliance, proxy voting
  crisis/                  # Emergency powers, pandemic governance, resilience
  dao/                     # DAO lifecycle, delegation, proposals, quality gates
  decisions/               # MCDA, prediction markets, futarchy, quality tracking
  deliberation/            # Discussion platform, argument mapping, citizen assembly
  digital/                 # Platform governance, algorithmic accountability, AI oversight
  environmental/           # Climate governance, commons, intergenerational mechanisms
  frameworks/              # Direct/representative/liquid democracy, sociocracy, holacracy
  funding/                 # Quadratic funding, retroactive PGF, bonding curves
  identity/                # Decentralized identity, eligibility, sybil resistance
  integrations/            # Cross-domain bridges (Veritas, Aje, Maat, Lakshmi, etc.)
  international/           # UN/EU/AU governance, treaties, diplomacy, sovereignty
  justice/                 # Judicial systems, legal traditions, transitional justice
  knowledge/               # Political systems, governance theory, case studies
  nonprofit/               # B-Corp, cooperative, grant, fiscal sponsorship governance
  policy/                  # Computational law, policy analysis, simulation
  privacy/                 # MACI anti-collusion, ZK anonymous voting, private delegation
  reputation/              # Delegate scoring, EigenTrust reputation, participation analytics
  sectors/                 # Military, health, financial, urban, media governance
  simulation/              # Agent-based simulation, stress testing, constitutional design
  traditional/             # Indigenous governance, customary law, religious governance
  transparency/            # Campaign finance, audit trails, lobbying, public records
  treasury/                # Participatory budgeting, spending controls, fiscal dashboards
  voting/                  # Quadratic, ranked-choice, conviction, holographic, multi-sig
```

### Individual Library Layout

Each library follows a consistent structure:

```
libs/themis/<library>/
  package.json             # Name, version, ESM exports, dependencies
  project.json             # Nx config (build, lint, test, typecheck targets)
  tsconfig.json            # Extends domain tsconfig
  tsconfig.lib.json        # Library compilation config
  tsconfig.spec.json       # Test compilation config
  vitest.config.ts         # Imports from ../vitest.shared.ts
  src/
    index.ts               # Barrel export with module identifier constant
    <module>/
      index.ts             # Module barrel
      <file>.ts            # Implementation
      <file>.spec.ts       # Co-located tests
```

---

## Local Development Setup

### Initial Setup

```bash
# Clone the repository
git clone git@github.com:GreyChimp/oshun.git
cd oshun

# Install all dependencies
pnpm install
```

### Database Setup

The `@themis/core` library includes PostgreSQL migrations. To run them:

```bash
# Start PostgreSQL
docker compose -f docker/docker-compose.dev.yml up -d postgres

# Run migrations
pnpm nx db:migrate @themis/core

# Check migration status
pnpm nx db:migrate:status @themis/core

# Roll back the last migration
pnpm nx db:migrate:down @themis/core
```

---

## Building Libraries

### Build a Single Library

```bash
pnpm nx build @themis/core
```

### Build All Themis Libraries

```bash
pnpm nx run-many --target=build --projects=tag:scope:themis
```

### Build Configuration

The build executor is `@nx/js:tsc`. Each library's `project.json` specifies a
`rootDir` option pointing to its `src/` directory:

```json
{
  "build": {
    "executor": "@nx/js:tsc",
    "outputs": ["{options.outputPath}"],
    "options": {
      "outputPath": "dist/libs/themis/core",
      "main": "libs/themis/core/src/index.ts",
      "tsConfig": "libs/themis/core/tsconfig.lib.json",
      "assets": [],
      "rootDir": "libs/themis/core/src"
    }
  }
}
```

Build output goes to `dist/libs/themis/<library>/`.

### Typecheck Without Building

Themis libraries have a dedicated `typecheck` target:

```bash
pnpm nx typecheck @themis/voting
```

This runs `tsc --noEmit` against the library's `tsconfig.lib.json` without
producing output files, useful for rapid validation during development.

---

## Testing

### Run Tests for a Single Library

```bash
pnpm nx test @themis/core
```

### Run All Domain Tests

```bash
pnpm nx run-many --target=test --projects=tag:scope:themis
```

### Watch Mode

```bash
npx vitest --config libs/themis/voting/vitest.config.ts --watch
```

### Shared Vitest Configuration

Themis uses a domain-wide shared Vitest configuration at
`libs/themis/vitest.shared.ts`. Individual libraries import and extend this
base:

```typescript
import { defineConfig, mergeConfig, type UserConfig } from 'vitest/config';

const baseThemisVitestConfig = defineConfig({
  test: {
    globals: true,
    environment: 'node',
    include: ['src/**/*.{test,spec}.ts'],
    passWithNoTests: true,
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
      include: ['src/**/*.ts'],
      exclude: ['src/**/*.{test,spec}.ts', 'src/**/index.ts'],
    },
  },
});

export function defineThemisVitestConfig(
  overrides: UserConfig = {}
): UserConfig {
  return mergeConfig(baseThemisVitestConfig, overrides);
}
```

Key points:

- `passWithNoTests: true` allows libraries under active development to pass CI
  before tests are written
- Coverage excludes barrel `index.ts` files and test files themselves
- Individual libraries can override any setting by passing an overrides object

### Coverage

```bash
npx vitest --config libs/themis/voting/vitest.config.ts --coverage
```

Coverage output lands in `coverage/libs/themis/<library>/` as configured by the
`outputs` field in the test target.

### Testing Patterns

**Voting mechanism tests** should verify mathematical properties. For example,
quadratic voting tests should confirm that the cost scales with the square of
votes:

```typescript
describe('quadraticVoting', () => {
  it('costs 9 credits for 3 votes', () => {
    expect(calculateCost(3)).toBe(9);
  });
});
```

**Event sourcing tests** should verify that replaying an event stream produces
the expected state.

**Graph relationship tests** should validate that adding and querying edges in
the governance graph returns correct adjacency results.

---

## Linting and Formatting

### Lint a Single Library

```bash
pnpm nx lint @themis/voting
```

### Lint All Themis Libraries

```bash
pnpm nx run-many --target=lint --projects=tag:scope:themis
```

### Domain-Specific ESLint Rules

Themis has its own ESLint configuration at `libs/themis/eslint.config.js` that
extends the monorepo base and adds these rules:

- `@typescript-eslint/no-explicit-any` is set to `error` (no `any` allowed)
- `@typescript-eslint/consistent-type-imports` enforces `type` keyword for
  type-only imports using `inline-type-imports` style
- **Explicit `.js` extensions** are enforced on all relative ESM imports and
  exports via `no-restricted-syntax` rules

Example of a correct import:

```typescript
import { type GovernanceProposal } from './types/index.js';
```

### Formatting

Themis has a domain-specific Prettier config at `libs/themis/prettier.config.js`
that extends the monorepo base and enforces `trailingComma: 'all'` for Themis
files.

```bash
# Format a library's source
cd libs/themis/voting && pnpm format

# Check formatting without writing
cd libs/themis/voting && pnpm format:check
```

---

## Common Development Tasks

### Adding a New Library

1. Create the directory:

```bash
mkdir -p libs/themis/new-library/src
```

2. Create `project.json` with all four targets (build, lint, test, typecheck):

```json
{
  "name": "@themis/new-library",
  "$schema": "../../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "libs/themis/new-library/src",
  "projectType": "library",
  "tags": ["scope:themis", "type:lib", "layer:domain"],
  "implicitDependencies": ["@themis/core"],
  "targets": {
    "build": {
      "executor": "@nx/js:tsc",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/libs/themis/new-library",
        "main": "libs/themis/new-library/src/index.ts",
        "tsConfig": "libs/themis/new-library/tsconfig.lib.json",
        "assets": [],
        "rootDir": "libs/themis/new-library/src"
      }
    },
    "lint": {
      "executor": "@nx/eslint:lint",
      "outputs": ["{options.outputFile}"],
      "options": {
        "lintFilePatterns": ["libs/themis/new-library/**/*.ts"],
        "eslintConfig": "libs/themis/eslint.config.js"
      }
    },
    "test": {
      "executor": "@nx/vite:test",
      "outputs": ["{workspaceRoot}/coverage/libs/themis/new-library"],
      "options": {
        "configFile": "libs/themis/new-library/vitest.config.ts"
      }
    },
    "typecheck": {
      "executor": "nx:run-commands",
      "options": {
        "command": "tsc --noEmit -p libs/themis/new-library/tsconfig.lib.json"
      }
    }
  }
}
```

3. Create `package.json`:

```json
{
  "name": "@themis/new-library",
  "version": "0.1.0",
  "description": "Themis new-library module",
  "type": "module",
  "main": "./index.js",
  "module": "./index.js",
  "types": "./index.d.ts",
  "exports": {
    ".": {
      "types": "./index.d.ts",
      "import": "./index.js"
    },
    "./*": {
      "types": "./*.d.ts",
      "import": "./*.js"
    }
  },
  "files": ["dist", "src"],
  "scripts": {
    "build": "tsc -p tsconfig.lib.json",
    "test": "vitest run",
    "test:watch": "vitest",
    "lint": "eslint src --ext .ts",
    "typecheck": "tsc --noEmit",
    "format": "prettier --config ../prettier.config.js --write \"src/**/*.ts\"",
    "format:check": "prettier --config ../prettier.config.js --check \"src/**/*.ts\""
  },
  "dependencies": {
    "zod": "catalog:"
  },
  "devDependencies": {
    "@types/node": "catalog:",
    "typescript": "catalog:",
    "vitest": "catalog:"
  },
  "engines": {
    "node": ">=20"
  }
}
```

4. Create `src/index.ts` with the module identifier constant:

```typescript
export const themisNewLibraryModule = {
  name: '@themis/new-library',
} as const;

export * from './implementation/index.js';
```

5. Point the lint config to the domain-wide ESLint and use the shared Vitest
   config.

6. Run `pnpm install`.

### Adding Cross-Domain Integrations

The `@themis/integrations` library contains bridges to other Oshun domains. Each
integration is a sub-module:

```typescript
// libs/themis/integrations/src/index.ts
export * from './veritas-themis-intelligence-pipeline/index.js';
export * from './themis-aje-governance-execution-bridge/index.js';
```

When adding a new integration, declare the cross-domain dependency in
`implicitDependencies` in the project.json.

### Working with the Database Layer

`@themis/core` includes database migrations managed through custom CLI targets:

```bash
# Apply pending migrations
pnpm nx db:migrate @themis/core

# Check current migration status
pnpm nx db:migrate:status @themis/core

# Roll back the most recent migration
pnpm nx db:migrate:down @themis/core
```

The migration CLI is located at
`libs/themis/core/src/database/migrations/cli.ts` and is executed via `tsx`.

---

## Key Patterns and Conventions

### Module Identifier Constants

Every Themis library exports a module identifier constant and re-exports its
implementation:

```typescript
export const themisvotingModule = {
  name: '@themis/voting',
} as const;

export * from './universal-ballot-system/index.js';
export * from './delegation-engine/index.js';
// ...
```

This constant enables runtime identification of loaded modules.

### Domain-Wide TypeScript Configuration

Themis uses a shared `tsconfig.domain.json` at `libs/themis/` that extends the
monorepo base with stricter settings:

```json
{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "isolatedModules": true,
    "verbatimModuleSyntax": true
  }
}
```

Notable additions beyond the base config:

- `noUncheckedIndexedAccess` - Array/record access returns `T | undefined`
- `exactOptionalPropertyTypes` - `undefined` must be explicitly typed

### Tier Tags

In addition to the standard `scope:themis` tag, libraries use tier tags to
indicate their position in the architecture:

- `themis:tier:core` - Foundation layer (`@themis/core`)
- `themis:tier:decision` - Decision-making layer (`@themis/voting`,
  `@themis/decisions`, etc.)

### Dependency Graph

`@themis/core` is the foundation. Most libraries declare implicit dependencies:

```json
{
  "implicitDependencies": [
    "@themis/core",
    "@themis/identity",
    "@themis/reputation"
  ]
}
```

The `@themis/core` library depends on `zod` and `@oshun/database` as direct
dependencies. All other libraries depend on `@themis/core` implicitly or as a
peer.

### Event Sourcing Pattern

The `@themis/core` event system provides an event bus for governance actions.
Libraries publish events for governance state changes (proposal created, vote
cast, delegation changed) and consumers subscribe to build projections.

### Graph Structure

The `@themis/core` graph module models relationships between governance entities
(organizations, proposals, participants, delegations) as a directed graph,
enabling queries like "who delegated to whom" or "which proposals are blocked by
this vote."

---

## Debugging Tips

### TypeScript Path Resolution

Themis uses specific path mappings in `tsconfig.base.json`:

```json
{
  "@themis/*": ["libs/themis/*/src/index.ts"],
  "@themis/core": ["libs/themis/core/src/index.ts"],
  "@themis/core/*": ["libs/themis/core/src/*"]
}
```

The more specific `@themis/core` and `@themis/core/*` mappings take precedence
over the wildcard, allowing deep imports from core sub-modules.

### ESLint Extension Errors

If ESLint complains about missing `.js` extensions, remember that Themis
enforces explicit extensions for all relative imports and exports. This is
required for proper ESM resolution at runtime.

### Database Migration Failures

If migrations fail, check that PostgreSQL is running and the `DATABASE_URL` is
correct:

```bash
docker compose -f docker/docker-compose.dev.yml ps
```

To reset the database and reapply all migrations:

```bash
docker compose -f docker/docker-compose.dev.yml down -v
docker compose -f docker/docker-compose.dev.yml up -d postgres
pnpm nx db:migrate @themis/core
```

### Nx Cache Issues

```bash
pnpm nx reset
```

### Viewing the Dependency Graph

```bash
pnpm nx graph --focus=@themis/core
```

---

## Quick Reference

| Action                     | Command                                                       |
| -------------------------- | ------------------------------------------------------------- |
| Install dependencies       | `pnpm install`                                                |
| Build one library          | `pnpm nx build @themis/<lib>`                                 |
| Build all Themis libraries | `pnpm nx run-many --target=build --projects=tag:scope:themis` |
| Test one library           | `pnpm nx test @themis/<lib>`                                  |
| Test all Themis libraries  | `pnpm nx run-many --target=test --projects=tag:scope:themis`  |
| Lint one library           | `pnpm nx lint @themis/<lib>`                                  |
| Typecheck one library      | `pnpm nx typecheck @themis/<lib>`                             |
| Run database migrations    | `pnpm nx db:migrate @themis/core`                             |
| Check migration status     | `pnpm nx db:migrate:status @themis/core`                      |
| Reset Nx cache             | `pnpm nx reset`                                               |
| View dependency graph      | `pnpm nx graph --focus=@themis/core`                          |
