cargoless-core 0.2.0

The cargoless daemon: filesystem watcher, rust-analyzer wrapper, green/red model, build orchestration.
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
//! Transport abstraction (Model R #10, `D-FLEET-SHARED-DAEMON` §10).
//!
//! One logical API — [`VerdictService`] — bound to three interchangeable
//! transports from the same codebase:
//!
//! | adapter | module | use case (§10.2) |
//! |---|---|---|
//! | in-process | [`inproc`] | single-binary (`cargoless watch` — daemon + CLI in one process; zero IPC) |
//! | Unix socket | [`unix`] | local-default fleet (long-running `serve --repo` + many short CLI calls) |
//! | HTTP + SSE | [`http`] | network mode (`--bind <addr>`; cross-host orchestration) |
//!
//! Plus the CLI auto-discovery fallback chain ([`discovery`], §10.3):
//! `--remote <url>` → conventional Unix socket → file-read `cli-status` /
//! diagnostics (the v0 no-daemon behaviour) → spawn a local single-binary
//! daemon.
//!
//! ## Layering
//!
//! The logical API + DTOs live in `cargoless-core` and use **only**
//! core/proto types — the Stream-B serve loop (#3/#4) *implements*
//! [`VerdictService`] and the adapters are generic over it, so this seam
//! is definable without the serve-loop body in-tree (that is the point of
//! the abstraction). Per-crate verdicts are computed in the `cargoless`
//! cli crate (#9 `cratemap`), which `cargoless-core` cannot depend on;
//! the serve loop therefore passes already-rolled-up
//! [`CrateVerdict`]s into the status DTO. Diagnostics retention is
//! core-owned ([`crate::diagnostics_store`]) so [`VerdictService::
//! get_diagnostics`] can delegate directly.
//!
//! ## Auth seam (#14 — explicitly out of #10 scope)
//!
//! Network auth is Model R #14 (builder-infra), sequenced *after* #10.
//! This module defines the [`Authorizer`] seam + a default-permissive
//! [`AllowAll`]; the HTTP adapter consults it on every request. #14 swaps
//! a bearer-token `Authorizer` in **without reshaping the adapter** — the
//! seam is the contract, the policy is #14's.
//!
//! ## Dependency posture
//!
//! std-only + the crate's existing `serde_json` (Value + `json!`, no
//! derive — the sanctioned house tool; hand-rolled JSON for the wire is
//! the latent-bug factory the crate's dep rationale warns against). No
//! HTTP framework: the network adapter is a minimal, bounded HTTP/1.1 +
//! SSE over `std::net` (house ethos — JSON-RPC framing / debounce /
//! ignore are all hand-rolled in-crate already). Best-effort throughout:
//! a transport failure is surfaced as a typed error, never a panic.

use std::sync::Arc;
use std::sync::mpsc::Receiver;

use cargoless_proto::Diagnostic;

use crate::config::{FleetConfig, FleetConfigError};

pub mod discovery;
pub mod http;
pub mod inproc;
pub mod unix;

/// One crate's verdict within a worktree (the #9 schema=2 `crates=`
/// roll-up, transport-DTO form). `verdict` is `"green"|"red"|"unknown"`
/// — string, not an enum, so the wire is forward-compatible and a
/// schema=1-era reader is unaffected (same discipline as cli-status #9).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CrateVerdict {
    pub name: String,
    pub verdict: String,
}

/// Transport-agnostic worktree status (the `get_status` payload, §10.1).
/// `crates` empty ⇒ no trustworthy per-crate breakdown (single-crate, or
/// the #9 unattributable-error honesty case); `verdict` is **always** the
/// authoritative tree verdict and stands alone — the sidecar discipline
/// (#11/#176) carried into the transport layer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorktreeStatus {
    pub worktree: String,
    pub verdict: String,
    pub crates: Vec<CrateVerdict>,
    pub red_diagnostics: u32,
    pub heartbeat_age_secs: u64,
    pub published_at: u64,
}

/// Light per-worktree summary for `list_worktrees` (§10.1) — just enough
/// for a dashboard without the heavy diagnostics payload (asymmetric
/// principle: terse by default, detail on demand via `get_diagnostics`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorktreeSummary {
    pub worktree: String,
    pub verdict: String,
    pub red_diagnostics: u32,
}

/// A verdict-transition event for `subscribe` (§10.1, SSE-style stream).
/// Carries the new status; the HTTP adapter renders it as an SSE
/// `data:` frame, the Unix adapter as a newline-delimited JSON record,
/// the in-proc adapter hands the `Receiver` back directly.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransitionEvent {
    pub worktree: String,
    pub verdict: String,
    pub red_diagnostics: u32,
    pub published_at: u64,
}

/// The single logical API (§10.1). The Stream-B serve loop implements
/// this; every adapter is generic over `S: VerdictService`. `Send +
/// Sync` so the Unix/HTTP adapters can share one service across
/// connection threads.
pub trait VerdictService: Send + Sync {
    /// Full status for a worktree (current verdict + heartbeat +
    /// per-crate breakdown). `None` ⇒ unknown worktree.
    fn get_status(&self, worktree: &str) -> Option<WorktreeStatus>;

    /// Just the verdict string (light — no per-crate, no heartbeat).
    /// `None` ⇒ unknown worktree.
    fn get_verdict(&self, worktree: &str) -> Option<String>;

    /// Full retained diagnostics for a worktree's current red state
    /// (heavy). Empty ⇒ green / never-red / unknown (callers treat "no
    /// detail" and "green" the same — correct, a green tree retains
    /// nothing; see [`crate::diagnostics_store`]).
    fn get_diagnostics(&self, worktree: &str) -> Vec<Diagnostic>;

    /// All discovered worktrees with their light verdict summary.
    fn list_worktrees(&self) -> Vec<WorktreeSummary>;

    /// Subscribe to the transition-event stream. The serve loop owns the
    /// fan-out; each call yields an independent `Receiver`.
    fn subscribe(&self) -> Receiver<TransitionEvent>;
}

/// The **client** counterpart of [`VerdictService`] — the uniform
/// surface the CLI programs against regardless of which transport
/// [`discovery`] resolved. Every adapter ships a client implementing
/// this; the CLI fallback chain swaps implementations without changing
/// call sites. Methods return [`TransportError`] (in-proc is infallible
/// and always `Ok`, but the signature is uniform so a fallible socket /
/// HTTP client is a drop-in).
pub trait TransportClient {
    fn get_status(&self, worktree: &str) -> Result<Option<WorktreeStatus>, TransportError>;
    fn get_verdict(&self, worktree: &str) -> Result<Option<String>, TransportError>;
    fn get_diagnostics(&self, worktree: &str) -> Result<Vec<Diagnostic>, TransportError>;
    fn list_worktrees(&self) -> Result<Vec<WorktreeSummary>, TransportError>;
    /// Subscribe to transitions. Returns a `Receiver` so all three
    /// transports present the same pull interface (in-proc hands the
    /// service receiver back; Unix/HTTP spawn a reader thread that
    /// forwards decoded frames into a channel).
    fn subscribe(&self) -> Result<Receiver<TransitionEvent>, TransportError>;
}

/// Network-auth seam (Model R #14 — NOT implemented in #10). The HTTP
/// adapter calls [`Authorizer::authorize`] on every request with the
/// presented bearer token (if any). #14 provides a real token policy by
/// swapping the `Arc<dyn Authorizer>` — the adapter is unchanged.
pub trait Authorizer: Send + Sync {
    /// `true` ⇒ allow. `token` is the `Authorization: Bearer <token>`
    /// value if the client sent one, else `None`.
    fn authorize(&self, token: Option<&str>) -> bool;
}

/// Default-permissive authorizer (the #10 posture: localhost-only,
/// no auth — `D-FLEET §10.4`). #14 replaces this with a bearer-token
/// policy for `--bind`-to-network deployments. Named (not a closure) so
/// the "this is intentionally open in #10" decision is greppable.
#[derive(Debug, Clone, Copy, Default)]
pub struct AllowAll;

impl Authorizer for AllowAll {
    fn authorize(&self, _token: Option<&str>) -> bool {
        true
    }
}

/// #14 — bearer-token [`Authorizer`] for network (`--bind`) mode.
///
/// Allows a request iff it presents `Authorization: Bearer <token>` whose
/// value equals the configured secret. A request with no token is denied
/// (⇒ the HTTP adapter's existing clean `401`); the #10 seam is unchanged
/// — this is pure policy swapped in via [`authorizer_for`].
///
/// ## Constant-time content compare (the load-bearing security property)
///
/// The token compare must not early-return on the first differing byte —
/// that leaks, via response timing, a prefix-matching oracle that turns
/// secret recovery from `O(charset^len)` into `O(charset*len)`. The
/// content comparison here folds every byte into a single accumulator
/// with `|=` and only inspects the accumulator at the end: the work is
/// independent of *where* (or whether) a mismatch occurs.
///
/// Length is compared first and may short-circuit: this is the standard
/// token-compare discipline (ring `verify_slices_are_equal`, OpenSSL
/// `CRYPTO_memcmp` both require equal length). A bearer token's *length*
/// is low-entropy and not the secret; its *content* is. Equalising the
/// loop bound on unequal lengths would compare against attacker-chosen
/// bytes and still reveal nothing the length didn't — the standard
/// trade, made explicit.
pub struct BearerToken {
    secret: Vec<u8>,
}

impl BearerToken {
    /// The configured shared secret (from `--auth-token` /
    /// `CARGOLESS_AUTH_TOKEN` / `tf.toml [fleet] auth_token`, resolved
    /// through the frozen #1 `FleetConfig` contract).
    pub fn new(secret: impl Into<String>) -> Self {
        Self {
            secret: secret.into().into_bytes(),
        }
    }
}

/// Constant-time-content byte-slice equality (see [`BearerToken`] docs).
/// `#[inline(never)]` so an optimiser can't peel the loop into an
/// early-exit shape that reintroduces the timing oracle.
#[inline(never)]
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff: u8 = 0;
    for (x, y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    diff == 0
}

impl Authorizer for BearerToken {
    fn authorize(&self, token: Option<&str>) -> bool {
        // Consumer-side make-the-bad-state-unrepresentable (CWDL #197):
        // a BearerToken whose configured secret is empty or
        // whitespace-only authorizes NOTHING. Even if some future config
        // path reconstructed an empty-secret bearer, it fails CLOSED
        // (deny → 401) — never an empty-`Authorization: Bearer ` bypass.
        // `[].iter().all(..)` is vacuously true ⇒ an empty secret denies.
        if self.secret.iter().all(u8::is_ascii_whitespace) {
            return false;
        }
        match token {
            // No credential presented ⇒ deny (HTTP adapter → 401).
            None => false,
            Some(presented) => constant_time_eq(presented.as_bytes(), &self.secret),
        }
    }
}

/// Select the network [`Authorizer`] for a resolved [`FleetConfig`],
/// **failing closed**.
///
/// This is the #14 policy seam binding (the HTTP adapter takes the
/// returned `Arc<dyn Authorizer>` unchanged — `D-FLEET §10.4`):
///
/// * non-loopback `bind` **without** an `auth_token` ⇒ `Err` (the
///   [`FleetConfig::security_check`] by-construction refusal — the
///   daemon must NOT serve an unauthenticated socket reachable
///   off-host; surfacing the typed config error is the safe failure,
///   never a silent [`AllowAll`] on a public bind);
/// * an `auth_token` present ⇒ [`BearerToken`] (enforced even on a
///   loopback bind — opting into auth is always honoured);
/// * otherwise (no token; absent or loopback `bind`) ⇒ [`AllowAll`],
///   the #10 localhost-only posture, unchanged.
///
/// Pure: no I/O, no socket — the serve/daemon I/O-shell calls this and
/// hands the result to `HttpServer::bind`. Exhaustively unit-tested over
/// the loopback/non-loopback × token/no-token matrix.
pub fn authorizer_for(cfg: &FleetConfig) -> Result<Arc<dyn Authorizer>, FleetConfigError> {
    // Fail closed first: a network-reachable bind with no token is
    // refused here, not downgraded to permissive.
    cfg.security_check()?;
    // Single source of truth for "an effective secret exists" (CWDL
    // #197): a blank (empty / whitespace-only) configured token is NOT a
    // token — `effective_auth_token()` returns `None`, so a blank token
    // yields `AllowAll` only where `security_check` already permits it
    // (loopback / no bind); a non-loopback blank token was refused by
    // `security_check` above. No `BearerToken` is ever built from a
    // blank secret.
    Ok(match cfg.effective_auth_token() {
        Some(secret) => Arc::new(BearerToken::new(secret)),
        None => Arc::new(AllowAll),
    })
}

/// A transport error. Best-effort discipline: adapters return this, never
/// panic; the CLI fallback chain ([`discovery`]) treats any `Err` as
/// "this transport unavailable, try the next".
#[derive(Debug)]
pub enum TransportError {
    /// Socket/TCP/HTTP I/O failure (connection refused, reset, timeout).
    Io(std::io::Error),
    /// Wire payload could not be parsed (malformed JSON / framing).
    Protocol(String),
    /// Auth denied by the [`Authorizer`] (#14; never produced under
    /// [`AllowAll`]). Defined now so #14 adds policy, not a new variant.
    Unauthorized,
}

impl std::fmt::Display for TransportError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            TransportError::Io(e) => write!(f, "transport I/O: {e}"),
            TransportError::Protocol(m) => write!(f, "transport protocol: {m}"),
            TransportError::Unauthorized => write!(f, "transport: unauthorized"),
        }
    }
}

impl std::error::Error for TransportError {}

impl From<std::io::Error> for TransportError {
    fn from(e: std::io::Error) -> Self {
        TransportError::Io(e)
    }
}

// --------------------------------------------------------------------------
// Wire codec — one place, shared by the Unix + HTTP adapters so the two
// transports speak byte-identical JSON (serde_json::Value, no derive —
// house style, cf. `diagnostics_store`). Pure (no I/O) ⇒ unit-tested
// directly without a socket.
// --------------------------------------------------------------------------

/// The set of logical calls, as a parsed request (the JSON-RPC-ish
/// envelope the Unix/HTTP adapters decode a line / request body into).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Request {
    GetStatus(String),
    GetVerdict(String),
    GetDiagnostics(String),
    ListWorktrees,
    Subscribe,
}

impl Request {
    /// Parse `{"op":"get_status","worktree":"W"}` (best-effort; unknown
    /// op ⇒ `None` so the adapter answers a clean protocol error rather
    /// than panicking).
    pub fn from_json(text: &str) -> Option<Request> {
        let v: serde_json::Value = serde_json::from_str(text).ok()?;
        let op = v.get("op")?.as_str()?;
        let wt = || {
            v.get("worktree")
                .and_then(serde_json::Value::as_str)
                .unwrap_or("")
                .to_string()
        };
        match op {
            "get_status" => Some(Request::GetStatus(wt())),
            "get_verdict" => Some(Request::GetVerdict(wt())),
            "get_diagnostics" => Some(Request::GetDiagnostics(wt())),
            "list_worktrees" => Some(Request::ListWorktrees),
            "subscribe" => Some(Request::Subscribe),
            _ => None,
        }
    }

    pub fn to_json(&self) -> String {
        let v = match self {
            Request::GetStatus(w) => serde_json::json!({"op":"get_status","worktree":w}),
            Request::GetVerdict(w) => serde_json::json!({"op":"get_verdict","worktree":w}),
            Request::GetDiagnostics(w) => {
                serde_json::json!({"op":"get_diagnostics","worktree":w})
            }
            Request::ListWorktrees => serde_json::json!({"op":"list_worktrees"}),
            Request::Subscribe => serde_json::json!({"op":"subscribe"}),
        };
        v.to_string()
    }
}

fn crate_verdicts_json(crates: &[CrateVerdict]) -> serde_json::Value {
    serde_json::Value::Array(
        crates
            .iter()
            .map(|c| serde_json::json!({"name": c.name, "verdict": c.verdict}))
            .collect(),
    )
}

fn crate_verdicts_from_json(v: Option<&serde_json::Value>) -> Vec<CrateVerdict> {
    let Some(serde_json::Value::Array(items)) = v else {
        return Vec::new();
    };
    items
        .iter()
        .filter_map(|c| {
            Some(CrateVerdict {
                name: c.get("name")?.as_str()?.to_string(),
                verdict: c
                    .get("verdict")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("unknown")
                    .to_string(),
            })
        })
        .collect()
}

/// Serialise a `WorktreeStatus` to the wire JSON.
pub fn status_to_json(s: &WorktreeStatus) -> String {
    serde_json::json!({
        "worktree": s.worktree,
        "verdict": s.verdict,
        "crates": crate_verdicts_json(&s.crates),
        "red_diagnostics": s.red_diagnostics,
        "heartbeat_age_secs": s.heartbeat_age_secs,
        "published_at": s.published_at,
    })
    .to_string()
}

/// Parse wire JSON back to a `WorktreeStatus` (best-effort: a missing
/// `worktree` ⇒ `None`; missing scalars ⇒ 0/empty, never a panic).
pub fn status_from_json(text: &str) -> Option<WorktreeStatus> {
    let v: serde_json::Value = serde_json::from_str(text).ok()?;
    Some(WorktreeStatus {
        worktree: v.get("worktree")?.as_str()?.to_string(),
        verdict: v
            .get("verdict")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("unknown")
            .to_string(),
        crates: crate_verdicts_from_json(v.get("crates")),
        red_diagnostics: v
            .get("red_diagnostics")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(0) as u32,
        heartbeat_age_secs: v
            .get("heartbeat_age_secs")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(0),
        published_at: v
            .get("published_at")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(0),
    })
}

/// Serialise the `list_worktrees` summary array.
pub fn summaries_to_json(list: &[WorktreeSummary]) -> String {
    serde_json::Value::Array(
        list.iter()
            .map(|s| {
                serde_json::json!({
                    "worktree": s.worktree,
                    "verdict": s.verdict,
                    "red_diagnostics": s.red_diagnostics,
                })
            })
            .collect(),
    )
    .to_string()
}

/// Parse the `list_worktrees` summary array (best-effort, skips malformed
/// elements — a dashboard degrades to fewer rows, never crashes).
pub fn summaries_from_json(text: &str) -> Vec<WorktreeSummary> {
    let Ok(serde_json::Value::Array(items)) = serde_json::from_str::<serde_json::Value>(text)
    else {
        return Vec::new();
    };
    items
        .iter()
        .filter_map(|s| {
            Some(WorktreeSummary {
                worktree: s.get("worktree")?.as_str()?.to_string(),
                verdict: s
                    .get("verdict")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("unknown")
                    .to_string(),
                red_diagnostics: s
                    .get("red_diagnostics")
                    .and_then(serde_json::Value::as_u64)
                    .unwrap_or(0) as u32,
            })
        })
        .collect()
}

/// Serialise a transition event (SSE `data:` payload / Unix NDJSON line).
pub fn event_to_json(e: &TransitionEvent) -> String {
    serde_json::json!({
        "worktree": e.worktree,
        "verdict": e.verdict,
        "red_diagnostics": e.red_diagnostics,
        "published_at": e.published_at,
    })
    .to_string()
}

/// Parse a transition event from its wire JSON (the `subscribe` NDJSON
/// frame / SSE `data:` payload). Shared by the Unix + HTTP stream
/// clients so both decode byte-identically. Best-effort: a malformed
/// frame ⇒ `None` (the stream client skips it, never panics).
pub fn event_from_json(text: &str) -> Option<TransitionEvent> {
    let v: serde_json::Value = serde_json::from_str(text).ok()?;
    Some(TransitionEvent {
        worktree: v.get("worktree")?.as_str()?.to_string(),
        verdict: v
            .get("verdict")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("unknown")
            .to_string(),
        red_diagnostics: v
            .get("red_diagnostics")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(0) as u32,
        published_at: v
            .get("published_at")
            .and_then(serde_json::Value::as_u64)
            .unwrap_or(0),
    })
}

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

    // ───────────────────────── #14 auth ─────────────────────────

    #[test]
    fn bearer_token_accepts_exact_denies_wrong_and_none() {
        let a = BearerToken::new("s3cr3t-abc");
        assert!(a.authorize(Some("s3cr3t-abc")), "exact match ⇒ allow");
        assert!(!a.authorize(Some("s3cr3t-abd")), "1-byte-off ⇒ deny");
        assert!(!a.authorize(Some("s3cr3t-ab")), "prefix (shorter) ⇒ deny");
        assert!(
            !a.authorize(Some("s3cr3t-abcd")),
            "superstring (longer) ⇒ deny"
        );
        assert!(!a.authorize(Some("")), "empty presented ⇒ deny");
        assert!(!a.authorize(None), "no credential ⇒ deny (→ adapter 401)");
    }

    #[test]
    fn constant_time_eq_is_correct_total_and_length_safe() {
        // Correctness (the timing property itself is structural — no
        // early return over content — and asserted by code review, not a
        // flaky wall-clock test; here we pin the FUNCTIONAL contract).
        assert!(constant_time_eq(b"", b""));
        assert!(constant_time_eq(b"abc", b"abc"));
        assert!(!constant_time_eq(b"abc", b"abd")); // last byte differs
        assert!(!constant_time_eq(b"abc", b"Xbc")); // first byte differs
        assert!(!constant_time_eq(b"abc", b"ab")); // length differs
        assert!(!constant_time_eq(b"ab", b"abc"));
        // A first-byte mismatch and a last-byte mismatch are both `false`
        // — the accumulator folds the whole equal-length slice; position
        // of the mismatch never short-circuits.
        assert_eq!(
            constant_time_eq(b"\x00xxxxxxxx", b"\xffxxxxxxxx"),
            constant_time_eq(b"xxxxxxxx\x00", b"xxxxxxxx\xff"),
            "mismatch position must not change the result path"
        );
    }

    fn cfg_bind_token(bind: Option<&str>, token: Option<&str>) -> FleetConfig {
        let mut c = FleetConfig::defaults();
        c.bind = bind.map(|b| b.parse().expect("test bind addr"));
        c.auth_token = token.map(str::to_string);
        c
    }

    #[test]
    fn authorizer_for_loopback_no_token_is_allowall_open_posture() {
        // #10 posture preserved: loopback bind, no token ⇒ AllowAll
        // (open, localhost-only — D-FLEET §10.4).
        let c = cfg_bind_token(Some("127.0.0.1:8080"), None);
        let a = authorizer_for(&c).expect("loopback no-token must not error");
        assert!(a.authorize(None), "AllowAll ⇒ no-token allowed on loopback");
        assert!(a.authorize(Some("whatever")));
    }

    #[test]
    fn authorizer_for_non_loopback_no_token_fails_closed() {
        // THE load-bearing security property: a network-reachable bind
        // with no auth_token is REFUSED here (security_check by
        // construction) — never silently downgraded to AllowAll on a
        // public socket.
        let c = cfg_bind_token(Some("0.0.0.0:8080"), None);
        let r = authorizer_for(&c);
        assert!(
            matches!(r, Err(FleetConfigError::BadBind { .. })),
            "non-loopback + no token MUST be a refused config error \
             (Ok would mean a public socket got a silent AllowAll)"
        );
    }

    #[test]
    fn authorizer_for_token_present_is_bearer_even_on_loopback() {
        // Opting into auth is always honoured (loopback too).
        let c = cfg_bind_token(Some("127.0.0.1:8080"), Some("tok-XYZ"));
        let a = authorizer_for(&c).expect("token present ⇒ ok");
        assert!(a.authorize(Some("tok-XYZ")), "correct token allowed");
        assert!(!a.authorize(Some("tok-xyz")), "wrong token denied");
        assert!(!a.authorize(None), "no token denied when policy is bearer");
    }

    #[test]
    fn authorizer_for_non_loopback_with_token_is_bearer_enforced() {
        let c = cfg_bind_token(Some("0.0.0.0:8080"), Some("net-secret"));
        let a = authorizer_for(&c).expect("non-loopback + token ⇒ ok");
        assert!(a.authorize(Some("net-secret")));
        assert!(!a.authorize(Some("net-secre")));
        assert!(
            !a.authorize(None),
            "public bind w/ bearer ⇒ no-token denied"
        );
    }

    // ───────── CWDL #197: blank secret is not auth ─────────

    #[test]
    fn authorizer_for_non_loopback_blank_token_fails_closed() {
        // A blank (empty / whitespace-only) auth_token on a public bind
        // is treated as NO token ⇒ security_check refusal — never a
        // silent AllowAll or an empty-bearer on an off-host socket.
        for blank in ["", "   ", "\t "] {
            let c = cfg_bind_token(Some("0.0.0.0:8080"), Some(blank));
            let r = authorizer_for(&c);
            assert!(
                matches!(r, Err(FleetConfigError::BadBind { .. })),
                "non-loopback + blank {blank:?} MUST refuse (got Ok ⇒ \
                 unauthenticated public socket)"
            );
        }
    }

    #[test]
    fn bearer_with_empty_or_blank_secret_authorizes_nothing() {
        // Consumer-side make-the-bad-state-unrepresentable: even if an
        // empty/blank-secret BearerToken were constructed by some path,
        // it denies EVERY request (fail-closed → 401), never an
        // empty-`Bearer ` bypass.
        for blank in ["", "   ", "\t"] {
            let bt = BearerToken::new(blank);
            assert!(!bt.authorize(None), "blank-secret bearer denies None");
            assert!(
                !bt.authorize(Some("")),
                "blank-secret bearer denies empty presented"
            );
            assert!(
                !bt.authorize(Some(blank)),
                "blank-secret bearer denies the blank itself"
            );
            assert!(
                !bt.authorize(Some("anything")),
                "blank-secret bearer denies any token"
            );
        }
        // A loopback bind with a blank token ⇒ no token ⇒ AllowAll
        // (unchanged #10 localhost posture; blank only ever downgrades
        // where security_check already permits open).
        let c = cfg_bind_token(Some("127.0.0.1:8080"), Some("  "));
        let a = authorizer_for(&c).expect("loopback blank ⇒ AllowAll, not Err");
        assert!(a.authorize(None), "loopback no-effective-token ⇒ AllowAll");
    }

    #[test]
    fn authorizer_for_no_bind_defaults_open_v0_compat() {
        // No daemon/network at all (v0 default) ⇒ AllowAll, no error.
        let c = FleetConfig::defaults();
        let a = authorizer_for(&c).expect("no bind ⇒ no auth required");
        assert!(a.authorize(None));
    }

    #[test]
    fn request_roundtrips_and_rejects_unknown_op() {
        for r in [
            Request::GetStatus("w1".into()),
            Request::GetVerdict("w2".into()),
            Request::GetDiagnostics("w3".into()),
            Request::ListWorktrees,
            Request::Subscribe,
        ] {
            assert_eq!(Request::from_json(&r.to_json()), Some(r.clone()), "{r:?}");
        }
        assert_eq!(Request::from_json(r#"{"op":"nope"}"#), None);
        assert_eq!(Request::from_json("not json"), None);
        assert_eq!(Request::from_json("{}"), None);
    }

    #[test]
    fn status_roundtrips_including_empty_crates_honesty_case() {
        // The #9/#11 sidecar invariant carried into the wire: empty
        // `crates` (untrustworthy / single-crate) must roundtrip as
        // empty — never silently become a bogus all-green list — and
        // `verdict` stands alone.
        let s = WorktreeStatus {
            worktree: "tf-mv-flat".into(),
            verdict: "red".into(),
            crates: vec![],
            red_diagnostics: 3,
            heartbeat_age_secs: 2,
            published_at: 1234567890,
        };
        assert_eq!(status_from_json(&status_to_json(&s)), Some(s));

        let s2 = WorktreeStatus {
            worktree: "tf-mv-check".into(),
            verdict: "red".into(),
            crates: vec![
                CrateVerdict {
                    name: "isolation".into(),
                    verdict: "green".into(),
                },
                CrateVerdict {
                    name: "physics".into(),
                    verdict: "red".into(),
                },
            ],
            red_diagnostics: 1,
            heartbeat_age_secs: 0,
            published_at: 42,
        };
        assert_eq!(status_from_json(&status_to_json(&s2)), Some(s2));
    }

    #[test]
    fn status_from_json_is_best_effort_never_panics() {
        assert_eq!(status_from_json(""), None);
        assert_eq!(status_from_json("garbage"), None);
        assert_eq!(status_from_json("{}"), None); // no worktree ⇒ None
        // Missing scalars default, never panic.
        let s = status_from_json(r#"{"worktree":"w"}"#).unwrap();
        assert_eq!(s.verdict, "unknown");
        assert_eq!(s.red_diagnostics, 0);
        assert!(s.crates.is_empty());
    }

    #[test]
    fn summaries_roundtrip_and_tolerate_malformed_elements() {
        let list = vec![
            WorktreeSummary {
                worktree: "a".into(),
                verdict: "green".into(),
                red_diagnostics: 0,
            },
            WorktreeSummary {
                worktree: "b".into(),
                verdict: "red".into(),
                red_diagnostics: 2,
            },
        ];
        assert_eq!(summaries_from_json(&summaries_to_json(&list)), list);
        // A malformed element (no worktree) is skipped, not fatal.
        assert_eq!(
            summaries_from_json(
                r#"[{"verdict":"green"},{"worktree":"ok","verdict":"red","red_diagnostics":1}]"#
            ),
            vec![WorktreeSummary {
                worktree: "ok".into(),
                verdict: "red".into(),
                red_diagnostics: 1
            }]
        );
    }

    #[test]
    fn allow_all_authorizes_with_or_without_token() {
        // #10 posture: open. #14 replaces this; the seam (not the
        // policy) is what #10 ships.
        assert!(AllowAll.authorize(None));
        assert!(AllowAll.authorize(Some("anything")));
    }
}