autumn-cli 0.10.0

CLI tool for the Autumn web framework
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
//! `autumn console` scaffolds and runs a pre-wired data playground (issue #1039).
//!
//! These tests exercise the CLI end-to-end against a project produced by
//! `autumn new`, covering the issue's acceptance criteria:
//!
//! * the subcommand exists and appears in `--help`;
//! * the first invocation scaffolds `src/bin/playground.rs` pre-wired with the
//!   shared config + database-URL resolution and a constructed pool;
//! * re-running never overwrites a user-edited playground, and `--force` does;
//! * the generated target compiles (the `#[ignore]`d `cargo check` test);
//! * a missing project exits non-zero with an actionable error.

use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

const fn autumn_bin() -> &'static str {
    env!("CARGO_BIN_EXE_autumn")
}

fn run_autumn(dir: &Path, args: &[&str]) -> std::process::Output {
    Command::new(autumn_bin())
        .args(args)
        .current_dir(dir)
        .output()
        .expect("failed to run autumn")
}

fn run_autumn_ok(dir: &Path, args: &[&str]) -> std::process::Output {
    let output = run_autumn(dir, args);
    assert!(
        output.status.success(),
        "autumn {args:?} failed (exit={:?})\nstdout: {}\nstderr: {}",
        output.status.code(),
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr),
    );
    output
}

/// `autumn new <name>`, returning the tempdir guard and the project directory.
fn new_project(name: &str) -> (tempfile::TempDir, PathBuf) {
    let tmp = tempfile::tempdir().expect("tempdir");
    run_autumn_ok(tmp.path(), &["new", name]);
    let project = tmp.path().join(name);
    assert!(project.join("Cargo.toml").is_file());
    (tmp, project)
}

fn playground_path(project: &Path) -> PathBuf {
    project.join("src/bin/playground.rs")
}

// ── AC1: the subcommand exists and is discoverable ─────────────────────────

#[test]
fn console_appears_in_top_level_help() {
    let tmp = tempfile::tempdir().unwrap();
    let out = run_autumn_ok(tmp.path(), &["--help"]);
    let help = String::from_utf8_lossy(&out.stdout);
    assert!(
        help.contains("console"),
        "`autumn --help` must list the console subcommand:\n{help}"
    );
}

#[test]
fn console_has_its_own_help_describing_the_playground() {
    let tmp = tempfile::tempdir().unwrap();
    let out = run_autumn_ok(tmp.path(), &["console", "--help"]);
    let help = String::from_utf8_lossy(&out.stdout);
    assert!(
        help.contains("playground"),
        "`autumn console --help` must describe the playground:\n{help}"
    );
    assert!(
        help.contains("--force"),
        "`autumn console --help` must document --force:\n{help}"
    );
}

// ── AC2: first invocation scaffolds a pre-wired playground ─────────────────

#[test]
fn console_scaffolds_a_prewired_playground() {
    let (_tmp, project) = new_project("console-scaffold-app");
    assert!(!playground_path(&project).exists());

    let out = run_autumn_ok(&project, &["console", "--scaffold-only"]);
    let stderr = String::from_utf8_lossy(&out.stderr);

    let src = fs::read_to_string(playground_path(&project)).expect("playground must be scaffolded");
    assert!(
        src.contains("your code here"),
        "playground must carry a clearly-marked editable region:\n{src}"
    );
    assert!(
        src.contains("SeedContext::build()"),
        "playground must reuse the shared config + DB-URL resolution:\n{src}"
    );
    assert!(
        src.contains("ctx.conn()"),
        "playground must check out a real pooled connection:\n{src}"
    );
    assert!(
        src.contains("console-scaffold-app"),
        "playground must name the project it belongs to:\n{src}"
    );
    assert!(
        stderr.contains("src/bin/playground.rs"),
        "the CLI must report the file it created:\n{stderr}"
    );
}

#[test]
fn console_wires_the_manifest_for_the_playground_target() {
    let (_tmp, project) = new_project("console-manifest-app");
    let before = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    run_autumn_ok(&project, &["console", "--scaffold-only"]);

    let cargo = fs::read_to_string(project.join("Cargo.toml")).unwrap();
    assert!(
        cargo.contains("name = \"playground\"") && cargo.contains("src/bin/playground.rs"),
        "Cargo.toml must register the playground bin target:\n{cargo}"
    );
    assert!(
        cargo.contains("required-features = [\"playground\"]"),
        "the bin must be feature-gated so a bare `cargo build` — which is what \
         `autumn dev` runs — never compiles it:\n{cargo}"
    );
    assert!(
        cargo.contains("playground = [\"autumn-web/seed\"]"),
        "the gate feature must turn on the autumn-web feature the playground \
         bootstraps through:\n{cargo}"
    );
    assert!(
        !cargo.contains("default-run"),
        "the feature gate keeps `cargo run` unambiguous, so default-run — which \
         bricks every cargo command when it names a target that does not exist \
         — must not be written:\n{cargo}"
    );

    // The `autumn-web` dependency line must be byte-identical: we never
    // rewrite a line whose shape and decoration we do not control.
    let dep_line = |src: &str| {
        src.lines()
            .find(|l| l.trim_start().starts_with("autumn-web ="))
            .unwrap_or_default()
            .to_owned()
    };
    assert_eq!(
        dep_line(&cargo),
        dep_line(&before),
        "the autumn-web dependency must not be touched"
    );
}

/// The whole point of the `required-features` gate: scaffolding a playground
/// must not change what a bare `cargo build` compiles. This is the regression
/// test for "`autumn console` broke `autumn dev`".
#[test]
fn console_keeps_the_playground_out_of_the_default_build_set() {
    let (_tmp, project) = new_project("console-buildset-app");
    run_autumn_ok(&project, &["console", "--scaffold-only"]);

    let out = Command::new("cargo")
        .args(["metadata", "--no-deps", "--format-version", "1"])
        .current_dir(&project)
        .output()
        .expect("cargo metadata");
    assert!(
        out.status.success(),
        "the wired manifest must still parse:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let meta = String::from_utf8_lossy(&out.stdout);
    assert!(
        meta.contains("\"required-features\":[\"playground\"]")
            || meta.contains("\"required-features\": [\"playground\"]"),
        "cargo must see the playground target as feature-gated:\n{meta}"
    );
}

/// A project that already declares `[[bin]] name = "playground"` *without* a
/// `path` (valid — Cargo infers `src/bin/playground.rs`) must survive
/// `autumn console`. Appending a second same-named target makes cargo reject
/// the manifest at parse time, which breaks every cargo command in the
/// project, not merely the playground.
#[test]
fn console_does_not_duplicate_a_path_less_playground_bin() {
    let (_tmp, project) = new_project("console-pathless-app");

    let manifest_path = project.join("Cargo.toml");
    let manifest = fs::read_to_string(&manifest_path).unwrap();
    fs::write(
        &manifest_path,
        format!(
            "{manifest}\n[[bin]]\nname = \"playground\"\nrequired-features = [\"playground\"]\n"
        ),
    )
    .unwrap();
    fs::create_dir_all(project.join("src/bin")).unwrap();
    fs::write(playground_path(&project), "fn main() {}\n").unwrap();

    let cargo_metadata_ok = |stage: &str| {
        let out = Command::new("cargo")
            .args(["metadata", "--no-deps", "--format-version", "1"])
            .current_dir(&project)
            .output()
            .expect("cargo metadata");
        assert!(
            out.status.success(),
            "manifest must parse {stage} `autumn console`:\n{}",
            String::from_utf8_lossy(&out.stderr)
        );
    };

    cargo_metadata_ok("before");
    run_autumn_ok(&project, &["console", "--scaffold-only"]);
    cargo_metadata_ok("after");

    let wired = fs::read_to_string(&manifest_path).unwrap();
    assert_eq!(
        wired.matches("name = \"playground\"").count(),
        1,
        "the pre-existing target must be recognised, not duplicated:\n{wired}"
    );
}

/// The isolation guarantee has to hold for configurations we did not create.
/// Each of these would put the seed-dependent playground into the default
/// build set, so `autumn console` refuses and leaves the project untouched
/// rather than scaffolding a project-wide build failure.
/// A manifest mutation that breaks isolation, plus the phrase the resulting
/// error must contain.
type IsolationGuardCase = (&'static str, fn(&str) -> String, &'static str);

#[test]
fn console_refuses_configurations_it_cannot_isolate() {
    let cases: &[IsolationGuardCase] = &[
        // An ungated pre-existing target would carry the template into every build.
        (
            "ungated-bin",
            |m| format!("{m}\n[[bin]]\nname = \"playground\"\npath = \"src/bin/playground.rs\"\n"),
            "required-features",
        ),
        // A default-enabled gate is no gate at all.
        (
            "default-feature",
            |m| {
                m.replace(
                    "default = [\"flash\"]",
                    "default = [\"flash\", \"playground\"]",
                )
            },
            "default",
        ),
        // Edition 2015 auto-discovers the file as an ungated binary.
        (
            "edition-2015",
            |m| m.replace("edition = \"2024\"", "edition = \"2015\""),
            "edition 2015",
        ),
    ];

    for (name, mutate, expected) in cases {
        let (_tmp, project) = new_project(&format!("console-guard-{name}-app"));
        let manifest_path = project.join("Cargo.toml");
        let original = mutate(&fs::read_to_string(&manifest_path).unwrap());
        fs::write(&manifest_path, &original).unwrap();

        let out = run_autumn(&project, &["console", "--scaffold-only"]);
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            !out.status.success(),
            "[{name}] must refuse rather than break the default build:\n{stderr}"
        );
        assert!(
            stderr.contains(expected),
            "[{name}] the error must name the problem (`{expected}`):\n{stderr}"
        );
        assert_eq!(
            fs::read_to_string(&manifest_path).unwrap(),
            original,
            "[{name}] a refused project must keep its manifest byte-identical"
        );
        assert!(
            !playground_path(&project).exists(),
            "[{name}] nothing may be scaffolded when isolation cannot be guaranteed"
        );
    }
}

// ── AC3: model/repository APIs are reachable from the playground ───────────

#[test]
fn console_wires_generated_models_into_the_playground_crate() {
    let (_tmp, project) = new_project("console-models-app");
    run_autumn_ok(
        &project,
        &["generate", "model", "Post", "title:String", "body:Text"],
    );
    run_autumn_ok(&project, &["console", "--scaffold-only"]);

    let src = fs::read_to_string(playground_path(&project)).unwrap();
    assert!(
        src.contains("mod models;"),
        "a bin target cannot see src/models/ without an explicit module \
         declaration -- the playground must supply one:\n{src}"
    );
    assert!(
        src.contains("mod schema;"),
        "models reference `crate::schema`, so schema must be declared too:\n{src}"
    );
}

// ── AC5: idempotent; --force regenerates ───────────────────────────────────

#[test]
fn console_never_overwrites_an_edited_playground() {
    let (_tmp, project) = new_project("console-idempotent-app");
    run_autumn_ok(&project, &["console", "--scaffold-only"]);

    let edited = "// MY PRECIOUS QUERY\nfn main() {}\n";
    fs::write(playground_path(&project), edited).unwrap();

    let out = run_autumn_ok(&project, &["console", "--scaffold-only"]);
    assert_eq!(
        fs::read_to_string(playground_path(&project)).unwrap(),
        edited,
        "re-running `autumn console` must never clobber a user-edited playground"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("--force"),
        "the CLI must point at --force when it keeps an existing file:\n{stderr}"
    );
}

#[test]
fn console_force_regenerates_from_the_template() {
    let (_tmp, project) = new_project("console-force-app");
    run_autumn_ok(&project, &["console", "--scaffold-only"]);
    fs::write(playground_path(&project), "// stale\n").unwrap();

    run_autumn_ok(&project, &["console", "--scaffold-only", "--force"]);
    let src = fs::read_to_string(playground_path(&project)).unwrap();
    assert!(
        src.contains("your code here") && !src.contains("// stale"),
        "--force must regenerate the playground from the template:\n{src}"
    );
}

#[test]
fn console_manifest_wiring_is_idempotent() {
    let (_tmp, project) = new_project("console-manifest-idem-app");
    run_autumn_ok(&project, &["console", "--scaffold-only"]);
    let first = fs::read_to_string(project.join("Cargo.toml")).unwrap();

    run_autumn_ok(&project, &["console", "--scaffold-only"]);
    let second = fs::read_to_string(project.join("Cargo.toml")).unwrap();

    assert_eq!(
        first, second,
        "a second `autumn console` must leave Cargo.toml byte-identical"
    );
    assert_eq!(
        second.matches("name = \"playground\"").count(),
        1,
        "the bin entry must not be duplicated:\n{second}"
    );
    assert_eq!(
        second.matches("playground = [").count(),
        1,
        "the gate feature must not be duplicated:\n{second}"
    );
}

// ── AC4: failures are loud and non-zero ────────────────────────────────────

#[test]
fn console_fails_outside_a_cargo_project() {
    let tmp = tempfile::tempdir().unwrap();
    let out = run_autumn(tmp.path(), &["console", "--scaffold-only"]);
    assert!(
        !out.status.success(),
        "`autumn console` outside a project must exit non-zero"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("Cargo.toml"),
        "the error must name what is missing:\n{stderr}"
    );
    assert!(
        !playground_path(tmp.path()).exists(),
        "no file may be written when the project check fails"
    );
}

#[test]
fn console_fails_when_the_project_has_no_autumn_web_dependency() {
    let tmp = tempfile::tempdir().unwrap();
    fs::write(
        tmp.path().join("Cargo.toml"),
        "[package]\nname = \"plain\"\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[dependencies]\nserde = \"1\"\n",
    )
    .unwrap();

    let before = fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap();

    let out = run_autumn(tmp.path(), &["console", "--scaffold-only"]);
    assert!(
        !out.status.success(),
        "a non-Autumn Cargo project must exit non-zero"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("autumn-web"),
        "the error must name the missing dependency:\n{stderr}"
    );
    assert!(
        !playground_path(tmp.path()).exists(),
        "validation must run before any write"
    );
    assert_eq!(
        fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap(),
        before,
        "a rejected project's manifest must be left byte-identical"
    );
}

#[test]
fn console_fails_on_an_unparsable_manifest_without_writing_anything() {
    let tmp = tempfile::tempdir().unwrap();
    let broken = "this is not = = toml\n";
    fs::write(tmp.path().join("Cargo.toml"), broken).unwrap();

    let out = run_autumn(tmp.path(), &["console", "--scaffold-only"]);
    assert!(
        !out.status.success(),
        "an unparsable manifest must exit non-zero"
    );
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("Cargo.toml"),
        "the error must name the file it could not parse:\n{stderr}"
    );
    assert!(
        !playground_path(tmp.path()).exists(),
        "validation must run before any write"
    );
    assert_eq!(
        fs::read_to_string(tmp.path().join("Cargo.toml")).unwrap(),
        broken,
        "a manifest we cannot parse must never be rewritten"
    );
}

#[test]
fn console_scaffolding_does_not_require_a_database() {
    // Scaffolding is a pure filesystem operation: it must succeed with no
    // database reachable at all. The run path (which does need one) is proved
    // separately by `console_run_exits_non_zero_when_the_database_is_unreachable`.
    let (_tmp, project) = new_project("console-db-split-app");
    let out = run_autumn(&project, &["console", "--scaffold-only"]);
    assert!(
        out.status.success(),
        "scaffolding must not require a database (exit={:?})\nstderr: {}",
        out.status.code(),
        String::from_utf8_lossy(&out.stderr),
    );
}

/// Run `autumn console` (the real build-and-run path) in `project`, with the
/// higher-precedence database env vars scrubbed so an ambient
/// `AUTUMN_DATABASE__*` on the developer's box or the CI runner cannot decide
/// the outcome, and `extra` env applied on top.
fn run_console_for_real(project: &Path, extra: &[(&str, &str)]) -> (String, Option<i32>) {
    let out = Command::new(autumn_bin())
        .args(["console"])
        .current_dir(project)
        .env_remove("AUTUMN_DATABASE__PRIMARY_URL")
        .env_remove("AUTUMN_DATABASE__URL")
        .env_remove("DATABASE_URL")
        .env_remove("AUTUMN_ENV")
        .env_remove("AUTUMN_PROFILE")
        .envs(extra.iter().copied())
        .output()
        .expect("failed to run autumn console");
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    (combined, out.status.code())
}

/// AC4: "a config or DB-connection failure exits non-zero and prints the
/// underlying error (no silent success)".
///
/// Builds and runs the real playground three ways against the same (already
/// compiled) project:
///
/// * no database configured at all -> the *config* stage fails;
/// * a database configured but unreachable -> the *connection* stage fails;
/// * a `[profile.<name>.database]` section -> `--profile` is forwarded and the
///   profile-aware `autumn.toml` lookup is the one that resolves the URL.
///
/// Each asserts a non-zero exit, the underlying error text, and — the real
/// "no silent success" oracle — that the playground's completion sentinel is
/// absent.
///
/// Ignored by default (it compiles a fresh project); run with:
/// `cargo test -p autumn-cli --test cli_tests -- --ignored console_run_exits`
#[test]
#[ignore = "slow: builds and runs a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn console_run_exits_non_zero_when_the_database_is_unreachable() {
    let (_tmp, project) = new_project("console-dbfail-app");
    run_autumn_ok(&project, &["console", "--scaffold-only"]);
    patch_autumn_web_to_workspace(&project);

    // The scaffolded `autumn.toml` leaves the database URL unset, so with the
    // env scrubbed there is nothing to resolve: the *config* stage must fail.
    let (out, code) = run_console_for_real(&project, &[]);
    assert_eq!(
        code,
        Some(1),
        "an unresolvable database URL must exit 1:\n{out}"
    );
    assert!(
        out.contains("could not resolve configuration or build the database pool"),
        "the config-stage failure must be named:\n{out}"
    );
    assert!(
        out.contains("no primary database URL configured"),
        "the underlying error must be printed verbatim, not swallowed:\n{out}"
    );
    assert!(
        !out.contains("autumn console: done."),
        "a failed run must never print the completion sentinel:\n{out}"
    );

    // Port 1 is reserved and never listening: config resolves, the *connection*
    // stage fails. Proves the two stages are distinct and both are fatal.
    let (out, code) = run_console_for_real(
        &project,
        &[("DATABASE_URL", "postgres://nobody@127.0.0.1:1/nodb")],
    );
    assert_eq!(code, Some(1), "an unreachable database must exit 1:\n{out}");
    assert!(
        out.contains("could not connect to the database"),
        "the connection-stage failure must be named:\n{out}"
    );
    assert!(
        !out.contains("could not resolve configuration"),
        "a reachable config must not report a config failure:\n{out}"
    );
    assert!(
        !out.contains("autumn console: done."),
        "a failed run must never print the completion sentinel:\n{out}"
    );

    // AC2: the resolution is profile-aware and reads the project's
    // `autumn.toml` from the package root. Adding only a
    // `[profile.demo.database]` section must move the failure from the config
    // stage to the connection stage — but only under `--profile demo`.
    let autumn_toml = project.join("autumn.toml");
    let mut config = fs::read_to_string(&autumn_toml).unwrap();
    config.push_str("\n[profile.demo.database]\nurl = \"postgres://nobody@127.0.0.1:1/demo\"\n");
    fs::write(&autumn_toml, config).unwrap();

    let out = Command::new(autumn_bin())
        .args(["console", "--profile", "demo"])
        .current_dir(&project)
        .env_remove("AUTUMN_DATABASE__PRIMARY_URL")
        .env_remove("AUTUMN_DATABASE__URL")
        .env_remove("DATABASE_URL")
        .output()
        .expect("failed to run autumn console");
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(out.status.code(), Some(1), "still unreachable:\n{combined}");
    assert!(
        combined.contains("autumn console: profile `demo`"),
        "--profile must reach the playground via AUTUMN_ENV:\n{combined}"
    );
    assert!(
        combined.contains("could not connect to the database"),
        "the profile-scoped autumn.toml URL must have resolved, leaving only \
         the connection to fail:\n{combined}"
    );
}

/// AC4: a user's broken edit surfaces cargo's diagnostics and a non-zero exit,
/// rather than a confusing success. Reuses the already-built target directory
/// of a scaffolded project so this costs an incremental rebuild, not a full one.
///
/// Ignored by default; run with:
/// `cargo test -p autumn-cli --test cli_tests -- --ignored console_run_surfaces`
#[test]
#[ignore = "slow: builds a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn console_run_surfaces_a_compile_error_in_the_playground() {
    let (_tmp, project) = new_project("console-buildfail-app");
    run_autumn_ok(&project, &["console", "--scaffold-only"]);
    patch_autumn_web_to_workspace(&project);

    let src = fs::read_to_string(playground_path(&project)).unwrap();
    fs::write(
        playground_path(&project),
        src.replace("// ── your code here", "this is not valid rust;"),
    )
    .unwrap();

    let (out, code) = run_console_for_real(
        &project,
        &[("DATABASE_URL", "postgres://nobody@127.0.0.1:1/nodb")],
    );
    assert_ne!(
        code,
        Some(0),
        "a playground that fails to build must not report success:\n{out}"
    );
    assert!(
        out.contains("error"),
        "cargo's diagnostics must reach the user:\n{out}"
    );
    assert!(
        !out.contains("autumn console: done."),
        "a build failure must never print the completion sentinel:\n{out}"
    );
}

// ── AC3/AC7: the generated target actually compiles ────────────────────────

/// Repoint `autumn-web` at the workspace copy so builds in these tests use this
/// tree rather than a published crate.
fn patch_autumn_web_to_workspace(project: &Path) {
    use std::fmt::Write as _;

    let cargo_toml_path = project.join("Cargo.toml");
    let mut content = fs::read_to_string(&cargo_toml_path).unwrap();
    let workspace_root = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .expect("workspace root");
    let autumn_web = workspace_root.join("autumn");
    let _ = write!(
        content,
        "\n[patch.crates-io]\nautumn-web = {{ path = \"{}\" }}\n",
        autumn_web.display().to_string().replace('\\', "/")
    );
    fs::write(&cargo_toml_path, content).unwrap();
}

/// AC3/AC7: the scaffolded target compiles, and a real repository round-trip
/// (`find_all()`) written into the "your code here" region compiles with it —
/// no further wiring by hand.
///
/// Ignored by default (it builds a fresh project); run with:
/// `cargo test -p autumn-cli --test cli_tests -- --ignored console_playground`
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn console_playground_target_compiles_with_a_repository_round_trip() {
    let (_tmp, project) = new_project("console-check-app");
    run_autumn_ok(
        &project,
        &["generate", "scaffold", "Post", "title:String", "body:Text"],
    );
    run_autumn_ok(&project, &["console", "--scaffold-only"]);
    patch_autumn_web_to_workspace(&project);

    // Drop a real repository round-trip into the editable region.
    let src = fs::read_to_string(playground_path(&project)).unwrap();
    let marker = "// ── your code here";
    assert!(
        src.contains(marker),
        "expected the editable-region marker in:\n{src}"
    );
    // Touch every module the playground declares — models, repositories, and
    // policies — so a wrong `#[path]` on any of them fails the build rather
    // than passing unnoticed.
    let round_trip = "\
use repositories::post::{PgPostRepository, PostRepository};\n    \
let _policy = policies::post::PostPolicy::default();\n    \
let repo = PgPostRepository::with_pool_untracked(ctx.pool().clone());\n    \
let _rows: Vec<models::post::Post> = repo.find_all().await.unwrap();\n    \
let _by_id: Option<models::post::Post> = repo.find_by_id(1).await.unwrap();\n    \
// ── your code here";
    fs::write(playground_path(&project), src.replace(marker, round_trip)).unwrap();

    cargo_check_playground(&project);
}

/// AC2/AC7: the *first-invocation* shape — a bare `autumn new` project with no
/// models, so `{{app_modules}}` renders empty — must compile untouched. This is
/// the exact file a user sees on their very first `autumn console`, and it is
/// the one shape the model round-trip test never exercises.
///
/// Ignored by default; run with:
/// `cargo test -p autumn-cli --test cli_tests -- --ignored console_bare`
#[test]
#[ignore = "slow: cargo-checks a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn console_bare_playground_target_compiles_untouched() {
    let (_tmp, project) = new_project("console-bare-app");
    run_autumn_ok(&project, &["console", "--scaffold-only"]);

    let src = fs::read_to_string(playground_path(&project)).unwrap();
    // Match a real declaration, not the header prose that explains the
    // mechanism — `#[path = "../…"]` only ever appears as emitted code.
    assert!(
        !src.contains("#[path = \"../"),
        "a project with no data modules must render no #[path] declarations:\n{src}"
    );

    patch_autumn_web_to_workspace(&project);
    cargo_check_playground(&project);
}

fn cargo_check_playground(project: &Path) {
    let check = Command::new("cargo")
        .args(["check", "--bin", "playground", "--features", "playground"])
        .current_dir(project)
        .output()
        .unwrap();
    assert!(
        check.status.success(),
        "cargo check on the scaffolded playground failed:\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&check.stdout),
        String::from_utf8_lossy(&check.stderr),
    );
    // The playground ships with `#![allow(...)]` for the lints an
    // intentionally-empty editable region would otherwise trip; a warning here
    // means the scaffold is nagging the user on a file they have not edited.
    let stderr = String::from_utf8_lossy(&check.stderr);
    assert!(
        !stderr.contains("warning: unused")
            && !stderr.contains("warning: variable does not need to be mutable"),
        "the scaffolded playground must compile without warnings:\n{stderr}"
    );
}

// ── #2148: `--repl` opens a Rhai prompt on the same playground ─────────────

#[test]
fn console_help_documents_repl() {
    let tmp = tempfile::tempdir().unwrap();
    let out = run_autumn_ok(tmp.path(), &["console", "--help"]);
    let help = String::from_utf8_lossy(&out.stdout);
    assert!(help.contains("--repl"), "{help}");
    assert!(help.contains("Rhai"), "{help}");
}

/// `--repl` adds a feature on the command line only: the manifest it writes is
/// byte-identical to the one plain `autumn console` writes.
#[test]
fn console_repl_does_not_change_the_manifest_wiring() {
    let (_plain_tmp, plain) = new_project("console-repl-app");
    let (_repl_tmp, repl) = new_project("console-repl-app");
    run_autumn_ok(&plain, &["console", "--scaffold-only"]);
    run_autumn_ok(&repl, &["console", "--repl", "--scaffold-only"]);
    assert_eq!(
        fs::read_to_string(plain.join("Cargo.toml")).unwrap(),
        fs::read_to_string(repl.join("Cargo.toml")).unwrap(),
    );
    assert_eq!(
        fs::read_to_string(playground_path(&plain)).unwrap(),
        fs::read_to_string(playground_path(&repl)).unwrap(),
        "one template serves both modes"
    );
}

/// The REPL builds against a generated app and answers piped lines. The
/// database is unreachable, so a repository read must be a script error and
/// the session must still end cleanly. The edit-and-run body never runs.
///
/// Ignored by default; run with:
/// `cargo test -p autumn-cli --test cli_tests -- --ignored console_repl_runs`
#[test]
#[ignore = "slow: builds and runs a fresh project — run with `cargo test -p autumn-cli -- --ignored`"]
fn console_repl_runs_and_reports_errors_as_script_errors() {
    use std::io::Write as _;
    use std::process::Stdio;

    let (_tmp, project) = new_project("console-repl-run-app");
    run_autumn_ok(
        &project,
        &["generate", "scaffold", "Post", "title:String", "body:Text"],
    );
    run_autumn_ok(&project, &["console", "--scaffold-only"]);
    patch_autumn_web_to_workspace(&project);

    // REPL mode must not depend on the playground source: the body must not
    // run, whatever it holds.
    let src = fs::read_to_string(playground_path(&project)).unwrap();
    let marker = "// ── your code here";
    assert!(src.contains(marker), "{src}");
    fs::write(
        playground_path(&project),
        src.replace(
            marker,
            "eprintln!(\"PLAYGROUND BODY RAN\");\n    // ── your code here",
        ),
    )
    .unwrap();

    let mut child = Command::new(autumn_bin())
        .args(["console", "--repl"])
        .current_dir(&project)
        .env_remove("AUTUMN_DATABASE__PRIMARY_URL")
        .env_remove("AUTUMN_DATABASE__URL")
        .env_remove("AUTUMN_ENV")
        .env_remove("AUTUMN_PROFILE")
        .env("DATABASE_URL", "postgres://nobody@127.0.0.1:1/nodb")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("failed to run autumn console --repl");
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"40 + 2\nPostRepository::count()\nrepositories()\nexit\n")
        .unwrap();
    let out = child.wait_with_output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert_eq!(
        out.status.code(),
        Some(0),
        "stdout:\n{stdout}\nstderr:\n{stderr}"
    );
    assert!(
        stdout.contains("42"),
        "an expression is evaluated:\n{stdout}"
    );
    assert!(
        stdout.contains("\"PostRepository\""),
        "the generated repository is registered:\n{stdout}"
    );
    assert!(
        stderr.contains("error: "),
        "a failed read is a script error:\n{stderr}"
    );
    assert!(!stderr.contains("panicked"), "never a panic:\n{stderr}");
    assert!(
        !stderr.contains("PLAYGROUND BODY RAN") && !stderr.contains("autumn console: done."),
        "the edit-and-run body does not run in REPL mode:\n{stderr}"
    );

    // A playground that never reaches `SeedContext::build()` cannot open the
    // prompt. Its run must fail, not end as a finished REPL session.
    fs::write(
        playground_path(&project),
        "#[autumn_web::main]\nasync fn main() {\n    eprintln!(\"NO BUILD CALL\");\n}\n",
    )
    .unwrap();
    let out = Command::new(autumn_bin())
        .args(["console", "--repl"])
        .current_dir(&project)
        .env("DATABASE_URL", "postgres://nobody@127.0.0.1:1/nodb")
        .stdin(Stdio::null())
        .output()
        .expect("failed to run autumn console --repl");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(stderr.contains("NO BUILD CALL"), "{stderr}");
    assert_eq!(out.status.code(), Some(1), "{stderr}");
    assert!(
        stderr.contains("exited without opening the REPL"),
        "the CLI names the missing prompt:\n{stderr}"
    );
}

// ── AC2/AC6: no drift from `autumn seed`, and the docs exist ───────────────

/// AC2: the console's bootstrap must stay the same one `autumn seed` uses.
/// A future edit that gives the playground its own config/pool wiring — the
/// exact drift the issue calls out — fails here.
#[test]
fn console_and_seed_share_one_bootstrap() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"));
    let seed_tmpl = fs::read_to_string(root.join("src/templates/seed.rs.tmpl")).unwrap();
    let playground_tmpl =
        fs::read_to_string(root.join("src/templates/playground.rs.tmpl")).unwrap();

    for (name, tmpl) in [("seed", &seed_tmpl), ("playground", &playground_tmpl)] {
        assert!(
            tmpl.contains("use autumn_web::seed::SeedContext;")
                && tmpl.contains("SeedContext::build()"),
            "the {name} template must bootstrap through the shared SeedContext, \
             so the console and the app never resolve different databases:\n{tmpl}"
        );
    }
}

/// Read a repository document with line endings normalised to LF.
///
/// Docs are checked out with CRLF on Windows (git `autocrlf`), so a multi-line
/// `\n` needle would never match there. `repo_hygiene.rs` normalises the same
/// way for the same reason.
fn read_doc_lf(path: &Path) -> String {
    fs::read_to_string(path)
        .unwrap_or_else(|e| panic!("failed to read {}: {e}", path.display()))
        .replace("\r\n", "\n")
}

/// AC6: README and the CLI docs carry a one-line usage example.
#[test]
fn console_usage_is_documented() {
    let root = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .expect("workspace root");

    let readme = read_doc_lf(&root.join("README.md"));
    assert!(
        readme.contains("autumn console"),
        "README must show `autumn console`"
    );
    assert!(
        readme.contains("docs/guide/console.md"),
        "README must link the data-playground guide"
    );

    let guide = read_doc_lf(&root.join("docs/guide/console.md"));
    assert!(
        guide.contains("```bash\nautumn console\n```"),
        "the guide must show the one-line usage example:\n{guide}"
    );
    for flag in ["--force", "--profile", "--scaffold-only"] {
        assert!(
            guide.contains(flag),
            "the guide must document `{flag}`:\n{guide}"
        );
    }
}