jjj 0.3.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
use super::super::next_actions::EntityType;
use super::{App, InputAction, InputMode};
use crate::error::Result;
use crate::models::{CritiqueStatus, Event, EventExtra, EventType, ProblemStatus};

impl App {
    pub(super) fn create_problem(
        &mut self,
        title: &str,
        milestone_id: Option<String>,
    ) -> Result<()> {
        use crate::id::generate_id;
        use crate::models::Problem;

        let id = generate_id();
        let mut problem = Problem::new(id.clone(), title.to_string());
        problem.milestone_id = milestone_id;

        self.store
            .with_metadata(&format!("Create problem: {}", title), || {
                self.store.save_problem(&problem)
            })?;

        self.show_flash(&format!("Created {}", id));
        self.refresh_data()?;
        Ok(())
    }

    pub(super) fn create_solution(&mut self, title: &str, problem_id: &str) -> Result<()> {
        use crate::id::generate_id;
        use crate::models::Solution;

        let id = generate_id();
        let solution = Solution::new(id.clone(), title.to_string(), problem_id.to_string());

        self.store
            .with_metadata(&format!("Create solution: {}", title), || {
                self.store.save_solution(&solution)
            })?;

        self.show_flash(&format!("Created {}", id));
        self.refresh_data()?;
        Ok(())
    }

    pub(super) fn create_critique(&mut self, title: &str, solution_id: &str) -> Result<()> {
        use crate::id::generate_id;
        use crate::models::Critique;

        let id = generate_id();
        let critique = Critique::new(id.clone(), title.to_string(), solution_id.to_string());

        self.store
            .with_metadata(&format!("Create critique: {}", title), || {
                self.store.save_critique(&critique)
            })?;

        self.show_flash(&format!("Created {}", id));
        self.refresh_data()?;
        Ok(())
    }

    pub(super) fn update_title(
        &mut self,
        entity_type: &EntityType,
        entity_id: &str,
        new_title: &str,
    ) -> Result<()> {
        match entity_type {
            EntityType::Problem => {
                self.store.with_metadata(
                    &format!("Update problem title: {}", new_title),
                    || {
                        let mut problem = self.store.load_problem(entity_id)?;
                        problem.title = new_title.to_string();
                        self.store.save_problem(&problem)
                    },
                )?;
            }
            EntityType::Solution => {
                self.store.with_metadata(
                    &format!("Update solution title: {}", new_title),
                    || {
                        let mut solution = self.store.load_solution(entity_id)?;
                        solution.title = new_title.to_string();
                        self.store.save_solution(&solution)
                    },
                )?;
            }
            EntityType::Critique => {
                self.store.with_metadata(
                    &format!("Update critique title: {}", new_title),
                    || {
                        let mut critique = self.store.load_critique(entity_id)?;
                        critique.title = new_title.to_string();
                        self.store.save_critique(&critique)
                    },
                )?;
            }
            EntityType::Milestone => {
                self.store.with_metadata(
                    &format!("Update milestone title: {}", new_title),
                    || {
                        let mut milestone = self.store.load_milestone(entity_id)?;
                        milestone.title = new_title.to_string();
                        self.store.save_milestone(&milestone)
                    },
                )?;
            }
        }
        self.show_flash(&format!("Updated title: {}", new_title));
        self.refresh_data()?;
        Ok(())
    }

    pub(super) fn start_new_item(&mut self) -> Result<()> {
        use super::super::tree::TreeNode;

        let (prompt, action) = if let Some(item) = self.cache.tree_items.get(self.ui.tree_index) {
            match &item.node {
                TreeNode::ProjectRoot { .. } => (
                    "New milestone title: ".to_string(),
                    InputAction::NewMilestone,
                ),
                TreeNode::Milestone { id, .. } => (
                    "New problem title: ".to_string(),
                    InputAction::NewProblem {
                        milestone_id: Some(id.clone()),
                    },
                ),
                TreeNode::Backlog { .. } => (
                    "New problem title: ".to_string(),
                    InputAction::NewProblem { milestone_id: None },
                ),
                TreeNode::Problem { id, .. } => (
                    "New solution title: ".to_string(),
                    InputAction::NewSolution {
                        problem_id: id.clone(),
                    },
                ),
                TreeNode::Solution { id, .. } => (
                    "New critique title: ".to_string(),
                    InputAction::NewCritique {
                        solution_id: id.clone(),
                    },
                ),
                TreeNode::Critique { .. } => return Ok(()),
            }
        } else {
            return Ok(());
        };

        self.ui.input_mode = InputMode::Input {
            prompt,
            buffer: String::new(),
            action,
            cursor_pos: 0,
        };
        Ok(())
    }

    pub(super) fn start_edit_title(&mut self) -> Result<()> {
        use super::super::tree::TreeNode;

        let (prompt, action, current_title) =
            if let Some(item) = self.cache.tree_items.get(self.ui.tree_index) {
                match &item.node {
                    TreeNode::Problem { id, title, .. } => (
                        "Edit title: ".to_string(),
                        InputAction::EditTitle {
                            entity_type: EntityType::Problem,
                            entity_id: id.clone(),
                        },
                        title.clone(),
                    ),
                    TreeNode::Solution { id, title, .. } => (
                        "Edit title: ".to_string(),
                        InputAction::EditTitle {
                            entity_type: EntityType::Solution,
                            entity_id: id.clone(),
                        },
                        title.clone(),
                    ),
                    TreeNode::Critique { id, title, .. } => (
                        "Edit title: ".to_string(),
                        InputAction::EditTitle {
                            entity_type: EntityType::Critique,
                            entity_id: id.clone(),
                        },
                        title.clone(),
                    ),
                    TreeNode::Milestone { id, title, .. } => (
                        "Edit title: ".to_string(),
                        InputAction::EditTitle {
                            entity_type: EntityType::Milestone,
                            entity_id: id.clone(),
                        },
                        title.clone(),
                    ),
                    _ => return Ok(()),
                }
            } else {
                return Ok(());
            };

        let cursor_pos = current_title.len();
        self.ui.input_mode = InputMode::Input {
            prompt,
            buffer: current_title,
            action,
            cursor_pos,
        };
        Ok(())
    }

    pub(super) fn start_edit_tags(&mut self) -> Result<()> {
        use super::super::tree::TreeNode;

        let (prompt, action, current_tags) =
            if let Some(item) = self.cache.tree_items.get(self.ui.tree_index) {
                match &item.node {
                    TreeNode::Problem { id, .. } => {
                        let problem = self.store.load_problem(id)?;
                        (
                            "Tags (comma-separated): ".to_string(),
                            InputAction::EditTags {
                                entity_type: EntityType::Problem,
                                entity_id: id.clone(),
                            },
                            problem.tags.join(", "),
                        )
                    }
                    TreeNode::Solution { id, .. } => {
                        let solution = self.store.load_solution(id)?;
                        (
                            "Tags (comma-separated): ".to_string(),
                            InputAction::EditTags {
                                entity_type: EntityType::Solution,
                                entity_id: id.clone(),
                            },
                            solution.tags.join(", "),
                        )
                    }
                    _ => return Ok(()),
                }
            } else {
                return Ok(());
            };

        let cursor_pos = current_tags.len();
        self.ui.input_mode = InputMode::Input {
            prompt,
            buffer: current_tags,
            action,
            cursor_pos,
        };
        Ok(())
    }

    pub(super) fn update_tags(
        &mut self,
        entity_type: &EntityType,
        entity_id: &str,
        input: &str,
    ) -> Result<()> {
        let mut tags: Vec<String> = input
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();
        // Case-insensitive dedup
        let mut seen = std::collections::HashSet::new();
        tags.retain(|t| seen.insert(t.to_lowercase()));
        tags.sort();

        match entity_type {
            EntityType::Problem => {
                self.store
                    .with_metadata(&format!("Update problem tags: {}", entity_id), || {
                        let mut problem = self.store.load_problem(entity_id)?;
                        problem.tags = tags.clone();
                        self.store.save_problem(&problem)
                    })?;
            }
            EntityType::Solution => {
                self.store.with_metadata(
                    &format!("Update solution tags: {}", entity_id),
                    || {
                        let mut solution = self.store.load_solution(entity_id)?;
                        solution.tags = tags.clone();
                        self.store.save_solution(&solution)
                    },
                )?;
            }
            EntityType::Critique | EntityType::Milestone => return Ok(()),
        }
        self.show_flash("Tags updated");
        self.refresh_data()?;
        Ok(())
    }

    pub(super) fn handle_action_a(&mut self) -> Result<()> {
        if let Some((id, entity_type)) = self.get_selected_entity() {
            match entity_type {
                EntityType::Solution => self.approve_solution(&id)?,
                EntityType::Critique => self.address_critique(&id)?,
                EntityType::Problem | EntityType::Milestone => {}
            }
        }
        Ok(())
    }

    pub(super) fn handle_action_u(&mut self) -> Result<()> {
        if let Some((id, entity_type)) = self.get_selected_entity() {
            if entity_type == EntityType::Solution {
                self.submit_solution(&id)?;
            }
        }
        Ok(())
    }

    pub(super) fn handle_action_d(&mut self) -> Result<()> {
        use super::super::tree::TreeNode;
        use crate::models::{MilestoneStatus, ProblemStatus};

        // Extract action info from the selected tree item (clone to release borrow)
        enum DeclineAction {
            DismissCritique(String),
            WithdrawSolution(String),
            DissolveProblem(String),
            CancelMilestone(String),
            None,
        }

        let action = if let Some(item) = self.cache.tree_items.get(self.ui.tree_index) {
            match &item.node {
                TreeNode::Critique { id, .. } => DeclineAction::DismissCritique(id.clone()),
                TreeNode::Solution { id, .. } => DeclineAction::WithdrawSolution(id.clone()),
                TreeNode::Problem { id, status, .. } => {
                    if matches!(status, ProblemStatus::Open | ProblemStatus::InProgress) {
                        DeclineAction::DissolveProblem(id.clone())
                    } else {
                        DeclineAction::None
                    }
                }
                TreeNode::Milestone { id, status, .. } => {
                    if matches!(status, MilestoneStatus::Planning | MilestoneStatus::Active) {
                        DeclineAction::CancelMilestone(id.clone())
                    } else {
                        DeclineAction::None
                    }
                }
                _ => DeclineAction::None,
            }
        } else {
            DeclineAction::None
        };

        match action {
            DeclineAction::DismissCritique(id) => {
                self.dismiss_critique(&id)?;
            }
            DeclineAction::WithdrawSolution(id) => {
                self.withdraw_solution(&id)?;
            }
            DeclineAction::DissolveProblem(id) => {
                self.ui.input_mode = super::InputMode::Input {
                    prompt: "Dissolve reason: ".to_string(),
                    buffer: String::new(),
                    action: super::InputAction::DissolveP { problem_id: id },
                    cursor_pos: 0,
                };
            }
            DeclineAction::CancelMilestone(id) => {
                let id_clone = id.clone();
                match self
                    .store
                    .with_metadata(&format!("Cancel milestone {}", id), || {
                        let mut milestone = self.store.load_milestone(&id_clone)?;
                        milestone.set_status(MilestoneStatus::Cancelled);
                        self.store.save_milestone(&milestone)
                    }) {
                    Ok(_) => {
                        self.show_flash(&format!("{} cancelled", id_clone));
                        self.refresh_data()?;
                    }
                    Err(e) => {
                        self.show_flash(&format!("Error: {}", e));
                    }
                }
            }
            DeclineAction::None => {}
        }
        Ok(())
    }

    pub(super) fn handle_action_s(&mut self) -> Result<()> {
        use crate::models::{MilestoneStatus, ProblemStatus};

        if let Some((id, entity_type)) = self.get_selected_entity() {
            match entity_type {
                EntityType::Problem => {
                    let id_clone = id.clone();
                    match self
                        .store
                        .with_metadata(&format!("Solve problem {}", id), || {
                            let mut problem = self.store.load_problem(&id)?;
                            problem.set_status(ProblemStatus::Solved);
                            self.store.save_problem(&problem)
                        }) {
                        Ok(_) => {
                            self.show_flash(&format!("{} solved", id_clone));
                            self.refresh_data()?;
                        }
                        Err(e) => {
                            self.show_flash(&format!("Error: {}", e));
                        }
                    }
                }
                EntityType::Milestone => {
                    let id_clone = id.clone();
                    match self
                        .store
                        .with_metadata(&format!("Complete milestone {}", id), || {
                            let mut milestone = self.store.load_milestone(&id)?;
                            milestone.set_status(MilestoneStatus::Completed);
                            self.store.save_milestone(&milestone)
                        }) {
                        Ok(_) => {
                            self.show_flash(&format!("{} completed", id_clone));
                            self.refresh_data()?;
                        }
                        Err(e) => {
                            self.show_flash(&format!("Error: {}", e));
                        }
                    }
                }
                _ => {}
            }
        }
        Ok(())
    }

    pub(super) fn handle_action_o(&mut self) -> Result<()> {
        use crate::models::{MilestoneStatus, ProblemStatus};

        if let Some((id, entity_type)) = self.get_selected_entity() {
            match entity_type {
                EntityType::Problem => {
                    let id_clone = id.clone();
                    match self
                        .store
                        .with_metadata(&format!("Reopen problem {}", id), || {
                            let mut problem = self.store.load_problem(&id)?;
                            problem.set_status(ProblemStatus::Open);
                            self.store.save_problem(&problem)
                        }) {
                        Ok(_) => {
                            self.show_flash(&format!("{} reopened", id_clone));
                            self.refresh_data()?;
                        }
                        Err(e) => {
                            self.show_flash(&format!("Error: {}", e));
                        }
                    }
                }
                EntityType::Milestone => {
                    let id_clone = id.clone();
                    match self
                        .store
                        .with_metadata(&format!("Activate milestone {}", id), || {
                            let mut milestone = self.store.load_milestone(&id)?;
                            milestone.set_status(MilestoneStatus::Active);
                            self.store.save_milestone(&milestone)
                        }) {
                        Ok(_) => {
                            self.show_flash(&format!("{} activated", id_clone));
                            self.refresh_data()?;
                        }
                        Err(e) => {
                            self.show_flash(&format!("Error: {}", e));
                        }
                    }
                }
                _ => {}
            }
        }
        Ok(())
    }

    pub(super) fn handle_action_v(&mut self) -> Result<()> {
        if let Some((id, entity_type)) = self.get_selected_entity() {
            if entity_type == EntityType::Critique {
                let id_clone = id.clone();
                match self
                    .store
                    .with_metadata(&format!("Validate critique {}", id), || {
                        let mut critique = self.store.load_critique(&id)?;
                        critique.validate();
                        self.store.save_critique(&critique)
                    }) {
                    Ok(_) => {
                        self.show_flash(&format!("{} validated", id_clone));
                        self.refresh_data()?;
                    }
                    Err(e) => {
                        self.show_flash(&format!("Error: {}", e));
                    }
                }
            }
        }
        Ok(())
    }

    fn approve_solution(&mut self, solution_id: &str) -> Result<()> {
        // Block if there are open critiques
        let open_critiques = self
            .store
            .list_critiques()
            .unwrap_or_default()
            .into_iter()
            .filter(|c| c.solution_id == solution_id && c.status == CritiqueStatus::Open)
            .count();
        if open_critiques > 0 {
            self.show_flash(&format!(
                "Blocked: {} open critique(s) must be resolved first",
                open_critiques
            ));
            return Ok(());
        }

        let id = solution_id.to_string();
        let user = self
            .store
            .get_current_user()
            .unwrap_or_else(|_| "unknown".to_string());
        match self
            .store
            .with_metadata(&format!("Approve solution {}", solution_id), || {
                let event = Event::new(
                    EventType::SolutionApproved,
                    solution_id.to_string(),
                    user.clone(),
                );
                self.store.set_pending_event(event.clone());
                let mut solution = self.store.load_solution(solution_id)?;
                solution.approve();
                self.store.save_solution(&solution)?;
                // Auto-solve problem
                let (can_solve, _) = self.store.can_solve_problem(&solution.problem_id)?;
                if can_solve {
                    let mut problem = self.store.load_problem(&solution.problem_id)?;
                    if problem.status != ProblemStatus::Solved {
                        problem.set_status(ProblemStatus::Solved);
                        self.store.save_problem(&problem)?;
                        let solve_event =
                            Event::new(EventType::ProblemSolved, problem.id.clone(), user.clone());
                        self.store.set_pending_event(solve_event);
                    }
                }
                Ok(())
            }) {
            Ok(_) => {
                self.show_flash(&format!("{} approved", id));
                self.refresh_data()?;
            }
            Err(e) => {
                self.show_flash(&format!("Error: {}", e));
            }
        }
        Ok(())
    }

    fn withdraw_solution(&mut self, solution_id: &str) -> Result<()> {
        let id = solution_id.to_string();
        match self
            .store
            .with_metadata(&format!("Withdraw solution {}", solution_id), || {
                let mut solution = self.store.load_solution(solution_id)?;
                solution.withdraw();
                self.store.save_solution(&solution)?;
                Ok(())
            }) {
            Ok(_) => {
                self.show_flash(&format!("{} withdrawn", id));
                self.refresh_data()?;
            }
            Err(e) => {
                self.show_flash(&format!("Error: {}", e));
            }
        }
        Ok(())
    }

    fn submit_solution(&mut self, solution_id: &str) -> Result<()> {
        let id = solution_id.to_string();
        let user = self
            .store
            .get_current_user()
            .unwrap_or_else(|_| "unknown".to_string());
        match self.store.with_metadata(
            &format!("Submit solution {} for review", solution_id),
            || {
                let mut solution = self.store.load_solution(solution_id)?;
                solution.submit();
                self.store.save_solution(&solution)?;
                let event = Event::new(
                    EventType::SolutionSubmitted,
                    solution_id.to_string(),
                    user.clone(),
                )
                .with_extra(EventExtra {
                    problem: Some(solution.problem_id.clone()),
                    ..Default::default()
                });
                self.store.set_pending_event(event);
                // Auto-set problem to InProgress if it's Open
                let mut problem = self.store.load_problem(&solution.problem_id)?;
                if problem.status == ProblemStatus::Open {
                    problem.set_status(ProblemStatus::InProgress);
                    self.store.save_problem(&problem)?;
                }
                Ok(())
            },
        ) {
            Ok(_) => {
                self.show_flash(&format!("{} submitted for review", id));
                self.refresh_data()?;
            }
            Err(e) => {
                self.show_flash(&format!("Error: {}", e));
            }
        }
        Ok(())
    }

    fn address_critique(&mut self, critique_id: &str) -> Result<()> {
        let id = critique_id.to_string();
        match self
            .store
            .with_metadata(&format!("Address critique {}", critique_id), || {
                let mut critique = self.store.load_critique(critique_id)?;
                critique.address();
                self.store.save_critique(&critique)?;
                Ok(())
            }) {
            Ok(_) => {
                self.show_flash(&format!("{} addressed", id));
                self.refresh_data()?;
            }
            Err(e) => {
                self.show_flash(&format!("Error: {}", e));
            }
        }
        Ok(())
    }

    fn dismiss_critique(&mut self, critique_id: &str) -> Result<()> {
        let id = critique_id.to_string();
        match self
            .store
            .with_metadata(&format!("Dismiss critique {}", critique_id), || {
                let mut critique = self.store.load_critique(critique_id)?;
                critique.dismiss();
                self.store.save_critique(&critique)?;
                Ok(())
            }) {
            Ok(_) => {
                self.show_flash(&format!("{} dismissed", id));
                self.refresh_data()?;
            }
            Err(e) => {
                self.show_flash(&format!("Error: {}", e));
            }
        }
        Ok(())
    }

    pub(super) fn refresh_data(&mut self) -> Result<()> {
        use super::ProjectData;
        self.data = ProjectData::load(&self.store)?;
        self.ui.related_cache.clear();
        self.rebuild_cache();
        // Clamp tree_index to valid range after data change
        let max_index = self.cache.tree_items.len().saturating_sub(1);
        if self.ui.tree_index > max_index {
            self.ui.tree_index = max_index;
        }
        Ok(())
    }

    fn rebuild_cache(&mut self) {
        self.cache.next_actions = super::super::build_next_actions(
            &self.data.problems,
            &self.data.solutions,
            &self.data.critiques,
            &self.user,
        );
        self.rebuild_tree();
        // Annotate tree with action symbols
        super::super::annotate_tree_with_actions(
            &mut self.cache.tree_items,
            &self.cache.next_actions,
        );
        self.update_selected_detail();
    }

    pub(super) fn dissolve_problem(&mut self, problem_id: &str, reason: &str) -> Result<()> {
        let id = problem_id.to_string();
        match self
            .store
            .with_metadata(&format!("Dissolve problem {}", problem_id), || {
                let mut problem = self.store.load_problem(problem_id)?;
                problem.dissolve(reason.to_string());
                self.store.save_problem(&problem)
            }) {
            Ok(_) => {
                self.show_flash(&format!("{} dissolved", id));
                self.refresh_data()?;
            }
            Err(e) => {
                self.show_flash(&format!("Error: {}", e));
            }
        }
        Ok(())
    }

    pub(super) fn handle_action_shift_a(&mut self) -> Result<()> {
        let user = self
            .store
            .get_current_user()
            .unwrap_or_else(|_| "unknown".to_string());

        if let Some((id, entity_type)) = self.get_selected_entity() {
            let id_clone = id.clone();
            let user_clone = user.clone();
            match entity_type {
                EntityType::Problem => {
                    match self.store.with_metadata(
                        &format!("Assign problem {} to {}", id, user),
                        || {
                            let mut problem = self.store.load_problem(&id)?;
                            problem.assignee = Some(user.clone());
                            self.store.save_problem(&problem)
                        },
                    ) {
                        Ok(_) => {
                            self.show_flash(&format!("{} assigned to {}", id_clone, user_clone));
                            self.refresh_data()?;
                        }
                        Err(e) => self.show_flash(&format!("Error: {}", e)),
                    }
                }
                EntityType::Solution => {
                    match self.store.with_metadata(
                        &format!("Assign solution {} to {}", id, user),
                        || {
                            let mut solution = self.store.load_solution(&id)?;
                            solution.assignee = Some(user.clone());
                            self.store.save_solution(&solution)
                        },
                    ) {
                        Ok(_) => {
                            self.show_flash(&format!("{} assigned to {}", id_clone, user_clone));
                            self.refresh_data()?;
                        }
                        Err(e) => self.show_flash(&format!("Error: {}", e)),
                    }
                }
                EntityType::Milestone => {
                    match self.store.with_metadata(
                        &format!("Assign milestone {} to {}", id, user),
                        || {
                            let mut milestone = self.store.load_milestone(&id)?;
                            milestone.assignee = Some(user.clone());
                            self.store.save_milestone(&milestone)
                        },
                    ) {
                        Ok(_) => {
                            self.show_flash(&format!("{} assigned to {}", id_clone, user_clone));
                            self.refresh_data()?;
                        }
                        Err(e) => self.show_flash(&format!("Error: {}", e)),
                    }
                }
                EntityType::Critique => {}
            }
        }
        Ok(())
    }

    pub(super) fn start_delete(&mut self) -> Result<()> {
        use super::super::tree::TreeNode;

        if let Some(item) = self.cache.tree_items.get(self.ui.tree_index) {
            let (entity_type, entity_id, title) = match &item.node {
                TreeNode::Critique { id, title, .. } => {
                    ("critique".to_string(), id.clone(), title.clone())
                }
                TreeNode::Solution { id, title, .. } => {
                    // Block if has critiques
                    let has_critiques = self.data.critiques.iter().any(|c| c.solution_id == *id);
                    if has_critiques {
                        self.show_flash("Delete critiques first");
                        return Ok(());
                    }
                    ("solution".to_string(), id.clone(), title.clone())
                }
                TreeNode::Problem { id, title, .. } => {
                    // Block if has solutions
                    let has_solutions = self.data.solutions.iter().any(|s| s.problem_id == *id);
                    if has_solutions {
                        self.show_flash("Delete solutions first");
                        return Ok(());
                    }
                    ("problem".to_string(), id.clone(), title.clone())
                }
                TreeNode::Milestone { id, title, .. } => {
                    // Block if has child problems
                    let has_problems = self
                        .data
                        .problems
                        .iter()
                        .any(|p| p.milestone_id.as_deref() == Some(id));
                    if has_problems {
                        self.show_flash("Remove problems first");
                        return Ok(());
                    }
                    ("milestone".to_string(), id.clone(), title.clone())
                }
                _ => return Ok(()),
            };

            self.ui.input_mode = InputMode::Input {
                prompt: format!("Delete '{}'? y to confirm: ", title),
                buffer: String::new(),
                action: InputAction::ConfirmDelete {
                    entity_type,
                    entity_id,
                },
                cursor_pos: 0,
            };
        }
        Ok(())
    }

    pub(super) fn delete_entity(&mut self, entity_type: &str, entity_id: &str) -> Result<()> {
        let id = entity_id.to_string();
        let result = match entity_type {
            "critique" => self
                .store
                .with_metadata(&format!("Delete critique {}", entity_id), || {
                    self.store.delete_critique(entity_id)
                }),
            "solution" => self
                .store
                .with_metadata(&format!("Delete solution {}", entity_id), || {
                    self.store.delete_solution(entity_id)
                }),
            "problem" => self
                .store
                .with_metadata(&format!("Delete problem {}", entity_id), || {
                    self.store.delete_problem(entity_id)
                }),
            "milestone" => self
                .store
                .with_metadata(&format!("Delete milestone {}", entity_id), || {
                    self.store.delete_milestone(entity_id)
                }),
            _ => return Ok(()),
        };
        match result {
            Ok(_) => {
                self.show_flash(&format!("Deleted {}", id));
                self.refresh_data()?;
            }
            Err(e) => {
                self.show_flash(&format!("Error: {}", e));
            }
        }
        Ok(())
    }

    pub(super) fn start_move_to_milestone(&mut self) -> Result<()> {
        use super::super::tree::TreeNode;

        if let Some(item) = self.cache.tree_items.get(self.ui.tree_index) {
            if let TreeNode::Problem { id, .. } = &item.node {
                self.ui.input_mode = InputMode::Input {
                    prompt: "Milestone [→ backlog]: ".to_string(),
                    buffer: String::new(),
                    action: InputAction::MoveProblemToMilestone {
                        problem_id: id.clone(),
                    },
                    cursor_pos: 0,
                };
            }
        }
        Ok(())
    }

    pub(super) fn move_problem_to_milestone(
        &mut self,
        problem_id: &str,
        input: &str,
    ) -> Result<()> {
        let input = input.trim();

        // Find target milestone by fuzzy title match
        let target_milestone = if input.is_empty() {
            None
        } else {
            let input_lower = input.to_lowercase();
            self.data
                .milestones
                .iter()
                .find(|m| m.title.to_lowercase().contains(&input_lower))
        };

        if !input.is_empty() && target_milestone.is_none() {
            self.show_flash("No matching milestone found");
            return Ok(());
        }

        let target_id = target_milestone.map(|m| m.id.clone());

        // Load problem to find old milestone
        let problem = self.store.load_problem(problem_id)?;
        let old_milestone_id = problem.milestone_id.clone();

        self.store
            .with_metadata(&format!("Move problem {} to milestone", problem_id), || {
                // Update problem's milestone_id
                let mut problem = self.store.load_problem(problem_id)?;
                problem.milestone_id = target_id.clone();
                self.store.save_problem(&problem)?;

                // Remove from old milestone
                if let Some(ref old_id) = old_milestone_id {
                    if let Ok(mut old_milestone) = self.store.load_milestone(old_id) {
                        old_milestone.remove_problem(problem_id);
                        self.store.save_milestone(&old_milestone)?;
                    }
                }

                // Add to new milestone
                if let Some(ref new_id) = target_id {
                    let mut new_milestone = self.store.load_milestone(new_id)?;
                    new_milestone.add_problem(problem_id);
                    self.store.save_milestone(&new_milestone)?;
                }

                Ok(())
            })?;

        let dest = target_milestone
            .map(|m| m.title.as_str())
            .unwrap_or("backlog");
        self.show_flash(&format!("Moved to {}", dest));
        self.refresh_data()?;
        Ok(())
    }

    pub(super) fn create_milestone(&mut self, title: &str) -> Result<()> {
        use crate::id::generate_id;
        use crate::models::Milestone;

        let id = generate_id();
        let milestone = Milestone::new(id.clone(), title);

        self.store
            .with_metadata(&format!("Create milestone: {}", title), || {
                self.store.save_milestone(&milestone)
            })?;

        self.show_flash(&format!("Created milestone {}", id));
        self.refresh_data()?;
        Ok(())
    }
}