slabs-cli 0.2.0

CLI for Slabs: scaffold transaction scripts & jobs, run migrations, dump schema.sql, inspect routes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
//! Command-line interface (`slabs`) for creating, formatting, migrating, and running Slabs apps.
//!
//! Pass `--app-dir <PATH>` before any subcommand to target an app outside the current directory.
//!
//! # Subcommands
//!
//! - `slabs new app <name> [--dir <path>]`: create a starter Slabs application with Clippy lints,
//!   CI workflow, `build.rs` discovery, and an initial page slab.
//! - `slabs new slab <feature> <name> [--method <verb>] [--path <route>]`: create
//!   `slabs/<feature>/<name>.rs` without editing any shared file.
//! - `slabs new job <name>`: create `jobs/<name>.rs` without editing any shared file.
//! - `slabs fmt [--check]`: format the crate and every `.rs` file in `slabs/` and `jobs/`.
//! - `slabs check [--workspace] [--no-docs]`: run the full CI suite (formatting, Clippy with
//!   `-D warnings`, Rustdoc with `-D warnings`, doctests, and `cargo nextest` or `cargo test`).
//! - `slabs db migrate --database-url <url>`: apply SQL migrations in `<app_dir>/migrations` for
//!   `SQLite` or `PostgreSQL`.
//! - `slabs db dump-schema --database-url <url>`: write the live schema to `<app_dir>/schema.sql`.
//! - `slabs db seed --database-url <url> [--file <path>]`: execute an idempotent SQL seed file
//!   (defaults to `<app_dir>/seeds.sql`) against `SQLite` or `PostgreSQL`.
//! - `slabs db prepare [--database-url <url>] [--package <name>]`: generate offline `.sqlx/` query
//!   metadata using an ephemeral migrated `SQLite` database when `DATABASE_URL` is omitted.
//! - `slabs list`: print all auto-discovered slabs and background jobs in the app directory.
//! - `slabs css [--watch]`: compile `assets/input.css` into `assets/styles/app.css` via the
//!   standalone `tailwindcss` binary.
//! - `slabs dev [--package <name>] [--bind <addr>]`: compile Tailwind CSS, start `tailwindcss
//!   --watch`, and run `cargo watch` (or `cargo run` when `cargo-watch` is absent).
//!
//! # Why `slabs fmt` exists
//!
//! `slabs_build::discover()` generates `OUT_DIR/discovered_slabs.rs` at build time with
//! `#[path = "..."]` module entries for `slabs/` and `jobs/`.
//! Because `cargo fmt` only walks modules reachable from `src/` without inspecting `OUT_DIR`, it
//! skips every file under `slabs/` and `jobs/`.
//! `slabs fmt` runs `cargo fmt` on the crate and then runs `rustfmt --edition 2021` on all
//! discovered `.rs` files in `slabs/` and `jobs/`.

use clap::{Parser, Subcommand};
use slabs_db::{Db, DbEngine, PgDb};
use std::fs;
use std::path::{Path, PathBuf};
use tokio::process::Command;

#[derive(Parser)]
#[command(
    name = "slabs",
    about = "Batteries-included, agent-first Transaction Script web framework CLI"
)]
struct Cli {
    /// Path to the Slabs application directory (defaults to current directory)
    #[arg(long, global = true, default_value = ".")]
    app_dir: PathBuf,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Create a new Slabs app, Transaction Script, or Background Job
    New {
        #[command(subcommand)]
        kind: NewKind,
    },
    /// Database commands (auto-detects `SQLite` or `PostgreSQL` from `DATABASE_URL`)
    Db {
        #[command(subcommand)]
        action: DbAction,
    },
    /// Format the app crate and auto-discovered `slabs/` and `jobs/` files with `rustfmt`
    Fmt {
        /// Check formatting without modifying files (exits non-zero on diffs)
        #[arg(long)]
        check: bool,
    },
    /// Run the full CI verification suite (fmt, clippy, rustdoc, doctests, and nextest/test)
    Check {
        /// Check every crate in the Cargo workspace (auto-detected if `Cargo.toml` has `[workspace]`)
        #[arg(long)]
        workspace: bool,
        /// Skip `cargo doc` and `cargo test --doc` steps
        #[arg(long)]
        no_docs: bool,
    },
    /// List all discovered Transaction Scripts and Background Jobs in an app directory
    List,
    /// Compile Tailwind CSS v4 (via standalone `tailwindcss` binary) for an app directory
    Css {
        /// Watch for changes instead of one-shot minified build
        #[arg(long)]
        watch: bool,
    },
    /// Start live dev server with Tailwind v4 `--watch` and `cargo watch` (or `cargo run`)
    Dev {
        /// Cargo package name (inferred from `<app_dir>/Cargo.toml` if omitted)
        #[arg(long, short)]
        package: Option<String>,
        /// Bind address override (sets `SLABS_BIND`)
        #[arg(long)]
        bind: Option<String>,
    },
}

#[derive(Subcommand)]
enum NewKind {
    /// Create a starter Slabs application with Clippy defaults and CI workflow
    App {
        /// Package and directory name (for example `my_app`)
        name: String,
        /// Optional target directory (defaults to `./<name>`)
        #[arg(long)]
        dir: Option<PathBuf>,
    },
    /// Create `slabs/<feature>/<name>.rs` without editing shared files
    Slab {
        feature: String,
        name: String,
        #[arg(long, default_value = "post")]
        method: String,
        #[arg(long)]
        path: Option<String>,
    },
    /// Create `jobs/<name>.rs` without editing shared files
    Job { name: String },
}

#[derive(Subcommand)]
enum DbAction {
    /// Run all SQL migrations in `<app_dir>/migrations` (`sqlite://` or `postgres://`)
    Migrate {
        #[arg(long, env = "DATABASE_URL")]
        database_url: String,
    },
    /// Dump the live database schema into `<app_dir>/schema.sql` (`SQLite` or `PostgreSQL`)
    DumpSchema {
        #[arg(long, env = "DATABASE_URL")]
        database_url: String,
    },
    /// Apply an idempotent SQL seed script (defaults to `<app_dir>/seeds.sql`)
    Seed {
        #[arg(long, env = "DATABASE_URL")]
        database_url: String,
        /// Optional path to a SQL seed file (defaults to `<app_dir>/seeds.sql`)
        #[arg(long)]
        file: Option<PathBuf>,
    },
    /// Generate offline `.sqlx/` metadata for compile-time `sqlx::query!` and `sqlx::query_as!` checks
    Prepare {
        /// Optional database URL (defaults to an ephemeral `SQLite` DB migrated from `<app_dir>/migrations`)
        #[arg(long, env = "DATABASE_URL")]
        database_url: Option<String>,
        /// Cargo package name (inferred from `<app_dir>/Cargo.toml` if omitted)
        #[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 } => {
                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,
            } => {
                let method_lower = method.to_lowercase();
                let route_path = path.unwrap_or_else(|| format!("/api/{feature}/{name}"));
                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_lower, &route_path);
                fs::write(&target, template)?;
                println!("Created slab: {}", target.display());
            }
            NewKind::Job { 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) => 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::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?;
        }
    }

    Ok(())
}

fn render_slab_template(feature: &str, name: &str, method_lower: &str, route_path: &str) -> String {
    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?;
    let mut tx = ctx.db.begin().await?;

    // Write self-contained raw SQL here using `sqlx::query` / `sqlx::query_as`.
    tx.commit().await?;

    Ok((StatusCode::OK, Json(Output {{ ok: true }})))
}}
"#
    )
}

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}}")))?;
    let _pool = ctx.db.pool();
    Ok(())
}}
"#
    )
}

fn scaffold_app(name: &str, dir: &Path) -> Result<(), Box<dyn std::error::Error>> {
    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"))?;

    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"
# Switch to `slabs-framework = "0.1"` once published to crates.io.
slabs-framework = {{ git = "https://github.com/sogamoso/slabs.git" }}
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]
# Switch to `slabs-build = "0.1"` once published to crates.io.
slabs-build = {{ git = "https://github.com/sogamoso/slabs.git" }}

[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
}}

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": "#1a1b26",
        "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", (event) => {{
  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.pathname.startsWith("/assets/") || url.pathname.startsWith("/_slabs/vendor/")) {{
    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 (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) => {{
  const data = event.data ? event.data.json() : {{ title: "{name}", body: "New update" }};
  event.waitUntil(
    self.registration.showNotification(data.title || "{name}", {{
      body: data.body || "",
      data: {{ url: data.url || "/" }},
    }})
  );
}});

self.addEventListener("notificationclick", (event) => {{
  event.notification.close();
  const target = (event.notification.data && event.notification.data.url) || "/";
  event.waitUntil(clients.openWindow(target));
}});
"#;

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("addEventListener"));
    }}
}}
"##
    );

    let icon_svg = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" fill="none">
  <polygon points="64,68 110,87 64,106 18,87" fill="#bb9af7"/>
  <polygon points="18,87 64,106 64,119 18,100" fill="#7847bd"/>
  <polygon points="110,87 64,106 64,119 110,100" fill="#9d7cd8"/>
  <polygon points="64,44 110,63 64,82 18,63" fill="#7aa2f7"/>
  <polygon points="18,63 64,82 64,95 18,76" fill="#3d59a1"/>
  <polygon points="110,63 64,82 64,95 110,76" fill="#5a86e8"/>
  <polygon points="64,10 110,33 64,56 18,33" fill="#7dcfff"/>
  <polygon points="18,33 64,56 64,69 18,46" fill="#0db9d7"/>
  <polygon points="110,33 64,56 64,69 110,46" fill="#2ac3de"/>
</svg>
"##;

    let dockerfile = format!(
        r#"FROM rust:1.88-slim AS builder
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends pkg-config libssl-dev curl ca-certificates && rm -rf /var/lib/apt/lists/*
COPY . .
RUN cargo build --release

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 /app/assets /app/assets
RUN mkdir -p /data && chown -R slabs:slabs /app /data
USER slabs
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/_slabs/health || exit 1
CMD ["{name}"]
"#
    );

    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

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 = 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?`).
- Run `slabs fmt --check`, `cargo clippy --all-targets -- -D warnings`, and `cargo nextest run` 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)?;
    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")?;

    Ok(())
}

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_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 { 3 } else { 5 };
    let mut step = 1usize;

    // 1. Formatting (crate/workspace + discovered slabs/ and jobs/)
    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;

    // 2. Clippy
    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 {
        // 3. Rustdoc
        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;

        // 4. Doctests
        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;
    }

    // 5. Test suite (prefer cargo-nextest when available)
    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_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 collect_workspace_discovered_rs_files(
    root: &Path,
) -> Result<Vec<PathBuf>, Box<dyn std::error::Error>> {
    let mut files = collect_discovered_rs_files(root)?;
    for entry in fs::read_dir(root)? {
        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() {
            files.extend(collect_discovered_rs_files(&path)?);
        }
    }
    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) => p,
        None => infer_package_name(app_dir)?,
    };

    // 1. Ensure fresh CSS before booting app
    let _ = run_tailwind(app_dir, false).await;
    let (input, output) = ensure_tailwind_paths(app_dir)?;

    // 2. Spawn Tailwind CSS v4 --watch
    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");
    }

    // 3. Prefer `cargo watch` if installed, otherwise `cargo run`
    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(app_dir: &Path) -> Result<String, Box<dyn std::error::Error>> {
    let cargo_toml = app_dir.join("Cargo.toml");
    let content = fs::read_to_string(&cargo_toml).map_err(|_| {
        format!(
            "could not read {}; pass `--package <name>`",
            cargo_toml.display()
        )
    })?;
    for line in content.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("name") {
            let rest = rest.trim_start();
            if let Some(val) = rest.strip_prefix('=') {
                let name = val.trim().trim_matches('"').trim_matches('\'');
                if !name.is_empty() {
                    return Ok(name.to_string());
                }
            }
        }
    }
    Err("could not infer package name from Cargo.toml; pass `--package <name>`".into())
}

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 feat_name = feat.file_name().unwrap().to_string_lossy();
            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 stem = file.file_stem().unwrap().to_string_lossy();
                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 stem = file.file_stem().unwrap().to_string_lossy();
            println!("  job   {stem}  ({})", file.display());
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn infers_package_name_from_cargo_toml() {
        let tmp = std::env::temp_dir().join(format!(
            "slabs_cli_infer_pkg_test_{}",
            slabs_core::id::new("pkg")
        ));
        fs::create_dir_all(&tmp).unwrap();
        fs::write(
            tmp.join("Cargo.toml"),
            "[package]\nname = \"campfire\"\nversion = \"0.1.0\"\n",
        )
        .unwrap();

        assert_eq!(infer_package_name(&tmp).unwrap(), "campfire");

        let _ = fs::remove_dir_all(&tmp);
    }

    #[test]
    fn scaffolded_app_slab_and_job_pass_rustfmt() {
        let tmp = std::env::temp_dir().join(format!(
            "slabs_cli_scaffold_test_{}",
            slabs_core::id::new("app")
        ));
        scaffold_app("demo_app", &tmp).unwrap();
        fs::write(
            tmp.join("slabs/pages/create_item.rs"),
            render_slab_template("pages", "create_item", "post", "/api/items"),
        )
        .unwrap();
        fs::write(
            tmp.join("jobs/send_digest.rs"),
            render_job_template("send_digest"),
        )
        .unwrap();

        let mut rs_files = vec![
            tmp.join("build.rs"),
            tmp.join("src/lib.rs"),
            tmp.join("src/main.rs"),
        ];
        rs_files.extend(collect_discovered_rs_files(&tmp).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 cargo_toml = fs::read_to_string(tmp.join("Cargo.toml")).unwrap();
        assert!(cargo_toml.contains("unsafe_code = \"forbid\""));
        assert!(cargo_toml.contains("await_holding_lock = \"deny\""));
        assert!(cargo_toml.contains("git = \"https://github.com/sogamoso/slabs.git\""));
        assert!(tmp.join(".github/workflows/ci.yml").exists());
        assert!(tmp.join("slabs/pwa/manifest.rs").exists());
        assert!(tmp.join("slabs/pwa/service_worker.rs").exists());
        assert!(tmp.join("assets/icon.svg").exists());
        assert!(tmp.join("Dockerfile").exists());
        assert!(tmp.join("litestream.yml").exists());
        assert!(tmp.join("seeds.sql").exists());
        let claude_md = fs::read_to_string(tmp.join("CLAUDE.md")).unwrap();
        assert!(claude_md.contains("@AGENTS.md"));

        let _ = fs::remove_dir_all(&tmp);
    }
}