jj-cz 1.1.0

Conventional commits for Jujutsu
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
//! Interactive commit workflow orchestration
//!
//! This module provides the CommitWorkflow struct that guides users through
//! creating a conventional commit message using interactive prompts.

use crate::{
    commit::types::{
        Body, BreakingChange, CommitMessageError, CommitType, ConventionalCommit, Description,
        References, Scope,
    },
    error::Error,
    jj::JjExecutor,
    prompts::prompter::{Prompter, RealPrompts},
};

/// Orchestrates the interactive commit workflow
///
/// This struct handles the complete user interaction flow:
/// 1. Check if we're in a jj repository
/// 2. Select commit type from 11 options
/// 3. Optionally input scope (validated)
/// 4. Input required description (validated)
/// 5. Preview formatted message and confirm
/// 6. Apply the message to the current change
///
/// Uses dependency injection for prompts to enable testing without TUI.
#[derive(Debug)]
pub struct CommitWorkflow<J: JjExecutor, P: Prompter = RealPrompts> {
    executor: J,
    prompts: P,
}

impl<J: JjExecutor> CommitWorkflow<J> {
    /// Create a new CommitWorkflow with the given executor
    ///
    /// Uses RealPrompts by default for interactive TUI prompts.
    pub fn new(executor: J) -> Self {
        Self::with_prompts(executor, RealPrompts)
    }
}

impl<J: JjExecutor, P: Prompter> CommitWorkflow<J, P> {
    /// Create a new CommitWorkflow with custom prompts
    ///
    /// This allows using MockPrompts in tests to avoid TUI hanging.
    pub fn with_prompts(executor: J, prompts: P) -> Self {
        Self { executor, prompts }
    }

    /// Run the complete interactive workflow
    ///
    /// Returns Ok(()) on successful completion, or an error if:
    /// - Not in a jj repository
    /// - User cancels the workflow
    /// - Repository operation fails
    /// - Message validation fails
    pub async fn run_for_revset(&self, revset: &str) -> Result<(), Error> {
        if !self.executor.is_repository().await? {
            return Err(Error::NotARepository);
        }
        // For future reference
        let _existing_desc = self.executor.get_description(revset).await.ok();
        let commit_type = self.type_selection()?;
        loop {
            let scope = self.scope_input()?;
            let description = self.description_input()?;
            let breaking_change = self.breaking_change_input()?;
            let references = self.references_input()?;
            let body = self.body_input()?;
            match self.preview_and_confirm(
                commit_type,
                scope,
                description,
                breaking_change,
                body,
                references,
            ) {
                Ok(conventional_commit) => {
                    self.executor
                        .describe(revset, &conventional_commit.to_string())
                        .await?;
                    return Ok(());
                }
                Err(Error::InvalidCommitMessage(_)) => {
                    // The scope/description combination exceeds 72 characters.
                    // The user has already been shown the error via emit_message.
                    // Loop back to re-prompt scope and description (type is kept).
                    continue;
                }
                Err(e) => return Err(e),
            }
        }
    }

    /// Prompt user to select a commit type from the 11 available options
    fn type_selection(&self) -> Result<CommitType, Error> {
        self.prompts.select_commit_type()
    }

    /// Prompt user to input an optional scope
    ///
    /// Returns Ok(Scope) with the validated scope, or
    /// Error::Cancelled if user cancels
    fn scope_input(&self) -> Result<Scope, Error> {
        self.prompts.input_scope()
    }

    /// Prompt user to input a required description
    ///
    /// Returns Ok(Description) with the validated description, or
    /// Error::Cancelled if user cancels
    fn description_input(&self) -> Result<Description, Error> {
        self.prompts.input_description()
    }

    /// Prompt user for breaking change
    ///
    /// Returns Ok(BreakingChange) with the validated breaking change,
    /// or Error::Cancel if user cancels
    fn breaking_change_input(&self) -> Result<BreakingChange, Error> {
        self.prompts.input_breaking_change()
    }

    /// Prompt user for references
    fn references_input(&self) -> Result<References, Error> {
        self.prompts.input_references()
    }

    /// Prompt user to optionally add a free-form body via an external editor
    fn body_input(&self) -> Result<Body, Error> {
        self.prompts.input_body()
    }

    /// Preview the formatted conventional commit message and get user confirmation
    ///
    /// This method also validates that the complete first line
    /// doesn't exceed 72 characters
    fn preview_and_confirm(
        &self,
        commit_type: CommitType,
        scope: Scope,
        description: Description,
        breaking_change: BreakingChange,
        body: Body,
        references: References,
    ) -> Result<ConventionalCommit, Error> {
        // Format the message for preview
        let message = ConventionalCommit::format_preview(
            commit_type,
            &scope,
            &description,
            &breaking_change,
            &body,
            &references,
        );

        // Try to build the conventional commit (this validates the 72-char limit)
        let conventional_commit: ConventionalCommit = match ConventionalCommit::new(
            commit_type,
            scope.clone(),
            description.clone(),
            breaking_change,
            body,
            references,
        ) {
            Ok(cc) => cc,
            Err(CommitMessageError::FirstLineTooLong { actual, max }) => {
                self.prompts.emit_message("❌ Message too long!");
                self.prompts.emit_message(&format!(
                    "The complete first line must be ≤ {} characters.",
                    max
                ));
                self.prompts
                    .emit_message(&format!("Current length: {} characters", actual));
                self.prompts.emit_message("");
                self.prompts.emit_message("Formatted message would be:");
                self.prompts.emit_message(&message);
                self.prompts.emit_message("");
                self.prompts
                    .emit_message("Please try again with a shorter scope or description.");
                return Err(Error::InvalidCommitMessage(format!(
                    "First line too long: {} > {}",
                    actual, max
                )));
            }
            Err(CommitMessageError::InvalidConventionalFormat { reason }) => {
                return Err(Error::InvalidCommitMessage(format!(
                    "Internal error: generated message failed conventional commit validation: {}",
                    reason
                )));
            }
        };

        // Get confirmation from user
        let confirmed = self.prompts.confirm_apply(&message)?;

        if confirmed {
            Ok(conventional_commit)
        } else {
            Err(Error::Cancelled)
        }
    }

    pub async fn new_revision(&self, revset: &str) -> Result<(), Error> {
        self.executor.new_revision(revset).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::Error;
    use crate::jj::mock::MockJjExecutor;
    use crate::prompts::mock::MockPrompts;

    /// Test that CommitWorkflow can be created with a mock executor
    #[test]
    fn workflow_creation() {
        let mock = MockJjExecutor::new();
        let workflow = CommitWorkflow::new(mock);
        // If this compiles, the workflow is properly typed
        assert!(matches!(workflow, CommitWorkflow { .. }));
    }

    /// Test workflow returns NotARepository when is_repository() returns false
    #[tokio::test]
    async fn workflow_returns_not_a_repository() {
        let mock = MockJjExecutor::new().with_is_repo_response(Ok(false));
        let workflow = CommitWorkflow::new(mock);
        let result: Result<(), Error> = workflow.run_for_revset("@").await;
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::NotARepository));
    }

    /// Test workflow returns NotARepository when is_repository() returns error
    #[tokio::test]
    async fn workflow_returns_repository_error() {
        let mock = MockJjExecutor::new().with_is_repo_response(Err(Error::NotARepository));
        let workflow = CommitWorkflow::new(mock);
        let result: Result<(), Error> = workflow.run_for_revset("@").await;
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::NotARepository));
    }

    /// Test that type_selection returns a valid CommitType
    #[test]
    fn type_selection_returns_valid_type() {
        // Updated to use mock prompts to avoid TUI hanging
        let mock_executor = MockJjExecutor::new();
        let mock_prompts = MockPrompts::new().with_commit_type(CommitType::Feat);
        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);

        // Now we can actually test the method with mock prompts
        let result = workflow.type_selection();
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), CommitType::Feat);
    }

    /// Test that scope_input returns a valid Scope
    #[test]
    fn scope_input_returns_valid_scope() {
        let mock_executor = MockJjExecutor::new();
        let mock_prompts = MockPrompts::new().with_scope(Scope::parse("test").unwrap());
        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);

        let result = workflow.scope_input();
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Scope::parse("test").unwrap());
    }

    /// Test that description_input returns a valid Description
    #[test]
    fn description_input_returns_valid_description() {
        let mock_executor = MockJjExecutor::new();
        let mock_prompts = MockPrompts::new().with_description(Description::parse("test").unwrap());
        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);

        let result = workflow.description_input();
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Description::parse("test").unwrap());
    }

    /// Test that preview_and_confirm returns a ConventionalCommit
    #[test]
    fn preview_and_confirm_returns_conventional_commit() {
        let mock_executor = MockJjExecutor::new();
        let mock_prompts = MockPrompts::new().with_confirm(true);
        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);

        let commit_type = CommitType::Feat;
        let scope = Scope::empty();
        let description = Description::parse("test description").unwrap();
        let breaking_change = BreakingChange::No;
        let body = Body::default();
        let references = References::default();
        let result = workflow.preview_and_confirm(
            commit_type,
            scope,
            description,
            breaking_change,
            body,
            references,
        );
        assert!(result.is_ok());
    }

    /// Test workflow error handling for describe failure
    #[tokio::test]
    async fn workflow_handles_describe_error() {
        // Test the mock executor methods directly
        let mock = MockJjExecutor::new()
            .with_is_repo_response(Ok(true))
            .with_describe_response(Err(Error::RepositoryLocked));

        // Verify the mock behaves as expected
        assert!(mock.is_repository().await.is_ok());
        assert!(mock.describe("@", "test").await.is_err());

        // Also test with a working mock
        let working_mock = MockJjExecutor::new();
        let workflow = CommitWorkflow::new(working_mock);
        // We can't complete the full workflow without mocking prompts,
        // but we can verify the workflow was created successfully
        assert!(matches!(workflow, CommitWorkflow { .. }));
    }

    /// Test that workflow implements Debug trait
    #[test]
    fn workflow_implements_debug() {
        let mock = MockJjExecutor::new();
        let workflow = CommitWorkflow::new(mock);
        let debug_output = format!("{:?}", workflow);
        assert!(debug_output.contains("CommitWorkflow"));
    }

    /// Test complete workflow with mock prompts (happy path)
    #[tokio::test]
    async fn test_complete_workflow_happy_path() {
        // Create mock executor that returns true for is_repository
        let mock_executor = MockJjExecutor::new().with_is_repo_response(Ok(true));

        // Create mock prompts with successful responses
        let mock_prompts = MockPrompts::new()
            .with_commit_type(CommitType::Feat)
            .with_scope(Scope::empty())
            .with_description(Description::parse("add new feature").unwrap())
            .with_breaking_change(BreakingChange::Yes)
            .with_references(References::default())
            .with_body(Body::default())
            .with_confirm(true);

        // Create workflow with both mocks
        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);

        // Run the workflow - should succeed
        let result: Result<(), Error> = workflow.run_for_revset("@").await;
        assert!(result.is_ok());
    }

    /// Test workflow cancellation at type selection
    #[tokio::test]
    async fn test_workflow_cancellation_at_type_selection() {
        let mock_executor = MockJjExecutor::new().with_is_repo_response(Ok(true));
        let mock_prompts = MockPrompts::new().with_error(Error::Cancelled);

        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
        let result: Result<(), Error> = workflow.run_for_revset("@").await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::Cancelled));
    }

    /// Test workflow cancellation at confirmation
    #[tokio::test]
    async fn test_workflow_cancellation_at_confirmation() {
        let mock_executor = MockJjExecutor::new().with_is_repo_response(Ok(true));
        let mock_prompts = MockPrompts::new()
            .with_commit_type(CommitType::Fix)
            .with_scope(Scope::parse("api").unwrap())
            .with_description(Description::parse("fix bug").unwrap())
            .with_breaking_change(BreakingChange::No)
            .with_references(References::default())
            .with_body(Body::default())
            .with_confirm(false); // User cancels at confirmation

        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
        let result: Result<(), Error> = workflow.run_for_revset("@").await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::Cancelled));
    }

    /// Test workflow loops back on line length error, re-prompting scope and description
    ///
    /// "feat(very-long-scope-name): " + 45 'a's = 4+1+20+3+45 = 73 chars → too long (first pass)
    /// "feat: short description" = 4+2+17 = 23 chars → fine (second pass)
    #[tokio::test]
    async fn test_workflow_line_length_validation() {
        let mock_executor = MockJjExecutor::new().with_is_repo_response(Ok(true));

        let mock_prompts = MockPrompts::new()
            .with_commit_type(CommitType::Feat)
            // First iteration: scope + description exceed 72 chars combined
            .with_scope(Scope::parse("very-long-scope-name").unwrap())
            .with_description(Description::parse("a".repeat(45)).unwrap())
            .with_breaking_change(BreakingChange::No)
            .with_references(References::default())
            .with_body(Body::default())
            // Second iteration: short enough to succeed
            .with_scope(Scope::empty())
            .with_description(Description::parse("short description").unwrap())
            .with_breaking_change(BreakingChange::No)
            .with_references(References::default())
            .with_body(Body::default())
            .with_confirm(true);

        // Clone before moving into workflow so we can inspect emitted messages after
        let mock_prompts_handle = mock_prompts.clone();
        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
        let result: Result<(), Error> = workflow.run_for_revset("@").await;

        // Should succeed after the retry
        assert!(
            result.is_ok(),
            "Workflow should succeed after retry, got: {:?}",
            result
        );

        // Error messages about the line being too long must have been emitted
        // (via emit_message, not bare println) during the first iteration
        let messages = mock_prompts_handle.emitted_messages();
        assert!(
            messages.iter().any(|m| m.contains("too long")),
            "Expected a 'too long' message, got: {:?}",
            messages
        );
        assert!(
            messages.iter().any(|m| m.contains("72")),
            "Expected a message about the 72-char limit, got: {:?}",
            messages
        );
    }

    /// Test workflow with invalid scope
    #[tokio::test]
    async fn test_workflow_invalid_scope() {
        let mock_executor = MockJjExecutor::new().with_is_repo_response(Ok(true));

        // Create mock prompts that would return invalid scope
        let mock_prompts = MockPrompts::new()
            .with_commit_type(CommitType::Docs)
            .with_error(Error::InvalidScope(
                "Invalid characters in scope".to_string(),
            ));

        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
        let result: Result<(), Error> = workflow.run_for_revset("@").await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::InvalidScope(_)));
    }

    /// Test workflow with invalid description
    #[tokio::test]
    async fn test_workflow_invalid_description() {
        let mock_executor = MockJjExecutor::new().with_is_repo_response(Ok(true));

        let mock_prompts = MockPrompts::new()
            .with_commit_type(CommitType::Refactor)
            .with_scope(Scope::empty())
            .with_error(Error::InvalidDescription(
                "Description cannot be empty".to_string(),
            ));

        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
        let result: Result<(), Error> = workflow.run_for_revset("@").await;

        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::InvalidDescription(_)));
    }

    /// Test that mock prompts track method calls correctly
    #[test]
    fn test_mock_prompts_track_calls() {
        let mock_executor = MockJjExecutor::new().with_is_repo_response(Ok(true));
        let mock_prompts = MockPrompts::new()
            .with_commit_type(CommitType::Feat)
            .with_scope(Scope::empty())
            .with_description(Description::parse("test").unwrap())
            .with_confirm(true);

        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
        // We don't need to run the full workflow, just verify the mock was created correctly
        assert!(matches!(workflow, CommitWorkflow { .. }));
    }

    /// Test workflow with all commit types
    #[tokio::test]
    async fn test_all_commit_types() {
        let _mock_executor = MockJjExecutor::new().with_is_repo_response(Ok(true));

        for commit_type in CommitType::all() {
            let mock_prompts = MockPrompts::new()
                .with_commit_type(*commit_type)
                .with_scope(Scope::empty())
                .with_description(Description::parse("test").unwrap())
                .with_breaking_change(BreakingChange::Yes)
                .with_references(References::default())
                .with_body(Body::default())
                .with_confirm(true);

            let workflow = CommitWorkflow::with_prompts(
                MockJjExecutor::new().with_is_repo_response(Ok(true)),
                mock_prompts,
            );
            let result: Result<(), Error> = workflow.run_for_revset("@").await;
            assert!(result.is_ok(), "Failed for commit type: {:?}", commit_type);
        }
    }

    /// Test workflow with various scope formats
    #[tokio::test]
    async fn test_various_scope_formats() {
        let _mock_executor = MockJjExecutor::new().with_is_repo_response(Ok(true));

        // Test empty scope
        let mock_prompts = MockPrompts::new()
            .with_commit_type(CommitType::Feat)
            .with_scope(Scope::empty())
            .with_description(Description::parse("test").unwrap())
            .with_breaking_change(BreakingChange::Yes)
            .with_references(References::default())
            .with_body(Body::default())
            .with_confirm(true);

        let workflow = CommitWorkflow::with_prompts(
            MockJjExecutor::new().with_is_repo_response(Ok(true)),
            mock_prompts,
        );
        {
            let result: Result<(), Error> = workflow.run_for_revset("@").await;
            assert!(result.is_ok());
        }

        // Test valid scope
        let mock_prompts = MockPrompts::new()
            .with_commit_type(CommitType::Feat)
            .with_scope(Scope::parse("api").unwrap())
            .with_description(Description::parse("test").unwrap())
            .with_breaking_change(BreakingChange::No)
            .with_references(References::default())
            .with_body(Body::default())
            .with_confirm(true);

        let workflow = CommitWorkflow::with_prompts(
            MockJjExecutor::new().with_is_repo_response(Ok(true)),
            mock_prompts,
        );
        {
            let result: Result<(), Error> = workflow.run_for_revset("@").await;
            assert!(result.is_ok());
        }
    }

    /// Test that workflow can be used with trait objects for both executor and prompts
    #[test]
    fn workflow_works_with_trait_objects() {
        let mock_executor = MockJjExecutor::new();
        let mock_prompts = MockPrompts::new()
            .with_commit_type(CommitType::Feat)
            .with_scope(Scope::empty())
            .with_description(Description::parse("test").unwrap())
            .with_confirm(true);

        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
        assert!(matches!(workflow, CommitWorkflow { .. }));
    }

    /// Preview_and_confirm must forward BreakingChange::Yes to
    /// ConventionalCommit::new(), producing a commit whose string
    /// contains '!'.
    ///
    /// Before the fix the parameter was ignored and
    /// BreakingChange::No was hard-coded, so a confirmed
    /// breaking-change commit was silently applied without the '!'
    /// marker.
    #[test]
    fn preview_and_confirm_forwards_breaking_change_yes() {
        let mock_executor = MockJjExecutor::new();
        let mock_prompts = MockPrompts::new().with_confirm(true);
        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);

        let result = workflow.preview_and_confirm(
            CommitType::Feat,
            Scope::empty(),
            Description::parse("remove old API").unwrap(),
            BreakingChange::Yes,
            Body::default(),
            References::default(),
        );

        assert!(result.is_ok(), "expected Ok, got: {:?}", result);
        let message = result.unwrap().to_string();
        assert!(
            message.contains("feat!:"),
            "expected '!' marker in described message, got: {:?}",
            message,
        );
    }

    /// Preview_and_confirm must forward BreakingChange::WithNote,
    /// producing a commit with both the '!' header marker and the
    /// BREAKING CHANGE footer.
    #[test]
    fn preview_and_confirm_forwards_breaking_change_with_note() {
        let mock_executor = MockJjExecutor::new();
        let mock_prompts = MockPrompts::new().with_confirm(true);
        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);

        let breaking_change: BreakingChange = "removes legacy endpoint".into();
        let result = workflow.preview_and_confirm(
            CommitType::Feat,
            Scope::empty(),
            Description::parse("drop legacy API").unwrap(),
            breaking_change,
            Body::default(),
            References::default(),
        );

        assert!(result.is_ok(), "expected Ok, got: {:?}", result);
        let message = result.unwrap().to_string();
        assert!(
            message.contains("feat!:"),
            "expected '!' header marker in message, got: {:?}",
            message,
        );
        assert!(
            message.contains("BREAKING CHANGE:"),
            "expected BREAKING CHANGE footer in message, got: {:?}",
            message,
        );
    }

    /// The message passed to executor.describe() must include the '!'
    /// marker when the user selects a breaking change.
    ///
    /// This test exercises the full run() path and inspects what was
    /// actually handed to the jj executor, which is the authoritative
    /// check that the described commit is correct.
    #[tokio::test]
    async fn full_workflow_describes_commit_with_breaking_change_marker() {
        let mock_executor = MockJjExecutor::new().with_is_repo_response(Ok(true));
        let mock_prompts = MockPrompts::new()
            .with_commit_type(CommitType::Feat)
            .with_scope(Scope::empty())
            .with_description(Description::parse("remove old API").unwrap())
            .with_breaking_change(BreakingChange::Yes)
            .with_references(References::default())
            .with_body(Body::default())
            .with_confirm(true);

        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
        let result: Result<(), Error> = workflow.run_for_revset("@").await;

        assert!(
            result.is_ok(),
            "expected workflow to succeed, got: {:?}",
            result
        );

        let messages = workflow.executor.describe_messages();
        assert_eq!(messages.len(), 1, "expected exactly one describe() call");
        assert!(
            messages[0].contains("feat!:"),
            "expected '!' marker in the described message, got: {:?}",
            messages[0],
        );
    }

    // --- Body tests ---
    // preview_and_confirm() tests compile now but will fail until the Body::default()
    // at line 138 of preview_and_confirm() is replaced with the `body` parameter.
    // The full_workflow_* tests additionally require MockPrompts::with_body().

    /// preview_and_confirm must forward the body to ConventionalCommit::new()
    ///
    /// Currently the implementation passes Body::default() instead of the
    /// received body, so this test will fail until that is fixed.
    #[test]
    fn preview_and_confirm_forwards_body() {
        let mock_executor = MockJjExecutor::new();
        let mock_prompts = MockPrompts::new().with_confirm(true);
        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);

        let result = workflow.preview_and_confirm(
            CommitType::Feat,
            Scope::empty(),
            Description::parse("add feature").unwrap(),
            BreakingChange::No,
            Body::from("This explains the change."),
            References::default(),
        );

        assert!(result.is_ok(), "expected Ok, got: {:?}", result);
        assert!(
            result
                .unwrap()
                .to_string()
                .contains("This explains the change."),
            "body must appear in the commit message"
        );
    }

    /// preview_and_confirm must forward the body even when a breaking change is present
    ///
    /// Expected format: "type!: desc\n\nbody\n\nBREAKING CHANGE: note"
    #[test]
    fn preview_and_confirm_forwards_body_with_breaking_change() {
        let mock_executor = MockJjExecutor::new();
        let mock_prompts = MockPrompts::new().with_confirm(true);
        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);

        let result = workflow.preview_and_confirm(
            CommitType::Feat,
            Scope::empty(),
            Description::parse("drop legacy API").unwrap(),
            "removes legacy endpoint".into(),
            Body::from("The endpoint was deprecated in v2."),
            References::default(),
        );

        assert!(result.is_ok(), "expected Ok, got: {:?}", result);
        let message = result.unwrap().to_string();
        assert!(
            message.contains("The endpoint was deprecated in v2."),
            "body must appear in the commit message, got: {message:?}"
        );
        assert!(
            message.contains("BREAKING CHANGE: removes legacy endpoint"),
            "breaking change footer must still be present, got: {message:?}"
        );
    }

    /// The full run() workflow must collect a body and include it in the
    /// described commit.
    ///
    /// Requires MockPrompts::with_body() and run() to call body_input().
    #[tokio::test]
    async fn full_workflow_describes_commit_with_body() {
        let mock_executor = MockJjExecutor::new().with_is_repo_response(Ok(true));
        let mock_prompts = MockPrompts::new()
            .with_commit_type(CommitType::Feat)
            .with_scope(Scope::empty())
            .with_description(Description::parse("add feature").unwrap())
            .with_breaking_change(BreakingChange::No)
            .with_references(References::default())
            .with_body(Body::from("This explains the change."))
            .with_confirm(true);

        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
        let result: Result<(), Error> = workflow.run_for_revset("@").await;

        assert!(
            result.is_ok(),
            "expected workflow to succeed, got: {:?}",
            result
        );

        let messages = workflow.executor.describe_messages();
        assert_eq!(messages.len(), 1, "expected exactly one describe() call");
        assert!(
            messages[0].contains("This explains the change."),
            "body must appear in the described commit, got: {:?}",
            messages[0]
        );
    }

    /// run() must still work correctly when the user declines to add a body
    ///
    /// Requires MockPrompts::with_body() returning Body::default().
    #[tokio::test]
    async fn full_workflow_with_no_body_succeeds() {
        let mock_executor = MockJjExecutor::new().with_is_repo_response(Ok(true));
        let mock_prompts = MockPrompts::new()
            .with_commit_type(CommitType::Fix)
            .with_scope(Scope::empty())
            .with_description(Description::parse("fix crash").unwrap())
            .with_breaking_change(BreakingChange::No)
            .with_references(References::default())
            .with_body(Body::default())
            .with_confirm(true);

        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);
        let result: Result<(), Error> = workflow.run_for_revset("@").await;

        assert!(
            result.is_ok(),
            "expected workflow to succeed, got: {:?}",
            result
        );

        let messages = workflow.executor.describe_messages();
        assert_eq!(messages.len(), 1);
        assert_eq!(messages[0], "fix: fix crash");
    }

    /// Test workflow new_revision() records the revset
    #[tokio::test]
    async fn workflow_new_revision_records_revset() {
        let mock_executor = MockJjExecutor::new();
        let workflow = CommitWorkflow::new(mock_executor);

        let result = workflow.new_revision("@").await;
        assert!(result.is_ok());

        let calls = workflow.executor.new_revision_calls();
        assert_eq!(calls, vec!["@"]);
    }

    /// Test workflow new_revision() propagates executor errors
    #[tokio::test]
    async fn workflow_new_revision_propagates_error() {
        let mock_executor =
            MockJjExecutor::new().with_new_revision_response(Err(Error::RepositoryLocked));
        let workflow = CommitWorkflow::new(mock_executor);

        let result = workflow.new_revision("@").await;
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), Error::RepositoryLocked));
    }

    /// Test workflow run_for_revset() followed by new_revision() records both
    ///
    /// This mirrors the actual usage pattern in main.rs.
    #[tokio::test]
    async fn workflow_describe_then_new_revision() {
        let mock_executor = MockJjExecutor::new().with_is_repo_response(Ok(true));
        let mock_prompts = MockPrompts::new()
            .with_commit_type(CommitType::Feat)
            .with_scope(Scope::empty())
            .with_description(Description::parse("add feature").unwrap())
            .with_breaking_change(BreakingChange::No)
            .with_references(References::default())
            .with_body(Body::default())
            .with_confirm(true);

        let workflow = CommitWorkflow::with_prompts(mock_executor, mock_prompts);

        workflow.run_for_revset("@").await.expect("describe failed");
        workflow
            .new_revision("@")
            .await
            .expect("new_revision failed");

        let messages = workflow.executor.describe_messages();
        assert_eq!(messages.len(), 1);
        assert!(messages[0].contains("feat:"));

        let calls = workflow.executor.new_revision_calls();
        assert_eq!(calls, vec!["@"]);
    }
}