slabs-core 0.4.0

Core error, ID, config, and manifest primitives for Slabs
Documentation
<p align="left">
  <img src="assets/slabs-logo.svg" alt="Slabs" height="52" />
</p>

# Slabs

A batteries-included Rust web framework built for parallel AI agents and humans. Every HTTP endpoint is a self-contained Transaction Script with raw SQL, explicit transactions, and compile-time discovery, so multiple contributors can ship features in parallel with zero merge conflicts.

- **Architecture and philosophy:** [`DOCTRINE.md`](DOCTRINE.md)
- **Live documentation site:** [sogamoso.github.io/slabs-docs](https://sogamoso.github.io/slabs-docs/) ([`sogamoso/slabs-docs`](https://github.com/sogamoso/slabs-docs))
- **Full-stack example apps (Campfire, Fizzy, Writebook):** [`sogamoso/slabs-examples`](https://github.com/sogamoso/slabs-examples)
- **Main crate (`crates.io`):** `slabs-framework` (imported in Rust as `slabs`, for example `use slabs::prelude::*;`)

## Quickstart

Install the pinned toolchain (`rust`, standalone `tailwindcss` v4, and `cargo-nextest`) with [mise](https://mise.jdx.dev/), then run the workspace verification suite or generate a new application:

```bash
mise install

# Run all core crate tests and doctests
mise exec -- cargo test --doc --workspace
mise exec -- cargo nextest run --workspace

# Install the slabs CLI locally
mise exec -- cargo install --path crates/slabs-cli

# Generate a new standalone Slabs app with cargo-chef Dockerfile, Litestream, bundled skills, and CI
slabs new app my_app
```

## What a slab looks like

Each endpoint lives in its own file under `slabs/<feature>/<action>.rs`. There is no central `routes.rs`, no ORM, and no `models/` or `controllers/` hierarchy. `slabs-build` discovers every file at compile time and registers its route automatically.

```rust
// slabs/cards/create_card.rs
use axum::{extract::State, http::StatusCode, Json};
use axum_extra::extract::CookieJar;
use serde::{Deserialize, Serialize};
use slabs::prelude::*;

pub fn slab() -> SlabDef {
    SlabDef::post("/api/boards/{board_id}/cards", handle)
        .name("cards.create_card")
        .summary("Create a card and enqueue watcher notifications atomically")
}

#[derive(Debug, Deserialize)]
pub struct Input {
    pub title: String,
}

#[derive(Debug, Serialize)]
pub struct Output {
    pub id: String,
    pub title: String,
}

async fn handle(
    State(ctx): State<AppCtx>,
    jar: CookieJar,
    axum::extract::Path(board_id): axum::extract::Path<String>,
    Json(input): Json<Input>,
) -> SlabResult<(StatusCode, Json<Output>)> {
    let session = ctx.auth.require_session(&jar).await?;
    ctx.rate_limit
        .check(&format!("cards:create:{}", session.user_id), 60, 60)?;

    let title = input.title.trim().to_string();
    if title.is_empty() {
        return Err(SlabError::bad_request("title is required"));
    }

    let card_id = id::new("crd");
    let mut tx = ctx.db.begin().await?;

    sqlx::query("INSERT INTO cards (id, board_id, creator_id, title) VALUES (?, ?, ?, ?)")
        .bind(&card_id)
        .bind(&board_id)
        .bind(&session.user_id)
        .bind(&title)
        .execute(&mut *tx)
        .await?;

    ctx.jobs
        .enqueue_in_tx(
            &mut tx,
            "notify_watchers",
            serde_json::json!({ "card_id": card_id }),
        )
        .await?;

    tx.commit().await?;
    Ok((StatusCode::CREATED, Json(Output { id: card_id, title })))
}
```

## Architecture

Read [`DOCTRINE.md`](DOCTRINE.md) for the eight pillars behind Slabs. At the crate level, Slabs combines Axum 0.8 and SQLx 0.8 with explicit, low-level libraries attached to `AppCtx`:

- **Compile-time file discovery.** A one-line `build.rs` calls `slabs_build::discover()`, generating `$OUT_DIR/discovered_slabs.rs` from `slabs/<feature>/*.rs` and `jobs/*.rs`. `src/lib.rs` includes it with `slabs::discover_slabs!()` and passes `collect_slabs()`, `collect_jobs()`, and `sqlx::migrate!("./migrations")` into `SlabsApp::boot(...)`.
- **Split SQLite WAL pools and PostgreSQL support.** `AppCtx.db` opens a 16-connection read-only pool (`ctx.db.reader()`) and a dedicated 1-connection writer pool (`ctx.db.writer()`, where `ctx.db.begin()` runs `BEGIN IMMEDIATE`). `slabs_db::PgDb` and `slabs db migrate` / `dump-schema` also support standalone PostgreSQL connections (`DATABASE_URL=postgres://...`).
- **Optional compile-time SQL checks.** Write raw `sqlx::query` statements immediately, or run `slabs db prepare` to generate offline `.sqlx/` metadata for compile-time checked `sqlx::query!` and `sqlx::query_as!`.
- **MIT-licensed HTML frontend with zero Node.** Render typed HTML in Rust with `maud!` and `html::document(title, &ctx.assets.stylesheet_urls(), &ctx.assets.behavior_urls(), body)`, render untrusted Markdown safely with `html::render_markdown(&text)`, style with standalone Tailwind CSS v4 and vendored Basecoat UI (shadcn tokens for plain HTML), update pages with HTMX 2, SSE, and Idiomorph (`hx-ext="morph"`), and handle local state with Alpine.js 3, native `<dialog>`, and `@view-transition { navigation: auto; }`.
- **Fail-closed security and production defaults.** `AppEnv` (`SLABS_ENV=development|staging|production`) enforces a 32-byte random `SLABS_SECRET_KEY` in staging and production. Axum serves gzip and brotli compression, ULID `X-Request-Id` headers, Fetch Metadata CSRF protection, opt-in CORS (`SLABS_CORS_ORIGINS`), gated proxy trust (`SLABS_TRUST_PROXY`), `X-Frame-Options: SAMEORIGIN`, `X-Content-Type-Options: nosniff`, 4 MiB default body limits (`SLABS_MAX_BODY_BYTES`), `GET /health/ready`, `GET /_slabs/metrics`, explicit in-memory rate limiting (`ctx.rate_limit.check` and `check_pair`), `slab_file`-tagged structured JSON logging (`SLABS_LOG_FORMAT=json`), and graceful `SIGINT`/`SIGTERM` shutdown with SQLite `PRAGMA wal_checkpoint(TRUNCATE)`.
- **Built-in incident tracking and per-route latency telemetry.** Every Slabs app maintains a 3-state (`open`, `resolved`, `reopened`) Active Failures Inbox in `slabs_incidents` with configurable stale auto-close (`SLABS_INCIDENT_STALE_DAYS`, default 30), recording deduplicated runtime errors (`http_5xx`, `panic`, `job_dead`, `user_bug_report`) and slow operations (`slow_request`, `slow_job`). It exposes `GET /_slabs/incidents`, `GET /_slabs/incidents/{id}` (with ready-to-paste `repro_test` skeletons), and `POST /_slabs/incidents/{id}/resolve`, tracks per-route latency histograms (`p50`/`p95`/`p99`/`max`, slow counts, 5xx counts) in `GET /_slabs/metrics`, and ships `Db::explain_query_plan` for indexed query verification in tests. Run `slabs new bug-report` to scaffold an editable, zero-JS user bug-report slab.

## Agent skills

Slabs ships five procedural skills in [`skills/`](skills/) for AI coding agents working on Slabs applications (and `slabs new app` bundles all five into `.claude/skills/`):

| Skill | Purpose |
| --- | --- |
| [`skills/add-slab/SKILL.md`](skills/add-slab/SKILL.md) | End-to-end procedure for authoring, guarding, testing, and formatting a new Transaction Script. |
| [`skills/add-migration/SKILL.md`](skills/add-migration/SKILL.md) | Expand-and-contract schema migration, `schema.sql` refresh, and `.sqlx/` preparation workflow. |
| [`skills/review-slab/SKILL.md`](skills/review-slab/SKILL.md) | Audit checklist for Slabs-specific transaction, security, HTML, and formatting pitfalls. |
| [`skills/deploy-app/SKILL.md`](skills/deploy-app/SKILL.md) | Production pre-flight checks, zero-downtime deployment, and rollback checklist for Kamal 2, Fly.io, and VPS hosts. |
| [`skills/fix-incident/SKILL.md`](skills/fix-incident/SKILL.md) | Closed-loop triage, reproduction, query-plan inspection, and fix workflow for runtime incidents and slow routes. |

## Workspace crates

| Crate | Responsibility |
| --- | --- |
| `slabs-framework` (`use slabs::...`) | Top-level facade, `prelude::*`, `discover_slabs!()`, `SlabsApp::boot`, `SlabsApp::serve`, and `init_tracing()`. |
| `slabs-build` | Build-script scanner that generates `$OUT_DIR/discovered_slabs.rs` from `slabs/` and `jobs/`. |
| `slabs-core` | Prefixed ULIDs (`id::new`), URL slugs (`slug::slugify`), fractional positions (`position::between`), SHA-256 `fingerprint`, `SlabError` HTTP mapping, `AppEnv`, `AppConfig`, and `AppManifest`. |
| `slabs-db` | Split SQLite WAL pools, `PgDb` PostgreSQL pool, system migrations (including `slabs_incidents`), `QueryBuilder`, `explain_query_plan`, `fts5_query`, `AuditLog`, cursor pagination, and `dump_schema_sql`. |
| `slabs-auth` | Async Argon2id password hashing, cookie sessions, single-use 6-character magic links, signed expiring tokens, and SHA-256 Bearer access tokens. |
| `slabs-http` | Axum 0.8 router builder, `AppCtx`, `SlabDef`, `JobDef`, `ScheduleDef`, `RateLimiter`, Fetch Metadata CSRF, `/health/ready`, `/_slabs/metrics` with per-route histograms, `/_slabs/incidents`, vendored UI assets, and `slab_file`-tagged tracing middleware. |
| `slabs-html` | Maud re-exports, HTML document shell, safe `render_markdown`, signed flash cookies, HTMX `HX-*` and `hx-swap-oob` helpers, and CSRF helpers. |
| `slabs-assets` | Content-hashed static asset loader (`/assets/{hash}/{*path}`) with immutable cache headers. |
| `slabs-jobs` | SQLite-backed durable job queue with transactional `enqueue_in_tx`, exponential backoff, and dead-lettering. |
| `slabs-mail` | Outbox mailer with Resend HTTP API (`SLABS_RESEND_API_KEY`) and SMTP (`SLABS_SMTP_URL`) transports. |
| `slabs-storage` | Local disk storage and path-style AWS SigV4 S3 backend (AWS S3, Cloudflare R2, MinIO, Tigris) with safe blob serving and opt-in image resizing. |
| `slabs-cache` | SQLite TTL key-value cache with RFC 3339 expiration and lazy purging. |
| `slabs-realtime` | In-process broadcast hub for SSE streams (`publish_html`, `publish_json`), WebSockets, and `Presence` tracking. |
| `slabs-webhooks` | HMAC-SHA256 signed outbound and inbound webhooks with transactional dispatch and DNS-resolving SSRF blocking. |
| `slabs-test` | Ephemeral in-memory `TestApp::boot` helper for isolated parallel slab tests. |
| `slabs-cli` | `slabs` CLI for app and slab generation, `[security]` static analysis, `doctor`, `deploy init`, `incidents`, formatting, database tasks, Tailwind builds, and live dev. |

## CLI commands

Run the CLI from this workspace with `mise exec -- cargo run -p slabs-cli -- [--app-dir <dir>] <command>`, or install the `slabs` binary locally with `cargo install --path crates/slabs-cli`.

| Command | Action |
| --- | --- |
| `slabs new app <name>` | Create a standalone PWA-ready Slabs app with `cargo-chef` + Litestream `Dockerfile`, `docker-entrypoint.sh`, `.dockerignore`, bundled `.claude/skills/`, `seeds.sql`, gentle Clippy defaults, `CLAUDE.md`, and GitHub Actions CI. |
| `slabs new slab <feature> <name> [--method <verb>] [--path <route>]` | Create `slabs/<feature>/<name>.rs` with validated identifiers, starter guard, and co-located test without editing any existing file. |
| `slabs new bug-report [--feature support] [--name report_bug]` | Create an editable, zero-JS multipart user bug-report slab with Basecoat form helper, scoped attachment storage, and co-located tests. |
| `slabs new job <name>` | Create `jobs/<name>.rs` without editing any existing file. |
| `slabs fmt [--check]` | Format the crate and all auto-discovered files under `slabs/` and `jobs/`. |
| `slabs check [--workspace] [--no-docs]` | Run the 6-step CI suite (formatting, `[security]` static scan, Clippy `-D warnings`, Rustdoc `-D warnings`, doctests, and `cargo nextest` or `cargo test`). |
| `slabs doctor` | Verify Rust toolchain, `unsafe_code = "forbid"`, `schema.sql`, `.dockerignore`, `SLABS_ENV`/`SLABS_SECRET_KEY`, and security scan summary. |
| `slabs deploy init --target <kamal\|fly\|vps> [--db <sqlite\|postgres>]` | Generate database-aware zero-downtime deployment templates (`config/deploy.yml`, `fly.toml`, or `deploy/Caddyfile` + hardened `systemd` unit). |
| `slabs incidents <list\|show\|resolve\|perf>` | Inspect active, open, reopened, resolved, or all incidents from `/_slabs/incidents`, view full detail and `repro_test` skeletons, mark incidents resolved with a commit SHA, or print per-route latency percentiles (`p50`/`p95`/`p99`/`max`) ranked slowest first from `/_slabs/metrics`. |
| `slabs dev` | Run standalone Tailwind CSS v4 `--watch` alongside `cargo watch` (or `cargo run`). |
| `slabs css [--watch]` | Compile `assets/input.css` to `assets/styles/app.css` with Tailwind CSS v4. |
| `slabs db migrate` | Apply SQL migrations from `migrations/` to SQLite or PostgreSQL. |
| `slabs db dump-schema` | Write the live database schema snapshot to `schema.sql`. |
| `slabs db seed` | Apply an idempotent SQL seed script (`seeds.sql`) to SQLite or PostgreSQL. |
| `slabs db prepare` | Generate offline `.sqlx/` metadata for compile-time checked `sqlx::query!`. |
| `slabs list` | Print all discovered slabs and jobs in an app directory. |

## Reference applications

Three full-stack applications rebuilt from Ruby on Rails live in [`sogamoso/slabs-examples`](https://github.com/sogamoso/slabs-examples):

- **Campfire** (rebuilt from [`basecamp/once-campfire`](https://github.com/basecamp/once-campfire)): group chat with 27 slabs, 2 jobs, FTS5 message search, SSE live rooms, boosts, file uploads, and webhook bots.
- **Fizzy** (rebuilt from [`basecamp/fizzy`](https://github.com/basecamp/fizzy)): Kanban tracker with 28 slabs, 2 jobs, passwordless magic links, Bearer API tokens, multi-filter board views, native `<dialog>` card modals with Idiomorph, signed webhooks, and an entropy cron job.
- **Writebook** (rebuilt from [`basecamp/writebook`](https://github.com/basecamp/writebook)): book publishing app with 25 slabs, 1 job, Markdown pages, section dividers, multipart picture uploads, SHA-256 fingerprint conflict detection, O(1) fractional leaf reordering, revision history, and FTS5 `porter` search.

## Formatting, linting, and CI

Core crates enforce default `rustfmt`, `unsafe_code = "forbid"`, `missing_docs`, `missing_debug_implementations`, `unreachable_pub`, `rust_2018_idioms`, `clippy::pedantic`, and permissive OSS licenses ([`deny.toml`](deny.toml)). User apps generated by `slabs new app` enforce gentle guardrails (`unsafe_code = "forbid"`, `dbg_macro`, `todo`, `unimplemented`, `await_holding_lock`, `await_holding_refcell_ref`).

Run the full CI check locally in one command:

```bash
mise exec -- cargo run -q -p slabs-cli -- check
```

Or run each step individually:

```bash
mise exec -- cargo fmt --all -- --check
mise exec -- cargo clippy --workspace --all-targets -- -D warnings
RUSTDOCFLAGS="-D warnings" mise exec -- cargo doc --workspace --no-deps
mise exec -- cargo test --doc --workspace
mise exec -- cargo nextest run --workspace
```

## Contributing, releasing, and security

- Read [`DOCTRINE.md`](DOCTRINE.md), [`AGENTS.md`](AGENTS.md), and [`CONTRIBUTING.md`](CONTRIBUTING.md) before opening a pull request.
- Follow [`RELEASING.md`](RELEASING.md) to publish all 16 crates to `crates.io`.
- Report security issues privately following [`SECURITY.md`](SECURITY.md).
- Track releases in [`CHANGELOG.md`](CHANGELOG.md).

## License

MIT. See [`LICENSE`](LICENSE).