# Nacho — Architecture & Plan

Nacho is a 100% Rust, microkernel-first AI agent harness built on **Cordis** principles (spatiotemporal composability), **hot-swappable WASM Component plugins**, a **perfectly decoupled UI/protocol layer** (GPUI first, plus TUI, headless, and ACP), and a **Cloudflare-native durable agent loop** inspired by `pi-durable` and `@cloudflare/computer`.

---

## 1. Core Principles

1. **Kernel-only core (`nacho-kernel`).** Zero agent loop logic, zero LLM code, zero tool code, zero UI code. The core is strictly a Cordis microkernel.
2. **Everything is a hot-swappable Rust plugin.** Agent loops, model providers, code-mode tools, sandbox executors, session logs, ACP/RPC servers, and UI panels are all equal plugins that can be toggled, unloaded, or hot-swapped live.
3. **Spatiotemporal composability (Cordis).**
   - *Temporal (Revertible Effects):* Every plugin mounts in its own `Fork` / `EffectScope`. Every registration (service, listener, interceptor, background task, child plugin) records a cleanup disposable. Unloading or hot-swapping unwinds in LIFO order with zero leaks.
   - *Spatial (Reactive DI):* Plugins declare `provides` and `requires` service keys. Dependents activate automatically when dependencies appear and cleanly suspend/rebind when a provider unloads or hot-swaps.
4. **Perfect UI / Core split.** Renderers have zero harness logic and talk to any local or remote kernel over the same wire protocol.
5. **Pragmatic sandboxing, no over-engineering.** WASI capabilities provide clean memory and permission boundaries out of the box without building a heavy custom security engine.

---

## 2. System Topology

```text
  Renderers / Clients (ZERO agent logic)
  ┌──────────────┐  ┌─────────┐  ┌──────────────┐  ┌───────────────┐
  │  nacho-gpui  │  │   TUI   │  │ Headless/SDK │  │ Zed / T3 (ACP)│
  └──────┬───────┘  └────┬────┘  └──────┬───────┘  └───────┬───────┘
         └───────────────┴──────────────┴──────────────────┘
                                 │  ACP + Kernel Control RPC (stdio / WS / local)
  ┌──────────────────────────────▼──────────────────────────────────┐
  │                   nacho-kernel  (Pure Cordis)                   │
  │   Context · Fork/EffectScope · LIFO Disposables · Reactive DI   │
  │   Typed Event Bus + Interceptors · Plugin Lifecycle / Hot-Swap  │
  └──────────────────────────────┬──────────────────────────────────┘
                                 │  WIT Component ABI (or static Rust trait)
  ┌──────────────────────────────▼──────────────────────────────────┐
  │                Hot-Swappable Rust Plugins (.wasm)               │
  │  • durable-loop (pi-durable)   • codemode + exec-cf-*           │
  │  • session-log (append-only)   • llm (providers / AI Gateway)   │
  │  • rpc-acp (client bridge)     • providers / runtimes / ui      │
  └──────────────────────────────┬──────────────────────────────────┘
                                 │  Host Primitives (storage, http, fs, shell, sandbox)
         ┌───────────────────────┴───────────────────────┐
         ▼                                               ▼
  nacho-host-local (Tokio + Wasmtime + SQLite)    plugins/runtime-*/ (pluggable hosts:
  Unified RPC/WS + HTTP/SSE remote wire protocol  Cloudflare Workers DO, Hetzner/VPS, etc.)
```

---

## 3. Architectural Decisions

### 3.1 Pure Cordis Microkernel (`nacho-kernel`)
- **`Context` & `Fork` (`EffectScope`):** Recursive scoped execution environment. Each plugin runs in an isolated child scope.
- **Disposables (LIFO stack):** Registering a service, event hook, timer, or child plugin returns/records a cleanup handle unwound automatically on dispose.
- **Reactive Service Registry (`provides` / `requires`):** Services are addressed by typed/named capability keys (`service.storage`, `service.llm`, `service.exec`, `service.loop`, etc.). Swapping a provider cleanly notifies and rebinds dependents.
- **Event Bus & Interceptors:** Supports both broadcast events (append-only session facts, runtime telemetry) and waterfall/middleware hooks (inspect, rewrite, or veto calls).
- **Abstract `PluginHost`:** The kernel owns lifecycle (`load`, `reload`, `unload`, `status`) while remaining agnostic to whether a plugin runs via Wasmtime, Cloudflare Dynamic Workers, or static Rust linking.

### 3.2 Plugin Format: Rust → WASM Component Model
- **Primary format:** `wasm32-wasip2` components defined by canonical WIT contracts (`nacho-wit`) and ergonomic Rust macros (`nacho-sdk`).
- **Hot-swapping:** Dropping the old Wasmtime `Store` and instantiating the new `.wasm` component takes single-digit milliseconds, with complete crash isolation and no native `dlclose`/ABI fragility.
- **Dual compilation:** The exact same Rust plugin crate can compile to:
  1. A portable `.wasm` component (hot-swapped locally via Wasmtime or dynamically via Cloudflare's `env.LOADER`), or
  2. A statically linked Rust library for zero-overhead bundled builds (e.g., core bundles inside a `workers-rs` deployment).

### 3.3 First Agentic Pattern: Durable Loop + Cloudflare Computer
- **`plugin-durable-loop` (`pi-durable` style):**
  - Environment-less state machine — requires **no OS, no local filesystem, no persistent shell**.
  - Depends solely on three Cordis services: `service.storage`, `service.llm`, and `service.exec`.
  - Checkpoints every turn/step to append-only storage so Cloudflare Durable Object hibernation, evictions, or process restarts resume cleanly from the last committed step.
- **`plugin-codemode` + swappable `service.exec` backends (`@cloudflare/computer` style):**
  - Instead of dozens of discrete tool schemas, exposes a compact **Code Mode** `exec` surface backed by a persistent SQLite virtual workspace.
  - Per-command execution routes dynamically:
    - **`exec-cf-isolate` (fast path):** Spins up a Cloudflare Dynamic Worker (`env.LOADER.load(...)`) V8/WASM isolate *just for that single command* (~ms startup).
    - **`exec-cf-container` (heavy path):** Falls back to an on-demand Cloudflare Container / microVM with workspace state projected from DO SQLite when a command needs real Linux binaries/compilers.
    - **`exec-local-wasm` (local dev parity):** Runs single-command Wasmtime sandboxes locally so everything develops and tests cleanly offline.
- **Plugin-owned Hosts (`plugins/runtime-*`):** Core `crates/` contain zero vendor or cloud-specific code. Every remote host (such as `plugins/runtime-cloudflare/`, which bundles its own `worker/` Durable Object target and provisions itself over generic `service.shell_local` + `service.http`) is a plugin. Any Linux server (Hetzner, Fly, Docker, SSH) can run `nacho-host-local serve --host 0.0.0.0 --token ...` and speak the exact same HTTP+SSE remote runtime protocol (`/sessions/:id/turn/stream`, `/events`, `/workspace`, `/service/:svc/:method`).

### 3.4 UI & Protocol Split (GPUI First, ACP Native)
- **`plugin-rpc-acp`:** Implements the **Agent Client Protocol (ACP)** (`agent-client-protocol` crate) for sessions, streaming output, tool calls, diffs, and permissions over stdio / WebSocket / local IPC, plus a lightweight `nacho/*` extension namespace for kernel & plugin inspection/hot-reload.
- **Clients:**
  - **`nacho-gpui`:** Standalone Rust desktop app built with `gpui` + `gpui-component`, connecting to either a local or remote Cloudflare kernel over the same protocol.
  - **ACP clients (Zed, T3 Code, Neovim, etc.):** Work directly against `plugin-rpc-acp`.
  - **TUI / Headless / Embedded:** Any client can attach to the same protocol.

---

## 4. State Ownership & Complexity Guardrails

### Where State Lives (Only 3 Authoritative Homes)
1. **`service.storage` (SQLite locally / Durable Object SQLite on Cloudflare):** 100% of durable domain state — session event logs, `LoopCheckpoint`, virtual workspace files, and installed plugin manifests.
2. **`nacho-kernel`:** Ephemeral Cordis wiring topology only — `EffectScope` tree, LIFO disposables, loaded plugin slots, active service/hook maps. Zero domain state.
3. **UI Renderers (`nacho-gpui`, TUI):** Ephemeral view state only — scroll position, draft input, focused pane, derived projection of streamed events.

### Where State Must NOT Live
- **Logic plugins (`session-log`, `llm`, `codemode`, `durable-loop`, `rpc-acp`) are strictly stateless.** No in-memory session maps, file caches, or `static Mutex<HashMap>` caches inside WASM memory. Hot-swapping or Cloudflare DO eviction loses zero state.
- **Per-command sandboxes (`exec-*`) are 100% ephemeral.** Spawned for a single command with a workspace snapshot, return output + `file_changes`, and immediately destroyed.
- **No mirrored state machines.** Only `durable-loop` owns `LoopPhase` (`Idle | PendingModel | PendingExec | Completed | Failed`) in `service.storage`. Other layers project from it rather than inventing parallel state machines.

### Mechanical Enforcement (`clippy.toml` + `[workspace.lints]`)
- `clippy::cognitive_complexity = "deny"` (max `15`)
- `clippy::too_many_lines = "deny"` (max `60`)
- `clippy::too_many_arguments = "deny"` (max `5`)
- `clippy::struct_excessive_bools = "deny"` (max `2`)
- `clippy::unwrap_used`, `expect_used`, `panic`, `todo`, `dbg_macro` = `"deny"` outside tests
- No unnecessary comments — code must be self-documenting through sharp naming and clean structure.

---

## 5. Workspace Layout

```text
nacho/
├── assets/
│   └── nacho-logo.png        # Nacho mascot (transparent PNG)
├── docs/
│   └── ARCHITECTURE.md       # This document
├── crates/
│   ├── nacho-contracts/      # Shared zero-logic JSON contracts & UI primitives
│   ├── nacho-kernel/         # Pure Cordis microkernel
│   ├── nacho-wit/            # Canonical WIT contracts
│   ├── nacho-sdk/            # Rust plugin author SDK & macros
│   ├── nacho-host-local/     # Generic host: Tokio + Wasmtime + SQLite + FS/Git/Shell + WS/HTTP/SSE
│   └── nacho-gpui/           # Pure thin GPUI primitive renderer (zero hardcoded chrome/animations)
└── plugins/                  # Standard bundled dual-mode plugins (wasm32-wasip2 + native)
    ├── session-log/          # Append-only trajectory log, replay, forking
    ├── llm/                  # Protocol engines (Anthropic, Gemini, OpenAI-compatible, dynamic)
    ├── providers/            # Pure pluggable Provider Registry (zero hardcoded providers)
    ├── provider-{anthropic,deepseek,openai,openrouter,gemini,ollama}/  # 1 plugin per provider
    ├── projects/             # Local workspace folders, Git status/diff, session bindings
    ├── tools-core/           # Pluggable coding tools (read/write/edit/list/search/run/code_exec)
    ├── durable-loop/         # Cancellable multi-tool pi-durable state machine
    ├── codemode/             # Code-mode VFS & ephemeral sandbox runner
    ├── runtime-{registry,local,cloudflare}/  # Pluggable host targets (incl. runtime-cloudflare/worker/)
    ├── rpc-acp/              # ACP + Nacho kernel control RPC bridge
    ├── ui-registry/          # Dynamic UI provider & recursive WindowRoot/SlotRef composer
    └── ui-{theme-obsidian,shell,sidebar,conversation,workbench}/  # Bundled Studio UI plugins
```

---

## 5. Build Roadmap

### Phase 1 — Kernel & Hot-Swap Proof
- Scaffold Cargo workspace (`nacho-kernel`, `nacho-wit`, `nacho-sdk`, `nacho-host-local`).
- Implement Cordis primitives: `Context`, `Fork`/`EffectScope`, LIFO `Disposables`, Reactive DI (`provides`/`requires`), Event Bus + Interceptors.
- Load and hot-swap a sample `.wasm` plugin live via Wasmtime with verified zero-leak teardown.

### Phase 2 — Durable Loop & Cloudflare Computer
- Build `session-log`, `llm`, `durable-loop`, `codemode`, and `exec-local-wasm`.
- Build `plugins/runtime-cloudflare/worker` (`workers-rs` DO + DO SQLite) with `exec-cf-isolate` and `exec-cf-container`.
- Verify an end-to-end crash-resilient agent session running on Cloudflare with per-command sandboxes.

### Phase 3 — Protocol, ACP & GPUI Renderer
- Build `rpc-acp` supporting headless execution and standard ACP clients over stdio and WebSocket.
- Build `nacho-gpui` (`gpui` + `gpui-component`) connecting to local or Cloudflare kernels with streaming sessions and a live plugin manager.
