slabs-core 0.1.0

Core error, ID, config, and manifest primitives for Slabs
Documentation
# Slabs

An 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.

- **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`, e.g., `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 test 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 gentle Clippy defaults, CLAUDE.md, and GitHub Actions 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

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; }`.
- **Production defaults.** Axum serves gzip and brotli compression, ULID `X-Request-Id` headers, `CorsLayer::permissive()`, `X-Frame-Options: SAMEORIGIN`, `X-Content-Type-Options: nosniff`, 25 MiB body limits, explicit in-memory rate limiting (`ctx.rate_limit.check`), JSON logging (`SLABS_LOG_FORMAT=json`), and graceful `SIGINT`/`SIGTERM` shutdown for HTTP and background workers.

## Agent skills

Slabs ships three procedural skills in [`skills/`](skills/) for AI coding agents working on Slabs applications:

| 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) | 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. |

## 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, `AppConfig`, and `AppManifest`. |
| `slabs-db` | Split SQLite WAL pools, `PgDb` PostgreSQL pool, system migrations, `QueryBuilder`, `fts5_query`, and `dump_schema_sql`. |
| `slabs-auth` | Argon2id password hashing, cookie sessions, single-use 6-character magic links, and SHA-256 Bearer access tokens. |
| `slabs-http` | Axum 0.8 router builder, `AppCtx`, `SlabDef`, `JobDef`, `ScheduleDef`, `RateLimiter`, vendored UI assets, and middleware. |
| `slabs-html` | Maud re-exports, HTML document shell, safe `render_markdown`, 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). |
| `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`) and WebSockets. |
| `slabs-webhooks` | HMAC-SHA256 signed outbound webhooks with transactional dispatch and loopback SSRF blocking. |
| `slabs-test` | Ephemeral in-memory `TestApp::boot` helper for isolated parallel slab tests. |
| `slabs-cli` | `slabs` CLI for app and slab generation, 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 Slabs app with gentle Clippy defaults, `CLAUDE.md`, and GitHub Actions CI. |
| `slabs new slab <feature> <name> [--method <verb>] [--path <route>]` | Create `slabs/<feature>/<name>.rs` without editing any existing file. |
| `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 full CI check suite (formatting, Clippy `-D warnings`, Rustdoc `-D warnings`, doctests, and `cargo nextest` or `cargo test`). |
| `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 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 [`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).