git-paw 0.5.0

Parallel AI Worktrees — orchestrate multiple AI coding CLI sessions across git worktrees
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
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
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
//! Message routing, cursor-based polling, and log flush.
//!
//! Contains the core delivery logic for the broker: publishing messages
//! to agent inboxes, polling with cursor-based pagination, snapshot
//! queries for the dashboard, and the background log flush thread.

use std::collections::HashMap;
use std::fs::OpenOptions;
use std::io::Write;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, SystemTime};

use super::messages::BrokerMessage;
use super::{AgentRecord, AgentStatusEntry, BrokerState, BrokerStateInner};

/// Returns the sender's `agent_id` for a message.
///
/// For most variants this is the top-level `agent_id` field. For `Verified`
/// and `Feedback`, the `agent_id` identifies the target, so the sender lives
/// inside the payload (`verified_by` / `from`).
fn sender_id(msg: &BrokerMessage) -> &str {
    match msg {
        BrokerMessage::Status { agent_id, .. }
        | BrokerMessage::Artifact { agent_id, .. }
        | BrokerMessage::Blocked { agent_id, .. }
        | BrokerMessage::Question { agent_id, .. }
        | BrokerMessage::Intent { agent_id, .. } => agent_id,
        BrokerMessage::Verified { payload, .. } => &payload.verified_by,
        BrokerMessage::Feedback { payload, .. } => &payload.from,
    }
}
/// Updates (or creates) the agent record and inbox for the message sender.
fn update_agent_record(inner: &mut BrokerStateInner, msg: &BrokerMessage) {
    let agent_id = sender_id(msg).to_string();
    let status = msg.status_label().to_string();

    let record = inner
        .agents
        .entry(agent_id.clone())
        .or_insert_with(|| AgentRecord {
            agent_id: agent_id.clone(),
            status: String::new(),
            last_seen: std::time::Instant::now(),
            last_message: None,
        });

    // Make terminal states sticky: only update status if the new status is also terminal
    // or if the current status is not terminal
    let is_terminal_status = |s: &str| matches!(s, "done" | "verified" | "blocked" | "committed");

    if !is_terminal_status(&record.status) || is_terminal_status(&status) {
        record.status = status;
    }

    record.last_seen = std::time::Instant::now();
    record.last_message = Some(msg.clone());

    // Upsert the CLI map from any `agent.status` payload that names a CLI.
    // This is how the supervisor's CLI lands in `agent_clis` — coding agents
    // already populate the map from `WatchTarget` at broker start, but the
    // supervisor is not a watch target and self-registers with `cli`
    // populated in the status payload (supervisor-as-pane-followups D2).
    if let BrokerMessage::Status { payload, .. } = msg
        && let Some(cli) = payload.cli.as_ref()
        && !cli.is_empty()
    {
        inner.agent_clis.insert(agent_id.clone(), cli.clone());
    }

    // Ensure inbox exists for the sender
    inner.queues.entry(agent_id).or_default();
}

/// Publishes a message through the broker.
///
/// - Updates the sender's [`AgentRecord`]
/// - Assigns a global sequence number
/// - Routes the message to the appropriate inboxes:
///   - `Status` -- record update only, no inbox routing
///   - `Artifact` -- broadcast to every other registered agent's inbox
///   - `Blocked` -- delivered to `payload.from`'s inbox (if registered)
/// - Appends the message to the in-memory log
pub fn publish_message(state: &Arc<BrokerState>, msg: &BrokerMessage) {
    let seq = state.next_seq();
    {
        let mut inner = state.write();

        update_agent_record(&mut inner, msg);

        // Append to the in-memory message log
        inner
            .message_log
            .push((seq, SystemTime::now(), msg.clone()));

        // Route based on message type
        route_message(&mut inner, msg, seq);
    }

    // Forward to the learnings aggregator after delivery completes. The
    // aggregator only writes to a markdown file — it does NOT publish back
    // into the broker.
    if let Some(agg) = state.learnings.as_ref()
        && let Ok(mut a) = agg.lock()
    {
        a.observe(msg);
    }
}

fn route_message(inner: &mut BrokerStateInner, msg: &BrokerMessage, seq: u64) {
    match msg {
        BrokerMessage::Status { .. } => {
            // Status messages are informational only -- not routed to inboxes
        }
        BrokerMessage::Artifact { agent_id, .. } => {
            // Broadcast to every other agent's inbox
            let targets: Vec<String> = inner
                .queues
                .keys()
                .filter(|id| id.as_str() != agent_id)
                .cloned()
                .collect();
            for target in targets {
                if let Some(inbox) = inner.queues.get_mut(&target) {
                    inbox.push((seq, msg.clone()));
                }
            }
        }
        BrokerMessage::Blocked { payload, .. } => {
            // Deliver to the target agent's inbox if it exists
            if let Some(inbox) = inner.queues.get_mut(&payload.from) {
                inbox.push((seq, msg.clone()));
            }
            // Silently drop if target has no inbox (not yet registered)
        }
        BrokerMessage::Verified { payload, .. } => {
            // Broadcast to every other agent's inbox, skipping the verifier
            let sender = payload.verified_by.clone();
            let targets: Vec<String> = inner
                .queues
                .keys()
                .filter(|id| id.as_str() != sender.as_str())
                .cloned()
                .collect();
            for target in targets {
                if let Some(inbox) = inner.queues.get_mut(&target) {
                    inbox.push((seq, msg.clone()));
                }
            }
        }
        BrokerMessage::Feedback { agent_id, .. } => {
            // Deliver to the target agent's inbox if it exists
            if let Some(inbox) = inner.queues.get_mut(agent_id) {
                inbox.push((seq, msg.clone()));
            }
            // Silently drop if target has no inbox (not yet registered)
        }
        BrokerMessage::Question { .. } => {
            // Route to the supervisor inbox, creating it if absent.
            // Do NOT enqueue in sender's or any other agent's inbox.
            let inbox = inner.queues.entry("supervisor".to_string()).or_default();
            inbox.push((seq, msg.clone()));
        }
        BrokerMessage::Intent { agent_id, .. } => {
            // Broadcast to every other registered agent's inbox, skipping
            // the sender. Agents without an existing inbox are silently
            // skipped — same pattern as Artifact / Verified.
            let targets: Vec<String> = inner
                .queues
                .keys()
                .filter(|id| id.as_str() != agent_id)
                .cloned()
                .collect();
            for target in targets {
                if let Some(inbox) = inner.queues.get_mut(&target) {
                    inbox.push((seq, msg.clone()));
                }
            }
        }
    }
}

/// Polls an agent's inbox for messages newer than `since`.
///
/// Returns `(messages, last_seq)` where `last_seq` is the highest
/// sequence number in the result, or `0` if no messages match.
/// This is a non-destructive read -- messages remain in the inbox.
///
/// Uses a read lock only.
pub fn poll_messages(
    state: &Arc<BrokerState>,
    agent_id: &str,
    since: u64,
) -> (Vec<BrokerMessage>, u64) {
    let inner = state.read();

    let Some(inbox) = inner.queues.get(agent_id) else {
        return (Vec::new(), 0);
    };

    let mut messages = Vec::new();
    let mut last_seq: u64 = 0;

    for (seq, msg) in inbox {
        if *seq > since {
            messages.push(msg.clone());
            if *seq > last_seq {
                last_seq = *seq;
            }
        }
    }

    (messages, last_seq)
}

/// Returns the most recent broker messages for display in the dashboard.
///
/// Returns messages in reverse chronological order (newest first), limited
/// to the specified number of messages. Takes a read lock only during
/// the data copy operation.
pub fn recent_messages(
    state: &Arc<BrokerState>,
    limit: usize,
) -> Vec<(u64, std::time::SystemTime, BrokerMessage)> {
    let inner = state.read();
    inner
        .message_log
        .iter()
        .rev()
        .take(limit)
        .cloned()
        .collect()
}

/// Returns the broker's full message log, in chronological order (oldest
/// first), filtered to messages with `seq > since`. `since == 0` returns
/// every message.
///
/// Used by `cmd_supervisor` to reconstruct broker state from outside the
/// dashboard process: the supervisor runs in a different process from the
/// broker, so it cannot read [`BrokerState`] directly. Fetching the full
/// log over HTTP lets the supervisor rebuild a state-equivalent view for
/// merge-order decisions and the session-summary write.
///
/// Takes a read lock only during the data copy.
pub fn full_log(
    state: &Arc<BrokerState>,
    since: u64,
) -> Vec<(u64, std::time::SystemTime, BrokerMessage)> {
    let inner = state.read();
    inner
        .message_log
        .iter()
        .filter(|(seq, _, _)| *seq > since)
        .cloned()
        .collect()
}

/// Returns a snapshot of all known agents' status.
///
/// Takes a read lock, clones each record into an [`AgentStatusEntry`],
/// and releases the lock. The returned value is fully owned and can be
/// used for rendering or serialization without holding any lock.
pub fn agent_status_snapshot(state: &Arc<BrokerState>) -> Vec<AgentStatusEntry> {
    let inner = state.read();
    // Start from the watched-target CLI map so every known pane shows up
    // even before it has published a status message, then overlay any
    // agents that have actually published with their live status.
    let mut entries: HashMap<String, AgentStatusEntry> = inner
        .agent_clis
        .iter()
        .map(|(agent_id, cli)| {
            (
                agent_id.clone(),
                AgentStatusEntry {
                    agent_id: agent_id.clone(),
                    cli: cli.clone(),
                    status: "idle".to_string(),
                    last_seen_seconds: 0,
                    summary: String::new(),
                    last_seen: std::time::Instant::now(),
                    phase: None,
                },
            )
        })
        .collect();
    for r in inner.agents.values() {
        let cli = inner
            .agent_clis
            .get(&r.agent_id)
            .cloned()
            .unwrap_or_default();
        // Pull the most-recent `payload.phase` (if any) so the dashboard
        // can prefer it over the message-type-derived status label.
        let phase = if let Some(BrokerMessage::Status { payload, .. }) = r.last_message.as_ref() {
            payload.phase.clone()
        } else {
            None
        };
        entries.insert(
            r.agent_id.clone(),
            AgentStatusEntry {
                agent_id: r.agent_id.clone(),
                cli,
                status: r.status.clone(),
                last_seen_seconds: r.last_seen.elapsed().as_secs(),
                summary: String::new(),
                last_seen: r.last_seen,
                phase,
            },
        );
    }
    // Sort by agent_id so the dashboard rows stay in a stable order across
    // ticks — otherwise HashMap iteration order makes rows jitter on every
    // redraw.
    let mut out: Vec<AgentStatusEntry> = entries.into_values().collect();
    out.sort_by(|a, b| a.agent_id.cmp(&b.agent_id));
    out
}

/// Background loop that periodically flushes new log entries to disk.
///
/// Runs every ~5 seconds, reading new entries under a read lock and
/// writing them outside the lock. Performs a final flush when the
/// stop flag is set. Sleeps in small increments to enable prompt
/// shutdown (exits within ~100ms of the stop signal).
pub fn flush_loop(state: &Arc<BrokerState>, stop: &Arc<AtomicBool>) {
    let log_path = match &state.log_path {
        Some(p) => p.clone(),
        None => return,
    };

    let mut last_flushed_seq: u64 = 0;
    let flush_interval = Duration::from_secs(5);
    let check_interval = Duration::from_millis(100);

    loop {
        // Sleep in small increments, checking the stop flag
        let mut elapsed = Duration::ZERO;
        while elapsed < flush_interval {
            if stop.load(Ordering::Acquire) {
                flush_entries(state, &log_path, &mut last_flushed_seq);
                return;
            }
            std::thread::sleep(check_interval);
            elapsed += check_interval;
        }

        flush_entries(state, &log_path, &mut last_flushed_seq);
    }
}

/// Flushes log entries with `seq > last_flushed_seq` to the given path.
///
/// Updates `last_flushed_seq` to the highest flushed sequence number.
/// Disk write failures are silently ignored (best-effort).
fn flush_entries(state: &Arc<BrokerState>, log_path: &std::path::Path, last_flushed_seq: &mut u64) {
    let entries: Vec<(u64, SystemTime, BrokerMessage)> = {
        let inner = state.read();
        inner
            .message_log
            .iter()
            .filter(|(seq, _, _)| *seq > *last_flushed_seq)
            .cloned()
            .collect()
    };

    if entries.is_empty() {
        return;
    }

    let Ok(mut file) = OpenOptions::new().create(true).append(true).open(log_path) else {
        return; // Best-effort: silently ignore disk write failures
    };

    for (seq, timestamp, msg) in &entries {
        let ts = timestamp
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_or_else(|_| "0".to_string(), |d| d.as_secs().to_string());

        let line = format!("[{seq}] {ts} [{}] {msg}\n", msg.agent_id());
        let _ = file.write_all(line.as_bytes());
    }

    if let Some((max_seq, _, _)) = entries.last() {
        *last_flushed_seq = *max_seq;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::broker::messages::{
        ArtifactPayload, BlockedPayload, FeedbackPayload, IntentPayload, QuestionPayload,
        StatusPayload, VerifiedPayload,
    };
    use crate::broker::start_broker;
    use crate::config::BrokerConfig;

    fn make_status(agent_id: &str, status: &str) -> BrokerMessage {
        BrokerMessage::Status {
            agent_id: agent_id.to_string(),
            payload: StatusPayload {
                status: status.to_string(),
                modified_files: vec![],
                message: None,
                ..Default::default()
            },
        }
    }

    fn make_artifact(agent_id: &str, status: &str, exports: &[&str]) -> BrokerMessage {
        BrokerMessage::Artifact {
            agent_id: agent_id.to_string(),
            payload: ArtifactPayload {
                status: status.to_string(),
                exports: exports.iter().map(|s| (*s).to_string()).collect(),
                modified_files: vec!["src/main.rs".to_string()],
            },
        }
    }

    fn make_blocked(agent_id: &str, needs: &str, from: &str) -> BrokerMessage {
        BrokerMessage::Blocked {
            agent_id: agent_id.to_string(),
            payload: BlockedPayload {
                needs: needs.to_string(),
                from: from.to_string(),
            },
        }
    }

    fn make_verified(agent_id: &str, verified_by: &str, message: Option<&str>) -> BrokerMessage {
        BrokerMessage::Verified {
            agent_id: agent_id.to_string(),
            payload: VerifiedPayload {
                verified_by: verified_by.to_string(),
                message: message.map(str::to_string),
            },
        }
    }

    fn make_feedback(agent_id: &str, from: &str, errors: &[&str]) -> BrokerMessage {
        BrokerMessage::Feedback {
            agent_id: agent_id.to_string(),
            payload: FeedbackPayload {
                from: from.to_string(),
                errors: errors.iter().map(|s| (*s).to_string()).collect(),
            },
        }
    }

    fn make_question(agent_id: &str, question: &str) -> BrokerMessage {
        BrokerMessage::Question {
            agent_id: agent_id.to_string(),
            payload: QuestionPayload {
                question: question.to_string(),
            },
        }
    }

    fn make_intent(agent_id: &str, files: &[&str], summary: &str, ttl: u64) -> BrokerMessage {
        BrokerMessage::Intent {
            agent_id: agent_id.to_string(),
            payload: IntentPayload {
                files: files.iter().map(|s| (*s).to_string()).collect(),
                summary: summary.to_string(),
                valid_for_seconds: ttl,
            },
        }
    }

    fn fresh_state() -> Arc<BrokerState> {
        Arc::new(BrokerState::new(None))
    }

    // === Task 3: Message log accumulation ===

    #[test]
    fn message_log_accumulates_three_entries() {
        let state = fresh_state();
        publish_message(&state, &make_status("a", "working"));
        publish_message(&state, &make_artifact("b", "done", &[]));
        publish_message(&state, &make_blocked("c", "reason", "a"));

        let inner = state.read();
        assert_eq!(inner.message_log.len(), 3);
        assert_eq!(inner.message_log[0].0, 1);
        assert_eq!(inner.message_log[1].0, 2);
        assert_eq!(inner.message_log[2].0, 3);
    }

    #[test]
    fn message_log_includes_all_types() {
        let state = fresh_state();
        publish_message(&state, &make_status("a", "working"));
        publish_message(&state, &make_artifact("a", "done", &[]));
        publish_message(&state, &make_blocked("b", "reason", "a"));

        let inner = state.read();
        assert_eq!(inner.message_log.len(), 3);
    }

    // === Task 4: Inbox storage with sequence numbers ===

    #[test]
    fn inbox_stores_correct_sequence_number() {
        let state = fresh_state();
        publish_message(&state, &make_status("a", "working")); // seq 1
        publish_message(&state, &make_status("b", "working")); // seq 2
        publish_message(&state, &make_artifact("a", "done", &[])); // seq 3

        let inner = state.read();
        let b_inbox = &inner.queues["b"];
        assert_eq!(b_inbox.len(), 1);
        assert_eq!(b_inbox[0].0, 3);
    }

    // === Task 5: publish_message routing ===

    #[test]
    fn first_publish_creates_record_and_inbox() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-errors", "working"));

        let inner = state.read();
        assert!(inner.agents.contains_key("feat-errors"));
        assert_eq!(inner.agents["feat-errors"].status, "working");
        assert!(inner.queues.contains_key("feat-errors"));
    }

    #[test]
    fn status_not_routed_to_any_inbox() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-errors", "working"));
        publish_message(&state, &make_status("feat-detect", "working"));
        publish_message(&state, &make_status("feat-errors", "idle"));

        let (detect_msgs, _) = poll_messages(&state, "feat-detect", 0);
        let (errors_msgs, _) = poll_messages(&state, "feat-errors", 0);
        assert!(detect_msgs.is_empty());
        assert!(errors_msgs.is_empty());
    }

    #[test]
    fn artifact_broadcast_to_all_peers() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-errors", "working"));
        publish_message(&state, &make_status("feat-detect", "working"));
        publish_message(&state, &make_status("feat-config", "working"));

        publish_message(&state, &make_artifact("feat-errors", "done", &[]));

        let (detect_msgs, _) = poll_messages(&state, "feat-detect", 0);
        let (config_msgs, _) = poll_messages(&state, "feat-config", 0);
        assert_eq!(detect_msgs.len(), 1);
        assert_eq!(config_msgs.len(), 1);
    }

    #[test]
    fn artifact_broadcast_skips_sender() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-errors", "working"));
        publish_message(&state, &make_status("feat-detect", "working"));

        publish_message(&state, &make_artifact("feat-errors", "done", &[]));

        let (errors_msgs, _) = poll_messages(&state, "feat-errors", 0);
        assert!(errors_msgs.is_empty());
    }

    #[test]
    fn artifact_broadcast_skips_unregistered_agents() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-errors", "working"));

        publish_message(&state, &make_artifact("feat-errors", "done", &[]));

        let inner = state.read();
        assert!(!inner.queues.contains_key("feat-detect"));
    }

    #[test]
    fn blocked_delivered_to_target() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-config", "working"));
        publish_message(&state, &make_status("feat-errors", "working"));

        publish_message(
            &state,
            &make_blocked("feat-config", "error types", "feat-errors"),
        );

        let (errors_msgs, _) = poll_messages(&state, "feat-errors", 0);
        assert_eq!(errors_msgs.len(), 1);
        assert_eq!(errors_msgs[0].agent_id(), "feat-config");
    }

    #[test]
    fn blocked_not_delivered_to_other_agents() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-config", "working"));
        publish_message(&state, &make_status("feat-errors", "working"));
        publish_message(&state, &make_status("feat-detect", "working"));

        publish_message(
            &state,
            &make_blocked("feat-config", "error types", "feat-errors"),
        );

        let (detect_msgs, _) = poll_messages(&state, "feat-detect", 0);
        assert!(detect_msgs.is_empty());
    }

    #[test]
    fn blocked_to_unregistered_target_silently_dropped() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-config", "working"));

        publish_message(
            &state,
            &make_blocked("feat-config", "error types", "feat-errors"),
        );

        let inner = state.read();
        assert!(!inner.queues.contains_key("feat-errors"));
    }

    // === Supervisor messages: verified and feedback ===

    #[test]
    fn verified_broadcast_reaches_all_peers() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-errors", "working"));
        publish_message(&state, &make_status("feat-detect", "working"));
        publish_message(&state, &make_status("supervisor", "working"));

        publish_message(&state, &make_verified("feat-errors", "supervisor", None));

        let (errors_msgs, _) = poll_messages(&state, "feat-errors", 0);
        let (detect_msgs, _) = poll_messages(&state, "feat-detect", 0);
        assert_eq!(errors_msgs.len(), 1);
        assert_eq!(detect_msgs.len(), 1);
    }

    #[test]
    fn verified_broadcast_skips_sender() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-errors", "working"));
        publish_message(&state, &make_status("supervisor", "working"));

        publish_message(&state, &make_verified("feat-errors", "supervisor", None));

        let (sup_msgs, _) = poll_messages(&state, "supervisor", 0);
        assert!(sup_msgs.is_empty());
    }

    #[test]
    fn verified_updates_sender_record() {
        let state = fresh_state();
        publish_message(&state, &make_status("supervisor", "working"));

        publish_message(&state, &make_verified("feat-errors", "supervisor", None));

        let inner = state.read();
        let record = inner
            .agents
            .get("supervisor")
            .expect("supervisor record exists");
        assert_eq!(record.status, "verified");
    }

    #[test]
    fn feedback_delivered_to_target_agent() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-errors", "working"));
        publish_message(&state, &make_status("supervisor", "working"));

        publish_message(
            &state,
            &make_feedback("feat-errors", "supervisor", &["test failed"]),
        );

        let (errors_msgs, _) = poll_messages(&state, "feat-errors", 0);
        assert_eq!(errors_msgs.len(), 1);
        assert_eq!(errors_msgs[0].status_label(), "feedback");
    }

    #[test]
    fn feedback_not_delivered_to_other_agents() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-errors", "working"));
        publish_message(&state, &make_status("feat-detect", "working"));
        publish_message(&state, &make_status("supervisor", "working"));

        publish_message(
            &state,
            &make_feedback("feat-errors", "supervisor", &["test failed"]),
        );

        let (detect_msgs, _) = poll_messages(&state, "feat-detect", 0);
        assert!(detect_msgs.is_empty());
    }

    #[test]
    fn feedback_updates_sender_record() {
        let state = fresh_state();
        publish_message(&state, &make_status("supervisor", "working"));

        publish_message(
            &state,
            &make_feedback("feat-errors", "supervisor", &["test failed"]),
        );

        let inner = state.read();
        let record = inner
            .agents
            .get("supervisor")
            .expect("supervisor record exists");
        assert_eq!(record.status, "feedback");
    }

    // === Question routing ===

    #[test]
    fn question_routed_to_supervisor_inbox() {
        let state = fresh_state();
        publish_message(
            &state,
            &make_question("feat-config", "Should I skip tests?"),
        );

        let (msgs, _) = poll_messages(&state, "supervisor", 0);
        assert_eq!(msgs.len(), 1);
        assert_eq!(msgs[0].agent_id(), "feat-config");
        assert_eq!(msgs[0].status_label(), "question");
    }

    #[test]
    fn question_creates_supervisor_inbox_if_absent() {
        let state = fresh_state();
        {
            let inner = state.read();
            assert!(!inner.queues.contains_key("supervisor"));
        }

        publish_message(&state, &make_question("feat-config", "anything?"));

        let inner = state.read();
        assert!(inner.queues.contains_key("supervisor"));
    }

    #[test]
    fn question_not_in_sender_inbox() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-config", "working"));
        publish_message(&state, &make_question("feat-config", "anything?"));

        let (msgs, _) = poll_messages(&state, "feat-config", 0);
        assert!(msgs.is_empty());
    }

    #[test]
    fn question_not_delivered_to_other_agents() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-config", "working"));
        publish_message(&state, &make_status("feat-detect", "working"));
        publish_message(&state, &make_question("feat-config", "anything?"));

        let (msgs, _) = poll_messages(&state, "feat-detect", 0);
        assert!(msgs.is_empty());
    }

    #[test]
    fn question_appears_in_message_log() {
        let state = fresh_state();
        publish_message(&state, &make_question("feat-config", "anything?"));

        let inner = state.read();
        assert_eq!(inner.message_log.len(), 1);
        assert_eq!(inner.message_log[0].2.status_label(), "question");
    }

    // === Intent broadcast (forward-coordination) ===

    #[test]
    fn intent_broadcast_reaches_all_peers() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-auth", "working"));
        publish_message(&state, &make_status("feat-detect", "working"));
        publish_message(&state, &make_status("supervisor", "working"));

        publish_message(
            &state,
            &make_intent("feat-auth", &["src/a.rs"], "wire AuthClient", 600),
        );

        let (detect_msgs, _) = poll_messages(&state, "feat-detect", 0);
        let (sup_msgs, _) = poll_messages(&state, "supervisor", 0);
        assert!(
            detect_msgs
                .iter()
                .any(|m| matches!(m, BrokerMessage::Intent { .. }))
        );
        assert!(
            sup_msgs
                .iter()
                .any(|m| matches!(m, BrokerMessage::Intent { .. }))
        );
    }

    #[test]
    fn intent_broadcast_skips_sender() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-auth", "working"));
        publish_message(&state, &make_status("feat-detect", "working"));

        publish_message(
            &state,
            &make_intent("feat-auth", &["src/a.rs"], "wire AuthClient", 600),
        );

        let (own_msgs, _) = poll_messages(&state, "feat-auth", 0);
        assert!(
            !own_msgs
                .iter()
                .any(|m| matches!(m, BrokerMessage::Intent { .. }))
        );
    }

    #[test]
    fn intent_broadcast_skips_unregistered_agents() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-auth", "working"));

        publish_message(
            &state,
            &make_intent("feat-auth", &["src/a.rs"], "wire AuthClient", 600),
        );

        let inner = state.read();
        assert!(!inner.queues.contains_key("feat-detect"));
    }

    #[test]
    fn intent_updates_sender_record_status_to_intent() {
        let state = fresh_state();
        publish_message(
            &state,
            &make_intent("feat-auth", &["src/a.rs"], "wire AuthClient", 600),
        );
        let inner = state.read();
        let record = inner.agents.get("feat-auth").expect("record exists");
        assert_eq!(record.status, "intent");
    }

    // === Question coverage (v040-hardening) ===

    #[test]
    fn question_updates_sender_status_to_question() {
        let state = fresh_state();
        publish_message(&state, &make_question("feat-x", "Should I rebase?"));

        let inner = state.read();
        let record = inner
            .agents
            .get("feat-x")
            .expect("sender record should exist after publishing");
        assert_eq!(record.status, "question");
    }

    #[test]
    fn question_updates_sender_last_seen() {
        let state = fresh_state();
        let before = std::time::Instant::now();
        publish_message(&state, &make_question("feat-x", "Should I rebase?"));
        let after = std::time::Instant::now();

        let inner = state.read();
        let record = inner
            .agents
            .get("feat-x")
            .expect("sender record should exist after publishing");
        // last_seen must lie inside the publish window — proves it was set
        // by this publish, not left at some pre-existing default.
        assert!(record.last_seen >= before);
        assert!(record.last_seen <= after);
    }

    #[test]
    fn question_vs_blocked_inbox_creation_differs() {
        // The spec calls out that `Question` creates the supervisor inbox if
        // it is missing, whereas `Blocked` silently drops when its target
        // inbox is missing. This test pins both behaviours in one place so
        // any regression on either side is loud.
        let state = fresh_state();

        // Blocked with a non-existent target: nothing should be enqueued, and
        // no inbox should be created for the missing target.
        publish_message(
            &state,
            &make_blocked("feat-x", "needs types", "feat-missing"),
        );
        {
            let inner = state.read();
            assert!(
                !inner.queues.contains_key("feat-missing"),
                "Blocked must not create the target inbox when it is missing"
            );
        }

        // Question without any pre-existing supervisor inbox: the inbox must
        // be created and the message must be enqueued there.
        publish_message(&state, &make_question("feat-x", "anything?"));
        let inner = state.read();
        assert!(
            inner.queues.contains_key("supervisor"),
            "Question must create the supervisor inbox when it is missing"
        );
        let (msgs, _) = poll_messages(&state, "supervisor", 0);
        assert_eq!(msgs.len(), 1);
        assert_eq!(msgs[0].status_label(), "question");
    }

    // === Task 6: poll_messages ===

    #[test]
    fn poll_since_zero_returns_all() {
        let state = fresh_state();
        publish_message(&state, &make_status("a", "working")); // seq 1
        publish_message(&state, &make_status("b", "working")); // seq 2
        publish_message(&state, &make_artifact("b", "done", &[])); // seq 3
        publish_message(&state, &make_artifact("b", "done", &[])); // seq 4
        publish_message(&state, &make_artifact("b", "done", &[])); // seq 5

        let (msgs, last_seq) = poll_messages(&state, "a", 0);
        assert_eq!(msgs.len(), 3);
        assert_eq!(last_seq, 5);
    }

    #[test]
    fn poll_since_filters_older_messages() {
        let state = fresh_state();
        publish_message(&state, &make_status("a", "working")); // seq 1
        publish_message(&state, &make_status("b", "working")); // seq 2
        for _ in 0..5 {
            publish_message(&state, &make_artifact("b", "done", &[]));
        } // seqs 3..7, all go to a's inbox

        let (msgs, last_seq) = poll_messages(&state, "a", 5);
        assert_eq!(msgs.len(), 2); // seqs 6, 7
        assert_eq!(last_seq, 7);
    }

    #[test]
    fn poll_since_latest_returns_empty() {
        let state = fresh_state();
        publish_message(&state, &make_status("a", "working"));
        publish_message(&state, &make_status("b", "working"));
        publish_message(&state, &make_artifact("b", "done", &[]));

        let (_, first_seq) = poll_messages(&state, "a", 0);

        let (msgs, last_seq) = poll_messages(&state, "a", first_seq);
        assert!(msgs.is_empty());
        assert_eq!(last_seq, 0);
    }

    #[test]
    fn poll_is_nondestructive() {
        let state = fresh_state();
        publish_message(&state, &make_status("a", "working"));
        publish_message(&state, &make_status("b", "working"));
        publish_message(&state, &make_artifact("b", "done", &[]));

        let (msgs1, seq1) = poll_messages(&state, "a", 0);
        let (msgs2, seq2) = poll_messages(&state, "a", 0);
        assert_eq!(msgs1.len(), msgs2.len());
        assert_eq!(seq1, seq2);
    }

    #[test]
    fn poll_unknown_agent_returns_empty() {
        let state = fresh_state();
        let (msgs, last_seq) = poll_messages(&state, "feat-unknown", 0);
        assert!(msgs.is_empty());
        assert_eq!(last_seq, 0);
    }

    // === Task 7: agent_status_snapshot ===

    #[test]
    fn snapshot_contains_all_registered_agents() {
        let state = fresh_state();
        publish_message(&state, &make_status("a", "working"));
        publish_message(&state, &make_status("b", "idle"));
        publish_message(&state, &make_status("c", "done"));

        let snap = agent_status_snapshot(&state);
        assert_eq!(snap.len(), 3);
    }

    #[test]
    fn snapshot_reflects_latest_status() {
        let state = fresh_state();
        publish_message(&state, &make_status("feat-errors", "working"));
        publish_message(&state, &make_artifact("feat-errors", "done", &[]));

        let snap = agent_status_snapshot(&state);
        let entry = snap.iter().find(|e| e.agent_id == "feat-errors").unwrap();
        assert_eq!(entry.status, "done");
    }

    #[test]
    fn snapshot_empty_on_fresh_state() {
        let state = fresh_state();
        let snap = agent_status_snapshot(&state);
        assert!(snap.is_empty());
    }

    // === supervisor-as-pane-followups: cli + phase plumbing ===

    #[test]
    fn snapshot_carries_phase_from_most_recent_status_message() {
        let state = fresh_state();
        let msg = BrokerMessage::Status {
            agent_id: "supervisor".to_string(),
            payload: StatusPayload {
                status: "working".to_string(),
                modified_files: vec![],
                message: None,
                cli: Some("claude".to_string()),
                phase: Some("merging".to_string()),
            },
        };
        publish_message(&state, &msg);

        let snap = agent_status_snapshot(&state);
        let entry = snap.iter().find(|e| e.agent_id == "supervisor").unwrap();
        assert_eq!(entry.phase.as_deref(), Some("merging"));
        assert_eq!(entry.cli, "claude");
    }

    #[test]
    fn snapshot_phase_is_none_when_last_message_is_not_status() {
        let state = fresh_state();
        publish_message(&state, &make_status("supervisor", "working"));
        publish_message(
            &state,
            &make_feedback("feat-x", "supervisor", &["bad test"]),
        );

        let snap = agent_status_snapshot(&state);
        let entry = snap.iter().find(|e| e.agent_id == "supervisor").unwrap();
        assert_eq!(
            entry.phase, None,
            "Feedback as last_message must not carry over a phase"
        );
    }

    #[test]
    fn supervisor_cli_lands_in_agent_clis_via_status_payload() {
        let state = fresh_state();
        let msg = BrokerMessage::Status {
            agent_id: "supervisor".to_string(),
            payload: StatusPayload {
                status: "working".to_string(),
                modified_files: vec![],
                message: None,
                cli: Some("claude".to_string()),
                phase: Some("baseline".to_string()),
            },
        };
        publish_message(&state, &msg);

        let inner = state.read();
        assert_eq!(
            inner.agent_clis.get("supervisor").map(String::as_str),
            Some("claude"),
            "supervisor's cli must be upserted into agent_clis from the status payload",
        );
    }

    // === Task 8: Log flush thread ===

    #[test]
    fn flush_writes_messages_to_disk() {
        let tmp = tempfile::tempdir().unwrap();
        let log_path = tmp.path().join("broker.log");
        let state = Arc::new(BrokerState::new(Some(log_path.clone())));

        publish_message(&state, &make_status("a", "working"));
        publish_message(&state, &make_status("b", "working"));
        publish_message(&state, &make_artifact("a", "done", &[]));

        let mut last_flushed = 0u64;
        flush_entries(&state, &log_path, &mut last_flushed);

        let content = std::fs::read_to_string(&log_path).unwrap();
        let lines: Vec<&str> = content.lines().collect();
        assert_eq!(lines.len(), 3);
        assert!(lines[0].starts_with("[1]"));
        assert!(lines[2].starts_with("[3]"));
        assert_eq!(last_flushed, 3);
    }

    #[test]
    fn flush_only_writes_new_entries() {
        let tmp = tempfile::tempdir().unwrap();
        let log_path = tmp.path().join("broker.log");
        let state = Arc::new(BrokerState::new(Some(log_path.clone())));

        publish_message(&state, &make_status("a", "working"));
        publish_message(&state, &make_status("b", "working"));
        publish_message(&state, &make_artifact("a", "done", &[]));

        let mut last_flushed = 0u64;
        flush_entries(&state, &log_path, &mut last_flushed);
        assert_eq!(last_flushed, 3);

        publish_message(&state, &make_artifact("b", "done", &[]));
        publish_message(&state, &make_artifact("a", "done", &[]));

        flush_entries(&state, &log_path, &mut last_flushed);
        assert_eq!(last_flushed, 5);

        let content = std::fs::read_to_string(&log_path).unwrap();
        assert_eq!(content.lines().count(), 5);
    }

    #[test]
    fn final_flush_on_handle_drop() {
        let tmp = tempfile::tempdir().unwrap();
        let log_path = tmp.path().join("broker.log");
        let config = BrokerConfig {
            enabled: true,
            #[allow(clippy::cast_possible_truncation)]
            port: 19_300 + (std::process::id() as u16 % 100),
            bind: "127.0.0.1".to_string(),
        };
        let handle = start_broker(
            &config,
            BrokerState::new(Some(log_path.clone())),
            Vec::new(),
        );
        if let Ok(handle) = handle {
            publish_message(&handle.state, &make_status("a", "working"));
            publish_message(&handle.state, &make_artifact("a", "done", &[]));
            drop(handle);
            let content = std::fs::read_to_string(&log_path).unwrap();
            assert_eq!(content.lines().count(), 2);
        }
    }

    #[test]
    fn no_flush_thread_when_no_log_path() {
        let config = BrokerConfig {
            enabled: true,
            #[allow(clippy::cast_possible_truncation)]
            port: 19_400 + (std::process::id() as u16 % 100),
            bind: "127.0.0.1".to_string(),
        };
        if let Ok(handle) = start_broker(&config, BrokerState::new(None), Vec::new()) {
            assert!(handle.flush_thread.is_none());
            publish_message(&handle.state, &make_status("a", "working"));
            let inner = handle.state.read();
            assert!(inner.agents.contains_key("a"));
        }
    }

    #[test]
    fn disk_failure_does_not_affect_state() {
        let bad_path = std::path::PathBuf::from("/nonexistent/path/broker.log");
        let state = Arc::new(BrokerState::new(Some(bad_path.clone())));

        publish_message(&state, &make_status("a", "working"));
        publish_message(&state, &make_artifact("a", "done", &[]));

        let mut last_flushed = 0u64;
        flush_entries(&state, &bad_path, &mut last_flushed);

        // In-memory state is unaffected
        let inner = state.read();
        assert_eq!(inner.message_log.len(), 2);
        assert!(inner.agents.contains_key("a"));
    }

    // === recent_messages function ===

    #[test]
    fn recent_messages_returns_empty_when_no_messages() {
        let state = fresh_state();
        let messages = recent_messages(&state, 10);
        assert!(messages.is_empty());
    }

    #[test]
    fn recent_messages_returns_messages_in_reverse_order() {
        let state = fresh_state();
        publish_message(&state, &make_status("a", "working")); // seq 1
        publish_message(&state, &make_status("b", "working")); // seq 2
        publish_message(&state, &make_artifact("a", "done", &[])); // seq 3

        let messages = recent_messages(&state, 10);
        assert_eq!(messages.len(), 3);
        // Should be in reverse order (newest first)
        assert_eq!(messages[0].0, 3); // seq 3
        assert_eq!(messages[1].0, 2); // seq 2
        assert_eq!(messages[2].0, 1); // seq 1
    }

    #[test]
    fn recent_messages_respects_limit() {
        let state = fresh_state();
        for i in 0..5 {
            publish_message(&state, &make_status(&format!("agent-{i}"), "working"));
        }

        let messages = recent_messages(&state, 3);
        assert_eq!(messages.len(), 3);
        // Should get the 3 most recent (seqs 5, 4, 3)
        assert_eq!(messages[0].0, 5);
        assert_eq!(messages[1].0, 4);
        assert_eq!(messages[2].0, 3);
    }

    #[test]
    fn recent_messages_includes_all_types() {
        let state = fresh_state();
        publish_message(&state, &make_status("a", "working"));
        publish_message(&state, &make_artifact("b", "done", &[]));
        publish_message(&state, &make_blocked("c", "types", "b"));
        publish_message(&state, &make_verified("d", "supervisor", None));
        publish_message(&state, &make_feedback("e", "supervisor", &["error"]));
        publish_message(&state, &make_question("f", "question?"));

        let messages = recent_messages(&state, 10);
        assert_eq!(messages.len(), 6);
        // Verify all types are present by checking message variants
        let has_status = messages
            .iter()
            .any(|(_, _, msg)| matches!(msg, BrokerMessage::Status { .. }));
        let has_artifact = messages
            .iter()
            .any(|(_, _, msg)| matches!(msg, BrokerMessage::Artifact { .. }));
        let has_blocked = messages
            .iter()
            .any(|(_, _, msg)| matches!(msg, BrokerMessage::Blocked { .. }));
        let has_verified = messages
            .iter()
            .any(|(_, _, msg)| matches!(msg, BrokerMessage::Verified { .. }));
        let has_feedback = messages
            .iter()
            .any(|(_, _, msg)| matches!(msg, BrokerMessage::Feedback { .. }));
        let has_question = messages
            .iter()
            .any(|(_, _, msg)| matches!(msg, BrokerMessage::Question { .. }));

        assert!(has_status, "Should contain Status message");
        assert!(has_artifact, "Should contain Artifact message");
        assert!(has_blocked, "Should contain Blocked message");
        assert!(has_verified, "Should contain Verified message");
        assert!(has_feedback, "Should contain Feedback message");
        assert!(has_question, "Should contain Question message");
    }

    // === Sequence number correctness ===

    #[test]
    fn first_message_gets_sequence_one() {
        let state = fresh_state();
        publish_message(&state, &make_status("a", "working"));
        publish_message(&state, &make_status("b", "working"));
        publish_message(&state, &make_artifact("a", "done", &[])); // seq 3

        let inner = state.read();
        assert_eq!(inner.message_log[0].0, 1);
    }

    #[test]
    fn sequence_numbers_are_globally_monotonic() {
        let state = fresh_state();
        publish_message(&state, &make_status("a", "working")); // seq 1
        publish_message(&state, &make_status("b", "working")); // seq 2
        publish_message(&state, &make_artifact("a", "done", &[])); // seq 3 -> b's inbox
        publish_message(&state, &make_artifact("b", "done", &[])); // seq 4 -> a's inbox

        let inner = state.read();
        let b_inbox_seq = inner.queues["b"][0].0; // should be 3
        let a_inbox_seq = inner.queues["a"][0].0; // should be 4
        assert!(b_inbox_seq < a_inbox_seq);
    }

    // === Terminal Status Protection Tests ===

    #[test]
    fn terminal_state_not_overwritten_by_non_terminal() {
        let state = fresh_state();
        // Set agent to terminal state "done"
        publish_message(&state, &make_artifact("feat-errors", "done", &[]));

        // Verify status is "done"
        assert_eq!(state.read().agents["feat-errors"].status, "done");

        // Try to overwrite with non-terminal state "working"
        publish_message(&state, &make_status("feat-errors", "working"));

        // Verify status remains "done" (protected)
        assert_eq!(state.read().agents["feat-errors"].status, "done");
    }

    #[test]
    fn terminal_state_not_overwritten_by_non_terminal_simple() {
        // Simplified version of the hanging test
        let state = fresh_state();

        // Set agent to terminal state "done"
        publish_message(&state, &make_artifact("feat-simple", "done", &[]));

        // Verify status is "done"
        assert_eq!(state.read().agents["feat-simple"].status, "done");

        // Try to overwrite with non-terminal state "working"
        publish_message(&state, &make_status("feat-simple", "working"));

        // Verify status remains "done" (protected)
        assert_eq!(state.read().agents["feat-simple"].status, "done");
    }

    #[test]
    fn terminal_state_can_be_overwritten_by_other_terminal() {
        let state = fresh_state();
        // Set agent to terminal state "done"
        publish_message(&state, &make_artifact("feat-errors", "done", &[]));

        // Overwrite with another terminal state "verified"
        publish_message(&state, &make_artifact("feat-errors", "verified", &[]));

        // Verify status changed to "verified"
        let inner = state.read();
        assert_eq!(inner.agents["feat-errors"].status, "verified");
    }

    #[test]
    fn non_terminal_state_can_be_overwritten_by_terminal() {
        let state = fresh_state();
        // Set agent to non-terminal state "working"
        publish_message(&state, &make_status("feat-errors", "working"));

        // Overwrite with terminal state "done"
        publish_message(&state, &make_artifact("feat-errors", "done", &[]));

        // Verify status changed to "done"
        let inner = state.read();
        assert_eq!(inner.agents["feat-errors"].status, "done");
    }

    #[test]
    fn all_terminal_states_are_protected() {
        let terminal_states = ["done", "verified", "blocked", "committed"];

        for &terminal_state in &terminal_states {
            // Create a unique agent for each terminal state
            let agent_id = format!("feat-{terminal_state}");
            let state = fresh_state(); // Use fresh_state() helper instead of Arc::new directly

            // Set agent to terminal state
            publish_message(&state, &make_artifact(&agent_id, terminal_state, &[]));

            // Try to overwrite with non-terminal state "working"
            publish_message(&state, &make_status(&agent_id, "working"));

            // Verify status remains protected
            let inner = state.read();
            assert_eq!(
                inner.agents[&agent_id].status, terminal_state,
                "Terminal state {terminal_state} should be protected from non-terminal overwrite"
            );
        }
    }

    #[test]
    fn terminal_status_protection_with_artifact_messages() {
        let state = fresh_state();
        // Set agent to terminal state via artifact
        publish_message(
            &state,
            &make_artifact("feat-config", "done", &["ConfigType"]),
        );

        // Try to overwrite with non-terminal status message
        publish_message(&state, &make_status("feat-config", "working"));

        // Verify status remains "done" (protected)
        let inner = state.read();
        assert_eq!(inner.agents["feat-config"].status, "done");
    }

    #[test]
    fn terminal_status_protection_with_blocked_messages() {
        let state = fresh_state();
        // Set agent to terminal state "blocked"
        publish_message(&state, &make_artifact("feat-ui", "blocked", &[]));

        // Try to overwrite with non-terminal status
        publish_message(&state, &make_status("feat-ui", "idle"));

        // Verify status remains "blocked" (protected)
        let inner = state.read();
        assert_eq!(inner.agents["feat-ui"].status, "blocked");
    }

    // Maps to scenario `Question creates supervisor inbox when absent` from
    // v040-hardening. (test-coverage-v0-5-0 task 8.1)
    #[test]
    fn question_creates_supervisor_inbox_when_absent() {
        let state = fresh_state();
        // Register feat-x but no supervisor inbox.
        publish_message(&state, &make_status("feat-x", "working"));
        {
            let inner = state.read();
            assert!(
                !inner.queues.contains_key("supervisor"),
                "supervisor inbox must be absent before publishing the question"
            );
        }

        publish_message(&state, &make_question("feat-x", "How should I proceed?"));

        {
            let inner = state.read();
            assert!(
                inner.queues.contains_key("supervisor"),
                "publishing an agent.question must create the supervisor inbox; got queues: {:?}",
                inner.queues.keys().collect::<Vec<_>>()
            );
        }

        let (messages, last_seq) = poll_messages(&state, "supervisor", 0);
        assert_eq!(
            messages.len(),
            1,
            "supervisor inbox should contain the published question"
        );
        assert!(
            matches!(&messages[0], BrokerMessage::Question { agent_id, payload }
                if agent_id == "feat-x" && payload.question == "How should I proceed?"),
            "supervisor inbox should hold the original question; got: {:?}",
            messages[0]
        );
        assert!(
            last_seq > 0,
            "poll_messages should return a non-zero cursor"
        );
    }
}