# Architecture

Harmonia follows a strict separation: **Lisp orchestrates, Rust executes**. SBCL Common Lisp handles reasoning, memory, scoring, and evolution. Rust capability libraries handle all I/O and computation, connected via C-ABI/CFFI through 9 explicit port boundaries.

## 6-Layer Architecture

```
+─────────────────────────────────────────────────────+
│  1. GOVERNANCE                                      │
│     Genesis constraints + evolution state            │
+─────────────────────────────────────────────────────+
│  2. LISP RUNTIME                                    │
│     core/ dna/ orchestrator/ memory/ ports/          │
+─────────────────────────────────────────────────────+
│  3. RUST CAPABILITIES                               │
│     lib/ (18 core + 3 backends + 6 tools            │
│          + 13 frontends)                            │
+───────────────────────┬─────────────────────────────+
│  4. SIGNAL/CHANNEL    │  5. SECURITY                │
│     gateway/baseband  │     SignalGuard v6           │
│     harmonia-signal   │     kernel + shell           │
+───────────────────────┴─────────────────────────────+
│  6. EXPERIENCE                                      │
│     Logs, memory, matrix telemetry, recovery        │
+─────────────────────────────────────────────────────+
```

| Layer | Components | Role |
|-------|-----------|------|
| **Governance** | Genesis constraints, evolution state | Constitutional rules, invariants, identity |
| **Lisp Runtime** | `core/`, `dna/`, `orchestrator/`, `memory/`, `ports/` | Task planning, memory, harmony scoring, evolution |
| **Rust Capabilities** | `lib/` (39 crates) | I/O, LLM routing, search, voice, browser, storage |
| **Signal/Channel** | `gateway/baseband`, `harmonia-signal` structs | Frontend signal processing, capability dispatch |
| **Security** | SignalGuard v6 (kernel + shell) | Typed dispatch, policy gate, taint propagation, injection scanning |
| **Experience** | Logs, memory, matrix telemetry, recovery | Feeds future behavior, scoring, and evolution |

## 9 Port/FFI Boundaries

All external I/O flows through nine explicit ports. Nothing bypasses this boundary.

| Port | Lisp Side | Rust Crate | Purpose |
|------|-----------|-----------|---------|
| **Vault** | `ports/vault.lisp` | `lib/core/vault` | Encrypted secret storage (AES, master key from env) |
| **Store** | `ports/store.lisp` | `lib/core/config-store` | Mutable runtime key-value store |
| **Router** | `ports/router.lisp` | `lib/backends/llms/openrouter` | LLM completion routing |
| **Lineage** | `ports/lineage.lisp` | `lib/core/git-ops` | Self-versioning via Git |
| **Matrix** | `ports/matrix.lisp` | `lib/core/harmonic-matrix` | Route constraints + telemetry |
| **Tool-Runtime** | `ports/tool-runtime.lisp` | `lib/tools/*` | Search, voice, browser dispatch |
| **Baseband** | `ports/baseband.lisp` | `lib/core/gateway` + `frontends` | Signal poll/send across all frontends |
| **Swarm** | `ports/swarm.lisp` | `lib/core/parallel-agents` | Parallel + tmux subagents |
| **Evolution** | `ports/evolution.lisp` | `lib/core/ouroboros` + `phoenix` | Source rewrite and artifact rollout |

## Rust Crate Inventory

### Core Crates (18)

| Crate | Purpose |
|-------|---------|
| `phoenix` | Supervisor (PID 1), hot-reload, crash recovery |
| `ouroboros` | Crash history, patch artifact, source-rewrite path |
| `vault` | Encrypted secret storage |
| `memory` | Persistent memory subsystem |
| `git-ops` | Self-versioning and lineage tracking |
| `rust-forge` | Rust build and compilation |
| `cron-scheduler` | Scheduled task execution |
| `recovery` | Crash recovery and rollback |
| `fs` | Filesystem operations |
| `parallel-agents` | Swarm orchestration, tmux subagents |
| `harmonic-matrix` | Route constraints, telemetry, harmonic scoring |
| `config-store` | Runtime configuration KV store |
| `tailnet` | Mesh networking via Tailscale |
| `gateway` | Frontend signal processing |
| `signal-integrity` | Signal validation and integrity checks |
| `admin-intent` | Administrative command parsing |
| `push` | Push notification delivery |
| `http` | HTTP client/server |

### Backend Crates (3)

| Crate | Purpose |
|-------|---------|
| `openrouter-backend` | LLM completion via OpenRouter |
| S3 storage | Object storage for snapshots and artifacts |
| Shared HTTP | Common HTTP utilities across backends |

### Tool Crates (6)

| Crate | Purpose |
|-------|---------|
| `browser` | Chrome CDP automation |
| `search-exa` | Exa search integration |
| `search-brave` | Brave search integration |
| `whisper` | Speech-to-text (STT) |
| `elevenlabs` | Text-to-speech (TTS) |
| `social` | Social media interactions |

### Frontend Crates (12)

| Crate | Transport | Notes |
|-------|-----------|-------|
| `tui` | Terminal | Always on |
| `mqtt-client` | MQTT 5.0 | Fingerprint validation |
| `telegram` | Bot API | |
| `slack` | Bot API | |
| `discord` | Bot API | |
| `signal` | signal-cli bridge | REST/JSON-RPC adapter |
| `whatsapp` | Cloud API | |
| `imessage` | BlueBubbles | macOS bridge |
| `mattermost` | Bot API | |
| `nostr` | NIP-01 relay | |
| `email-client` | IMAP/SMTP | |
| `tailscale-frontend` | Mesh network | HMAC-SHA256 transport |

## Deterministic Tick Model

The orchestration engine runs a deterministic cycle on every tick, defined in `loop.lisp`:

```
gateway-poll → process-prompt → memory-heartbeat → harmonic-step → gateway-flush
                                                        │
                                                  security-audit
```

Each tick:

1. **gateway-poll** — collect signals from all frontends via baseband
2. **process-prompt** — dispatch queued prompts through the conductor
3. **memory-heartbeat** — persist and consolidate memory state
4. **harmonic-step** — score, route, and audit (includes security-audit phase)
5. **gateway-flush** — send responses back through frontends

## Prompt-Orchestration Flow

```
Prompt queue
    │
    ▼
Conductor (assembles DNA + memory context)
    │
    ├── harmonia-signal (external) → orchestrate-signal
    │       │
    │       ├── boundary-wrap external data
    │       ├── LLM completion
    │       └── policy-gated tool calls
    │
    └── string (internal) → orchestrate-prompt
            │
            └── direct tool dispatch
    │
    ▼
Policy gate (%policy-gate)
    │
    ▼
Result scored + persisted
```

**External signals** (from frontends) are wrapped with boundary markers and routed through the full security pipeline. **Internal prompts** (from the agent itself) use direct tool dispatch, bypassing boundary wrapping but still passing through the policy gate.

## DNA & Constitution

Defined in `src/dna/dna.lisp`:

- **Creator lineage:** harmoniis (non-negotiable)
- **Prime Directive:** "Seek harmony through minimal, composable orchestration"
- **Vitruvian Triad:** Firmitas (strength), Utilitas (utility), Venustas (beauty)
- **Ethical constraints:** all-species-respect, non-domination, human-care, truth-seeking, avoid-harm

The DNA is part of the genomic layer — identity that cannot be modified by the evolution engines.

## System Workspace

The system workspace at `~/.harmoniis/harmonia/` contains:

| Path | Purpose |
|------|---------|
| `vault.db` | Encrypted secret storage (AES) |
| `config/workspace.sexp` | Workspace configuration |
| `config/gateway-frontends.sexp` | Active frontend configuration |
| `genesis/` | Constitutional documents and constraints |
| `frontends/` | Frontend-specific state and data |

## Configuration Files

All runtime policy is declarative, stored as S-expressions:

| File | Purpose |
|------|---------|
| `config/tools.sexp` | Tool registry and permissions |
| `config/model-policy.sexp` | Model profiles and LLM routing rules |
| `config/harmony-policy.sexp` | Harmonic thresholds and weights |
| `config/matrix-topology.sexp` | Allowed nodes, edges, tool toggles |
| `config/swarm.sexp` | Swarm width, tmux policy, rewrite gates |
| `config/baseband.sexp` | Frontend auto-load, capabilities, security labels |
| `config/tailnet.sexp` | Tailscale mesh networking configuration |
| `config/a2ui-catalog.sexp` | A2UI component definitions (21 components) |
| `config/structure-allowlist.txt` | Allowed file/directory structures |

## Next Steps

- [Self-Improvement](/docs/harmonia/self-improvement) — Ouroboros, Phoenix, and evolution safety gates
- [Frontends](/docs/harmonia/frontends) — A2UI, gateway architecture, and 13 supported frontends
- [Harmonia vs OpenClaw](/docs/harmonia/vs-openclaw) — framework comparison
