agentty 0.12.5

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
Documentation
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
//! Shared helpers and agentty-specific `Journey` builders for E2E tests.
//!
//! Provides [`BuilderEnv`] for isolated test environments and
//! [`FeatureTest`] for declarative feature demo tests with optional Zola
//! page generation.

use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard, OnceLock};
use std::time::Duration;

use agentty::db::{DB_DIR, DB_FILE, Database, DbError};
use assert_cmd::cargo::cargo_bin;
use testty::assertion;
use testty::feature::{FeatureDemo, GifMode, GifStatus};
use testty::frame::TerminalFrame;
use testty::journey::Journey;
use testty::proof::report::{ProofCapture, ProofReport};
use testty::region::Region;
use testty::scenario::Scenario;
use testty::session::PtySessionBuilder;
use testty::step::Step;

/// Isolated test environment carrying `agentty_root` and `workdir` paths.
///
/// Use [`BuilderEnv::new`] to create a fresh environment under a temporary
/// directory, [`BuilderEnv::builder`] to get a configured
/// [`PtySessionBuilder`], and [`BuilderEnv::as_vhs_env_pairs`] to export the
/// environment for VHS tape compilation.
pub(crate) struct BuilderEnv {
    /// Path used as `AGENTTY_ROOT` for database and session isolation.
    pub(crate) agentty_root: PathBuf,
    /// Directory used as `HOME` so project discovery stays isolated from
    /// developer and CI machine repositories.
    pub(crate) home_dir: PathBuf,
    /// Directory containing stub agent executables so the app passes startup
    /// availability validation even when no real agent CLI is installed.
    pub(crate) stub_bin: PathBuf,
    /// Deterministic working directory registered as a project on startup.
    pub(crate) workdir: PathBuf,
}

impl BuilderEnv {
    /// Create a new isolated environment under `temp_root`.
    ///
    /// Creates `agentty_root` and `test-project` subdirectories so each test
    /// gets a fresh database and deterministic project name.
    ///
    /// # Errors
    ///
    /// Returns an error if directory creation fails.
    pub(crate) fn new(temp_root: &Path) -> std::io::Result<Self> {
        let agentty_root = temp_root.join("agentty_root");
        let home_dir = temp_root.join("home");
        let workdir = temp_root.join("test-project");
        let stub_bin = temp_root.join("stub-bin");

        std::fs::create_dir_all(&agentty_root)?;
        std::fs::create_dir_all(&home_dir)?;
        std::fs::create_dir_all(&workdir)?;
        std::fs::create_dir_all(&stub_bin)?;

        // Create a stub `claude` executable so the app passes startup agent
        // availability validation and exercises the background CLI update
        // refresh on machines without real agent CLIs (CI).
        let stub_agent_path = stub_bin.join("claude");
        let stub_version_path = stub_bin.join("claude.version");
        let stub_script = format!(
            "#!/bin/sh\nif [ \"$1\" = \"update\" ]; then printf '0.0.1-updated\\n' > \"{}\"; exit \
             0; fi\nif [ \"$1\" = \"--version\" ]; then if [ -f \"{}\" ]; then read version < \
             \"{}\"; else version='0.0.0-test'; fi; printf 'claude %s\\n' \"$version\"; exit 0; \
             fi\nexit 1\n",
            stub_version_path.display(),
            stub_version_path.display(),
            stub_version_path.display(),
        );
        std::fs::write(&stub_agent_path, stub_script)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&stub_agent_path, std::fs::Permissions::from_mode(0o755))?;
        }

        Ok(Self {
            agentty_root,
            home_dir,
            stub_bin,
            workdir,
        })
    }

    /// Return a configured [`PtySessionBuilder`] using this environment.
    ///
    /// Sets `AGENTTY_ROOT`, working directory, 80×24 terminal size, and
    /// prepends the stub agent bin directory to `PATH` so the app passes
    /// startup agent availability validation.
    pub(crate) fn builder(&self) -> PtySessionBuilder {
        let path_with_stub_bin = self.path_with_stub_bin();

        self.builder_with_path_and_size(
            path_with_stub_bin,
            DEFAULT_TERMINAL_COLS,
            DEFAULT_TERMINAL_ROWS,
        )
    }

    /// Return a configured [`PtySessionBuilder`] with an explicit `PATH` and
    /// terminal size.
    ///
    /// This keeps feature tests able to choose between inheriting system
    /// commands, using only deterministic stub agent executables, and
    /// exercising responsive layouts at their intended widths.
    fn builder_with_path_and_size(
        &self,
        path_env: String,
        terminal_cols: u16,
        terminal_rows: u16,
    ) -> PtySessionBuilder {
        PtySessionBuilder::new(cargo_bin("agentty"))
            .size(terminal_cols, terminal_rows)
            .env("AGENTTY_ROOT", self.agentty_root.to_string_lossy())
            .env("HOME", self.home_dir.to_string_lossy())
            .env("PATH", path_env)
            .workdir(&self.workdir)
    }

    /// Return environment variable pairs for VHS tape compilation.
    ///
    /// These match the variables set by [`BuilderEnv::builder`] so the VHS
    /// recording reproduces the same environment as the PTY session.
    pub(crate) fn as_vhs_env_pairs(&self) -> Vec<(String, String)> {
        self.as_vhs_env_pairs_with_path(self.path_with_stub_bin())
    }

    /// Return VHS environment variable pairs with an explicit `PATH`.
    ///
    /// This mirrors [`BuilderEnv::builder_with_path_and_size`] so PTY proof
    /// runs and VHS recordings see the same command lookup environment.
    fn as_vhs_env_pairs_with_path(&self, path_env: String) -> Vec<(String, String)> {
        vec![
            (
                "AGENTTY_ROOT".to_string(),
                self.agentty_root.to_string_lossy().into_owned(),
            ),
            (
                "HOME".to_string(),
                self.home_dir.to_string_lossy().into_owned(),
            ),
            ("PATH".to_string(), path_env),
        ]
    }

    /// Build a `PATH` value with the stub bin directory prepended to the
    /// inherited system `PATH`.
    fn path_with_stub_bin(&self) -> String {
        let system_path = std::env::var("PATH").unwrap_or_default();
        let mut paths = vec![self.stub_bin.clone()];
        paths.extend(std::env::split_paths(&system_path));

        match std::env::join_paths(paths) {
            Ok(path) => path.to_string_lossy().into_owned(),
            Err(_) => self.stub_bin.to_string_lossy().into_owned(),
        }
    }

    /// Build a deterministic `PATH` that exposes only the test stub bin.
    fn stub_only_path(&self) -> String {
        self.stub_bin.to_string_lossy().into_owned()
    }
}

/// Session row shape inserted by [`seed_session`].
#[derive(Clone, Copy)]
enum SessionSeedKind<'a> {
    /// Insert a normal persisted session row.
    Regular,
    /// Insert a draft session row that has not started running.
    Draft,
    /// Insert a stacked draft session linked to an existing parent.
    StackedDraft {
        /// Parent session id used by the stack relationship.
        parent_session_id: &'a str,
        /// Worktree path stored on the stacked draft session.
        worktree_path: &'a str,
    },
}

/// Declarative seed data for inserting one E2E session row.
#[derive(Clone, Copy)]
pub(crate) struct SessionSeed<'a> {
    base_branch: &'a str,
    kind: SessionSeedKind<'a>,
    model: &'a str,
    project_git_branch: Option<&'a str>,
    session_id: &'a str,
    status: &'a str,
    title: Option<&'a str>,
}

impl<'a> SessionSeed<'a> {
    /// Build seed data for a regular persisted session.
    pub(crate) fn regular(
        session_id: &'a str,
        model: &'a str,
        base_branch: &'a str,
        status: &'a str,
    ) -> Self {
        Self {
            base_branch,
            kind: SessionSeedKind::Regular,
            model,
            project_git_branch: Some(base_branch),
            session_id,
            status,
            title: None,
        }
    }

    /// Build seed data for an unstarted draft session.
    pub(crate) fn draft(
        session_id: &'a str,
        model: &'a str,
        base_branch: &'a str,
        status: &'a str,
    ) -> Self {
        Self {
            base_branch,
            kind: SessionSeedKind::Draft,
            model,
            project_git_branch: Some(base_branch),
            session_id,
            status,
            title: None,
        }
    }

    /// Build seed data for a stacked draft session.
    pub(crate) fn stacked_draft(
        session_id: &'a str,
        model: &'a str,
        worktree_path: &'a str,
        status: &'a str,
        parent_session_id: &'a str,
    ) -> Self {
        Self {
            base_branch: worktree_path,
            kind: SessionSeedKind::StackedDraft {
                parent_session_id,
                worktree_path,
            },
            model,
            project_git_branch: Some("main"),
            session_id,
            status,
            title: None,
        }
    }

    /// Return seed data that updates the inserted row title.
    pub(crate) fn with_title(mut self, title: &'a str) -> Self {
        self.title = Some(title);

        self
    }
}

/// Seed one session into the isolated E2E database.
///
/// Opens the database under [`BuilderEnv::agentty_root`], upserts and touches
/// the canonical test project, inserts the requested session row, and applies
/// an optional title update.
///
/// # Errors
///
/// Returns an error if runtime creation, project canonicalization, database
/// opening, project upsert/touch, or session insertion fails.
pub(crate) fn seed_session(
    env: &BuilderEnv,
    seed: SessionSeed<'_>,
) -> Result<(), Box<dyn std::error::Error>> {
    let runtime = seed_runtime()?;

    runtime.block_on(async {
        let (database, project_id) =
            open_database_with_seeded_project(env, seed.project_git_branch).await?;
        insert_session_seed(&database, project_id, &seed).await
    })?;

    Ok(())
}

/// Create the current-thread Tokio runtime used by synchronous E2E seeders.
///
/// The E2E tests are synchronous `#[test]` functions, so database setup uses a
/// short-lived runtime that does not leak across PTY scenario execution.
///
/// # Errors
///
/// Returns an error if the Tokio runtime cannot be built.
pub(crate) fn seed_runtime() -> std::io::Result<tokio::runtime::Runtime> {
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
}

/// Open the isolated E2E database and register the current test project.
///
/// The project path is canonicalized from [`BuilderEnv::workdir`], upserted
/// with `project_git_branch`, and marked as last opened so startup sees the
/// same active project as the seed data.
///
/// # Errors
///
/// Returns an error if path canonicalization, database opening, project upsert,
/// or last-opened persistence fails.
async fn open_database_with_seeded_project(
    env: &BuilderEnv,
    project_git_branch: Option<&str>,
) -> Result<(Database, i64), DbError> {
    let canonical_workdir = env.workdir.canonicalize()?;
    let database = open_database(env).await?;
    let project_id = database
        .projects()
        .upsert_project(
            &canonical_workdir.to_string_lossy(),
            project_git_branch.map(str::to_string),
        )
        .await?;

    database
        .projects()
        .touch_project_last_opened(project_id)
        .await?;

    Ok((database, project_id))
}

/// Open the isolated E2E database for direct test data setup.
///
/// # Errors
///
/// Returns an error if the database cannot be opened or migrated.
pub(crate) async fn open_database(env: &BuilderEnv) -> Result<Database, DbError> {
    let db_path = env.agentty_root.join(DB_DIR).join(DB_FILE);

    Database::open(&db_path).await
}

/// Insert one seeded session row and apply any row-level seed updates.
async fn insert_session_seed(
    database: &Database,
    project_id: i64,
    seed: &SessionSeed<'_>,
) -> Result<(), DbError> {
    match seed.kind {
        SessionSeedKind::Regular => {
            database
                .sessions()
                .insert_session(
                    seed.session_id,
                    seed.model,
                    seed.base_branch,
                    seed.status,
                    project_id,
                )
                .await?;
        }
        SessionSeedKind::Draft => {
            database
                .sessions()
                .insert_draft_session(
                    seed.session_id,
                    seed.model,
                    seed.base_branch,
                    seed.status,
                    project_id,
                )
                .await?;
        }
        SessionSeedKind::StackedDraft {
            parent_session_id,
            worktree_path,
        } => {
            database
                .sessions()
                .insert_stacked_draft_session(
                    seed.session_id,
                    seed.model,
                    worktree_path,
                    seed.status,
                    parent_session_id,
                    project_id,
                )
                .await?;
        }
    }

    if let Some(title) = seed.title {
        database
            .sessions()
            .update_session_title(seed.session_id, title)
            .await?;
    }

    Ok(())
}

/// Acquire the global E2E test lock so PTY-driven tests do not overlap.
///
/// The real `agentty` binary uses shared terminal, process, and filesystem
/// resources that become flaky when multiple PTY scenarios run in parallel
/// under coverage or high-load CI jobs.
pub(crate) fn acquire_e2e_test_lock() -> MutexGuard<'static, ()> {
    static E2E_TEST_LOCK: OnceLock<Mutex<()>> = OnceLock::new();

    E2E_TEST_LOCK
        .get_or_init(|| Mutex::new(()))
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// Return the feature GIF output directory as a pure path.
///
/// Derives the path from `CARGO_MANIFEST_DIR` →
/// `../../docs/site/static/features/`. This resolver intentionally does
/// not create the directory: `GifMode::CheckOnly` is a read-only path
/// that must work on read-only mounts and against a missing output
/// directory. Generation modes create the directory themselves inside
/// `testty::feature::generate_gif` only when they actually need to write.
fn feature_output_dir() -> PathBuf {
    let manifest_dir = env!("CARGO_MANIFEST_DIR");

    Path::new(manifest_dir).join("../../docs/site/static/features")
}

/// Environment variable that selects the GIF freshness mode for
/// [`FeatureTest`] runs.
///
/// Recognized values:
///
/// - unset / `generate` / `generate-if-stale` → [`GifMode::GenerateIfStale`]
/// - `check` / `check-only` → [`GifMode::CheckOnly`]
/// - `force` / `always` / `always-generate` → [`GifMode::AlwaysGenerate`]
///
/// Unknown values fall back to the default. The variable is parsed once
/// per test run.
pub(crate) const TESTTY_GIF_MODE_ENV_VAR: &str = "TESTTY_GIF_MODE";
/// Default PTY width used by feature tests unless a scenario requests a
/// wider responsive layout.
const DEFAULT_TERMINAL_COLS: u16 = 80;
/// Default PTY height used by feature tests unless a scenario requests a
/// taller responsive layout.
const DEFAULT_TERMINAL_ROWS: u16 = 24;

/// Resolve the GIF freshness mode from [`TESTTY_GIF_MODE_ENV_VAR`].
///
/// Returns [`GifMode::GenerateIfStale`] when the variable is unset.
/// Otherwise delegates to [`parse_gif_mode`] for value parsing.
fn resolve_gif_mode() -> GifMode {
    let Ok(raw) = std::env::var(TESTTY_GIF_MODE_ENV_VAR) else {
        return GifMode::GenerateIfStale;
    };

    parse_gif_mode(&raw)
}

/// Pure parser that maps a raw `TESTTY_GIF_MODE` value to a [`GifMode`].
///
/// Returns [`GifMode::GenerateIfStale`] for empty input or unrecognized
/// values via the catch-all arm. Comparison is case-insensitive and ignores
/// surrounding whitespace.
fn parse_gif_mode(raw: &str) -> GifMode {
    match raw.trim().to_ascii_lowercase().as_str() {
        "check" | "check-only" => GifMode::CheckOnly,
        "force" | "always" | "always-generate" => GifMode::AlwaysGenerate,
        _ => GifMode::GenerateIfStale,
    }
}

/// Reconstruct a [`TerminalFrame`] from a [`ProofCapture`] so full cell-level
/// assertions (highlight, color, style) can be run against intermediate
/// captures.
pub(crate) fn frame_from_capture(capture: &ProofCapture) -> TerminalFrame {
    TerminalFrame::new(capture.cols, capture.rows, &capture.frame_bytes)
}

// ---------------------------------------------------------------------------
// Zola feature page generation
// ---------------------------------------------------------------------------

/// Return the Zola feature content directory, creating it if needed.
///
/// Derives the path from `CARGO_MANIFEST_DIR` →
/// `../../docs/site/content/features/`.
fn feature_content_dir() -> PathBuf {
    let manifest_dir = env!("CARGO_MANIFEST_DIR");
    let content_dir = Path::new(manifest_dir).join("../../docs/site/content/features");

    let _ = std::fs::create_dir_all(&content_dir);

    content_dir
}

/// Metadata for generating a Zola feature content page.
///
/// When passed to [`FeatureTest::zola`], the test runner writes a minimal
/// `.md` frontmatter page to `docs/site/content/features/{name}.md` if the
/// file does not already exist.
pub(crate) struct ZolaFeaturePage {
    /// Human-readable title shown on the features page.
    pub(crate) title: String,
    /// Short description shown below the title.
    pub(crate) description: String,
    /// Ordering weight for the Zola features section (lower = first).
    pub(crate) weight: u32,
}

impl ZolaFeaturePage {
    /// Write the Zola frontmatter page if it does not already exist.
    ///
    /// The generated page uses TOML frontmatter with `title`, `description`,
    /// `weight`, and `[extra] gif` fields matching the Zola feature page
    /// conventions.
    fn ensure(&self, name: &str) {
        let content_dir = feature_content_dir();
        let page_path = content_dir.join(format!("{name}.md"));

        if page_path.exists() {
            return;
        }

        let content = format!(
            "+++\ntitle = \"{title}\"\ndescription = \"{description}\"\nweight = \
             {weight}\n\n[extra]\ngif = \"{name}.gif\"\n+++\n",
            title = self.title,
            description = self.description,
            weight = self.weight,
        );

        let _ = std::fs::write(&page_path, content);
    }
}

// ---------------------------------------------------------------------------
// FeatureTest builder
// ---------------------------------------------------------------------------

/// Declarative feature test builder for agentty E2E tests.
///
/// Owns the full test lifecycle: `TempDir` + [`BuilderEnv`] creation,
/// optional git init, scenario execution via [`FeatureDemo`], assertions,
/// GIF generation with hash caching, and optional Zola page creation.
///
/// # Example
///
/// ```ignore
/// #[test]
/// fn session_creation() {
///     FeatureTest::new("session_creation")
///         .with_git()
///         .zola("Session creation", "Start a new agent session.", 30)
///         .run(
///             |scenario| {
///                 scenario
///                     .compose(&common::wait_for_agentty_startup())
///                     .press_key("a")
///                     .press_key("Enter")
///                     .capture_labeled("prompt", "Prompt mode")
///             },
///             |frame, _report| {
///                 let full = Region::full(frame.cols(), frame.rows());
///                 assertion::assert_text_in_region(frame, "Enter", &full);
///             },
///         );
/// }
/// ```
pub(crate) struct FeatureTest {
    /// Extra child-process environment variables applied to PTY and VHS runs.
    child_env: Vec<(String, String)>,
    /// Whether PTY and VHS runs inherit the ambient system `PATH`.
    inherit_system_path: bool,
    /// Feature name used for GIF filename and Zola page filename.
    name: String,
    /// Optional environment setup hook that can seed database state or files
    /// before the PTY session starts.
    setup: Option<FeatureSetupHook>,
    /// Terminal column count used for the PTY proof run.
    terminal_cols: u16,
    /// Terminal row count used for the PTY proof run.
    terminal_rows: u16,
    /// Whether to initialize a git repository in the workdir.
    with_git: bool,
    /// Optional Zola page metadata for auto-generation.
    zola_page: Option<ZolaFeaturePage>,
}

/// Boxed setup hook used by [`FeatureTest`] before launching the PTY session.
type FeatureSetupHook = Box<dyn Fn(&BuilderEnv) -> Result<(), Box<dyn std::error::Error>>>;

impl FeatureTest {
    /// Create a new feature test builder with the given name.
    ///
    /// The name is used as the GIF filename stem and Zola page filename.
    pub(crate) fn new(name: impl Into<String>) -> Self {
        Self {
            child_env: Vec::new(),
            inherit_system_path: true,
            name: name.into(),
            setup: None,
            terminal_cols: DEFAULT_TERMINAL_COLS,
            terminal_rows: DEFAULT_TERMINAL_ROWS,
            with_git: false,
            zola_page: None,
        }
    }

    /// Configure an environment setup hook that runs after optional git
    /// initialization and before the PTY session starts.
    pub(crate) fn setup(
        mut self,
        setup: impl Fn(&BuilderEnv) -> Result<(), Box<dyn std::error::Error>> + 'static,
    ) -> Self {
        self.setup = Some(Box::new(setup));

        self
    }

    /// Add an environment variable for the PTY session and VHS recording.
    pub(crate) fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.child_env.push((key.into(), value.into()));

        self
    }

    /// Enable git initialization in the test workdir.
    ///
    /// Required for tests that exercise worktree-dependent features like
    /// session creation.
    pub(crate) fn with_git(mut self) -> Self {
        self.with_git = true;

        self
    }

    /// Configure the PTY terminal dimensions used while running the feature
    /// proof.
    pub(crate) fn with_terminal_size(mut self, cols: u16, rows: u16) -> Self {
        self.terminal_cols = cols;
        self.terminal_rows = rows;

        self
    }

    /// Run the PTY proof and VHS tape with only deterministic stub
    /// executables on `PATH`.
    pub(crate) fn with_stub_only_path(mut self) -> Self {
        self.inherit_system_path = false;

        self
    }

    /// Configure Zola feature page auto-generation.
    ///
    /// When set, the test runner writes a minimal `.md` frontmatter page
    /// to `docs/site/content/features/{name}.md` if it does not already
    /// exist.
    pub(crate) fn zola(mut self, title: &str, description: &str, weight: u32) -> Self {
        self.zola_page = Some(ZolaFeaturePage {
            title: title.to_string(),
            description: description.to_string(),
            weight,
        });

        self
    }

    /// Run the feature test: build scenario, execute, assert, generate GIF.
    ///
    /// The `build_scenario` closure receives a fresh [`Scenario`] with the
    /// feature name and should return it after composing journeys and steps.
    /// The `assert` closure receives the final frame and proof report for
    /// semantic assertions.
    pub(crate) fn run(
        self,
        build_scenario: impl FnOnce(Scenario) -> Scenario,
        assert: impl FnOnce(&TerminalFrame, &ProofReport),
    ) -> Result<(), Box<dyn std::error::Error>> {
        let _test_guard = acquire_e2e_test_lock();
        let temp = tempfile::TempDir::new()?;
        let env = BuilderEnv::new(temp.path())?;

        if self.with_git {
            env.init_git()?;
        }

        if let Some(setup) = &self.setup {
            setup(&env)?;
        }

        let scenario = build_scenario(Scenario::new(&self.name));
        let terminal_cols = self.terminal_cols;
        let terminal_rows = self.terminal_rows;
        let uses_default_terminal_size =
            terminal_cols == DEFAULT_TERMINAL_COLS && terminal_rows == DEFAULT_TERMINAL_ROWS;
        let (mut builder, mut owned_pairs) =
            if self.inherit_system_path && uses_default_terminal_size {
                (env.builder(), env.as_vhs_env_pairs())
            } else if self.inherit_system_path {
                (
                    env.builder_with_path_and_size(
                        env.path_with_stub_bin(),
                        terminal_cols,
                        terminal_rows,
                    ),
                    env.as_vhs_env_pairs(),
                )
            } else {
                let path_env = env.stub_only_path();

                (
                    env.builder_with_path_and_size(path_env.clone(), terminal_cols, terminal_rows),
                    env.as_vhs_env_pairs_with_path(path_env),
                )
            };
        for (key, value) in &self.child_env {
            builder = builder.env(key.clone(), value.clone());
            owned_pairs.push((key.clone(), value.clone()));
        }
        let env_pairs: Vec<(&str, &str)> = owned_pairs
            .iter()
            .map(|(key, value)| (key.as_str(), value.as_str()))
            .collect();

        let gif_mode = resolve_gif_mode();
        let result = FeatureDemo::new(&self.name)
            .gif_output_dir(feature_output_dir())
            .gif_mode(gif_mode)
            .run(&scenario, builder, &cargo_bin("agentty"), &env_pairs)
            .map_err(|error| std::io::Error::other(format!("feature demo failed: {error}")))?;

        // Surface GIF generation diagnostics — explicitly whitelist
        // benign variants and fail on every error-like variant, including
        // future ones added behind `#[non_exhaustive]`. The wildcard arm
        // is intentionally a hard failure so a new error variant cannot
        // be silently ignored by the harness.
        match &result.gif_status {
            GifStatus::Generated(_)
            | GifStatus::CacheHit(_)
            | GifStatus::Fresh { .. }
            | GifStatus::VhsNotInstalled
            | GifStatus::NoOutputDir => {}
            GifStatus::DirCreateFailed(err) => {
                return Err(std::io::Error::other(format!(
                    "Feature GIF dir creation failed for {}: {err}",
                    self.name
                ))
                .into());
            }
            GifStatus::TapeExecutionFailed(err) => {
                return Err(std::io::Error::other(format!(
                    "VHS tape execution failed for {}: {err}",
                    self.name
                ))
                .into());
            }
            GifStatus::Stale {
                gif_path,
                current,
                committed,
            } => {
                return Err(std::io::Error::other(format!(
                    "Feature GIF is stale for {} (gif: {}, current hash: {current}, committed \
                     hash: {committed:?}). Re-run with `{TESTTY_GIF_MODE_ENV_VAR}=force` (or \
                     unset to default) to regenerate.",
                    self.name,
                    gif_path.display(),
                ))
                .into());
            }
            other => {
                return Err(std::io::Error::other(format!(
                    "Feature GIF generation returned an unrecognized status for {}: {other:?}. \
                     Update the FeatureTest harness to handle the new GifStatus variant.",
                    self.name,
                ))
                .into());
            }
        }

        assert(&result.frame, &result.report);

        if let Some(zola_page) = self.zola_page {
            zola_page.ensure(&self.name);
        }

        Ok(())
    }
}

impl BuilderEnv {
    /// Initialize a git repository in the workdir so sessions can create
    /// worktrees.
    ///
    /// Sets up a `main` branch with an empty initial commit and minimal git
    /// config for the test environment.
    ///
    /// # Errors
    ///
    /// Returns an error if any git command fails.
    pub(crate) fn init_git(&self) -> std::io::Result<()> {
        let run = |args: &[&str]| -> std::io::Result<()> {
            let output = std::process::Command::new("git")
                .args(args)
                .current_dir(&self.workdir)
                .output()?;
            if !output.status.success() {
                return Err(std::io::Error::other(format!(
                    "git {} failed: {}",
                    args.join(" "),
                    String::from_utf8_lossy(&output.stderr)
                )));
            }

            Ok(())
        };
        run(&["init", "-b", "main"])?;
        run(&["config", "user.email", "test@test.com"])?;
        run(&["config", "user.name", "Test"])?;
        run(&["commit", "--allow-empty", "-m", "init"])
    }
}

// ---------------------------------------------------------------------------
// Agentty-specific Journey builders
// ---------------------------------------------------------------------------

/// Wait for agentty to start up and render a stable initial frame.
///
/// Waits for the initial TUI frame to appear and then settle briefly before
/// the scenario starts interacting with the app.
pub(crate) fn wait_for_agentty_startup() -> Journey {
    Journey::new("agentty_startup")
        .with_description("Wait for agentty startup and initial render")
        .step(Step::wait_for_text("Agentty", 30000))
        .step(Step::wait_for_stable_frame(300, 5000))
}

/// Switch to a tab by pressing `Tab` and waiting for the tab label text.
///
/// Useful for navigating forward through the tab bar one step at a time.
pub(crate) fn switch_to_tab(tab_name: &str) -> Journey {
    Journey::new(format!("switch_to_{tab_name}"))
        .with_description(format!("Press Tab and wait for '{tab_name}' to appear"))
        .step(Step::press_key("Tab"))
        .step(Step::wait_for_stable_frame(300, 3000))
}

/// Switch to a tab by pressing `BackTab` and waiting for stability.
///
/// Useful for navigating backward through the tab bar one step at a time.
pub(crate) fn switch_to_tab_reverse(tab_name: &str) -> Journey {
    Journey::new(format!("switch_back_to_{tab_name}"))
        .with_description(format!("Press BackTab and wait for '{tab_name}' to appear"))
        .step(Step::press_key("BackTab"))
        .step(Step::wait_for_stable_frame(300, 3000))
}

/// Open the quit confirmation dialog by pressing `q`.
///
/// Waits for the dialog to render with a stable frame.
pub(crate) fn open_quit_dialog() -> Journey {
    Journey::new("open_quit_dialog")
        .with_description("Press q and wait for quit confirmation dialog")
        .step(Step::press_key("q"))
        .step(Step::wait_for_stable_frame(300, 3000))
}

/// Open the help overlay by pressing `?`.
///
/// Waits for the overlay to render with a stable frame.
pub(crate) fn open_help_overlay() -> Journey {
    Journey::new("open_help_overlay")
        .with_description("Press ? and wait for help overlay")
        .step(Step::press_key("?"))
        .step(Step::wait_for_stable_frame(300, 3000))
}

/// Footer marker that only renders inside the in-session chat view.
///
/// `q: back` is the back-to-list help action exposed by the session view
/// footer. The sessions list view never renders this label, so it is a
/// reliable predicate target for the eventually waiter that detects when
/// the prompt-submit transition has completed.
const SESSION_VIEW_FOOTER_MARKER: &str = "q: back";

/// Footer marker that only renders on the sessions list view.
///
/// `new session` is the `a` shortcut label exposed by the sessions list
/// footer. The session chat view never renders this label, so it is a
/// reliable predicate target for the eventually waiter that detects when
/// the back-to-list transition has completed.
const SESSION_LIST_FOOTER_MARKER: &str = "new session";

/// Wait budget for predicate-driven session-view transitions.
///
/// Five seconds covers slow CI workers without masking real regressions: a
/// faster settle short-circuits the waiter on the first matching poll, and
/// a true regression still surfaces a structured `AssertionFailure` instead
/// of an opaque over-sleep.
const SESSION_TRANSITION_TIMEOUT: Duration = Duration::from_secs(5);

/// Polling cadence for the predicate-driven waiters above.
///
/// Fifty milliseconds keeps idle-CPU cost low while still finishing within
/// a single render frame on healthy hosts.
const SESSION_TRANSITION_POLL: Duration = Duration::from_millis(50);

/// Number of bottom rows scanned for footer help-action markers.
///
/// Both the sessions list page and the session view page render their
/// page-level help-action line two rows above the global worktree-status
/// footer bar (a one-cell page margin sits between them). Scanning the
/// bottom three rows therefore covers the page help row, the blank margin
/// row, and the global footer bar without reaching up into the chat
/// transcript or prompt input where agent output or user-typed text could
/// contain a matching substring.
const SESSION_TRANSITION_FOOTER_ROWS: u16 = 3;

/// Build an `eventually` step that succeeds once `marker` appears in the
/// live frame's bottom footer rows.
///
/// Wraps `assertion::match_text_in_region` against the bottom
/// `SESSION_TRANSITION_FOOTER_ROWS` rows so the waiter cannot be tricked by
/// prompt input or agent output that happens to contain the marker text, and
/// a timeout still surfaces a structured `AssertionFailure` carrying the
/// missing needle and current frame excerpt instead of a generic timeout
/// panic.
fn eventually_footer_text_visible(marker: &'static str) -> Step {
    Step::eventually(
        SESSION_TRANSITION_TIMEOUT,
        SESSION_TRANSITION_POLL,
        move |frame| {
            let rows = frame.rows();
            let height = SESSION_TRANSITION_FOOTER_ROWS.min(rows);
            let region = Region::new(0, rows.saturating_sub(height), frame.cols(), height);

            assertion::match_text_in_region(frame, marker, &region)
        },
    )
}

/// Create a session with a prompt, submit it, and return to the Sessions
/// list.
///
/// Presses `a` to open the creation selector, accepts the regular-session
/// default with `Enter`, types `"test"`, submits with `Enter` (which starts
/// the agent asynchronously while the session persists), and presses `q` from
/// the session view to return to the list.
///
/// Uses predicate-driven `eventually` waits keyed off footer markers because
/// the agent may produce continuous output after submit, so a stable-frame
/// wait can never settle.
///
/// Requires the Sessions tab to be active and a git-initialized workdir.
pub(crate) fn create_session_and_return_to_list() -> Journey {
    create_session_with_prompt_and_return_to_list("test")
}

/// Create a session with a caller-provided prompt, submit it, and return to
/// the Sessions list.
///
/// Uses predicate-driven `eventually` waits keyed off footer markers because
/// the agent may produce continuous output after submit, so a stable-frame
/// wait can never settle.
///
/// Requires the Sessions tab to be active and a git-initialized workdir.
pub(crate) fn create_session_with_prompt_and_return_to_list(prompt: &str) -> Journey {
    Journey::new("create_session")
        .with_description(format!(
            "Create regular session via a, type {prompt}, submit, return to list"
        ))
        .step(Step::press_key("a"))
        .step(Step::press_key("Enter"))
        .step(Step::wait_for_stable_frame(300, 5000))
        .step(Step::write_text(prompt))
        .step(Step::wait_for_text(prompt, 3000))
        .step(Step::press_key("Enter"))
        .step(eventually_footer_text_visible(SESSION_VIEW_FOOTER_MARKER))
        .step(Step::press_key("q"))
        .step(eventually_footer_text_visible(SESSION_LIST_FOOTER_MARKER))
}

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

    #[test]
    fn parse_gif_mode_empty_falls_back_to_default() {
        // Arrange / Act / Assert
        assert_eq!(parse_gif_mode(""), GifMode::GenerateIfStale);
    }

    #[test]
    fn parse_gif_mode_recognizes_check_only_aliases() {
        // Arrange / Act / Assert
        assert_eq!(parse_gif_mode("check"), GifMode::CheckOnly);
        assert_eq!(parse_gif_mode("check-only"), GifMode::CheckOnly);
        assert_eq!(parse_gif_mode("CHECK"), GifMode::CheckOnly);
        assert_eq!(parse_gif_mode("  check  "), GifMode::CheckOnly);
    }

    #[test]
    fn parse_gif_mode_recognizes_always_generate_aliases() {
        // Arrange / Act / Assert
        assert_eq!(parse_gif_mode("force"), GifMode::AlwaysGenerate);
        assert_eq!(parse_gif_mode("always"), GifMode::AlwaysGenerate);
        assert_eq!(parse_gif_mode("always-generate"), GifMode::AlwaysGenerate);
        assert_eq!(parse_gif_mode("Force"), GifMode::AlwaysGenerate);
    }

    #[test]
    fn parse_gif_mode_recognizes_generate_if_stale_aliases() {
        // Arrange / Act / Assert
        assert_eq!(parse_gif_mode("generate"), GifMode::GenerateIfStale);
        assert_eq!(
            parse_gif_mode("generate-if-stale"),
            GifMode::GenerateIfStale,
        );
    }

    #[test]
    fn parse_gif_mode_unknown_value_falls_back_to_default() {
        // Arrange / Act / Assert
        assert_eq!(parse_gif_mode("nonsense"), GifMode::GenerateIfStale);
        assert_eq!(parse_gif_mode("checkk"), GifMode::GenerateIfStale);
    }
}