mahbot 0.3.0

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
use super::*;
use crate::util::test::make_ticket;
use crate::util::test::{
    create_test_workspace, expect_ticket, expect_ticket_phase, init_management_test_stores,
    init_test_stores,
};
use crate::workspace::test_ws_named;
use strum::IntoEnumIterator;

/// All non-General circuit breaker variants must have a threshold strictly
/// less than [`CircuitBreakerKind::General`]'s threshold.
///
/// ## Rationale
///
/// - **Sanitation breaker** (`threshold = 3`): must trip before the general
///   breaker (`threshold = 30`), otherwise a ticket could accumulate 30+
///   comments during repeated sanitation loops without tripping.
/// - **Diagnostics breaker** (`threshold = 4`): must also trip before the
///   general breaker. This is a conservative approximation — the general
///   breaker counts *all* comments (not just diagnostics), but guaranteeing
///   that diagnostics-only chatter cannot bypass the general breaker prevents
///   pathological ticket growth from repeated diagnostic cycles.

#[test]
fn all_non_general_circuit_breakers_trip_before_general() {
    let general = CircuitBreakerKind::General.threshold();
    for kind in CircuitBreakerKind::iter() {
        if kind == CircuitBreakerKind::General {
            continue;
        }
        assert!(
            kind.threshold() < general,
            "{kind:?}.threshold() ({}) must be less than General.threshold() ({general})",
            kind.threshold(),
        );
    }
}

/// Verify that when the circuit breaker trips on a ticket, all other
/// ReadyForDevelopment tickets in the same workspace are moved to Planning.
/// Tickets in other workspaces must not be affected.
#[tokio::test]
async fn circuit_breaker_moves_other_ready_for_development_tickets_to_planning() {
    init_management_test_stores().await;

    let ws_a = test_ws_named("/ws_a", "ws_a");
    let ws_b = test_ws_named("/ws_b", "ws_b");

    // Create ticket A in workspace A — this will trip the circuit breaker.
    let trip_id = make_ticket(
        board(),
        &ws_a,
        "Trip Ticket",
        TicketPhase::ReadyForDevelopment,
    )
    .await;

    // Create ticket B in workspace A — this should be moved to Planning when A trips.
    let victim_id = make_ticket(
        board(),
        &ws_a,
        "Victim Ticket",
        TicketPhase::ReadyForDevelopment,
    )
    .await;

    // Create ticket C in workspace B — this must NOT be moved.
    let other_ws_id = make_ticket(
        board(),
        &ws_b,
        "Other Workspace Ticket",
        TicketPhase::ReadyForDevelopment,
    )
    .await;

    // Add comments to ticket A so the circuit breaker has something to count
    // (CircuitBreakerKind::General.threshold() + 1 = 31 comments, enough to trip).
    for i in 0..=CircuitBreakerKind::General.threshold() {
        board()
            .add_comment(&trip_id, SYSTEM_ROLE, &format!("Comment {i}"))
            .await
            .expect("add_comment to A");
    }

    // Fetch ticket A and trip the circuit breaker.
    let ticket_a = expect_ticket(board(), &trip_id).await;

    let tripped = try_trip_circuit_breaker(
        &ticket_a,
        TicketPhase::ReadyForDevelopment,
        CircuitBreakerKind::General,
        "test",
    )
    .await;

    assert!(tripped, "circuit breaker should have tripped");

    // ── Verify ticket A is Failed ──
    {
        let ticket_a = expect_ticket(board(), &trip_id).await;
        assert_eq!(
            ticket_a.phase,
            TicketPhase::Failed,
            "tripped ticket A should be Failed"
        );
    }

    // ── Verify ticket B (same workspace) is Planning ──
    {
        let ticket_b = expect_ticket(board(), &victim_id).await;
        assert_eq!(
            ticket_b.phase,
            TicketPhase::Planning,
            "other ReadyForDevelopment ticket B in same workspace should be Planning"
        );
    }

    // ── Verify ticket C (different workspace) is still ReadyForDevelopment ──
    {
        let ticket_c = expect_ticket(board(), &other_ws_id).await;
        assert_eq!(
            ticket_c.phase,
            TicketPhase::ReadyForDevelopment,
            "ticket C in different workspace must not be moved"
        );
    }
}

/// Verify that `record_verdict_comments_tx` correctly writes comments
/// based on verdict filter.
#[tokio::test]
async fn record_verdict_comments_filtering() {
    init_test_stores().await;

    let ticket_id = make_ticket(
        board(),
        &test_ws_named("/tmp/test", "test"),
        "Test",
        TicketPhase::Backlog,
    )
    .await;

    // ── FailingOnly with all-passing verdicts ──
    // Should produce 0 comments (nothing to write).
    let results = vec![pass_result()];
    crate::turso::with_tx(
        &board().conn,
        &ticket_id,
        "test verdict comments",
        async |tx| {
            record_verdict_comments_tx(
                tx,
                &ticket_id,
                &results,
                Role::Reviewer.as_str(),
                VerdictFilter::FailingOnly,
            )
            .await
        },
    )
    .await
    .expect("record_verdict_comments_tx should succeed");

    let comments = board()
        .get_comments(&ticket_id)
        .await
        .expect("get_comments");
    assert_eq!(
        comments.len(),
        0,
        "passing verdicts with FailingOnly filter should produce 0 comments"
    );

    // ── FailingOnly with a failing verdict ──
    // Should produce 1 comment.
    let results = vec![fail_result()];
    crate::turso::with_tx(
        &board().conn,
        &ticket_id,
        "test verdict comments",
        async |tx| {
            record_verdict_comments_tx(
                tx,
                &ticket_id,
                &results,
                Role::Reviewer.as_str(),
                VerdictFilter::FailingOnly,
            )
            .await
        },
    )
    .await
    .expect("record_verdict_comments_tx should succeed");

    let comments = board()
        .get_comments(&ticket_id)
        .await
        .expect("get_comments");
    assert_eq!(
        comments.len(),
        1,
        "failing verdict should create one comment"
    );
    assert_eq!(comments[0].role, "reviewer_1");

    // ── All filter (analyst path) ──
    // Should produce 2 comments (both verdicts recorded).
    let results = vec![
        analyst_verdict(10, "Excellent analysis.", &[]),
        analyst_verdict(4, "Needs more research.", &["Missing citations"]),
    ];
    crate::turso::with_tx(
        &board().conn,
        &ticket_id,
        "test verdict comments",
        async |tx| {
            record_verdict_comments_tx(
                tx,
                &ticket_id,
                &results,
                Role::Analyst.as_str(),
                VerdictFilter::All,
            )
            .await
        },
    )
    .await
    .expect("record_verdict_comments_tx should succeed");

    let comments = board()
        .get_comments(&ticket_id)
        .await
        .expect("get_comments");
    assert_eq!(
        comments.len(),
        3,
        "All filter should write both verdicts (total 3)"
    );
    assert_eq!(comments[1].role, "analyst_1");
    assert_eq!(comments[2].role, "analyst_2");
}

// ── transition_ticket_to_done — conditional notification ─────────

/// Shorthand for [`init_management_test_stores`] + [`create_test_workspace`]
/// with a generated `ws_{suffix}` / `/tmp/test_{suffix}` name/path.
///
/// Creates a **DB-backed** workspace (inserted into the test DB), unlike
/// [`setup_ticket`] which returns an in-memory workspace.
///
/// Each test must pass a unique `suffix` to avoid UNIQUE constraint
/// and cross-test pollution on the shared ticket buffer.
async fn setup_db_workspace(suffix: &str) -> crate::Workspace {
    init_management_test_stores().await;

    let ws_name = format!("ws_{suffix}");
    let ws_path = format!("/tmp/test_{suffix}");
    create_test_workspace(&ws_path, &ws_name).await
}

/// Shorthand for [`init_management_test_stores`] + [`test_ws_named`] +
/// [`TicketBuilder`].
///
/// Creates an in-memory workspace (no DB insertion) with the given `path`
/// and `name`, creates a ticket with `title` and starting `phase`, and
/// returns `(workspace, ticket_id)`.
async fn setup_ticket(
    ws_path: &str,
    ws_name: &str,
    title: &str,
    phase: TicketPhase,
) -> (crate::Workspace, String) {
    init_management_test_stores().await;
    let ws = test_ws_named(ws_path, ws_name);
    let ticket_id = make_ticket(board(), &ws, title, phase).await;
    (ws, ticket_id)
}

/// Verify the Buffer → Notify + drain sequence across two QaPassed tickets
/// via `transition_ticket_to_done`: the first one buffers, the last one
/// notifies and drains the buffer.
#[tokio::test]
async fn transition_ticket_to_done_buffer_and_notify() {
    let ws = setup_db_workspace("drains_buffer").await;

    // Two QaPassed tickets in the same workspace
    let first_id = make_ticket(board(), &ws, "Ticket A", TicketPhase::QaPassed).await;
    let second_id = make_ticket(board(), &ws, "Ticket B", TicketPhase::QaPassed).await;

    let ticket_a = expect_ticket(board(), &first_id).await;

    // Transition ticket A — ticket B is still QaPassed (active), so Buffer
    transition_ticket_to_done(
        &ticket_a,
        TicketPhase::QaPassed,
        "Test — ticket A done, B still active",
    )
    .await;

    // Intermediate assertion: verify the Buffer path was actually taken.
    // Without this, a bug where has_active_tickets_excluding incorrectly
    // returns false (causing Notify instead of Buffer) would only be caught
    // by the final empty-buffer check — which could still pass if the Notify
    // path also happened to drain the buffer cleanly (e.g., by sending an
    // empty notification). Draining here verifies entry was pushed.
    let intermediate = crate::ticket_buffer::drain("ws_drains_buffer");
    assert!(
        !intermediate.is_empty(),
        "After first QaPassed → Done with other active tickets: \
             should have buffered the notification (got empty buffer)",
    );

    // Transition ticket B — no more active tickets, should Notify and drain
    let ticket_b = expect_ticket(board(), &second_id).await;
    transition_ticket_to_done(
        &ticket_b,
        TicketPhase::QaPassed,
        "Test — ticket B done, last ticket",
    )
    .await;

    // Verify both tickets are Done and have SYSTEM_ROLE comments
    for (id, label) in [(&first_id, "A"), (&second_id, "B")] {
        let t = expect_ticket(board(), id).await;
        assert_eq!(t.phase, TicketPhase::Done, "Ticket {label} should be Done");

        // Each Done transition should have written a SYSTEM_ROLE comment
        let comments = board().get_comments(id).await.expect("get_comments");
        assert!(
            comments.iter().any(|c| c.role == SYSTEM_ROLE),
            "Ticket {label}: expected SYSTEM_ROLE comment from transition_ticket_to_done"
        );
    }

    // No entries should remain for this workspace (the Notify path on
    // ticket B calls drain() internally; we drained the intermediate
    // buffer above, so this check is for leftover / stale entries).
    let drained = crate::ticket_buffer::drain("ws_drains_buffer");
    assert!(
        drained.is_empty(),
        "Buffer should be empty after last ticket's Notify drains it",
    );
}

// ── try_trip_circuit_breaker — failure counting ──────────────────

/// Verify that circuit breaker counting logic works correctly for each
/// non-General breaker variant.
///
/// For each variant:
/// - Adds below-threshold failures — verifies the breaker does NOT trip
/// - Adds more failures to reach the trip count — verifies the breaker
///   trips, transitions to Failed, and writes a trip comment with the
///   "Circuit breaker" marker as a SYSTEM_ROLE comment.
#[tokio::test]
async fn breaker_counts_failures() {
    struct BreakerCase {
        name: &'static str,
        kind: CircuitBreakerKind,
        source_phase: TicketPhase,
        log_label: &'static str,
        ws_suffix: &'static str,
        below_threshold_count: usize,
        trip_count: usize,
    }

    init_management_test_stores().await;

    let cases = [
        BreakerCase {
            name: "Sanitation",
            kind: CircuitBreakerKind::Sanitation,
            source_phase: TicketPhase::InSanitation,
            log_label: "Sanitation",
            ws_suffix: "san_breaker_test",
            below_threshold_count: 2,
            trip_count: 4,
        },
        BreakerCase {
            name: "Diagnostics",
            kind: CircuitBreakerKind::Diagnostics,
            source_phase: TicketPhase::InDiagnostics,
            log_label: "Diagnostics",
            ws_suffix: "diag_breaker_test",
            below_threshold_count: 3,
            trip_count: 5,
        },
    ];

    for case in &cases {
        let ticket_id = make_ticket(
            board(),
            &test_ws_named("/tmp/test", case.ws_suffix),
            &format!("{} Breaker Test", case.log_label),
            case.source_phase,
        )
        .await;

        // Add below-threshold failures.
        for _ in 0..case.below_threshold_count {
            add_breaker_failure(case.kind, &ticket_id).await;
        }

        let ticket = expect_ticket(board(), &ticket_id).await;

        assert!(
            !try_trip_circuit_breaker(&ticket, case.source_phase, case.kind, case.log_label,).await,
            "case {}: should NOT trip with {} failures (threshold: {})",
            case.name,
            case.below_threshold_count,
            case.kind.threshold(),
        );

        // Add more failures to reach the trip count.
        // Breaker trips when count > threshold.
        for _ in case.below_threshold_count..case.trip_count {
            add_breaker_failure(case.kind, &ticket_id).await;
        }

        // Re-fetch ticket (comments are refetched internally by
        // try_trip_circuit_breaker, so we just need the ID).
        let ticket = expect_ticket(board(), &ticket_id).await;

        let tripped =
            try_trip_circuit_breaker(&ticket, case.source_phase, case.kind, case.log_label).await;
        assert!(
            tripped,
            "case {}: should trip with {} failures (threshold: {}, {} > {})",
            case.name,
            case.trip_count,
            case.kind.threshold(),
            case.trip_count,
            case.kind.threshold(),
        );

        // Verify the ticket is now Failed
        let phase = expect_ticket_phase(board(), &ticket_id).await;
        assert_eq!(
            phase,
            TicketPhase::Failed,
            "case {}: circuit breaker should transition to Failed",
            case.name,
        );

        // Verify the trip comment was written correctly:
        // must be a SYSTEM_ROLE comment containing "circuit breaker"
        let comments = board()
            .get_comments(&ticket_id)
            .await
            .expect("get_comments");
        let has_breaker_comment = comments
            .iter()
            .any(|c| c.role == SYSTEM_ROLE && c.content.to_lowercase().contains("circuit breaker"));
        assert!(
            has_breaker_comment,
            "case {}: should have a SYSTEM_ROLE comment with the circuit breaker message \
             (containing 'circuit breaker')",
            case.name,
        );
    }
}

// ── Setup helpers ──────────────────────────────────────────────────────

/// Shared helper: create a passing verdict (score >= REVIEW_QA_THRESHOLD).
fn pass_verdict() -> crate::Verdict {
    crate::Verdict {
        score: REVIEW_QA_THRESHOLD,
        critique: Some("Good work.".into()),
        issues_detected: vec![],
    }
}

/// Shared helper: create a failing verdict (score < REVIEW_QA_THRESHOLD).
fn fail_verdict() -> crate::Verdict {
    crate::Verdict {
        score: 3,
        critique: Some("Missing error handling.".into()),
        issues_detected: vec!["No timeout check".into()],
    }
}

/// Helper: a `ParallelVerdict` with no response.
fn no_verdict() -> ParallelVerdict {
    ParallelVerdict::NoResponse
}

/// Add a failure comment for circuit breaker testing, matching the
/// comment format used for the given breaker variant.
///
/// For [`CircuitBreakerKind::Sanitation`], adds a [`SYSTEM_ROLE`] comment
/// with [`SANITATION_FAILED_MARKER`]. For [`CircuitBreakerKind::Diagnostics`],
/// adds a [`DIAGNOSTICS_ROLE`] comment with [`DIAGNOSTICS_COMMENT_PREFIX`]
/// and [`DIAGNOSTICS_FAILED_MARKER`].
async fn add_breaker_failure(kind: CircuitBreakerKind, ticket_id: &str) {
    let (role, comment) = match kind {
        CircuitBreakerKind::Sanitation => (
            SYSTEM_ROLE,
            format!("{SANITATION_FAILED_MARKER} — garbage files: 1"),
        ),
        CircuitBreakerKind::Diagnostics => (
            DIAGNOSTICS_ROLE,
            format!("{DIAGNOSTICS_COMMENT_PREFIX}\n\n---\n{DIAGNOSTICS_FAILED_MARKER} test_step"),
        ),
        CircuitBreakerKind::General => {
            unreachable!("General breaker not used in failure-counting tests")
        }
    };
    let _ = board().add_comment(ticket_id, role, &comment).await;
}

/// Helper: wrap a passing verdict (reviewer/QA flow).
fn pass_result() -> ParallelVerdict {
    ParallelVerdict::Verdict(pass_verdict())
}

/// Helper: wrap a failing verdict (reviewer/QA flow).
fn fail_result() -> ParallelVerdict {
    ParallelVerdict::Verdict(fail_verdict())
}

/// Helper: construct an analyst verdict with explicit score / critique / issues.
fn analyst_verdict(score: u8, critique: &str, issues: &[&str]) -> ParallelVerdict {
    ParallelVerdict::Verdict(crate::Verdict {
        score,
        critique: Some(critique.into()),
        issues_detected: issues.iter().map(|&s| s.into()).collect(),
    })
}

// ── process_verifier_verdicts — verdict processing ─────────────────────

/// Verify all verdict-processing outcomes:
/// - All failed → Failed
/// - Any failed → bounce-back to ReadyForDevelopment with pipeline reservation
/// - All passed (Reviewer) → Reviewed
/// - All passed (QA) → QaPassed
#[tokio::test]
async fn process_verifier_verdicts_cases() {
    struct Case {
        name: &'static str,
        ws_suffix: &'static str,
        title: &'static str,
        phase: TicketPhase,
        results: Vec<ParallelVerdict>,
        vi: VerifierInfo,
        expected_phase: TicketPhase,
        expected_pipeline_reservation: bool,
    }

    init_management_test_stores().await;

    let cases = vec![
        Case {
            name: "all failed -> Failed",
            ws_suffix: "vp_all_fail",
            title: "VP All Failed",
            phase: TicketPhase::InReview,
            results: vec![no_verdict(); 3],
            vi: REVIEWER_VI,
            expected_phase: TicketPhase::Failed,
            expected_pipeline_reservation: false,
        },
        Case {
            name: "any failed -> bounce-back with pipeline reservation",
            ws_suffix: "vp_any_fail",
            title: "VP Any Failed",
            phase: TicketPhase::InReview,
            results: vec![pass_result(), fail_result(), pass_result()],
            vi: REVIEWER_VI,
            expected_phase: TicketPhase::ReadyForDevelopment,
            expected_pipeline_reservation: true,
        },
        Case {
            name: "all passed -> Reviewed",
            ws_suffix: "vp_all_pass",
            title: "VP All Pass",
            phase: TicketPhase::InReview,
            results: vec![pass_result(), pass_result(), pass_result()],
            vi: REVIEWER_VI,
            expected_phase: TicketPhase::Reviewed,
            expected_pipeline_reservation: false,
        },
        Case {
            name: "all passed (QA) -> QaPassed",
            ws_suffix: "vp_qa_pass",
            title: "VP QA Pass",
            phase: TicketPhase::InQa,
            results: vec![pass_result(), pass_result(), pass_result()],
            vi: QA_VI,
            expected_phase: TicketPhase::QaPassed,
            expected_pipeline_reservation: false,
        },
    ];

    for case in &cases {
        let ticket_id = make_ticket(
            board(),
            &test_ws_named("/tmp/test", case.ws_suffix),
            case.title,
            case.phase,
        )
        .await;

        let ticket = expect_ticket(board(), &ticket_id).await;

        process_verifier_verdicts(&ticket, &case.results, case.vi).await;

        let ticket = expect_ticket(board(), &ticket_id).await;
        assert_eq!(
            ticket.phase, case.expected_phase,
            "case {}: expected phase {:?}, got {:?}",
            case.name, case.expected_phase, ticket.phase,
        );
        assert_eq!(
            ticket.pipeline_reservation, case.expected_pipeline_reservation,
            "case {}: expected pipeline_reservation={}, got {}",
            case.name, case.expected_pipeline_reservation, ticket.pipeline_reservation,
        );
    }
}

// ── try_trip_circuit_breaker — general circuit breaker ────────

/// Verify the circuit breaker trips at the threshold boundary:
/// - `> CircuitBreakerKind::General.threshold()` comments → trips (ticket → Failed)
/// - `= CircuitBreakerKind::General.threshold()` comments → does NOT trip
///
/// When the breaker trips, also verifies the trip comment contains the
/// "circuit breaker" marker as produced by [`CircuitBreakerKind::should_trip`].
#[tokio::test]
async fn circuit_breaker_comment_boundary() {
    struct Case {
        name: &'static str,
        ws_suffix: &'static str,
        title: &'static str,
        comment_count: usize,
        expected_trip: bool,
        expected_phase: TicketPhase,
    }

    init_management_test_stores().await;

    let cases = [
        Case {
            name: "> threshold trips",
            ws_suffix: "cb_thresh",
            title: "CB Threshold",
            comment_count: CircuitBreakerKind::General.threshold() + 1,
            expected_trip: true,
            expected_phase: TicketPhase::Failed,
        },
        Case {
            name: "= threshold does not trip",
            ws_suffix: "cb_no_trip",
            title: "CB No Trip",
            comment_count: CircuitBreakerKind::General.threshold(),
            expected_trip: false,
            expected_phase: TicketPhase::InReview,
        },
    ];

    for case in &cases {
        let ticket_id = make_ticket(
            board(),
            &test_ws_named("/tmp/test", case.ws_suffix),
            case.title,
            TicketPhase::InReview,
        )
        .await;

        for i in 0..case.comment_count {
            board()
                .add_comment(&ticket_id, "user", &format!("Comment {i}"))
                .await
                .expect("add_comment");
        }

        let ticket = expect_ticket(board(), &ticket_id).await;

        let tripped = try_trip_circuit_breaker(
            &ticket,
            TicketPhase::InReview,
            CircuitBreakerKind::General,
            "test",
        )
        .await;
        assert_eq!(
            tripped, case.expected_trip,
            "case {}: expected trip={}, got tripped={}",
            case.name, case.expected_trip, tripped,
        );

        let phase = expect_ticket_phase(board(), &ticket_id).await;
        assert_eq!(
            phase, case.expected_phase,
            "case {}: expected phase {:?}, got {:?}",
            case.name, case.expected_phase, phase,
        );

        // When the breaker trips, verify the trip comment contains the
        // circuit breaker marker as produced by `CircuitBreakerKind::should_trip`.
        if tripped {
            let comments = board()
                .get_comments(&ticket_id)
                .await
                .expect("get_comments");
            let has_marker = comments
                .iter()
                .any(|c| c.content.to_lowercase().contains("circuit breaker"));
            assert!(
                has_marker,
                "case {}: trip comment must contain circuit breaker marker",
                case.name,
            );
        }
    }
}

// ── process_analyst_verdicts — analyst scoring and transitions ─────────

/// Verify process_analyst_verdicts across all outcomes:
/// - All analysts pass → Planning with "All LGTM" summary
/// - Partial fail → Planning with "blockers" summary
/// - No verdicts → Planning with "no analysis" summary
#[tokio::test]
async fn process_analyst_verdicts_cases() {
    struct Case {
        name: &'static str,
        ws_suffix: &'static str,
        title: &'static str,
        results: Vec<ParallelVerdict>,
        expected_comment_substring: &'static str,
    }

    init_management_test_stores().await;

    let cases = vec![
        Case {
            name: "all pass -> Planning with LGTM",
            ws_suffix: "an_all_pass",
            title: "Analyst All Pass",
            results: vec![
                analyst_verdict(10, "Great analysis.", &[]),
                analyst_verdict(9, "Solid work.", &[]),
                analyst_verdict(8, "Good analysis.", &[]),
            ],
            expected_comment_substring: "All LGTM",
        },
        Case {
            name: "partial fail -> Planning with blockers",
            ws_suffix: "an_partial",
            title: "Analyst Partial Fail",
            results: vec![
                analyst_verdict(10, "Great.", &[]),
                analyst_verdict(3, "Poor analysis.", &["Missing data"]),
                analyst_verdict(8, "Decent.", &["Minor issue"]),
            ],
            expected_comment_substring: "blockers",
        },
        Case {
            name: "no verdicts -> Planning with no analysis",
            ws_suffix: "an_no_v",
            title: "Analyst No Verdicts",
            results: vec![no_verdict(); 3],
            expected_comment_substring: "no analysis",
        },
    ];

    for case in &cases {
        let ticket_id = make_ticket(
            board(),
            &test_ws_named("/tmp/test", case.ws_suffix),
            case.title,
            TicketPhase::Analysis,
        )
        .await;

        let ticket = expect_ticket(board(), &ticket_id).await;

        process_analyst_verdicts(&ticket, &case.results).await;

        let phase = expect_ticket_phase(board(), &ticket_id).await;
        assert_eq!(
            phase,
            TicketPhase::Planning,
            "case {}: expected Planning, got {:?}",
            case.name,
            phase,
        );

        let comments = board()
            .get_comments(&ticket_id)
            .await
            .expect("get_comments");

        let system = comments
            .iter()
            .find(|c| c.role == SYSTEM_ROLE)
            .unwrap_or_else(|| panic!("case {}: system summary comment should exist", case.name));
        assert!(
            system.content.contains(case.expected_comment_substring),
            "case {}: system comment should contain {:?}, got: {}",
            case.name,
            case.expected_comment_substring,
            system.content,
        );
    }
}

// ── handle_qa_passed — QA → Done path ───────────────────────────────

/// handle_qa_passed first checks whether git is available and whether the
/// workspace path is a git repo. In test environments git may exist, but
/// the workspace path is deliberately not a git repo, so the function
/// transitions directly to Done without committing.
/// This test validates the graceful non-git fallback path.
#[tokio::test]
async fn handle_qa_passed_no_git_to_done() {
    // Use a temporary directory without git init — guarantees no git repo
    // exists regardless of the test runner's filesystem state. The `dir`
    // binding must stay alive (function scope) for the workspace path to
    // remain valid.
    let dir = tempfile::tempdir().expect("create temp dir");
    let ws_path = dir.path().to_str().expect("temp path is valid UTF-8");
    let (ws, ticket_id) =
        setup_ticket(ws_path, "qa_no_git", "QA No Git", TicketPhase::QaPassed).await;

    let ticket = expect_ticket(board(), &ticket_id).await;

    handle_qa_passed(ticket, ws).await;

    let phase = expect_ticket_phase(board(), &ticket_id).await;
    assert_eq!(
        phase,
        TicketPhase::Done,
        "QA passed should eventually transition to Done"
    );

    // Verify a SYSTEM_ROLE comment was written capturing the reason.
    let comments = board()
        .get_comments(&ticket_id)
        .await
        .expect("get_comments");
    assert!(
        comments
            .iter()
            .any(|c| c.role == SYSTEM_ROLE && c.content.contains("without commit")),
        "Expected a SYSTEM_ROLE comment explaining why no commit was made"
    );
}

/// handle_qa_passed with untracked files present should claim the ticket
/// to InSanitation and dispatch a sanitation agent. Creates a real git repo
/// with an untracked file to exercise the full claim path.
#[tokio::test]
async fn handle_qa_passed_untracked_files_to_insanitation() {
    // Skip if git is not installed — the test cannot create a repo.
    if !crate::git_commands::git_is_installed().await {
        eprintln!("git not installed — skipping git-dependent test");
        return;
    }

    // Create a temp directory and init a git repo
    let (_dir, repo_path) = crate::util::test::init_temp_repo();

    // Create an untracked file
    std::fs::write(repo_path.join("untracked.txt"), b"garbage").expect("write untracked file");

    let (ws, ticket_id) = setup_ticket(
        repo_path.to_str().unwrap(),
        "qa_untracked",
        "QA Untracked",
        TicketPhase::QaPassed,
    )
    .await;

    let ticket = expect_ticket(board(), &ticket_id).await;

    handle_qa_passed(ticket, ws).await;

    let phase = expect_ticket_phase(board(), &ticket_id).await;
    assert_eq!(
        phase,
        TicketPhase::InSanitation,
        "QA passed with untracked files should transition to InSanitation"
    );

    // Verify assigned_to is set to the sanitation session key
    let ticket = expect_ticket(board(), &ticket_id).await;
    let expected_key =
        crate::session::ticket_session_key(&ticket_id, crate::Role::Sanitation.as_str());
    assert_eq!(
        ticket.assigned_to.as_deref(),
        Some(expected_key.as_str()),
        "assigned_to should be set to sanitation session key"
    );
}

/// handle_qa_passed with a clean working tree (no untracked files, no
/// modifications) should transition to Done directly without creating a
/// commit — exercising the clean-tree path through [`finalize_ticket_with_status`].
///
/// Creates a real git repo with a clean working tree to exercise the
/// QaPassed→Done transition through the clean-tree path.
#[tokio::test]
async fn handle_qa_passed_clean_tree_to_done() {
    // Skip if git is not installed — the test cannot create a repo.
    if !crate::git_commands::git_is_installed().await {
        eprintln!("git not installed — skipping git-dependent test");
        return;
    }

    let (_dir, repo_path) = crate::util::test::init_temp_repo();

    let (ws, ticket_id) = setup_ticket(
        repo_path.to_str().unwrap(),
        "qa_clean",
        "QA Clean Tree",
        TicketPhase::QaPassed,
    )
    .await;

    let ticket = expect_ticket(board(), &ticket_id).await;

    handle_qa_passed(ticket, ws).await;

    let phase = expect_ticket_phase(board(), &ticket_id).await;
    assert_eq!(
        phase,
        TicketPhase::Done,
        "QA passed with clean tree should transition to Done"
    );

    // Verify a SYSTEM_ROLE comment was written explaining the clean-tree skip.
    let comments = board()
        .get_comments(&ticket_id)
        .await
        .expect("get_comments");
    assert!(
        comments
            .iter()
            .any(|c| c.role == SYSTEM_ROLE && c.content.contains("Clean working tree")),
        "Expected a SYSTEM_ROLE comment explaining the clean-tree skip"
    );
}

// ── process_sanitation_verdict — verdict processing ──────────────────

/// Verify both branches of `process_sanitation_verdict`:
/// - pass=true → SanitationPassed with a sanitation comment
/// - pass=false → ReadyForDevelopment with pipeline reservation,
///   a sanitation comment, and a system circuit-breaker comment
#[tokio::test]
async fn process_sanitation_verdict_cases() {
    init_management_test_stores().await;

    // Case 1: pass=true → SanitationPassed
    let ws_pass = test_ws_named("/tmp/test", "sv_pass");
    let pass_id = make_ticket(board(), &ws_pass, "SV Pass", TicketPhase::InSanitation).await;
    let ticket_pass = expect_ticket(board(), &pass_id).await;

    let pass_verdict = crate::SanitationVerdict {
        pass: true,
        garbage_files: vec![],
        rationale: "All files are legitimate project files.".into(),
    };

    process_sanitation_verdict(&ticket_pass, pass_verdict).await;

    let phase = expect_ticket_phase(board(), &pass_id).await;
    assert_eq!(
        phase,
        TicketPhase::SanitationPassed,
        "pass=true should transition to SanitationPassed, got {phase:?}",
    );

    // assigned_to must be cleared after a successful transition
    let ticket = expect_ticket(board(), &pass_id).await;
    assert!(
        ticket.assigned_to.is_none(),
        "assigned_to should be cleared after pass=true",
    );

    // Verify a sanitation comment was added
    let comments = board().get_comments(&pass_id).await.expect("get_comments");
    let has_sanitation_comment = comments.iter().any(|c| c.role == Role::Sanitation.as_str());
    assert!(
        has_sanitation_comment,
        "pass=true should add a sanitation comment",
    );

    // No system comment (only added in fail path)
    let has_system_comment = comments.iter().any(|c| c.role == SYSTEM_ROLE);
    assert!(
        !has_system_comment,
        "pass=true should not add a system comment",
    );

    // Case 2: pass=false → ReadyForDevelopment with pipeline reservation
    let ws_fail = test_ws_named("/tmp/test", "sv_fail");
    let fail_id = make_ticket(board(), &ws_fail, "SV Fail", TicketPhase::InSanitation).await;
    let ticket_fail = expect_ticket(board(), &fail_id).await;

    let fail_verdict = crate::SanitationVerdict {
        pass: false,
        garbage_files: vec!["node_modules/".into(), "tmp/scratch.js".into()],
        rationale: "These are intermediate build artifacts.".into(),
    };

    process_sanitation_verdict(&ticket_fail, fail_verdict).await;

    let ticket = expect_ticket(board(), &fail_id).await;
    assert_eq!(
        ticket.phase,
        TicketPhase::ReadyForDevelopment,
        "pass=false should bounce back to ReadyForDevelopment, got {:?}",
        ticket.phase,
    );
    assert!(
        ticket.pipeline_reservation,
        "pass=false should set pipeline_reservation=true",
    );
    assert!(
        ticket.assigned_to.is_none(),
        "assigned_to should be cleared after pass=false transition",
    );

    // Verify a sanitation comment was added about the garbage files
    let comments = board().get_comments(&fail_id).await.expect("get_comments");
    let has_garbage_comment = comments
        .iter()
        .any(|c| c.role == Role::Sanitation.as_str() && c.content.contains("node_modules/"));
    assert!(
        has_garbage_comment,
        "pass=false should have a sanitation comment mentioning garbage files",
    );

    // Verify a system comment with SANITATION_FAILED_MARKER was added
    let has_system_breaker = comments
        .iter()
        .any(|c| c.role == SYSTEM_ROLE && c.content.contains(SANITATION_FAILED_MARKER));
    assert!(
        has_system_breaker,
        "pass=false should have a system comment with the circuit breaker prefix",
    );
}

/// Verify [`dispatch_diagnostics`] behaviour across all scenarios:
///
/// | Scenario | Commands | Expected Phase | Pipeline Reservation | Comment Contains |
/// |---|---|---|---|---|
/// | No diagnostics commands | None (unset) | DiagnosticsDone | false | "No diagnostics commands are configured" |
/// | Diagnostics failure | `false` | ReadyForDevelopment | true | DIAGNOSTICS_COMMENT_PREFIX + DIAGNOSTICS_FAILED_MARKER |
/// | Diagnostics pass | `true`, ... | DiagnosticsDone | false | DIAGNOSTICS_COMMENT_PREFIX + DIAGNOSTICS_PASSED_MARKER |
/// | DB error (corrupt JSON) | N/A (corrupt) | DiagnosticsDone | false | "database error" |
#[allow(clippy::too_many_lines)]
#[tokio::test]
async fn dispatch_diagnostics_cases() {
    struct Case {
        name: &'static str,
        ws_suffix: &'static str,
        title: &'static str,
        /// Diagnostics commands to persist (None = leave unset).
        commands: Option<DiagnosticsCommands>,
        /// If true, overwrite the diagnostics column with invalid JSON.
        corrupt_diagnostics: bool,
        /// If true, create a real temp directory for command execution.
        needs_tempdir: bool,
        expected_phase: TicketPhase,
        expected_pipeline_reservation: bool,
        /// Substrings that must all be present in a DIAGNOSTICS_ROLE comment.
        expected_comment_contains: &'static [&'static str],
    }

    init_management_test_stores().await;

    let fail_cmds = DiagnosticsCommands {
        format: Some("false".to_string()),
        ..Default::default()
    };
    let pass_cmds = DiagnosticsCommands {
        format: Some("true".to_string()),
        type_check: Some("true".to_string()),
        ..Default::default()
    };

    let cases = [
        Case {
            name: "no diagnostics commands",
            ws_suffix: "dc_no_cmds",
            title: "No Diagnostics Commands",
            commands: None,
            corrupt_diagnostics: false,
            needs_tempdir: false,
            expected_phase: TicketPhase::DiagnosticsDone,
            expected_pipeline_reservation: false,
            expected_comment_contains: &["No diagnostics commands are configured"],
        },
        Case {
            name: "diagnostics failure",
            ws_suffix: "dc_fail",
            title: "Diagnostics Failure Test",
            commands: Some(fail_cmds),
            corrupt_diagnostics: false,
            needs_tempdir: true,
            expected_phase: TicketPhase::ReadyForDevelopment,
            expected_pipeline_reservation: true,
            expected_comment_contains: &[DIAGNOSTICS_COMMENT_PREFIX, DIAGNOSTICS_FAILED_MARKER],
        },
        Case {
            name: "diagnostics all pass",
            ws_suffix: "dc_pass",
            title: "Diagnostics All Pass Test",
            commands: Some(pass_cmds),
            corrupt_diagnostics: false,
            needs_tempdir: true,
            expected_phase: TicketPhase::DiagnosticsDone,
            expected_pipeline_reservation: false,
            expected_comment_contains: &[DIAGNOSTICS_COMMENT_PREFIX, DIAGNOSTICS_PASSED_MARKER],
        },
        Case {
            name: "diagnostics DB error",
            ws_suffix: "dc_db_err",
            title: "Diagnostics DB Error Test",
            commands: None,
            corrupt_diagnostics: true,
            needs_tempdir: false,
            expected_phase: TicketPhase::DiagnosticsDone,
            expected_pipeline_reservation: false,
            expected_comment_contains: &["database error"],
        },
    ];

    for case in &cases {
        let (_dir, ws_path): (Option<tempfile::TempDir>, String) = if case.needs_tempdir {
            let dir = tempfile::tempdir().expect("create temp dir");
            let path = dir.path().to_string_lossy().to_string();
            (Some(dir), path)
        } else {
            (None, format!("/tmp/{}", case.ws_suffix))
        };

        let ws = create_test_workspace(&ws_path, case.ws_suffix).await;

        if let Some(cmds) = &case.commands {
            crate::workspace::store()
                .set_diagnostics(case.ws_suffix, cmds, &crate::turso::now())
                .await
                .expect("set diagnostics");
        }
        if case.corrupt_diagnostics {
            crate::workspace::store()
                .conn
                .execute(
                    "UPDATE workspaces SET diagnostics = ?1 WHERE name = ?2",
                    turso::params!["not valid json", case.ws_suffix],
                )
                .await
                .expect("set diagnostics to invalid JSON");
        }

        let ticket_id = make_ticket(board(), &ws, case.title, TicketPhase::InDiagnostics).await;

        // NOTE: Do NOT claim the ticket beforehand — dispatch_diagnostics
        // calls claim_diagnostics internally as its first step.
        let ticket = expect_ticket(board(), &ticket_id).await;
        dispatch_diagnostics(Arc::new(ticket), ws).await;

        let phase = expect_ticket_phase(board(), &ticket_id).await;
        assert_eq!(
            phase, case.expected_phase,
            "case {}: expected phase {:?}, got {:?}",
            case.name, case.expected_phase, phase,
        );

        let ticket = expect_ticket(board(), &ticket_id).await;
        assert_eq!(
            ticket.pipeline_reservation, case.expected_pipeline_reservation,
            "case {}: pipeline_reservation mismatch",
            case.name,
        );
        assert!(
            ticket.assigned_to.is_none(),
            "case {}: assigned_to should be cleared after diagnostics dispatch",
            case.name,
        );

        let comments = board()
            .get_comments(&ticket_id)
            .await
            .expect("get_comments");
        assert!(
            !comments.is_empty(),
            "case {}: should have written at least one comment",
            case.name,
        );
        let has_expected = comments.iter().any(|c| {
            c.role == DIAGNOSTICS_ROLE
                && case
                    .expected_comment_contains
                    .iter()
                    .all(|&marker| c.content.contains(marker))
        });
        assert!(
            has_expected,
            "case {}: should have a DIAGNOSTICS_ROLE comment containing: {:?}",
            case.name, case.expected_comment_contains,
        );
    }
}