cellos-fleet 0.6.0-pre

S3-queue fleet dispatch agent for CellOS — pulls pending cell specs from S3, claims them, hands off to a local cellos-supervisor.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
//! cellos-fleet — host-resident agent that polls a spec queue and dispatches
//! execution cells to cellos-supervisor.
//!
//! # Library seam (S24)
//!
//! This crate exposes a thin library target alongside its binary so that the
//! configuration surface ([`Config`]) and node-identity surface
//! ([`NodeIdentity`]) can be exercised by integration tests and reused by
//! future control-plane tooling without shelling out to the binary. The
//! binary (`src/main.rs`) is a thin wrapper: it parses `--version`, installs
//! the tracing subscriber, builds a [`Config`] via [`Config::from_env`], and
//! drives [`run`]. No runtime behaviour changed when the seam was carved —
//! every item below was lifted verbatim from the original `main.rs`.
//!
//! # Queue model
//!
//! The agent treats an S3 prefix as a simple work queue using key renaming as
//! the claim primitive:
//!
//! ```text
//! pending/<spec-id>.json   →  claimed/<spec-id>.json  →  supervisor runs
//!                                                      →  completed/<spec-id>.json  (exit 0)
//!                                                      →  failed/<spec-id>.json     (exit ≠ 0)
//! ```
//!
//! Claiming is performed by `aws s3 mv` (copy + delete), which is not atomic
//! but is safe enough for low-concurrency single-agent deployments. A future
//! version can replace this with a DynamoDB conditional write for true
//! atomic claim.
//!
//! # Environment variables
//!
//! | Variable | Required | Description |
//! |----------|----------|-------------|
//! | `CELLOS_FLEET_BUCKET` | yes | S3 bucket name |
//! | `CELLOS_FLEET_PREFIX` | no | Key prefix inside bucket (default: `fleet`) |
//! | `CELLOS_FLEET_QUEUE_NAME` | no | Optional queue lane under the prefix |
//! | `CELLOS_FLEET_POOL_ID` | no | Runner pool identifier; T11 placement gate. When set, the dispatcher skips specs whose `spec.placement.poolId` is set AND does not equal this value. Specs without a `poolId` constraint are accepted everywhere. |
//! | `CELLOS_FLEET_SUPERVISOR` | no | Path to cellos-supervisor binary (default: `cellos-supervisor`) |
//! | `CELLOS_FLEET_POLL_INTERVAL_MS` | no | Poll interval in milliseconds (default: `5000`) |
//! | `CELLOS_FLEET_HEARTBEAT_INTERVAL_MS` | no | Heartbeat interval in milliseconds (default: `30000`) |
//! | `CELLOS_FLEET_NODE_ID` | no | Unique node identifier (default: hostname) |
//!
//! The agent inherits AWS credentials from the environment (IAM role, env vars,
//! or instance metadata) — it does not manage its own identity.
//!
//! # Drain / graceful shutdown
//!
//! On SIGTERM the poll loop stops accepting new work. Any in-flight cell
//! finishes normally before the process exits. A clean drain log line is
//! emitted so operators can distinguish graceful shutdown from a crash.

use anyhow::{Context, Result};
use std::path::PathBuf;
use std::time::Duration;
use tokio::process::Command;
use tokio::time::interval;
use tracing::{error, info, warn};

#[cfg(unix)]
use tokio::signal::unix::{signal, SignalKind};

/// Runtime configuration resolved from environment variables at startup.
#[derive(Debug)]
pub struct Config {
    pub bucket: String,
    pub prefix: String,
    /// Optional queue name for placement-aware routing.
    ///
    /// When set, all S3 key paths gain a `{queue_name}/` sub-prefix so that
    /// multiple fleet agents on different nodes can each service a distinct
    /// named lane of work without stepping on each other.
    ///
    /// Empty string means "default queue" — uses the legacy flat layout and is
    /// backwards-compatible with existing deployments that predate placement routing.
    pub queue_name: String,
    /// T11 — runner pool identifier. When non-empty, the dispatcher skips
    /// specs whose `spec.placement.poolId` is set and does not match this
    /// value. Empty string means "no pool constraint" — every spec accepted.
    ///
    /// Sourced from `CELLOS_FLEET_POOL_ID`.
    pub pool_id: String,
    pub supervisor: PathBuf,
    pub poll_interval: Duration,
    pub heartbeat_interval: Duration,
    pub node_id: String,
}

impl Config {
    pub fn from_env() -> Result<Self> {
        let bucket =
            std::env::var("CELLOS_FLEET_BUCKET").context("CELLOS_FLEET_BUCKET is required")?;
        let prefix = std::env::var("CELLOS_FLEET_PREFIX").unwrap_or_else(|_| "fleet".to_string());
        let queue_name = std::env::var("CELLOS_FLEET_QUEUE_NAME")
            .map(|value| value.trim().to_string())
            .unwrap_or_default();
        let pool_id = std::env::var("CELLOS_FLEET_POOL_ID")
            .map(|value| value.trim().to_string())
            .unwrap_or_default();
        let supervisor = PathBuf::from(
            std::env::var("CELLOS_FLEET_SUPERVISOR")
                .unwrap_or_else(|_| "cellos-supervisor".to_string()),
        );
        let poll_ms: u64 = std::env::var("CELLOS_FLEET_POLL_INTERVAL_MS")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(5000);
        let heartbeat_ms: u64 = std::env::var("CELLOS_FLEET_HEARTBEAT_INTERVAL_MS")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(30_000);
        let node_id = std::env::var("CELLOS_FLEET_NODE_ID").unwrap_or_else(|_| {
            hostname::get()
                .ok()
                .and_then(|h| h.into_string().ok())
                .unwrap_or_else(|| "unknown-node".to_string())
        });
        Ok(Config {
            bucket,
            prefix,
            queue_name,
            pool_id,
            supervisor,
            poll_interval: Duration::from_millis(poll_ms),
            heartbeat_interval: Duration::from_millis(heartbeat_ms),
            node_id,
        })
    }

    pub fn queue_prefix(&self) -> String {
        let base_prefix = self.prefix.trim_end_matches('/');
        if self.queue_name.is_empty() {
            base_prefix.to_string()
        } else {
            format!("{}/{}/", base_prefix, self.queue_name)
                .trim_end_matches('/')
                .to_string()
        }
    }

    pub fn pending_prefix(&self) -> String {
        format!("{}/pending/", self.queue_prefix())
    }

    pub fn claimed_key(&self, spec_id: &str) -> String {
        format!("{}/claimed/{}.json", self.queue_prefix(), spec_id)
    }

    pub fn completed_key(&self, spec_id: &str) -> String {
        format!("{}/completed/{}.json", self.queue_prefix(), spec_id)
    }

    pub fn failed_key(&self, spec_id: &str) -> String {
        format!("{}/failed/{}.json", self.queue_prefix(), spec_id)
    }

    /// T11 — placement gate.
    ///
    /// Returns `true` when this runner should dispatch the spec.
    ///
    /// - If the runner has no `pool_id` configured (env var unset / empty),
    ///   the spec is always accepted (legacy behaviour).
    /// - If the spec carries no `spec.placement.poolId`, it is accepted
    ///   everywhere (a spec without a pool constraint is portable).
    /// - Otherwise the spec is accepted only when the two values match
    ///   exactly. Mismatches return `false` and the dispatcher logs a
    ///   `skipping spec <id>: placement.poolId=<X> != runner poolId=<Y>`
    ///   line at the call site.
    pub fn should_dispatch(&self, spec_pool_id: Option<&str>) -> bool {
        if self.pool_id.is_empty() {
            return true;
        }
        match spec_pool_id {
            None => true,
            Some(spec_pool) => spec_pool == self.pool_id,
        }
    }
}

/// Stable identity a fleet node presents to a control plane.
///
/// S24 carved this as a forward-looking seam: today the fleet agent inherits
/// AWS credentials from the ambient environment and identifies itself only by
/// `node_id`. As accredited-deployment work lands (signed heartbeats, attested
/// runners), the control plane needs a typed handle for *who* a node claims to
/// be and *how* that claim is backed.
///
/// The struct is intentionally minimal and additive:
///
/// - `node_id` mirrors [`Config::node_id`] — the operator-visible name a node
///   answers to (hostname by default).
/// - `public_key_ref` is an opaque reference to the node's signing key (e.g. a
///   KMS key ARN or a key fingerprint). It is a *reference*, never key
///   material — the fleet agent does not hold private keys.
/// - `attestation` is a placeholder for a future hardware/software attestation
///   document. It defaults to `None`; no attestation path is wired today, so
///   the type parameter is the unit type until a concrete attestation shape is
///   chosen in a later track.
///
/// No runtime path constructs or consumes this type yet — it is a library
/// surface only, so the binary's behaviour is unchanged.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NodeIdentity {
    /// Operator-visible node name (matches [`Config::node_id`]).
    pub node_id: String,
    /// Opaque reference to the node's signing key (ARN / fingerprint / URI).
    /// Never the key material itself.
    pub public_key_ref: String,
    /// Future attestation document. `None` until an attestation path is wired.
    pub attestation: Option<()>,
}

impl NodeIdentity {
    /// Construct a `NodeIdentity` with no attestation (the only shape wired
    /// today). `attestation` defaults to `None`.
    pub fn new(node_id: impl Into<String>, public_key_ref: impl Into<String>) -> Self {
        NodeIdentity {
            node_id: node_id.into(),
            public_key_ref: public_key_ref.into(),
            attestation: None,
        }
    }
}

// ── S25: signed node attestation ────────────────────────────────────────────
//
// A fleet node proves *who it claims to be* to a control plane by emitting a
// signed CloudEvent carrying its `nodeId` + `publicKeyRef`. Today the only
// custody mode is key-possession (the node holds an Ed25519 signing seed behind
// a `Signer`), so the attestation is stamped `identityKind: "key-possession"`
// and `attestation: null` — an *explicit* marker that this node is NOT
// hardware-attested. The event is signed through the same per-event signing
// seam (`sign_event_with` over a `SoftwareSigner`, S32/ADR-0031) the rest of
// the fleet uses, so it verifies offline against the org-root
// `TrustAnchorPublicKey` only — no network, no PKI walk.
//
// Doctrine: this is identity *assertion*, not hardware *attestation*. The
// `attestation: null` field is load-bearing — a future hardware-attested node
// would carry a non-null attestation document and a different `identityKind`,
// and a verifier can branch on the marker without guessing.

/// CloudEvent `type` carried by a fleet node-attestation event (S25).
pub const NODE_ATTESTATION_EVENT_TYPE: &str = "dev.cellos.events.fleet.v1.node-attestation";

/// Identity-kind marker stamped into a key-possession attestation (S25).
///
/// "key-possession" means the node proved control of its signing key by
/// signing the attestation — it is explicitly NOT a hardware attestation.
pub const IDENTITY_KIND_KEY_POSSESSION: &str = "key-possession";

/// Build a signed node-attestation event for `identity` (S25).
///
/// Constructs a [`cellos_core::CloudEventV1`] of type
/// [`NODE_ATTESTATION_EVENT_TYPE`] whose `data` payload carries:
///
/// - `nodeId` — the node's operator-visible name ([`NodeIdentity::node_id`]),
/// - `publicKeyRef` — the opaque signing-key reference
///   ([`NodeIdentity::public_key_ref`]), never key material,
/// - `identityKind` — always [`IDENTITY_KIND_KEY_POSSESSION`] here, and
/// - `attestation` — an explicit JSON `null`, marking the node as NOT
///   hardware-attested.
///
/// The event is then signed through the per-event signing seam
/// ([`cellos_core::sign_event_with`]) using the supplied [`Signer`] (a
/// [`cellos_core::SoftwareSigner`] in the default key-possession custody mode).
/// The returned envelope verifies offline against the org-root verifying key.
///
/// `event_id` / `time` are caller-supplied so the function stays pure and
/// deterministic (no clock / RNG dependence) — the binary stamps a ULID + RFC
/// 3339 timestamp at the call site.
///
/// # Errors
///
/// Returns an error if the canonical signing payload cannot be produced or the
/// signer rejects the signing operation.
pub fn build_node_attestation(
    identity: &NodeIdentity,
    signer: &dyn cellos_core::Signer,
    event_id: impl Into<String>,
    source: impl Into<String>,
    time: Option<String>,
) -> Result<cellos_core::SignedEventEnvelopeV1, cellos_core::CellosError> {
    let event = cellos_core::CloudEventV1 {
        specversion: "1.0".to_string(),
        id: event_id.into(),
        source: source.into(),
        ty: NODE_ATTESTATION_EVENT_TYPE.to_string(),
        datacontenttype: Some("application/json".to_string()),
        data: Some(serde_json::json!({
            "nodeId": identity.node_id,
            "publicKeyRef": identity.public_key_ref,
            "identityKind": IDENTITY_KIND_KEY_POSSESSION,
            // Explicit null: this node is NOT hardware-attested. A future
            // hardware-attested node carries a non-null attestation document.
            "attestation": serde_json::Value::Null,
        })),
        time,
        traceparent: None,
        cex: None,
    };
    cellos_core::sign_event_with(signer, &event)
}

/// Verify a signed node-attestation envelope offline (S25).
///
/// Verifies the envelope's signature against `verifying_keys` (the org-root
/// keyring) via [`cellos_core::verify_signed_event_envelope`] — Ed25519 only,
/// so an empty HMAC keyring is passed — then re-asserts the structural
/// invariants of a node attestation:
///
/// - the event `type` is [`NODE_ATTESTATION_EVENT_TYPE`],
/// - the `data` payload carries an `identityKind` of
///   [`IDENTITY_KIND_KEY_POSSESSION`], and
/// - the `attestation` field is explicitly JSON `null` (NOT hardware-attested).
///
/// On success returns the asserted [`NodeIdentity`] reconstructed from the
/// signed payload. Any signature, type, or structural failure returns `Err` —
/// the verifier is fail-closed and never returns a partially-trusted identity.
///
/// # Errors
///
/// Returns an error when the signature does not verify under `verifying_keys`,
/// the event type is wrong, the payload is missing/malformed, the identity kind
/// is not key-possession, or the attestation marker is not explicit `null`.
pub fn verify_node_attestation(
    envelope: &cellos_core::SignedEventEnvelopeV1,
    verifying_keys: &std::collections::HashMap<String, cellos_core::crypto::TrustAnchorPublicKey>,
) -> Result<NodeIdentity, cellos_core::CellosError> {
    use cellos_core::CellosError;

    // 1. Cryptographic verification against the org-root keyring (Ed25519 only).
    let empty_hmac: std::collections::HashMap<String, Vec<u8>> = std::collections::HashMap::new();
    let event = cellos_core::verify_signed_event_envelope(envelope, verifying_keys, &empty_hmac)?;

    // 2. Re-assert the event type (defense in depth: the signature covers it,
    //    but a verifier asking "is this an attestation?" must not assume).
    if event.ty != NODE_ATTESTATION_EVENT_TYPE {
        return Err(CellosError::InvalidSpec(format!(
            "node attestation: expected event type {NODE_ATTESTATION_EVENT_TYPE}, got {:?}",
            event.ty
        )));
    }

    // 3. Re-assert the structural invariants of the signed payload.
    let data = event.data.as_ref().ok_or_else(|| {
        CellosError::InvalidSpec("node attestation: event has no data payload".into())
    })?;

    let identity_kind = data.get("identityKind").and_then(|v| v.as_str());
    if identity_kind != Some(IDENTITY_KIND_KEY_POSSESSION) {
        return Err(CellosError::InvalidSpec(format!(
            "node attestation: expected identityKind {IDENTITY_KIND_KEY_POSSESSION:?}, got {:?}",
            identity_kind
        )));
    }

    // The attestation marker MUST be present AND explicitly null — a missing
    // key is ambiguous, a non-null value would be a hardware attestation this
    // key-possession verifier does not understand.
    match data.get("attestation") {
        Some(serde_json::Value::Null) => {}
        other => {
            return Err(CellosError::InvalidSpec(format!(
                "node attestation: attestation must be explicit null (NOT hardware-attested), got {:?}",
                other
            )));
        }
    }

    let node_id = data.get("nodeId").and_then(|v| v.as_str()).ok_or_else(|| {
        CellosError::InvalidSpec("node attestation: missing/invalid nodeId".into())
    })?;
    let public_key_ref = data
        .get("publicKeyRef")
        .and_then(|v| v.as_str())
        .ok_or_else(|| {
            CellosError::InvalidSpec("node attestation: missing/invalid publicKeyRef".into())
        })?;

    Ok(NodeIdentity::new(node_id, public_key_ref))
}

// ── S26: advisory pre-claim ceiling-epoch floor ─────────────────────────────
//
// Defense-in-depth ONLY. The authoritative admission-ceiling control lives in
// the control plane / supervisor; this is an advisory pre-claim floor a fleet
// node reads from `CELLOS_FLEET_MIN_CEILING_EPOCH` so a node that has *locally*
// observed a stale ceiling epoch can refuse to claim work before it even
// reaches the authoritative gate. It is NOT a substitute for that gate — a
// node with no floor configured proceeds exactly as before.

/// Environment variable carrying the advisory minimum ceiling-epoch floor (S26).
pub const MIN_CEILING_EPOCH_ENV: &str = "CELLOS_FLEET_MIN_CEILING_EPOCH";

/// Outcome of the advisory pre-claim ceiling-epoch floor check (S26).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CeilingEpochDecision {
    /// No floor configured, or `observed >= floor`: the node may proceed to
    /// claim. The authoritative control still runs downstream.
    Admit,
    /// `observed < floor`: the node refuses to claim (advisory, fail-safe).
    /// Carries the stable reason code `ceiling_epoch_stale`.
    Refuse { reason: &'static str },
}

impl CeilingEpochDecision {
    /// `true` when the decision admits the work to the claim path.
    pub fn admits(&self) -> bool {
        matches!(self, CeilingEpochDecision::Admit)
    }
}

/// Reason code emitted when the advisory floor refuses a claim (S26).
pub const CEILING_EPOCH_STALE: &str = "ceiling_epoch_stale";

/// Pure advisory decision: does `observed_epoch` clear the `floor`? (S26)
///
/// - `floor == None` → [`CeilingEpochDecision::Admit`] (no floor configured;
///   legacy behaviour — the authoritative control is the only gate).
/// - `observed_epoch >= floor` → [`CeilingEpochDecision::Admit`].
/// - `observed_epoch < floor` → [`CeilingEpochDecision::Refuse`] with reason
///   [`CEILING_EPOCH_STALE`].
///
/// This is defense-in-depth: it can only ever *refuse* work a node was about to
/// claim, never *authorize* anything the authoritative ceiling control would
/// deny.
pub fn ceiling_epoch_admits(observed_epoch: u64, floor: Option<u64>) -> CeilingEpochDecision {
    match floor {
        None => CeilingEpochDecision::Admit,
        Some(floor) if observed_epoch >= floor => CeilingEpochDecision::Admit,
        Some(_) => CeilingEpochDecision::Refuse {
            reason: CEILING_EPOCH_STALE,
        },
    }
}

/// Read the advisory ceiling-epoch floor from [`MIN_CEILING_EPOCH_ENV`] (S26).
///
/// Returns `Ok(None)` when the variable is unset (no floor — proceed), `Ok(Some)`
/// when it parses as a `u64`, and `Err` when it is set but unparsable (fail-safe
/// for a misconfigured floor: a garbage value must not silently disable the
/// floor).
pub fn read_min_ceiling_epoch() -> Result<Option<u64>> {
    match std::env::var(MIN_CEILING_EPOCH_ENV) {
        Err(std::env::VarError::NotPresent) => Ok(None),
        Err(e) => Err(anyhow::anyhow!(
            "{MIN_CEILING_EPOCH_ENV} is not valid unicode: {e}"
        )),
        Ok(raw) => {
            let parsed = raw.trim().parse::<u64>().with_context(|| {
                format!("{MIN_CEILING_EPOCH_ENV}={raw:?} is not a valid u64 epoch")
            })?;
            Ok(Some(parsed))
        }
    }
}

// ── S29: profile-gated fail-open / fail-closed admission ─────────────────────
//
// `CELLOS_FLEET_PROFILE=hardened` flips the fleet node's posture when a
// pre-flight precondition cannot be satisfied — it cannot sign its attestation,
// it observed a stale ceiling epoch, or its audit sink is unreachable. Under
// the hardened profile any such failure fails CLOSED: the node refuses to
// dispatch. Under the default (non-hardened) profile the same failures fail
// OPEN with a *named* advisory so the gap is visible in logs rather than
// silent.

/// Environment variable selecting the fleet admission profile (S29).
pub const FLEET_PROFILE_ENV: &str = "CELLOS_FLEET_PROFILE";

/// Admission profile governing fail-open vs fail-closed behaviour (S29).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FleetProfile {
    /// Default posture: preconditions are best-effort; a failure fails OPEN
    /// with a named advisory.
    Default,
    /// Hardened posture: a precondition failure fails CLOSED (refuse dispatch).
    Hardened,
}

impl FleetProfile {
    /// Resolve the profile from `raw` (the `CELLOS_FLEET_PROFILE` value).
    /// `"hardened"` (case-insensitive, trimmed) selects [`FleetProfile::Hardened`];
    /// anything else — including unset — is [`FleetProfile::Default`].
    pub fn from_raw(raw: Option<&str>) -> Self {
        match raw.map(|s| s.trim().to_ascii_lowercase()) {
            Some(s) if s == "hardened" => FleetProfile::Hardened,
            _ => FleetProfile::Default,
        }
    }

    /// Resolve the profile from [`FLEET_PROFILE_ENV`].
    pub fn from_env() -> Self {
        Self::from_raw(std::env::var(FLEET_PROFILE_ENV).ok().as_deref())
    }

    /// `true` for the hardened (fail-closed) posture.
    pub fn is_hardened(&self) -> bool {
        matches!(self, FleetProfile::Hardened)
    }
}

/// The pre-flight preconditions a fleet node checks before dispatching (S29).
///
/// Each field is `true` when the precondition is SATISFIED. The decision
/// function [`profile_admits`] folds these against the active [`FleetProfile`].
#[derive(Debug, Clone, Copy)]
pub struct PreflightChecks {
    /// The node can sign its attestation (holds a usable signer).
    pub can_sign_attestation: bool,
    /// The locally observed ceiling epoch is not stale (cleared the S26 floor).
    pub ceiling_epoch_fresh: bool,
    /// The audit sink is reachable (signed events can be durably recorded).
    pub audit_sink_reachable: bool,
}

impl PreflightChecks {
    /// All preconditions satisfied.
    pub fn all_ok() -> Self {
        PreflightChecks {
            can_sign_attestation: true,
            ceiling_epoch_fresh: true,
            audit_sink_reachable: true,
        }
    }

    /// The stable reason codes for every UNSATISFIED precondition, in a fixed
    /// order. Empty when all preconditions hold.
    pub fn failure_reasons(&self) -> Vec<&'static str> {
        let mut reasons = Vec::new();
        if !self.can_sign_attestation {
            reasons.push("cannot_sign_attestation");
        }
        if !self.ceiling_epoch_fresh {
            reasons.push(CEILING_EPOCH_STALE);
        }
        if !self.audit_sink_reachable {
            reasons.push("audit_sink_unreachable");
        }
        reasons
    }
}

/// Outcome of the profile-gated admission decision (S29).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProfileAdmission {
    /// Dispatch may proceed. `advisories` is empty when every precondition
    /// holds, or carries the named reason codes that failed OPEN under the
    /// default profile (visible-but-permitted gaps).
    Admit { advisories: Vec<&'static str> },
    /// Dispatch is refused (hardened profile, a precondition failed CLOSED).
    /// `reasons` names every unsatisfied precondition.
    Refuse { reasons: Vec<&'static str> },
}

impl ProfileAdmission {
    /// `true` when dispatch may proceed.
    pub fn admits(&self) -> bool {
        matches!(self, ProfileAdmission::Admit { .. })
    }
}

/// Fold pre-flight preconditions against the active profile (S29).
///
/// - All preconditions satisfied → [`ProfileAdmission::Admit`] with no
///   advisories, regardless of profile.
/// - A precondition failed under [`FleetProfile::Hardened`] →
///   [`ProfileAdmission::Refuse`] naming every unsatisfied precondition
///   (fail CLOSED).
/// - A precondition failed under [`FleetProfile::Default`] →
///   [`ProfileAdmission::Admit`] carrying the failures as *named advisories*
///   (fail OPEN, but visibly — the gap is logged, not swallowed).
pub fn profile_admits(profile: FleetProfile, checks: &PreflightChecks) -> ProfileAdmission {
    let failures = checks.failure_reasons();
    if failures.is_empty() {
        return ProfileAdmission::Admit {
            advisories: Vec::new(),
        };
    }
    if profile.is_hardened() {
        ProfileAdmission::Refuse { reasons: failures }
    } else {
        ProfileAdmission::Admit {
            advisories: failures,
        }
    }
}

/// T11 — minimal spec view used by the placement gate.
///
/// We deserialize only the fields the gate needs so that fleet remains
/// resilient to other spec evolutions: a `pool_id` mismatch should be
/// detectable even if some other unrelated field rejects strict parsing.
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct FleetSpecView {
    #[serde(default)]
    spec: FleetSpecBody,
}

#[derive(Debug, Default, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct FleetSpecBody {
    #[serde(default)]
    placement: Option<FleetPlacementView>,
}

#[derive(Debug, Default, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct FleetPlacementView {
    #[serde(default)]
    pool_id: Option<String>,
}

/// Read `spec.placement.poolId` from a spec JSON file on disk. Returns
/// `Ok(None)` when the spec has no `placement` block or no `poolId` within
/// it. Returns `Err` if the file cannot be read or parsed.
pub fn read_spec_pool_id(spec_path: &std::path::Path) -> Result<Option<String>> {
    let bytes = std::fs::read(spec_path)
        .with_context(|| format!("read spec file {}", spec_path.display()))?;
    let view: FleetSpecView = serde_json::from_slice(&bytes)
        .with_context(|| format!("parse spec file {}", spec_path.display()))?;
    Ok(view.spec.placement.and_then(|p| p.pool_id))
}

/// List pending spec keys from the S3 queue prefix.
///
/// Uses `aws s3api list-objects-v2` so we don't depend on the S3 SDK crate.
/// Returns key names (not full URIs) for all `.json` objects under `pending/`.
pub async fn list_pending(cfg: &Config) -> Result<Vec<String>> {
    let output = Command::new("aws")
        .args([
            "s3api",
            "list-objects-v2",
            "--bucket",
            &cfg.bucket,
            "--prefix",
            &cfg.pending_prefix(),
            "--query",
            "Contents[?ends_with(Key, '.json')].Key",
            "--output",
            "json",
        ])
        .output()
        .await
        .context("aws s3api list-objects-v2 failed")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        warn!("list_pending stderr: {stderr}");
        return Ok(vec![]);
    }

    let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if stdout == "null" || stdout.is_empty() {
        return Ok(vec![]);
    }

    let keys: Vec<String> =
        serde_json::from_str(&stdout).context("failed to parse list-objects-v2 output")?;
    Ok(keys)
}

/// Attempt to claim a pending spec key by moving it to the claimed prefix.
///
/// Returns `true` if the claim succeeded (key moved); `false` if the key
/// was already claimed by another agent (race condition, non-fatal).
pub async fn try_claim(cfg: &Config, pending_key: &str) -> Result<bool> {
    // Extract spec-id from the key: pending/<spec-id>.json → <spec-id>
    let spec_id = pending_key
        .trim_start_matches(&cfg.pending_prefix())
        .trim_end_matches(".json");

    let src = format!("s3://{}/{}", cfg.bucket, pending_key);
    let dst = format!("s3://{}/{}", cfg.bucket, cfg.claimed_key(spec_id));

    let status = Command::new("aws")
        .args(["s3", "mv", &src, &dst])
        .status()
        .await
        .context("aws s3 mv (claim) failed")?;

    Ok(status.success())
}

/// Download the claimed spec to a local temp file and return its path.
pub async fn download_spec(cfg: &Config, spec_id: &str) -> Result<tempfile::NamedTempFile> {
    let tmp = tempfile::Builder::new()
        .prefix("cellos-fleet-spec-")
        .suffix(".json")
        .tempfile()
        .context("failed to create temp file for spec")?;

    let s3_key = format!("s3://{}/{}", cfg.bucket, cfg.claimed_key(spec_id));

    let status = Command::new("aws")
        .args(["s3", "cp", &s3_key, tmp.path().to_str().unwrap()])
        .status()
        .await
        .context("aws s3 cp (download spec) failed")?;

    anyhow::ensure!(status.success(), "aws s3 cp exited non-zero");
    Ok(tmp)
}

/// T11 — peek a pending spec without claiming it, so we can run the
/// placement gate before stealing the work from another pool's runner.
pub async fn peek_pending_spec(cfg: &Config, pending_key: &str) -> Result<tempfile::NamedTempFile> {
    let tmp = tempfile::Builder::new()
        .prefix("cellos-fleet-peek-")
        .suffix(".json")
        .tempfile()
        .context("failed to create temp file for peek")?;

    let s3_key = format!("s3://{}/{}", cfg.bucket, pending_key);

    let status = Command::new("aws")
        .args(["s3", "cp", &s3_key, tmp.path().to_str().unwrap()])
        .status()
        .await
        .context("aws s3 cp (peek pending spec) failed")?;

    anyhow::ensure!(status.success(), "aws s3 cp (peek) exited non-zero");
    Ok(tmp)
}

/// Run cellos-supervisor with the downloaded spec file.
///
/// Returns the exit code (0 = success, non-zero = cell failed or supervisor error).
pub async fn run_cell(cfg: &Config, spec_path: &std::path::Path) -> Result<i32> {
    let status = Command::new(&cfg.supervisor)
        .arg(spec_path)
        .status()
        .await
        .context("cellos-supervisor failed to launch")?;

    Ok(status.code().unwrap_or(1))
}

/// Move the claimed spec to completed/ or failed/ based on exit code.
pub async fn finalize(cfg: &Config, spec_id: &str, exit_code: i32) -> Result<()> {
    let src = format!("s3://{}/{}", cfg.bucket, cfg.claimed_key(spec_id));
    let dst = if exit_code == 0 {
        format!("s3://{}/{}", cfg.bucket, cfg.completed_key(spec_id))
    } else {
        format!("s3://{}/{}", cfg.bucket, cfg.failed_key(spec_id))
    };

    Command::new("aws")
        .args(["s3", "mv", &src, &dst])
        .status()
        .await
        .context("aws s3 mv (finalize) failed")?;

    Ok(())
}

/// Process one spec: (T11 placement peek →) claim → download → run → finalize.
pub async fn process_spec(cfg: &Config, pending_key: &str) -> Result<()> {
    let spec_id = pending_key
        .trim_start_matches(&cfg.pending_prefix())
        .trim_end_matches(".json");

    // T11 — placement gate: peek the spec's `placement.poolId` BEFORE we
    // attempt to claim. This way another runner whose pool matches gets a
    // fair shot at the work; we never steal a spec just to immediately
    // bounce it back. Runners with no `pool_id` configured skip the peek
    // entirely (every spec is in scope) and fall through to the legacy
    // claim path.
    if !cfg.pool_id.is_empty() {
        let peek_tmp = peek_pending_spec(cfg, pending_key).await?;
        let spec_pool = read_spec_pool_id(peek_tmp.path()).unwrap_or_else(|e| {
            warn!(spec_id, error = %e, "failed to read placement.poolId — treating as no constraint");
            None
        });
        if !cfg.should_dispatch(spec_pool.as_deref()) {
            info!(
                node = %cfg.node_id,
                spec_id,
                "skipping spec {}: placement.poolId={} != runner poolId={}",
                spec_id,
                spec_pool.as_deref().unwrap_or("<none>"),
                cfg.pool_id,
            );
            return Ok(());
        }
    }

    info!(node = %cfg.node_id, spec_id, "claiming spec");

    if !try_claim(cfg, pending_key).await? {
        info!(spec_id, "spec already claimed by another node, skipping");
        return Ok(());
    }

    info!(node = %cfg.node_id, spec_id, "claimed — downloading");
    let tmp = download_spec(cfg, spec_id).await?;

    info!(node = %cfg.node_id, spec_id, path = %tmp.path().display(), "running cell");
    let exit_code = run_cell(cfg, tmp.path()).await?;

    info!(node = %cfg.node_id, spec_id, exit_code, "cell completed — finalizing");
    finalize(cfg, spec_id, exit_code).await?;

    if exit_code == 0 {
        info!(node = %cfg.node_id, spec_id, "spec completed successfully");
    } else {
        warn!(node = %cfg.node_id, spec_id, exit_code, "spec completed with failure");
    }

    Ok(())
}

#[cfg(unix)]
async fn wait_for_shutdown_signal() -> Result<()> {
    let mut sigterm =
        signal(SignalKind::terminate()).context("failed to install SIGTERM handler")?;
    sigterm.recv().await;
    Ok(())
}

#[cfg(not(unix))]
async fn wait_for_shutdown_signal() -> Result<()> {
    tokio::signal::ctrl_c()
        .await
        .context("failed to install Ctrl+C handler")?;
    Ok(())
}

/// Main poll loop with heartbeat emission and SIGTERM drain.
///
/// The loop runs three concurrent timers via `tokio::select!`:
/// - **poll tick**: list pending specs and dispatch cells
/// - **heartbeat tick**: emit a structured `fleet.v1.heartbeat` event so
///   a control plane (or log aggregator) can track node liveness
/// - **SIGTERM**: stop accepting new work; current in-flight cell finishes
///   before the loop exits
pub async fn run(cfg: Config) -> Result<()> {
    info!(
        node = %cfg.node_id,
        bucket = %cfg.bucket,
        prefix = %cfg.prefix,
        queue_name = %cfg.queue_name,
        pool_id = %cfg.pool_id,
        supervisor = %cfg.supervisor.display(),
        poll_interval_ms = cfg.poll_interval.as_millis(),
        heartbeat_interval_ms = cfg.heartbeat_interval.as_millis(),
        "cellos-fleet agent starting"
    );

    let mut poll_tick = interval(cfg.poll_interval);
    let mut heartbeat_tick = interval(cfg.heartbeat_interval);
    let shutdown = wait_for_shutdown_signal();
    tokio::pin!(shutdown);

    // Fire immediately on first tick rather than waiting a full interval.
    poll_tick.tick().await;
    heartbeat_tick.tick().await;

    loop {
        tokio::select! {
            // Poll tick: check for pending specs and dispatch.
            _ = poll_tick.tick() => {
                match list_pending(&cfg).await {
                    Err(e) => error!("list_pending error: {e:#}"),
                    Ok(keys) if keys.is_empty() => {}
                    Ok(keys) => {
                        for key in &keys {
                            if let Err(e) = process_spec(&cfg, key).await {
                                error!(key, "process_spec error: {e:#}");
                            }
                        }
                    }
                }
            }

            // Heartbeat tick: emit liveness event.
            _ = heartbeat_tick.tick() => {
                info!(
                    event_type = "dev.cellos.events.fleet.v1.heartbeat",
                    node = %cfg.node_id,
                    bucket = %cfg.bucket,
                    prefix = %cfg.prefix,
                    queue_name = %cfg.queue_name,
                    pool_id = %cfg.pool_id,
                    "heartbeat"
                );
            }

            // SIGTERM: drain — finish no new work, let in-flight cells complete.
            _ = &mut shutdown => {
                info!(
                    node = %cfg.node_id,
                    "SIGTERM received — draining (no new work accepted)"
                );
                break;
            }
        }
    }

    info!(node = %cfg.node_id, "cellos-fleet agent stopped (drain complete)");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{Config, NodeIdentity};
    use std::path::PathBuf;
    use std::time::Duration;

    fn config(prefix: &str, queue_name: &str) -> Config {
        config_with_pool(prefix, queue_name, "")
    }

    fn config_with_pool(prefix: &str, queue_name: &str, pool_id: &str) -> Config {
        Config {
            bucket: "bucket".into(),
            prefix: prefix.into(),
            queue_name: queue_name.into(),
            pool_id: pool_id.into(),
            supervisor: PathBuf::from("cellos-supervisor"),
            poll_interval: Duration::from_secs(5),
            heartbeat_interval: Duration::from_secs(30),
            node_id: "node-a".into(),
        }
    }

    #[test]
    fn uses_legacy_layout_when_queue_name_is_empty() {
        let cfg = config("fleet", "");

        assert_eq!(cfg.pending_prefix(), "fleet/pending/");
        assert_eq!(cfg.claimed_key("spec-1"), "fleet/claimed/spec-1.json");
        assert_eq!(cfg.completed_key("spec-1"), "fleet/completed/spec-1.json");
        assert_eq!(cfg.failed_key("spec-1"), "fleet/failed/spec-1.json");
    }

    #[test]
    fn uses_queue_qualified_layout_when_queue_name_is_set() {
        let cfg = config("fleet", "gpu-runners");

        assert_eq!(cfg.pending_prefix(), "fleet/gpu-runners/pending/");
        assert_eq!(
            cfg.claimed_key("spec-1"),
            "fleet/gpu-runners/claimed/spec-1.json"
        );
        assert_eq!(
            cfg.completed_key("spec-1"),
            "fleet/gpu-runners/completed/spec-1.json"
        );
        assert_eq!(
            cfg.failed_key("spec-1"),
            "fleet/gpu-runners/failed/spec-1.json"
        );
    }

    #[test]
    fn trims_trailing_slash_from_prefix() {
        let cfg = config("fleet/", "gpu-runners");

        assert_eq!(cfg.pending_prefix(), "fleet/gpu-runners/pending/");
        assert_eq!(
            cfg.claimed_key("spec-1"),
            "fleet/gpu-runners/claimed/spec-1.json"
        );
    }

    // T11-2 — placement gate matrix. The dispatcher accepts a spec only
    // when the runner's pool constraint either is empty (legacy) or
    // matches the spec's `placement.poolId` exactly. Specs without a
    // `poolId` constraint are accepted everywhere — they are portable.
    #[test]
    fn dispatch_matrix_for_pool_id_placement_gate() {
        // Legacy runner (no pool_id configured): accepts everything.
        let unbounded = config_with_pool("fleet", "", "");
        assert!(
            unbounded.should_dispatch(None),
            "no-pool runner must accept specs without a poolId constraint"
        );
        assert!(
            unbounded.should_dispatch(Some("runner-pool-amd64")),
            "no-pool runner must accept specs with any poolId constraint"
        );

        // Bound runner: skips mismatches, accepts matches AND
        // accepts portable specs (placement.poolId not set).
        let amd64 = config_with_pool("fleet", "", "runner-pool-amd64");
        assert!(
            amd64.should_dispatch(None),
            "pool-bound runner must accept specs with no poolId constraint"
        );
        assert!(
            amd64.should_dispatch(Some("runner-pool-amd64")),
            "pool-bound runner must accept matching poolId"
        );
        assert!(
            !amd64.should_dispatch(Some("runner-pool-arm64")),
            "pool-bound runner must skip mismatching poolId"
        );
    }

    #[test]
    fn read_spec_pool_id_parses_placement_and_handles_absence() {
        use std::io::Write;

        // Spec WITH placement.poolId — should be Some.
        let mut with_pool = tempfile::NamedTempFile::new().unwrap();
        write!(
            with_pool,
            r#"{{
                "apiVersion": "cellos.io/v1",
                "kind": "ExecutionCell",
                "spec": {{
                    "id": "test",
                    "placement": {{ "poolId": "runner-pool-amd64" }}
                }}
            }}"#
        )
        .unwrap();
        let pool = super::read_spec_pool_id(with_pool.path()).unwrap();
        assert_eq!(pool.as_deref(), Some("runner-pool-amd64"));

        // Spec WITHOUT placement — should be None (portable).
        let mut without = tempfile::NamedTempFile::new().unwrap();
        write!(
            without,
            r#"{{
                "apiVersion": "cellos.io/v1",
                "kind": "ExecutionCell",
                "spec": {{ "id": "test" }}
            }}"#
        )
        .unwrap();
        assert_eq!(super::read_spec_pool_id(without.path()).unwrap(), None);
    }

    // S24 — NodeIdentity is an additive library seam. These tests pin the
    // documented shape: `attestation` defaults to `None`, the convenience
    // constructor mirrors the field order, and the struct is comparable.
    #[test]
    fn node_identity_new_defaults_attestation_to_none() {
        let id = NodeIdentity::new("node-a", "arn:aws:kms:us-east-1:0:key/abc");
        assert_eq!(id.node_id, "node-a");
        assert_eq!(id.public_key_ref, "arn:aws:kms:us-east-1:0:key/abc");
        assert_eq!(id.attestation, None);
    }

    #[test]
    fn node_identity_is_constructible_with_explicit_fields() {
        let id = NodeIdentity {
            node_id: "node-b".into(),
            public_key_ref: "fingerprint:deadbeef".into(),
            attestation: None,
        };
        assert_eq!(id, NodeIdentity::new("node-b", "fingerprint:deadbeef"));
    }

    // ── S25: signed node attestation ───────────────────────────────────────
    use super::{
        build_node_attestation, ceiling_epoch_admits, profile_admits, verify_node_attestation,
        CeilingEpochDecision, FleetProfile, PreflightChecks, ProfileAdmission,
        IDENTITY_KIND_KEY_POSSESSION, NODE_ATTESTATION_EVENT_TYPE,
    };
    use cellos_core::crypto::{dalek::public_key_from_seed, TrustAnchorPublicKey};
    use cellos_core::SoftwareSigner;
    use std::collections::HashMap;

    /// Org-root verifying-key map for a deterministic test seed.
    fn org_root_keys(kid: &str, seed: [u8; 32]) -> HashMap<String, TrustAnchorPublicKey> {
        let mut keys = HashMap::new();
        keys.insert(
            kid.to_string(),
            TrustAnchorPublicKey::from_bytes_unchecked(public_key_from_seed(&seed).unwrap()),
        );
        keys
    }

    #[test]
    fn node_attestation_verifies_offline_against_org_root_only() {
        // S25: a key-possession attestation signed by the node verifies offline
        // against the org-root TrustAnchorPublicKey only — no network, no HMAC.
        let seed = [9u8; 32];
        let kid = "org-root-2026";
        let signer = SoftwareSigner::from_seed(kid, seed).expect("signer");
        let identity = NodeIdentity::new("node-alpha", "arn:aws:kms:us-east-1:0:key/abc");

        let envelope = build_node_attestation(
            &identity,
            &signer,
            "ev-attest-1",
            "/cellos-fleet/node-alpha",
            Some("2026-06-25T00:00:00Z".into()),
        )
        .expect("build attestation");

        // The event carries the type and the key-possession marker.
        assert_eq!(envelope.event.ty, NODE_ATTESTATION_EVENT_TYPE);
        let data = envelope.event.data.as_ref().unwrap();
        assert_eq!(
            data.get("identityKind").and_then(|v| v.as_str()),
            Some(IDENTITY_KIND_KEY_POSSESSION)
        );
        // attestation is explicit null — NOT hardware-attested.
        assert!(data.get("attestation").unwrap().is_null());

        let keys = org_root_keys(kid, seed);
        let asserted = verify_node_attestation(&envelope, &keys).expect("verify offline");
        assert_eq!(asserted, identity);
    }

    #[test]
    fn node_attestation_tamper_fails_closed() {
        // S25: tampering with the signed event invalidates the signature.
        let seed = [9u8; 32];
        let kid = "org-root-2026";
        let signer = SoftwareSigner::from_seed(kid, seed).expect("signer");
        let identity = NodeIdentity::new("node-alpha", "ref-1");

        let mut envelope =
            build_node_attestation(&identity, &signer, "ev-1", "/src", None).expect("build");
        // Tamper: swap the asserted nodeId in the signed payload.
        envelope.event.data = Some(serde_json::json!({
            "nodeId": "node-impostor",
            "publicKeyRef": "ref-1",
            "identityKind": IDENTITY_KIND_KEY_POSSESSION,
            "attestation": serde_json::Value::Null,
        }));

        let keys = org_root_keys(kid, seed);
        let err = verify_node_attestation(&envelope, &keys)
            .expect_err("tampered attestation must fail verify");
        assert!(
            format!("{err}").contains("ed25519 verify failed"),
            "expected signature failure, got: {err}"
        );
    }

    #[test]
    fn node_attestation_wrong_org_root_fails() {
        // S25: a verifier holding a different org-root key cannot verify.
        let signer = SoftwareSigner::from_seed("org-root-2026", [9u8; 32]).expect("signer");
        let identity = NodeIdentity::new("node-alpha", "ref-1");
        let envelope =
            build_node_attestation(&identity, &signer, "ev-1", "/src", None).expect("build");

        // Verifier knows the kid but with the WRONG public key.
        let wrong_keys = org_root_keys("org-root-2026", [1u8; 32]);
        let err = verify_node_attestation(&envelope, &wrong_keys)
            .expect_err("wrong org-root key must fail");
        assert!(format!("{err}").contains("ed25519 verify failed"));
    }

    // ── S26: advisory pre-claim ceiling-epoch floor ────────────────────────
    #[test]
    fn ceiling_epoch_floor_refuses_when_observed_below_floor() {
        // floor 5 + epoch 4 -> refuse (stale).
        let decision = ceiling_epoch_admits(4, Some(5));
        assert_eq!(
            decision,
            CeilingEpochDecision::Refuse {
                reason: super::CEILING_EPOCH_STALE
            }
        );
        assert!(!decision.admits());

        // 5 + 5 (at the floor) -> proceeds.
        assert!(ceiling_epoch_admits(5, Some(5)).admits());
        // 5 + 6 (above the floor) -> proceeds.
        assert!(ceiling_epoch_admits(6, Some(5)).admits());

        // No floor configured -> proceeds regardless of observed epoch.
        assert!(ceiling_epoch_admits(0, None).admits());
        assert!(ceiling_epoch_admits(u64::MAX, None).admits());
    }

    // ── S29: profile-gated fail-open / fail-closed admission ────────────────
    #[test]
    fn profile_from_raw_only_hardened_selects_hardened() {
        assert_eq!(
            FleetProfile::from_raw(Some("hardened")),
            FleetProfile::Hardened
        );
        assert_eq!(
            FleetProfile::from_raw(Some(" Hardened ")),
            FleetProfile::Hardened
        );
        assert_eq!(
            FleetProfile::from_raw(Some("HARDENED")),
            FleetProfile::Hardened
        );
        assert_eq!(
            FleetProfile::from_raw(Some("default")),
            FleetProfile::Default
        );
        assert_eq!(FleetProfile::from_raw(Some("")), FleetProfile::Default);
        assert_eq!(FleetProfile::from_raw(None), FleetProfile::Default);
    }

    #[test]
    fn profile_admits_all_ok_regardless_of_profile() {
        let ok = PreflightChecks::all_ok();
        assert_eq!(
            profile_admits(FleetProfile::Hardened, &ok),
            ProfileAdmission::Admit { advisories: vec![] }
        );
        assert_eq!(
            profile_admits(FleetProfile::Default, &ok),
            ProfileAdmission::Admit { advisories: vec![] }
        );
    }

    #[test]
    fn hardened_fails_closed_on_each_precondition() {
        // Cannot sign attestation -> refuse closed under hardened.
        let cannot_sign = PreflightChecks {
            can_sign_attestation: false,
            ..PreflightChecks::all_ok()
        };
        let d = profile_admits(FleetProfile::Hardened, &cannot_sign);
        assert!(!d.admits());
        assert_eq!(
            d,
            ProfileAdmission::Refuse {
                reasons: vec!["cannot_sign_attestation"]
            }
        );

        // Stale ceiling epoch -> refuse closed.
        let stale = PreflightChecks {
            ceiling_epoch_fresh: false,
            ..PreflightChecks::all_ok()
        };
        assert_eq!(
            profile_admits(FleetProfile::Hardened, &stale),
            ProfileAdmission::Refuse {
                reasons: vec![super::CEILING_EPOCH_STALE]
            }
        );

        // Audit sink unreachable -> refuse closed.
        let sink_down = PreflightChecks {
            audit_sink_reachable: false,
            ..PreflightChecks::all_ok()
        };
        assert_eq!(
            profile_admits(FleetProfile::Hardened, &sink_down),
            ProfileAdmission::Refuse {
                reasons: vec!["audit_sink_unreachable"]
            }
        );
    }

    #[test]
    fn default_profile_fails_open_with_named_advisory() {
        // Default profile: same failures admit, but carry named advisories.
        let cannot_sign = PreflightChecks {
            can_sign_attestation: false,
            ..PreflightChecks::all_ok()
        };
        let d = profile_admits(FleetProfile::Default, &cannot_sign);
        assert!(d.admits());
        assert_eq!(
            d,
            ProfileAdmission::Admit {
                advisories: vec!["cannot_sign_attestation"]
            }
        );

        // Multiple failures: all named, in fixed order.
        let multi = PreflightChecks {
            can_sign_attestation: false,
            ceiling_epoch_fresh: false,
            audit_sink_reachable: false,
        };
        assert_eq!(
            profile_admits(FleetProfile::Default, &multi),
            ProfileAdmission::Admit {
                advisories: vec![
                    "cannot_sign_attestation",
                    super::CEILING_EPOCH_STALE,
                    "audit_sink_unreachable"
                ]
            }
        );
    }
}