mahbot 0.10.1

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
//! Shared LLM grouping/synthesis core for pipeline joint-verdict and analyze consolidation.
//! One LLM pass groups id-referenced items (pipeline issues; analyze claims) into thematic groups.
//! Every item gets a stable numeric id assigned once per operation across the whole input; the LLM
//! refers to items by id only, and the system resolves id → (agent, text) via [`ItemTable`] for
//! rendering. The LLM never produces counts: brackets `[n/N]` and the DISPUTED marker are computed
//! here from distinct cited agent ids — pure arithmetic.
//!
//! Validation is strictly structural: ids in range, no duplicate placement, set
//! completeness (every item appears exactly once across placed ∪ pinned ∪ remainder), and
//! a contradiction guardrail (contradiction:true requires ≥2 distinct cited agents).
//! Text-based membership checks are gone everywhere — a wrong-but-valid id is accepted by
//! design, since semantic judgment is the LLM's; the gate only catches structural lies.
//!
//! The single retry mode is the progress-preserving repair ([`run_grouping_repair`]):
//! accepted groups freeze, repair rounds propose deltas for the remainder only, and
//! termination deterministically places every remaining item in the ungrouped section.

use serde::Deserialize;
use std::collections::HashSet;
use std::fmt::Write as _;
use std::time::Instant;

use crate::retry::{FailureClass, RetryFailureRecord, RetryLoop, RetryPolicy};
use crate::{ChatRequest, ChatRequestMeta, Workspace};

/// One member of a group: a flat global item id (matching the `{id}: {text}` input numbering),
/// resolved to (agent, text) by the operation's [`ItemTable`], never by the model.
///
/// A member is a REPRESENTATIVE for one distinct fact: the first raised id is `id`, the duplicate
/// same-fact ids go in [`Self::collapsed_ids`]. Collapsed ids are placed by the group but never
/// rendered as members of their own.
#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct GroupingMember {
    /// Flat global item id, 0-based across all sources combined.
    pub id: usize,
    /// Duplicate same-fact ids collapsed under this representative.
    #[serde(default)]
    pub collapsed_ids: Vec<usize>,
}

impl GroupingMember {
    /// The representative id followed by every collapsed id, in order — the full set of
    /// ids this member places. Order matters: the representative comes first (its text is
    /// preferred for display).
    pub(crate) fn ids(&self) -> impl Iterator<Item = usize> + '_ {
        std::iter::once(self.id).chain(self.collapsed_ids.iter().copied())
    }
}

/// A group of related items plus the LLM's contradiction judgment.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct GroupingGroup {
    pub heading: String,
    /// Set by the LLM only for genuine contradictions between agents.
    #[serde(default)]
    pub contradiction: bool,
    pub members: Vec<GroupingMember>,
}

/// The full grouping output: summary prose, groups, and an explicit ungrouped list (a
/// valid, visible destination — silent dropout is rejected).
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct GroupingOutput {
    pub summary: String,
    pub groups: Vec<GroupingGroup>,
    #[serde(default)]
    pub ungrouped: Vec<GroupingMember>,
}

/// A repair-round proposal: only new groups for REMAINING items, an explicit ungrouped
/// list (completeness, never final), optional contradiction references from remainder items
/// to frozen groups, and an optional summary (accepted only when none was yet).
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
struct GroupingDelta {
    #[serde(default)]
    pub summary: Option<String>,
    #[serde(default)]
    pub groups: Vec<GroupingGroup>,
    #[serde(default)]
    pub ungrouped: Vec<GroupingMember>,
    #[serde(default)]
    pub references: Vec<GroupingReference>,
}

/// A remainder item contradicting a frozen group: renders with DISPUTED and a
/// code-computed cross-reference to it — the frozen group never changes. The group index is
/// stable because frozen groups are append-only.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct GroupingReference {
    /// Index into the frozen-groups list (0-based, matching the prompt skeletons).
    pub group: usize,
    /// The remainder item flagging the contradiction.
    pub member: GroupingMember,
}

/// Outcome of the repair-mode grouping pass (pipeline synthesis + analyze consolidation).
pub(crate) enum RepairOutcome {
    /// Frozen groups + first-accepted summary + a code-computed ungrouped remainder.
    /// `references` attach DISPUTED cross-references from remainder items to frozen groups.
    Repaired {
        output: GroupingOutput,
        references: Vec<GroupingReference>,
    },
    Fallback,
}

/// Global flat id → (agent, item index) for one grouping operation. Ids are assigned once
/// per operation across the whole input, in (agent, item) order; the model refers to items
/// by id only.
///
/// A wrong-but-valid id is accepted by design: validation is structural only, and the LLM's
/// semantic judgment is the only correctness gate. Never re-add text-equality membership
/// checks — they only create a false sense of safety.
pub(crate) struct ItemTable<'a> {
    /// id → (agent index, item index within that agent's list).
    rows: Vec<(usize, usize)>,
    items_by_agent: &'a [Vec<String>],
}

impl<'a> ItemTable<'a> {
    #[must_use]
    pub(crate) fn new(items_by_agent: &'a [Vec<String>]) -> Self {
        let mut rows = Vec::new();
        for (agent, items) in items_by_agent.iter().enumerate() {
            for i in 0..items.len() {
                rows.push((agent, i));
            }
        }
        Self {
            rows,
            items_by_agent,
        }
    }

    /// Total item count across all sources.
    #[must_use]
    pub(crate) fn len(&self) -> usize {
        self.rows.len()
    }

    /// Resolve an id to its (agent, text) — `None` when out of range.
    #[must_use]
    pub(crate) fn resolve(&self, id: usize) -> Option<(usize, &str)> {
        let (agent, item) = *self.rows.get(id)?;
        let text = self.items_by_agent.get(agent)?.get(item)?;
        Some((agent, text))
    }

    /// Resolve an id to its (agent, per-agent item index) — `None` when out of range.
    #[must_use]
    pub(crate) fn resolve_index(&self, id: usize) -> Option<(usize, usize)> {
        self.rows.get(id).copied()
    }

    /// Agent index of an id — `None` when out of range.
    #[must_use]
    fn agent(&self, id: usize) -> Option<usize> {
        self.rows.get(id).map(|r| r.0)
    }
}

/// Distinct cited agent ids of a group, sorted (out-of-range ids are ignored — validation
/// rejects them before rendering). Collapsed ids count too, so the bracket reflects every
/// agent behind a representative.
#[must_use]
pub(crate) fn distinct_agents(group: &GroupingGroup, table: &ItemTable<'_>) -> Vec<usize> {
    let mut agents: Vec<usize> = group
        .members
        .iter()
        .flat_map(|m| m.ids().filter_map(|id| table.agent(id)))
        .collect();
    agents.sort_unstable();
    agents.dedup();
    agents
}

/// `[n/N]`, with ` · DISPUTED` appended only for a genuine contradiction (which validation
/// guarantees implies ≥2 distinct cited agents). Solo `[1/N]` renders without it.
#[must_use]
pub(crate) fn bracket_label(n: usize, n_valid: usize, disputed: bool) -> String {
    if disputed {
        format!("[{n}/{n_valid} · DISPUTED]")
    } else {
        format!("[{n}/{n_valid}]")
    }
}

/// One member line attributed to its source: `Agent N: text`.
#[must_use]
pub(crate) fn render_member_line(member: &GroupingMember, table: &ItemTable<'_>) -> String {
    match table.resolve(member.id) {
        Some((agent, text)) => format!("Agent {agent}: {text}"),
        None => format!("Agent ?: <unknown item id {}>", member.id),
    }
}

/// `Agent N:\n- id: text` input material for the grouping pass — global flat ids across all
/// agents, matching the schema's `id` field.
#[must_use]
pub(crate) fn numbered_items_material(items_by_agent: &[Vec<String>]) -> String {
    let mut material = String::new();
    let mut id = 0usize;
    for (agent_idx, items) in items_by_agent.iter().enumerate() {
        if items.is_empty() {
            continue;
        }
        let _ = writeln!(material, "Agent {agent_idx}:");
        for item in items {
            let _ = writeln!(material, "- {id}: {item}");
            id += 1;
        }
    }
    material
}

/// The ungrouped remainder section: header plus one member line each with the code-computed
/// DISPUTED suffix. Every remaining item lands here exactly once.
#[must_use]
pub(crate) fn render_ungrouped_section(
    output: &GroupingOutput,
    references: &[GroupingReference],
    render_member: impl Fn(&GroupingMember, &str) -> String,
) -> String {
    if output.ungrouped.is_empty() {
        return String::new();
    }
    let mut out = String::from("\n\n**Other**");
    for member in &output.ungrouped {
        let mut disputed = String::new();
        for reference in references.iter().filter(|r| r.member.id == member.id) {
            if let Some(group) = output.groups.get(reference.group) {
                let _ = write!(
                    disputed,
                    " [DISPUTED — contradicts group {} \"{}\"]",
                    reference.group, group.heading
                );
            }
        }
        let _ = write!(out, "\n- {}", render_member(member, &disputed));
    }
    out
}

/// Mutable state of the repair protocol across rounds.
struct RepairState<'a> {
    /// Global flat id table for this operation (id → agent, text).
    table: ItemTable<'a>,
    /// Accepted (frozen) groups in order — indices are stable references.
    frozen_groups: Vec<GroupingGroup>,
    /// Ids of frozen-group members — placement bookkeeping.
    placed: HashSet<usize>,
    /// Accepted contradiction references (remainder item id → frozen group idx).
    references: Vec<GroupingReference>,
    /// Ids pinned to the remainder by an accepted reference — they can never be placed in
    /// a group, so the DISPUTED render stays visible and `accepted_refs` never goes stale.
    pinned: HashSet<usize>,
    /// First accepted summary (never revised).
    summary: Option<String>,
}

impl<'a> RepairState<'a> {
    fn new(items_by_agent: &'a [Vec<String>]) -> Self {
        Self {
            table: ItemTable::new(items_by_agent),
            frozen_groups: Vec::new(),
            placed: HashSet::new(),
            references: Vec::new(),
            pinned: HashSet::new(),
            summary: None,
        }
    }

    /// Deterministic remainder: every non-placed item id in global order.
    #[must_use]
    fn remainder(&self) -> Vec<usize> {
        (0..self.table.len())
            .filter(|id| !self.placed.contains(id))
            .collect()
    }

    /// True when every non-placed item is pinned by an accepted reference — nothing left to
    /// place, so the run terminates without a redundant empty round.
    #[must_use]
    fn complete(&self) -> bool {
        (0..self.table.len()).all(|id| self.placed.contains(&id) || self.pinned.contains(&id))
    }
}

/// One round's proposal, parsed from the full schema (round 1) or the repair-delta one.
struct RoundInput {
    pub summary: Option<String>,
    pub groups: Vec<GroupingGroup>,
    pub ungrouped: Vec<GroupingMember>,
    pub references: Vec<GroupingReference>,
}

/// Per-round acceptance result.
#[derive(Default)]
struct RoundOutcome {
    /// Round-level rejection (incomplete coverage) — nothing froze this round.
    pub round_rejection: Option<String>,
    /// Per-group/per-entry rejections fed to the next round, each with its typed cause (no
    /// substring classification of message wording).
    pub rejections: Vec<(FailureClass, String)>,
    /// Newly frozen groups.
    pub froze: usize,
    /// Newly accepted contradiction references.
    pub accepted_refs: usize,
    /// A summary was accepted this round.
    pub accepted_summary: bool,
}

/// Id-range check for one member. Text membership is deliberately NOT checked — ids are the
/// only references (see [`ItemTable`]).
fn member_range_error(member: &GroupingMember, table: &ItemTable<'_>) -> Option<String> {
    (member.id >= table.len()).then(|| format!("unknown item id {}", member.id))
}

/// Push a typed rejection onto the outcome.
fn reject(outcome: &mut RoundOutcome, cause: FailureClass, msg: String) {
    outcome.rejections.push((cause, msg));
}

/// Global completeness on the RAW proposal (silent dropout rejects the round), then the summary
/// (first accepted wins), then per-group acceptance (id range, no already-placed member), then
/// ungrouped entries and contradiction references. Rejected groups are dropped with reasons;
/// accepted ones freeze immediately. Structural only — see [`ItemTable`].
#[expect(clippy::too_many_lines)]
fn process_round(input: RoundInput, state: &mut RepairState<'_>) -> RoundOutcome {
    let RoundInput {
        summary,
        groups,
        ungrouped,
        references,
    } = input;
    let mut outcome = RoundOutcome::default();

    // Round-level completeness on the RAW proposal: every unfrozen item id must appear in a
    // proposed group or the ungrouped list.
    let mut raw: HashSet<usize> = HashSet::new();
    for g in &groups {
        raw.extend(g.members.iter().flat_map(GroupingMember::ids));
    }
    raw.extend(ungrouped.iter().map(|m| m.id));
    for id in 0..state.table.len() {
        // Placed and pinned items need not be re-proposed this round.
        if state.placed.contains(&id) || state.pinned.contains(&id) {
            continue;
        }
        if !raw.contains(&id) {
            outcome.round_rejection = Some(format!(
                "item {id} missing from every proposed group and the ungrouped list"
            ));
            return outcome;
        }
    }

    // Summary: first accepted is final; repair rounds may supply one only when none was.
    if state.summary.is_none() {
        if let Some(s) = summary.as_deref().filter(|s| !s.trim().is_empty()) {
            state.summary = Some(s.trim().to_string());
            outcome.accepted_summary = true;
        } else {
            reject(
                &mut outcome,
                FailureClass::ValidationOther,
                "summary is empty or missing — supply a non-empty summary".to_string(),
            );
        }
    }

    // Per-group acceptance, first placement winning within the round. The telemetry cause is
    // first-wins, so a multi-defect group never loses its primary cause.
    for (i, group) in groups.into_iter().enumerate() {
        let mut reasons: Vec<String> = Vec::new();
        let mut cause: Option<FailureClass> = None;
        if group.members.is_empty() {
            reasons.push("group has no members".to_string());
            cause.get_or_insert(FailureClass::Membership);
        }
        if group.heading.trim().is_empty() {
            reasons.push("empty heading".to_string());
            cause.get_or_insert(FailureClass::ValidationOther);
        }
        if group.contradiction && distinct_agents(&group, &state.table).len() < 2 {
            reasons.push("contradiction without ≥2 distinct cited agents".to_string());
            cause.get_or_insert(FailureClass::ContradictionAgents);
        }
        // Intra-group duplicate ids are rejected (a member is placed once per round;
        // already-placed/pinned ones are rejected below). A member's collapsed_ids are
        // validated too: in range, unpinned, unplaced, and no duplicate of another group id.
        let mut seen: HashSet<usize> = HashSet::new();
        for member in &group.members {
            if !seen.insert(member.id) {
                reasons.push("duplicate member within the group".to_string());
            } else if state.pinned.contains(&member.id) {
                reasons.push(
                    "member has an accepted contradiction reference and must remain ungrouped"
                        .to_string(),
                );
            } else if let Some(msg) = member_range_error(member, &state.table) {
                reasons.push(msg);
            } else if state.placed.contains(&member.id) {
                reasons.push("member already placed in a frozen group".to_string());
            }
            cause.get_or_insert(FailureClass::Membership);
            for &cid in &member.collapsed_ids {
                if cid == member.id {
                    reasons.push("collapsed id equals its own member id".to_string());
                } else if !seen.insert(cid) {
                    reasons.push("duplicate collapsed id within the group".to_string());
                } else if state.pinned.contains(&cid) {
                    reasons.push(
                        "collapsed id has an accepted contradiction reference and must remain ungrouped"
                            .to_string(),
                    );
                } else if cid >= state.table.len() {
                    reasons.push(format!("unknown collapsed item id {cid}"));
                } else if state.placed.contains(&cid) {
                    reasons.push("collapsed id already placed in a frozen group".to_string());
                }
                cause.get_or_insert(FailureClass::Membership);
            }
        }
        if reasons.is_empty() {
            for member in &group.members {
                state.placed.extend(member.ids());
            }
            state.frozen_groups.push(group);
            outcome.froze += 1;
        } else {
            reject(
                &mut outcome,
                // Never None: the pre-member guards above set a cause directly, and every
                // member/collapsed-id rejection is followed by a
                // `get_or_insert(FailureClass::Membership)`.
                cause.unwrap(),
                format!("group {i}: {}", reasons.join("; ")),
            );
        }
    }

    // Ungrouped entries: per-member id-range validation, invalid ones dropped with reasons
    // (completeness was already satisfied); an already-placed entry is dropped silently — the
    // placement wins.
    for (i, member) in ungrouped.into_iter().enumerate() {
        if let Some(msg) = member_range_error(&member, &state.table) {
            reject(
                &mut outcome,
                FailureClass::Membership,
                format!("ungrouped entry {i}: {msg}"),
            );
        }
    }

    // Contradiction references to frozen groups.
    for (i, reference) in references.into_iter().enumerate() {
        if reference.group >= state.frozen_groups.len() {
            reject(
                &mut outcome,
                FailureClass::ValidationOther,
                format!(
                    "reference {i}: unknown frozen group index {}",
                    reference.group
                ),
            );
            continue;
        }
        if state.frozen_groups[reference.group].contradiction {
            continue; // cosmetic duplicate — never a rejection
        }
        if state
            .references
            .iter()
            .any(|r| r.group == reference.group && r.member.id == reference.member.id)
        {
            continue; // already accepted — cosmetic duplicate
        }
        if let Some(msg) = member_range_error(&reference.member, &state.table) {
            reject(
                &mut outcome,
                FailureClass::Membership,
                format!("reference {i}: {msg}"),
            );
            continue;
        }
        if state.placed.contains(&reference.member.id) {
            reject(
                &mut outcome,
                FailureClass::Membership,
                format!("reference {i}: member already placed in a frozen group"),
            );
            continue;
        }
        let mut agents = distinct_agents(&state.frozen_groups[reference.group], &state.table);
        if let Some(agent) = state.table.agent(reference.member.id)
            && !agents.contains(&agent)
        {
            agents.push(agent);
        }
        if agents.len() < 2 {
            reject(
                &mut outcome,
                FailureClass::ContradictionAgents,
                format!("reference {i}: contradiction without ≥2 distinct cited agents"),
            );
            continue;
        }
        state.pinned.insert(reference.member.id);
        state.references.push(reference);
        outcome.accepted_refs += 1;
    }
    outcome
}

/// How the previous round ended, so the next repair section is honest: a transport failure or parse
/// error never claims the response was rejected, a fully-accepted round never claims a rejection.
#[derive(Clone, Copy, Debug)]
enum PrevRound {
    /// The previous call did not complete (transport failure).
    Transport,
    /// The previous response could not be parsed.
    Parse,
    /// The previous round parsed and processed.
    Processed {
        /// Whether the round accepted anything (groups, a reference, the first summary) —
        /// distinguishes "partially accepted" from "rejected".
        accepted: bool,
    },
}

/// In-Rust fallback framings, indexed by the [`PrevRound`] selection order below. Used only
/// when `synthesis/repair_framing.md` is missing or truncated (warn and keep the literal).
const REPAIR_FRAMING_FALLBACK: [&str; 5] = [
    "The previous call did not complete (transport failure) — please respond now with the repair delta.",
    "Your previous response could not be parsed — please respond now with the repair delta.",
    "Your previous response was rejected — the rejected proposals are listed below.",
    "Your previous response was accepted; the remaining items below still need placement.",
    "Your previous response was partially accepted; rejected proposals are listed below.",
];

/// The framing sentence for `prev`, selected by index from `synthesis/repair_framing.md`
/// (section order is a contract — see the asset's trailing comment; reordering silently
/// misselects). The lookup is bounded to the framing sections, so the trailing comment is
/// never selectable. Degrades with a warning, never a panic: an unmatched variant yields an
/// empty framing. A new variant must extend the match arm, the asset, the fallback consts and
/// the test tables.
fn repair_framing(prev: PrevRound, rejections: &[String]) -> String {
    let idx = match prev {
        PrevRound::Transport => 0,
        PrevRound::Parse => 1,
        PrevRound::Processed { accepted: false } => 2,
        PrevRound::Processed { accepted: true } if rejections.is_empty() => 3,
        PrevRound::Processed { accepted: true } => 4,
    };
    let sections = crate::prompt::load_prompt_sections("synthesis/repair_framing.md");
    let bounded = sections.get(..REPAIR_FRAMING_FALLBACK.len());
    bounded
        .and_then(|framings| framings.get(idx))
        .cloned()
        .unwrap_or_else(|| {
            let fallback = REPAIR_FRAMING_FALLBACK
                .get(idx)
                .copied()
                .unwrap_or_default();
            tracing::warn!(
                asset = "synthesis/repair_framing.md",
                framing_sections = sections.len().min(REPAIR_FRAMING_FALLBACK.len()),
                index = idx,
                "repair framing section unavailable — using {}",
                if fallback.is_empty() {
                    "an empty framing (no fallback const for this index)"
                } else {
                    "the in-Rust fallback literal"
                }
            );
            fallback.to_owned()
        })
}

/// Append the repair-round instructions (delta schema, frozen skeletons, remainder list,
/// previous-round feedback) to the last user message. Append-only: the message prefix stays
/// byte-identical across rounds, preserving the KV prefix.
fn append_repair_instructions(
    request: &mut ChatRequest,
    round: u32,
    state: &RepairState<'_>,
    rejections: &[String],
    prev: PrevRound,
) {
    let framing = repair_framing(prev, rejections);
    // Section bodies align with the template's newline structure: the rejections slot keeps
    // its conditional leading separator (a static one would leave a stray blank line when
    // empty); the frozen and remainder slots carry only writeln list lines, whose trailing
    // newline plus the template's following newline supply the blank line between blocks
    // (byte-identical assembly, pinned by the tests).
    let mut rejections_section = String::new();
    if !rejections.is_empty() {
        rejections_section.push_str("\nRejected proposals still outstanding (fix these):\n");
        for r in rejections {
            let _ = writeln!(rejections_section, "- {r}");
        }
    }
    let mut frozen_groups_lines = String::new();
    if state.frozen_groups.is_empty() {
        frozen_groups_lines.push_str("- none\n");
    } else {
        for (i, g) in state.frozen_groups.iter().enumerate() {
            let agents = distinct_agents(g, &state.table)
                .iter()
                .map(usize::to_string)
                .collect::<Vec<_>>()
                .join(", ");
            let representative = g.members.first().map_or_else(
                || "—".to_string(),
                |m| format!("{} (id {})", render_member_line(m, &state.table), m.id),
            );
            let _ = writeln!(
                frozen_groups_lines,
                "- {i}: {:?} [agents {agents}, contradiction: {}] — e.g. {representative}",
                g.heading, g.contradiction,
            );
        }
    }
    let mut remainder_lines = String::new();
    for id in state.remainder() {
        let line = render_member_line(
            &GroupingMember {
                id,
                ..Default::default()
            },
            &state.table,
        );
        if state.pinned.contains(&id) {
            let _ = writeln!(
                remainder_lines,
                "- {id}: {line} [pinned — accepted contradiction reference; do NOT place in a group]"
            );
        } else {
            let _ = writeln!(remainder_lines, "- {id}: {line}");
        }
    }
    let section = crate::prompt::substitute(
        &crate::prompt::load_prompt("synthesis/repair_round.md"),
        &[
            ("{{round}}", &round.to_string()),
            ("{{framing}}", &framing),
            ("{{rejections_section}}", &rejections_section),
            ("{{frozen_groups_lines}}", &frozen_groups_lines),
            ("{{remainder_lines}}", &remainder_lines),
        ],
    );
    if let Some(last) = request.messages.last_mut() {
        last.content.push_str(&section);
    }
}

/// Run the repair-mode grouping pass: 1 full synthesis call + up to N-1 repair rounds (N = 3,
/// the lower edge of the approved 3–5 band). Accepted groups freeze; repair rounds propose deltas
/// for the remainder only. Termination — zero-progress or budget exhaustion — places every
/// remaining item deterministically in the ungrouped section; fail-open fires only on
/// transport/parse/non-retryable exhaustion, or an exhaustion with zero groups ever frozen.
///
/// Validation and parse rejections consume a round immediately (no backoff); transport failures
/// keep the synthesis schedule, indexed by the transport-failure count so a rejected round never
/// advances the backoff slot. The schedule is bounded by attempts, not wall time. A round-1 parse
/// failure permanently converts the run to the repair-delta schema.
///
/// Rejection feedback is one-shot for fully-rejected rounds: one failing completeness freezes zero
/// groups and trips the zero-progress break before the fed-back reasons can be acted on.
///
/// Telemetry: a round that accepts anything is a SUCCESS through the per-call path; one that
/// accepts nothing is a FAILURE with a typed granular cause, including clean zero-progress rounds
/// (the most common terminal shape), keeping the trail non-empty on Fallback. A Fallback may still
/// carry an earlier summary-only round's success row beside the operation-level failure row.
#[expect(clippy::too_many_lines)]
pub(crate) async fn run_grouping_repair(
    ws: &Workspace,
    purpose: &'static str,
    mut request: ChatRequest,
    items_by_agent: &[Vec<String>],
    parent: Option<crate::agent::registry::ParentKey>,
    parent_label: Option<String>,
) -> RepairOutcome {
    let _call = crate::agent::registry::NON_AGENT_CALLS.register(
        purpose,
        &ws.name,
        parent,
        false,
        parent_label,
    );
    crate::prompt::prepend_general_context(&mut request.messages, ws).await;
    let policy = RetryPolicy::synthesis();
    let mut loop_state = RetryLoop::new_scoped(&policy, &request);
    let operation_started = Instant::now();
    let mut state = RepairState::new(items_by_agent);
    // Rejection reasons for the next repair round; cleared only once a round responds, so
    // feedback survives a mid-repair transport failure.
    let mut rejections: Vec<String> = Vec::new();
    // How the previous round ended — frames the next repair section honestly.
    let mut prev_round = PrevRound::Processed { accepted: false };
    // Transport-failure count — indexes the backoff schedule independently of the round
    // number (validation rejections consume a round without a sleep).
    let mut transport_failures: u32 = 0;

    for round in 1..=policy.max_attempts {
        let attempt_started = Instant::now();
        loop_state.begin_attempt(attempt_started);
        if round > 1 {
            append_repair_instructions(&mut request, round, &state, &rejections, prev_round);
        }
        let resp = match crate::providers::chat_scoped(request.clone()).await {
            Ok(resp) => resp,
            Err(err) => {
                let non_retryable = !err.class.is_retryable();
                loop_state.record(err.record);
                if non_retryable {
                    break;
                }
                transport_failures += 1;
                if round < policy.max_attempts
                    && let Err(FailureClass::Shutdown) =
                        loop_state.sleep_between(transport_failures).await
                {
                    break;
                }
                prev_round = PrevRound::Transport;
                continue;
            }
        };
        let raw = resp.text_or_empty();
        // A tool-call response parses as empty text — classify it explicitly so the retry
        // trail distinguishes it (same taxonomy as extraction).
        if !resp.tool_calls.is_empty() {
            let rec = RetryFailureRecord::with_metadata(
                FailureClass::Parse,
                &anyhow::anyhow!("grouping response returned a tool call instead of JSON"),
                resp.finish_reason.clone(),
                None,
            );
            loop_state.record(rec);
            prev_round = PrevRound::Parse;
            continue;
        }
        let parsed: Result<RoundInput, _> = if round == 1 {
            crate::util::json::parse_fenced_json::<GroupingOutput>(raw).map(|o| RoundInput {
                summary: Some(o.summary),
                groups: o.groups,
                ungrouped: o.ungrouped,
                references: Vec::new(),
            })
        } else {
            crate::util::json::parse_fenced_json::<GroupingDelta>(raw).map(|d| RoundInput {
                summary: d.summary,
                groups: d.groups,
                ungrouped: d.ungrouped,
                references: d.references,
            })
        };
        let outcome = match parsed {
            Ok(input) => {
                let outcome = process_round(input, &mut state);
                // Deliver the previous round's rejection feedback (appended above), then
                // replace it with this round's. A transport or parse failure never clears it,
                // so feedback survives a mid-repair outage.
                rejections.clear();
                if let Some(msg) = &outcome.round_rejection {
                    rejections.push(msg.clone());
                }
                rejections.extend(outcome.rejections.iter().map(|(_, msg)| msg.clone()));
                outcome
            }
            Err(e) => {
                let rec = RetryFailureRecord::with_metadata(
                    FailureClass::Parse,
                    &e,
                    resp.finish_reason.clone(),
                    None,
                );
                loop_state.record(rec);
                prev_round = PrevRound::Parse;
                continue;
            }
        };
        // A round that accepted anything is a success, recorded per-round through the
        // per-call path (usage tokens, the calibration signal). A round is never both a
        // success and a failure row in llm_requests.
        let accepted = outcome.froze > 0 || outcome.accepted_refs > 0 || outcome.accepted_summary;
        prev_round = PrevRound::Processed { accepted };
        if accepted {
            crate::stats::record_llm_success(&request, attempt_started, round, &resp);
        }
        // Typed granular cause: completeness (round-level) or the first per-group/per-entry cause.
        let cause = if outcome.round_rejection.is_some() {
            FailureClass::Completeness
        } else {
            outcome
                .rejections
                .first()
                .map_or(FailureClass::ValidationOther, |(c, _)| *c)
        };
        tracing::debug!(
            purpose,
            workspace = %ws.name,
            round,
            accepted,
            froze = outcome.froze,
            refs = outcome.accepted_refs,
            summary = outcome.accepted_summary,
            rejections = outcome.rejections.len(),
            cause = cause.label(),
            "Grouping synthesis repair round",
        );
        // A parsed-and-processed round that accepted NOTHING is a failure with the typed
        // cause, including clean zero-progress rounds (the most common terminal shape).
        // Recording them keeps the trail non-empty, so a later Fallback never mislabels the
        // operation as `transport`/`retry_attempts=0`.
        if !accepted {
            let detail = if rejections.is_empty() {
                "round accepted nothing (zero-progress; no validation rejections)".to_string()
            } else {
                rejections.join("; ")
            };
            let err = anyhow::anyhow!("grouping validation failed: {detail}");
            let rec =
                RetryFailureRecord::with_metadata(cause, &err, resp.finish_reason.clone(), None);
            loop_state.record(rec);
        }
        if state.complete() {
            break; // every item is frozen or pinned — nothing left to place
        }
        if round > 1 && outcome.froze == 0 {
            break; // zero-progress repair round — stop immediately
        }
    }

    if state.frozen_groups.is_empty() {
        tracing::warn!(
            purpose,
            workspace = %ws.name,
            attempts = policy.max_attempts,
            "Grouping synthesis exhausted — writing deterministic fail-open output",
        );
        // A Fallback with an empty failure trail (e.g. a summary-only round at
        // max_attempts=1) would be classified `transport`/`retry_attempts=0` — spurious.
        // Record the real cause.
        if !loop_state.has_failures() {
            let detail = if state.summary.is_some() {
                "operation exhausted after accepting only a summary — no groups ever frozen"
            } else {
                "operation exhausted with no accepted output"
            };
            let rec = RetryFailureRecord::new_simple(
                FailureClass::ValidationOther,
                &anyhow::anyhow!("{detail}"),
                None,
            );
            // Trail-only: no HTTP attempt failed here — no llm_failures row.
            loop_state.record_trail_only(rec);
        }
        let final_class = loop_state.final_class();
        let exhausted = crate::retry::RetryExhausted::with_last_raw(
            loop_state.into_failures(),
            final_class,
            None,
        );
        crate::stats::record_llm_failure(&request, operation_started, &exhausted);
        return RepairOutcome::Fallback;
    }
    let ungrouped: Vec<GroupingMember> = state
        .remainder()
        .into_iter()
        .map(|id| GroupingMember {
            id,
            ..Default::default()
        })
        .collect();
    tracing::info!(
        purpose,
        workspace = %ws.name,
        groups = state.frozen_groups.len(),
        ungrouped = ungrouped.len(),
        "Grouping synthesis repaired",
    );
    RepairOutcome::Repaired {
        output: GroupingOutput {
            summary: state.summary.unwrap_or_default(),
            groups: state.frozen_groups,
            ungrouped,
        },
        references: state.references,
    }
}

/// Grouping request with the consumer-supplied system prompt, user material,
/// model/effort/routing/max_tokens. `meta` purpose and agent id are filled in here so the
/// consumer gets a uniform telemetry shape. The pipeline joint-verdict path deliberately
/// builds its own `ChatRequest` instead (`pipeline::verdict::synthesis_request`) — its
/// telemetry differs on purpose.
#[expect(clippy::too_many_arguments)]
pub(crate) fn grouping_request(
    ws: &Workspace,
    purpose: &'static str,
    system: &str,
    user: &str,
    model: String,
    reasoning_effort: Option<String>,
    provider_order: Option<String>,
    max_tokens: Option<u32>,
) -> ChatRequest {
    ChatRequest {
        messages: vec![
            crate::ChatMessage::system(system),
            crate::ChatMessage::user(user),
        ],
        tools: None,
        model,
        max_tokens,
        reasoning_effort,
        provider_order,
        meta: Some(ChatRequestMeta {
            purpose,
            agent_id: format!("grouping_{}_{}", ws.name, crate::generate_suffix()),
            role: "grouping".to_string(),
            workspace: ws.name.clone(),
            ticket_id: None,
        }),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Collapse semantics: a representative freezes and places every collapsed id (so the
    /// remainder excludes them), the distinct-agent count includes the collapsed agents, and a
    /// round is complete when an id's only coverage is via `collapsed_ids`. A collapsed id that
    /// ALSO appears as an ungrouped entry is accepted — placement wins, the duplicate dropped.
    #[test]
    fn collapsed_ids_freeze_place_and_count() {
        // Three items across three agents: id → agent idx.
        let items = vec![
            vec!["a".to_string()],
            vec!["b".to_string()],
            vec!["c".to_string()],
        ];
        let mut state = RepairState::new(&items);

        // Ids 1 and 2 are covered ONLY via collapsed_ids on representative 0 — the
        // raw-proposal completeness check must accept the round.
        let outcome = process_round(
            RoundInput {
                summary: Some("s".to_string()),
                groups: vec![GroupingGroup {
                    heading: "G".to_string(),
                    contradiction: false,
                    members: vec![GroupingMember {
                        id: 0,
                        collapsed_ids: vec![1, 2],
                    }],
                }],
                ungrouped: Vec::new(),
                references: Vec::new(),
            },
            &mut state,
        );
        assert!(outcome.round_rejection.is_none());
        assert!(outcome.rejections.is_empty());
        assert_eq!(outcome.froze, 1);
        // Collapse placement leaves nothing in the remainder.
        assert!(state.remainder().is_empty());
        assert_eq!(
            distinct_agents(&state.frozen_groups[0], &state.table),
            vec![0, 1, 2]
        );

        // A collapsed id that also appears as an ungrouped entry: placement wins, never a
        // rejection.
        let items2 = vec![vec!["a".to_string()], vec!["b".to_string()]];
        let mut state2 = RepairState::new(&items2);
        let outcome = process_round(
            RoundInput {
                summary: Some("s".to_string()),
                groups: vec![GroupingGroup {
                    heading: "G".to_string(),
                    contradiction: false,
                    members: vec![GroupingMember {
                        id: 0,
                        collapsed_ids: vec![1],
                    }],
                }],
                ungrouped: vec![GroupingMember {
                    id: 1,
                    ..Default::default()
                }],
                references: Vec::new(),
            },
            &mut state2,
        );
        assert!(outcome.round_rejection.is_none());
        assert!(outcome.rejections.is_empty());
        assert_eq!(outcome.froze, 1);
        assert!(state2.remainder().is_empty());
    }

    /// Byte-exact pin of the repair-instruction assembly for every PrevRound framing:
    /// framing sentence, headers, list lines and blank-line structure. Guards the asset's
    /// section order (a reordered or rewrapped section silently misselects) and the template's
    /// newline contract.
    ///
    /// Only the region this migration changed is hardcoded — the framings, the two moved
    /// headers, the list rendering and the newline coordination. Unchanged regions (prefix,
    /// lead-in line, schema tail) are derived from the asset, so unrelated prompt edits don't
    /// force syncing this test.
    #[expect(clippy::too_many_lines)] // 5 framings × scenarios: exhaustive byte pin of the moved prose
    #[test]
    fn repair_instructions_assembly_is_byte_exact() {
        // State: item 0 frozen in one group; item 1 stays in the remainder.
        let items = vec![vec!["first".to_string()], vec!["second".to_string()]];
        let mut state = RepairState::new(&items);
        let outcome = process_round(
            RoundInput {
                summary: Some("s".to_string()),
                groups: vec![GroupingGroup {
                    heading: "G".to_string(),
                    contradiction: false,
                    members: vec![GroupingMember {
                        id: 0,
                        ..Default::default()
                    }],
                }],
                ungrouped: vec![GroupingMember {
                    id: 1,
                    ..Default::default()
                }],
                references: Vec::new(),
            },
            &mut state,
        );
        assert_eq!(outcome.froze, 1);
        assert_eq!(state.remainder(), vec![1]);

        let rejections =
            vec!["item 1 missing from every proposed group and the ungrouped list".to_string()];

        // The in-Rust fallback must mirror the asset sections, or the degraded path changes
        // silently. The +1 is the asset's trailing order-contract comment section.
        let asset_sections = crate::prompt::load_prompt_sections("synthesis/repair_framing.md");
        let fallback: Vec<String> = REPAIR_FRAMING_FALLBACK
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(
            asset_sections.len(),
            REPAIR_FRAMING_FALLBACK.len() + 1,
            "repair_framing.md must hold the framing sections plus the order-contract comment"
        );
        assert_eq!(
            asset_sections.get(..REPAIR_FRAMING_FALLBACK.len()),
            Some(fallback.as_slice()),
            "fallback framings must mirror the asset sections"
        );

        // Derived unchanged regions: prefix, lead-in line after {{framing}}, schema tail.
        // Exactly one newline follows {{remainder_lines}} — the slot's trailing writeln supplies
        // the other half of the blank line before Respond (the empty-remainder edge).
        let template = crate::prompt::load_prompt("synthesis/repair_round.md");
        let (raw_prefix, after_framing) = template
            .split_once("{{framing}}")
            .expect("repair_round.md must keep the {{framing}} slot");
        let prefix = raw_prefix.replace("{{round}}", "2");
        let (lead_in, _) = after_framing
            .split_once("{{rejections_section}}")
            .expect("repair_round.md must keep the {{rejections_section}} slot");
        let (_, after_remainder) = template
            .split_once("{{remainder_lines}}")
            .expect("repair_round.md must keep the {{remainder_lines}} slot");
        let tail = after_remainder
            .strip_prefix('\n')
            .expect("repair_round.md must put a single newline after {{remainder_lines}}");
        assert!(
            !tail.starts_with('\n'),
            "repair_round.md must put exactly one newline after {{remainder_lines}}"
        );

        // Headers that moved into the template — pinned so a reword in the asset breaks the
        // test instead of silently changing the prompt.
        let frozen_header = "Frozen groups (skeletons — do NOT re-propose their members; references to a group flagged contradiction:true are ignored):\n";
        let remainder_header = "Remaining items (place EVERY un-pinned one in a proposed group or the ungrouped list; pinned items must NOT be placed in a group). Reference each item by its id:\n";
        let with_rejections = format!(
            "\nRejected proposals still outstanding (fix these):\n\
             - item 1 missing from every proposed group and the ungrouped list\n\
             \n{frozen_header}\
             - 0: \"G\" [agents 0, contradiction: false] — e.g. Agent 0: first (id 0)\n\
             \n{remainder_header}\
             - 1: Agent 1: second\n"
        );
        let without_rejections = format!(
            "\n{frozen_header}\
             - 0: \"G\" [agents 0, contradiction: false] — e.g. Agent 0: first (id 0)\n\
             \n{remainder_header}\
             - 1: Agent 1: second\n"
        );
        // Variants in asset section order (0-4); the bool is "no outstanding rejections",
        // selecting section 3 (accepted) vs 4 (partial).
        let variants: [(PrevRound, bool); 5] = [
            (PrevRound::Transport, false),
            (PrevRound::Parse, false),
            (PrevRound::Processed { accepted: false }, false),
            (PrevRound::Processed { accepted: true }, true),
            (PrevRound::Processed { accepted: true }, false),
        ];
        for (i, (prev, empty_rejections)) in variants.into_iter().enumerate() {
            let mut request =
                crate::providers::test_request(vec![crate::ChatMessage::user("")], None);
            append_repair_instructions(
                &mut request,
                2,
                &state,
                if empty_rejections { &[] } else { &rejections },
                prev,
            );
            let middle = if empty_rejections {
                &without_rejections
            } else {
                &with_rejections
            };
            let expected = format!(
                "{prefix}{framing}{lead_in}{middle}\n{tail}",
                framing = REPAIR_FRAMING_FALLBACK[i]
            );
            assert_eq!(
                request.messages.last().unwrap().content,
                expected,
                "variant {i}: framing misselection or newline drift"
            );
        }

        // Empty-frozen edge: `- none` under the frozen header.
        let no_frozen = RepairState::new(&items);
        let mut request = crate::providers::test_request(vec![crate::ChatMessage::user("")], None);
        append_repair_instructions(&mut request, 2, &no_frozen, &[], PrevRound::Transport);
        let empty_frozen = format!(
            "\n{frozen_header}\
             - none\n\
             \n{remainder_header}\
             - 0: Agent 0: first\n\
             - 1: Agent 1: second\n"
        );
        assert_eq!(
            request.messages.last().unwrap().content,
            format!(
                "{prefix}{framing}{lead_in}{empty_frozen}\n{tail}",
                framing = REPAIR_FRAMING_FALLBACK[0]
            ),
            "empty-frozen: `- none` line or newline drift"
        );

        // Pinned-marker path: an accepted reference pins item 1 to the remainder (it must
        // render with the marker, never in a group).
        let mut pinned_state = RepairState::new(&items);
        let outcome = process_round(
            RoundInput {
                summary: Some("s".to_string()),
                groups: vec![GroupingGroup {
                    heading: "G".to_string(),
                    contradiction: false,
                    members: vec![GroupingMember {
                        id: 0,
                        ..Default::default()
                    }],
                }],
                ungrouped: vec![GroupingMember {
                    id: 1,
                    ..Default::default()
                }],
                references: vec![GroupingReference {
                    member: GroupingMember {
                        id: 1,
                        ..Default::default()
                    },
                    group: 0,
                }],
            },
            &mut pinned_state,
        );
        assert_eq!(outcome.froze, 1);
        assert_eq!(outcome.accepted_refs, 1);
        let mut request = crate::providers::test_request(vec![crate::ChatMessage::user("")], None);
        append_repair_instructions(&mut request, 2, &pinned_state, &[], PrevRound::Transport);
        let pinned = format!(
            "\n{frozen_header}\
             - 0: \"G\" [agents 0, contradiction: false] — e.g. Agent 0: first (id 0)\n\
             \n{remainder_header}\
             - 1: Agent 1: second [pinned — accepted contradiction reference; do NOT place in a group]\n"
        );
        assert_eq!(
            request.messages.last().unwrap().content,
            format!(
                "{prefix}{framing}{lead_in}{pinned}\n{tail}",
                framing = REPAIR_FRAMING_FALLBACK[0]
            ),
            "pinned-marker: marker text or newline drift"
        );

        // Empty-remainder edge: all items frozen — the empty slot must still yield exactly one
        // blank line before Respond.
        let mut all_frozen = RepairState::new(&items);
        let outcome = process_round(
            RoundInput {
                summary: Some("s".to_string()),
                groups: vec![
                    GroupingGroup {
                        heading: "G".to_string(),
                        contradiction: false,
                        members: vec![GroupingMember {
                            id: 0,
                            ..Default::default()
                        }],
                    },
                    GroupingGroup {
                        heading: "G1".to_string(),
                        contradiction: false,
                        members: vec![GroupingMember {
                            id: 1,
                            ..Default::default()
                        }],
                    },
                ],
                ungrouped: Vec::new(),
                references: Vec::new(),
            },
            &mut all_frozen,
        );
        assert_eq!(outcome.froze, 2);
        assert!(all_frozen.remainder().is_empty());
        let mut request = crate::providers::test_request(vec![crate::ChatMessage::user("")], None);
        append_repair_instructions(&mut request, 2, &all_frozen, &[], PrevRound::Transport);
        let empty_remainder = format!(
            "\n{frozen_header}\
             - 0: \"G\" [agents 0, contradiction: false] — e.g. Agent 0: first (id 0)\n\
             - 1: \"G1\" [agents 1, contradiction: false] — e.g. Agent 1: second (id 1)\n\
             \n{remainder_header}"
        );
        assert_eq!(
            request.messages.last().unwrap().content,
            format!(
                "{prefix}{framing}{lead_in}{empty_remainder}\n{tail}",
                framing = REPAIR_FRAMING_FALLBACK[0]
            ),
            "empty-remainder: must not gain a blank line before Respond"
        );
    }

    /// Independent PrevRound → framing pin: each variant's sentence keeps its marker, and the
    /// marker set pairwise-distinguishes the five framings ("rejected" is shared with the
    /// partially-accepted sentence, but "partially" still catches that swap). A coordinated
    /// reorder of the asset and the fallback consts (invisible to the byte compare, which
    /// derives its expectation from the consts) cannot silently swap which sentence reaches the
    /// model. The markers are semantic invariants — dropping one changes the framing's meaning.
    #[test]
    fn repair_framing_mapping_is_pinned() {
        let rejections =
            vec!["item 1 missing from every proposed group and the ungrouped list".to_string()];
        let variants: [(PrevRound, &[String], &str); 5] = [
            (PrevRound::Transport, &[], "transport"),
            (PrevRound::Parse, &[], "parsed"),
            (PrevRound::Processed { accepted: false }, &[], "rejected"),
            (
                PrevRound::Processed { accepted: true },
                &[],
                "still need placement",
            ),
            (
                PrevRound::Processed { accepted: true },
                &rejections,
                "partially",
            ),
        ];
        let mut seen = HashSet::new();
        for (prev, outstanding, keyword) in variants {
            let framing = repair_framing(prev, outstanding);
            assert!(
                framing.contains(keyword),
                "framing for {prev:?} lost its disposition keyword {keyword:?}"
            );
            assert!(
                seen.insert(framing),
                "framings must be pairwise distinct for {prev:?}"
            );
        }
    }
}