# Elixir + Phoenix LiveView + PostgreSQL — AI Agent Guidelines & Architecture Rules

> Real-time reactive web architecture for Elixir 1.17, Phoenix 1.7+, LiveView HTML-over-WebSockets, OTP supervision trees, and Ecto.
> Technologies: Elixir, Phoenix, LiveView, PostgreSQL, Ecto, Tailwind CSS

---

## AGENTS.md
```markdown
# Project Architecture & Guidelines (Elixir + Phoenix LiveView + PostgreSQL)

## 1. System Architecture
- **Platform & Language**: Erlang/BEAM runtime with Elixir (v1.17+).
- **Web Framework**: Phoenix 1.7+ with Phoenix LiveView for reactive, zero-bundle real-time interfaces.
- **Database & Persistence**: PostgreSQL accessed via Ecto (`Ecto.Repo`, `Ecto.Changeset`).
- **Real-Time Communication**: Phoenix Channels & PubSub over persistent WebSockets.

## 2. Directory & Application Structure
- `lib/my_app/`: Core business logic domains, Ecto schemas, and context modules (e.g. `Accounts`, `Catalog`).
- `lib/my_app_web/`: Web layer containing:
  - `live/`: LiveView modules (`*_live.ex`) paired with colocated HEEx templates or `render/1` functions.
  - `components/`: Reusable function components (`core_components.ex`) using Tailwind CSS.
  - `controllers/`: REST and webhook fallback endpoints.
- `priv/repo/migrations/`: Sequential Ecto database migrations.

## 3. LiveView State & Event Lifecycle
- Handle initial page loads via `mount/3`, checking `connected?(socket)` before establishing heavy background subscriptions.
- Manage user interactions in `handle_event/3` and asynchronous process messages in `handle_info/2`.
- Use `assign/2` and `assign_async/3` to update socket state reactively; avoid accumulating unbounded lists in memory without LiveView Streams (`stream/3`).

## 4. Ecto & Data Integrity
- Encapsulate all database mutations inside Context modules; never query `Repo` directly from LiveView templates.
- Validate business constraints through dedicated `Changeset` functions with descriptive validation errors.
- Wrap multi-table operations in `Ecto.Multi` transactions for atomic rollbacks on failure.

## 5. Fault Tolerance & OTP Concurrency
- Design supervision trees (`Application.start/2`) to isolate crashing worker processes from critical web connections.
- Broadcast real-time changes using `Phoenix.PubSub.broadcast/3` to notify active LiveViews across distributed nodes.
- Enforce English-only documentation, `@doc` attributes, and `@spec` type specifications on all public context functions.

## 6. Testing Conventions
- Use `ExUnit` with `Phoenix.LiveViewTest` (`live/2`, `render_click/2`, `render_submit/2`) to test LiveView interactions without a browser.
- Test Context modules independently of LiveView — a Context function should be testable with plain `ExUnit.Case`, no web layer required.
- Use `Ecto.Adapters.SQL.Sandbox` in async mode for isolated, parallel test transactions that roll back automatically.
- Run `mix test --cover` in CI; Context modules and Changesets should carry the highest coverage since they own data integrity.

## 7. Git Workflow & PR Conventions
- Conventional Commits (`feat:`, `fix:`, `refactor:`) scoped to the context or LiveView, e.g. `fix(accounts): validate email uniqueness case-insensitively`.
- Ecto migrations ship in the same PR as the schema/Changeset change that requires them.
- Require `mix test`, `mix format --check-formatted`, and `mix credo --strict` green before merge.
- Squash-merge; run `mix ecto.migrate` in CI against a throwaway database to catch migration errors before deploy.
```

---

## CLAUDE.md
```markdown
# CLAUDE.md — Elixir + Phoenix LiveView Commands & Conventions

## Common Commands
- `mix phx.server` - Start development server with LiveReload at localhost:4000
- `mix test` - Run automated test suite
- `mix format --check-formatted` - Verify Elixir formatting
- `mix credo --strict` - Run Elixir static code analysis
- `mix ecto.migrate` - Run pending PostgreSQL database migrations
- `mix ecto.rollback` - Roll back the latest migration

## Code Style Guidelines
- Leverage pattern matching in function heads rather than deeply nested `if/else` or `case` blocks.
- Use the pipe operator `|>` cleanly with the subject as the first parameter.
- Style UI elements using Tailwind CSS utility classes within HEEx `~H"""..."""` blocks.
- Keep LiveViews focused on presentation; delegate all persistence to Context modules.
```

---

## .cursor/rules/stack.mdc
```markdown
---
description: Elixir + Phoenix LiveView + PostgreSQL architecture rules
globs: ["**/*.ex", "**/*.heex"]
alwaysApply: true
---

# Elixir + Phoenix LiveView + PostgreSQL

- Elixir 1.17+ on BEAM, Phoenix 1.7+ with LiveView, Ecto over PostgreSQL.
- `live/` LiveView modules paired with HEEx templates; `components/` for reusable function components.
- Check `connected?(socket)` in `mount/3` before establishing heavy subscriptions — the first mount is disconnected (static render).
- `handle_event/3` for user interactions, `handle_info/2` for async process messages; use `stream/3` for growing collections, never unbounded assigns.
- Never query `Repo` directly from a LiveView or template — all persistence goes through Context modules.
- Wrap multi-table mutations in `Ecto.Multi` for atomic rollback on failure.
- Isolate crash-prone workers in the supervision tree so one crash never takes down web connections.
- `Phoenix.PubSub.broadcast/3` for cross-node real-time updates. `@doc`/`@spec` on every public Context function.
```

---

## Architecture Overview & Best Practices
## Architecture Overview

Standardized production guidelines for **Elixir**, **Phoenix LiveView**, and **PostgreSQL**.

### Key Advantages

- **Zero JavaScript Overhead**: LiveView computes differential DOM diffs on the server and pushes minimal binary payloads over WebSockets.
- **BEAM Fault Tolerance**: Erlang's battle-tested actor model isolates failure so individual user crashes never take down the system.
- **Instant Real-Time Sync**: Built-in Phoenix PubSub coordinates live updates across millions of concurrent users with negligible CPU footprint.