# Themis Domain — Architecture

---

## Overview

Themis is a **library-only domain** with 40 TypeScript libraries and no
standalone applications or services (no `apps/themis/`, no `services/themis/`).
It provides governance infrastructure at every scale and organizational form —
from small DAOs to nation-states, from corporate boards to citizen assemblies —
as consumable TypeScript modules.

The domain is uniquely broad in scope: it models governance as a universal
concern applicable to any organized human activity, not just Web3 DAOs or
political systems. The libraries cover cryptoeconomic mechanisms, indigenous
governance traditions, international institutions, corporate compliance, and
AI-assisted democratic deliberation — all built on a shared event-sourced data
model.

Because Themis is pure infrastructure, it has no HTTP API server and no
long-running process of its own. Consuming applications (a civic engagement app,
a DAO front-end, a corporate board platform) import the libraries they need, own
their own service topology, and are responsible for hosting the Kafka broker and
any scheduling. Themis contributes the database schema, event-sourcing logic,
and governance algorithms; the host application contributes the HTTP surface.

The domain also hosts an originality / IP-protection layer — the six
`@themis/*-shield` and `@themis/originality-shields` libraries — that acts as a
gatekeeping accept-gate for generated content. These are currently thin wrappers
over the `@concordia/contracts` originality-shield contract; the fuller
per-media detection systems are planned (TODO Phases 74–75).

---

## Domain Architecture

The diagram below shows the four conceptual layers. Data and control flow
upward: the Core layer is the sole source of truth for data models and the audit
log; the specialized domain libraries build on it; the AI layer orchestrates
across domain libraries; and the integrations layer surfaces Themis capabilities
to other Oshun domains.

```
+─────────────────────────────────────────────────────────────────────────+
│                        CROSS-DOMAIN INTEGRATIONS                        │
│                          @themis/integrations                           │
│   (Veritas, Aje, Maat, Lakshmi, Kuanyin, Iris, Sophia, Metis, Maya)      │
+─────────────────────────────────────────────────────────────────────────+
                                   |
+─────────────────────────────────────────────────────────────────────────+
│                           AI LAYER                                      │
│                           @themis/ai                                    │
│   (Autonomous delegate agent, proposal analyst, facilitator, advisor)   │
+─────────────────────────────────────────────────────────────────────────+
                                   |
+─────────────────────────────────────────────────────────────────────────+
│                       SPECIALIZED DOMAIN LIBRARIES                      │
│                                                                         │
│  DAO LAYER        DECISION LAYER        ACCOUNTABILITY LAYER            │
│  @dao             @voting               @accountability                  │
│  @constitutions   @deliberation         @transparency                   │
│  @treasury        @decisions            @privacy                        │
│  @funding         @reputation           @identity                       │
│                                                                         │
│  GOVERNANCE FORM LIBRARIES              ANALYTICS AND SIMULATION        │
│  @traditional  @digital  @international @analytics  @simulation         │
│  @justice  @arbitration  @corporate     @policy     @frameworks         │
│  @nonprofit  @community  @civic         @knowledge  @crisis             │
│  @sectors  @environmental                                               │
│                                                                         │
│  ADJUDICATION                 ORIGINALITY SHIELDS                        │
│  @academic-integrity          @originality-shields  @music-shield        │
│  @dispute-resolution          @visual-shield  @text-shield               │
│                               @video-shield  @design-shield             │
+─────────────────────────────────────────────────────────────────────────+
                                   |
+─────────────────────────────────────────────────────────────────────────+
│                            CORE LAYER                                   │
│                           @themis/core                                  │
│    (data models, event sourcing, graph structure, database schema)      │
+─────────────────────────────────────────────────────────────────────────+
```

---

## Library Organization

### Foundation: `@themis/core`

`@themis/core` is the root dependency for all Themis libraries — every other
package in the domain builds on it, either directly or transitively. It provides
four modules that together form the data backbone of the platform:

| Module     | Purpose                                                                                                                                                                                                                 |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `types`    | Governance entity Zod schemas: Organization, Charter, Member, Role, GovernanceIdentity, Delegation, Proposal, Vote, GovernanceFramework, Deliberation, Argument, CitizenAssembly, Dispute, Treasury, governance-metrics |
| `events`   | Hash-chained, Merkle-anchored event log — 126 typed event constants; per-organization advisory-locked append; Kafka publisher; Aje-SDK Ethereum anchoring                                                               |
| `graph`    | Cypher-backed graph of governance actors and relationships (`DELEGATES_TO`, `MEMBER_OF`, `CONTROLS`, …) for power-flow, topology, and influence-path queries                                                            |
| `database` | PostgreSQL `themis`-schema migrations (plain SQL, run by a custom migration service) for production governance data, plus an IPFS/Arweave document-storage service                                                      |

The immutable audit log is central to Themis's design: alongside the relational
governance tables, every governance action also appends a hash-chained event to
the partitioned `audit_events` table. Each event's `hash_current` chains over
its predecessor and yields a Merkle leaf hash; checkpoints' Merkle roots can be
anchored on-chain through the Aje SDK. This enables complete, tamper-evident
audit trails and event-replay for governance failure analysis.

### Decision-Making Cluster

Three libraries provide the mechanics of collective decision-making. They are
deliberately separated so that the same voting mechanism can be reused across
any organizational form.

#### `@themis/voting`

Twelve voting mechanism implementations from simple approval to advanced
cryptoeconomic mechanisms. Each mechanism is a self-contained implementation
with:

- Ballot creation and tallying
- Result computation
- Verification and audit
- On-chain/off-chain adaptability

#### `@themis/deliberation`

Structured deliberation tools that go beyond voting. Discussion platforms,
argument maps, and opinion clustering (Polis-style) help organizations surface
consensus before a vote is even called, improving decision quality.

#### `@themis/decisions`

Structured decision frameworks: MCDA, prediction markets, and futarchy. These
tools complement voting by providing better information about expected outcomes
before choices are made.

### Identity and Accountability Cluster

Four libraries address who participates in governance and how they are held
responsible:

- `@themis/identity` — DID-based identity, eligibility, credentials, Sybil
  resistance
- `@themis/reputation` — Delegate scoring, EigenTrust propagation, participation
  analytics
- `@themis/accountability` — Integrity monitoring, promise tracking,
  whistleblower systems
- `@themis/privacy` — MACI, ZK voting, confidential channels, private delegation

### Organizational Form Libraries

Nine libraries implement governance for specific organizational types. Each
library models the rules, roles, and decision-making patterns appropriate to
that type — a DAO library understands token-weighted voting and cross-chain
coordination, while a traditional governance library models indigenous consensus
processes. The underlying voting and deliberation mechanisms are always sourced
from the shared mechanism libraries.

| Library                 | Organizational Types                        |
| ----------------------- | ------------------------------------------- |
| `@themis/dao`           | Decentralized autonomous organizations      |
| `@themis/corporate`     | Corporations, boards, ESG                   |
| `@themis/nonprofit`     | Nonprofits, cooperatives, B-Corps           |
| `@themis/community`     | Associations, housing, unions, sports clubs |
| `@themis/civic`         | Digital democracy, e-government, elections  |
| `@themis/traditional`   | Indigenous, customary, religious governance |
| `@themis/digital`       | Platform, algorithmic, AI, data governance  |
| `@themis/international` | UN/EU/AU, treaties, diplomacy               |
| `@themis/sectors`       | Military, health, financial, urban, media   |

### Knowledge and Simulation Libraries

Four libraries provide the intellectual infrastructure for governance work.
Rather than encoding governance as mere CRUD operations, these libraries embed
political science theory, governance history, and agent-based simulation
directly into the platform:

- `@themis/knowledge` — 15 engines covering political science and governance
  theory as queryable knowledge
- `@themis/frameworks` — Implemented governance system primitives (direct
  democracy through futarchy)
- `@themis/simulation` — Agent-based simulation for testing governance designs
  before deployment
- `@themis/policy` — Computational law and policy analysis engines

### Legal and Dispute Libraries

Four libraries cover the legal and dispute dimension of governance. The boundary
between them reflects their different roles: `@themis/constitutions` deals with
written rules, `@themis/justice` models judicial systems, and
`@themis/arbitration` provides the heavyweight machinery for resolving disputes
once they arise. `@themis/dispute-resolution` is a thin routing layer that
decides which system handles a given dispute.

- `@themis/constitutions` — Constitutional authoring, versioning, and
  computational law compilation
- `@themis/justice` — Judicial system modeling and transitional justice
- `@themis/arbitration` — Decentralized arbitration (Kleros-style) and
  structured mediation (≈5,700 LOC of dispute/mediation engines)
- `@themis/dispute-resolution` — A small routing/intake layer (TODO Phase 179)
  that classifies a governance dispute and decides whether to route it into the
  Concordia mediation substrate; also implements the V2 DSA
  Statement-of-Reasons, moderation-appeal, and tournament-result dispute flows

### Adjudication Library

- `@themis/academic-integrity` — Themis adjudication engine for Metis
  academic-integrity cases: signal taxonomy, calibrated classifier policy,
  severity→action map, appeals workflow, bias monitor, and verdict persistence

### Originality / IP Protection Libraries

Six libraries form the generated-content originality accept-gate. They are real
but thin — each media shield is a ≈50-LOC wrapper that delegates verdict
computation through `@themis/originality-shields` to the `@concordia/contracts`
originality-shield contract:

- `@themis/originality-shields` — shared `buildThemisOriginalityShieldVerdict`
  implementation and scan-input / verdict types
- `@themis/music-shield`, `@themis/visual-shield`, `@themis/text-shield`,
  `@themis/video-shield`, `@themis/design-shield` — per-media-family shields,
  each fixing a `mediaFamily`, supported UGC upload kinds, and default evidence
  kind

The fuller per-element detection systems (the planned Phase 74 Music Shield and
Phase 75 Universal Originality Shield) are documented as backlog, not as
existing code. There are no `model-shield`, `character-shield`, `game-shield`,
or `animation-shield` libraries.

---

## Dependency Model

The tree below shows which libraries depend on which. Reading it, you can see
that `@themis/core` is the universal foundation, while `@themis/ai` and
`@themis/integrations` sit at the top because they depend on the widest set of
domain libraries. The originality-shield libraries form a separate cluster that
depends on `@concordia/contracts` rather than `@themis/core`.

```
@themis/core  (foundation, depends on @oshun/database)
     |
     ├── @themis/voting
     ├── @themis/deliberation
     ├── @themis/decisions
     ├── @themis/reputation
     ├── @themis/identity
     ├── @themis/accountability
     ├── @themis/transparency
     ├── @themis/privacy
     ├── @themis/constitutions
     ├── @themis/dao  (may depend on @themis/voting, @themis/constitutions)
     ├── @themis/corporate
     ├── @themis/nonprofit
     ├── @themis/community
     ├── @themis/civic
     ├── @themis/traditional
     ├── @themis/digital
     ├── @themis/international
     ├── @themis/justice
     ├── @themis/arbitration
     ├── @themis/sectors
     ├── @themis/treasury
     ├── @themis/funding
     ├── @themis/environmental
     ├── @themis/crisis
     ├── @themis/policy
     ├── @themis/analytics
     ├── @themis/knowledge
     ├── @themis/frameworks
     ├── @themis/simulation
     ├── @themis/ai  (depends on @themis/voting, @themis/deliberation, @themis/analytics)
     └── @themis/integrations  (depends on multiple @themis/* and cross-domain types)

# Libraries that do NOT depend on @themis/core:
@themis/academic-integrity   (depends only on zod)
@themis/dispute-resolution   (depends on @concordia/contracts, zod)
@themis/originality-shields  (depends on @concordia/contracts, zod)
     ├── @themis/music-shield   (depends on @themis/originality-shields)
     ├── @themis/visual-shield  (depends on @themis/originality-shields)
     ├── @themis/text-shield    (depends on @themis/originality-shields)
     ├── @themis/video-shield   (depends on @themis/originality-shields)
     └── @themis/design-shield  (depends on @themis/originality-shields)
```

---

## Design Patterns

### 1. Event Sourcing as the Core Model

Governance systems require tamper-evident records. Every governance action (vote
cast, proposal submitted, amendment ratified, delegation created) is written as
an immutable `GovernanceEvent` before any state change. State is derived by
replaying events. This provides:

- Complete, verifiable audit trails
- Temporal queries over governance history
- Ability to replay and analyze governance failures
- Foundation for blockchain anchoring of the audit log

### 2. Module Identifier Constants

Most libraries export a `themis<package>Module` constant (lower case, e.g.
`themiscoreModule`, `themisvotingModule`; `@themis/academic-integrity` uses
PascalCase `themisAcademicIntegrityModule`). The constant carries only a `name`
field — there is no `version` field. This lets host applications verify at
runtime which Themis modules are loaded. `@themis/crisis`,
`@themis/international`, `@themis/justice`, `@themis/dispute-resolution`,
`@themis/originality-shields`, and the five media shields do not currently
export this constant.

### 3. Mechanism Separation from Organizational Form

The voting mechanisms (`@themis/voting`) are fully separable from the
organizational form libraries (`@themis/dao`, `@themis/corporate`, etc.). A DAO
can use conviction voting; a corporation can use the same conviction voting
mechanism; a labor union can use it too. The mechanisms are not coupled to the
organizational type.

This enables:

- Governance designers to mix mechanisms and organizational forms
- The hybrid framework composer (`@themis/frameworks`) to assemble novel
  governance configurations
- Reuse of well-tested mechanism code across organizational contexts

### 4. Computational Governance

`@themis/constitutions` includes a computational law compiler that converts
governance rules (expressed in a structured language) to executable TypeScript
code or smart contract bytecode. This closes the loop between governance design
and execution — constitutions are not just documents, they are programs.

### 5. Simulation Before Deployment

`@themis/simulation` provides agent-based simulation that models how governance
systems behave under adversarial conditions (voter apathy, governance capture,
coordination failure). The integration with `@themis/constitutions` means
constitutional designs can be simulated before ratification, reducing governance
failures from design flaws.

### 6. Originality Shields as a Concordia-Backed Accept-Gate

The originality shields are architecturally positioned as a content accept-gate,
but they delegate rather than implement: each `@themis/*-shield` library builds
an `OriginalityEvidenceBundle` and calls `evaluateShield` from
`@concordia/contracts`, which returns a verdict that Themis maps to a
three-value `decision` (`passed` / `review` / `blocked`). Themis owns the
per-media-family configuration and the public-UGC accept-gate mapping; Concordia
owns the underlying evidence model and verdict function.

---

## Technology Stack

| Component       | Technology                                                                               |
| --------------- | ---------------------------------------------------------------------------------------- |
| Language        | TypeScript (ESM, strict mode)                                                            |
| Runtime         | Node.js (`engines.node >= 20`)                                                           |
| Build           | Nx `@nx/js:tsc` (most libraries); `nx:run-commands` + `tsup` for the originality shields |
| Testing         | Vitest (per-library configs, shared `vitest.shared.ts`)                                  |
| Type checking   | `tsc --noEmit` (run directly from a library directory under worktrees)                   |
| Shared config   | Domain-wide `tsconfig.domain.json`, `eslint.config.js`, `prettier.config.js`             |
| Database        | PostgreSQL — `themis`-schema plain-SQL migrations via `@themis/core`                     |
| Validation      | Zod (`@themis/core` types are Zod schemas; many libraries use Zod)                       |
| Event transport | Kafka publisher abstraction in `@themis/core` (with an in-memory implementation)         |

---

## Build and Development

The commands below assume Nx is functioning normally. Under worktrees, Nx may
fail due to duplicate project detection; in that case, run `npx tsc --noEmit`
and `npx vitest run` directly from the library directory.

```bash
# Test a specific library
pnpm nx test @themis/core
pnpm nx test @themis/voting

# Build all Themis libraries
pnpm nx run-many --target=build --projects=tag:scope:themis

# Lint
pnpm nx lint @themis/deliberation

# Type check
pnpm nx typecheck @themis/dao

# Run all domain tests
pnpm nx run-many --target=test --projects=tag:scope:themis

# Worktree-safe type check
cd libs/themis/core && npx tsc --noEmit
```

---

## Service Topology

Themis has no standalone services. It is a pure library domain. Applications
that build governance tools on top of Themis are responsible for their own
service infrastructure.

The domain does define a database schema (via `@themis/core`) that requires
PostgreSQL, and `@themis/core` ships an event-publishing abstraction
(`ThemisKafkaPublisher`, with an in-memory fallback) and an on-chain
audit-anchor service. But there is no Themis-managed HTTP API server or
long-running background worker; the consuming application owns process hosting,
the Kafka broker, and any scheduling.

---

## Cross-Domain Integration Points

The integrations in the table below all live in `@themis/integrations` (one
bridge file per row). The boundary rule is: Themis owns governance mechanics;
other domains own their own workflows but consume Themis data and decisions
through these bridges. For example, Aje owns on-chain settlement logic but
Themis owns which proposals are ready for execution; the bridge file is where
those two concerns meet.

| Domain                  | Integration Library                                         | Integration Type                                                                                                            |
| ----------------------- | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| **Veritas**             | `@themis/integrations`                                      | Bidirectional: journalism feeds governance analytics; governance feeds Veritas newsroom                                     |
| **Aje** (blockchain)    | `@themis/integrations`, `@themis/core` events               | Governance decisions executed on-chain; on-chain data ingested into Themis; Merkle audit-root anchoring via the Aje SDK     |
| **Maat** (organization) | `@themis/integrations`                                      | Organizational management data for governance context                                                                       |
| **Lakshmi** (finance)   | `@themis/integrations`                                      | Fiscal-governance bridge (`lakshmi-themis-fiscal-governance.ts`)                                                            |
| **Kuanyin** (ethics)    | `@themis/integrations`                                      | Ethical-governance bridge (`kuan-yin-themis-ethical-governance.ts`)                                                         |
| **Iris** (voice)        | `@themis/integrations`                                      | Conversational governance assistant interface                                                                               |
| **Sophia** (knowledge)  | `@themis/integrations`                                      | Knowledge base integration for governance research                                                                          |
| **Metis** (education)   | `@themis/integrations`, `@themis/academic-integrity`        | Civic-education curriculum bridge; Themis adjudication of Metis academic-integrity cases                                    |
| **Maya** (metaverse)    | `@themis/integrations`                                      | Virtual governance environment support                                                                                      |
| **Concordia**           | `@themis/dispute-resolution`, `@themis/originality-shields` | Dispute routing into the Concordia mediation substrate; originality verdicts via the `@concordia/contracts` shield contract |

---

## Domain Boundaries

Understanding what Themis does and does not own prevents scope creep and
duplicate implementations. Themis owns governance mechanics — the rules, voting,
deliberation, accountability, and audit trail. It does not own the financial
market infrastructure, content pipelines, or communication layers that other
domains provide.

**Themis provides:**

- Governance primitives and mechanisms (voting, deliberation, decision
  frameworks)
- Organizational governance for every organizational form
- Constitutional authoring, versioning, and computational law
- Reputation, identity, and accountability systems
- Privacy-preserving governance mechanisms
- A Concordia-backed originality accept-gate for generated content
- Dispute routing into the Concordia mediation substrate
- Adjudication for Metis academic-integrity cases
- Cross-domain governance integration bridges

**Themis does not provide:**

- Financial market infrastructure (delegated to Aje and Lakshmi domains)
- General content production (Euterpe, Veritas, Isis domains)
- Communication infrastructure (Iris domain)
- The underlying originality evidence model and verdict function (owned by
  `@concordia/contracts`) or the Concordia mediation substrate itself
- HTTP API servers or application frontends
