# Nacho Platform Primitives — Architectural Direction & RFC

> **Status: Implemented.** All 7 platform primitives (`P1`–`P7`) below are shipped across `nacho-contracts`, `nacho-kernel`, `nacho-host-local`, `nacho-gpui`, and `plugins/ui-*`, and verified by end-to-end blank-canvas tests (`crates/nacho-host-local/tests/platform_primitives_e2e.rs`).

This document sets the architectural direction for evolving Nacho from an **AI coding workspace with plugins** into a **native Rust/GPUI shell for any malleable AI-native application** — while keeping `crates/` strictly limited to the 6 core primitives.

---

## 1. The North Star

Anyone (or Nacho itself) should be able to disable every built-in UI and coding plugin (`nacho.ui.shell`, `nacho.ui.sidebar`, `nacho.ui.conversation`, `nacho.ui.workbench`), register a custom `UiSlot::WindowRoot` plugin, and reinvent 100% of the application — with **zero edits to `crates/`**.

### Two Stress Tests
We evaluate every proposed primitive against two completely non-coding target apps:
1. **ServiceNow AI Triage Workstation:** Dense ticket queue, SLA/priority filters, background polling every 30s, `J`/`K`/`R` single-key triage shortcuts, drag-and-drop status/Kanban lanes, resizable split panes, OS P1 alert notifications, and 1-click AI resolution workflows.
2. **Social Feed Client (Bluesky / X-style layout):** 3-column fixed/fluid layout, remote avatars & 3:1 profile banners with an overlapping circular avatar, custom simultaneous brand/action colors & hover tints, infinite virtualized feed scrolling, and centered compose/lightbox modal overlays.

### The Core Boundary Rule (Anti-Bloat Filter)
Before adding anything to `crates/`, ask one question:

> **Can a sandboxed `wasm32-wasip2` plugin already build this cleanly from existing primitives?**

- **If YES → Plugin.** Never add it to `crates/`.
  - Examples that **MUST stay plugins**: cron/recurring schedulers, keymap editors & command palettes, OS desktop notifications (via `service.shell_local` → `notify-send` / `osascript` / PowerShell), Kanban boards, data tables, ticket cards, social feeds, domain workflows.
- **If NO (because of a physical OS, GPU, or WASM execution boundary) → Add the smallest orthogonal primitive.**

---

## 2. Current State vs. Physical Boundaries

Audited directly against `nacho-contracts`, `nacho-wit`, `nacho-host-local`, and `nacho-gpui` (`gpui-pre 0.3.14`):

| Capability | Today | Physical Boundary? | Where It Belongs |
| :--- | :--- | :--- | :--- |
| Full window takeover | `UiSlot::WindowRoot` renders full-bleed in `ui_renderer.rs` | Already solved | Plugins |
| HTTP / Storage / Shell / Git / Exec | Generic host capabilities in `nacho-host-local` | Already solved | Host primitives |
| OS Desktop Notifications | Can invoke `notify-send` / `osascript` / PowerShell via `service.shell_local` | **No** | Standalone plugin (`service.notifications`) |
| Background wakeup for WASM | `wasm32-wasip2` cannot spawn persistent threads inside `mount()` | **Yes (WASM lifecycle)** | Tiny host syscall (`service.timer` one-shot) + plugin scheduler |
| Keyboard shortcuts | `app.rs` hardcodes `Ctrl+B`/`Ctrl+N`/`Esc` to `ui.shell`/`ui.sidebar` and drops all other keys | **Yes (OS window input)** | Generic `UiKeybinding` / raw key forwarding in GPUI; shortcuts in plugins |
| Virtualized lists & infinite scroll | `gpui::list` hardcoded to `id == "chat-scroll"`; no near-end event | **Yes (GPU viewport)** | Generic `virtualized`, `follow_tail`, `on_near_start`/`on_near_end` on `UiNode::Scroll` |
| Remote images & `ObjectFit` | `Avatar` loads bundled assets only; `ImageGallery` is base64-only | **Yes (GPU texture decode)** | Generic `UiNode::Image` + bounded LRU HTTP loader in `nacho-gpui` |
| Overlapping layouts & modals | Pure flexbox `NodeStyle`; `Box` auto-clips overflow; no modal primitive | **Yes (GPU layout/z-order)** | `PositionSpec`, `OverflowMode`, `z_index`, `opacity`, `ShadowSize`, `UiNode::Overlay` |
| Per-node colors & hover tints | Semantic `SurfaceBg` / `UiTone` tokens only | **Yes (GPUI style mapping)** | Optional `NodeColors` hex overrides + `font_size_px` / `font_weight` |
| Drag-and-drop & split panes | `Clickable` supports click & right-click only | **Yes (GPUI pointer gestures)** | Generic `DragSpec`/`DropSpec` + 60fps `UiNode::SplitPane` |

All 7 primitive gaps map directly to APIs **already present** in our pinned `gpui-pre = "0.3.14"` crate (`img().object_fit(ObjectFit::*)`, `absolute()`/`top()`/`right()`/`bottom()`/`left()`, `deferred().with_priority()`, `occlude()`, `on_drag()`/`can_drop()`/`drag_over()`/`on_drop()`, `ListState`, `ScrollHandle::max_offset()`, `opacity()`, `on_key_down()`).

---

## 3. Primitive Specifications

All contract changes in `crates/nacho-contracts/src/lib.rs` MUST be additive with `#[serde(default)]` so existing plugins stay 100% wire-compatible, and MUST respect `clippy.toml` (`max_struct_bools <= 2`, `too_many_lines <= 60`, `cognitive_complexity <= 15`, zero comments in `.rs` files).

### P1. One-Shot Timer Primitive (`service.timer`)
- **Location:** `crates/nacho-contracts` (`services::TIMER`, `pub mod timer`) + `crates/nacho-host-local/src/capabilities/timer_local.rs`
- **Methods:**
  - `schedule { timer_id: Option<String>, delay_ms: u64, topic: String, payload: Value, owner_plugin_id: String } -> { timer_id: String }`
  - `cancel { timer_id: String } -> { cancelled: bool }`
  - `cancel_owner { owner_plugin_id: String } -> { cancelled: u32 }`
- **Guardrails:**
  - Clamp `delay_ms` to `[50, 86_400_000]` (50ms..24h); cap active timers per `owner_plugin_id` (e.g. `64`).
  - When a timer fires, emit `(topic, payload)` onto the kernel event bus (so any subscribed plugin's `on_event` wakes up) and remove the handle.
  - Subscribe to plugin lifecycle disposal/unload (or expose a cleanup hook from `kernel_control`) so disabling, unloading, or hot-swapping a plugin cancels all timers owned by that `owner_plugin_id` with zero leaks.
- **Plugin layer:** Cron expressions, recurring schedules, backoff, and persistent job queues live in plugins, never in `crates/`.

### P2. Declarative Keybindings & Zero Hardcoded Renderer Shortcuts
- **Location:** `crates/nacho-contracts` (`ui::UiKeybinding`, `ui::KeybindingScope`, `ui::RegisterKeybindingsReq`) + `plugins/ui-registry` + `crates/nacho-gpui/src/app.rs`
- **Contract:**
  - `KeybindingScope`: `Global` (fires even inside focused inputs, e.g. `Escape`, `Cmd+K`) | `OutsideInputs` (fires only when no `TextInput`/`Composer` has focus, e.g. `j`, `k`, `r`, `/`).
  - `UiKeybinding { id, plugin_id, chord, scope, service, action_id, payload, priority }`.
  - `UiSnapshot.keybindings: Vec<UiKeybinding>` merged by active plugins in `ui-registry` (automatically filtered out when a plugin is disabled/unloaded, just like `surfaces` and `theme`).
- **Renderer behavior (`nacho-gpui`):**
  - Remove hardcoded `"service.ui.shell"` and `"service.ui.sidebar"` dispatches from `app.rs::on_root_key_down` (keeping only local modal UX like lightbox `Escape`/`Left`/`Right` and dropdown/context-menu `Escape`).
  - Match incoming `KeyDownEvent` chords (`cmd`/`ctrl`/`alt`/`shift` + key, normalizing `cmd` to `platform` on macOS and `control` on Linux/Windows) against `self.ui.keybindings` respecting `KeybindingScope` via GPUI focus checks.
  - Move default `Cmd/Ctrl+B` (`toggle_sidebar`), `Cmd/Ctrl+N` (`new_thread`), and `Escape` (`close_drawer`) registrations into `plugins/ui-shell` and `plugins/ui-sidebar`.

### P3. Generic Virtualized `Scroll` & Pagination Events
- **Location:** `crates/nacho-contracts` (`UiNode::Scroll`, `UiActionTarget`) + `crates/nacho-gpui/src/render_layout.rs` & `render_chat_list.rs`
- **Contract additions on `UiNode::Scroll` (all `#[serde(default)]`):**
  - `mode: ScrollMode` (`Standard` | `VirtualizedTop` | `VirtualizedTail`) — replaces boolean sprawl (`max_struct_bools <= 2`) and subsumes `"chat-scroll"` cleanly!
  - `on_near_start: Option<UiActionTarget>`
  - `on_near_end: Option<UiActionTarget>`
- **Renderer behavior (`nacho-gpui`):**
  - Replace single `chat_list_state` with a generic `HashMap<String, VirtualScrollEntry>` keyed by `Scroll.id`, supporting both `ListAlignment::Top` + `FollowMode::None` (feeds/ticket queues) and `ListAlignment::Top` + `FollowMode::Tail` (chat streams).
  - Evict stale entries whose `Scroll.id` is absent from the latest snapshot.
  - Debounce `on_near_end` / `on_near_start` triggers (e.g. fire once when crossing within `240px` of boundary, re-arm after moving away or when item count changes) so infinite scroll never loops.

### P4. Generic `UiNode::Image` with Bounded LRU Remote Cache
- **Location:** `crates/nacho-contracts` (`UiNode::Image`, `ImageSourceSpec`, `ImageFit`) + `crates/nacho-gpui/src/media.rs`
- **Contract:**
  - `ImageSourceSpec`: `Url { url: String }` | `Asset { name: String }` | `Base64 { mime_type: String, data_base64: String }`.
  - `ImageFit`: `Contain` (default) | `Cover` | `Fill` | `ScaleDown`.
  - `UiNode::Image { id, source, width: Option<u16>, height: Option<u16>, radius: Option<u16>, fit: ImageFit, alt: Option<String>, lightbox: bool }`.
- **Renderer behavior (`nacho-gpui`):**
  - Bounded in-memory LRU cache (`MAX_ENTRIES = 256`, `MAX_BYTES = 64 MiB`, per-image download cap `12 MiB`).
  - Only fetch `http://` and `https://` URLs; deduplicate concurrent fetches for the same URL; decode via `gpui::Image::from_bytes` (`Png`, `Jpeg`, `Webp`, `Gif`, `Svg`) and render with `img(ImageSource::Image(arc)).object_fit(...)`.
  - Render subtle placeholder surface while loading and muted fallback icon on error; support optional click-to-lightbox when `lightbox == true`.

### P5. Positioning, Layering, Overflow & `UiNode::Overlay`
- **Location:** `crates/nacho-contracts` (`PositionSpec`, `OverflowMode`, `ShadowSize`, `UiNode::Overlay`) + `crates/nacho-gpui/src/render_layout.rs`
- **Contract:**
  - `PositionSpec`: `Relative` | `Absolute { top: Option<i16>, right: Option<i16>, bottom: Option<i16>, left: Option<i16> }`.
  - `OverflowMode`: `Auto` (preserves current default) | `Visible` | `Hidden` | `ScrollX` | `ScrollY`.
  - `ShadowSize`: `None` | `Sm` | `Md` | `Lg`.
  - Add optional fields on `NodeStyle`: `position: Option<PositionSpec>`, `overflow: Option<OverflowMode>`, `z_index: Option<u16>`, `opacity: Option<u8>`, `shadow: Option<ShadowSize>`.
  - Add `UiNode::Overlay { id, dim_backdrop: bool, dismiss: Option<UiActionTarget>, children: Vec<UiNode> }`.
- **Renderer behavior (`nacho-gpui`):**
  - Map `PositionSpec::Absolute` to GPUI `.absolute()` + `.top(px(..))`/`.right(..)`/`.bottom(..)`/`.left(..)`.
  - Wrap nodes with `z_index` in `deferred(el).with_priority(z as usize)`.
  - Render `UiNode::Overlay` via `deferred(...).with_priority(200)` with `.absolute().inset_0().occlude()` so background pointer events are blocked; clicking the dimmed backdrop dispatches `dismiss`.

### P6. Per-Node Custom Colors, Typography & Hover Styles
- **Location:** `crates/nacho-contracts` (`NodeColors`, `FontWeightSpec`) + `crates/nacho-gpui/src/render_layout.rs` & `render_content.rs`
- **Contract:**
  - `NodeColors { bg: Option<String>, border: Option<String>, hover_bg: Option<String>, hover_border: Option<String>, text: Option<String>, hover_text: Option<String> }` (hex strings parsed via `theme::parse_hex_color`, supporting `#RGB`, `#RRGGBB`, `#RRGGBBAA`).
  - Add `colors: Option<NodeColors>` to `NodeStyle`.
  - Add optional `color: Option<String>`, `size_px: Option<u16>`, `weight: Option<FontWeightSpec>` (`Normal` | `Medium` | `Semibold` | `Bold`) on `UiNode::RichText`, and optional `color: Option<String>` on `UiNode::Icon`.

### P7. Generic Drag-and-Drop & 60fps `UiNode::SplitPane`
- **Location:** `crates/nacho-contracts` (`DragSpec`, `DropSpec`, `UiNode::SplitPane`) + `crates/nacho-gpui/src/render_layout.rs`
- **Contract:**
  - `DragSpec { channel: String, payload: Value, preview_label: Option<String> }`
  - `DropSpec { channel: String, service: String, plugin_id: String, action_id: String, payload: Value }`
  - Add optional `drag: Option<DragSpec>` and `drop: Option<DropSpec>` on `UiNode::Box` and `UiNode::Clickable`.
  - Add `UiNode::SplitPane { id: String, axis: Axis, initial_ratio_pct: u8, min_first_px: u16, min_second_px: u16, first: Box<UiNode>, second: Box<UiNode> }`.
- **Renderer behavior (`nacho-gpui`):**
  - Use a single generic `GenericDragData` type with GPUI's `.on_drag(...)`, `.can_drop(|data, _, _| data.channel == expected)`, `.drag_over(|style, _, _, _| style.border_color(palette.accent))`, and `.on_drop(...)` dispatching `UiActionReq` with `{ "target": drop.payload, "dragged": data.payload }`.
  - Implement `UiNode::SplitPane` using GPUI local mouse-drag tracking stored in `NachoApp.split_ratios: HashMap<String, f32>` for 60fps zero-RPC resizing.

---

## 4. Phased Implementation Plan

1. **Phase 1 — Timers (`service.timer`):** Contracts + `timer_local.rs` host capability + lifecycle auto-cancel on plugin unload + unit/E2E tests.
2. **Phase 2 — Keybindings:** Contracts + `ui-registry` aggregation + GPUI chord matching with input-focus awareness + remove hardcoded shell/sidebar shortcuts from `nacho-gpui` and move them into `ui-shell` / `ui-sidebar`.
3. **Phase 3 — Generic Virtualized Scroll & Pagination:** `ScrollMode` + `on_near_start`/`on_near_end` in contracts + generalized `VirtualScrollEntry` map in `nacho-gpui` + preserve `"chat-scroll"` seamlessly.
4. **Phase 4 — Remote `UiNode::Image` & `NodeColors` / Typography:** Bounded async LRU image cache in `nacho-gpui` + `ObjectFit` + hex color/hover/font overrides.
5. **Phase 5 — Positioning, Layering & `UiNode::Overlay`:** `PositionSpec`, `OverflowMode`, `z_index`, `opacity`, `ShadowSize`, and backdrop-occluding `UiNode::Overlay`.
6. **Phase 6 — Generic Drag-and-Drop & `UiNode::SplitPane`:** `DragSpec`/`DropSpec` via GPUI native drag-drop + 60fps `SplitPane`.
7. **Phase 7 — Docs, Devtools & Total-Reinvention Proof:** Update `docs/UI_GUIDE.md`, `docs/PLUGINS.md`, `plugins/plugin-devtools` schemas, redeploy `site/` (`getnacho.app` / `nachobot.dev`), and add an integration test suite (in `crates/nacho-host-local/tests/` and `crates/nacho-gpui` unit tests — zero example plugins under `plugins/`) proving that disabling all built-in UI plugins and mounting a custom `WindowRoot` exercises all 7 primitives cleanly.

---

## 5. Non-Negotiable Architecture Guardrails

Every phase MUST pass all checks from `AGENTS.md`:
- `crates/` stays strictly the 6 primitive crates (`nacho-wit`, `nacho-contracts`, `nacho-kernel`, `nacho-sdk`, `nacho-host-local`, `nacho-gpui`) with **zero** vendor/app/domain logic.
- Zero protected plugins; every UI and host plugin degrades cleanly when any other plugin is disabled or unloaded.
- Zero comments (`//` or `/*`) in `.rs` files.
- Zero Clippy warnings (`-D warnings`) including `cognitive_complexity <= 15`, `too_many_lines <= 60`, `too_many_arguments <= 5`, `max_struct_bools <= 2`, and no `unwrap`/`expect`/`panic`/`todo`/`dbg_macro` outside tests.
- All plugin tests (`--features native`), `wasm32-wasip2` checks, `cargo test --workspace` (including `core_architecture_guardrails`), and `nacho-gpui` Clippy + tests + `--release` build pass cleanly.
