git-paw 0.6.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
//! Axum HTTP server for the broker.
//!
//! Defines the router and endpoint handlers for `/publish`, `/messages/:agent_id`,
//! and `/status`. All handlers follow the lock discipline documented in
//! [`super`] — no `RwLock` guard is held across an `.await` boundary.

use std::sync::{Arc, OnceLock};

use axum::Router;
use axum::extract::{Path, Query, State};
use axum::http::{HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use regex::Regex;
use serde::{Deserialize, Serialize};

use super::BrokerState;
use super::delivery;
use super::messages::BrokerMessage;

/// Compiled-once regex matching the only `agent_id` shapes the broker accepts:
/// `"supervisor"`, or a `feat-{name}` / `feat/{name}` slug whose `{name}`
/// begins with `[a-z0-9]` and consists of `[a-z0-9-]+`. See
/// `supervisor-bugfixes-v0-5-x` §4 + `broker-messages` spec.
fn agent_id_regex() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"^(supervisor|feat/[a-z0-9][a-z0-9-]+|feat-[a-z0-9][a-z0-9-]+)$")
            .expect("AGENT_ID_RE compiles")
    })
}

/// Compiled-once regex matching unfilled placeholder strings — exact match
/// `<anything>` from start to end.
fn placeholder_regex() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"^<.*>$").expect("PLACEHOLDER_RE compiles"))
}

/// Build the HTTP 400 response for an `agent_id` that did not match
/// [`agent_id_regex`].
fn agent_id_rejection(value: &str) -> Response {
    (
        StatusCode::BAD_REQUEST,
        axum::Json(serde_json::json!({
            "error": "invalid agent_id",
            "value": value,
            "detail": "agent_id must be 'supervisor' or match feat-{name} / feat/{name}",
        })),
    )
        .into_response()
}

/// Build the HTTP 400 response for a payload string that looks like an
/// unfilled placeholder (`<…>`).
fn placeholder_rejection(field: &str, value: &str) -> Response {
    (
        StatusCode::BAD_REQUEST,
        axum::Json(serde_json::json!({
            "error": "field looks like an unfilled placeholder",
            "field": field,
            "value": value,
            "detail": "substitute the real value before publishing",
        })),
    )
        .into_response()
}

/// Returns `Some(response)` if any tracked payload string field of `msg`
/// matches [`placeholder_regex`]; otherwise `None`.
///
/// Per `supervisor-bugfixes-v0-5-x` design D5, the placeholder check covers
/// only the fields the supervisor skill's example curls populate:
/// `payload.question`, `payload.needs`, and each string element of
/// `payload.errors[]`. Other free-form string fields (`StatusPayload.message`,
/// `VerifiedPayload.message`) are left alone — real human content sometimes
/// uses angle brackets inline.
fn check_placeholder_fields(msg: &BrokerMessage) -> Option<Response> {
    let re = placeholder_regex();
    match msg {
        BrokerMessage::Question { payload, .. } => {
            if re.is_match(&payload.question) {
                return Some(placeholder_rejection("question", &payload.question));
            }
        }
        BrokerMessage::Blocked { payload, .. } => {
            if re.is_match(&payload.needs) {
                return Some(placeholder_rejection("needs", &payload.needs));
            }
        }
        BrokerMessage::Feedback { payload, .. } => {
            for err in &payload.errors {
                if re.is_match(err) {
                    return Some(placeholder_rejection("errors", err));
                }
            }
        }
        BrokerMessage::Status { .. }
        | BrokerMessage::Artifact { .. }
        | BrokerMessage::Verified { .. }
        | BrokerMessage::Intent { .. }
        | BrokerMessage::AdvancedMain { .. }
        | BrokerMessage::Learning { .. }
        | BrokerMessage::VerifyNow { .. } => {}
    }
    None
}

/// Query parameters for the `GET /messages/:agent_id` endpoint.
#[derive(Deserialize)]
struct PollQuery {
    /// Return only messages with sequence number > `since`. Defaults to 0.
    since: Option<String>,
}

/// Response body for the `GET /messages/:agent_id` endpoint.
#[derive(Serialize)]
struct PollResponse {
    /// Messages newer than the requested cursor.
    messages: Vec<BrokerMessage>,
    /// Highest sequence number in the result (0 if empty).
    last_seq: u64,
}

/// Response body for the `GET /log` endpoint.
#[derive(Serialize)]
struct LogResponse {
    /// All messages with `seq > since`, in chronological order.
    /// Each entry is `[seq, timestamp_unix_secs, message]`.
    entries: Vec<LogEntry>,
    /// Highest sequence number in the result (0 if empty).
    last_seq: u64,
}

/// One entry in `GET /log`.
#[derive(Serialize)]
struct LogEntry {
    /// Sequence number assigned at publish time.
    seq: u64,
    /// Wall-clock seconds since the Unix epoch when the message was published.
    timestamp_unix_secs: u64,
    /// The original broker message.
    message: BrokerMessage,
}

/// Builds the axum [`Router`] with all broker endpoints.
pub fn router(state: Arc<BrokerState>) -> Router {
    Router::new()
        .route("/publish", post(publish))
        .route("/messages/{agent_id}", get(messages))
        .route("/status", get(status))
        .route("/log", get(log))
        .with_state(state)
}

/// `POST /publish` — accepts a JSON [`BrokerMessage`] and queues it for delivery.
///
/// - 415 if `Content-Type` is missing or not `application/json`
/// - 400 if body is empty or fails validation
/// - 202 on success
async fn publish(
    State(state): State<Arc<BrokerState>>,
    headers: HeaderMap,
    body: String,
) -> Response {
    // Check Content-Type
    let content_type = headers
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");

    if !content_type.starts_with("application/json") {
        return (
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
            axum::Json(serde_json::json!({"error": "Content-Type must be application/json"})),
        )
            .into_response();
    }

    // Check for empty body
    if body.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            axum::Json(serde_json::json!({"error": "request body must not be empty"})),
        )
            .into_response();
    }

    // Parse and validate
    match BrokerMessage::from_json(&body) {
        Ok(msg) => {
            // Validate the top-level agent_id against the broker regex.
            // Phantom debris (`"a"`, `"<agent-id>"`, empty strings) is
            // rejected at the API boundary so it cannot leak into
            // `/status`.
            if !agent_id_regex().is_match(msg.agent_id()) {
                return agent_id_rejection(msg.agent_id());
            }
            // Reject obviously-unfilled placeholder strings in the few
            // payload fields the supervisor skill's examples touch.
            if let Some(rejection) = check_placeholder_fields(&msg) {
                return rejection;
            }
            delivery::publish_message(&state, &msg);
            StatusCode::ACCEPTED.into_response()
        }
        Err(e) => (
            StatusCode::BAD_REQUEST,
            axum::Json(serde_json::json!({"error": e.to_string()})),
        )
            .into_response(),
    }
}

/// `GET /messages/:agent_id?since=N` — polls for messages destined to the given agent.
///
/// - 400 if `agent_id` contains invalid characters
/// - 400 if `since` is present but not a valid `u64`
/// - 200 with `{"messages": [...], "last_seq": N}` on success
async fn messages(
    State(state): State<Arc<BrokerState>>,
    Path(agent_id): Path<String>,
    Query(params): Query<PollQuery>,
) -> Response {
    // Validate agent_id: only lowercase alphanumeric, hyphens, underscores
    if agent_id.is_empty()
        || !agent_id
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
    {
        return (
            StatusCode::BAD_REQUEST,
            axum::Json(serde_json::json!({"error": "agent_id must match [a-z0-9-_]+"})),
        )
            .into_response();
    }

    let since = match params.since {
        Some(s) => match s.parse::<u64>() {
            Ok(n) => n,
            Err(_) => {
                return (
                    StatusCode::BAD_REQUEST,
                    axum::Json(serde_json::json!({"error": "since must be a valid u64"})),
                )
                    .into_response();
            }
        },
        None => 0,
    };

    let (msgs, last_seq) = delivery::poll_messages(&state, &agent_id, since);
    (
        StatusCode::OK,
        axum::Json(PollResponse {
            messages: msgs,
            last_seq,
        }),
    )
        .into_response()
}

/// `GET /log?since=N` — returns the broker's full message log filtered to
/// `seq > since`.
///
/// Used by `cmd_supervisor` to reconstruct broker state from outside the
/// dashboard process so it can build the dependency graph for merge ordering
/// and write a real session summary instead of an empty one.
async fn log(State(state): State<Arc<BrokerState>>, Query(params): Query<PollQuery>) -> Response {
    let since = match params.since {
        Some(s) => match s.parse::<u64>() {
            Ok(n) => n,
            Err(_) => {
                return (
                    StatusCode::BAD_REQUEST,
                    axum::Json(serde_json::json!({"error": "since must be a valid u64"})),
                )
                    .into_response();
            }
        },
        None => 0,
    };

    let raw = delivery::full_log(&state, since);
    let last_seq = raw.iter().map(|(s, _, _)| *s).max().unwrap_or(0);
    let entries: Vec<LogEntry> = raw
        .into_iter()
        .map(|(seq, ts, message)| LogEntry {
            seq,
            timestamp_unix_secs: ts
                .duration_since(std::time::UNIX_EPOCH)
                .map_or(0, |d| d.as_secs()),
            message,
        })
        .collect();

    (
        StatusCode::OK,
        axum::Json(LogResponse { entries, last_seq }),
    )
        .into_response()
}

/// `GET /status` — returns broker health and agent summary.
async fn status(State(state): State<Arc<BrokerState>>) -> Response {
    let uptime = state.uptime_seconds();
    let agents = delivery::agent_status_snapshot(&state);
    (
        StatusCode::OK,
        axum::Json(serde_json::json!({
            "git_paw": true,
            "version": env!("CARGO_PKG_VERSION"),
            "uptime_seconds": uptime,
            "agents": agents,
        })),
    )
        .into_response()
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::Request;
    use tower::ServiceExt;

    fn test_router() -> Router {
        router(Arc::new(BrokerState::new(None)))
    }

    #[tokio::test]
    async fn publish_valid_message_returns_202() {
        let app = test_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/publish")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        r#"{"type":"agent.status","agent_id":"feat-xx","payload":{"status":"idle","modified_files":[]}}"#,
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::ACCEPTED);
    }

    #[tokio::test]
    async fn publish_invalid_json_returns_400() {
        let app = test_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/publish")
                    .header("content-type", "application/json")
                    .body(Body::from("not json"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn publish_empty_body_returns_400() {
        let app = test_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/publish")
                    .header("content-type", "application/json")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn publish_wrong_content_type_returns_415() {
        let app = test_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/publish")
                    .header("content-type", "text/plain")
                    .body(Body::from("{}"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
    }

    #[tokio::test]
    async fn publish_missing_content_type_returns_415() {
        let app = test_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/publish")
                    .body(Body::from("{}"))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
    }

    #[tokio::test]
    async fn publish_empty_agent_id_returns_400() {
        let app = test_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/publish")
                    .header("content-type", "application/json")
                    .body(Body::from(
                        r#"{"type":"agent.status","agent_id":"","payload":{"status":"idle","modified_files":[]}}"#,
                    ))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    // -----------------------------------------------------------------------
    // supervisor-bugfixes-v0-5-x §4 — broker validates agent_id + payload
    // placeholder syntax. The unit-test matrix below covers the spec scenarios
    // for invalid + valid agent_ids and the placeholder rejection rules.
    // -----------------------------------------------------------------------

    /// Helper: POST a body to `/publish` and return (status, body-bytes).
    async fn post_publish(body: &'static str) -> (StatusCode, axum::body::Bytes) {
        let app = test_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/publish")
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        let status = resp.status();
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        (status, bytes)
    }

    #[tokio::test]
    async fn agent_id_rejects_single_letter() {
        let (status, body) = post_publish(
            r#"{"type":"agent.status","agent_id":"a","payload":{"status":"working","modified_files":[]}}"#,
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        let text = String::from_utf8_lossy(&body);
        assert!(
            text.contains("invalid agent_id"),
            "body should mention 'invalid agent_id'; got: {text}"
        );
    }

    #[tokio::test]
    async fn agent_id_rejects_placeholder() {
        let (status, body) = post_publish(
            r#"{"type":"agent.status","agent_id":"<agent-id>","payload":{"status":"working","modified_files":[]}}"#,
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        let text = String::from_utf8_lossy(&body);
        assert!(text.contains("invalid agent_id"), "body: {text}");
    }

    #[tokio::test]
    async fn agent_id_rejects_empty() {
        let (status, body) = post_publish(
            r#"{"type":"agent.status","agent_id":"","payload":{"status":"working","modified_files":[]}}"#,
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        // The empty-string case is caught either by from_json's
        // EmptyAgentId validation or by the regex — both surface as 400.
        let _ = body;
    }

    #[tokio::test]
    async fn agent_id_accepts_supervisor() {
        let (status, _) = post_publish(
            r#"{"type":"agent.status","agent_id":"supervisor","payload":{"status":"working","modified_files":[]}}"#,
        )
        .await;
        assert!(
            status == StatusCode::ACCEPTED || status == StatusCode::OK,
            "supervisor should be accepted; got: {status}"
        );
    }

    #[tokio::test]
    async fn agent_id_accepts_feat_dash() {
        let (status, _) = post_publish(
            r#"{"type":"agent.status","agent_id":"feat-test-branch","payload":{"status":"working","modified_files":[]}}"#,
        )
        .await;
        assert!(
            status == StatusCode::ACCEPTED || status == StatusCode::OK,
            "feat-test-branch should be accepted; got: {status}"
        );
    }

    #[tokio::test]
    async fn agent_id_accepts_feat_slash() {
        let (status, _) = post_publish(
            r#"{"type":"agent.status","agent_id":"feat/test-branch","payload":{"status":"working","modified_files":[]}}"#,
        )
        .await;
        assert!(
            status == StatusCode::ACCEPTED || status == StatusCode::OK,
            "feat/test-branch should be accepted; got: {status}"
        );
    }

    #[tokio::test]
    async fn payload_question_rejects_placeholder() {
        let (status, body) = post_publish(
            r#"{"type":"agent.question","agent_id":"feat-test-branch","payload":{"question":"<your specific question>"}}"#,
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        let text = String::from_utf8_lossy(&body);
        assert!(
            text.contains("placeholder") && text.contains("question"),
            "body should mention both 'placeholder' and 'question'; got: {text}"
        );
    }

    #[tokio::test]
    async fn payload_question_accepts_real_content() {
        let (status, _) = post_publish(
            r#"{"type":"agent.question","agent_id":"feat-test-branch","payload":{"question":"Should we use bcrypt or argon2?"}}"#,
        )
        .await;
        assert!(
            status == StatusCode::ACCEPTED || status == StatusCode::OK,
            "real human content should be accepted; got: {status}"
        );
    }

    #[tokio::test]
    async fn payload_blocked_rejects_placeholder_needs() {
        let (status, body) = post_publish(
            r#"{"type":"agent.blocked","agent_id":"feat-test-branch","payload":{"needs":"<what>","from":"feat-other"}}"#,
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        let text = String::from_utf8_lossy(&body);
        assert!(
            text.contains("placeholder") && text.contains("needs"),
            "body: {text}"
        );
    }

    #[tokio::test]
    async fn payload_feedback_rejects_placeholder_error_entry() {
        let (status, body) = post_publish(
            r#"{"type":"agent.feedback","agent_id":"feat-test-branch","payload":{"from":"supervisor","errors":["<error 1>"]}}"#,
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        let text = String::from_utf8_lossy(&body);
        assert!(
            text.contains("placeholder") && text.contains("errors"),
            "body: {text}"
        );
    }

    // === agent.advanced-main routing + validation (advanced-main-event §3) ===

    #[tokio::test]
    async fn advanced_main_accepted_through_publish_endpoint() {
        // No new endpoint: the variant flows through the existing /publish.
        let (status, _) = post_publish(
            r#"{"type":"agent.advanced-main","from":"supervisor","merged_branch":"feat/auth","new_main_sha":"a1b2c3d4e5f6","base":"main","merged_at":"2026-06-04T13:30:00Z","summary":"landed auth"}"#,
        )
        .await;
        assert_eq!(
            status,
            StatusCode::ACCEPTED,
            "a well-formed advanced-main must be accepted (202)"
        );
    }

    #[tokio::test]
    async fn advanced_main_missing_field_returns_400_naming_field() {
        let (status, body) = post_publish(
            r#"{"type":"agent.advanced-main","from":"supervisor","new_main_sha":"a1b2c3d4e5f6","base":"main","merged_at":"2026-06-04T13:30:00Z"}"#,
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        let text = String::from_utf8_lossy(&body);
        assert!(
            text.contains("merged_branch"),
            "the 400 must name the missing field; got: {text}"
        );
    }

    #[tokio::test]
    async fn advanced_main_routes_to_every_registered_agent() {
        // After two agents register, a supervisor-published advance lands in
        // both their inboxes within one poll.
        let state = Arc::new(BrokerState::new(None));
        publish_json(
            &state,
            r#"{"type":"agent.status","agent_id":"feat-alpha","payload":{"status":"working","modified_files":[]}}"#,
        )
        .await;
        publish_json(
            &state,
            r#"{"type":"agent.status","agent_id":"feat-beta","payload":{"status":"working","modified_files":[]}}"#,
        )
        .await;
        publish_json(
            &state,
            r#"{"type":"agent.advanced-main","from":"supervisor","merged_branch":"feat/alpha","new_main_sha":"a1b2c3d4e5f6","base":"main","merged_at":"2026-06-04T13:30:00Z"}"#,
        )
        .await;

        for agent in ["feat-alpha", "feat-beta"] {
            let (msgs, _) = delivery::poll_messages(&state, agent, 0);
            assert!(
                msgs.iter()
                    .any(|m| matches!(m, BrokerMessage::AdvancedMain { .. })),
                "{agent} inbox must surface the advanced-main event"
            );
        }
    }

    #[tokio::test]
    async fn messages_valid_agent_returns_200_with_last_seq() {
        let app = test_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/messages/feat-x")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["messages"], serde_json::json!([]));
        assert_eq!(json["last_seq"], serde_json::json!(0));
    }

    #[tokio::test]
    async fn messages_invalid_agent_returns_400() {
        let app = test_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/messages/INVALID!")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn messages_invalid_since_returns_400() {
        let app = test_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/messages/feat-x?since=abc")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn status_returns_marker_and_version() {
        let app = test_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/status")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["git_paw"], true);
        assert!(json["version"].is_string());
        assert!(json["uptime_seconds"].is_number());
        assert_eq!(json["agents"], serde_json::json!([]));
    }

    /// POSTs a JSON body to `/publish` against a router built from `state`.
    async fn publish_json(state: &Arc<BrokerState>, body: &'static str) {
        let resp = router(Arc::clone(state))
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/publish")
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::ACCEPTED);
    }

    /// GETs `/status` against a router built from `state` and returns the
    /// parsed JSON body.
    async fn get_status(state: &Arc<BrokerState>) -> serde_json::Value {
        let resp = router(Arc::clone(state))
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/status")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        serde_json::from_slice(&body).unwrap()
    }

    #[tokio::test]
    async fn e2e_feedback_from_human_creates_no_phantom_roster_row() {
        // W15-16 end-to-end: two real agents register via `agent.status`,
        // then a `agent.feedback` with `from:"human"` is published. The
        // `/status` roster must hold exactly the two real agents — no
        // phantom `"human"` row.
        let state = Arc::new(BrokerState::new(None));
        publish_json(
            &state,
            r#"{"type":"agent.status","agent_id":"supervisor","payload":{"status":"working","modified_files":[],"cli":"claude-oss"}}"#,
        )
        .await;
        publish_json(
            &state,
            r#"{"type":"agent.status","agent_id":"feat-roster","payload":{"status":"working","modified_files":[],"cli":"claude-oss"}}"#,
        )
        .await;
        publish_json(
            &state,
            r#"{"type":"agent.feedback","agent_id":"feat-roster","payload":{"from":"human","errors":["fix the flaky test"]}}"#,
        )
        .await;

        let json = get_status(&state).await;
        let agents = json["agents"].as_array().expect("agents array");
        let ids: Vec<&str> = agents
            .iter()
            .map(|a| a["agent_id"].as_str().unwrap())
            .collect();
        assert!(
            !ids.contains(&"human"),
            "a feedback `from:human` must not mint a phantom roster row; got {ids:?}",
        );
        assert_eq!(ids.len(), 2, "roster holds exactly the two real agents");
    }

    #[tokio::test]
    async fn e2e_status_shows_cli_for_every_agent() {
        // W15-15 end-to-end: every agent that publishes `agent.status` with a
        // `cli` shows that CLI in the `/status` roster — not just the
        // supervisor.
        let state = Arc::new(BrokerState::new(None));
        publish_json(
            &state,
            r#"{"type":"agent.status","agent_id":"supervisor","payload":{"status":"working","modified_files":[],"cli":"claude-oss"}}"#,
        )
        .await;
        publish_json(
            &state,
            r#"{"type":"agent.status","agent_id":"feat-build","payload":{"status":"working","modified_files":[],"cli":"claude-oss"}}"#,
        )
        .await;

        let json = get_status(&state).await;
        let agents = json["agents"].as_array().expect("agents array");
        assert_eq!(agents.len(), 2);
        for a in agents {
            assert_eq!(
                a["cli"].as_str(),
                Some("claude-oss"),
                "every agent row must carry its cli: {a}",
            );
        }
    }

    #[tokio::test]
    async fn unknown_route_returns_404() {
        let app = test_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/unknown/route")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn wrong_method_returns_405() {
        let app = test_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/publish")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
    }

    #[tokio::test]
    async fn panic_in_handler_is_isolated() {
        // Verify that a panicking handler does not take down the server.
        let app = Router::new()
            .route(
                "/panic",
                get(|| async {
                    panic!("deliberate test panic");
                    #[allow(unreachable_code)]
                    StatusCode::OK.into_response()
                }),
            )
            .route("/status", get(status))
            .with_state(Arc::new(BrokerState::new(None)));

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        let server = tokio::spawn(async move {
            axum::serve(listener, app).await.ok();
        });

        let client =
            hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())
                .build_http();

        // Request to /panic — should not crash the server.
        let _panic_resp = client
            .request(
                Request::builder()
                    .method("GET")
                    .uri(format!("http://{addr}/panic"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await;

        // The panicking connection may return an error or a 500.
        // Either is acceptable — the key test is that /status still works after.

        let status_resp = client
            .request(
                Request::builder()
                    .method("GET")
                    .uri(format!("http://{addr}/status"))
                    .body(axum::body::Body::empty())
                    .unwrap(),
            )
            .await
            .expect("server should still be alive after a panic in another handler");

        assert_eq!(status_resp.status(), StatusCode::OK);

        server.abort();
    }

    #[tokio::test]
    async fn log_returns_full_message_log_in_chronological_order() {
        let state = Arc::new(BrokerState::new(None));
        // Seed the broker with three published messages.
        for (agent, status_label) in [
            ("feat-a", "working"),
            ("feat-b", "blocked"),
            ("feat-c", "done"),
        ] {
            let msg = BrokerMessage::Status {
                agent_id: agent.to_string(),
                payload: super::super::messages::StatusPayload {
                    status: status_label.to_string(),
                    modified_files: vec![],
                    message: None,
                    ..Default::default()
                },
            };
            delivery::publish_message(&state, &msg);
        }

        let app = router(state);
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/log")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let parsed: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let entries = parsed["entries"].as_array().expect("entries array");
        assert_eq!(entries.len(), 3, "all three messages must appear in /log");
        // Chronological order: feat-a first, feat-c last.
        assert_eq!(entries[0]["message"]["agent_id"], "feat-a");
        assert_eq!(entries[2]["message"]["agent_id"], "feat-c");
        assert_eq!(parsed["last_seq"], 3);
    }

    #[tokio::test]
    async fn log_with_since_filters_older_entries() {
        let state = Arc::new(BrokerState::new(None));
        for agent in ["feat-a", "feat-b", "feat-c"] {
            let msg = BrokerMessage::Status {
                agent_id: agent.to_string(),
                payload: super::super::messages::StatusPayload {
                    status: "working".to_string(),
                    modified_files: vec![],
                    message: None,
                    ..Default::default()
                },
            };
            delivery::publish_message(&state, &msg);
        }

        let app = router(state);
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/log?since=2")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let parsed: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let entries = parsed["entries"].as_array().unwrap();
        assert_eq!(
            entries.len(),
            1,
            "since=2 must yield only the message at seq=3"
        );
        assert_eq!(entries[0]["seq"], 3);
    }

    #[tokio::test]
    async fn log_invalid_since_returns_400() {
        let app = test_router();
        let resp = app
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/log?since=notanumber")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }
}