mahbot 0.5.3

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
//! Joint verdict comments for pipeline stages (analysis, review, QA).
//!
//! Replaces the per-agent verdict comments with ONE comment per round —
//! written even on fully clean rounds so the audit trail is uniform. The
//! merge backbone is the shared LLM grouping core ([`crate::consensus`]):
//! a progress-preserving repair synthesis pass groups the agents' exact issue
//! statements — accepted groups freeze, repair rounds only touch the
//! remainder — contradiction groups carry a `— DISPUTED` marker on their
//! heading. The DISPUTED cross-reference appears in the ungrouped section
//! only when a member contradicts a frozen group (contradiction:true — never
//! for solo findings). Per-agent attribution (brackets, "Agent N:" /
//! "[blocker]" prefixes) and free-form critiques are stripped from comments —
//! scores + issues are persisted in the verdict store instead. The Analysis
//! stage shares this renderer, so analyst critiques are dropped too (analysis
//! uses the score-less `AnalysisVerdict` with per-issue grades; review and QA
//! use the score-based `Verdict` — critiques were never persisted anywhere).
//!
//! Items are referenced by stable numeric ids (global flat numbering across
//! all agents); validation is strictly structural (id range, duplicate
//! placement, completeness, contradiction ≥2 agents) and termination
//! deterministically places every remaining item in the ungrouped section,
//! eventually falling back to a deterministic raw member dump with an
//! explicit marker when nothing ever freezes.

use std::fmt::Write as _;
use std::sync::Arc;

use crate::jobs::RowStatus;
use crate::pipeline::board::Ticket;
use crate::retry::RetryExhausted;
use crate::util::{panic_message, scrub_credentials};
use crate::{
    AnalysisVerdict, BlockerVerificationVerdict, ChatMessage, ChatRequest, ChatRequestMeta, Role,
    Verdict, Workspace,
};

use super::{
    FinalizeOutcome, TicketPhase, TransitionCtx, bounce_to_development, comment_and_transition,
    info, raw_response_dump_section, reset_phase_attempt,
};

// ── Hardcoded review-count calibration defaults (no config surface) ──────

pub(crate) const DEFAULT_REVIEW_COUNT_TINY_CHURN: i64 = 200;
pub(crate) const DEFAULT_REVIEW_COUNT_LOW_CHURN: i64 = 1000;
pub(crate) const DEFAULT_REVIEW_COUNT_HIGH_CHURN: i64 = 3000;

// ── Round data ─────────────────────────────────────────────────────────

/// One valid verdict from a parallel round, unified across review/QA
/// (score-based Score) and analysis (score-less Graded). The verdict data is
/// OWNED so the round can be split away from the base_results vec — the
/// analysis consolidation must run before escalation and be reused afterward.
pub(crate) enum JointVerdict {
    Score { verdict: crate::Verdict },
    Graded { verdict: AnalysisVerdict },
}

impl JointVerdict {
    #[must_use]
    pub(crate) fn is_empty_issues(&self) -> bool {
        match self {
            Self::Score { verdict, .. } => verdict.issues_detected.is_empty(),
            Self::Graded { verdict, .. } => verdict.issues_detected.is_empty(),
        }
    }

    /// Passes the round's pass threshold. Review/QA use the numeric score;
    /// analysis (Graded) has no score in the renderer, so it always "passes"
    /// the clean-round check (a score-less analysis verdict with an empty
    /// issues list is simply clean).
    #[must_use]
    pub(crate) fn passes(&self, threshold: u8) -> bool {
        match self {
            Self::Score { verdict, .. } => verdict.score >= threshold,
            Self::Graded { .. } => true,
        }
    }
}

/// One failed agent (no response / parse failure) with its rendered dump.
pub(crate) struct JointFailure {
    pub dump: String,
}

/// Everything the joint-comment renderer needs about a round.
pub(crate) struct JointRound {
    /// Stage name: "Analysis", "Review" or "QA" (comment role = stage name).
    pub stage: &'static str,
    /// Valid verdicts, one per responding agent.
    pub verdicts: Vec<JointVerdict>,
    /// Failed agents (no response / parse failure).
    pub failures: Vec<JointFailure>,
    /// Pass threshold: the clean-round summary only claims "passed clean" when
    /// every valid verdict clears it (a sub-threshold verdict bounces the round
    /// even with an empty issues list).
    pub threshold: u8,
    /// Per-agent issue texts, indexed by dispatch index (empty for failures /
    /// no-verdict slots). This is the text-only input to the grouping core.
    pub issues: Vec<Vec<String>>,
    /// Per-agent per-issue grade (analysis only; `None` for review/QA and for
    /// issues that carry no grade).
    pub grades: Vec<Vec<Option<crate::IssueGrade>>>,
}

impl JointRound {
    /// Number of valid verdicts (responding agents with parseable verdicts).
    #[must_use]
    pub fn n_valid(&self) -> usize {
        self.verdicts.len()
    }

    /// True when every valid verdict carries no detected issues.
    #[must_use]
    pub fn has_no_issues(&self) -> bool {
        self.verdicts.iter().all(JointVerdict::is_empty_issues)
    }
}

// ── Synthesis request ──────────────────────────────────────────────────

/// Max output tokens for the pipeline grouping pass: raised above the old
/// budget (8K) — probes truncated at 4K output on 36-issue rounds; 16K is the
/// floor for claim-length rounds.
const PIPELINE_GROUPING_MAX_TOKENS: u32 = 16_000;

/// Build the synthesis chat request for a stage role (the stage role's own
/// model, reasoning effort, and provider routing — no separate grouping
/// model). The shared contradiction package is appended to the system prompt;
/// the general workspace context is prepended by the consensus core. The
/// system prompt is byte-stable across rounds — repair-round schema selection
/// lives in the appended user-section instructions.
fn synthesis_request(
    round: &JointRound,
    role: Role,
    ws: &Workspace,
    items: &[Vec<String>],
) -> ChatRequest {
    let system = format!(
        "{}\n\n{}",
        crate::prompt::load_prompt("synthesis/synthesis.md"),
        crate::prompt::load_prompt("synthesis/grouping_contradictions.md"),
    );
    // Scores are deliberately NOT included: grouping needs issue text only —
    // scores are persisted in the verdict store, never in the comment.
    let material = crate::consensus::numbered_items_material(items);
    let user = format!(
        "{}\n\nStage: {}\nAgent issues (id-numbered):\n{}",
        crate::prompt::load_prompt("synthesis/synthesis_input.md"),
        round.stage,
        material,
    );
    let derived = crate::agent::role_chat_params(role);
    ChatRequest {
        messages: vec![ChatMessage::system(&system), ChatMessage::user(&user)],
        tools: None,
        model: derived.model,
        // Override the default 32K budget with the 16K aggregation budget.
        max_tokens: Some(PIPELINE_GROUPING_MAX_TOKENS),
        reasoning_effort: derived.reasoning_effort,
        provider_order: derived.provider_order,
        meta: Some(ChatRequestMeta {
            purpose: "synthesis",
            agent_id: format!("verdict_{}", crate::generate_suffix()),
            role: role.as_str().to_string(),
            workspace: ws.name.clone(),
            ticket_id: None,
        }),
    }
}

/// Run the repair-mode synthesis pass through the shared consensus core
/// (1 full call + up to N-1 repair rounds; frozen groups; per-group
/// acceptance; deterministic remainder placement; narrowed fail-open).
pub(crate) async fn run_synthesis(
    round: &JointRound,
    role: Role,
    ws: &Workspace,
    ticket_id: &str,
    ticket_title: &str,
) -> crate::consensus::RepairOutcome {
    let request = synthesis_request(round, role, ws, &round.issues);
    crate::consensus::run_grouping_repair(
        ws,
        "synthesis",
        request,
        &round.issues,
        Some(crate::agent::registry::ParentKey::Ticket(
            ticket_id.to_string(),
        )),
        Some(ticket_title.to_string()),
    )
    .await
}

// ── Joint comment rendering ─────────────────────────────────────────────

/// Render the joint comment for a round given the repair-mode synthesis
/// outcome.
///
/// Structure: groups of issue statements (frozen by the repair protocol
/// when synthesis succeeded, raw member dump otherwise; contradiction groups
/// carry a `— DISPUTED` marker), the code-computed
/// ungrouped remainder in a deterministic trailing section (DISPUTED
/// cross-references for items that flag a contradiction against a frozen
/// group), the first-accepted LLM summary prose (or an explicit marker), and a
/// raw-dump appendix for failed agents. Per-agent attribution (brackets,
/// "Agent N:" / "[blocker]" prefixes) and free-form critiques are noise and
/// are not rendered — scores + issues are already persisted in the verdict
/// store.
#[must_use]
pub(crate) fn render_joint_comment(
    round: &JointRound,
    outcome: &crate::consensus::RepairOutcome,
    table: &crate::consensus::ItemTable<'_>,
) -> String {
    let mut out = String::new();

    // Issues — grouped by the LLM when available.
    let has_issues = table.len() > 0;
    if has_issues {
        match outcome {
            crate::consensus::RepairOutcome::Repaired { output, references } => {
                for group in &output.groups {
                    let _ = write!(out, "\n\n**{}**", group.heading);
                    if group.contradiction {
                        out.push_str(" — DISPUTED");
                    }
                    for member in &group.members {
                        let _ = write!(out, "\n- {}", member_bullet(round, table, member));
                    }
                }
                out.push_str(&crate::consensus::render_ungrouped_section(
                    output,
                    references,
                    |member, disputed| member_bullet(round, table, member) + disputed,
                ));
            }
            crate::consensus::RepairOutcome::Fallback => {
                // Deterministic fail-open: raw per-agent issue dump + marker
                // (global flat id order = (agent, item) order).
                out.push_str("\n\n**Issues**");
                for id in 0..table.len() {
                    if let Some((_, text)) = table.resolve(id) {
                        let line = match issue_grade(round, table, id) {
                            Some(grade) => format!("{}: {}", grade.as_str(), text),
                            None => text.to_string(),
                        };
                        let _ = write!(out, "\n- {line}");
                    }
                }
            }
        }
    }

    // First-accepted LLM summary or explicit marker.
    match outcome {
        crate::consensus::RepairOutcome::Repaired { output, .. } => {
            let summary = output.summary.trim();
            if !summary.is_empty() {
                out.push_str("\n\n### Summary");
                let _ = write!(out, "\n{summary}");
            }
        }
        crate::consensus::RepairOutcome::Fallback => {
            if has_issues {
                // the grouping pass either failed or was
                // deliberately skipped (single-verdict verifier round) — both
                // reduce to the deterministic per-agent dump.
            } else {
                // No issues existed to merge — the synthesis pass was
                // deliberately skipped, so the summary must not imply it
                // failed. "Passed clean" additionally requires every valid
                // verdict to clear the round threshold: a sub-threshold
                // verdict with an empty issues list still bounces the round.
                let clean = round.failures.is_empty()
                    && round.verdicts.iter().all(|v| v.passes(round.threshold));
                let summary = if clean || round.n_valid() > 0 {
                    "\n\n### Summary\nNo issues found.".to_string()
                } else {
                    "\n\n### Summary\nNo issues to merge — no agent produced a verdict.".to_string()
                };
                out.push_str(&summary);
            }
        }
    }

    // Raw-dump appendix for failed agents.
    if !round.failures.is_empty() {
        out.push_str("\n\n### Plain verifier responses");
        for f in &round.failures {
            let _ = write!(out, "\n- {}\n", f.dump);
        }
    }

    // The first section's leading separator would leave leading blank lines —
    // strip them.
    crate::util::failure_detail(out.trim_start_matches('\n'), "joint verdict comment")
}

/// Resolve a grouped member's issue text via the item table (no text
/// equality). Unknown ids (defensive) render with an explicit marker.
fn member_text(
    table: &crate::consensus::ItemTable<'_>,
    member: &crate::consensus::GroupingMember,
) -> String {
    table.resolve(member.id).map_or_else(
        || format!("<unknown item id {}>", member.id),
        |(_, text)| text.to_string(),
    )
}

/// Resolve a flat item id's per-issue grade (analysis only): `None` for
/// review/QA, for unknown ids, and for issues that carry no grade.
#[must_use]
pub(crate) fn issue_grade(
    round: &JointRound,
    table: &crate::consensus::ItemTable<'_>,
    id: usize,
) -> Option<crate::IssueGrade> {
    let (agent, item) = table.resolve_index(id)?;
    round
        .grades
        .get(agent)
        .and_then(|g| g.get(item))
        .copied()
        .flatten()
}

fn member_bullet(
    round: &JointRound,
    table: &crate::consensus::ItemTable<'_>,
    member: &crate::consensus::GroupingMember,
) -> String {
    match issue_grade(round, table, member.id) {
        Some(grade) => format!("{}: {}", grade.as_str(), member_text(table, member)),
        None => member_text(table, member),
    }
}

// ── Calibrated dynamic agent counts ─────────────────────────────────────

/// Compute the reviewer-count base from total working-tree churn (added +
/// deleted lines, including lines of new files): 1 for churn < tiny, 2 for
/// churn < low, 3 for churn < high, 4 otherwise — each threshold belongs to
/// the higher band (e.g. churn == low calibrates to 3).
#[must_use]
pub(crate) fn review_base_from_signals(
    total_churn: i64,
    tiny_churn: i64,
    low_churn: i64,
    high_churn: i64,
) -> usize {
    if total_churn < tiny_churn {
        1
    } else if total_churn < low_churn {
        2
    } else if total_churn < high_churn {
        3
    } else {
        4
    }
}

/// Apply the P0 floor: priority-0 tickets never drop below 2 reviewers
/// (floor 2). Bounces do not change the count.
#[must_use]
pub(crate) fn review_agent_count(base: usize, priority: i64) -> usize {
    if priority == 0 { base.max(2) } else { base }
}

/// Human-readable stage name for a parallel-verdict role (used in the joint
/// comment title and the comment role).
#[must_use]
pub(crate) fn stage_name(role: Role) -> &'static str {
    match role {
        Role::Analyst => "Analysis",
        Role::Reviewer => "Review",
        Role::Qa => "QA",
        // Only the three parallel-verdict roles reach this function (all call
        // sites pass Analyst/Reviewer/Qa).
        _ => unreachable!("stage_name called with a non-verdict role"),
    }
}

/// Inverse of [`stage_name`]: resolve a stage-name comment role back to the
/// verdict role (used by the GUI to color joint-comment badges).
#[must_use]
pub(crate) fn stage_role(name: &str) -> Option<Role> {
    match name {
        "Analysis" => Some(Role::Analyst),
        "Review" => Some(Role::Reviewer),
        "QA" => Some(Role::Qa),
        _ => None,
    }
}

// ── Parallel-round data shapes & joint-comment builder ──────────────────
//
// These are the verdict-round types the renderer above consumes, so they
// live with it rather than in the orchestrator.

/// Result from a single parallel verifier agent.
#[derive(Clone)]
pub(crate) enum ParallelVerdict {
    /// Agent failed to produce any response (crashed, timed out, empty output).
    NoResponse(String),
    /// Agent produced a response but structured verdict extraction failed.
    ParseFailed(RetryExhausted),
    /// Agent produced a successfully-parsed verdict.
    Verdict(Verdict),
    /// Agent produced a score-less analysis verdict (analysis base round).
    Analysis(AnalysisVerdict),
    /// Agent produced a blocker-verification verdict (analysis escalation).
    BlockerVerification(BlockerVerificationVerdict),
}

/// Structured-extraction behavior for a parallel round member.
#[derive(Clone)]
pub(crate) enum ExtractionMode {
    /// Standard score+issues verdict (review, QA).
    ScoreVerdict,
    /// Score-less analysis base round (no score; each issue graded).
    ScorelessVerdict,
    /// Blocker verification (analysis escalation).
    BlockerVerification { blockers: Arc<[String]> },
}

/// One roster slot of a ticket phase round.
#[derive(Clone)]
pub(crate) struct AgentSlot {
    /// Dispatch slot index (0-based; escalation continues at 3, 4).
    pub idx: i64,
    pub agent_id: String,
    /// FINAL per-agent rendered prompt (angle appended).
    pub task: String,
    pub status: RowStatus,
    /// Stored agents.outcome (tagged JSON) — set on replay of a done slot.
    pub outcome: Option<String>,
}

/// Map a panicked round member's [`tokio::task::JoinError`] to a contained
/// [`ParallelVerdict::NoResponse`] (round continues fail-open).
pub(crate) fn round_member_failed(e: tokio::task::JoinError) -> ParallelVerdict {
    let reason = scrub_credentials(&panic_message(&*e.into_panic()));
    tracing::warn!(%reason, "round member task failed");
    ParallelVerdict::NoResponse(reason)
}

/// Validate a verdict score is within [0, 10].
pub(crate) fn validate_verdict_score(v: &Verdict) -> Result<(), String> {
    if v.score <= 10 {
        Ok(())
    } else {
        Err(format!("verdict score {} out of range [0,10]", v.score))
    }
}

/// Validate a blocker-verification verdict.
pub(crate) fn validate_blocker_verification(
    v: &BlockerVerificationVerdict,
    blockers: &[String],
) -> Result<(), String> {
    if v.verdicts.is_empty() {
        return Err("blocker verification returned no verdicts".to_string());
    }
    if v.verdicts.len() != blockers.len() {
        return Err(format!(
            "blocker verification returned {} verdicts for {} blockers",
            v.verdicts.len(),
            blockers.len()
        ));
    }
    let mut seen = vec![false; blockers.len()];
    for item in &v.verdicts {
        if item.index >= blockers.len() {
            return Err(format!("blocker index {} out of range", item.index));
        }
        if seen[item.index] {
            return Err(format!("duplicate blocker index {}", item.index));
        }
        seen[item.index] = true;
        if item.reasoning.trim().is_empty() {
            return Err(format!("blocker {} missing reasoning", item.index));
        }
        if item.impact.trim().is_empty() {
            return Err(format!("blocker {} missing impact", item.index));
        }
    }
    Ok(())
}

/// Serialize a [`ParallelVerdict`] into the agents.outcome column.
#[must_use]
pub(crate) fn serialize_verdict_outcome(result: &ParallelVerdict) -> String {
    match result {
        ParallelVerdict::Verdict(v) => serde_json::json!({ "verdict": v }).to_string(),
        ParallelVerdict::Analysis(v) => serde_json::json!({ "verdict": v }).to_string(),
        ParallelVerdict::NoResponse(reason) => {
            serde_json::json!({ "no_response": reason }).to_string()
        }
        ParallelVerdict::ParseFailed(f) => {
            serde_json::json!({ "parse_failed": raw_response_dump_section(f) }).to_string()
        }
        ParallelVerdict::BlockerVerification(v) => {
            serde_json::json!({ "blocker_verification": v }).to_string()
        }
    }
}

/// Reconstruct a [`ParallelVerdict`] from the agents.outcome column.
#[must_use]
pub(crate) fn deserialize_verdict_outcome(outcome: &str) -> ParallelVerdict {
    let Ok(v) = serde_json::from_str::<serde_json::Value>(outcome) else {
        return ParallelVerdict::NoResponse("unreadable stored outcome".to_string());
    };
    if let Some(verdict) = v.get("verdict") {
        // A numeric `score` is the review/QA shape; score-less graded objects
        // are analysis verdicts. The two are NOT distinguishable at the type
        // level for empty-issue rows (`AnalysisVerdict` ignores the unknown
        // `score` field and accepts `{"issues":[]}`), so the presence of
        // `score` is the discriminating signal.
        if verdict.get("score").is_some() {
            if let Ok(vv) = serde_json::from_value::<crate::Verdict>(verdict.clone()) {
                return ParallelVerdict::Verdict(vv);
            }
        } else if let Ok(av) = serde_json::from_value::<crate::AnalysisVerdict>(verdict.clone()) {
            return ParallelVerdict::Analysis(av);
        }
        ParallelVerdict::NoResponse("unreadable stored verdict".to_string())
    } else if let Some(r) = v.get("no_response").and_then(serde_json::Value::as_str) {
        ParallelVerdict::NoResponse(r.to_string())
    } else if let Some(p) = v.get("parse_failed").and_then(serde_json::Value::as_str) {
        ParallelVerdict::NoResponse(p.to_string())
    } else if let Some(v) = v.get("blocker_verification") {
        match serde_json::from_value(v.clone()) {
            Ok(bv) => ParallelVerdict::BlockerVerification(bv),
            Err(_) => {
                ParallelVerdict::NoResponse("unreadable stored blocker verification".to_string())
            }
        }
    } else {
        ParallelVerdict::NoResponse("unrecognized stored outcome".to_string())
    }
}

/// Build the joint comment for a round: deterministic merge + a single LLM
/// synthesis pass.
pub(crate) async fn build_round_joint_comment(
    stage: &'static str,
    results: &[ParallelVerdict],
    threshold: u8,
    role: Role,
    ws: &Workspace,
    ticket_id: &str,
    ticket_title: &str,
) -> String {
    let (round, outcome) =
        build_round_grouping(stage, results, threshold, role, ws, ticket_id, ticket_title).await;
    render_joint_comment(
        &round,
        &outcome,
        &crate::consensus::ItemTable::new(&round.issues),
    )
}

/// Run the grouping pass ONCE for a round, returning the round plus its
/// synthesis outcome so the caller can reuse both (escalation selection and
/// final rendering). Skips the LLM grouping pass when every verdict is clean
/// or when a single verifier's verdict is authoritative; otherwise runs
/// [`run_synthesis`].
pub(crate) async fn build_round_grouping(
    stage: &'static str,
    results: &[ParallelVerdict],
    threshold: u8,
    role: Role,
    ws: &Workspace,
    ticket_id: &str,
    ticket_title: &str,
) -> (JointRound, crate::consensus::RepairOutcome) {
    let round = build_joint_round(stage, results, threshold);
    let has_no_issues = round.has_no_issues();
    let single_verifier_verdict = matches!(role, Role::Reviewer | Role::Qa) && round.n_valid() == 1;
    if has_no_issues || single_verifier_verdict {
        (round, crate::consensus::RepairOutcome::Fallback)
    } else {
        let outcome = run_synthesis(&round, role, ws, ticket_id, ticket_title).await;
        (round, outcome)
    }
}

/// Build a [`JointRound`] from raw parallel results, cloning any valid verdict
/// data and leaving failed / no-verdict slots empty in every per-agent table.
fn build_joint_round(
    stage: &'static str,
    results: &[ParallelVerdict],
    threshold: u8,
) -> JointRound {
    let mut verdicts: Vec<JointVerdict> = Vec::new();
    let mut failures: Vec<JointFailure> = Vec::new();
    let mut issues: Vec<Vec<String>> = vec![Vec::new(); results.len()];
    let mut grades: Vec<Vec<Option<crate::IssueGrade>>> = vec![Vec::new(); results.len()];
    for (i, r) in results.iter().enumerate() {
        match r {
            ParallelVerdict::Verdict(v) => {
                verdicts.push(JointVerdict::Score { verdict: v.clone() });
                issues[i].clone_from(&v.issues_detected);
                grades[i] = vec![None; v.issues_detected.len()];
            }
            ParallelVerdict::Analysis(v) => {
                verdicts.push(JointVerdict::Graded { verdict: v.clone() });
                issues[i] = v.issues_detected.iter().map(|a| a.text.clone()).collect();
                grades[i] = v.issues_detected.iter().map(|a| Some(a.grade)).collect();
            }
            ParallelVerdict::NoResponse(reason) => {
                failures.push(JointFailure {
                    dump: reason.clone(),
                });
            }
            ParallelVerdict::ParseFailed(f) => {
                failures.push(JointFailure {
                    dump: scrub_credentials(&raw_response_dump_section(f)),
                });
            }
            ParallelVerdict::BlockerVerification(_) => {}
        }
    }
    JointRound {
        stage,
        verdicts,
        failures,
        threshold,
        issues,
        grades,
    }
}

// ── Verifier round processing (review / QA) ─────────────────────────────

/// Minimum acceptable verification score (0-10) for review and QA phases.
const REVIEW_QA_THRESHOLD: u8 = 9;

/// Check whether a review or QA verdict passes (score at or above threshold).
#[must_use]
fn verdict_passes(verdict: &crate::Verdict) -> bool {
    verdict.score >= REVIEW_QA_THRESHOLD
}

/// Static metadata driving a verifier round (reviewer or QA).
#[derive(Copy, Clone)]
pub(crate) struct VerifierInfo {
    pub(crate) role: Role,
    /// Human-readable label used in logs and bounce-breaker messages.
    pub(crate) log_label: &'static str,
    /// The phase the ticket advances to when every verifier agent passes.
    pub(crate) success_phase: TicketPhase,
    /// The phase the verifier is actively working in.
    pub(crate) active_phase: TicketPhase,
    pub(crate) prompt_template: &'static str,
    pub(crate) extraction_prompt_path: &'static str,
}

pub(crate) const REVIEWER_VI: VerifierInfo = VerifierInfo {
    role: Role::Reviewer,
    log_label: "Reviewers",
    success_phase: TicketPhase::InQa,
    active_phase: TicketPhase::InReview,
    prompt_template: "review.md",
    extraction_prompt_path: "extraction/reviewer.md",
};

pub(crate) const QA_VI: VerifierInfo = VerifierInfo {
    role: Role::Qa,
    log_label: "QA",
    success_phase: TicketPhase::InSanitation,
    active_phase: TicketPhase::InQa,
    prompt_template: "qa.md",
    extraction_prompt_path: "extraction/qa.md",
};

/// Process parallel verifier results: add the joint comment, determine
/// pass/fail, and update ticket phase accordingly.
pub(crate) async fn process_verifier_verdicts(
    ws: &Workspace,
    ticket: &Ticket,
    results: &[ParallelVerdict],
    verifier: VerifierInfo,
    job_id: &str,
) -> bool {
    // Distinguish the two failure classes: a verifier that did NOT complete
    // (NoResponse/ParseFailed) is a HARD TECHNICAL failure — reset the attempt
    // (comment + delete job + pause; no bounce budget). A verifier that DID
    // complete but found issues (a Verdict below threshold) is a rework verdict
    // — bounce to development, consuming bounce budget.
    let technical_failure = results.iter().any(|r| {
        matches!(
            r,
            ParallelVerdict::NoResponse(_) | ParallelVerdict::ParseFailed(_)
        )
    });
    let rework_failure = !technical_failure
        && results.iter().any(|r| match r {
            ParallelVerdict::Verdict(v) => !verdict_passes(v),
            _ => false,
        });

    if crate::shutdown::aborting() {
        info!(
            ticket = %ticket.id,
            stage = %verifier.log_label,
            "Verifier round cut short by drain — job stays launched for boot resume",
        );
        return false;
    }

    if technical_failure {
        // Hard technical failure: a verifier did not complete. Reset the
        // attempt (the round is destroyed; the puller creates a fresh one).
        let comment = format!(
            "{} could not complete the round (a verifier did not respond).",
            verifier.log_label,
        );
        reset_phase_attempt(
            ticket,
            verifier.active_phase,
            job_id,
            verifier.log_label,
            &comment,
        )
        .await;
        return false;
    }

    // Build the joint comment only for the success / rework paths — the reset
    // path above uses its own short failure comment.
    let joint_comment = build_round_joint_comment(
        stage_name(verifier.role),
        results,
        REVIEW_QA_THRESHOLD,
        verifier.role,
        ws,
        &ticket.id,
        &ticket.title,
    )
    .await;

    if !rework_failure {
        return apply_clean_verifier_round(ticket, verifier, &joint_comment, job_id).await;
    }

    let outcome = bounce_to_development(
        ticket,
        verifier.active_phase,
        verifier.log_label,
        /* drains_siblings */ true,
        stage_name(verifier.role),
        &joint_comment,
        job_id,
    )
    .await;
    matches!(outcome, FinalizeOutcome::Applied)
}

/// Apply the clean-pass outcome of a verifier round: write the joint comment,
/// transition the ticket to its next phase, and delete the phase job. Returns
/// `false` if the transition was not applied (phase moved concurrently).
async fn apply_clean_verifier_round(
    ticket: &Ticket,
    verifier: VerifierInfo,
    joint_comment: &str,
    job_id: &str,
) -> bool {
    if !matches!(
        comment_and_transition(
            TransitionCtx::buffered(
                ticket,
                verifier.active_phase,
                verifier.success_phase,
                verifier.log_label,
            ),
            stage_name(verifier.role),
            joint_comment,
        )
        .await,
        FinalizeOutcome::Applied
    ) {
        return false;
    }
    info!(
        ticket = %ticket.id,
        "{log_label}: all passed (≥ {threshold}/10)",
        log_label = verifier.log_label,
        threshold = REVIEW_QA_THRESHOLD,
    );
    // Delete the phase job; the puller creates the next phase job.
    let _ = crate::jobs::terminalize_job(&crate::session::store().conn, job_id).await;
    true
}