use clap::{Parser, Subcommand, ValueEnum};
use serde_json::{json, Value};
use slabs_db::{Db, DbEngine, PgDb};
use std::fmt::Write as _;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::process::Command;
#[derive(Parser, Debug)]
#[command(
name = "slabs",
about = "Batteries-included, agent-first Transaction Script web framework CLI"
)]
struct Cli {
#[arg(long, global = true, default_value = ".")]
app_dir: PathBuf,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
New {
#[command(subcommand)]
kind: NewKind,
},
Db {
#[command(subcommand)]
action: DbAction,
},
Fmt {
#[arg(long)]
check: bool,
},
Check {
#[arg(long)]
workspace: bool,
#[arg(long)]
no_docs: bool,
},
Doctor,
Deploy {
#[command(subcommand)]
action: DeployAction,
},
List,
Css {
#[arg(long)]
watch: bool,
},
Dev {
#[arg(long, short)]
package: Option<String>,
#[arg(long)]
bind: Option<String>,
},
Incidents {
#[command(subcommand)]
action: IncidentsAction,
},
Mcp {
#[arg(long, env = "SLABS_URL", default_value = "http://127.0.0.1:3000")]
url: String,
#[arg(long, env = "SLABS_METRICS_TOKEN")]
token: Option<String>,
},
}
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
enum HttpMethod {
Get,
Post,
Put,
Patch,
Delete,
}
impl HttpMethod {
const fn as_str(self) -> &'static str {
match self {
Self::Get => "get",
Self::Post => "post",
Self::Put => "put",
Self::Patch => "patch",
Self::Delete => "delete",
}
}
const fn axum_const(self) -> &'static str {
match self {
Self::Get => "GET",
Self::Post => "POST",
Self::Put => "PUT",
Self::Patch => "PATCH",
Self::Delete => "DELETE",
}
}
}
#[derive(Subcommand, Debug)]
enum NewKind {
App {
name: String,
#[arg(long)]
dir: Option<PathBuf>,
},
Slab {
feature: String,
name: String,
#[arg(long, value_enum, default_value_t = HttpMethod::Post)]
method: HttpMethod,
#[arg(long)]
path: Option<String>,
},
Job { name: String },
}
#[derive(Subcommand, Debug)]
enum DeployAction {
Init {
#[arg(long, value_enum)]
target: DeployTarget,
#[arg(long)]
app: Option<String>,
#[arg(long)]
force: bool,
},
}
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
enum DeployTarget {
Kamal,
Fly,
Vps,
}
#[derive(ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
enum IncidentStatusFilter {
Open,
#[value(name = "in_progress")]
InProgress,
Resolved,
Ignored,
All,
}
impl IncidentStatusFilter {
const fn as_str(self) -> &'static str {
match self {
Self::Open => "open",
Self::InProgress => "in_progress",
Self::Resolved => "resolved",
Self::Ignored => "ignored",
Self::All => "all",
}
}
}
#[derive(Subcommand, Debug)]
enum IncidentsAction {
List {
#[arg(long, env = "SLABS_URL", default_value = "http://127.0.0.1:3000")]
url: String,
#[arg(long, env = "SLABS_METRICS_TOKEN")]
token: Option<String>,
#[arg(long, value_enum, default_value_t = IncidentStatusFilter::Open)]
status: IncidentStatusFilter,
#[arg(long, default_value_t = 50)]
limit: u32,
#[arg(long)]
json: bool,
},
Show {
id: String,
#[arg(long, env = "SLABS_URL", default_value = "http://127.0.0.1:3000")]
url: String,
#[arg(long, env = "SLABS_METRICS_TOKEN")]
token: Option<String>,
#[arg(long)]
json: bool,
},
Claim {
id: String,
#[arg(long)]
assignee: String,
#[arg(long, env = "SLABS_URL", default_value = "http://127.0.0.1:3000")]
url: String,
#[arg(long, env = "SLABS_METRICS_TOKEN")]
token: Option<String>,
},
Link {
id: String,
#[arg(long)]
key: String,
#[arg(long = "issue-url")]
issue_url: String,
#[arg(long, env = "SLABS_URL", default_value = "http://127.0.0.1:3000")]
url: String,
#[arg(long, env = "SLABS_METRICS_TOKEN")]
token: Option<String>,
},
Ignore {
id: String,
#[arg(long, env = "SLABS_URL", default_value = "http://127.0.0.1:3000")]
url: String,
#[arg(long, env = "SLABS_METRICS_TOKEN")]
token: Option<String>,
},
Resolve {
id: String,
#[arg(long)]
sha: Option<String>,
#[arg(long, env = "SLABS_URL", default_value = "http://127.0.0.1:3000")]
url: String,
#[arg(long, env = "SLABS_METRICS_TOKEN")]
token: Option<String>,
},
Perf {
#[arg(long, env = "SLABS_URL", default_value = "http://127.0.0.1:3000")]
url: String,
#[arg(long, env = "SLABS_METRICS_TOKEN")]
token: Option<String>,
#[arg(long)]
json: bool,
},
}
#[derive(Subcommand, Debug)]
enum DbAction {
Migrate {
#[arg(long, env = "DATABASE_URL")]
database_url: String,
},
DumpSchema {
#[arg(long, env = "DATABASE_URL")]
database_url: String,
},
Seed {
#[arg(long, env = "DATABASE_URL")]
database_url: String,
#[arg(long)]
file: Option<PathBuf>,
},
Prepare {
#[arg(long, env = "DATABASE_URL")]
database_url: Option<String>,
#[arg(long, short)]
package: Option<String>,
},
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
match cli.command {
Commands::New { kind } => match kind {
NewKind::App { name, dir } => {
validate_app_name(&name)?;
let target_dir = dir.unwrap_or_else(|| PathBuf::from(&name));
scaffold_app(&name, &target_dir)?;
println!("Created Slabs app `{name}` in {}", target_dir.display());
}
NewKind::Slab {
feature,
name,
method,
path,
} => {
validate_rust_ident(&feature)?;
validate_rust_ident(&name)?;
let route_path = path.unwrap_or_else(|| format!("/api/{feature}/{name}"));
validate_route_path(&route_path)?;
let dir = cli.app_dir.join("slabs").join(&feature);
fs::create_dir_all(&dir)?;
let target = dir.join(format!("{name}.rs"));
if target.exists() {
return Err(format!("slab already exists: {}", target.display()).into());
}
let template = render_slab_template(&feature, &name, method, &route_path);
fs::write(&target, template)?;
println!("Created slab: {}", target.display());
}
NewKind::Job { name } => {
validate_rust_ident(&name)?;
let dir = cli.app_dir.join("jobs");
fs::create_dir_all(&dir)?;
let target = dir.join(format!("{name}.rs"));
if target.exists() {
return Err(format!("job already exists: {}", target.display()).into());
}
let template = render_job_template(&name);
fs::write(&target, template)?;
println!("Created job: {}", target.display());
}
},
Commands::Db { action } => match action {
DbAction::Migrate { database_url } => {
let migrations_dir = cli.app_dir.join("migrations");
match DbEngine::detect(&database_url) {
DbEngine::Sqlite => {
let db = Db::connect(&database_url).await?;
db.migrate_dir(&migrations_dir).await?;
println!(
"SQLite migrations applied from {}",
migrations_dir.display()
);
}
DbEngine::Postgres => {
let db = PgDb::connect(&database_url).await?;
db.migrate_dir(&migrations_dir).await?;
println!(
"PostgreSQL migrations applied from {}",
migrations_dir.display()
);
}
}
}
DbAction::DumpSchema { database_url } => {
let schema_sql = match DbEngine::detect(&database_url) {
DbEngine::Sqlite => {
let db = Db::connect(&database_url).await?;
db.dump_schema_sql().await?
}
DbEngine::Postgres => {
let db = PgDb::connect(&database_url).await?;
db.dump_schema_sql().await?
}
};
let target = cli.app_dir.join("schema.sql");
fs::write(&target, schema_sql)?;
println!("Wrote schema snapshot to {}", target.display());
}
DbAction::Seed { database_url, file } => {
let seed_file = file.unwrap_or_else(|| cli.app_dir.join("seeds.sql"));
match DbEngine::detect(&database_url) {
DbEngine::Sqlite => {
let db = Db::connect(&database_url).await?;
db.execute_sql_file(&seed_file).await?;
println!("Applied SQLite seed script from {}", seed_file.display());
}
DbEngine::Postgres => {
let db = PgDb::connect(&database_url).await?;
db.execute_sql_file(&seed_file).await?;
println!(
"Applied PostgreSQL seed script from {}",
seed_file.display()
);
}
}
}
DbAction::Prepare {
database_url,
package,
} => {
let pkg = match package {
Some(p) => {
validate_app_name(&p)?;
p
}
None => infer_package_name(&cli.app_dir)?,
};
let (url, temp_file) = if let Some(u) = database_url {
(u, None)
} else {
let tmp = std::env::temp_dir().join(format!(
"slabs_prepare_{pkg}_{}.db",
slabs_core::id::new("tmp")
));
let u = format!("sqlite://{}", tmp.display());
let db = Db::connect(&u).await?;
db.migrate_dir(&cli.app_dir.join("migrations")).await?;
(u, Some(tmp))
};
let status = Command::new("cargo")
.args(["sqlx", "prepare", "--", "-p", &pkg, "--all-targets"])
.env("DATABASE_URL", &url)
.status()
.await;
if let Some(tmp) = temp_file {
let _ = fs::remove_file(&tmp);
let _ = fs::remove_file(format!("{}-wal", tmp.display()));
let _ = fs::remove_file(format!("{}-shm", tmp.display()));
}
match status {
Ok(s) if s.success() => {
println!("Prepared compile-time SQLx metadata (.sqlx/) for `{pkg}`");
}
_ => {
return Err(
"cargo sqlx prepare failed. Install sqlx-cli via: `cargo install sqlx-cli --no-default-features --features sqlite,postgres`"
.into(),
);
}
}
}
},
Commands::Fmt { check } => {
run_fmt(&cli.app_dir, check).await?;
}
Commands::Check { workspace, no_docs } => {
run_check(&cli.app_dir, workspace, no_docs).await?;
}
Commands::Doctor => {
run_doctor(&cli.app_dir).await?;
}
Commands::Deploy { action } => match action {
DeployAction::Init { target, app, force } => {
let app_name = match app {
Some(a) => {
validate_app_name(&a)?;
a
}
None => infer_package_name(&cli.app_dir)?,
};
let created = scaffold_deploy(&cli.app_dir, &app_name, target, force)?;
for path in created {
println!("Created deployment template: {}", path.display());
}
}
},
Commands::List => {
list_dir(&cli.app_dir)?;
}
Commands::Css { watch } => {
run_tailwind(&cli.app_dir, watch).await?;
}
Commands::Dev { package, bind } => {
run_dev(&cli.app_dir, package, bind).await?;
}
Commands::Incidents { action } => match action {
IncidentsAction::List {
url,
token,
status,
limit,
json,
} => {
run_incidents_list(&url, token.as_deref(), status, limit, json).await?;
}
IncidentsAction::Show {
id,
url,
token,
json,
} => {
run_incidents_show(&url, token.as_deref(), &id, json).await?;
}
IncidentsAction::Claim {
id,
assignee,
url,
token,
} => {
run_incidents_claim(&url, token.as_deref(), &id, &assignee).await?;
}
IncidentsAction::Link {
id,
key,
issue_url,
url,
token,
} => {
run_incidents_link(&url, token.as_deref(), &id, &key, &issue_url).await?;
}
IncidentsAction::Ignore { id, url, token } => {
run_incidents_ignore(&url, token.as_deref(), &id).await?;
}
IncidentsAction::Resolve {
id,
sha,
url,
token,
} => {
run_incidents_resolve(&url, token.as_deref(), &id, sha.as_deref()).await?;
}
IncidentsAction::Perf { url, token, json } => {
run_incidents_perf(&url, token.as_deref(), json).await?;
}
},
Commands::Mcp { url, token } => {
run_mcp_stdio(&url, token.as_deref()).await?;
}
}
Ok(())
}
const RUST_KEYWORDS: &[&str] = &[
"as", "async", "await", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern",
"false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub",
"ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type",
"unsafe", "use", "where", "while", "abstract", "become", "box", "do", "final", "gen", "macro",
"override", "priv", "try", "typeof", "unsized", "virtual", "yield", "union",
];
fn validate_rust_ident(value: &str) -> Result<(), String> {
let mut chars = value.chars();
let Some(first) = chars.next() else {
return Err("identifier must not be empty".to_string());
};
if !first.is_ascii_lowercase() {
return Err(format!(
"invalid Rust identifier `{value}`: must match ^[a-z][a-z0-9_]*$"
));
}
if !chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') {
return Err(format!(
"invalid Rust identifier `{value}`: must match ^[a-z][a-z0-9_]*$"
));
}
if RUST_KEYWORDS.contains(&value) {
return Err(format!(
"invalid Rust identifier `{value}`: reserved Rust keyword"
));
}
Ok(())
}
fn validate_app_name(value: &str) -> Result<(), String> {
if value.is_empty() || value.len() > 64 {
return Err(format!(
"invalid app name `{value}`: must be 1 to 64 characters matching ^[a-z][a-z0-9_-]*$"
));
}
let mut chars = value.chars();
let Some(first) = chars.next() else {
return Err("app name must not be empty".to_string());
};
if !first.is_ascii_lowercase()
|| !chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
{
return Err(format!(
"invalid app name `{value}`: must match ^[a-z][a-z0-9_-]*$"
));
}
Ok(())
}
fn validate_route_path(value: &str) -> Result<(), String> {
if !value.starts_with('/') {
return Err(format!("invalid route path `{value}`: must start with `/`"));
}
if value.chars().any(|c| {
c.is_whitespace() || c == '"' || c == '\\' || c == '\r' || c == '\n' || c.is_control()
}) {
return Err(format!(
"invalid route path `{value}`: must not contain whitespace, quotes, backslashes, or control characters"
));
}
Ok(())
}
fn render_slab_template(feature: &str, name: &str, method: HttpMethod, route_path: &str) -> String {
let method_lower = method.as_str();
let axum_method = method.axum_const();
if method == HttpMethod::Get {
format!(
r#"use axum::{{extract::State, http::StatusCode, Json}};
use axum_extra::extract::CookieJar;
use serde::Serialize;
use slabs::prelude::*;
pub fn slab() -> SlabDef {{
SlabDef::get("{route_path}", handle)
.name("{feature}.{name}")
.summary("TODO: describe {feature}.{name}")
}}
#[derive(Debug, Serialize)]
pub struct Output {{
pub ok: bool,
}}
async fn handle(
State(ctx): State<AppCtx>,
jar: CookieJar,
) -> SlabResult<(StatusCode, Json<Output>)> {{
let session = ctx.auth.require_session(&jar).await?;
// Enforce resource ownership or role checks against `session.user_id` before returning data.
tracing::debug!(user_id = %session.user_id, "handling {feature}.{name}");
let _reader = ctx.db.reader();
Ok((StatusCode::OK, Json(Output {{ ok: true }})))
}}
#[cfg(test)]
mod tests {{
use axum::http::StatusCode;
#[tokio::test]
async fn requires_authentication() {{
let app = crate::test_app().await;
let res = app.get("{route_path}").await;
assert_eq!(res.status, StatusCode::UNAUTHORIZED);
}}
}}
"#
)
} else {
format!(
r#"use axum::{{extract::State, http::StatusCode, Json}};
use axum_extra::extract::CookieJar;
use serde::{{Deserialize, Serialize}};
use slabs::prelude::*;
pub fn slab() -> SlabDef {{
SlabDef::{method_lower}("{route_path}", handle)
.name("{feature}.{name}")
.summary("TODO: describe {feature}.{name}")
}}
#[derive(Debug, Deserialize)]
pub struct Input {{
// Define request fields here, owned locally by this slab.
}}
#[derive(Debug, Serialize)]
pub struct Output {{
pub ok: bool,
}}
async fn handle(
State(ctx): State<AppCtx>,
jar: CookieJar,
Json(_input): Json<Input>,
) -> SlabResult<(StatusCode, Json<Output>)> {{
let session = ctx.auth.require_session(&jar).await?;
// Enforce resource ownership or role checks against `session.user_id` before mutating state.
tracing::debug!(user_id = %session.user_id, "handling {feature}.{name}");
let mut tx = ctx.db.begin().await?;
// Write self-contained parameterized SQL here using `sqlx::query` / `sqlx::query_as`.
tx.commit().await?;
Ok((StatusCode::OK, Json(Output {{ ok: true }})))
}}
#[cfg(test)]
mod tests {{
use axum::{{
body::Body,
http::{{header, Method, Request, StatusCode}},
}};
#[tokio::test]
async fn requires_authentication() {{
let app = crate::test_app().await;
let req = Request::builder()
.method(Method::{axum_method})
.uri("{route_path}")
.header(header::CONTENT_TYPE, "application/json")
.body(Body::from("{{}}"))
.unwrap();
let res = app.request(req).await;
assert_eq!(res.status, StatusCode::UNAUTHORIZED);
}}
}}
"#
)
}
}
fn render_job_template(name: &str) -> String {
format!(
r#"use serde::Deserialize;
use serde_json::Value;
use slabs::prelude::*;
pub fn job() -> JobDef {{
JobDef::new("{name}", run).summary("TODO: describe {name}")
}}
#[derive(Debug, Deserialize)]
struct Payload {{
// Define job payload fields here.
}}
async fn run(ctx: AppCtx, raw: Value) -> SlabResult<()> {{
let payload: Payload = serde_json::from_value(raw)
.map_err(|e| SlabError::bad_request(format!("invalid job payload: {{e}}")))?;
tracing::debug!(?payload, "running job {name}");
let mut tx = ctx.db.begin().await?;
// Execute idempotent SQL updates inside this transaction.
tx.commit().await?;
Ok(())
}}
"#
)
}
fn scaffold_app(name: &str, dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
validate_app_name(name)?;
if dir.exists() && fs::read_dir(dir)?.next().is_some() {
return Err(format!("target directory is not empty: {}", dir.display()).into());
}
fs::create_dir_all(dir.join("src"))?;
fs::create_dir_all(dir.join("slabs/pages"))?;
fs::create_dir_all(dir.join("slabs/pwa"))?;
fs::create_dir_all(dir.join("jobs"))?;
fs::create_dir_all(dir.join("migrations"))?;
fs::create_dir_all(dir.join("assets/styles"))?;
fs::create_dir_all(dir.join(".github/workflows"))?;
fs::create_dir_all(dir.join(".claude/skills/add-slab"))?;
fs::create_dir_all(dir.join(".claude/skills/add-migration"))?;
fs::create_dir_all(dir.join(".claude/skills/review-slab"))?;
fs::create_dir_all(dir.join(".claude/skills/deploy-app"))?;
fs::create_dir_all(dir.join(".claude/skills/fix-incident"))?;
let cargo_toml = format!(
r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = {{ version = "0.8", features = ["ws", "multipart"] }}
axum-extra = {{ version = "0.10", features = ["cookie"] }}
maud = {{ version = "0.27", features = ["axum"] }}
serde = {{ version = "1", features = ["derive"] }}
serde_json = "1"
slabs-framework = "0.3"
sqlx = {{ version = "0.8", default-features = false, features = ["runtime-tokio", "tls-rustls", "sqlite", "migrate", "chrono", "json", "macros"] }}
tokio = {{ version = "1", features = ["full"] }}
tracing = "0.1"
[build-dependencies]
slabs-build = "0.3"
[lints.rust]
unsafe_code = "forbid"
[lints.clippy]
dbg_macro = "warn"
todo = "warn"
unimplemented = "warn"
await_holding_lock = "deny"
await_holding_refcell_ref = "deny"
"#
);
let build_rs = "fn main() {\n slabs_build::discover();\n}\n";
let lib_rs = format!(
r#"use slabs::SlabsApp;
use sqlx::migrate::Migrator;
slabs::discover_slabs!();
pub static MIGRATOR: Migrator = sqlx::migrate!("./migrations");
pub async fn boot(config: slabs::AppConfig) -> slabs::SlabResult<SlabsApp> {{
SlabsApp::boot(config, &MIGRATOR, collect_slabs(), collect_jobs()).await
}}
#[cfg(test)]
pub async fn test_app() -> slabs::test::TestApp {{
slabs::test::TestApp::boot("{name}", &MIGRATOR, collect_slabs(), collect_jobs()).await
}}
"#
);
let pkg_ident = name.replace('-', "_");
let main_rs = format!(
r#"#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {{
slabs::init_tracing();
let config = slabs::AppConfig::from_env("{name}");
let app = {pkg_ident}::boot(config).await?;
app.serve().await?;
Ok(())
}}
"#
);
let show_home_rs = format!(
r#"use axum::extract::State;
use slabs::prelude::*;
pub fn slab() -> SlabDef {{
SlabDef::get("/", handle)
.name("pages.show_home")
.summary("Render the {name} home page")
}}
async fn handle(State(ctx): State<AppCtx>) -> Markup {{
html::document(
"{name}",
&ctx.assets.stylesheet_urls(),
&ctx.assets.behavior_urls(),
maud! {{
main class="mx-auto max-w-2xl px-6 py-16 space-y-4" {{
h1 class="text-3xl font-bold tracking-tight" {{ "{name}" }}
p class="text-muted-foreground" {{
"Built with Slabs Transaction Scripts, raw SQL, Tailwind v4, Basecoat, HTMX, and Alpine."
}}
}}
}},
)
}}
#[cfg(test)]
mod tests {{
use axum::http::StatusCode;
#[tokio::test]
async fn home_page_renders() {{
let app = crate::test_app().await;
let res = app.get("/").await;
assert_eq!(res.status, StatusCode::OK);
assert!(res.text().contains("{name}"));
}}
}}
"#
);
let pwa_manifest_rs = format!(
r##"use axum::{{
extract::State,
http::{{header, HeaderValue, StatusCode}},
response::IntoResponse,
}};
use serde_json::json;
use slabs::prelude::*;
pub fn slab() -> SlabDef {{
SlabDef::get("/manifest.webmanifest", handle)
.name("pwa.manifest")
.summary("Serve the Progressive Web App manifest")
}}
async fn handle(State(ctx): State<AppCtx>) -> impl IntoResponse {{
let icon_url = ctx.assets.url("icon.svg");
let body = json!({{
"name": "{name}",
"short_name": "{name}",
"start_url": "/",
"display": "standalone",
"background_color": "#1a1b26",
"theme_color": "#D34516",
"icons": [
{{
"src": icon_url,
"sizes": "any",
"type": "image/svg+xml",
"purpose": "any maskable"
}}
]
}})
.to_string();
(
StatusCode::OK,
[(
header::CONTENT_TYPE,
HeaderValue::from_static("application/manifest+json; charset=utf-8"),
)],
body,
)
}}
#[cfg(test)]
mod tests {{
use axum::http::StatusCode;
#[tokio::test]
async fn serves_pwa_manifest() {{
let app = crate::test_app().await;
let res = app.get("/manifest.webmanifest").await;
assert_eq!(res.status, StatusCode::OK);
assert!(res.text().contains("\"display\":\"standalone\""));
}}
}}
"##
);
let pwa_service_worker_rs = format!(
r##"use axum::{{
http::{{header, HeaderName, HeaderValue, StatusCode}},
response::IntoResponse,
}};
use slabs::prelude::*;
pub fn slab() -> SlabDef {{
SlabDef::get("/service-worker.js", handle)
.name("pwa.service_worker")
.summary("Serve the Progressive Web App service worker")
}}
const SW_JS: &str = r#"const CACHE_NAME = "{name}-v1";
self.addEventListener("install", () => {{
self.skipWaiting();
}});
self.addEventListener("activate", (event) => {{
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))
)
);
self.clients.claim();
}});
self.addEventListener("fetch", (event) => {{
const req = event.request;
if (req.method !== "GET") return;
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
if (url.pathname.startsWith("/assets/")) {{
event.respondWith(
caches.open(CACHE_NAME).then((cache) =>
cache.match(req).then((cached) =>
cached ||
fetch(req).then((res) => {{
if (res.ok) cache.put(req, res.clone());
return res;
}})
)
)
);
return;
}}
if (url.pathname.startsWith("/_slabs/vendor/")) {{
event.respondWith(
caches.open(CACHE_NAME).then((cache) =>
cache.match(req).then((cached) => {{
const network = fetch(req).then((res) => {{
if (res.ok) cache.put(req, res.clone());
return res;
}});
return cached || network;
}})
)
);
return;
}}
if (req.mode === "navigate") {{
event.respondWith(
fetch(req).catch(() =>
new Response("<h1>Offline</h1><p>Reconnect to continue using {name}.</p>", {{
status: 503,
headers: {{ "Content-Type": "text/html; charset=utf-8" }},
}})
)
);
}}
}});
self.addEventListener("push", (event) => {{
let data = {{ title: "{name}", body: "New update", url: "/" }};
if (event.data) {{
try {{
const parsed = event.data.json();
if (parsed && typeof parsed === "object") {{
data = parsed;
}}
}} catch (_err) {{
data = {{ title: "{name}", body: event.data.text() || "New update", url: "/" }};
}}
}}
event.waitUntil(
self.registration.showNotification(data.title || "{name}", {{
body: data.body || "",
data: {{ url: data.url || "/" }},
}})
);
}});
self.addEventListener("notificationclick", (event) => {{
event.notification.close();
const rawTarget = (event.notification.data && event.notification.data.url) || "/";
let safeTarget = "/";
try {{
const resolved = new URL(rawTarget, self.location.origin);
if (resolved.origin === self.location.origin) {{
safeTarget = resolved.pathname + resolved.search + resolved.hash;
}}
}} catch (_err) {{
safeTarget = "/";
}}
event.waitUntil(clients.openWindow(safeTarget));
}});
"#;
async fn handle() -> impl IntoResponse {{
(
StatusCode::OK,
[
(
header::CONTENT_TYPE,
HeaderValue::from_static("application/javascript; charset=utf-8"),
),
(header::CACHE_CONTROL, HeaderValue::from_static("no-cache")),
(
HeaderName::from_static("service-worker-allowed"),
HeaderValue::from_static("/"),
),
],
SW_JS,
)
}}
#[cfg(test)]
mod tests {{
use axum::http::StatusCode;
#[tokio::test]
async fn serves_service_worker() {{
let app = crate::test_app().await;
let res = app.get("/service-worker.js").await;
assert_eq!(res.status, StatusCode::OK);
assert!(res.text().contains("url.origin !== self.location.origin"));
}}
}}
"##
);
let icon_svg = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 112 112" fill="none">
<defs>
<mask id="slabs-mark-cuts">
<rect x="0" y="0" width="112" height="112" fill="white"/>
<rect x="40" y="0" width="6" height="112" fill="black"/>
<rect x="66" y="0" width="6" height="112" fill="black"/>
</mask>
<path id="slabs-mark-s" d="M26,10 L86,10 C94,10 98,14 98,22 L98,42 L76,42 L76,27 L37,27 L37,46 L84,56 C93,58 98,64 98,73 L98,90 C98,98 94,102 86,102 L26,102 C18,102 14,98 14,90 L14,69 L36,69 L36,85 L76,85 L76,68 L29,58 C20,56 14,50 14,41 L14,22 C14,14 18,10 26,10 Z"/>
</defs>
<g mask="url(#slabs-mark-cuts)">
<use href="#slabs-mark-s" x="-5" y="4" fill="#8C2A0B"/>
<use href="#slabs-mark-s" x="-2.5" y="2" fill="#A6330E"/>
<use href="#slabs-mark-s" x="0" y="0" fill="#D34516"/>
</g>
</svg>
"##;
let dockerfile = format!(
r#"FROM lukemathwalker/cargo-chef:latest-rust-1.88-slim AS chef
WORKDIR /app
FROM chef AS planner
COPY . .
RUN cargo chef prepare --recipe-path recipe.json
FROM chef AS builder
ARG TARGETARCH
ARG LITESTREAM_VERSION=v0.3.13
RUN apt-get update && apt-get install -y --no-install-recommends \
pkg-config libssl-dev curl ca-certificates tar gzip \
&& rm -rf /var/lib/apt/lists/* \
&& ARCH="${{TARGETARCH:-amd64}}" \
&& curl -fsSL "https://github.com/benbjohnson/litestream/releases/download/${{LITESTREAM_VERSION}}/litestream-${{LITESTREAM_VERSION}}-linux-${{ARCH}}.tar.gz" \
| tar -xz -C /usr/local/bin litestream \
&& chmod +x /usr/local/bin/litestream
COPY --from=planner /app/recipe.json recipe.json
RUN cargo chef cook --release --recipe-path recipe.json
COPY . .
RUN cargo build --release --locked
FROM debian:bookworm-slim AS runtime
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl \
&& rm -rf /var/lib/apt/lists/* \
&& useradd -r -u 10001 -m slabs
COPY --from=builder /app/target/release/{name} /usr/local/bin/{name}
COPY --from=builder /usr/local/bin/litestream /usr/local/bin/litestream
COPY --from=builder /app/litestream.yml /etc/litestream.yml
COPY --from=builder /app/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
COPY --from=builder --chown=root:root /app/assets /app/assets
RUN chmod +x /usr/local/bin/docker-entrypoint.sh \
&& chmod -R a-w /app/assets \
&& mkdir -p /data \
&& chown -R slabs:slabs /data
USER slabs
ENV SLABS_ENV=production
ENV SLABS_COOKIE_SECURE=true
ENV SLABS_BIND=0.0.0.0:3000
ENV DATABASE_URL=sqlite:///data/{name}.db?mode=rwc
ENV SLABS_STORAGE_DIR=/data/storage
ENV SLABS_ASSETS_DIR=/app/assets
ENV SLABS_LOG_FORMAT=json
EXPOSE 3000
HEALTHCHECK --interval=15s --timeout=3s --start-period=5s --retries=3 \
CMD curl -fsS http://127.0.0.1:3000/health/ready || exit 1
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
"#
);
let entrypoint_sh = format!(
r#"#!/bin/sh
set -eu
if [ -n "${{LITESTREAM_BUCKET:-}}" ]; then
litestream restore -if-db-not-exists -if-replica-exists -config /etc/litestream.yml "/data/{name}.db"
exec litestream replicate -config /etc/litestream.yml -exec "/usr/local/bin/{name}"
fi
exec /usr/local/bin/{name}
"#
);
let dockerignore = ".git\ntarget\n.env\n.env.*\n*.db\n*.db-wal\n*.db-shm\nstorage/\n";
let litestream_yml = format!(
r"dbs:
- path: /data/{name}.db
replicas:
- type: s3
bucket: ${{LITESTREAM_BUCKET}}
path: {name}/db
endpoint: ${{LITESTREAM_ENDPOINT}}
region: ${{LITESTREAM_REGION:-auto}}
"
);
let seeds_sql = "-- Idempotent development seed data applied via `slabs db seed`.\nSELECT 1;\n";
let init_sql = "-- Add your domain tables here. Slabs manages sessions, jobs, mail, cache, blobs, webhooks, idempotency keys, and audit logs automatically.\n";
let input_css = "@import \"tailwindcss\";\n@source \"../slabs\";\n";
let ci_yml = r"name: CI
permissions:
contents: read
on:
push:
branches: [main]
pull_request:
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
- uses: taiki-e/install-action@nextest
- name: Check formatting (crate + slabs/ + jobs/)
run: |
cargo fmt --all -- --check
find slabs jobs -name '*.rs' -print0 2>/dev/null | xargs -0 -r rustfmt --edition 2021 --check
- name: Clippy
run: cargo clippy --all-targets -- -D warnings
- name: Tests
run: cargo nextest run
";
let agents_md = format!(
r"# AGENTS.md: {name} (Slabs App)
- One use case is one self-contained slab in `slabs/<feature>/<action>.rs` (auto-discovered at compile time).
- Background jobs live in `jobs/<name>.rs`.
- Read `schema.sql` before writing raw parameterized SQL inside explicit transactions (`ctx.db.begin().await?`).
- Bundled agent skills live in `.claude/skills/` (`add-slab`, `add-migration`, `review-slab`, `deploy-app`, `fix-incident`).
- Run `slabs doctor`, `slabs fmt --check`, and `slabs check --no-docs` before finishing changes.
"
);
fs::write(dir.join("Cargo.toml"), cargo_toml)?;
fs::write(dir.join("build.rs"), build_rs)?;
fs::write(dir.join("src/lib.rs"), lib_rs)?;
fs::write(dir.join("src/main.rs"), main_rs)?;
fs::write(dir.join("slabs/pages/show_home.rs"), show_home_rs)?;
fs::write(dir.join("slabs/pwa/manifest.rs"), pwa_manifest_rs)?;
fs::write(
dir.join("slabs/pwa/service_worker.rs"),
pwa_service_worker_rs,
)?;
fs::write(dir.join("migrations/0001_init.sql"), init_sql)?;
fs::write(dir.join("schema.sql"), init_sql)?;
fs::write(dir.join("seeds.sql"), seeds_sql)?;
fs::write(dir.join("assets/input.css"), input_css)?;
fs::write(dir.join("assets/icon.svg"), icon_svg)?;
fs::write(dir.join("Dockerfile"), dockerfile)?;
let entrypoint_path = dir.join("docker-entrypoint.sh");
fs::write(&entrypoint_path, entrypoint_sh)?;
set_executable_if_unix(&entrypoint_path)?;
fs::write(dir.join(".dockerignore"), dockerignore)?;
fs::write(dir.join("litestream.yml"), litestream_yml)?;
fs::write(dir.join(".github/workflows/ci.yml"), ci_yml)?;
fs::write(dir.join("AGENTS.md"), agents_md)?;
fs::write(dir.join("CLAUDE.md"), "@AGENTS.md\n")?;
fs::write(dir.join(".claude/skills/add-slab/SKILL.md"), SKILL_ADD_SLAB)?;
fs::write(
dir.join(".claude/skills/add-migration/SKILL.md"),
SKILL_ADD_MIGRATION,
)?;
fs::write(
dir.join(".claude/skills/review-slab/SKILL.md"),
SKILL_REVIEW_SLAB,
)?;
fs::write(
dir.join(".claude/skills/deploy-app/SKILL.md"),
SKILL_DEPLOY_APP,
)?;
fs::write(
dir.join(".claude/skills/fix-incident/SKILL.md"),
SKILL_FIX_INCIDENT,
)?;
Ok(())
}
#[cfg(unix)]
fn set_executable_if_unix(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
use std::os::unix::fs::PermissionsExt;
let mut perms = fs::metadata(path)?.permissions();
perms.set_mode(0o755);
fs::set_permissions(path, perms)?;
Ok(())
}
#[cfg(not(unix))]
fn set_executable_if_unix(_path: &Path) -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
fn scaffold_deploy(
app_dir: &Path,
app_name: &str,
target: DeployTarget,
force: bool,
) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
validate_app_name(app_name)?;
let mut created = Vec::new();
match target {
DeployTarget::Kamal => {
let path = app_dir.join("config/deploy.yml");
write_deploy_file(&path, &render_kamal_config(app_name), force)?;
created.push(path);
}
DeployTarget::Fly => {
let path = app_dir.join("fly.toml");
write_deploy_file(&path, &render_fly_config(app_name), force)?;
created.push(path);
}
DeployTarget::Vps => {
let caddy_path = app_dir.join("deploy/Caddyfile");
let service_path = app_dir.join(format!("deploy/{app_name}.service"));
write_deploy_file(&caddy_path, &render_vps_caddyfile(app_name), force)?;
write_deploy_file(&service_path, &render_vps_systemd_unit(app_name), force)?;
created.push(caddy_path);
created.push(service_path);
}
}
Ok(created)
}
fn write_deploy_file(
path: &Path,
content: &str,
force: bool,
) -> Result<(), Box<dyn std::error::Error>> {
if path.exists() && !force {
return Err(format!(
"deployment file already exists (pass `--force` to overwrite): {}",
path.display()
)
.into());
}
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(path, content)?;
Ok(())
}
fn render_kamal_config(app: &str) -> String {
format!(
r#"# Kamal 2 deployment configuration for `{app}`.
#
# Rollbacks:
# Kamal tags images with the git SHA by default. Roll back in seconds with:
# kamal rollback <version>
#
# SQLite vs PostgreSQL rollouts:
# - Single-volume SQLite + Litestream must run one writer at a time. Keep
# `boot.limit: 1` so kamal-proxy buffers incoming requests while the old
# container drains on SIGTERM (drain_timeout: 20) and the replacement
# container passes `/health/ready`.
# - PostgreSQL deployments can raise `boot.limit` and add multiple hosts in
# `servers.web` for multi-replica rolling deploys.
service: {app}
image: your-registry/{app}
servers:
web:
- 192.0.2.10
proxy:
ssl: true
host: {app}.example.com
app_port: 3000
healthcheck:
path: /health/ready
interval: 2
timeout: 3
drain_timeout: 20
boot:
limit: 1
wait: 5
volumes:
- /var/lib/{app}/data:/data
env:
clear:
SLABS_ENV: production
SLABS_COOKIE_SECURE: "true"
SLABS_TRUST_PROXY: "true"
SLABS_BIND: 0.0.0.0:3000
DATABASE_URL: sqlite:///data/{app}.db?mode=rwc
SLABS_STORAGE_DIR: /data/storage
SLABS_LOG_FORMAT: json
secret:
- SLABS_SECRET_KEY
- LITESTREAM_BUCKET
- LITESTREAM_ENDPOINT
- AWS_ACCESS_KEY_ID
- AWS_SECRET_ACCESS_KEY
"#
)
}
fn render_fly_config(app: &str) -> String {
let volume_source = format!("{}_data", app.replace('-', "_"));
format!(
r#"# Fly.io deployment configuration for `{app}`.
#
# Set required secrets before deploying:
# fly secrets set SLABS_SECRET_KEY="$(openssl rand -hex 32)"
#
# Roll back to a previous release with:
# fly releases rollback <version>
app = "{app}"
primary_region = "iad"
kill_signal = "SIGTERM"
kill_timeout = "20s"
[deploy]
# Single-volume SQLite allows only one active writer at a time, so keep
# `strategy = "immediate"`. Switch to `strategy = "rolling"` when using PostgreSQL.
strategy = "immediate"
[env]
SLABS_ENV = "production"
SLABS_COOKIE_SECURE = "true"
SLABS_TRUST_PROXY = "true"
SLABS_BIND = "0.0.0.0:3000"
DATABASE_URL = "sqlite:///data/{app}.db?mode=rwc"
SLABS_STORAGE_DIR = "/data/storage"
SLABS_LOG_FORMAT = "json"
[[mounts]]
source = "{volume_source}"
destination = "/data"
[http_service]
internal_port = 3000
force_https = true
auto_stop_machines = "off"
auto_start_machines = true
min_machines_running = 1
[[http_service.checks]]
grace_period = "10s"
interval = "15s"
method = "GET"
timeout = "3s"
path = "/health/ready"
"#
)
}
fn render_vps_caddyfile(app: &str) -> String {
format!(
r"# Caddy auto-HTTPS reverse proxy configuration for `{app}`.
# Copy to `/etc/caddy/Caddyfile` and reload with `systemctl reload caddy`.
{app}.example.com {{
encode zstd gzip
reverse_proxy 127.0.0.1:3000 {{
health_uri /health/ready
health_interval 5s
health_timeout 3s
header_up X-Forwarded-Proto {{scheme}}
}}
}}
"
)
}
fn render_vps_systemd_unit(app: &str) -> String {
format!(
r"# Hardened systemd unit for `{app}`.
# Copy to `/etc/systemd/system/{app}.service`, then run:
# systemctl daemon-reload && systemctl enable --now {app}
#
# Atomic deploy / fast rollback:
# ln -sfn /opt/{app}/releases/<git-sha> /opt/{app}/current
# systemctl restart {app}
[Unit]
Description={app} (Slabs web application)
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=slabs
Group=slabs
WorkingDirectory=/opt/{app}/current
EnvironmentFile=/etc/{app}/env
ExecStart=/opt/{app}/current/{app}
KillSignal=SIGTERM
TimeoutStopSec=20s
Restart=on-failure
RestartSec=2s
# Hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/data
[Install]
WantedBy=multi-user.target
"
)
}
async fn run_fmt(app_dir: &Path, check: bool) -> Result<(), Box<dyn std::error::Error>> {
let manifest_path = app_dir.join("Cargo.toml");
let mut cargo_cmd = Command::new("cargo");
cargo_cmd.arg("fmt");
if manifest_path.exists() {
cargo_cmd.arg("--manifest-path").arg(&manifest_path);
}
if check {
cargo_cmd.args(["--", "--check"]);
}
let cargo_status = cargo_cmd.status().await?;
if !cargo_status.success() {
return Err(format!("cargo fmt failed with status {cargo_status}").into());
}
let discovered_files = collect_workspace_discovered_rs_files(app_dir)?;
if !discovered_files.is_empty() {
let mut rustfmt_cmd = Command::new("rustfmt");
rustfmt_cmd.args(["--edition", "2021"]);
if check {
rustfmt_cmd.arg("--check");
}
rustfmt_cmd.args(&discovered_files);
let rustfmt_status = rustfmt_cmd.status().await?;
if !rustfmt_status.success() {
return Err(
format!("rustfmt failed on slabs/jobs files with status {rustfmt_status}").into(),
);
}
}
if check {
println!(
"Formatting OK ({} discovered slab/job files checked)",
discovered_files.len()
);
} else {
println!(
"Formatted crate + {} discovered slab/job files",
discovered_files.len()
);
}
Ok(())
}
async fn run_check(
app_dir: &Path,
workspace_flag: bool,
no_docs: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let manifest_path = app_dir.join("Cargo.toml");
let is_workspace = workspace_flag || manifest_is_workspace(&manifest_path);
let total_steps = if no_docs { 4 } else { 6 };
let mut step = 1usize;
println!("[{step}/{total_steps}] Checking formatting...");
if is_workspace {
let mut fmt_cmd = Command::new("cargo");
fmt_cmd.args(["fmt", "--all"]);
if manifest_path.exists() {
fmt_cmd.arg("--manifest-path").arg(&manifest_path);
}
fmt_cmd.args(["--", "--check"]);
run_checked_command(&mut fmt_cmd, "cargo fmt --all -- --check").await?;
let discovered_files = collect_workspace_discovered_rs_files(app_dir)?;
if !discovered_files.is_empty() {
let mut rustfmt_cmd = Command::new("rustfmt");
rustfmt_cmd
.args(["--edition", "2021", "--check"])
.args(&discovered_files);
run_checked_command(&mut rustfmt_cmd, "rustfmt on discovered slabs/jobs").await?;
}
} else {
run_fmt(app_dir, true).await?;
}
step += 1;
println!("[{step}/{total_steps}] [security] Running static security analyzer...");
let report = scan_security(app_dir, is_workspace)?;
print_security_report(&report);
if report.error_count() > 0 {
return Err(format!(
"[security] static analyzer failed with {} error(s) and {} warning(s)",
report.error_count(),
report.warning_count()
)
.into());
}
step += 1;
println!("[{step}/{total_steps}] Running clippy...");
let mut clippy_cmd = Command::new("cargo");
clippy_cmd.arg("clippy");
if manifest_path.exists() {
clippy_cmd.arg("--manifest-path").arg(&manifest_path);
}
if is_workspace {
clippy_cmd.arg("--workspace");
}
clippy_cmd.args(["--all-targets", "--", "-D", "warnings"]);
run_checked_command(&mut clippy_cmd, "cargo clippy").await?;
step += 1;
if !no_docs {
println!("[{step}/{total_steps}] Building rustdoc...");
let mut doc_cmd = Command::new("cargo");
doc_cmd.arg("doc").env("RUSTDOCFLAGS", "-D warnings");
if manifest_path.exists() {
doc_cmd.arg("--manifest-path").arg(&manifest_path);
}
if is_workspace {
doc_cmd.arg("--workspace");
}
doc_cmd.arg("--no-deps");
run_checked_command(&mut doc_cmd, "cargo doc").await?;
step += 1;
println!("[{step}/{total_steps}] Running doctests...");
let mut doctest_cmd = Command::new("cargo");
doctest_cmd.args(["test", "--doc"]);
if manifest_path.exists() {
doctest_cmd.arg("--manifest-path").arg(&manifest_path);
}
if is_workspace {
doctest_cmd.arg("--workspace");
}
run_checked_command(&mut doctest_cmd, "cargo test --doc").await?;
step += 1;
}
let has_nextest = Command::new("cargo")
.args(["nextest", "--version"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.await
.is_ok_and(|s| s.success());
if has_nextest {
println!("[{step}/{total_steps}] Running tests with cargo-nextest...");
let mut test_cmd = Command::new("cargo");
test_cmd.args(["nextest", "run"]);
if manifest_path.exists() {
test_cmd.arg("--manifest-path").arg(&manifest_path);
}
if is_workspace {
test_cmd.arg("--workspace");
}
run_checked_command(&mut test_cmd, "cargo nextest run").await?;
} else {
println!("[{step}/{total_steps}] Running tests with cargo test...");
let mut test_cmd = Command::new("cargo");
test_cmd.arg("test");
if manifest_path.exists() {
test_cmd.arg("--manifest-path").arg(&manifest_path);
}
if is_workspace {
test_cmd.arg("--workspace");
}
run_checked_command(&mut test_cmd, "cargo test").await?;
}
println!("All {total_steps} checks passed.");
Ok(())
}
async fn run_doctor(app_dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
let mut passed = 0usize;
let mut warned = 0usize;
let mut failed = 0usize;
let mut record = |status: &str, label: &str, detail: &str| {
println!("[{status}] {label}: {detail}");
match status {
"PASS" => passed += 1,
"WARN" => warned += 1,
_ => failed += 1,
}
};
match command_first_line("rustc", &["--version"]).await {
Some(ver) => record("PASS", "rustc", &ver),
None => record("FAIL", "rustc", "not found in PATH"),
}
match command_first_line("cargo", &["nextest", "--version"]).await {
Some(ver) => record("PASS", "cargo-nextest", &ver),
None => record(
"WARN",
"cargo-nextest",
"not installed (optional; install via `cargo install cargo-nextest`)",
),
}
let sqlx_ver = match command_first_line("sqlx", &["--version"]).await {
Some(ver) => Some(ver),
None => command_first_line("cargo", &["sqlx", "--version"]).await,
};
match sqlx_ver {
Some(ver) => record("PASS", "sqlx-cli", &ver),
None => record(
"WARN",
"sqlx-cli",
"not installed (optional; needed only for `slabs db prepare`)",
),
}
let manifest_path = app_dir.join("Cargo.toml");
let is_workspace = manifest_is_workspace(&manifest_path);
if manifest_path.exists() {
let workspace_forbids = cargo_toml_forbids_unsafe(&manifest_path);
if workspace_forbids {
record(
"PASS",
"Cargo.toml unsafe_code",
"unsafe_code = \"forbid\" configured",
);
} else {
record(
"FAIL",
"Cargo.toml unsafe_code",
"missing `unsafe_code = \"forbid\"` in Cargo.toml",
);
}
} else {
record(
"FAIL",
"Cargo.toml",
&format!("not found at {}", manifest_path.display()),
);
}
let schema_path = app_dir.join("schema.sql");
if schema_path.is_file() {
let content = fs::read_to_string(&schema_path).unwrap_or_default();
if content.trim().is_empty() {
record("FAIL", "schema.sql", "file exists but is empty");
} else {
record(
"PASS",
"schema.sql",
&format!("present ({} bytes)", content.len()),
);
}
} else if is_workspace && !app_dir.join("slabs").is_dir() {
record(
"WARN",
"schema.sql",
"not present at workspace root (expected inside individual app directories)",
);
} else {
record(
"FAIL",
"schema.sql",
"missing; run `slabs db dump-schema --database-url ...`",
);
}
let dockerignore_path = app_dir.join(".dockerignore");
if dockerignore_path.is_file() {
record("PASS", ".dockerignore", "present");
} else {
record(
"WARN",
".dockerignore",
"missing; add `.dockerignore` excluding `.git`, `target`, `.env`, and `*.db`",
);
}
let dockerfile_path = app_dir.join("Dockerfile");
if dockerfile_path.is_file() {
let content = fs::read_to_string(&dockerfile_path).unwrap_or_default();
let missing = missing_dockerfile_hardening_tokens(&content);
if missing.is_empty() {
record(
"PASS",
"dockerfile-hardening",
"Dockerfile sets SLABS_ENV=production, SLABS_COOKIE_SECURE=true, --locked, non-root USER, and /health/ready",
);
} else {
record(
"WARN",
"dockerfile-hardening",
&format!(
"Dockerfile is missing required hardening settings: {}",
missing.join(", ")
),
);
}
}
let slabs_env = std::env::var("SLABS_ENV").unwrap_or_else(|_| "development".to_string());
let env_lower = slabs_env.to_ascii_lowercase();
if env_lower == "staging" || env_lower == "production" {
let dev_sentinel = concat!("dev-only-change-me-", "in-production");
match std::env::var("SLABS_SECRET_KEY") {
Ok(key) if key.len() >= 32 && !key.contains(dev_sentinel) => record(
"PASS",
"SLABS_ENV / SLABS_SECRET_KEY",
&format!("SLABS_ENV={slabs_env} with valid secret key (>= 32 bytes)"),
),
Ok(key) => record(
"FAIL",
"SLABS_ENV / SLABS_SECRET_KEY",
&format!(
"SLABS_ENV={slabs_env} requires a non-default SLABS_SECRET_KEY of at least 32 bytes (got {} bytes)",
key.len()
),
),
Err(_) => record(
"FAIL",
"SLABS_ENV / SLABS_SECRET_KEY",
&format!("SLABS_ENV={slabs_env} requires SLABS_SECRET_KEY (>= 32 random bytes)"),
),
}
} else {
record(
"PASS",
"SLABS_ENV / SLABS_SECRET_KEY",
&format!(
"SLABS_ENV={slabs_env} (set SLABS_SECRET_KEY >= 32 bytes in staging/production)"
),
);
}
let report = scan_security(app_dir, is_workspace)?;
let errors = report.error_count();
let warnings = report.warning_count();
if errors > 0 {
record(
"FAIL",
"[security] static scan",
&format!(
"{errors} error(s), {warnings} warning(s) across {} file(s)",
report.files_scanned
),
);
print_security_report(&report);
} else if warnings > 0 {
record(
"WARN",
"[security] static scan",
&format!(
"0 errors, {warnings} warning(s) across {} file(s)",
report.files_scanned
),
);
print_security_report(&report);
} else {
record(
"PASS",
"[security] static scan",
&format!(
"0 errors, 0 warnings across {} file(s)",
report.files_scanned
),
);
}
println!("Doctor summary: {passed} passed, {warned} warnings, {failed} failed.");
if failed > 0 {
return Err(format!("slabs doctor found {failed} failing check(s)").into());
}
Ok(())
}
async fn command_first_line(program: &str, args: &[&str]) -> Option<String> {
let output = Command::new(program).args(args).output().await.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8_lossy(&output.stdout);
stdout
.lines()
.next()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Severity {
Error,
Warning,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct SecurityFinding {
severity: Severity,
rule: &'static str,
file: PathBuf,
line: usize,
message: String,
}
#[derive(Debug, Default)]
struct SecurityReport {
findings: Vec<SecurityFinding>,
files_scanned: usize,
}
impl SecurityReport {
fn error_count(&self) -> usize {
self.findings
.iter()
.filter(|f| f.severity == Severity::Error)
.count()
}
fn warning_count(&self) -> usize {
self.findings
.iter()
.filter(|f| f.severity == Severity::Warning)
.count()
}
}
fn print_security_report(report: &SecurityReport) {
for finding in &report.findings {
let tag = match finding.severity {
Severity::Error => "ERROR",
Severity::Warning => "WARN ",
};
println!(
" [{tag}] ({}) {}:{}: {}",
finding.rule,
finding.file.display(),
finding.line,
finding.message
);
}
println!(
"[security] Scanned {} file(s): {} error(s), {} warning(s).",
report.files_scanned,
report.error_count(),
report.warning_count()
);
}
fn scan_security(
root: &Path,
is_workspace: bool,
) -> Result<SecurityReport, Box<dyn std::error::Error>> {
let mut report = SecurityReport::default();
let root_manifest = root.join("Cargo.toml");
let workspace_forbids_unsafe =
root_manifest.is_file() && cargo_toml_forbids_unsafe(&root_manifest);
let crate_dirs = if is_workspace {
discover_workspace_member_dirs(root)
} else {
vec![root.to_path_buf()]
};
if is_workspace && root_manifest.is_file() {
scan_cargo_toml(&root_manifest, true, &mut report)?;
}
for crate_dir in crate_dirs {
let manifest = crate_dir.join("Cargo.toml");
let pkg_name = infer_package_name_raw(&manifest);
if manifest.is_file() {
scan_cargo_toml(&manifest, workspace_forbids_unsafe, &mut report)?;
}
let mut scan_targets: Vec<(PathBuf, FileArea)> = Vec::new();
for (subdir, area) in [
("slabs", FileArea::Slabs),
("jobs", FileArea::Jobs),
("src", FileArea::Src),
] {
let dir = crate_dir.join(subdir);
if dir.is_dir() {
let mut rs_files = Vec::new();
collect_rs_recursive(&dir, &mut rs_files)?;
rs_files.sort();
for path in rs_files {
scan_targets.push((path, area));
}
}
}
for (file, area) in scan_targets {
scan_rust_file(&file, area, pkg_name.as_deref(), &mut report)?;
}
}
Ok(report)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FileArea {
Slabs,
Jobs,
Src,
}
fn scan_cargo_toml(
path: &Path,
workspace_forbids_unsafe: bool,
report: &mut SecurityReport,
) -> Result<(), Box<dyn std::error::Error>> {
let content = fs::read_to_string(path)?;
report.files_scanned += 1;
let inherits_workspace_lints = cargo_toml_inherits_workspace_lints(&content);
let has_forbid = cargo_toml_content_forbids_unsafe(&content)
|| (inherits_workspace_lints && workspace_forbids_unsafe);
if !has_forbid {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "unsafe-code",
file: path.to_path_buf(),
line: 1,
message: "Cargo.toml must set `unsafe_code = \"forbid\"` (or inherit workspace lints that forbid unsafe code)".to_string(),
});
}
for (idx, line) in content.lines().enumerate() {
let trimmed = line.trim();
if trimmed.starts_with('#') {
continue;
}
if let Some(secret_kind) = detect_hardcoded_secret(line, false) {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "hardcoded-secret",
file: path.to_path_buf(),
line: idx + 1,
message: format!("possible hardcoded secret ({secret_kind}) in Cargo.toml"),
});
}
}
Ok(())
}
fn scan_rust_file(
path: &Path,
area: FileArea,
pkg_name: Option<&str>,
report: &mut SecurityReport,
) -> Result<(), Box<dyn std::error::Error>> {
let content = fs::read_to_string(path)?;
report.files_scanned += 1;
let lines: Vec<&str> = content.lines().collect();
let code_lines = strip_rust_file_code_lines(&content);
let is_slabs_html_crate = pkg_name == Some("slabs-html");
let is_slabs_core_crate = pkg_name == Some("slabs-core");
let is_service_worker_file =
path.file_name().and_then(|s| s.to_str()) == Some("service_worker.rs");
let is_auth_or_web = area == FileArea::Slabs && is_auth_or_web_slab(path);
let mut in_cfg_test = false;
let mut pending_cfg_test = false;
let mut test_brace_depth: i32 = 0;
let mut has_cfg_test = false;
let mut ws_upgrade_line: Option<usize> = None;
let mut has_validate_ws_origin = false;
let mut has_storage_get = false;
let mut content_disposition_line: Option<usize> = None;
let mut has_into_safe_response = false;
let mut sw_fetch_line: Option<usize> = None;
let mut sw_has_origin_check = false;
for (idx, &raw_line) in lines.iter().enumerate() {
let line_no = idx + 1;
let trimmed = raw_line.trim();
let code = code_lines.get(idx).map_or("", String::as_str);
if code.contains("#[cfg(test)]") {
has_cfg_test = true;
if !in_cfg_test {
pending_cfg_test = true;
}
}
let code_no_comment = strip_line_comment(raw_line);
if pending_cfg_test {
let (opens, closes, saw_semi) = count_braces_and_semi(code);
if opens > 0 {
in_cfg_test = true;
pending_cfg_test = false;
test_brace_depth = opens - closes;
if test_brace_depth <= 0 {
in_cfg_test = false;
test_brace_depth = 0;
}
} else if saw_semi {
pending_cfg_test = false;
}
} else if in_cfg_test {
let (opens, closes, _) = count_braces_and_semi(code);
test_brace_depth += opens - closes;
if test_brace_depth <= 0 {
in_cfg_test = false;
test_brace_depth = 0;
}
}
if trimmed.starts_with("//") {
continue;
}
for sql_call in ["sqlx::query(", "sqlx::query_as(", "sqlx::raw_sql("] {
if let Some(pos) = code.find(sql_call) {
let arg_slice = extract_call_arg_slice(&code_lines, idx, pos + sql_call.len());
if has_sql_interpolation(&arg_slice) {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "sql-injection",
file: path.to_path_buf(),
line: line_no,
message: format!(
"dynamic SQL construction (`format!(` or `+`) inside `{sql_call}...)`; use parameterized `.bind(...)` instead"
),
});
}
}
}
if !in_cfg_test && !is_slabs_html_crate && code.contains(concat!("Pre", "Escaped(")) {
let allow_marker = "// slabs:allow-raw-html:";
let has_allow_here = raw_line.contains(allow_marker);
let has_allow_prev = idx > 0 && lines[idx - 1].contains(allow_marker);
if !has_allow_here && !has_allow_prev {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "raw-html",
file: path.to_path_buf(),
line: line_no,
message: "unannotated `PreEscaped(` outside `#[cfg(test)]`; prefer `html::render_markdown` or add `// slabs:allow-raw-html: <reason>`".to_string(),
});
}
}
if contains_unsafe_pattern(code) {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "unsafe-code",
file: path.to_path_buf(),
line: line_no,
message: "unsafe Rust code or `allow(unsafe_code)` is forbidden in Slabs projects"
.to_string(),
});
}
if let Some(secret_kind) = detect_hardcoded_secret(code_no_comment, is_slabs_core_crate) {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "hardcoded-secret",
file: path.to_path_buf(),
line: line_no,
message: format!("possible hardcoded secret ({secret_kind})"),
});
}
if !in_cfg_test
&& matches!(area, FileArea::Slabs | FileArea::Jobs)
&& (code.contains(".unwrap()") || code.contains(".expect("))
{
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "panic-hazard",
file: path.to_path_buf(),
line: line_no,
message: "avoid `.unwrap()` / `.expect()` outside `#[cfg(test)]` in `slabs/` and `jobs/`; return a `SlabError` with `?`".to_string(),
});
}
if !in_cfg_test {
for hmac_call in [
"verify_incoming_hmac_sha256(",
"verify_signed_timestamped_webhook(",
] {
if let Some(pos) = code.find(hmac_call) {
let arg_slice = extract_call_arg_slice(&code_lines, idx, pos + hmac_call.len());
if arg_slice.contains("config.secret_key") {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "master-key-reuse",
file: path.to_path_buf(),
line: line_no,
message: "do not pass `config.secret_key` to webhook HMAC verification; use a dedicated webhook signing secret".to_string(),
});
}
}
}
if area == FileArea::Slabs {
if ws_upgrade_line.is_none() && code.contains("WebSocketUpgrade") {
ws_upgrade_line = Some(line_no);
}
if code.contains("validate_ws_origin") {
has_validate_ws_origin = true;
}
if code.contains(".storage.get") {
has_storage_get = true;
}
if content_disposition_line.is_none() && code.contains("CONTENT_DISPOSITION") {
content_disposition_line = Some(line_no);
}
if code.contains("into_safe_response") {
has_into_safe_response = true;
}
if code.contains("style=(format!") || code.contains("hx-vals=(format!") {
report.findings.push(SecurityFinding {
severity: Severity::Warning,
rule: "template-attr-injection",
file: path.to_path_buf(),
line: line_no,
message: "avoid `style=(format!(...))` or `hx-vals=(format!(...))` in Maud templates; use fixed CSS classes or JSON serialization".to_string(),
});
}
}
if is_service_worker_file {
if sw_fetch_line.is_none()
&& (raw_line.contains("addEventListener(\"fetch\"")
|| raw_line.contains("addEventListener('fetch'"))
{
sw_fetch_line = Some(line_no);
}
if raw_line.contains("self.location.origin") {
sw_has_origin_check = true;
}
}
if is_auth_or_web {
if code.contains(".verify_password(") {
report.findings.push(SecurityFinding {
severity: Severity::Warning,
rule: "password-timing-enum",
file: path.to_path_buf(),
line: line_no,
message: "prefer `verify_password_constant_time` over `.verify_password(` in auth handlers to prevent login timing enumeration".to_string(),
});
}
if code.contains(".create_session(") {
report.findings.push(SecurityFinding {
severity: Severity::Warning,
rule: "session-fixation",
file: path.to_path_buf(),
line: line_no,
message: "prefer `rotate_session` or `rotate_session_in_tx` over `.create_session(` in auth handlers to prevent session fixation".to_string(),
});
}
}
}
}
if area == FileArea::Slabs && is_discovered_slab_file(path) && !has_cfg_test {
report.findings.push(SecurityFinding {
severity: Severity::Warning,
rule: "missing-test",
file: path.to_path_buf(),
line: 1,
message: "slab file is missing a co-located `#[cfg(test)] mod tests` block".to_string(),
});
}
if area == FileArea::Slabs {
if let Some(line_no) = ws_upgrade_line {
if !has_validate_ws_origin {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "ws-missing-origin-check",
file: path.to_path_buf(),
line: line_no,
message:
"WebSocket slab uses `WebSocketUpgrade` without calling `validate_ws_origin`"
.to_string(),
});
}
}
}
if area == FileArea::Slabs && has_storage_get && !has_into_safe_response {
if let Some(line_no) = content_disposition_line {
report.findings.push(SecurityFinding {
severity: Severity::Warning,
rule: "unsafe-blob-response",
file: path.to_path_buf(),
line: line_no,
message: "blob response sets `CONTENT_DISPOSITION` manually instead of using `BlobMeta::into_safe_response`".to_string(),
});
}
}
if is_service_worker_file {
if let Some(line_no) = sw_fetch_line {
if !sw_has_origin_check {
report.findings.push(SecurityFinding {
severity: Severity::Error,
rule: "service-worker-origin",
file: path.to_path_buf(),
line: line_no,
message: "service worker `fetch` listener must check `self.location.origin` before caching or intercepting requests".to_string(),
});
}
}
}
Ok(())
}
fn is_auth_or_web_slab(path: &Path) -> bool {
let mut saw_slabs = false;
for comp in path.components() {
if let std::path::Component::Normal(os) = comp {
if let Some(s) = os.to_str() {
if saw_slabs && (s == "auth" || s == "web") {
return true;
}
if s == "slabs" {
saw_slabs = true;
}
}
}
}
false
}
fn missing_dockerfile_hardening_tokens(content: &str) -> Vec<&'static str> {
let active: String = content
.lines()
.filter(|line| !line.trim_start().starts_with('#'))
.collect::<Vec<_>>()
.join("\n");
[
"SLABS_ENV=production",
"SLABS_COOKIE_SECURE=true",
"--locked",
"USER ",
"/health/ready",
]
.into_iter()
.filter(|token| !active.contains(token))
.collect()
}
fn is_discovered_slab_file(path: &Path) -> bool {
let Some(file_name) = path.file_name().and_then(|s| s.to_str()) else {
return false;
};
if file_name == "mod.rs" || file_name.starts_with('_') || file_name.starts_with('.') {
return false;
}
let Some(parent_name) = path
.parent()
.and_then(|p| p.file_name())
.and_then(|s| s.to_str())
else {
return false;
};
!parent_name.starts_with('_') && !parent_name.starts_with('.') && parent_name != "slabs"
}
fn cargo_toml_forbids_unsafe(manifest_path: &Path) -> bool {
fs::read_to_string(manifest_path).is_ok_and(|c| cargo_toml_content_forbids_unsafe(&c))
}
fn cargo_toml_content_forbids_unsafe(content: &str) -> bool {
let mut in_lints_rust = false;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('#') || trimmed.is_empty() {
continue;
}
if trimmed.starts_with('[') {
in_lints_rust = trimmed == "[lints.rust]" || trimmed == "[workspace.lints.rust]";
continue;
}
if in_lints_rust {
if let Some(rest) = trimmed.strip_prefix("unsafe_code") {
let rest = rest.trim_start();
if let Some(val) = rest.strip_prefix('=') {
let val = val.split('#').next().unwrap_or("").trim();
if val == "\"forbid\"" || val == "'forbid'" {
return true;
}
}
}
}
}
false
}
fn cargo_toml_inherits_workspace_lints(content: &str) -> bool {
let mut in_lints = false;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.starts_with('#') || trimmed.is_empty() {
continue;
}
if trimmed.starts_with('[') {
in_lints = trimmed == "[lints]";
continue;
}
if in_lints {
if let Some(rest) = trimmed.strip_prefix("workspace") {
let rest = rest.trim_start();
if let Some(val) = rest.strip_prefix('=') {
let val = val.split('#').next().unwrap_or("").trim();
if val == "true" {
return true;
}
}
}
}
}
false
}
fn strip_line_comment(line: &str) -> &str {
let bytes = line.as_bytes();
let mut in_string = false;
let mut escaped = false;
let mut i = 0usize;
while i < bytes.len() {
let b = bytes[i];
if in_string {
if escaped {
escaped = false;
} else if b == b'\\' {
escaped = true;
} else if b == b'"' {
in_string = false;
}
} else if b == b'"' {
in_string = true;
} else if b == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
return &line[..i];
}
i += 1;
}
line
}
fn strip_rust_file_code_lines(content: &str) -> Vec<String> {
let chars: Vec<char> = content.chars().collect();
let mut lines = Vec::new();
let mut current = String::new();
let mut i = 0usize;
let mut block_comment_depth = 0usize;
let mut in_string = false;
let mut string_escaped = false;
let mut raw_string_hashes: Option<usize> = None;
while i < chars.len() {
let ch = chars[i];
if ch == '\n' {
lines.push(std::mem::take(&mut current));
i += 1;
continue;
}
if ch == '\r' {
i += 1;
continue;
}
if block_comment_depth > 0 {
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
block_comment_depth += 1;
current.push_str(" ");
i += 2;
} else if ch == '*' && i + 1 < chars.len() && chars[i + 1] == '/' {
block_comment_depth -= 1;
current.push_str(" ");
i += 2;
} else {
current.push(' ');
i += 1;
}
continue;
}
if let Some(hashes) = raw_string_hashes {
if ch == '"' {
let mut matched = 0usize;
while matched < hashes
&& i + 1 + matched < chars.len()
&& chars[i + 1 + matched] == '#'
{
matched += 1;
}
if matched == hashes {
raw_string_hashes = None;
for _ in 0..=hashes {
current.push(' ');
}
i += 1 + hashes;
continue;
}
}
current.push(' ');
i += 1;
continue;
}
if in_string {
if string_escaped {
string_escaped = false;
} else if ch == '\\' {
string_escaped = true;
} else if ch == '"' {
in_string = false;
}
current.push(' ');
i += 1;
continue;
}
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '/' {
while i < chars.len() && chars[i] != '\n' {
i += 1;
}
continue;
}
if ch == '/' && i + 1 < chars.len() && chars[i + 1] == '*' {
block_comment_depth = 1;
current.push_str(" ");
i += 2;
continue;
}
if ch == '\'' {
if i + 2 < chars.len() && chars[i + 1] == '\\' {
if let Some(end) = chars[i + 2..].iter().position(|&c| c == '\'') {
if end <= 6 {
for _ in 0..(end + 3) {
current.push(' ');
}
i += end + 3;
continue;
}
}
} else if i + 2 < chars.len() && chars[i + 2] == '\'' && chars[i + 1] != '\n' {
current.push_str(" ");
i += 3;
continue;
}
}
if ch == 'r'
&& (i == 0
|| (!chars[i - 1].is_alphanumeric() && chars[i - 1] != '_')
|| (chars[i - 1] == 'b'
&& (i == 1 || (!chars[i - 2].is_alphanumeric() && chars[i - 2] != '_'))))
{
let mut hashes = 0usize;
let mut j = i + 1;
while j < chars.len() && chars[j] == '#' {
hashes += 1;
j += 1;
}
if j < chars.len() && chars[j] == '"' {
raw_string_hashes = Some(hashes);
for _ in i..=j {
current.push(' ');
}
i = j + 1;
continue;
}
}
if ch == '"' {
in_string = true;
current.push(' ');
i += 1;
continue;
}
current.push(ch);
i += 1;
}
if !current.is_empty() || content.ends_with('\n') || lines.is_empty() {
lines.push(current);
}
lines
}
fn count_braces_and_semi(code: &str) -> (i32, i32, bool) {
let mut opens = 0i32;
let mut closes = 0i32;
let mut saw_semi = false;
for ch in code.chars() {
match ch {
'{' => opens += 1,
'}' => closes += 1,
';' => saw_semi = true,
_ => {}
}
}
(opens, closes, saw_semi)
}
fn extract_call_arg_slice(code_lines: &[String], start_idx: usize, start_col: usize) -> String {
let mut collected = String::new();
let mut depth = 1i32;
let end_idx = (start_idx + 20).min(code_lines.len());
for (offset, code) in code_lines[start_idx..end_idx].iter().enumerate() {
let segment = if offset == 0 {
code.get(start_col..).unwrap_or("")
} else {
code.as_str()
};
for ch in segment.chars() {
match ch {
'(' => {
depth += 1;
collected.push(ch);
}
')' => {
depth -= 1;
if depth == 0 {
return collected;
}
collected.push(ch);
}
_ => collected.push(ch),
}
}
collected.push(' ');
}
collected
}
fn has_sql_interpolation(code_arg: &str) -> bool {
code_arg.contains("format!(") || code_arg.contains('+')
}
fn contains_unsafe_pattern(code: &str) -> bool {
let allow_inner = concat!("#![allow(", "unsafe_code)]");
let allow_outer = concat!("#[allow(", "unsafe_code)]");
if code.contains(allow_inner) || code.contains(allow_outer) {
return true;
}
let unsafe_kw = concat!("un", "safe");
let bytes = code.as_bytes();
let mut start = 0usize;
while let Some(rel) = code[start..].find(unsafe_kw) {
let pos = start + rel;
let before_ok =
pos == 0 || !(bytes[pos - 1].is_ascii_alphanumeric() || bytes[pos - 1] == b'_');
let after = &code[pos + unsafe_kw.len()..];
if before_ok {
let trimmed_after = after.trim_start();
if trimmed_after.starts_with('{')
|| trimmed_after.starts_with("fn ")
|| trimmed_after.starts_with("fn\t")
{
return true;
}
}
start = pos + unsafe_kw.len();
}
false
}
fn detect_hardcoded_secret(line: &str, skip_dev_sentinel: bool) -> Option<&'static str> {
let stripe_live = concat!("sk_", "live_");
let pem_begin = concat!("-----", "BEGIN ");
let dev_sentinel = concat!("dev-only-change-me-", "in-production");
if line.contains(stripe_live) {
return Some("Stripe live secret key");
}
if line.contains(pem_begin) {
return Some("PEM private key block");
}
if !skip_dev_sentinel && line.contains(dev_sentinel) {
return Some("hardcoded development fallback secret");
}
if contains_resend_api_key(line) {
return Some("Resend API key");
}
None
}
fn contains_resend_api_key(line: &str) -> bool {
let bytes = line.as_bytes();
let prefix = concat!("re", "_");
let mut start = 0usize;
while let Some(rel) = line[start..].find(prefix) {
let pos = start + rel;
let quote_preceded = pos > 0 && (bytes[pos - 1] == b'"' || bytes[pos - 1] == b'\'');
if quote_preceded {
let tail = &bytes[pos + prefix.len()..];
let token_len = tail
.iter()
.take_while(|b| b.is_ascii_alphanumeric() || **b == b'_' || **b == b'-')
.count();
if token_len >= 16 {
return true;
}
}
start = pos + prefix.len();
}
false
}
async fn run_checked_command(
cmd: &mut Command,
label: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let status = cmd.status().await?;
if !status.success() {
return Err(format!("{label} failed with status {status}").into());
}
Ok(())
}
fn manifest_is_workspace(manifest_path: &Path) -> bool {
fs::read_to_string(manifest_path)
.is_ok_and(|content| content.lines().any(|line| line.trim() == "[workspace]"))
}
fn discover_workspace_member_dirs(root: &Path) -> Vec<PathBuf> {
let manifest_path = root.join("Cargo.toml");
if manifest_path.is_file() {
let output = std::process::Command::new("cargo")
.args([
"metadata",
"--no-deps",
"--format-version",
"1",
"--manifest-path",
])
.arg(&manifest_path)
.output();
if let Ok(out) = output {
if out.status.success() {
if let Ok(json) = serde_json::from_slice::<serde_json::Value>(&out.stdout) {
if let Some(packages) = json.get("packages").and_then(|v| v.as_array()) {
let mut dirs: Vec<PathBuf> = packages
.iter()
.filter_map(|p| p.get("manifest_path").and_then(|m| m.as_str()))
.filter_map(|p| Path::new(p).parent().map(Path::to_path_buf))
.collect();
dirs.sort();
dirs.dedup();
if !dirs.is_empty() {
return dirs;
}
}
}
}
}
}
let mut dirs = vec![root.to_path_buf()];
if let Ok(entries) = fs::read_dir(root) {
for entry in entries.flatten() {
let path = entry.path();
if !path.is_dir() {
continue;
}
let Some(name) = path.file_name().and_then(|s| s.to_str()) else {
continue;
};
if name.starts_with('.') || name == "target" {
continue;
}
if path.join("Cargo.toml").exists() {
dirs.push(path);
}
}
}
dirs.sort();
dirs.dedup();
dirs
}
fn collect_workspace_discovered_rs_files(
root: &Path,
) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
let mut files = collect_discovered_rs_files(root)?;
for member_dir in discover_workspace_member_dirs(root) {
files.extend(collect_discovered_rs_files(&member_dir)?);
}
files.sort();
files.dedup();
Ok(files)
}
fn collect_discovered_rs_files(app_dir: &Path) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
let mut files = Vec::new();
for root in [app_dir.join("slabs"), app_dir.join("jobs")] {
if root.is_dir() {
collect_rs_recursive(&root, &mut files)?;
}
}
files.sort();
Ok(files)
}
fn collect_rs_recursive(
dir: &Path,
out: &mut Vec<PathBuf>,
) -> Result<(), Box<dyn std::error::Error>> {
for entry in fs::read_dir(dir)? {
let path = entry?.path();
if path.is_dir() {
collect_rs_recursive(&path, out)?;
} else if path.extension().and_then(|s| s.to_str()) == Some("rs") {
out.push(path);
}
}
Ok(())
}
async fn run_tailwind(app_dir: &Path, watch: bool) -> Result<(), Box<dyn std::error::Error>> {
let (input, output) = ensure_tailwind_paths(app_dir)?;
let mut cmd = Command::new("tailwindcss");
cmd.arg("-i").arg(&input).arg("-o").arg(&output);
if watch {
cmd.arg("--watch");
} else {
cmd.arg("--minify");
}
let status = cmd.status().await.map_err(|e| {
format!(
"failed to launch standalone `tailwindcss` binary ({e}). Install via `mise use github:tailwindlabs/tailwindcss`."
)
})?;
if !status.success() {
return Err(format!("tailwindcss exited with status {status}").into());
}
println!("Compiled Tailwind CSS -> {}", output.display());
Ok(())
}
async fn run_dev(
app_dir: &Path,
package: Option<String>,
bind: Option<String>,
) -> Result<(), Box<dyn std::error::Error>> {
let pkg = match package {
Some(p) => {
validate_app_name(&p)?;
p
}
None => infer_package_name(app_dir)?,
};
let _ = run_tailwind(app_dir, false).await;
let (input, output) = ensure_tailwind_paths(app_dir)?;
let mut tw_child = Command::new("tailwindcss")
.arg("-i")
.arg(&input)
.arg("-o")
.arg(&output)
.arg("--watch")
.kill_on_drop(true)
.spawn()
.ok();
if tw_child.is_some() {
println!(
"[slabs dev] tailwind --watch running on {}",
input.display()
);
} else {
eprintln!("[slabs dev] warning: `tailwindcss` binary not found; skipping CSS watch");
}
let has_cargo_watch = Command::new("cargo")
.args(["watch", "--version"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.await
.is_ok_and(|s| s.success());
let mut app_cmd = Command::new("cargo");
if has_cargo_watch {
println!("[slabs dev] starting `{pkg}` with `cargo watch` (auto-reloads on .rs edits)");
app_cmd.args([
"watch",
"-q",
"-w",
&app_dir.to_string_lossy(),
"-x",
&format!("run -p {pkg}"),
]);
} else {
println!(
"[slabs dev] starting `{pkg}` with `cargo run` (install `cargo-watch` for Rust auto-reload)"
);
app_cmd.args(["run", "-p", &pkg]);
}
if let Some(addr) = bind {
app_cmd.env("SLABS_BIND", addr);
}
let mut app_child = app_cmd.kill_on_drop(true).spawn()?;
tokio::select! {
status = app_child.wait() => {
if let Ok(s) = status {
println!("[slabs dev] app exited with {s}");
}
}
_ = tokio::signal::ctrl_c() => {
println!("\n[slabs dev] shutting down...");
}
}
let _ = app_child.kill().await;
if let Some(ref mut tw) = tw_child {
let _ = tw.kill().await;
}
Ok(())
}
fn ensure_tailwind_paths(app_dir: &Path) -> Result<(PathBuf, PathBuf), Box<dyn std::error::Error>> {
let input = app_dir.join("assets/input.css");
let output = app_dir.join("assets/styles/app.css");
if let Some(parent) = output.parent() {
fs::create_dir_all(parent)?;
}
if !input.exists() {
fs::create_dir_all(app_dir.join("assets"))?;
fs::write(&input, "@import \"tailwindcss\";\n@source \"../slabs\";\n")?;
}
Ok((input, output))
}
fn infer_package_name_raw(cargo_toml: &Path) -> Option<String> {
let content = fs::read_to_string(cargo_toml).ok()?;
let mut in_package = false;
for line in content.lines() {
let trimmed = line.trim();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if trimmed.starts_with('[') {
in_package = trimmed == "[package]";
continue;
}
if !in_package {
continue;
}
if let Some(rest) = trimmed.strip_prefix("name") {
let rest = rest.trim_start();
if let Some(val) = rest.strip_prefix('=') {
let raw_val = val.split('#').next().unwrap_or("").trim();
let quoted = raw_val
.strip_prefix('"')
.and_then(|s| s.strip_suffix('"'))
.or_else(|| {
raw_val
.strip_prefix('\'')
.and_then(|s| s.strip_suffix('\''))
});
if let Some(name) = quoted {
if !name.is_empty() {
return Some(name.to_string());
}
}
}
}
}
None
}
fn infer_package_name(app_dir: &Path) -> Result<String, Box<dyn std::error::Error>> {
let cargo_toml = app_dir.join("Cargo.toml");
if !cargo_toml.exists() {
return Err(format!(
"could not read {}; pass `--package <name>`",
cargo_toml.display()
)
.into());
}
let name = infer_package_name_raw(&cargo_toml)
.ok_or("could not infer `[package] name` from Cargo.toml; pass `--package <name>`")?;
validate_app_name(&name)?;
Ok(name)
}
fn list_dir(app_dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
println!("Slabs in {}:", app_dir.display());
let slabs_dir = app_dir.join("slabs");
if slabs_dir.is_dir() {
let mut features: Vec<_> = fs::read_dir(&slabs_dir)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.is_dir())
.collect();
features.sort();
for feat in features {
let Some(feat_name) = feat.file_name().map(|n| n.to_string_lossy()) else {
continue;
};
let mut files: Vec<_> = fs::read_dir(&feat)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().and_then(|s| s.to_str()) == Some("rs"))
.collect();
files.sort();
for file in files {
let Some(stem) = file.file_stem().map(|n| n.to_string_lossy()) else {
continue;
};
println!(" slab {feat_name}.{stem} ({})", file.display());
}
}
}
let jobs_dir = app_dir.join("jobs");
if jobs_dir.is_dir() {
let mut files: Vec<_> = fs::read_dir(&jobs_dir)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.extension().and_then(|s| s.to_str()) == Some("rs"))
.collect();
files.sort();
for file in files {
let Some(stem) = file.file_stem().map(|n| n.to_string_lossy()) else {
continue;
};
println!(" job {stem} ({})", file.display());
}
}
Ok(())
}
fn normalize_base_url(raw: &str) -> Result<String, String> {
let trimmed = raw.trim().trim_end_matches('/');
let rest = trimmed
.strip_prefix("http://")
.or_else(|| trimmed.strip_prefix("https://"))
.ok_or_else(|| {
format!("invalid base URL `{raw}`: must start with `http://` or `https://`")
})?;
if rest.is_empty() || rest.chars().any(char::is_whitespace) {
return Err(format!("invalid base URL `{raw}`"));
}
Ok(trimmed.to_string())
}
fn validate_incident_id(id: &str) -> Result<(), String> {
if id.is_empty() || id.len() > 128 {
return Err(format!(
"invalid incident ID `{id}`: must be 1 to 128 characters"
));
}
if !id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
{
return Err(format!(
"invalid incident ID `{id}`: only ASCII letters, digits, `_`, and `-` are allowed"
));
}
Ok(())
}
fn build_http_client() -> Result<reqwest::Client, Box<dyn std::error::Error>> {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(15))
.user_agent(concat!("slabs-cli/", env!("CARGO_PKG_VERSION")))
.build()?;
Ok(client)
}
fn apply_bearer_auth(req: reqwest::RequestBuilder, token: Option<&str>) -> reqwest::RequestBuilder {
match token.map(str::trim).filter(|t| !t.is_empty()) {
Some(t) => req.bearer_auth(t),
None => req,
}
}
async fn parse_json_response(
resp: reqwest::Response,
endpoint: &str,
) -> Result<Value, Box<dyn std::error::Error>> {
let status = resp.status();
let body = resp.text().await?;
if !status.is_success() {
let hint = if status == reqwest::StatusCode::UNAUTHORIZED
|| status == reqwest::StatusCode::NOT_FOUND
{
" (hint: pass `--token` or set `SLABS_METRICS_TOKEN` in staging/production)"
} else {
""
};
let snippet = truncate_str(body.trim(), 200);
if snippet.is_empty() {
return Err(format!("request to {endpoint} failed with HTTP {status}{hint}").into());
}
return Err(
format!("request to {endpoint} failed with HTTP {status}: {snippet}{hint}").into(),
);
}
if body.trim().is_empty() {
return Ok(json!({}));
}
let parsed: Value = serde_json::from_str(&body)
.map_err(|e| format!("invalid JSON response from {endpoint}: {e}"))?;
Ok(parsed)
}
async fn run_incidents_list(
base_url: &str,
token: Option<&str>,
status: IncidentStatusFilter,
limit: u32,
json_out: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let base = normalize_base_url(base_url)?;
let endpoint = format!(
"{base}/_slabs/incidents?status={}&limit={limit}",
status.as_str()
);
let client = build_http_client()?;
let req = apply_bearer_auth(
client
.get(&endpoint)
.header(reqwest::header::ACCEPT, "application/json"),
token,
);
let resp = req.send().await?;
let payload = parse_json_response(resp, &endpoint).await?;
if json_out {
println!("{}", serde_json::to_string_pretty(&payload)?);
} else {
print!("{}", format_incidents_list_table(&payload));
}
Ok(())
}
async fn run_incidents_show(
base_url: &str,
token: Option<&str>,
id: &str,
json_out: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let base = normalize_base_url(base_url)?;
validate_incident_id(id)?;
let endpoint = format!("{base}/_slabs/incidents/{id}");
let client = build_http_client()?;
let req = apply_bearer_auth(
client
.get(&endpoint)
.header(reqwest::header::ACCEPT, "application/json"),
token,
);
let resp = req.send().await?;
let payload = parse_json_response(resp, &endpoint).await?;
if json_out {
println!("{}", serde_json::to_string_pretty(&payload)?);
} else {
print!("{}", format_incident_detail(&payload));
}
Ok(())
}
async fn run_incidents_resolve(
base_url: &str,
token: Option<&str>,
id: &str,
sha: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
let base = normalize_base_url(base_url)?;
validate_incident_id(id)?;
let endpoint = format!("{base}/_slabs/incidents/{id}/resolve");
let client = build_http_client()?;
let body = json!({ "resolved_in_sha": sha });
let req = apply_bearer_auth(
client
.post(&endpoint)
.header(reqwest::header::ACCEPT, "application/json")
.json(&body),
token,
);
let resp = req.send().await?;
let _payload = parse_json_response(resp, &endpoint).await?;
if let Some(commit) = sha {
println!("Resolved incident `{id}` (resolved_in_sha: {commit})");
} else {
println!("Resolved incident `{id}`");
}
Ok(())
}
async fn run_incidents_claim(
base_url: &str,
token: Option<&str>,
id: &str,
assignee: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let base = normalize_base_url(base_url)?;
validate_incident_id(id)?;
let endpoint = format!("{base}/_slabs/incidents/{id}/claim");
let client = build_http_client()?;
let body = json!({ "assignee": assignee });
let req = apply_bearer_auth(
client
.post(&endpoint)
.header(reqwest::header::ACCEPT, "application/json")
.json(&body),
token,
);
let resp = req.send().await?;
let _payload = parse_json_response(resp, &endpoint).await?;
println!("Claimed incident `{id}` (assignee: {assignee})");
Ok(())
}
async fn run_incidents_link(
base_url: &str,
token: Option<&str>,
id: &str,
key: &str,
issue_url: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let base = normalize_base_url(base_url)?;
validate_incident_id(id)?;
let endpoint = format!("{base}/_slabs/incidents/{id}/link");
let client = build_http_client()?;
let body = json!({
"external_issue_key": key,
"external_issue_url": issue_url,
});
let req = apply_bearer_auth(
client
.post(&endpoint)
.header(reqwest::header::ACCEPT, "application/json")
.json(&body),
token,
);
let resp = req.send().await?;
let _payload = parse_json_response(resp, &endpoint).await?;
println!("Linked incident `{id}` to `{key}` ({issue_url})");
Ok(())
}
async fn run_incidents_ignore(
base_url: &str,
token: Option<&str>,
id: &str,
) -> Result<(), Box<dyn std::error::Error>> {
let base = normalize_base_url(base_url)?;
validate_incident_id(id)?;
let endpoint = format!("{base}/_slabs/incidents/{id}/ignore");
let client = build_http_client()?;
let req = apply_bearer_auth(
client
.post(&endpoint)
.header(reqwest::header::ACCEPT, "application/json"),
token,
);
let resp = req.send().await?;
let _payload = parse_json_response(resp, &endpoint).await?;
println!("Ignored incident `{id}`");
Ok(())
}
async fn run_mcp_stdio(
base_url: &str,
token: Option<&str>,
) -> Result<(), Box<dyn std::error::Error>> {
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
let base = normalize_base_url(base_url)?;
let client = build_http_client()?;
let mut lines = BufReader::new(tokio::io::stdin()).lines();
let mut stdout = tokio::io::stdout();
while let Some(line) = lines.next_line().await? {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
let req: Value = match serde_json::from_str(trimmed) {
Ok(v) => v,
Err(e) => {
let err_resp = json!({
"jsonrpc": "2.0",
"id": Value::Null,
"error": { "code": -32700, "message": format!("parse error: {e}") }
});
stdout
.write_all(format!("{}\n", serde_json::to_string(&err_resp)?).as_bytes())
.await?;
stdout.flush().await?;
continue;
}
};
if let Some(resp) = handle_mcp_request(&client, &base, token, &req).await {
stdout
.write_all(format!("{}\n", serde_json::to_string(&resp)?).as_bytes())
.await?;
stdout.flush().await?;
}
}
Ok(())
}
async fn handle_mcp_request(
client: &reqwest::Client,
base: &str,
token: Option<&str>,
req: &Value,
) -> Option<Value> {
let id = req.get("id").cloned();
let method = req.get("method").and_then(Value::as_str).unwrap_or("");
if method == "notifications/initialized" || id.is_none() {
return None;
}
let req_id = id.unwrap_or(Value::Null);
match method {
"initialize" => Some(json!({
"jsonrpc": "2.0",
"id": req_id,
"result": {
"protocolVersion": "2024-11-05",
"capabilities": { "tools": {} },
"serverInfo": {
"name": "slabs",
"version": env!("CARGO_PKG_VERSION"),
}
}
})),
"tools/list" => Some(json!({
"jsonrpc": "2.0",
"id": req_id,
"result": {
"tools": [
{
"name": "list_incidents",
"description": "List runtime errors, slow routes, and user bug reports from /_slabs/incidents.",
"inputSchema": {
"type": "object",
"properties": {
"status": { "type": "string", "enum": ["open", "in_progress", "resolved", "ignored", "all"] },
"limit": { "type": "integer", "minimum": 1, "maximum": 500 }
}
}
},
{
"name": "get_incident",
"description": "Fetch full detail, recent deploy SHA occurrences, attachments, and repro hint for one incident.",
"inputSchema": {
"type": "object",
"required": ["id"],
"properties": { "id": { "type": "string" } }
}
},
{
"name": "claim_incident",
"description": "Atomically claim an open incident (open -> in_progress) to prevent duplicate fixes.",
"inputSchema": {
"type": "object",
"required": ["id", "assignee"],
"properties": {
"id": { "type": "string" },
"assignee": { "type": "string" }
}
}
},
{
"name": "resolve_incident",
"description": "Mark an incident resolved with an optional fix commit SHA.",
"inputSchema": {
"type": "object",
"required": ["id"],
"properties": {
"id": { "type": "string" },
"resolved_in_sha": { "type": "string" }
}
}
},
{
"name": "list_slow_routes",
"description": "Read per-route p50/p95/p99 latency histograms, queue depth, and open incidents from /_slabs/metrics.",
"inputSchema": { "type": "object", "properties": {} }
}
]
}
})),
"tools/call" => {
let params = req.get("params").cloned().unwrap_or_else(|| json!({}));
let tool = params.get("name").and_then(Value::as_str).unwrap_or("");
let args = params
.get("arguments")
.cloned()
.unwrap_or_else(|| json!({}));
let result = execute_mcp_tool(client, base, token, tool, &args).await;
match result {
Ok(val) => Some(json!({
"jsonrpc": "2.0",
"id": req_id,
"result": {
"content": [{
"type": "text",
"text": serde_json::to_string_pretty(&val).unwrap_or_default()
}]
}
})),
Err(err) => Some(json!({
"jsonrpc": "2.0",
"id": req_id,
"result": {
"isError": true,
"content": [{ "type": "text", "text": err.to_string() }]
}
})),
}
}
_ => Some(json!({
"jsonrpc": "2.0",
"id": req_id,
"error": { "code": -32601, "message": format!("method not found: {method}") }
})),
}
}
async fn execute_mcp_tool(
client: &reqwest::Client,
base: &str,
token: Option<&str>,
tool: &str,
args: &Value,
) -> Result<Value, Box<dyn std::error::Error>> {
match tool {
"list_incidents" => {
let status = args.get("status").and_then(Value::as_str).unwrap_or("open");
let limit = args
.get("limit")
.and_then(Value::as_u64)
.unwrap_or(50)
.clamp(1, 500);
let endpoint = format!("{base}/_slabs/incidents?status={status}&limit={limit}");
let resp = apply_bearer_auth(
client
.get(&endpoint)
.header(reqwest::header::ACCEPT, "application/json"),
token,
)
.send()
.await?;
parse_json_response(resp, &endpoint).await
}
"get_incident" => {
let id = args
.get("id")
.and_then(Value::as_str)
.ok_or("missing required argument `id`")?;
validate_incident_id(id)?;
let endpoint = format!("{base}/_slabs/incidents/{id}");
let resp = apply_bearer_auth(
client
.get(&endpoint)
.header(reqwest::header::ACCEPT, "application/json"),
token,
)
.send()
.await?;
parse_json_response(resp, &endpoint).await
}
"claim_incident" => {
let id = args
.get("id")
.and_then(Value::as_str)
.ok_or("missing required argument `id`")?;
let assignee = args
.get("assignee")
.and_then(Value::as_str)
.ok_or("missing required argument `assignee`")?;
validate_incident_id(id)?;
let endpoint = format!("{base}/_slabs/incidents/{id}/claim");
let resp = apply_bearer_auth(
client
.post(&endpoint)
.header(reqwest::header::ACCEPT, "application/json")
.json(&json!({ "assignee": assignee })),
token,
)
.send()
.await?;
parse_json_response(resp, &endpoint).await
}
"resolve_incident" => {
let id = args
.get("id")
.and_then(Value::as_str)
.ok_or("missing required argument `id`")?;
let sha = args.get("resolved_in_sha").and_then(Value::as_str);
validate_incident_id(id)?;
let endpoint = format!("{base}/_slabs/incidents/{id}/resolve");
let resp = apply_bearer_auth(
client
.post(&endpoint)
.header(reqwest::header::ACCEPT, "application/json")
.json(&json!({ "resolved_in_sha": sha })),
token,
)
.send()
.await?;
parse_json_response(resp, &endpoint).await
}
"list_slow_routes" => {
let endpoint = format!("{base}/_slabs/metrics");
let resp = apply_bearer_auth(
client
.get(&endpoint)
.header(reqwest::header::ACCEPT, "application/json"),
token,
)
.send()
.await?;
parse_json_response(resp, &endpoint).await
}
other => Err(format!("unknown MCP tool `{other}`").into()),
}
}
async fn run_incidents_perf(
base_url: &str,
token: Option<&str>,
json_out: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let base = normalize_base_url(base_url)?;
let endpoint = format!("{base}/_slabs/metrics");
let client = build_http_client()?;
let req = apply_bearer_auth(
client
.get(&endpoint)
.header(reqwest::header::ACCEPT, "application/json"),
token,
);
let resp = req.send().await?;
let payload = parse_json_response(resp, &endpoint).await?;
if json_out {
println!("{}", serde_json::to_string_pretty(&payload)?);
} else {
print!("{}", format_perf_table(&payload));
}
Ok(())
}
fn value_str<'a>(obj: &'a Value, keys: &[&str]) -> Option<&'a str> {
for key in keys {
if let Some(s) = obj.get(*key).and_then(Value::as_str) {
if !s.is_empty() {
return Some(s);
}
}
}
None
}
fn value_u64(obj: &Value, keys: &[&str]) -> u64 {
for key in keys {
if let Some(v) = obj.get(*key) {
if let Some(n) = v.as_u64() {
return n;
}
if let Some(n) = v.as_i64().and_then(|i| u64::try_from(i).ok()) {
return n;
}
}
}
0
}
fn value_f64(obj: &Value, keys: &[&str]) -> f64 {
for key in keys {
if let Some(v) = obj.get(*key) {
if let Some(n) = v.as_f64() {
return n;
}
}
}
0.0
}
fn truncate_str(input: &str, max_chars: usize) -> String {
let clean: String = input
.chars()
.map(|c| {
if c == '\n' || c == '\r' || c == '\t' {
' '
} else {
c
}
})
.collect();
let count = clean.chars().count();
if count <= max_chars {
return clean;
}
if max_chars <= 3 {
return clean.chars().take(max_chars).collect();
}
let mut out: String = clean.chars().take(max_chars - 3).collect();
out.push_str("...");
out
}
fn render_table(headers: &[&str], rows: &[Vec<String>], right_align: &[bool]) -> String {
let mut widths: Vec<usize> = headers.iter().map(|h| h.len()).collect();
for row in rows {
for (idx, cell) in row.iter().enumerate() {
if let Some(w) = widths.get_mut(idx) {
*w = (*w).max(cell.chars().count());
}
}
}
let mut out = String::new();
for (idx, header) in headers.iter().enumerate() {
if idx > 0 {
out.push_str(" ");
}
let width = widths[idx];
let is_last = idx + 1 == headers.len();
if right_align.get(idx).copied().unwrap_or(false) {
let _ = write!(out, "{header:>width$}");
} else if is_last {
out.push_str(header);
} else {
let _ = write!(out, "{header:<width$}");
}
}
out.push('\n');
for row in rows {
for (idx, cell) in row.iter().enumerate() {
if idx > 0 {
out.push_str(" ");
}
let width = widths[idx];
let is_last = idx + 1 == headers.len();
if right_align.get(idx).copied().unwrap_or(false) {
let _ = write!(out, "{cell:>width$}");
} else if is_last {
out.push_str(cell);
} else {
let _ = write!(out, "{cell:<width$}");
}
}
out.push('\n');
}
out
}
fn format_incidents_list_table(payload: &Value) -> String {
let items = payload
.get("incidents")
.and_then(Value::as_array)
.or_else(|| payload.as_array());
let Some(list) = items else {
return "No incidents found.\n".to_string();
};
if list.is_empty() {
return "No incidents found.\n".to_string();
}
let rows: Vec<Vec<String>> = list
.iter()
.map(|item| {
let id = value_str(item, &["id"]).unwrap_or("-").to_string();
let kind = value_str(item, &["kind"]).unwrap_or("-").to_string();
let occ = value_u64(item, &["occurrences", "count"]).to_string();
let source_file = value_str(item, &["source_file", "slab_name"])
.unwrap_or("-")
.to_string();
let route = value_str(item, &["route_pattern", "route"])
.unwrap_or("-")
.to_string();
let err_msg = truncate_str(
value_str(item, &["error_message", "message"]).unwrap_or("-"),
64,
);
vec![id, kind, occ, source_file, route, err_msg]
})
.collect();
render_table(
&[
"ID",
"KIND",
"OCCURRENCES",
"SOURCE_FILE",
"ROUTE",
"ERROR_MESSAGE",
],
&rows,
&[false, false, true, false, false, false],
)
}
fn format_incident_detail(payload: &Value) -> String {
let item = payload
.get("incident")
.filter(|v| v.is_object())
.unwrap_or(payload);
let mut out = String::new();
let _ = writeln!(
out,
"ID: {}",
value_str(item, &["id"]).unwrap_or("-")
);
if let Some(status) = value_str(item, &["status"]) {
let _ = writeln!(out, "Status: {status}");
}
let _ = writeln!(
out,
"Kind: {}",
value_str(item, &["kind"]).unwrap_or("-")
);
let _ = writeln!(
out,
"Occurrences: {}",
value_u64(item, &["occurrences", "count"])
);
if let Some(fp) = value_str(item, &["fingerprint"]) {
let _ = writeln!(out, "Fingerprint: {fp}");
}
let _ = writeln!(
out,
"Source File: {}",
value_str(item, &["source_file", "slab_name"]).unwrap_or("-")
);
let _ = writeln!(
out,
"Route Pattern: {}",
value_str(item, &["route_pattern", "route"]).unwrap_or("-")
);
if let Some(code) = item.get("status_code").and_then(Value::as_i64) {
let _ = writeln!(out, "Status Code: {code}");
}
let _ = writeln!(
out,
"Git SHA: {}",
value_str(item, &["git_sha"]).unwrap_or("-")
);
if let Some(first) = value_str(item, &["first_seen_at"]) {
let _ = writeln!(out, "First Seen: {first}");
}
if let Some(last) = value_str(item, &["last_seen_at"]) {
let _ = writeln!(out, "Last Seen: {last}");
}
if let Some(resolved_sha) = value_str(item, &["resolved_in_sha"]) {
let _ = writeln!(out, "Resolved SHA: {resolved_sha}");
}
let _ = writeln!(
out,
"Error Message: {}",
value_str(item, &["error_message", "message"]).unwrap_or("-")
);
let context_val = item.get("context_json").or_else(|| item.get("context"));
if let Some(ctx) = context_val.filter(|v| !v.is_null()) {
let formatted_ctx = match ctx {
Value::String(s) => serde_json::from_str::<Value>(s)
.ok()
.and_then(|v| serde_json::to_string_pretty(&v).ok())
.unwrap_or_else(|| s.clone()),
other => serde_json::to_string_pretty(other).unwrap_or_else(|_| other.to_string()),
};
if !formatted_ctx.trim().is_empty() {
let _ = writeln!(out, "\nContext:\n{formatted_ctx}");
}
}
if let Some(detail) = value_str(item, &["detail"]) {
let _ = writeln!(out, "\nDetail:\n{detail}");
}
let repro = value_str(item, &["repro_hint"]).or_else(|| value_str(payload, &["repro_hint"]));
if let Some(hint) = repro {
let _ = writeln!(out, "\nRepro Hint:\n{hint}");
}
out
}
fn format_ms(ms: f64) -> String {
if (ms - ms.round()).abs() < 0.05 {
format!("{:.0}ms", ms.round())
} else {
format!("{ms:.1}ms")
}
}
fn format_perf_table(payload: &Value) -> String {
let mut out = String::new();
let routes = payload
.get("routes")
.and_then(Value::as_array)
.or_else(|| payload.pointer("/http/routes").and_then(Value::as_array))
.or_else(|| payload.get("per_route").and_then(Value::as_array));
if let Some(route_list) = routes.filter(|r| !r.is_empty()) {
let mut entries: Vec<(&Value, f64, f64, u64)> = route_list
.iter()
.map(|r| {
let p95 = value_f64(r, &["p95_ms", "p95"]);
let max = value_f64(r, &["max_ms", "max"]);
let reqs = value_u64(r, &["requests", "requests_total", "count"]);
(r, p95, max, reqs)
})
.collect();
entries.sort_by(|a, b| {
b.1.total_cmp(&a.1)
.then_with(|| b.2.total_cmp(&a.2))
.then_with(|| b.3.cmp(&a.3))
});
let rows: Vec<Vec<String>> = entries
.into_iter()
.map(|(item, p95, max, reqs)| {
let source_file = value_str(item, &["source_file", "slab", "name"])
.unwrap_or("-")
.to_string();
let method = value_str(item, &["method"]).unwrap_or("");
let route = value_str(item, &["route_pattern", "route", "path"]).unwrap_or("-");
let method_route = if method.is_empty() {
route.to_string()
} else {
format!("{method} {route}")
};
let p50 = value_f64(item, &["p50_ms", "p50"]);
let p99 = value_f64(item, &["p99_ms", "p99"]);
let slow = value_u64(item, &["slow_count", "slow_requests", "slow"]);
let err_5xx = value_u64(item, &["errors_5xx", "status_5xx", "5xx"]);
vec![
source_file,
method_route,
format_ms(p50),
format_ms(p95),
format_ms(p99),
format_ms(max),
slow.to_string(),
err_5xx.to_string(),
reqs.to_string(),
]
})
.collect();
out.push_str(&render_table(
&[
"SOURCE_FILE",
"METHOD ROUTE",
"P50",
"P95",
"P99",
"MAX",
"SLOW",
"5XX",
"REQS",
],
&rows,
&[false, false, true, true, true, true, true, true, true],
));
} else {
out.push_str("No per-route latency metrics recorded yet.\n");
}
out.push('\n');
if let Some(http) = payload.get("http").filter(|v| v.is_object()) {
let reqs = value_u64(http, &["requests_total"]);
let err_5xx = value_u64(http, &["errors_5xx_total"]);
let avg = value_f64(http, &["avg_latency_ms"]);
let _ = writeln!(
out,
"HTTP: requests={reqs} errors_5xx={err_5xx} avg_latency={}",
format_ms(avg)
);
}
if let Some(jobs) = payload.get("jobs").filter(|v| v.is_object()) {
let pending = value_u64(jobs, &["pending"]);
let running = value_u64(jobs, &["running"]);
let dead = value_u64(jobs, &["dead"]);
let completed = value_u64(jobs, &["completed"]);
let _ = writeln!(
out,
"Jobs: pending={pending} running={running} dead={dead} completed={completed}"
);
}
let open_incidents = payload
.get("incidents")
.filter(|v| v.is_object())
.map(|inc| value_u64(inc, &["open", "open_count", "count"]))
.or_else(|| payload.get("open_incidents").and_then(Value::as_u64))
.unwrap_or(0);
let _ = writeln!(out, "Incidents: open={open_incidents}");
if let Some(realtime) = payload.get("realtime").filter(|v| v.is_object()) {
let topics = value_u64(realtime, &["active_topics"]);
let _ = writeln!(out, "Realtime: active_topics={topics}");
}
out
}
const SKILL_ADD_SLAB: &str = r#"---
name: add-slab
description: End-to-end procedure for creating a new self-contained HTTP Transaction Script in a Slabs application. Use when adding any new endpoint, page, or HTMX fragment handler.
---
# Add a slab
Follow every step in order. Do not create `models/`, `controllers/`, `repositories/`, `services/`, or a central `routes.rs`, and do not edit `src/lib.rs` to wire up the route.
## 1. Inspect the schema
Read `schema.sql` in the application directory before writing any SQL. Confirm exact table names, column types, foreign keys, and indexes.
## 2. Create the slab file
Place the file at `slabs/<feature>/<action>.rs` (for example `slabs/cards/create_card.rs`), or generate a starter with:
```bash
slabs new slab <feature> <action> --method <get|post|put|patch|delete> --path <route>
```
Use Axum 0.8 path syntax: `{id}` for parameters and `{*path}` for wildcards. Never use `:id` or `*path`. Keep `<feature>` and `<action>` lowercase snake_case Rust identifiers.
## 3. Implement the Transaction Script
Structure the file from top to bottom:
1. `pub fn slab() -> SlabDef` with `.name("<feature>.<action>")` and `.summary("...")`.
2. Local `Input` and `Output` structs (owned by this file; duplicate small structs instead of extracting shared DTO modules).
3. `async fn handle(...)`:
- Put authentication and rate-limit guards on line 1 (`ctx.auth.require_session(&jar).await?`, `require_admin`, `require_auth`, `require_write_auth`, and `ctx.rate_limit.check(&key, limit, window_secs)?` on auth or expensive routes).
- Verify resource ownership or role permissions against `session.user_id` before reading private data or mutating rows.
- Validate and trim inputs, returning `SlabError::validation(field, message)`, `SlabError::ValidationErrors`, or `SlabError::bad_request(message)`.
- Never use `.unwrap()` or `.expect()` in request handler code; propagate errors with `?`.
- For read-only `SELECT` queries, execute against `ctx.db.reader()`.
- For any multi-step write or write with side effects, open `let mut tx = ctx.db.begin().await?;` (`BEGIN IMMEDIATE` on the single writer pool).
- Use parameterized `sqlx::query` / `sqlx::query_as` only. Escape FTS5 search terms with `slabs::db::fts5_query`.
- Enqueue background jobs inside the transaction with `ctx.jobs.enqueue_in_tx(&mut tx, ...)` and queue webhooks with `ctx.webhooks.dispatch_in_tx(&mut tx, ...)`.
- Commit with `tx.commit().await?;`.
- For HTML responses, render with `maud!`, `html::document(...)`, and `html::render_markdown(&untrusted_md)`. Avoid raw HTML; if a static snippet requires it, document why with `// slabs:allow-raw-html: <reason>`.
## 4. Add a co-located test
Add `#[cfg(test)] mod tests` at the bottom of the same slab file using `crate::test_app().await`.
## 5. Verify before finishing
```bash
slabs css
slabs fmt --check || slabs fmt
slabs check --no-docs
```
"#;
const SKILL_ADD_MIGRATION: &str = r"---
name: add-migration
description: Procedure for adding or updating SQLite or PostgreSQL database schema migrations in a Slabs application and keeping schema.sql and offline SQLx metadata in sync.
---
# Add a database migration
Follow every step in order so `migrations/`, `schema.sql`, and any `.sqlx/` cache stay consistent and rollbacks remain safe.
## 1. Check existing migrations
List `migrations/` and read `schema.sql` to see the next sequential number. Do not modify an already-applied migration file; create a new numbered file.
## 2. Design for expand-and-contract rollbacks
- **Expand first:** add nullable columns, defaults, new tables, and new indexes so the previous container image continues to work if you roll back.
- **Contract later:** drop obsolete columns or tables in a follow-up migration after the new binary is stable.
## 3. Write the migration SQL
Create `migrations/<NNNN>_<description>.sql` (for example `migrations/0002_add_card_labels.sql`). Avoid colliding with the 12 framework system tables (`slabs_sessions`, `slabs_magic_links`, `slabs_access_tokens`, `slabs_jobs`, `slabs_mail_outbox`, `slabs_blobs`, `slabs_cache`, `slabs_webhooks`, `slabs_webhook_deliveries`, `slabs_idempotency_keys`, `slabs_audit_log`, `slabs_incidents`).
## 4. Apply and dump `schema.sql`
```bash
slabs db migrate --database-url sqlite://dev.db?mode=rwc
slabs db dump-schema --database-url sqlite://dev.db?mode=rwc
```
## 5. Refresh compile-time SQLx cache (if used)
```bash
slabs db prepare
```
## 6. Run the full verification suite
```bash
slabs check --no-docs
```
";
const SKILL_REVIEW_SLAB: &str = r#"---
name: review-slab
description: Audit a Slabs application or pull request for common agent and Rust pitfalls specific to the Slabs architecture. Use before merging or handing off a feature.
---
# Review a slab
Inspect every added or modified file in `slabs/` and `jobs/` against this checklist. Report concrete `file:line` references for every defect found.
## Architecture and discovery
- No `models/`, `controllers/`, `repositories/`, `services/`, or central `routes.rs` directories were added.
- `src/lib.rs` was not edited to register routes or jobs, and `test_app()` is gated behind `#[cfg(test)]`.
- Helper files inside `slabs/` or `jobs/` start with `_`.
- Every route path uses Axum 0.8 `{param}` and `{*wildcard}` syntax.
## Database and transactions
- Read-only `SELECT` queries use `ctx.db.reader()`.
- Multi-step writes and domain writes paired with jobs or webhooks use `let mut tx = ctx.db.begin().await?;`.
- All SQL uses parameterized binds (`.bind(...)`), with zero dynamic string interpolation.
- FTS5 search queries sanitize user input through `slabs::db::fts5_query`.
- `schema.sql` matches the latest SQL in `migrations/`.
## Security and HTML
- Protected endpoints call `ctx.auth.require_session`, `require_admin`, `require_auth`, or `require_write_auth` on line 1 of `handle`, and verify resource ownership against `session.user_id`.
- Auth, magic-link, and expensive endpoints call `ctx.rate_limit.check(...)`.
- User-authored Markdown uses `html::render_markdown(&text)` rather than raw HTML.
- No hardcoded secrets exist anywhere in source or config files.
- `Cargo.toml` enforces `unsafe_code = "forbid"`.
## Reliability, formatting, and tests
- No `.unwrap()` or `.expect()` calls appear outside `#[cfg(test)]` in `slabs/` or `jobs/`.
- Every new slab includes a co-located `#[cfg(test)] mod tests` block using `crate::test_app().await`.
- Run `slabs doctor`, `slabs fmt --check`, and `slabs check --no-docs`.
"#;
const SKILL_DEPLOY_APP: &str = r#"---
name: deploy-app
description: Production deployment, zero-downtime rollout, and fast rollback procedure for a Slabs application on Kamal 2, Fly.io, or a bare Linux VPS with Caddy and systemd.
---
# Deploy a Slabs application
## 1. Pre-flight verification
```bash
slabs doctor
slabs check --no-docs
slabs css
```
Confirm `SLABS_ENV=production`, `SLABS_SECRET_KEY` (>= 32 random bytes), `SLABS_COOKIE_SECURE=true`, `SLABS_TRUST_PROXY=true`, and optional `SLABS_CORS_ORIGINS` are configured.
## 2. Expand-and-contract migrations and backup
Ensure new migrations keep the previous container image functional during a rollback, and back up SQLite (`sqlite3 /data/<app>.db "VACUUM INTO '/data/backup-pre-deploy.db'"` or verify `litestream snapshots`) before migrating.
## 3. Immutable SHA tags and deploy target
Generate config once via `slabs deploy init --target kamal|fly|vps` and tag images with the git SHA, never `:latest`.
- PostgreSQL supports multi-replica rolling deploys.
- Single-volume SQLite + Litestream runs one writer at a time (Kamal 2 `boot.limit = 1` + `kamal-proxy` buffering on `/health/ready` + 20s `SIGTERM` drain, or Fly.io `strategy = "immediate"`).
## 4. Verify and roll back fast if needed
Check `GET /health/ready` and `GET /_slabs/metrics`. Roll back immediately on failure with `kamal rollback <sha>`, `fly releases rollback`, or flipping `/opt/<app>/current` and restarting `systemd`.
"#;
const SKILL_FIX_INCIDENT: &str = r"---
name: fix-incident
description: Closed-loop procedure for triaging, reproducing, and fixing production runtime errors and performance bottlenecks reported in slabs_incidents and /_slabs/metrics.
---
# Fix an incident
Follow every step in order to turn a production error or slow route into a verified pull request with a co-located regression test.
## 1. Pull open incidents and slowest routes
```bash
slabs incidents list --json
slabs incidents perf --json
```
Prioritize open runtime errors (`http_5xx`, `panic`, `job_dead`, `client_error`) by occurrence count, then inspect `slow_request`, `slow_job`, and the slowest `p95` routes.
## 2. Inspect the single incident
```bash
slabs incidents show <id>
```
Record `source_file` (for example `slabs/rooms/send_message.rs` or `jobs/send_email.rs`), `route_pattern`, `git_sha`, `fingerprint`, `context_json`, `detail`, and `repro_hint`.
## 3. Read only that single source file and `schema.sql`
Read only `source_file` and `schema.sql`. Do not scan unrelated slabs or extract shared helper layers.
## 4. Diagnose the root cause
- **Runtime errors (`http_5xx`, `panic`, `job_dead`, `client_error`):** check bounds checks, SQL constraints, missing HTMX target IDs, and unhandled upstream errors.
- **Performance bottlenecks (`slow_request`, `slow_job`, high `p95`):** run `Db::explain_query_plan` in a test to spot SQLite `SCAN` full table scans, remove N+1 queries inside loops, switch unbounded queries to `CursorPage`, and move CPU-heavy work into `tokio::task::spawn_blocking`.
## 5. Add a failing co-located test first
Add a `#[cfg(test)]` test inside `source_file` using `crate::test_app().await` that reproduces the failure or asserts an indexed query plan (`USING INDEX`).
## 6. Implement the fix, verify, open a PR, and resolve
1. Patch `source_file` (and add an expand-and-contract migration plus `slabs db dump-schema` if adding an index).
2. Run `slabs check`.
3. Open a pull request citing the incident ID and fingerprint.
4. Mark the incident resolved after deploy:
```bash
slabs incidents resolve <id> --sha <git_sha>
```
";
#[cfg(test)]
mod tests {
use super::*;
fn temp_test_dir(prefix: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("slabs_cli_{prefix}_{}", slabs_core::id::new("tst")));
fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn validates_rust_identifiers() {
assert!(validate_rust_ident("rooms").is_ok());
assert!(validate_rust_ident("rename_room_2").is_ok());
assert!(validate_rust_ident("").is_err());
assert!(validate_rust_ident("2rooms").is_err());
assert!(validate_rust_ident("RoomName").is_err());
assert!(validate_rust_ident("rename-room").is_err());
assert!(validate_rust_ident("../etc").is_err());
assert!(validate_rust_ident("match").is_err());
assert!(validate_rust_ident("async").is_err());
assert!(validate_rust_ident("unsafe").is_err());
assert!(validate_rust_ident("gen").is_err());
}
#[test]
fn validates_app_names() {
assert!(validate_app_name("my_app").is_ok());
assert!(validate_app_name("my-app-2").is_ok());
assert!(validate_app_name("").is_err());
assert!(validate_app_name("MyApp").is_err());
assert!(validate_app_name("1app").is_err());
assert!(validate_app_name("../escape").is_err());
assert!(validate_app_name("app;rm -rf /").is_err());
assert!(validate_app_name(&"a".repeat(64)).is_ok());
assert!(validate_app_name(&"a".repeat(65)).is_err());
}
#[test]
fn validates_route_paths() {
assert!(validate_route_path("/api/rooms/{room_id}").is_ok());
assert!(validate_route_path("/assets/{*path}").is_ok());
assert!(validate_route_path("api/rooms").is_err());
assert!(validate_route_path("/api/rooms with space").is_err());
assert!(validate_route_path("/api/\"quote").is_err());
assert!(validate_route_path("/api/\\slash").is_err());
assert!(validate_route_path("/api/line\nbreak").is_err());
}
#[test]
fn infers_package_name_strictly_from_package_section() {
let tmp = temp_test_dir("infer_pkg");
fs::write(
tmp.join("Cargo.toml"),
r#"
[[bin]]
name = "wrong_bin"
path = "src/main.rs"
[package]
version = "0.1.0"
name = "campfire" # inline comment
[dependencies]
name = "wrong_dep"
"#,
)
.unwrap();
assert_eq!(infer_package_name(&tmp).unwrap(), "campfire");
fs::write(
tmp.join("Cargo.toml"),
"[package]\nname = \"Invalid Name!\"\n",
)
.unwrap();
assert!(infer_package_name(&tmp).is_err());
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn security_scanner_catches_all_six_rules() {
let tmp = temp_test_dir("sec_scan");
fs::create_dir_all(tmp.join("slabs/items")).unwrap();
fs::create_dir_all(tmp.join("jobs")).unwrap();
fs::create_dir_all(tmp.join("src")).unwrap();
fs::write(
tmp.join("Cargo.toml"),
"[package]\nname = \"vuln_app\"\nversion = \"0.1.0\"\n",
)
.unwrap();
let bad_slab = format!(
r#"
async fn bad() {{
let q = sqlx::query(&format!("SELECT * FROM t WHERE id = {{}}", 1));
let q2 = sqlx::query_as("SELECT * FROM " + "items");
let ok_sql = sqlx::query("UPDATE counters SET n = n + 1 WHERE id = ?");
let ok_multiline = sqlx::query_as(
"UPDATE slabs_jobs
SET attempts = attempts + 1
WHERE id = ?"
);
let h = {pre}("<b>x</b>");
// slabs:allow-raw-html: static icon
let ok_h = {pre}("<svg/>");
let s1 = "{stripe}1234567890";
let s2 = "{resend}1234567890abcdef1234";
let s3 = "{pem}PRIVATE KEY-----";
let s4 = "{dev}";
let _ = Some(1).unwrap();
{unsafe_kw} {{ }}
}}
"#,
pre = concat!("Pre", "Escaped"),
stripe = concat!("sk_", "live_"),
resend = concat!("re", "_"),
pem = concat!("-----", "BEGIN "),
dev = concat!("dev-only-change-me-", "in-production"),
unsafe_kw = concat!("un", "safe"),
);
fs::write(tmp.join("slabs/items/create_item.rs"), bad_slab).unwrap();
let bad_job = "async fn run() { let _ = Some(1).expect(\"boom\"); }\n";
fs::write(tmp.join("jobs/notify.rs"), bad_job).unwrap();
let report = scan_security(&tmp, false).unwrap();
let rules: Vec<&str> = report.findings.iter().map(|f| f.rule).collect();
assert_eq!(
rules.iter().filter(|&&r| r == "sql-injection").count(),
2,
"expected exactly 2 sql-injection findings (and not the SQL + 1 literal): {:?}",
report.findings
);
assert_eq!(
rules.iter().filter(|&&r| r == "raw-html").count(),
1,
"expected 1 unannotated raw-html finding: {:?}",
report.findings
);
assert_eq!(
rules.iter().filter(|&&r| r == "unsafe-code").count(),
2,
"expected Cargo.toml + unsafe block findings: {:?}",
report.findings
);
assert_eq!(
rules.iter().filter(|&&r| r == "hardcoded-secret").count(),
4,
"expected 4 hardcoded secret findings: {:?}",
report.findings
);
assert_eq!(
rules.iter().filter(|&&r| r == "panic-hazard").count(),
2,
"expected 2 panic-hazard findings across slabs/ and jobs/: {:?}",
report.findings
);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "missing-test" && f.severity == Severity::Warning)
.count(),
1,
"expected 1 missing-test warning: {:?}",
report.findings
);
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn security_scanner_catches_new_upstream_rules_and_allows_safe_patterns() {
let tmp = temp_test_dir("sec_scan_new_rules");
fs::create_dir_all(tmp.join("slabs/webhooks")).unwrap();
fs::create_dir_all(tmp.join("slabs/realtime")).unwrap();
fs::create_dir_all(tmp.join("slabs/uploads")).unwrap();
fs::create_dir_all(tmp.join("slabs/pages")).unwrap();
fs::create_dir_all(tmp.join("slabs/pwa")).unwrap();
fs::create_dir_all(tmp.join("slabs/auth")).unwrap();
fs::create_dir_all(tmp.join("slabs/web")).unwrap();
fs::write(
tmp.join("Cargo.toml"),
"[package]\nname = \"audit_app\"\nversion = \"0.1.0\"\n\n[lints.rust]\nunsafe_code = \"forbid\"\n",
)
.unwrap();
fs::write(
tmp.join("slabs/webhooks/inbound.rs"),
r#"
async fn bad_hooks(ctx: AppCtx, body: &[u8]) {
let _ = Webhooks::verify_incoming_hmac_sha256(&ctx.config.secret_key, body, "sha256=00", "sha256=");
let _ = Webhooks::verify_signed_timestamped_webhook(
&ctx.config.secret_key,
123,
300,
body,
"v1=00",
"v1=",
);
let _ = Webhooks::verify_incoming_hmac_sha256("whsec_dedicated", body, "sha256=00", "sha256=");
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
fs::write(
tmp.join("slabs/realtime/bad_ws.rs"),
r"
async fn handle(ws: WebSocketUpgrade) { let _ = ws; }
#[cfg(test)]
mod tests {}
",
)
.unwrap();
fs::write(
tmp.join("slabs/realtime/good_ws.rs"),
r"
async fn handle(ws: WebSocketUpgrade, headers: HeaderMap) {
let _ = validate_ws_origin(&headers);
let _ = ws;
}
#[cfg(test)]
mod tests {}
",
)
.unwrap();
fs::write(
tmp.join("slabs/uploads/bad_download.rs"),
r#"
async fn handle(ctx: AppCtx) {
let (_meta, _bytes) = ctx.storage.get("blb_1").await;
let _hdr = header::CONTENT_DISPOSITION;
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
fs::write(
tmp.join("slabs/uploads/good_download.rs"),
r#"
async fn handle(ctx: AppCtx) {
let (meta, bytes) = ctx.storage.get_scoped("blb_1", None).await;
let _ = meta.into_safe_response(bytes, true);
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
fs::write(
tmp.join("slabs/pages/card.rs"),
r#"
fn render(color: &str, id: &str) {
let _ = maud! {
div style=(format!("color: {color}")) hx-vals=(format!("{{\"id\":\"{id}\"}}")) {}
};
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
fs::write(
tmp.join("slabs/pwa/service_worker.rs"),
r##"
const SW_JS: &str = r#"
self.addEventListener("fetch", (event) => {
event.respondWith(fetch(event.request));
});
"#;
#[cfg(test)]
mod tests {}
"##,
)
.unwrap();
fs::write(
tmp.join("slabs/auth/login.rs"),
r#"
async fn handle(ctx: AppCtx) {
let _ = ctx.auth.verify_password("pw", "hash").await;
let _ = ctx.auth.create_session("usr_1", "member", 30).await;
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
fs::write(
tmp.join("slabs/web/signin.rs"),
r#"
async fn handle(ctx: AppCtx) {
let _ = ctx.auth.verify_password_constant_time("pw", Some("hash")).await;
let _ = ctx.auth.rotate_session("old", "usr_1", "member", 30).await;
}
#[cfg(test)]
mod tests {}
"#,
)
.unwrap();
let report = scan_security(&tmp, false).unwrap();
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "master-key-reuse" && f.severity == Severity::Error)
.count(),
2,
"expected 2 master-key-reuse errors: {:?}",
report.findings
);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "ws-missing-origin-check" && f.severity == Severity::Error)
.count(),
1,
"expected 1 ws-missing-origin-check error: {:?}",
report.findings
);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "unsafe-blob-response" && f.severity == Severity::Warning)
.count(),
1,
"expected 1 unsafe-blob-response warning: {:?}",
report.findings
);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "template-attr-injection" && f.severity == Severity::Warning)
.count(),
1,
"expected 1 template-attr-injection warning: {:?}",
report.findings
);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "service-worker-origin" && f.severity == Severity::Error)
.count(),
1,
"expected 1 service-worker-origin error: {:?}",
report.findings
);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "password-timing-enum" && f.severity == Severity::Warning)
.count(),
1,
"expected 1 password-timing-enum warning: {:?}",
report.findings
);
assert_eq!(
report
.findings
.iter()
.filter(|f| f.rule == "session-fixation" && f.severity == Severity::Warning)
.count(),
1,
"expected 1 session-fixation warning: {:?}",
report.findings
);
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn dockerfile_hardening_check_detects_missing_directives() {
let hardened = r"
FROM debian:bookworm-slim
RUN cargo build --release --locked
USER slabs
ENV SLABS_ENV=production
ENV SLABS_COOKIE_SECURE=true
HEALTHCHECK CMD curl -fsS http://127.0.0.1:3000/health/ready || exit 1
";
assert_eq!(
missing_dockerfile_hardening_tokens(hardened),
Vec::<&str>::new()
);
let weak = r"
FROM debian:bookworm-slim
# USER slabs
RUN cargo build --release
ENV SLABS_ENV=development
";
let missing = missing_dockerfile_hardening_tokens(weak);
assert_eq!(
missing,
vec![
"SLABS_ENV=production",
"SLABS_COOKIE_SECURE=true",
"--locked",
"USER ",
"/health/ready",
]
);
}
#[test]
fn deploy_init_generates_kamal_fly_and_vps_templates() {
let tmp = temp_test_dir("deploy_init");
let kamal_files = scaffold_deploy(&tmp, "my-app", DeployTarget::Kamal, false).unwrap();
assert_eq!(kamal_files.len(), 1);
let kamal = fs::read_to_string(tmp.join("config/deploy.yml")).unwrap();
assert!(kamal.contains("path: /health/ready"));
assert!(kamal.contains("drain_timeout: 20"));
assert!(kamal.contains("SLABS_ENV: production"));
assert!(kamal.contains("SLABS_COOKIE_SECURE: \"true\""));
assert!(kamal.contains("SLABS_TRUST_PROXY: \"true\""));
assert!(kamal.contains("kamal rollback"));
assert!(kamal.contains("limit: 1"));
assert!(scaffold_deploy(&tmp, "my-app", DeployTarget::Kamal, false).is_err());
assert!(scaffold_deploy(&tmp, "my-app", DeployTarget::Kamal, true).is_ok());
let fly_files = scaffold_deploy(&tmp, "my-app", DeployTarget::Fly, false).unwrap();
assert_eq!(fly_files.len(), 1);
let fly = fs::read_to_string(tmp.join("fly.toml")).unwrap();
assert!(fly.contains("path = \"/health/ready\""));
assert!(fly.contains("kill_signal = \"SIGTERM\""));
assert!(fly.contains("kill_timeout = \"20s\""));
assert!(fly.contains("strategy = \"immediate\""));
assert!(fly.contains("destination = \"/data\""));
assert!(fly.contains("SLABS_ENV = \"production\""));
let vps_files = scaffold_deploy(&tmp, "my-app", DeployTarget::Vps, false).unwrap();
assert_eq!(vps_files.len(), 2);
let caddy = fs::read_to_string(tmp.join("deploy/Caddyfile")).unwrap();
assert!(caddy.contains("reverse_proxy 127.0.0.1:3000"));
assert!(caddy.contains("health_uri /health/ready"));
let unit = fs::read_to_string(tmp.join("deploy/my-app.service")).unwrap();
assert!(unit.contains("KillSignal=SIGTERM"));
assert!(unit.contains("TimeoutStopSec=20s"));
assert!(unit.contains("NoNewPrivileges=true"));
assert!(unit.contains("ProtectSystem=strict"));
assert!(unit.contains("ReadWritePaths=/data"));
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn scaffolded_app_slab_and_job_pass_rustfmt_and_security_scan() {
let tmp = temp_test_dir("scaffold_v03");
let app_dir = tmp.join("demo_app");
scaffold_app("demo_app", &app_dir).unwrap();
fs::write(
app_dir.join("slabs/pages/create_item.rs"),
render_slab_template("pages", "create_item", HttpMethod::Post, "/api/items"),
)
.unwrap();
fs::write(
app_dir.join("slabs/pages/list_items.rs"),
render_slab_template("pages", "list_items", HttpMethod::Get, "/api/items"),
)
.unwrap();
fs::write(
app_dir.join("jobs/send_digest.rs"),
render_job_template("send_digest"),
)
.unwrap();
let mut rs_files = vec![
app_dir.join("build.rs"),
app_dir.join("src/lib.rs"),
app_dir.join("src/main.rs"),
];
rs_files.extend(collect_discovered_rs_files(&app_dir).unwrap());
let output = std::process::Command::new("rustfmt")
.args(["--edition", "2021", "--check"])
.args(&rs_files)
.output()
.expect("rustfmt must be available");
assert!(
output.status.success(),
"scaffolded templates failed rustfmt:\n{}",
String::from_utf8_lossy(&output.stdout)
);
let report = scan_security(&app_dir, false).unwrap();
assert_eq!(
report.error_count(),
0,
"scaffolded app must have 0 security errors: {:?}",
report.findings
);
assert_eq!(
report.warning_count(),
0,
"scaffolded app must have 0 security warnings: {:?}",
report.findings
);
let cargo_toml = fs::read_to_string(app_dir.join("Cargo.toml")).unwrap();
assert!(cargo_toml.contains("unsafe_code = \"forbid\""));
assert!(cargo_toml.contains("slabs-framework = \"0.3\""));
assert!(cargo_toml.contains("slabs-build = \"0.3\""));
assert!(!cargo_toml.contains("git = "));
let lib_rs = fs::read_to_string(app_dir.join("src/lib.rs")).unwrap();
assert!(lib_rs.contains("#[cfg(test)]\npub async fn test_app()"));
let dockerfile = fs::read_to_string(app_dir.join("Dockerfile")).unwrap();
assert!(dockerfile.contains("lukemathwalker/cargo-chef:latest-rust-1.88-slim"));
assert!(dockerfile.contains("cargo build --release --locked"));
assert!(dockerfile.contains("LITESTREAM_VERSION=v0.3.13"));
assert!(dockerfile.contains("USER slabs"));
assert!(dockerfile.contains("ENV SLABS_ENV=production"));
assert!(dockerfile.contains("ENV SLABS_COOKIE_SECURE=true"));
assert!(dockerfile.contains("/health/ready"));
let entrypoint = fs::read_to_string(app_dir.join("docker-entrypoint.sh")).unwrap();
assert!(entrypoint.contains("litestream restore"));
assert!(entrypoint.contains("litestream replicate"));
let dockerignore = fs::read_to_string(app_dir.join(".dockerignore")).unwrap();
assert!(dockerignore.contains(".git"));
assert!(dockerignore.contains("target"));
assert!(dockerignore.contains(".env.*"));
assert!(dockerignore.contains("*.db-wal"));
let sw = fs::read_to_string(app_dir.join("slabs/pwa/service_worker.rs")).unwrap();
assert!(sw.contains("url.origin !== self.location.origin"));
assert!(sw.contains("try {"));
assert!(sw.contains("resolved.origin === self.location.origin"));
let icon = fs::read_to_string(app_dir.join("assets/icon.svg")).unwrap();
assert!(icon.contains("slabs-mark-cuts"));
assert!(icon.contains("slabs-mark-s"));
assert!(icon.contains("#D34516"));
assert!(icon.contains("#A6330E"));
assert!(icon.contains("#8C2A0B"));
let ci = fs::read_to_string(app_dir.join(".github/workflows/ci.yml")).unwrap();
assert!(ci.contains("permissions:\n contents: read"));
assert!(app_dir.join(".claude/skills/add-slab/SKILL.md").exists());
assert!(app_dir
.join(".claude/skills/add-migration/SKILL.md")
.exists());
assert!(app_dir.join(".claude/skills/review-slab/SKILL.md").exists());
assert!(app_dir.join(".claude/skills/deploy-app/SKILL.md").exists());
assert!(app_dir
.join(".claude/skills/fix-incident/SKILL.md")
.exists());
let create_slab = fs::read_to_string(app_dir.join("slabs/pages/create_item.rs")).unwrap();
assert!(create_slab.contains("let session = ctx.auth.require_session(&jar).await?;"));
assert!(create_slab.contains("#[cfg(test)]"));
let _ = fs::remove_dir_all(&tmp);
}
#[test]
fn validates_incident_ids_and_base_urls() {
assert!(validate_incident_id("inc_01JABC123").is_ok());
assert!(validate_incident_id("inc-42").is_ok());
assert!(validate_incident_id("").is_err());
assert!(validate_incident_id("../etc/passwd").is_err());
assert!(validate_incident_id("inc/123").is_err());
assert!(validate_incident_id("inc 123").is_err());
assert_eq!(
normalize_base_url("https://app.example.com///").unwrap(),
"https://app.example.com"
);
assert_eq!(
normalize_base_url("http://127.0.0.1:3000/").unwrap(),
"http://127.0.0.1:3000"
);
assert!(normalize_base_url("ftp://example.com").is_err());
assert!(normalize_base_url("http://").is_err());
}
#[test]
fn formats_incidents_list_detail_and_perf_tables() {
let list_payload = json!({
"incidents": [
{
"id": "inc_01TEST",
"kind": "http_5xx",
"occurrences": 7,
"source_file": "slabs/rooms/send_message.rs",
"route_pattern": "POST /api/rooms/{room_id}/messages",
"error_message": "UNIQUE constraint failed: messages.id"
}
]
});
let list_table = format_incidents_list_table(&list_payload);
assert!(list_table.contains("ID"));
assert!(list_table.contains("OCCURRENCES"));
assert!(list_table.contains("SOURCE_FILE"));
assert!(list_table.contains("inc_01TEST"));
assert!(list_table.contains("slabs/rooms/send_message.rs"));
assert!(list_table.contains("UNIQUE constraint failed"));
let show_payload = json!({
"id": "inc_01TEST",
"status": "open",
"kind": "slow_request",
"occurrences": 3,
"fingerprint": "fp_abc123",
"source_file": "slabs/cards/list_cards.rs",
"route_pattern": "GET /api/boards/{board_id}/cards",
"git_sha": "deadbeef",
"error_message": "request exceeded 500ms threshold",
"context_json": "{\"latency_ms\": 812}",
"detail": "SCAN cards",
"repro_hint": "curl -s http://127.0.0.1:3000/api/boards/brd_1/cards"
});
let detail = format_incident_detail(&show_payload);
assert!(detail.contains("Source File: slabs/cards/list_cards.rs"));
assert!(detail.contains("Route Pattern: GET /api/boards/{board_id}/cards"));
assert!(detail.contains("Git SHA: deadbeef"));
assert!(detail.contains("\"latency_ms\": 812"));
assert!(detail.contains("SCAN cards"));
assert!(detail.contains("Repro Hint:"));
let perf_payload = json!({
"http": {
"requests_total": 120,
"errors_5xx_total": 2,
"avg_latency_ms": 42.5
},
"jobs": {
"pending": 4,
"running": 1,
"dead": 2,
"completed": 99
},
"incidents": {
"open": 3
},
"realtime": {
"active_topics": 5
},
"routes": [
{
"source_file": "slabs/pages/show_home.rs",
"method": "GET",
"route_pattern": "/",
"p50_ms": 4.0,
"p95_ms": 12.0,
"p99_ms": 18.0,
"max_ms": 22.0,
"slow_count": 0,
"errors_5xx": 0,
"requests": 100
},
{
"source_file": "slabs/cards/list_cards.rs",
"method": "GET",
"route_pattern": "/api/boards/{board_id}/cards",
"p50_ms": 90.0,
"p95_ms": 620.0,
"p99_ms": 840.0,
"max_ms": 910.0,
"slow_count": 5,
"errors_5xx": 2,
"requests": 20
}
]
});
let perf = format_perf_table(&perf_payload);
assert!(perf.contains("SOURCE_FILE"));
assert!(perf.contains("METHOD ROUTE"));
assert!(perf.contains("P95"));
let slow_idx = perf.find("slabs/cards/list_cards.rs").unwrap();
let fast_idx = perf.find("slabs/pages/show_home.rs").unwrap();
assert!(
slow_idx < fast_idx,
"routes must be ranked slowest first:\n{perf}"
);
assert!(perf.contains("Jobs: pending=4 running=1 dead=2 completed=99"));
assert!(perf.contains("Incidents: open=3"));
}
#[test]
fn parses_incidents_cli_subcommands() {
let cli = Cli::try_parse_from([
"slabs",
"incidents",
"list",
"--url",
"https://demo.example.com",
"--token",
"tok_123",
"--status",
"all",
"--limit",
"25",
"--json",
])
.unwrap();
assert!(matches!(
cli.command,
Commands::Incidents {
action: IncidentsAction::List {
status: IncidentStatusFilter::All,
limit: 25,
json: true,
..
}
}
));
let show =
Cli::try_parse_from(["slabs", "incidents", "show", "inc_01ABC", "--json"]).unwrap();
assert!(matches!(
show.command,
Commands::Incidents {
action: IncidentsAction::Show { json: true, .. }
}
));
let resolve = Cli::try_parse_from([
"slabs",
"incidents",
"resolve",
"inc_01ABC",
"--sha",
"abcdef1",
])
.unwrap();
assert!(matches!(
resolve.command,
Commands::Incidents {
action: IncidentsAction::Resolve { sha: Some(_), .. }
}
));
let perf = Cli::try_parse_from(["slabs", "incidents", "perf", "--json"]).unwrap();
assert!(matches!(
perf.command,
Commands::Incidents {
action: IncidentsAction::Perf { json: true, .. }
}
));
let claim = Cli::try_parse_from([
"slabs",
"incidents",
"claim",
"inc_01ABC",
"--assignee",
"agent-1",
])
.unwrap();
assert!(matches!(
claim.command,
Commands::Incidents {
action: IncidentsAction::Claim { .. }
}
));
let link = Cli::try_parse_from([
"slabs",
"incidents",
"link",
"inc_01ABC",
"--key",
"LIN-42",
"--issue-url",
"https://linear.app/acme/issue/LIN-42",
])
.unwrap();
assert!(matches!(
link.command,
Commands::Incidents {
action: IncidentsAction::Link { .. }
}
));
let ignore = Cli::try_parse_from(["slabs", "incidents", "ignore", "inc_01ABC"]).unwrap();
assert!(matches!(
ignore.command,
Commands::Incidents {
action: IncidentsAction::Ignore { .. }
}
));
let mcp = Cli::try_parse_from(["slabs", "mcp", "--url", "http://127.0.0.1:3000"]).unwrap();
assert!(matches!(mcp.command, Commands::Mcp { .. }));
}
#[tokio::test]
async fn handles_mcp_initialize_and_tools_list() {
let client = build_http_client().unwrap();
let init_resp = handle_mcp_request(
&client,
"http://127.0.0.1:3000",
None,
&json!({"jsonrpc": "2.0", "id": 1, "method": "initialize"}),
)
.await
.unwrap();
assert_eq!(init_resp["result"]["serverInfo"]["name"], "slabs");
let list_resp = handle_mcp_request(
&client,
"http://127.0.0.1:3000",
None,
&json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
)
.await
.unwrap();
let tools = list_resp["result"]["tools"].as_array().unwrap();
assert_eq!(tools.len(), 5);
let unknown = handle_mcp_request(
&client,
"http://127.0.0.1:3000",
None,
&json!({"jsonrpc": "2.0", "id": 3, "method": "unknown/method"}),
)
.await
.unwrap();
assert_eq!(unknown["error"]["code"], -32601);
}
}