jjj 0.4.1

Distributed project management and code review 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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
use crate::cli::SolutionAction;
use crate::context::CommandContext;
use crate::db::{search, Database};
use crate::display::{short_id, truncated_prefixes};
use crate::embeddings::EmbeddingClient;
use crate::error::Result;
use crate::local_config::LocalConfig;
use crate::models::{
    Critique, CritiqueSeverity, CritiqueStatus, Event, EventExtra, EventType, ProblemStatus,
    Solution, SolutionStatus,
};
use std::io::{self, Write};

pub fn execute(ctx: &CommandContext, action: SolutionAction) -> Result<()> {
    match action {
        SolutionAction::New {
            title,
            problem,
            supersedes,
            reviewer,
            force,
            tags,
        } => new_solution(ctx, title, problem, supersedes, reviewer, force, tags),

        SolutionAction::List {
            problem,
            status,
            assignee,
            search,
            tag,
            sort,
            json,
        } => list_solutions(
            ctx,
            problem,
            status,
            assignee,
            search.as_deref(),
            tag,
            &sort,
            json,
        ),
        SolutionAction::Show { solution_id, json } => show_solution(ctx, solution_id, json),
        SolutionAction::Edit {
            solution_id,
            title,
            status,
            add_tag,
            remove_tag,
            set_tags,
        } => edit_solution(
            ctx,
            solution_id,
            title,
            status,
            add_tag,
            remove_tag,
            set_tags,
        ),
        SolutionAction::Attach { solution_id, force } => attach_change(ctx, solution_id, force),
        SolutionAction::Detach {
            solution_id,
            change_id,
            force,
        } => detach_change(ctx, solution_id, change_id, force),
        SolutionAction::Submit { solution_id } => submit_solution(ctx, solution_id),
        SolutionAction::Withdraw {
            solution_id,
            rationale,
            no_rationale,
        } => withdraw_solution(ctx, solution_id, rationale, no_rationale),
        SolutionAction::Approve {
            solution_id,
            force,
            rationale,
            no_rationale,
        } => approve_solution(ctx, solution_id, force, rationale, no_rationale),
        SolutionAction::Assign { solution_id, to } => assign_solution(ctx, solution_id, to),
        SolutionAction::Resume { solution_id } => resume_solution(ctx, solution_id),
        SolutionAction::Lgtm { solution_id } => lgtm_solution(ctx, solution_id),
        SolutionAction::Comment {
            solution_id,
            critique,
            body,
        } => comment_solution(ctx, solution_id, critique, body),
        SolutionAction::Diff { solution_id } => diff_solution(ctx, solution_id),
    }
}

fn new_solution(
    ctx: &CommandContext,
    title: String,
    problem_input: Option<String>,
    supersedes_input: Option<String>,
    reviewer_critiques: Vec<String>,
    force: bool,
    tags: Vec<String>,
) -> Result<()> {
    let store = &ctx.store;

    let jj_client = ctx.jj();

    // Validate title is not empty
    let title = title.trim().to_string();
    if title.is_empty() {
        return Err(crate::error::JjjError::Validation(
            "Title cannot be empty.".to_string(),
        ));
    }

    // If not forcing, check for duplicates
    if !force {
        // Check for similar solutions via FTS text search (best-effort, skip on error)
        let repo_root = jj_client.repo_root().to_path_buf();
        let db_path = repo_root.join(".jj").join("jjj.db");
        if db_path.exists() {
            if let Ok(db) = Database::open(&db_path) {
                if let Ok(results) = search::search(db.conn(), &title, Some("solution")) {
                    if !results.is_empty() {
                        eprintln!("Warning: similar solutions already exist:");
                        for r in &results {
                            eprintln!("  s/{} — \"{}\"", short_id(&r.entity_id), r.title);
                        }
                        eprintln!("\nUse --force to create anyway.");
                        return Err(crate::error::JjjError::Validation(
                            "Similar entities exist. Use --force to override.".to_string(),
                        ));
                    }
                }
            }
        }

        // Also check semantic duplicates via embeddings (if available)
        if let Some(similar) = check_for_similar_solutions(ctx, &title)? {
            if !prompt_create_solution_anyway(&similar)? {
                println!("Cancelled.");
                return Ok(());
            }
        }
    }

    // Resolve problem ID: use provided value or prompt interactively
    let problem_id = match problem_input {
        Some(ref input) => ctx.resolve_problem(input)?,
        None => {
            // List open problems for interactive selection
            let problems = store.list_problems()?;
            let open_problems: Vec<_> = problems.into_iter().filter(|p| p.is_open()).collect();

            if open_problems.is_empty() {
                return Err(crate::error::JjjError::Validation("No open problems found. Create a problem first with: jjj problem new \"title\"".to_string()));
            }

            println!("Select a problem to address:\n");
            for (i, p) in open_problems.iter().enumerate() {
                println!("  {}. {} - {} [{}]", i + 1, p.id, p.title, p.priority);
            }
            print!("\nChoice [1-{}]: ", open_problems.len());
            io::stdout().flush()?;

            let mut input = String::new();
            io::stdin().read_line(&mut input)?;
            let choice: usize = input
                .trim()
                .parse()
                .map_err(|_| crate::error::JjjError::Validation("Invalid choice".to_string()))?;

            if choice < 1 || choice > open_problems.len() {
                return Err(crate::error::JjjError::Validation(
                    "Invalid selection".to_string(),
                ));
            }

            open_problems[choice - 1].id.clone()
        }
    };

    // Validate problem exists
    let _problem = store.load_problem(&problem_id)?;

    // Resolve supersedes if provided
    let supersedes = match supersedes_input {
        Some(ref input) => Some(ctx.resolve_solution(input)?),
        None => None,
    };

    // Get user for event
    let user = store.get_current_user()?;

    store.with_metadata(&format!("Start solution: {}", title), || {
        let solution_id = store.next_solution_id()?;
        let mut solution = Solution::new(solution_id.clone(), title.clone(), problem_id.clone());

        // Set supersedes
        solution.supersedes = supersedes.clone();

        // Set tags (trim, dedup, sort)
        if !tags.is_empty() {
            let mut t: Vec<String> = tags
                .iter()
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            t.sort();
            t.dedup();
            solution.tags = t;
        }

        // Create event for decision log
        let extra = EventExtra {
            problem: Some(problem_id.clone()),
            supersedes: supersedes.clone(),
            ..Default::default()
        };
        let event = Event::new(
            EventType::SolutionCreated,
            solution_id.clone(),
            user.clone(),
        )
        .with_extra(extra);
        store.set_pending_event(event);

        // Auto-attach: create jj change and link to solution
        jj_client.new_empty_change(&title)?;
        let change_id = jj_client.current_change_id()?;
        solution.attach_change(change_id);

        store.save_solution(&solution)?;

        // Auto-set jj change description
        let problem = store.load_problem(&solution.problem_id)?;
        let description = format!(
            "{}: {}\n\nProblem: {} - {}",
            solution.id, solution.title, problem.id, problem.title
        );
        if let Err(e) = store.jj_client.describe(&description) {
            eprintln!("Warning: Could not set jj description: {}", e);
        }

        // Create awaiting review critiques for each reviewer (from --reviewer flag)
        for reviewer_spec in &reviewer_critiques {
            let (reviewer_name, severity) = parse_reviewer_spec(reviewer_spec);
            let critique_id = store.next_critique_id()?;
            let mut critique = Critique::new(
                critique_id.clone(),
                format!("Awaiting review from @{}", reviewer_name),
                solution.id.clone(),
            );
            critique.reviewer = Some(reviewer_name.clone());
            critique.severity = severity;
            critique.author = solution.assignee.clone();
            store.save_critique(&critique)?;
            solution.critique_ids.push(critique_id);
        }

        // Re-save solution with critique IDs if we added any
        if !reviewer_critiques.is_empty() {
            store.save_solution(&solution)?;
        }

        // Update problem
        let mut problem = store.load_problem(&problem_id)?;
        problem.add_solution(solution_id.clone());
        if problem.status == ProblemStatus::Open {
            let _ = problem.try_set_status(ProblemStatus::InProgress);
        }
        store.save_problem(&problem)?;

        println!("Created solution {} ({})", solution.id, solution.title);
        println!("  Addresses: {} - {}", problem.id, problem.title);
        if let Some(ref sup) = solution.supersedes {
            println!("  Supersedes: {}", sup);
        }
        if !reviewer_critiques.is_empty() {
            let names: Vec<_> = reviewer_critiques
                .iter()
                .map(|s| format!("@{}", parse_reviewer_spec(s).0))
                .collect();
            println!("  Awaiting review: {}", names.join(", "));
        }

        Ok(())
    })
}

/// Parse a reviewer specification like "@bob" or "bob:high" into (name, severity)
fn parse_reviewer_spec(spec: &str) -> (String, CritiqueSeverity) {
    let spec = spec.trim_start_matches('@');
    if let Some((name, severity_str)) = spec.split_once(':') {
        let severity = severity_str.parse().unwrap_or(CritiqueSeverity::Low);
        (name.to_string(), severity)
    } else {
        (spec.to_string(), CritiqueSeverity::Low)
    }
}

#[allow(clippy::too_many_arguments)]
fn list_solutions(
    ctx: &CommandContext,
    problem_filter: Option<String>,
    status_filter: Option<String>,
    assignee_filter: Option<String>,
    search_query: Option<&str>,
    tag_filter: Option<String>,
    sort: &str,
    json: bool,
) -> Result<()> {
    let store = &ctx.store;

    let mut solutions = store.list_solutions()?;

    // Filter by problem (resolve the input first)
    if let Some(ref problem_input) = problem_filter {
        let problem_id = ctx.resolve_problem(problem_input)?;
        solutions.retain(|s| s.problem_id == problem_id);
    }

    // Filter by status
    if let Some(status_str) = status_filter {
        let status: SolutionStatus = status_str
            .parse()
            .map_err(|e: String| crate::error::JjjError::Validation(e))?;
        solutions.retain(|s| s.status == status);
    }

    // Filter by assignee (substring match)
    if let Some(ref assignee_pattern) = assignee_filter {
        let pattern = assignee_pattern.trim_start_matches('@').to_lowercase();
        solutions.retain(|s| {
            s.assignee
                .as_deref()
                .map(|a| a.to_lowercase().contains(&pattern))
                .unwrap_or(false)
        });
    }

    // Filter by tag (case-insensitive exact match)
    if let Some(ref tag_pattern) = tag_filter {
        let pattern = tag_pattern.to_lowercase();
        solutions.retain(|s| s.tags.iter().any(|t| t.to_lowercase() == pattern));
    }

    // Filter by search query using FTS (auto-populate DB if needed)
    if let Some(query) = search_query {
        let jj_client = ctx.jj();
        let db_path = jj_client.repo_root().join(".jj").join("jjj.db");
        let db = Database::open(&db_path)?;
        crate::db::load_from_markdown(&db, &ctx.store)?;
        let results = search::search(db.conn(), query, Some("solution"))?;
        let matching_ids: std::collections::HashSet<_> =
            results.iter().map(|r| r.entity_id.as_str()).collect();
        solutions.retain(|s| matching_ids.contains(s.id.as_str()));
    }

    // Sort
    match sort {
        "status" => solutions.sort_by(|a, b| a.status.cmp(&b.status)),
        "created" => solutions.sort_by(|a, b| b.created_at.cmp(&a.created_at)),
        "title" => solutions.sort_by(|a, b| a.title.to_lowercase().cmp(&b.title.to_lowercase())),
        _ => {} // default: no additional sort (UUID7 order)
    }

    if json {
        println!("{}", serde_json::to_string_pretty(&solutions)?);
        return Ok(());
    }

    if solutions.is_empty() {
        println!("No solutions found.");
        return Ok(());
    }

    // Calculate truncated prefixes for solutions
    let solution_uuids: Vec<&str> = solutions.iter().map(|s| s.id.as_str()).collect();
    let solution_prefixes = truncated_prefixes(&solution_uuids);

    // Calculate truncated prefixes for problems (for display)
    let problem_uuids: Vec<&str> = solutions.iter().map(|s| s.problem_id.as_str()).collect();
    let problem_prefixes = truncated_prefixes(&problem_uuids);

    println!("{:<10} {:<12} {:<10} TITLE", "ID", "STATUS", "PROBLEM");
    println!("{}", "-".repeat(70));

    for ((solution, (_, sol_prefix)), (_, prob_prefix)) in solutions
        .iter()
        .zip(solution_prefixes.iter())
        .zip(problem_prefixes.iter())
    {
        let status_icon = match solution.status {
            SolutionStatus::Proposed => " ",
            SolutionStatus::Submitted => ">",
            SolutionStatus::Approved => "+",
            SolutionStatus::Withdrawn => "x",
        };

        println!(
            "{:<10} {}{:<11} {:<10} {}",
            sol_prefix, status_icon, solution.status, prob_prefix, solution.title
        );
    }

    Ok(())
}

fn show_solution(ctx: &CommandContext, solution_input: String, json: bool) -> Result<()> {
    let store = &ctx.store;
    let solution_id = ctx.resolve_solution(&solution_input)?;

    let solution = store.load_solution(&solution_id)?;

    if json {
        println!("{}", serde_json::to_string_pretty(&solution)?);
        return Ok(());
    }

    println!("Solution: {} - {}", solution.id, solution.title);
    println!("Status: {}", solution.status);
    if solution.force_approved {
        println!("Force approved: yes");
    }
    println!("Addresses: {}", solution.problem_id);
    if let Some(ref sup) = solution.supersedes {
        println!("Supersedes: {}", sup);
    }

    if let Some(ref assignee) = solution.assignee {
        println!("Assignee: {}", assignee);
    }

    if !solution.tags.is_empty() {
        println!("Tags: {}", solution.tags.join(", "));
    }

    // Show attached changes
    if !solution.change_ids.is_empty() {
        println!("\n## Changes ({})", solution.change_ids.len());
        for change_id in &solution.change_ids {
            println!("  {}", change_id);
        }
    }

    // Show approach
    if !solution.approach.is_empty() {
        println!("\n## Approach\n{}", solution.approach);
    }

    // Show critiques
    let critiques = store.list_critiques_for_solution(&solution_id)?;
    if !critiques.is_empty() {
        println!("\n## Critiques ({})", critiques.len());
        for critique in &critiques {
            let status_icon = match critique.status {
                crate::models::CritiqueStatus::Open => "?",
                crate::models::CritiqueStatus::Addressed => "+",
                crate::models::CritiqueStatus::Valid => "!",
                crate::models::CritiqueStatus::Dismissed => "-",
            };
            println!(
                "  {} {} - {} [{}, {}]",
                status_icon, critique.id, critique.title, critique.status, critique.severity
            );
        }
    }

    println!(
        "\nCreated: {}",
        solution.created_at.format("%Y-%m-%d %H:%M")
    );
    println!("Updated: {}", solution.updated_at.format("%Y-%m-%d %H:%M"));

    crate::commands::show_related_items(ctx, "solution", &solution.id)?;

    Ok(())
}

fn edit_solution(
    ctx: &CommandContext,
    solution_input: String,
    title: Option<String>,
    status: Option<String>,
    add_tag: Option<String>,
    remove_tag: Option<String>,
    set_tags: Option<Vec<String>>,
) -> Result<()> {
    let store = &ctx.store;
    let solution_id = ctx.resolve_solution(&solution_input)?;

    store.with_metadata(&format!("Edit solution {}", solution_id), || {
        let mut solution = store.load_solution(&solution_id)?;

        if let Some(new_title) = title {
            solution.title = new_title;
        }

        if let Some(status_str) = status {
            let new_status: SolutionStatus = status_str
                .parse()
                .map_err(|e: String| crate::error::JjjError::Validation(e))?;
            solution
                .try_set_status(new_status)
                .map_err(crate::error::JjjError::Validation)?;
        }

        if let Some(ref tags) = set_tags {
            let mut t: Vec<String> = tags
                .iter()
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect();
            t.sort();
            t.dedup();
            solution.tags = t;
        }

        if let Some(ref tag) = add_tag {
            let tag = tag.trim().to_string();
            if !tag.is_empty()
                && !solution
                    .tags
                    .iter()
                    .any(|t| t.to_lowercase() == tag.to_lowercase())
            {
                solution.tags.push(tag);
                solution.tags.sort();
            }
        }

        if let Some(ref tag) = remove_tag {
            let tag_lower = tag.trim().to_lowercase();
            solution.tags.retain(|t| t.to_lowercase() != tag_lower);
        }

        store.save_solution(&solution)?;
        println!("Updated solution {}", solution_id);
        Ok(())
    })
}

fn attach_change(ctx: &CommandContext, solution_input: String, force: bool) -> Result<()> {
    let store = &ctx.store;
    let solution_id = ctx.resolve_solution(&solution_input)?;

    let jj_client = ctx.jj();

    let change_id = jj_client.current_change_id()?;

    // Validate change exists in jj
    if !force {
        if !jj_client.change_exists(&change_id)? {
            return Err(crate::error::JjjError::Validation(format!(
                "Change '{}' not found in repository. Use --force to skip validation.",
                change_id
            )));
        }

        // Check no other solution already has this change attached
        let all_solutions = store.list_solutions()?;
        for other in &all_solutions {
            if other.id != solution_id && other.change_ids.contains(&change_id) {
                return Err(crate::error::JjjError::Validation(format!(
                    "Change '{}' is already attached to solution {}. Use --force to attach anyway.",
                    change_id, other.id
                )));
            }
        }
    }

    store.with_metadata(
        &format!("Attach change {} to solution {}", change_id, solution_id),
        || {
            let mut solution = store.load_solution(&solution_id)?;
            solution.attach_change(change_id.clone());
            store.save_solution(&solution)?;
            println!("Attached change {} to solution {}", change_id, solution_id);
            Ok(())
        },
    )
}

fn detach_change(
    ctx: &CommandContext,
    solution_input: String,
    change_id: Option<String>,
    force: bool,
) -> Result<()> {
    let store = &ctx.store;
    let solution_id = ctx.resolve_solution(&solution_input)?;

    let jj_client = ctx.jj();

    let change_id = match change_id {
        Some(id) => id,
        None => jj_client.current_change_id()?,
    };

    // Safety checks
    if !force {
        let solution = store.load_solution(&solution_id)?;

        // Block detach from Review solutions
        if solution.status == SolutionStatus::Submitted {
            return Err(crate::error::JjjError::Validation(format!(
                "Cannot detach change from solution {} while in Submitted state. Use --force to override.",
                solution_id
            )));
        }

        // Block detach of last change
        if solution.change_ids.len() <= 1 && solution.change_ids.contains(&change_id) {
            return Err(crate::error::JjjError::Validation(format!(
                "Cannot detach the last change from solution {}. Use --force to override.",
                solution_id
            )));
        }
    }

    store.with_metadata(
        &format!("Detach change {} from solution {}", change_id, solution_id),
        || {
            let mut solution = store.load_solution(&solution_id)?;

            if solution.detach_change(&change_id) {
                store.save_solution(&solution)?;
                println!(
                    "Detached change {} from solution {} ({} change(s) remaining)",
                    change_id,
                    solution_id,
                    solution.change_ids.len()
                );
            } else {
                println!(
                    "Change {} was not attached to solution {}",
                    change_id, solution_id
                );
            }
            Ok(())
        },
    )
}

fn submit_solution(ctx: &CommandContext, solution_input: String) -> Result<()> {
    let solution_id = ctx.resolve_solution(&solution_input)?;
    crate::domain::submit_solution(&ctx.store, &solution_id)?;
    println!("Solution {} submitted for review", solution_id);
    Ok(())
}

fn approve_solution(
    ctx: &CommandContext,
    solution_input: Option<String>,
    force: bool,
    rationale: Option<String>,
    no_rationale: bool,
) -> Result<()> {
    use crate::sync::SyncProvider as _;

    let store = &ctx.store;
    let jj_client = ctx.jj();

    let solution = if let Some(input) = solution_input {
        let id = ctx.resolve_solution(&input)?;
        store.load_solution(&id)?
    } else {
        let change_id = jj_client.current_change_id()?;
        let solutions = store.list_solutions()?;
        match solutions
            .into_iter()
            .find(|s| s.change_ids.contains(&change_id))
        {
            Some(s) => s,
            None => {
                return Err(crate::error::JjjError::Validation(
                    "No solution found for current change. Specify a solution: jjj solution approve <title-or-id>".to_string(),
                ));
            }
        }
    };

    if solution.status == SolutionStatus::Approved {
        return Err(crate::error::JjjError::Validation(format!(
            "Solution '{}' is already approved.",
            solution.title,
        )));
    }

    if solution.status == SolutionStatus::Proposed && !force {
        return Err(crate::error::JjjError::Validation(format!(
            "Solution '{}' is proposed — submit it for review first:\n  jjj solution submit {}",
            solution.title, solution.id,
        )));
    }

    // Core approval: critique check, events, auto-solve, automation.
    let rationale_str = rationale.as_deref().filter(|_| !no_rationale);
    crate::domain::approve_solution(store, &solution.id, force, rationale_str)?;
    println!("Solution '{}' approved.", solution.title);

    // Merge PR if one is linked.
    if let Some(pr_number) = solution.github_pr {
        let config = store.load_config()?;
        let repo_root = jj_client.repo_root();
        let provider = crate::sync::github::GitHubProvider::from_config(repo_root, &config.github)?;
        provider.merge_pr(pr_number)?;
        println!("  Merged PR #{}", pr_number);
    }

    Ok(())
}


fn withdraw_solution(
    ctx: &CommandContext,
    solution_input: String,
    rationale: Option<String>,
    no_rationale: bool,
) -> Result<()> {
    let solution_id = ctx.resolve_solution(&solution_input)?;

    // Get rationale (prompt if not provided and not skipped)
    let rationale = if let Some(r) = rationale {
        Some(r)
    } else if no_rationale {
        None
    } else {
        print!("Rationale (optional, press Enter to skip): ");
        io::stdout().flush()?;
        let mut input = String::new();
        io::stdin().read_line(&mut input)?;
        let trimmed = input.trim();
        if trimmed.is_empty() {
            None
        } else {
            Some(trimmed.to_string())
        }
    };

    crate::domain::withdraw_solution(&ctx.store, &solution_id, rationale.as_deref())?;
    println!("Solution {} withdrawn", solution_id);
    Ok(())
}

fn assign_solution(
    ctx: &CommandContext,
    solution_input: String,
    assignee: Option<String>,
) -> Result<()> {
    let store = &ctx.store;
    let solution_id = ctx.resolve_solution(&solution_input)?;

    let assignee_name = match assignee {
        Some(name) => name,
        None => store.jj_client.user_identity()?,
    };

    store.with_metadata(
        &format!("Assign solution {} to {}", solution_id, assignee_name),
        || {
            let mut solution = store.load_solution(&solution_id)?;
            solution.assignee = Some(assignee_name.clone());
            store.save_solution(&solution)?;
            println!("Solution {} assigned to {}", solution_id, assignee_name);
            Ok(())
        },
    )
}

fn resume_solution(ctx: &CommandContext, solution_input: String) -> Result<()> {
    let store = &ctx.store;
    let solution_id = ctx.resolve_solution(&solution_input)?;

    let jj_client = ctx.jj();

    let solution = store.load_solution(&solution_id)?;
    println!("Resuming solution {} ({})", solution.id, solution.title);

    // Check if solution has an active change attached
    if let Some(change_id) = solution.change_ids.last() {
        println!("Switching to change {}", change_id);
        jj_client.edit(change_id)?;
    } else {
        println!("No active change for solution. Creating new change.");

        // Build event before with_metadata so automation gets the same event
        let resume_user = store.get_current_user().unwrap_or_default();
        let resume_event = Event::new(
            EventType::SolutionSubmitted,
            solution_id.to_string(),
            resume_user,
        )
        .with_extra(EventExtra {
            problem: Some(solution.problem_id.clone()),
            ..Default::default()
        });

        store.with_metadata(&format!("Resume solution: {}", solution.title), || {
            jj_client.new_empty_change(&solution.title)?;
            let change_id = jj_client.current_change_id()?;

            let mut solution = store.load_solution(&solution_id)?;
            solution.attach_change(change_id);
            solution
                .submit()
                .map_err(crate::error::JjjError::Validation)?;
            store.save_solution(&solution)?;

            store.set_pending_event(resume_event.clone());

            // Update problem status
            let mut problem = store.load_problem(&solution.problem_id)?;
            if problem.status == ProblemStatus::Open {
                let _ = problem.try_set_status(ProblemStatus::InProgress);
                store.save_problem(&problem)?;
            }

            Ok(())
        })?;

        crate::automation::run(store, &resume_event, &solution_id);
    }

    Ok(())
}

fn lgtm_solution(ctx: &CommandContext, solution_input: String) -> Result<()> {
    let store = &ctx.store;
    let solution_id = ctx.resolve_solution(&solution_input)?;

    let current_user = store.get_current_user()?;

    let solution = store.load_solution(&solution_id)?;
    let critiques = store.list_critiques_for_solution(&solution_id)?;

    // Find an open review critique assigned to (or matching) the current user
    let my_review = critiques.iter().find(|c| {
        c.status == CritiqueStatus::Open
            && c.reviewer
                .as_ref()
                .is_some_and(|r| r.contains(&current_user) || current_user.contains(r.as_str()))
    });

    let critique = match my_review {
        Some(c) => c,
        None => {
            // Check if there are any open review critiques at all (assigned to others)
            let any_review = critiques
                .iter()
                .any(|c| c.status == CritiqueStatus::Open && c.reviewer.is_some());
            if any_review {
                return Err(crate::error::JjjError::Validation(format!(
                    "No open review critique assigned to you on '{}'.\n\
                     (There are review critiques assigned to others — are you the right reviewer?)\n\n\
                     To add yourself: jjj critique new \"{}\" \"Review\" --reviewer @{}",
                    solution.title, solution_input, current_user
                )));
            } else {
                return Err(crate::error::JjjError::Validation(format!(
                    "No review critique assigned to you on '{}'.\n\n\
                     To request review from yourself: jjj critique new \"{}\" \"Review\" --reviewer @{}\n\
                     Or use solution new --reviewer @{} when creating solutions.",
                    solution.title, solution_input, current_user, current_user
                )));
            }
        }
    };

    let critique_id = critique.id.clone();
    crate::domain::address_critique(store, &critique_id)?;
    println!("Signed off on '{}' as @{}", solution.title, current_user);

    // Check if this was the last blocking item
    let remaining = store
        .list_critiques_for_solution(&solution_id)?
        .into_iter()
        .filter(|c| c.status == CritiqueStatus::Open || c.status == CritiqueStatus::Valid)
        .count();

    if remaining == 0 {
        println!("All critiques resolved. Ready to approve:");
        println!("  jjj solution approve \"{}\"", solution.title);
    } else {
        println!("{} critique(s) still open.", remaining);
    }

    Ok(())
}

fn comment_solution(
    ctx: &CommandContext,
    solution_input: Option<String>,
    critique_input: Option<String>,
    body: Option<String>,
) -> Result<()> {
    let store = &ctx.store;

    // Resolve solution — use explicit input or fall back to the change attached to @
    let solution_id = if let Some(ref input) = solution_input {
        ctx.resolve_solution(input)?
    } else {
        // Try active change first
        let change_id = ctx
            .jj()
            .execute(&["log", "-r", "@", "-T", "change_id", "--no-graph"])
            .unwrap_or_default();
        let change_id = change_id.trim();

        let solutions = store.list_solutions()?;
        let by_change = solutions
            .iter()
            .find(|s| s.change_ids.iter().any(|c| c == change_id));

        if let Some(s) = by_change {
            s.id.clone()
        } else {
            // Fall back to any active solution
            let active: Vec<_> = solutions.iter().filter(|s| s.is_active()).collect();
            match active.len() {
                0 => {
                    return Err(crate::error::JjjError::Validation(
                        "No active solution found. Specify a solution ID.".to_string(),
                    ))
                }
                1 => active[0].id.clone(),
                _ => {
                    return Err(crate::error::JjjError::Validation(format!(
                        "Multiple active solutions. Specify one:\n{}",
                        active
                            .iter()
                            .map(|s| format!("  jjj solution comment \"{}\"", s.title))
                            .collect::<Vec<_>>()
                            .join("\n")
                    )))
                }
            }
        }
    };

    // Get open critiques for the solution
    let critiques: Vec<_> = store
        .list_critiques_for_solution(&solution_id)?
        .into_iter()
        .filter(|c| c.status == CritiqueStatus::Open || c.status == CritiqueStatus::Valid)
        .collect();

    if critiques.is_empty() {
        return Err(crate::error::JjjError::Validation(
            "No open critiques on this solution to reply to.".to_string(),
        ));
    }

    // Resolve critique — explicit, single, or interactive picker
    let critique_id = if let Some(ref input) = critique_input {
        // Resolve by prefix/title within this solution's critiques
        let resolved = ctx.resolve_critique(input)?;
        // Verify it belongs to this solution
        if !critiques.iter().any(|c| c.id == resolved) {
            return Err(crate::error::JjjError::Validation(format!(
                "Critique '{}' is not an open critique for this solution.",
                input
            )));
        }
        resolved
    } else if critiques.len() == 1 {
        critiques[0].id.clone()
    } else {
        // Interactive picker
        println!("Open critiques:");
        for (i, c) in critiques.iter().enumerate() {
            println!("  [{}] {} [{}]", i + 1, c.title, c.severity);
        }
        print!("Select [1-{}]: ", critiques.len());
        io::stdout().flush()?;
        let mut line = String::new();
        io::stdin().read_line(&mut line)?;
        let idx: usize = line.trim().parse().unwrap_or(0);
        critiques
            .get(idx.saturating_sub(1))
            .filter(|_| idx > 0)
            .ok_or_else(|| crate::error::JjjError::Validation("Invalid selection.".to_string()))?
            .id
            .clone()
    };

    // Get reply body — positional arg or prompt
    let reply_body = if let Some(b) = body {
        b
    } else {
        print!("Reply: ");
        io::stdout().flush()?;
        let mut line = String::new();
        io::stdin().read_line(&mut line)?;
        let b = line.trim().to_string();
        if b.is_empty() {
            return Err(crate::error::JjjError::Validation(
                "Reply cannot be empty.".to_string(),
            ));
        }
        b
    };

    let user = store.get_current_user()?;
    store.with_metadata(&format!("Reply to critique {}", critique_id), || {
        let mut critique = store.load_critique(&critique_id)?;
        critique.add_reply(user.clone(), reply_body.clone());
        store.save_critique(&critique)?;

        let event = Event::new(
            EventType::CritiqueReplied,
            critique_id.clone(),
            user.clone(),
        )
        .with_extra(EventExtra {
            target: Some(solution_id.clone()),
            ..Default::default()
        });
        store.set_pending_event(event);

        println!("Replied to critique '{}'.", critique.title);
        Ok(())
    })
}

fn check_for_similar_solutions(
    ctx: &CommandContext,
    title: &str,
) -> Result<Option<Vec<search::SimilarityResult>>> {
    let jj_client = ctx.jj();
    let repo_root = jj_client.repo_root();
    let db_path = repo_root.join(".jj").join("jjj.db");

    if !db_path.exists() {
        return Ok(None);
    }

    let local_config = LocalConfig::load(repo_root);
    if !local_config.duplicate_check_enabled() {
        return Ok(None);
    }

    let client = match EmbeddingClient::from_config(&local_config, false) {
        Some(c) => c,
        None => return Ok(None),
    };

    let db = Database::open(&db_path)?;
    let conn = db.conn();

    // Embed the title
    let embedding = match client.embed(title) {
        Ok(e) => e,
        Err(_) => return Ok(None),
    };

    // Find similar solutions
    let threshold = local_config.duplicate_threshold();
    let results = search::similarity_search(conn, &embedding, Some("solution"), None, 5)?;
    let similar: Vec<_> = results
        .into_iter()
        .filter(|r| r.similarity >= threshold)
        .collect();

    if similar.is_empty() {
        Ok(None)
    } else {
        Ok(Some(similar))
    }
}

fn prompt_create_solution_anyway(similar: &[search::SimilarityResult]) -> Result<bool> {
    println!("\nSimilar existing solutions found:\n");
    for result in similar {
        println!(
            "  s/{}  [{:.2}]  \"{}\"",
            short_id(&result.entity_id),
            result.similarity,
            result.title
        );
    }
    println!();

    print!("Create anyway? [y/N] ");
    io::stdout().flush()?;

    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    let input = input.trim().to_lowercase();

    Ok(input == "y" || input == "yes")
}

fn diff_solution(ctx: &CommandContext, solution_input: String) -> Result<()> {
    let solution_id = ctx.resolve_solution(&solution_input)?;
    let solution = ctx.store.load_solution(&solution_id)?;

    if solution.change_ids.is_empty() {
        println!("No change IDs attached to this solution.");
        return Ok(());
    }

    let jj_client = ctx.jj();
    for change_id in &solution.change_ids {
        println!("=== Change: {} ===", change_id);
        match jj_client.show_diff(change_id) {
            Ok(diff) => println!("{}", diff),
            Err(_) => println!("  (change {} not available in this repo)", change_id),
        }
    }

    Ok(())
}