zc2 0.0.45

P2P compute broker with credit-based billing, WAL, and broker mesh support
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
//! `zc agent`'s local API (spec ยง6.3-6.4): loopback-only, token-guarded, and
//! refusing anything a browser could send.

use crate::agent::core::{ApiError, Core};
use crate::agent::summary::Summary;
use axum::extract::rejection::JsonRejection;
use axum::extract::{Request, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{delete, get, post, put};
use axum::{Json, Router};
use serde::{Deserialize, Deserializer};
use std::sync::Arc;

#[derive(Clone)]
struct Guard {
    token: Arc<String>,
    port: u16,
}

pub fn router(core: Arc<Core>, token: String, port: u16) -> Router {
    let guard = Guard {
        token: Arc::new(token),
        port,
    };
    Router::new()
        .route("/v1/summary", get(get_summary))
        .route("/v1/refresh", post(post_refresh))
        .route("/v1/sharing", put(put_sharing))
        .route("/v1/workers", put(put_workers))
        .route("/v1/price", put(put_price))
        .merge(v2_routes())
        .fallback(not_found)
        .method_not_allowed_fallback(method_not_allowed)
        .layer(middleware::from_fn_with_state(guard, guard_layer))
        .with_state(core)
}

/// `/v2` (ADR ZC-0019 ยง2). Behind the same guard layer as `/v1`: it is
/// merged into the one router before the layer is applied.
fn v2_routes() -> Router<Arc<Core>> {
    Router::new()
        .route("/v2/summary", get(get_summary_v2))
        .route("/v2/jobs", get(get_jobs))
        .route("/v2/events", get(crate::agent::server::sse::get_events))
        .route(
            "/v2/policy",
            get(|| not_implemented("policy", ISSUE_POLICY))
                .put(|| not_implemented("policy", ISSUE_POLICY)),
        )
        .route(
            "/v2/ledger",
            get(|| not_implemented("ledger", ISSUE_LEDGER)),
        )
        .route(
            "/v2/sandbox",
            get(|| not_implemented("sandbox", ISSUE_SANDBOX)),
        )
        .route(
            "/v2/sandbox/resize",
            post(|| not_implemented("sandbox resize", ISSUE_BUDGET)),
        )
        .route(
            "/v2/squads",
            get(|| not_implemented("squads", ISSUE_SQUADS)),
        )
        .route(
            "/v2/squads/join",
            post(|| not_implemented("squads", ISSUE_SQUADS)),
        )
        .route(
            "/v2/squads/:id/leave",
            post(|| not_implemented("squads", ISSUE_SQUADS)),
        )
        .route(
            "/v2/envs",
            get(|| not_implemented("environments", ISSUE_ENVS))
                .post(|| not_implemented("environments", ISSUE_ENVS)),
        )
        .route(
            "/v2/envs/:id/connect",
            post(|| not_implemented("environments", ISSUE_ENVS)),
        )
        .route(
            "/v2/envs/:id",
            delete(|| not_implemented("environments", ISSUE_ENVS)),
        )
        .route(
            "/v2/handoff",
            post(|| not_implemented("deep-link hand-off", ISSUE_HANDOFF)),
        )
        .route(
            "/v2/handoff/:jti/confirm",
            post(|| not_implemented("deep-link hand-off", ISSUE_HANDOFF)),
        )
}

/// The issue each not-yet-built `/v2` feature ships in: what a 501's `until`
/// names, so a client can say when to expect it.
pub const ISSUE_POLICY: &str = "zakuro-ai/zc#514";
pub const ISSUE_LEDGER: &str = "zakuro-ai/zc#516";
pub const ISSUE_SANDBOX: &str = "zakuro-ai/zc#510";
pub const ISSUE_BUDGET: &str = "zakuro-ai/zc#513";
pub const ISSUE_SQUADS: &str = "zakuro-ai/zc#517";
pub const ISSUE_ENVS: &str = "zakuro-ai/zc#519";
pub const ISSUE_HANDOFF: &str = "zakuro-ai/zc#509";

/// `501 {"error":{"code":"not_implemented","message":โ€ฆ,"until":"<issue>"}}`:
/// the route is part of the v2 contract, but its feature has not shipped.
/// Same envelope as every other error, plus `until`.
async fn not_implemented(what: &'static str, until: &'static str) -> Response {
    (
        StatusCode::NOT_IMPLEMENTED,
        Json(serde_json::json!({ "error": {
            "code": "not_implemented",
            "message": format!("{what} is not available in this zc yet"),
            "until": until,
        } })),
    )
        .into_response()
}

async fn get_summary_v2(State(core): State<Arc<Core>>) -> Response {
    Json(core.summary_v2()).into_response()
}

#[derive(Deserialize)]
struct JobsParams {
    state: Option<String>,
    source: Option<String>,
    squad: Option<String>,
    since: Option<String>,
}

async fn get_jobs(
    State(core): State<Arc<Core>>,
    params: Result<axum::extract::Query<JobsParams>, axum::extract::rejection::QueryRejection>,
) -> Response {
    let Ok(axum::extract::Query(p)) = params else {
        return error(400, "invalid_input", "unreadable query string");
    };
    match crate::agent::jobs::Query::parse(p.state, p.source, p.squad, p.since) {
        Ok(q) => Json(serde_json::json!({ "jobs": core.jobs(&q) })).into_response(),
        Err(m) => error(400, "invalid_input", &m),
    }
}

/// `GET /v2/events`: Server-Sent Events (ADR ZC-0019 ยง3).
pub mod sse {
    use crate::agent::core::Core;
    use crate::agent::events::{Event as BusEvent, Replay};
    use axum::extract::State;
    use axum::http::HeaderMap;
    use axum::response::sse::{Event, KeepAlive, Sse};
    use axum::response::{IntoResponse, Response};
    use futures_util::stream::{self, Stream, StreamExt};
    use std::convert::Infallible;
    use std::sync::Arc;
    use std::time::Duration;
    use tokio::sync::broadcast::error::RecvError;

    /// A comment line this often, so idle proxies and clients keep the
    /// connection, and a dead client is noticed within one interval.
    pub const KEEPALIVE: Duration = Duration::from_secs(15);

    pub fn to_sse(e: &BusEvent) -> Event {
        Event::default()
            .id(e.id.to_string())
            .event(e.kind.clone())
            .data(serde_json::to_string(e).unwrap_or_default())
    }

    /// `resync`: re-fetch `/v2/summary`. Carries the current last id, so a
    /// client that reconnects after it resumes from here.
    fn resync(last_id: u64) -> Event {
        Event::default()
            .id(last_id.to_string())
            .event("resync")
            .data(serde_json::json!({ "type": "resync", "id": last_id }).to_string())
    }

    pub fn last_event_id(headers: &HeaderMap) -> Option<u64> {
        headers
            .get("last-event-id")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.trim().parse().ok())
    }

    pub async fn get_events(State(core): State<Arc<Core>>, headers: HeaderMap) -> Response {
        let (replay, rx) = core.events.subscribe(last_event_id(&headers));
        let first: Vec<Event> = match replay {
            Replay::Events(ev) => ev.iter().map(to_sse).collect(),
            Replay::Resync => vec![resync(core.events.last_id())],
        };
        let live = stream::unfold((rx, core), |(mut rx, core)| async move {
            let ev = match rx.recv().await {
                Ok(e) => to_sse(&e),
                // Fell behind the broadcast buffer: the client missed events.
                Err(RecvError::Lagged(_)) => resync(core.events.last_id()),
                Err(RecvError::Closed) => return None,
            };
            Some((ev, (rx, core)))
        });
        let body: std::pin::Pin<Box<dyn Stream<Item = Result<Event, Infallible>> + Send>> =
            Box::pin(stream::iter(first).chain(live).map(Ok));
        Sse::new(body)
            .keep_alive(KeepAlive::new().interval(KEEPALIVE))
            .into_response()
    }
}

fn error(status: u16, code: &str, message: &str) -> Response {
    (
        StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR),
        Json(serde_json::json!({ "error": { "code": code, "message": message } })),
    )
        .into_response()
}

/// Constant-time comparison: the time taken never depends on where two
/// equal-length inputs first differ.
pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
    a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
}

/// In order: any `Origin` header means a browser sent this, refused (CSRF); a
/// `Host` other than our own loopback name means DNS rebinding, also refused;
/// a missing, empty, or wrong bearer token is refused last.
#[allow(clippy::result_large_err)] // the Err carries the exact Response callers should return
pub fn check_request(headers: &HeaderMap, token: &str, port: u16) -> Result<(), Response> {
    if headers.contains_key(header::ORIGIN) {
        return Err(error(
            403,
            "forbidden",
            "requests from a browser are refused",
        ));
    }
    let host = headers
        .get(header::HOST)
        .and_then(|h| h.to_str().ok())
        .unwrap_or("");
    if host != format!("127.0.0.1:{port}") && host != format!("localhost:{port}") {
        return Err(error(403, "forbidden", "unexpected Host header"));
    }
    let presented = headers
        .get(header::AUTHORIZATION)
        .and_then(|h| h.to_str().ok())
        .and_then(|h| h.strip_prefix("Bearer "))
        .unwrap_or("");
    if token.is_empty() || !ct_eq(presented.as_bytes(), token.as_bytes()) {
        return Err(error(401, "unauthorized", "missing or invalid agent token"));
    }
    Ok(())
}

async fn guard_layer(State(g): State<Guard>, req: Request, next: Next) -> Response {
    match check_request(req.headers(), &g.token, g.port) {
        Ok(()) => next.run(req).await,
        Err(resp) => resp,
    }
}

fn respond(result: Result<Summary, ApiError>) -> Response {
    match result {
        Ok(s) => Json(s).into_response(),
        Err(e) => error(e.status, e.code, &e.message),
    }
}

fn bad_body(e: JsonRejection) -> Response {
    error(400, "invalid_input", &e.body_text())
}

async fn get_summary(State(core): State<Arc<Core>>) -> Response {
    Json(core.summary()).into_response()
}

/// Re-polls the hub now, then returns the summary. The broker and workers are
/// re-observed by the reconcile tick (every 2 s, 1 s while a worker drains):
/// this wakes that tick but doesn't wait for it, so a slow tick (stopping a
/// broker can take its whole grace period) never holds the request.
async fn post_refresh(State(core): State<Arc<Core>>) -> Response {
    core.refresh_hub().await;
    core.wake_reconcile.notify_one();
    Json(core.summary()).into_response()
}

#[derive(Deserialize)]
struct SharingBody {
    on: bool,
}

async fn put_sharing(
    State(core): State<Arc<Core>>,
    body: Result<Json<SharingBody>, JsonRejection>,
) -> Response {
    match body {
        Ok(Json(b)) => respond(core.set_sharing(b.on)),
        Err(e) => bad_body(e),
    }
}

#[derive(Deserialize)]
struct WorkersBody {
    count: u32,
}

async fn put_workers(
    State(core): State<Arc<Core>>,
    body: Result<Json<WorkersBody>, JsonRejection>,
) -> Response {
    match body {
        Ok(Json(b)) => respond(core.set_workers(b.count)),
        Err(e) => bad_body(e),
    }
}

/// Distinguishes "the key is present" from "the key is absent": paired with
/// `#[serde(default)]` on an `Option<Option<T>>` field, a missing key leaves
/// the outer `None`, while a present `null` gives `Some(None)`.
fn deserialize_present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
    T: Deserialize<'de>,
    D: Deserializer<'de>,
{
    T::deserialize(deserializer).map(Some)
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PriceBody {
    scope: String,
    /// Required: an explicit `null` clears the price (device โ†’ account
    /// default, default โ†’ mesh price), a number sets it, and a missing key
    /// is a 400 rather than a silent clear.
    #[serde(default, deserialize_with = "deserialize_present")]
    price_per_hour: Option<Option<f64>>,
}

async fn put_price(
    State(core): State<Arc<Core>>,
    body: Result<Json<PriceBody>, JsonRejection>,
) -> Response {
    match body {
        Ok(Json(b)) => match b.price_per_hour {
            Some(price) => respond(core.set_price(&b.scope, price).await),
            None => error(400, "invalid_input", "price_per_hour is required"),
        },
        Err(e) => bad_body(e),
    }
}

async fn not_found() -> Response {
    error(404, "not_found", "no such route")
}

async fn method_not_allowed() -> Response {
    error(
        405,
        "method_not_allowed",
        "method not allowed on this route",
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::core::tests::core_with;
    use std::time::Duration;

    fn headers(pairs: &[(&str, &str)]) -> axum::http::HeaderMap {
        let mut h = axum::http::HeaderMap::new();
        for (k, v) in pairs {
            h.insert(
                axum::http::HeaderName::from_bytes(k.as_bytes()).unwrap(),
                v.parse().unwrap(),
            );
        }
        h
    }

    #[test]
    fn guards_refuse_browsers_foreign_hosts_and_bad_tokens() {
        assert!(check_request(
            &headers(&[("host", "127.0.0.1:4720"), ("authorization", "Bearer tok")]),
            "tok",
            4720
        )
        .is_ok());
        assert!(check_request(
            &headers(&[("host", "localhost:4720"), ("authorization", "Bearer tok")]),
            "tok",
            4720
        )
        .is_ok());
        let status = |pairs: &[(&str, &str)]| {
            check_request(&headers(pairs), "tok", 4720)
                .unwrap_err()
                .status()
                .as_u16()
        };
        assert_eq!(status(&[("host", "127.0.0.1:4720")]), 401, "no token");
        assert_eq!(
            status(&[("host", "127.0.0.1:4720"), ("authorization", "Bearer nope")]),
            401,
            "wrong token"
        );
        assert_eq!(
            status(&[("host", "127.0.0.1:4720"), ("authorization", "tok")]),
            401,
            "Bearer scheme required"
        );
        assert_eq!(
            status(&[
                ("host", "evil.example:4720"),
                ("authorization", "Bearer tok")
            ]),
            403,
            "DNS rebinding"
        );
        assert_eq!(
            status(&[("host", "127.0.0.1:9999"), ("authorization", "Bearer tok")]),
            403
        );
        assert_eq!(
            status(&[
                ("host", "127.0.0.1:4720"),
                ("authorization", "Bearer tok"),
                ("origin", "https://evil.example")
            ]),
            403,
            "CSRF"
        );
        assert!(ct_eq(b"abc", b"abc") && !ct_eq(b"abc", b"abd") && !ct_eq(b"abc", b"ab"));
        assert_eq!(
            check_request(
                &headers(&[("host", "127.0.0.1:4720"), ("authorization", "Bearer ")]),
                "",
                4720
            )
            .unwrap_err()
            .status()
            .as_u16(),
            401,
            "an empty configured token never authenticates"
        );
    }

    fn serve(core: std::sync::Arc<crate::agent::core::Core>, token: &str) -> u16 {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        listener.set_nonblocking(true).unwrap();
        let app = router(core, token.to_string(), port);
        std::thread::spawn(move || {
            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap();
            rt.block_on(async move {
                let l = tokio::net::TcpListener::from_std(listener).unwrap();
                axum::serve(l, app).await.unwrap();
            });
        });
        port
    }

    fn call(
        method: &str,
        port: u16,
        path: &str,
        token: Option<&str>,
        body: &str,
    ) -> (u16, serde_json::Value, bool) {
        let agent = ureq::Agent::new_with_config(
            ureq::Agent::config_builder()
                .http_status_as_error(false)
                .timeout_global(Some(Duration::from_secs(5)))
                .build(),
        );
        let url = format!("http://127.0.0.1:{port}{path}");
        let auth = token.map(|t| format!("Bearer {t}")).unwrap_or_default();
        let resp = match method {
            "GET" => agent
                .get(&url)
                .header("Authorization", auth.as_str())
                .call(),
            "DELETE" => agent
                .delete(&url)
                .header("Authorization", auth.as_str())
                .call(),
            "PUT" => agent
                .put(&url)
                .header("Authorization", auth.as_str())
                .header("Content-Type", "application/json")
                .send(body),
            _ => agent
                .post(&url)
                .header("Authorization", auth.as_str())
                .header("Content-Type", "application/json")
                .send(body),
        }
        .unwrap();
        let status = resp.status().as_u16();
        let cors = resp
            .headers()
            .keys()
            .any(|k| k.as_str().starts_with("access-control"));
        let json = resp
            .into_body()
            .read_json::<serde_json::Value>()
            .unwrap_or(serde_json::Value::Null);
        (status, json, cors)
    }

    #[test]
    fn the_local_api_round_trip() {
        let core = core_with(3);
        let port = serve(core, "tok");

        let (s, v, cors) = call("GET", port, "/v1/summary", Some("tok"), "");
        assert_eq!(
            (s, v["v"].as_u64(), v["this_mac"]["workers"]["max"].as_u64()),
            (200, Some(1), Some(3))
        );
        assert!(!cors, "no CORS headers, ever");

        let (s, v, _) = call("GET", port, "/v1/summary", None, "");
        assert_eq!(
            (s, v["error"]["code"].as_str()),
            (401, Some("unauthorized"))
        );

        let (s, v, _) = call("PUT", port, "/v1/workers", Some("tok"), r#"{"count":2}"#);
        assert_eq!(
            (s, v["this_mac"]["workers"]["desired"].as_u64()),
            (200, Some(2))
        );
        let (s, v, _) = call("PUT", port, "/v1/workers", Some("tok"), r#"{"count":9}"#);
        assert_eq!(
            (s, v["error"]["code"].as_str()),
            (400, Some("invalid_input"))
        );
        let (s, v, _) = call(
            "PUT",
            port,
            "/v1/workers",
            Some("tok"),
            r#"{"count":"two"}"#,
        );
        assert_eq!(
            (s, v["error"]["code"].as_str()),
            (400, Some("invalid_input"))
        );

        let (s, v, _) = call("PUT", port, "/v1/sharing", Some("tok"), r#"{"on":true}"#);
        assert_eq!((s, v["this_mac"]["sharing"].as_bool()), (200, Some(true)));

        let (s, v, _) = call(
            "PUT",
            port,
            "/v1/price",
            Some("tok"),
            r#"{"scope":"device","price_per_hour":10}"#,
        );
        assert_eq!(
            (s, v["error"]["code"].as_str()),
            (503, Some("prerequisite_missing"))
        );

        let (s, v, _) = call("POST", port, "/v1/refresh", Some("tok"), "");
        assert_eq!((s, v["v"].as_u64()), (200, Some(1)));

        let (s, _, _) = call("GET", port, "/v1/nope", Some("tok"), "");
        assert_eq!(s, 404);
        let (s, v, _) = call("GET", port, "/v1/nope", None, "");
        assert_eq!(
            (s, v["error"]["code"].as_str()),
            (401, Some("unauthorized")),
            "the guard runs before the 404 too"
        );

        let (s, v, _) = call(
            "PUT",
            port,
            "/v1/price",
            Some("tok"),
            r#"{"scope":"device","price":18}"#,
        );
        assert_eq!(
            (s, v["error"]["code"].as_str()),
            (400, Some("invalid_input")),
            "an unknown field is rejected"
        );
        let (s, v, _) = call(
            "PUT",
            port,
            "/v1/price",
            Some("tok"),
            r#"{"scope":"device"}"#,
        );
        assert_eq!(
            (s, v["error"]["code"].as_str()),
            (400, Some("invalid_input")),
            "price_per_hour is required"
        );
        let (s, v, _) = call(
            "PUT",
            port,
            "/v1/price",
            Some("tok"),
            r#"{"scope":"device","price_per_hour":null}"#,
        );
        assert_ne!(
            (s, v["error"]["code"].as_str()),
            (400, Some("invalid_input")),
            "an explicit null still clears, it's not treated as missing"
        );
    }

    #[test]
    fn method_not_allowed_is_json_and_the_guard_runs_first() {
        let core = core_with(3);
        let port = serve(core, "tok");

        let (s, v, _) = call("POST", port, "/v1/summary", Some("tok"), "");
        assert_eq!(
            (s, v["error"]["code"].as_str()),
            (405, Some("method_not_allowed"))
        );

        let (s, v, _) = call("POST", port, "/v1/summary", None, "");
        assert_eq!(
            (s, v["error"]["code"].as_str()),
            (401, Some("unauthorized")),
            "the guard runs before the 405"
        );
    }

    #[test]
    fn v2_is_additive_and_guarded_like_v1() {
        let core = core_with(3);
        let port = serve(core, "tok");

        let (s, v, cors) = call("GET", port, "/v2/summary", Some("tok"), "");
        assert_eq!((s, v["summary_version"].as_u64()), (200, Some(2)));
        assert!(!cors);
        assert!(v["nodes"][0]["this_node"].as_bool().unwrap());
        assert_eq!(v["jobs"]["live"], serde_json::json!([]));
        for k in ["squads", "sandbox", "policy"] {
            assert!(v[k].is_null(), "{k}");
        }
        let (s, v, _) = call("GET", port, "/v1/summary", Some("tok"), "");
        assert_eq!((s, v["v"].as_u64()), (200, Some(1)), "v1 unchanged");

        let (s, v, _) = call("GET", port, "/v2/summary", None, "");
        assert_eq!(
            (s, v["error"]["code"].as_str()),
            (401, Some("unauthorized"))
        );
        let (s, _, _) = call("GET", port, "/v2/squads", None, "");
        assert_eq!(s, 401, "the guard runs before a 501 too");

        let (s, v, _) = call("GET", port, "/v2/jobs", Some("tok"), "");
        assert_eq!((s, v["jobs"].clone()), (200, serde_json::json!([])));
        let (s, v, _) = call("GET", port, "/v2/jobs?state=nope", Some("tok"), "");
        assert_eq!(
            (s, v["error"]["code"].as_str()),
            (400, Some("invalid_input"))
        );
        let (s, _, _) = call(
            "GET",
            port,
            "/v2/jobs?state=done&since=2026-01-01T00:00:00Z",
            Some("tok"),
            "",
        );
        assert_eq!(s, 200);

        for (method, path, until) in [
            ("GET", "/v2/policy", ISSUE_POLICY),
            ("PUT", "/v2/policy", ISSUE_POLICY),
            ("GET", "/v2/ledger", ISSUE_LEDGER),
            ("GET", "/v2/sandbox", ISSUE_SANDBOX),
            ("POST", "/v2/sandbox/resize", ISSUE_BUDGET),
            ("GET", "/v2/squads", ISSUE_SQUADS),
            ("POST", "/v2/squads/join", ISSUE_SQUADS),
            ("POST", "/v2/squads/s1/leave", ISSUE_SQUADS),
            ("GET", "/v2/envs", ISSUE_ENVS),
            ("POST", "/v2/envs", ISSUE_ENVS),
            ("POST", "/v2/envs/e1/connect", ISSUE_ENVS),
            ("DELETE", "/v2/envs/e1", ISSUE_ENVS),
            ("POST", "/v2/handoff", ISSUE_HANDOFF),
            ("POST", "/v2/handoff/abc/confirm", ISSUE_HANDOFF),
        ] {
            let (s, v, _) = call(method, port, path, Some("tok"), "{}");
            assert_eq!(
                (s, v["error"]["code"].as_str(), v["error"]["until"].as_str()),
                (501, Some("not_implemented"), Some(until)),
                "{method} {path}"
            );
            assert!(v["error"]["message"].is_string());
        }
        let (s, v, _) = call("POST", port, "/v2/summary", Some("tok"), "");
        assert_eq!(
            (s, v["error"]["code"].as_str()),
            (405, Some("method_not_allowed"))
        );
        let (s, _, _) = call("GET", port, "/v2/nope", Some("tok"), "");
        assert_eq!(s, 404);
    }

    /// Read SSE messages from `/v2/events` on a thread until `n` arrived.
    fn sse(
        port: u16,
        last_id: Option<u64>,
        n: usize,
    ) -> std::sync::mpsc::Receiver<crate::agent::client::SseMessage> {
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let dir = crate::agent::files::tests::tmp("sse-client");
            crate::agent::files::ensure_dir(&dir).unwrap();
            crate::agent::files::save_json(
                &dir.join(crate::agent::files::AGENT_FILE),
                &crate::agent::files::AgentFile {
                    v: 1,
                    port,
                    token: "tok".into(),
                    pid: 1,
                    version: "x".into(),
                    rev: 1,
                },
            )
            .unwrap();
            let c = crate::agent::client::AgentClient::from_dir(&dir).unwrap();
            let mut seen = 0;
            let _ = c.events(last_id, |m| {
                seen += 1;
                let _ = tx.send(m);
                seen < n
            });
        });
        rx
    }

    #[test]
    fn events_stream_live_and_replay_on_reconnect() {
        let core = core_with(3);
        let port = serve(core.clone(), "tok");
        let first = core
            .events
            .publish("job.started", serde_json::json!({"id": "j1"}));

        let rx = sse(port, None, 1);
        // The stream is open before anything new is published.
        std::thread::sleep(Duration::from_millis(300));
        core.events
            .publish("job.finished", serde_json::json!({"id": "j1"}));
        let m = rx.recv_timeout(Duration::from_secs(5)).unwrap();
        assert_eq!(m.event, "job.finished");
        let body: serde_json::Value = serde_json::from_str(&m.data).unwrap();
        assert_eq!(
            (body["type"].as_str(), body["data"]["id"].as_str()),
            (Some("job.finished"), Some("j1"))
        );
        assert_eq!(m.id, Some(body["id"].to_string()));

        // Reconnect after the first: the second is replayed.
        let rx = sse(port, Some(first), 1);
        let m = rx.recv_timeout(Duration::from_secs(5)).unwrap();
        assert_eq!(
            (m.event.as_str(), m.id),
            ("job.finished", Some((first + 1).to_string()))
        );

        // An id this agent never issued: resync.
        let rx = sse(port, Some(9_999), 1);
        let m = rx.recv_timeout(Duration::from_secs(5)).unwrap();
        assert_eq!(m.event, "resync");

        // No token: refused like every other route.
        let (s, _, _) = call("GET", port, "/v2/events", None, "");
        assert_eq!(s, 401);
    }

    #[test]
    fn a_write_publishes_summary_changed() {
        let core = core_with(3);
        let (_, mut rx) = core.events.subscribe(None);
        core.set_workers(2).unwrap();
        let mut kinds = vec![];
        while let Ok(e) = rx.try_recv() {
            kinds.push(e.kind.clone());
            if e.kind == "summary.changed" {
                assert_eq!(e.data["summary_version"], 2);
                assert_eq!(e.data["nodes"][0]["local"]["workers"]["desired"], 2);
            }
        }
        assert!(kinds.contains(&"summary.changed".to_string()), "{kinds:?}");
        assert!(
            kinds.contains(&"problem.raised".to_string()),
            "not signed in: {kinds:?}"
        );
        // Nothing changed: nothing published.
        core.publish_changes();
        assert!(rx.try_recv().is_err());
    }
}