eidetic-engine 0.15.2

Durable, local-first, explainable memory for coding agents.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
//! SRR6.46.7 — Per-peer discovery policy (privacy).
//!
//! Three discovery modes select who SRR6.46.2 autodiscovery probes
//! (`discoveryMode`) and who the SRR6.46.12 hello responder admits
//! (`respondMode`):
//!
//! - `service_tag` (default): only peers advertising the `tag:ee-mesh`
//!   Tailscale ACL tag are probed; the responder only admits peers we
//!   also advertise the tag to. Privacy-by-default — peers on the same
//!   tailnet who haven't opted in to ee discovery never receive (or
//!   respond to) a hello probe.
//! - `auto_admit`: probe every reachable peer; respond to anyone. Simple
//!   but leaks "ee is here" to every tailnet host. Suitable for trusted
//!   corporate tailnets.
//! - `allowlist`: probe only peers whose `nodeKey` appears in
//!   `.ee/discovery_allowlist.toml`; respond only to peers whose
//!   `nodeKey` appears in `.ee/respond_allowlist.toml`.
//!
//! A workspace-scoped denylist (`.ee/discovery_denylist.toml`) overrides
//! all three modes — denylisted peers are never probed and never
//! receive a response.
//!
//! This module owns the **pure decision logic**, the TOML
//! allowlist/denylist file loaders, and the env-var reader for
//! `EE_TAILSCALE_DISCOVERY_MODE` / `EE_TAILSCALE_RESPOND_MODE`
//! (registered in `src/config/env_registry.rs`). The CLI surface
//! (`ee mesh discovery-policy [set|allow|deny|--explain]`) consumes
//! these pure helpers and keeps file writes/audit emission in the CLI
//! layer.
//!
//! The SRR6.46.6 hello-handshake responder integration and the
//! SRR6.46.2 autodiscovery integration both consume this module's
//! `decide_discovery` / `decide_respond` functions; their wiring lands
//! in those beads.

use std::collections::BTreeSet;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::{fs, io};

use serde::{Deserialize, Serialize};

use crate::config::env_registry::{self, EnvVar};

/// JSON schema identifier for the `ee mesh discovery-policy --json`
/// surface. Held here as the source-of-truth constant so the renderer
/// and the schema-lifecycle drift gate agree.
pub const DISCOVERY_POLICY_SCHEMA_V1: &str = "ee.mesh.discovery_policy.v1";

/// The well-known Tailscale ACL tag opt-in marker. A peer advertises
/// `tag:ee-mesh` via `tailscale up --advertise-tags=tag:ee-mesh` to
/// signal that it is an ee participant willing to be discovered.
pub const EE_MESH_SERVICE_TAG: &str = "tag:ee-mesh";

/// Cap on the byte size of an operator-supplied node-key allowlist or
/// denylist TOML file before refusing to read it.
///
/// Node-key list files carry trimmed hex-style Tailscale nodeKey strings
/// (~70 bytes each plus TOML scaffolding); even a 10,000-entry list
/// stays well under 1 MiB. The cap bounds the allocation an operator
/// accidentally aiming the discovery-policy reader at a log file or
/// adversarial archive can demand. bd-3gmzf / bd-1icct multi-pass-bug-
/// hunting follow-up (mirrors the MESH_CONFIG_MAX_BYTES cap in 5b725c82
/// and the 8 MiB AGENT_MAIL_SNAPSHOT_MAX_BYTES precedent in bd-1sdr5).
pub const NODE_KEY_LIST_MAX_BYTES: usize = 1024 * 1024;

/// Degraded code emitted when `respondMode=service_tag` is set but the
/// host does not advertise `tag:ee-mesh`. Nobody on the tailnet will be
/// able to discover us; the user almost certainly didn't mean this.
pub const DISCOVERY_POLICY_NO_EE_MESH_TAG_CODE: &str = "discovery_policy_no_ee_mesh_tag";

/// Degraded code emitted when the caller is in `allowlist` mode but
/// the allowlist file is empty. Nothing will be probed.
pub const DISCOVERY_POLICY_EMPTY_ALLOWLIST_CODE: &str = "discovery_policy_empty_allowlist";

/// Default file name for the workspace allowlist (`<workspace>/.ee/discovery_allowlist.toml`).
pub const DISCOVERY_ALLOWLIST_FILE: &str = "discovery_allowlist.toml";

/// Default file name for the workspace denylist (`<workspace>/.ee/discovery_denylist.toml`).
pub const DISCOVERY_DENYLIST_FILE: &str = "discovery_denylist.toml";

/// Default file name for the responder-side allowlist (`<workspace>/.ee/respond_allowlist.toml`).
pub const RESPOND_ALLOWLIST_FILE: &str = "respond_allowlist.toml";

const NODE_KEY_PREFIX: &str = "nodekey:";
const NODE_KEY_HEX_LEN: usize = 64;

/// The three discovery modes that gate both probing (caller side) and
/// admission (responder side). The same enum is reused for both surfaces
/// so the discovery-policy schema is symmetric.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DiscoveryMode {
    /// Privacy-by-default: only peers advertising `tag:ee-mesh` are
    /// admitted. Recommended for shared / personal tailnets where ee
    /// participation should be opt-in per host.
    ServiceTag,
    /// Trusted-tailnet mode: probe every reachable peer; respond to
    /// anyone. Simpler but leaks "ee is here" to every tailnet member.
    AutoAdmit,
    /// Most restrictive: explicit allowlist of nodeKeys.
    Allowlist,
}

impl DiscoveryMode {
    /// Canonical schema representation (matches the `discoveryMode` /
    /// `respondMode` enum values in `ee.mesh.discovery_policy.v1`).
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::ServiceTag => "service_tag",
            Self::AutoAdmit => "auto_admit",
            Self::Allowlist => "allowlist",
        }
    }

    /// Default discovery mode: privacy-by-default `service_tag`.
    #[must_use]
    pub const fn default_mode() -> Self {
        Self::ServiceTag
    }

    /// Read [`EnvVar::TailscaleDiscoveryMode`] and parse it through
    /// [`FromStr`]. Returns the registry-defined default (`service_tag`)
    /// when the variable is unset or carries an unknown value. The
    /// `unknown_value` callback receives the raw string for
    /// degraded-code reporting; pass a no-op closure when only the mode
    /// matters.
    #[must_use]
    pub fn from_env_discovery<F>(on_unknown: F) -> Self
    where
        F: FnOnce(&str),
    {
        Self::from_env_var(EnvVar::TailscaleDiscoveryMode, on_unknown)
    }

    /// Symmetric reader for [`EnvVar::TailscaleRespondMode`].
    #[must_use]
    pub fn from_env_respond<F>(on_unknown: F) -> Self
    where
        F: FnOnce(&str),
    {
        Self::from_env_var(EnvVar::TailscaleRespondMode, on_unknown)
    }

    fn from_env_var<F>(var: EnvVar, on_unknown: F) -> Self
    where
        F: FnOnce(&str),
    {
        Self::from_raw_with_default(env_registry::read(var).as_deref(), on_unknown)
    }

    /// Pure helper: given an already-read raw value (or `None`), return
    /// the resolved mode, invoking `on_unknown` if the value is set but
    /// unparseable. Kept private; exposed only to unit tests so the env
    /// wrapper has a deterministic, env-free verification path.
    #[must_use]
    pub(crate) fn from_raw_with_default<F>(raw: Option<&str>, on_unknown: F) -> Self
    where
        F: FnOnce(&str),
    {
        let Some(raw) = raw else {
            return Self::default_mode();
        };
        match Self::from_str(raw) {
            Ok(mode) => mode,
            Err(_) => {
                on_unknown(raw);
                Self::default_mode()
            }
        }
    }
}

/// Error returned by [`DiscoveryMode::from_str`] when the raw token
/// does not match one of the three canonical lowercase modes.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseDiscoveryModeError {
    pub raw: String,
}

impl std::fmt::Display for ParseDiscoveryModeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "unknown discovery mode {:?}; expected one of service_tag, auto_admit, allowlist",
            self.raw
        )
    }
}

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

impl FromStr for DiscoveryMode {
    type Err = ParseDiscoveryModeError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value.trim() {
            "service_tag" => Ok(Self::ServiceTag),
            "auto_admit" => Ok(Self::AutoAdmit),
            "allowlist" => Ok(Self::Allowlist),
            other => Err(ParseDiscoveryModeError {
                raw: other.to_owned(),
            }),
        }
    }
}

impl Default for DiscoveryMode {
    fn default() -> Self {
        Self::default_mode()
    }
}

/// The decision SRR6.46.2 reaches on a per-peer basis when deciding
/// whether to issue a hello probe.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DiscoveryDecision {
    Probe,
    Skip,
}

impl DiscoveryDecision {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Probe => "probe",
            Self::Skip => "skip",
        }
    }
}

/// The decision SRR6.46.12 hello responder reaches on a per-incoming-request
/// basis. The decline path uses `DiscoveryConsent::Denied` so the hello
/// error response in SRR6.46.6 returns `discovery_consent_denied` with
/// no metadata leak.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DiscoveryConsent {
    Granted,
    Denied,
}

impl DiscoveryConsent {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Granted => "granted",
            Self::Denied => "denied",
        }
    }
}

/// Reason code attached to a [`DiscoveryDecision`] for forensic logging
/// and the `--explain` decision tree.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DiscoveryReason {
    /// `auto_admit` mode + peer not denylisted.
    AutoAdmit,
    /// `service_tag` mode + peer advertises `tag:ee-mesh` + not denylisted.
    ServiceTagMatch,
    /// `allowlist` mode + peer in `discovery_allowlist.toml` + not denylisted.
    Allowlisted,
    /// `service_tag` mode + peer does not advertise the tag.
    SkipNoTag,
    /// `allowlist` mode + peer not in `discovery_allowlist.toml`.
    SkipNotAllowlisted,
    /// Peer appears in `discovery_denylist.toml`. Takes priority over
    /// `auto_admit` / `service_tag` / `allowlist`.
    SkipDenylisted,
    /// Peer's nodeKey matches the caller's `selfNodeKey`. We never
    /// probe ourselves; this is a defensive guard.
    SkipSelf,
}

impl DiscoveryReason {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::AutoAdmit => "auto_admit",
            Self::ServiceTagMatch => "service_tag_match",
            Self::Allowlisted => "allowlisted",
            Self::SkipNoTag => "skip_no_tag",
            Self::SkipNotAllowlisted => "skip_not_allowlisted",
            Self::SkipDenylisted => "skip_denylisted",
            Self::SkipSelf => "skip_self",
        }
    }

    /// SRR6.46.2 `eeCapablePeers[].discoveryPolicyDecision` value.
    /// Returns `None` for skip reasons because skipped peers use the
    /// separate `skippedPeers[].reason` vocabulary.
    #[must_use]
    pub fn autodiscovery_policy_decision(self) -> Option<&'static str> {
        match self {
            Self::AutoAdmit => Some("auto_admit"),
            Self::ServiceTagMatch => Some("service_tag_match"),
            Self::Allowlisted => Some("allowlisted"),
            Self::SkipNoTag | Self::SkipNotAllowlisted | Self::SkipDenylisted | Self::SkipSelf => {
                None
            }
        }
    }

    /// SRR6.46.2 `skippedPeers[].reason` value for caller-side policy
    /// skips. Returns `None` for probe reasons because eligible peers
    /// carry `discoveryPolicyDecision` instead.
    #[must_use]
    pub fn autodiscovery_skip_reason(self) -> Option<&'static str> {
        match self {
            Self::AutoAdmit | Self::ServiceTagMatch | Self::Allowlisted => None,
            Self::SkipNoTag | Self::SkipNotAllowlisted => Some("no_discovery_consent"),
            Self::SkipDenylisted | Self::SkipSelf => Some("denied_by_policy"),
        }
    }
}

/// Caller-side inputs for [`decide_discovery`]. Borrowed-only so the
/// decision function is a pure read with no allocations beyond the
/// returned enum.
#[derive(Clone, Copy, Debug)]
pub struct DiscoveryDecisionInput<'a> {
    pub mode: DiscoveryMode,
    pub peer_node_key: &'a str,
    pub peer_advertised_tags: &'a [String],
    pub self_node_key: &'a str,
    pub allowlist: &'a BTreeSet<String>,
    pub denylist: &'a BTreeSet<String>,
}

/// Responder-side inputs for [`decide_respond`]. Mirrors
/// [`DiscoveryDecisionInput`] but flipped — `requester_*` is the peer
/// that just sent us a hello.
#[derive(Clone, Copy, Debug)]
pub struct RespondDecisionInput<'a> {
    pub mode: DiscoveryMode,
    pub requester_node_key: &'a str,
    pub requester_advertised_tags: &'a [String],
    pub self_advertised_tags: &'a [String],
    pub respond_allowlist: &'a BTreeSet<String>,
    pub denylist: &'a BTreeSet<String>,
}

/// Caller-side decision for whether to probe a peer.
///
/// Evaluation order (first-match wins):
///
/// 1. `peer_node_key == self_node_key` → `SkipSelf`. Never probe self.
/// 2. Peer in denylist → `SkipDenylisted`. Denylist overrides modes.
/// 3. `mode == AutoAdmit` → `Probe` with `AutoAdmit` reason.
/// 4. `mode == ServiceTag` + peer advertises `EE_MESH_SERVICE_TAG` →
///    `Probe` with `ServiceTagMatch`.
/// 5. `mode == ServiceTag` + peer does not advertise the tag →
///    `Skip` with `SkipNoTag`.
/// 6. `mode == Allowlist` + peer in allowlist → `Probe` with `Allowlisted`.
/// 7. `mode == Allowlist` + peer not in allowlist → `Skip` with
///    `SkipNotAllowlisted`.
#[must_use]
pub fn decide_discovery(
    input: &DiscoveryDecisionInput<'_>,
) -> (DiscoveryDecision, DiscoveryReason) {
    if input.peer_node_key == input.self_node_key {
        return (DiscoveryDecision::Skip, DiscoveryReason::SkipSelf);
    }
    if input.denylist.contains(input.peer_node_key) {
        return (DiscoveryDecision::Skip, DiscoveryReason::SkipDenylisted);
    }
    match input.mode {
        DiscoveryMode::AutoAdmit => (DiscoveryDecision::Probe, DiscoveryReason::AutoAdmit),
        DiscoveryMode::ServiceTag => {
            if input
                .peer_advertised_tags
                .iter()
                .any(|tag| tag == EE_MESH_SERVICE_TAG)
            {
                (DiscoveryDecision::Probe, DiscoveryReason::ServiceTagMatch)
            } else {
                (DiscoveryDecision::Skip, DiscoveryReason::SkipNoTag)
            }
        }
        DiscoveryMode::Allowlist => {
            if input.allowlist.contains(input.peer_node_key) {
                (DiscoveryDecision::Probe, DiscoveryReason::Allowlisted)
            } else {
                (DiscoveryDecision::Skip, DiscoveryReason::SkipNotAllowlisted)
            }
        }
    }
}

/// Responder-side decision for whether to admit a hello request.
///
/// Evaluation order (first-match wins):
///
/// 1. Requester in denylist → `Denied` with `SkipDenylisted`.
/// 2. `mode == AutoAdmit` → `Granted` with `AutoAdmit`. Respond to anyone.
/// 3. `mode == ServiceTag` + WE advertise `EE_MESH_SERVICE_TAG` →
///    `Granted` with `ServiceTagMatch`. The peer's tags are not
///    consulted on the responder side because the responder's own tag
///    advertisement is what signals opt-in.
/// 4. `mode == ServiceTag` + WE do not advertise the tag → `Denied`
///    with `SkipNoTag`. We told the tailnet we don't participate in
///    ee discovery, so we honor that on the response side.
/// 5. `mode == Allowlist` + requester in respond-allowlist → `Granted`
///    with `Allowlisted`.
/// 6. `mode == Allowlist` + requester not in respond-allowlist →
///    `Denied` with `SkipNotAllowlisted`.
#[must_use]
pub fn decide_respond(input: &RespondDecisionInput<'_>) -> (DiscoveryConsent, DiscoveryReason) {
    if input.denylist.contains(input.requester_node_key) {
        return (DiscoveryConsent::Denied, DiscoveryReason::SkipDenylisted);
    }
    let _ = input.requester_advertised_tags; // caller-side filter only
    match input.mode {
        DiscoveryMode::AutoAdmit => (DiscoveryConsent::Granted, DiscoveryReason::AutoAdmit),
        DiscoveryMode::ServiceTag => {
            if input
                .self_advertised_tags
                .iter()
                .any(|tag| tag == EE_MESH_SERVICE_TAG)
            {
                (DiscoveryConsent::Granted, DiscoveryReason::ServiceTagMatch)
            } else {
                (DiscoveryConsent::Denied, DiscoveryReason::SkipNoTag)
            }
        }
        DiscoveryMode::Allowlist => {
            if input.respond_allowlist.contains(input.requester_node_key) {
                (DiscoveryConsent::Granted, DiscoveryReason::Allowlisted)
            } else {
                (
                    DiscoveryConsent::Denied,
                    DiscoveryReason::SkipNotAllowlisted,
                )
            }
        }
    }
}

/// Error variants for [`load_node_key_list`].
#[derive(Debug)]
pub enum LoadListError {
    Read(std::io::Error),
    Parse(toml_edit::TomlError),
    InvalidShape(String),
}

impl std::fmt::Display for LoadListError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Read(error) => write!(f, "failed to read discovery list file: {error}"),
            Self::Parse(error) => write!(f, "failed to parse discovery list TOML: {error}"),
            Self::InvalidShape(detail) => {
                write!(f, "invalid discovery list shape: {detail}")
            }
        }
    }
}

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

/// Load a node-key list TOML file. Absent file → empty set (this is the
/// expected state for fresh workspaces; `service_tag` and `auto_admit`
/// modes work without any list file present).
///
/// Expected file shape:
///
/// ```toml
/// node_keys = [
///   "nodekey:0000000000000000000000000000000000000000000000000000000000000001",
///   "nodekey:0000000000000000000000000000000000000000000000000000000000000002",
/// ]
/// ```
///
/// Trims whitespace from each entry and skips empty entries; preserves
/// case (node-keys are case-sensitive). Duplicates are deduplicated via
/// the `BTreeSet` contract. Unknown top-level keys are silently ignored
/// for forward-compat; only `node_keys = [...]` is required.
pub fn load_node_key_list(path: &Path) -> Result<BTreeSet<String>, LoadListError> {
    if !node_key_list_path_is_regular(path)? {
        return Ok(BTreeSet::new());
    }
    let body = match read_node_key_list_bounded(path) {
        Ok(body) => body,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(BTreeSet::new()),
        Err(error) => return Err(LoadListError::Read(error)),
    };
    let document = body
        .parse::<toml_edit::DocumentMut>()
        .map_err(LoadListError::Parse)?;
    let Some(node_keys_item) = document.get("node_keys") else {
        // Missing field treated as empty list — symmetric with the
        // absent-file case. Lets a fresh workspace ship a file with
        // only a header comment and no entries yet.
        return Ok(BTreeSet::new());
    };
    let Some(array) = node_keys_item.as_array() else {
        return Err(LoadListError::InvalidShape(
            "expected `node_keys` to be a TOML array of strings".to_owned(),
        ));
    };
    let mut out = BTreeSet::new();
    for (index, value) in array.iter().enumerate() {
        let Some(s) = value.as_str() else {
            return Err(LoadListError::InvalidShape(format!(
                "expected `node_keys[{index}]` to be a string, got `{value:?}`",
            )));
        };
        let trimmed = s.trim();
        if !trimmed.is_empty() {
            validate_node_key_list_entry(index, trimmed)?;
            out.insert(trimmed.to_owned());
        }
    }
    Ok(out)
}

/// Validate one Tailscale node key using the discovery-list contract.
///
/// Public so CLI mutation surfaces can reject invalid `allow` / `deny`
/// arguments before writing `.ee/*_allowlist.toml` or
/// `.ee/*_denylist.toml`.
pub fn validate_node_key(value: &str) -> Result<(), LoadListError> {
    validate_node_key_list_entry(0, value)
}

fn validate_node_key_list_entry(index: usize, value: &str) -> Result<(), LoadListError> {
    if is_valid_node_key(value) {
        return Ok(());
    }
    Err(LoadListError::InvalidShape(format!(
        "expected `node_keys[{index}]` to be a Tailscale node key formatted as `{NODE_KEY_PREFIX}` plus {NODE_KEY_HEX_LEN} lowercase hex characters",
    )))
}

fn is_valid_node_key(value: &str) -> bool {
    let Some(body) = value.strip_prefix(NODE_KEY_PREFIX) else {
        return false;
    };
    body.len() == NODE_KEY_HEX_LEN
        && body
            .bytes()
            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
}

/// Read `path` into a string while refusing payloads above
/// [`NODE_KEY_LIST_MAX_BYTES`]. Uses `File::open + Read::take(cap+1) +
/// read_to_end`; an over-cap read returns `io::ErrorKind::InvalidData`
/// naming the cap, which the caller folds into `LoadListError::Read`.
/// Mirrors the bounded-read pattern in
/// `src/cli/mesh.rs::read_mesh_text_bounded` (bd-3l1cy, 5b725c82).
/// bd-3gmzf.
fn read_node_key_list_bounded(path: &Path) -> io::Result<String> {
    let read_limit = NODE_KEY_LIST_MAX_BYTES.checked_add(1).ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            "node-key list read cap overflowed usize",
        )
    })?;
    let file = fs::File::open(path)?;
    let mut bytes = Vec::new();
    file.take(read_limit as u64).read_to_end(&mut bytes)?;
    if bytes.len() > NODE_KEY_LIST_MAX_BYTES {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "Discovery list '{}' exceeds the {NODE_KEY_LIST_MAX_BYTES}-byte cap; refusing to read",
                path.display()
            ),
        ));
    }
    String::from_utf8(bytes).map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}

fn node_key_list_path_is_regular(path: &Path) -> Result<bool, LoadListError> {
    if let Some(symlink_path) = node_key_list_symlink_component(path)? {
        return Err(node_key_list_invalid_path_error(format!(
            "refusing to read discovery list {} because it traverses symbolic link {}",
            discovery_list_path_ref(path),
            discovery_list_path_ref(&symlink_path),
        )));
    }
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_file() => Ok(true),
        Ok(_) => Err(node_key_list_invalid_path_error(format!(
            "refusing to read discovery list {} because it is not a regular file",
            discovery_list_path_ref(path),
        ))),
        Err(error)
            if matches!(
                error.kind(),
                io::ErrorKind::NotFound | io::ErrorKind::NotADirectory
            ) =>
        {
            Ok(false)
        }
        Err(error) => Err(LoadListError::Read(error)),
    }
}

fn node_key_list_symlink_component(path: &Path) -> Result<Option<PathBuf>, LoadListError> {
    crate::core::path_safety::first_existing_symlink_component(path).map_err(LoadListError::Read)
}

fn node_key_list_invalid_path_error(message: String) -> LoadListError {
    LoadListError::Read(io::Error::new(io::ErrorKind::InvalidInput, message))
}

fn discovery_list_path_ref(path: &Path) -> String {
    let path = path.to_string_lossy();
    let hash = blake3::hash(path.as_bytes()).to_hex();
    format!("discovery_list_path_{}", &hash[..10])
}

/// Convenience: load all three workspace list files (`.ee/discovery_allowlist.toml`,
/// `.ee/discovery_denylist.toml`, `.ee/respond_allowlist.toml`).
///
/// Returns the three sets in order. Any individual missing file is
/// silently treated as empty; only an actual parse error or read error
/// propagates.
pub fn load_workspace_lists(workspace_path: &Path) -> Result<WorkspaceLists, LoadListError> {
    let ee_dir = workspace_path.join(".ee");
    let allowlist = load_node_key_list(&ee_dir.join(DISCOVERY_ALLOWLIST_FILE))?;
    let denylist = load_node_key_list(&ee_dir.join(DISCOVERY_DENYLIST_FILE))?;
    let respond_allowlist = load_node_key_list(&ee_dir.join(RESPOND_ALLOWLIST_FILE))?;
    Ok(WorkspaceLists {
        allowlist,
        denylist,
        respond_allowlist,
    })
}

/// Bundle returned by [`load_workspace_lists`].
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct WorkspaceLists {
    pub allowlist: BTreeSet<String>,
    pub denylist: BTreeSet<String>,
    pub respond_allowlist: BTreeSet<String>,
}

/// Posture-evaluation degradation: detects misconfigurations that the
/// `--json` surface should surface to the operator.
///
/// Empty when the configuration is internally consistent.
#[must_use]
pub fn evaluate_policy_degradations(
    discovery_mode: DiscoveryMode,
    respond_mode: DiscoveryMode,
    self_advertised_tags: &[String],
    discovery_allowlist: &BTreeSet<String>,
) -> Vec<PolicyDegradation> {
    let mut out = Vec::new();
    if respond_mode == DiscoveryMode::ServiceTag
        && !self_advertised_tags
            .iter()
            .any(|tag| tag == EE_MESH_SERVICE_TAG)
    {
        out.push(PolicyDegradation {
            code: DISCOVERY_POLICY_NO_EE_MESH_TAG_CODE,
            severity: "info",
            message: format!(
                "respondMode is {} but this host does not advertise {EE_MESH_SERVICE_TAG}; peers will see decline responses",
                DiscoveryMode::ServiceTag.as_str(),
            ),
            repair: "tailscale up --advertise-tags=tag:ee-mesh",
        });
    }
    if discovery_mode == DiscoveryMode::Allowlist && discovery_allowlist.is_empty() {
        out.push(PolicyDegradation {
            code: DISCOVERY_POLICY_EMPTY_ALLOWLIST_CODE,
            severity: "info",
            message: format!(
                "discoveryMode is {} but the allowlist is empty; no peers will be probed",
                DiscoveryMode::Allowlist.as_str(),
            ),
            repair: "ee mesh discovery-policy allow --help",
        });
    }
    out
}

/// Static-string-bearing degradation record used by
/// [`evaluate_policy_degradations`]. The `&'static str` fields keep
/// allocations off the hot path; the `message` field is owned because
/// it embeds mode-specific text.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PolicyDegradation {
    pub code: &'static str,
    pub severity: &'static str,
    pub message: String,
    pub repair: &'static str,
}

// ============================================================================
// Inline tests (AGENTS.md L300-302 / bd-3usjw.62 Rule 7)
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;

    #[test]
    fn load_node_key_list_refuses_oversized_payload() {
        // bd-3gmzf: an operator-supplied .ee/<allowlist|denylist>.toml
        // larger than NODE_KEY_LIST_MAX_BYTES (1 MiB) must be refused
        // with LoadListError::Read(io::Error{kind: InvalidData})
        // before we materialize it. Mirrors the bd-3l1cy / bd-1sdr5
        // regression for the same defect class.
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("oversized_allowlist.toml");
        std::fs::write(&path, vec![b'x'; NODE_KEY_LIST_MAX_BYTES + 1]).expect("write oversized");

        let error = load_node_key_list(&path).expect_err("oversized read must error");
        match error {
            LoadListError::Read(io_error) => {
                assert_eq!(io_error.kind(), io::ErrorKind::InvalidData);
                let message = format!("{io_error}");
                assert!(
                    message.contains("exceeds") && message.contains("byte cap"),
                    "expected over-cap diagnostic; got {message}"
                );
            }
            other => panic!("expected LoadListError::Read with InvalidData; got {other:?}"),
        }
    }

    #[test]
    fn load_node_key_list_passes_payload_at_cap() {
        // bd-3gmzf: at-the-cap reads must succeed; only over-cap reads
        // are refused. The contents intentionally do not contain a
        // `node_keys` array, so we expect the helper to read the body
        // and then the parser to fall through to the "missing field is
        // empty" branch — proving the read itself accepted the file.
        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("at_cap_allowlist.toml");
        // Construct a TOML body padded with whitespace up to the cap.
        let mut bytes = b"# at-cap fixture\n".to_vec();
        bytes.resize(NODE_KEY_LIST_MAX_BYTES, b' ');
        assert_eq!(bytes.len(), NODE_KEY_LIST_MAX_BYTES);
        std::fs::write(&path, &bytes).expect("write at-cap");

        let set = load_node_key_list(&path).expect("at-cap read must succeed");
        assert!(
            set.is_empty(),
            "fixture omits node_keys array; expected empty set"
        );
    }

    const NODE_KEY_A: &str =
        "nodekey:0000000000000000000000000000000000000000000000000000000000000001";
    const NODE_KEY_B: &str =
        "nodekey:0000000000000000000000000000000000000000000000000000000000000002";
    const NODE_KEY_C: &str =
        "nodekey:0000000000000000000000000000000000000000000000000000000000000003";

    fn empty_set() -> BTreeSet<String> {
        BTreeSet::new()
    }

    fn set_of(items: &[&str]) -> BTreeSet<String> {
        items.iter().map(|s| (*s).to_owned()).collect()
    }

    // ---- Mode + enum round-trips -------------------------------------------

    #[test]
    fn discovery_mode_default_is_service_tag() {
        assert_eq!(DiscoveryMode::default(), DiscoveryMode::ServiceTag);
        assert_eq!(DiscoveryMode::default_mode(), DiscoveryMode::ServiceTag);
        assert_eq!(DiscoveryMode::default().as_str(), "service_tag");
    }

    #[test]
    fn discovery_mode_from_str_accepts_three_canonical_tokens() {
        assert_eq!(
            DiscoveryMode::from_str("service_tag").expect("service_tag parses"),
            DiscoveryMode::ServiceTag
        );
        assert_eq!(
            DiscoveryMode::from_str("auto_admit").expect("auto_admit parses"),
            DiscoveryMode::AutoAdmit
        );
        assert_eq!(
            DiscoveryMode::from_str("allowlist").expect("allowlist parses"),
            DiscoveryMode::Allowlist
        );
    }

    #[test]
    fn discovery_mode_from_str_trims_surrounding_whitespace() {
        assert_eq!(
            DiscoveryMode::from_str("  auto_admit\n").expect("trim parses"),
            DiscoveryMode::AutoAdmit
        );
    }

    #[test]
    fn discovery_mode_from_str_rejects_unknown_token() {
        let err = DiscoveryMode::from_str("AUTO_ADMIT").expect_err("uppercase rejected");
        assert_eq!(err.raw, "AUTO_ADMIT");
        let err = DiscoveryMode::from_str("anything").expect_err("unknown rejected");
        assert_eq!(err.raw, "anything");
        let display = format!("{err}");
        assert!(display.contains("service_tag"), "{display}");
        assert!(display.contains("auto_admit"), "{display}");
        assert!(display.contains("allowlist"), "{display}");
    }

    #[test]
    fn discovery_mode_from_raw_missing_falls_back_to_default() {
        let mut unknown_seen = String::new();
        let mode = DiscoveryMode::from_raw_with_default(None, |raw| unknown_seen.push_str(raw));
        assert_eq!(mode, DiscoveryMode::ServiceTag);
        assert!(unknown_seen.is_empty(), "no on_unknown when value unset");
    }

    #[test]
    fn discovery_mode_from_raw_valid_returns_parsed_without_calling_on_unknown() {
        let mut unknown_seen = String::new();
        let mode = DiscoveryMode::from_raw_with_default(Some("allowlist"), |raw| {
            unknown_seen.push_str(raw);
        });
        assert_eq!(mode, DiscoveryMode::Allowlist);
        assert!(unknown_seen.is_empty(), "on_unknown not called on valid");
    }

    #[test]
    fn discovery_mode_from_raw_invalid_calls_on_unknown_and_falls_back() {
        let mut unknown_seen = String::new();
        let mode = DiscoveryMode::from_raw_with_default(Some("AUTO_ADMIT"), |raw| {
            unknown_seen.push_str(raw);
        });
        assert_eq!(mode, DiscoveryMode::ServiceTag);
        assert_eq!(unknown_seen, "AUTO_ADMIT");
    }

    #[test]
    fn discovery_mode_round_trips_through_serde_snake_case() {
        for mode in [
            DiscoveryMode::ServiceTag,
            DiscoveryMode::AutoAdmit,
            DiscoveryMode::Allowlist,
        ] {
            let serialized = serde_json::to_string(&mode).expect("serialize");
            let deserialized: DiscoveryMode =
                serde_json::from_str(&serialized).expect("deserialize");
            assert_eq!(deserialized, mode);
            assert!(serialized.contains(mode.as_str()));
        }
    }

    #[test]
    fn discovery_reason_str_matches_snake_case_serde() {
        for reason in [
            DiscoveryReason::AutoAdmit,
            DiscoveryReason::ServiceTagMatch,
            DiscoveryReason::Allowlisted,
            DiscoveryReason::SkipNoTag,
            DiscoveryReason::SkipNotAllowlisted,
            DiscoveryReason::SkipDenylisted,
            DiscoveryReason::SkipSelf,
        ] {
            let serialized = serde_json::to_string(&reason).expect("serialize");
            assert!(serialized.contains(reason.as_str()));
        }
    }

    // ---- Caller-side discovery decisions -----------------------------------

    #[test]
    fn caller_skips_self_node_key_in_every_mode() {
        let tags = vec![EE_MESH_SERVICE_TAG.to_owned()];
        let allow = set_of(&["nodekey:self"]);
        let deny = empty_set();
        for mode in [
            DiscoveryMode::ServiceTag,
            DiscoveryMode::AutoAdmit,
            DiscoveryMode::Allowlist,
        ] {
            let (decision, reason) = decide_discovery(&DiscoveryDecisionInput {
                mode,
                peer_node_key: "nodekey:self",
                peer_advertised_tags: &tags,
                self_node_key: "nodekey:self",
                allowlist: &allow,
                denylist: &deny,
            });
            assert_eq!(decision, DiscoveryDecision::Skip);
            assert_eq!(reason, DiscoveryReason::SkipSelf);
        }
    }

    #[test]
    fn caller_denylist_overrides_auto_admit() {
        let deny = set_of(&["nodekey:bad"]);
        let (decision, reason) = decide_discovery(&DiscoveryDecisionInput {
            mode: DiscoveryMode::AutoAdmit,
            peer_node_key: "nodekey:bad",
            peer_advertised_tags: &[],
            self_node_key: "nodekey:self",
            allowlist: &empty_set(),
            denylist: &deny,
        });
        assert_eq!(decision, DiscoveryDecision::Skip);
        assert_eq!(reason, DiscoveryReason::SkipDenylisted);
    }

    #[test]
    fn caller_denylist_overrides_allowlist() {
        let allow = set_of(&["nodekey:peer"]);
        let deny = set_of(&["nodekey:peer"]);
        let (decision, reason) = decide_discovery(&DiscoveryDecisionInput {
            mode: DiscoveryMode::Allowlist,
            peer_node_key: "nodekey:peer",
            peer_advertised_tags: &[],
            self_node_key: "nodekey:self",
            allowlist: &allow,
            denylist: &deny,
        });
        assert_eq!(decision, DiscoveryDecision::Skip);
        assert_eq!(reason, DiscoveryReason::SkipDenylisted);
    }

    #[test]
    fn caller_auto_admit_probes_peer_without_tag() {
        let (decision, reason) = decide_discovery(&DiscoveryDecisionInput {
            mode: DiscoveryMode::AutoAdmit,
            peer_node_key: "nodekey:peer",
            peer_advertised_tags: &[],
            self_node_key: "nodekey:self",
            allowlist: &empty_set(),
            denylist: &empty_set(),
        });
        assert_eq!(decision, DiscoveryDecision::Probe);
        assert_eq!(reason, DiscoveryReason::AutoAdmit);
    }

    #[test]
    fn caller_service_tag_probes_peer_with_ee_mesh_tag() {
        let tags = vec![EE_MESH_SERVICE_TAG.to_owned()];
        let (decision, reason) = decide_discovery(&DiscoveryDecisionInput {
            mode: DiscoveryMode::ServiceTag,
            peer_node_key: "nodekey:peer",
            peer_advertised_tags: &tags,
            self_node_key: "nodekey:self",
            allowlist: &empty_set(),
            denylist: &empty_set(),
        });
        assert_eq!(decision, DiscoveryDecision::Probe);
        assert_eq!(reason, DiscoveryReason::ServiceTagMatch);
    }

    #[test]
    fn caller_service_tag_skips_peer_without_ee_mesh_tag() {
        let tags = vec!["tag:something-else".to_owned()];
        let (decision, reason) = decide_discovery(&DiscoveryDecisionInput {
            mode: DiscoveryMode::ServiceTag,
            peer_node_key: "nodekey:peer",
            peer_advertised_tags: &tags,
            self_node_key: "nodekey:self",
            allowlist: &empty_set(),
            denylist: &empty_set(),
        });
        assert_eq!(decision, DiscoveryDecision::Skip);
        assert_eq!(reason, DiscoveryReason::SkipNoTag);
    }

    #[test]
    fn caller_allowlist_probes_listed_node_key() {
        let allow = set_of(&["nodekey:friend"]);
        let (decision, reason) = decide_discovery(&DiscoveryDecisionInput {
            mode: DiscoveryMode::Allowlist,
            peer_node_key: "nodekey:friend",
            peer_advertised_tags: &[],
            self_node_key: "nodekey:self",
            allowlist: &allow,
            denylist: &empty_set(),
        });
        assert_eq!(decision, DiscoveryDecision::Probe);
        assert_eq!(reason, DiscoveryReason::Allowlisted);
    }

    #[test]
    fn caller_allowlist_skips_unlisted_node_key() {
        let allow = set_of(&["nodekey:friend"]);
        let (decision, reason) = decide_discovery(&DiscoveryDecisionInput {
            mode: DiscoveryMode::Allowlist,
            peer_node_key: "nodekey:stranger",
            peer_advertised_tags: &[],
            self_node_key: "nodekey:self",
            allowlist: &allow,
            denylist: &empty_set(),
        });
        assert_eq!(decision, DiscoveryDecision::Skip);
        assert_eq!(reason, DiscoveryReason::SkipNotAllowlisted);
    }

    #[test]
    fn caller_probe_reasons_map_to_autodiscovery_policy_decisions() {
        for (reason, expected) in [
            (DiscoveryReason::AutoAdmit, "auto_admit"),
            (DiscoveryReason::ServiceTagMatch, "service_tag_match"),
            (DiscoveryReason::Allowlisted, "allowlisted"),
        ] {
            assert_eq!(reason.autodiscovery_policy_decision(), Some(expected));
            assert_eq!(reason.autodiscovery_skip_reason(), None);
        }
    }

    #[test]
    fn caller_skip_reasons_map_to_autodiscovery_skip_vocabulary() {
        for (reason, expected) in [
            (DiscoveryReason::SkipNoTag, "no_discovery_consent"),
            (DiscoveryReason::SkipNotAllowlisted, "no_discovery_consent"),
            (DiscoveryReason::SkipDenylisted, "denied_by_policy"),
            (DiscoveryReason::SkipSelf, "denied_by_policy"),
        ] {
            assert_eq!(reason.autodiscovery_policy_decision(), None);
            assert_eq!(reason.autodiscovery_skip_reason(), Some(expected));
        }
    }

    // ---- Responder-side decisions ------------------------------------------

    #[test]
    fn responder_denylist_overrides_auto_admit() {
        let deny = set_of(&["nodekey:bad"]);
        let (consent, reason) = decide_respond(&RespondDecisionInput {
            mode: DiscoveryMode::AutoAdmit,
            requester_node_key: "nodekey:bad",
            requester_advertised_tags: &[],
            self_advertised_tags: &[],
            respond_allowlist: &empty_set(),
            denylist: &deny,
        });
        assert_eq!(consent, DiscoveryConsent::Denied);
        assert_eq!(reason, DiscoveryReason::SkipDenylisted);
    }

    #[test]
    fn responder_service_tag_grants_when_self_advertises_tag() {
        let self_tags = vec![EE_MESH_SERVICE_TAG.to_owned()];
        let (consent, reason) = decide_respond(&RespondDecisionInput {
            mode: DiscoveryMode::ServiceTag,
            requester_node_key: "nodekey:peer",
            requester_advertised_tags: &[],
            self_advertised_tags: &self_tags,
            respond_allowlist: &empty_set(),
            denylist: &empty_set(),
        });
        assert_eq!(consent, DiscoveryConsent::Granted);
        assert_eq!(reason, DiscoveryReason::ServiceTagMatch);
    }

    #[test]
    fn responder_service_tag_denies_when_self_does_not_advertise_tag() {
        let (consent, reason) = decide_respond(&RespondDecisionInput {
            mode: DiscoveryMode::ServiceTag,
            requester_node_key: "nodekey:peer",
            requester_advertised_tags: &[EE_MESH_SERVICE_TAG.to_owned()],
            self_advertised_tags: &[],
            respond_allowlist: &empty_set(),
            denylist: &empty_set(),
        });
        assert_eq!(consent, DiscoveryConsent::Denied);
        assert_eq!(reason, DiscoveryReason::SkipNoTag);
    }

    #[test]
    fn responder_allowlist_grants_listed_requester() {
        let allow = set_of(&["nodekey:peer"]);
        let (consent, reason) = decide_respond(&RespondDecisionInput {
            mode: DiscoveryMode::Allowlist,
            requester_node_key: "nodekey:peer",
            requester_advertised_tags: &[],
            self_advertised_tags: &[],
            respond_allowlist: &allow,
            denylist: &empty_set(),
        });
        assert_eq!(consent, DiscoveryConsent::Granted);
        assert_eq!(reason, DiscoveryReason::Allowlisted);
    }

    #[test]
    fn responder_allowlist_denies_unlisted_requester() {
        let allow = set_of(&["nodekey:peer"]);
        let (consent, reason) = decide_respond(&RespondDecisionInput {
            mode: DiscoveryMode::Allowlist,
            requester_node_key: "nodekey:stranger",
            requester_advertised_tags: &[],
            self_advertised_tags: &[],
            respond_allowlist: &allow,
            denylist: &empty_set(),
        });
        assert_eq!(consent, DiscoveryConsent::Denied);
        assert_eq!(reason, DiscoveryReason::SkipNotAllowlisted);
    }

    // ---- TOML list loader --------------------------------------------------

    #[test]
    fn load_node_key_list_returns_empty_set_when_file_missing() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let path = tempdir.path().join("missing.toml");
        let result = load_node_key_list(&path).expect("missing file is ok");
        assert!(result.is_empty());
    }

    #[test]
    fn load_node_key_list_parses_simple_toml() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let path = tempdir.path().join("list.toml");
        let mut file = std::fs::File::create(&path).expect("create");
        writeln!(file, "node_keys = [\"{NODE_KEY_A}\", \"{NODE_KEY_B}\"]").expect("write");
        drop(file);
        let result = load_node_key_list(&path).expect("parse");
        assert_eq!(result.len(), 2);
        assert!(result.contains(NODE_KEY_A));
        assert!(result.contains(NODE_KEY_B));
    }

    #[cfg(unix)]
    #[test]
    fn load_node_key_list_rejects_symlinked_list_file() {
        use std::os::unix::fs::symlink;

        let tempdir = tempfile::tempdir().expect("tempdir");
        let real_path = tempdir.path().join("real.toml");
        std::fs::write(&real_path, "node_keys = [\"nodekey:outside\"]\n").expect("write");
        let linked_path = tempdir.path().join("linked.toml");
        symlink(&real_path, &linked_path).expect("symlink");

        let result = load_node_key_list(&linked_path);

        let Err(LoadListError::Read(error)) = result else {
            panic!("expected symlinked list path to fail closed, got {result:?}");
        };
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
        let message = error.to_string();
        assert!(message.contains("symbolic link"));
        assert!(message.contains("discovery_list_path_"));
        assert!(!message.contains("linked.toml"));
        assert!(!message.contains("real.toml"));
        assert!(!message.contains(tempdir.path().to_string_lossy().as_ref()));
    }

    #[test]
    fn load_node_key_list_rejects_non_regular_list_path() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let directory_path = tempdir.path().join("list.toml");
        std::fs::create_dir(&directory_path).expect("mkdir");

        let result = load_node_key_list(&directory_path);

        let Err(LoadListError::Read(error)) = result else {
            panic!("expected non-regular list path to fail closed, got {result:?}");
        };
        assert_eq!(error.kind(), std::io::ErrorKind::InvalidInput);
        let message = error.to_string();
        assert!(message.contains("not a regular file"));
        assert!(message.contains("discovery_list_path_"));
        assert!(!message.contains("list.toml"));
        assert!(!message.contains(tempdir.path().to_string_lossy().as_ref()));
    }

    #[test]
    fn load_node_key_list_deduplicates_and_trims() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let path = tempdir.path().join("list.toml");
        let mut file = std::fs::File::create(&path).expect("create");
        writeln!(
            file,
            "node_keys = [\"{NODE_KEY_A}\", \"  {NODE_KEY_A}  \", \"\", \"   \"]"
        )
        .expect("write");
        drop(file);
        let result = load_node_key_list(&path).expect("parse");
        assert_eq!(
            result.len(),
            1,
            "expected dedup + empty drop, got {result:?}"
        );
        assert!(result.contains(NODE_KEY_A));
    }

    #[test]
    fn load_node_key_list_rejects_non_node_key_entries() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let path = tempdir.path().join("list.toml");
        std::fs::write(&path, "node_keys = [\"machinekey:alpha\"]\n").expect("write");

        let result = load_node_key_list(&path);

        let Err(LoadListError::InvalidShape(message)) = result else {
            panic!("expected malformed node key to fail closed, got {result:?}");
        };
        assert!(message.contains("node_keys[0]"));
        assert!(message.contains("nodekey:"));
    }

    #[test]
    fn load_node_key_list_rejects_path_like_node_key_entries() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let path = tempdir.path().join("list.toml");
        std::fs::write(&path, "node_keys = [\"nodekey:../../secret\"]\n").expect("write");

        let result = load_node_key_list(&path);

        let Err(LoadListError::InvalidShape(message)) = result else {
            panic!("expected path-like node key to fail closed, got {result:?}");
        };
        assert!(message.contains("node_keys[0]"));
        assert!(message.contains("lowercase hex"));
    }

    #[test]
    fn load_node_key_list_rejects_invalid_toml() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let path = tempdir.path().join("list.toml");
        let mut file = std::fs::File::create(&path).expect("create");
        writeln!(file, "node_keys = this is not toml [").expect("write");
        drop(file);
        let result = load_node_key_list(&path);
        assert!(matches!(result, Err(LoadListError::Parse(_))));
    }

    #[test]
    fn load_workspace_lists_returns_default_when_ee_dir_missing() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let lists = load_workspace_lists(tempdir.path()).expect("ok");
        assert!(lists.allowlist.is_empty());
        assert!(lists.denylist.is_empty());
        assert!(lists.respond_allowlist.is_empty());
    }

    #[test]
    fn load_workspace_lists_reads_all_three_files_when_present() {
        let tempdir = tempfile::tempdir().expect("tempdir");
        let ee_dir = tempdir.path().join(".ee");
        std::fs::create_dir(&ee_dir).expect("mkdir");
        for (name, key) in [
            (DISCOVERY_ALLOWLIST_FILE, NODE_KEY_A),
            (DISCOVERY_DENYLIST_FILE, NODE_KEY_B),
            (RESPOND_ALLOWLIST_FILE, NODE_KEY_C),
        ] {
            let path = ee_dir.join(name);
            std::fs::write(&path, format!("node_keys = [\"{key}\"]\n")).expect("write");
        }
        let lists = load_workspace_lists(tempdir.path()).expect("ok");
        assert!(lists.allowlist.contains(NODE_KEY_A));
        assert!(lists.denylist.contains(NODE_KEY_B));
        assert!(lists.respond_allowlist.contains(NODE_KEY_C));
    }

    // ---- Degradation evaluation --------------------------------------------

    #[test]
    fn evaluate_policy_degradations_flags_missing_service_tag() {
        let degradations = evaluate_policy_degradations(
            DiscoveryMode::AutoAdmit,
            DiscoveryMode::ServiceTag,
            &[],
            &empty_set(),
        );
        assert!(
            degradations
                .iter()
                .any(|d| d.code == DISCOVERY_POLICY_NO_EE_MESH_TAG_CODE)
        );
    }

    #[test]
    fn evaluate_policy_degradations_does_not_flag_when_tag_advertised() {
        let tags = vec![EE_MESH_SERVICE_TAG.to_owned()];
        let degradations = evaluate_policy_degradations(
            DiscoveryMode::AutoAdmit,
            DiscoveryMode::ServiceTag,
            &tags,
            &empty_set(),
        );
        assert!(
            degradations
                .iter()
                .all(|d| d.code != DISCOVERY_POLICY_NO_EE_MESH_TAG_CODE)
        );
    }

    #[test]
    fn evaluate_policy_degradations_flags_empty_allowlist() {
        let degradations = evaluate_policy_degradations(
            DiscoveryMode::Allowlist,
            DiscoveryMode::AutoAdmit,
            &[],
            &empty_set(),
        );
        assert!(
            degradations
                .iter()
                .any(|d| d.code == DISCOVERY_POLICY_EMPTY_ALLOWLIST_CODE)
        );
        let empty_allowlist = degradations
            .iter()
            .find(|d| d.code == DISCOVERY_POLICY_EMPTY_ALLOWLIST_CODE)
            .expect("empty allowlist degradation");
        assert_eq!(
            empty_allowlist.repair,
            "ee mesh discovery-policy allow --help"
        );
        assert!(
            !empty_allowlist.repair.contains('<') && !empty_allowlist.repair.contains('>'),
            "repair hint must not expose an unresolved metavariable: {}",
            empty_allowlist.repair
        );
    }

    #[test]
    fn evaluate_policy_degradations_returns_empty_when_well_formed() {
        let tags = vec![EE_MESH_SERVICE_TAG.to_owned()];
        let allow = set_of(&["nodekey:friend"]);
        let degradations = evaluate_policy_degradations(
            DiscoveryMode::Allowlist,
            DiscoveryMode::ServiceTag,
            &tags,
            &allow,
        );
        assert!(degradations.is_empty());
    }

    #[test]
    fn evaluate_policy_degradations_can_return_both_codes_simultaneously() {
        let degradations = evaluate_policy_degradations(
            DiscoveryMode::Allowlist,
            DiscoveryMode::ServiceTag,
            &[],
            &empty_set(),
        );
        assert_eq!(degradations.len(), 2);
    }
}