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
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
//! Central registry for `EE_*` environment variables honored by ee.
//!
//! Adding a new `EE_*` environment variable requires adding a variant here.
//! Tests enforce that production code reads these variables through this
//! registry rather than spelling raw names at call sites.

use std::ffi::OsString;
use std::str::FromStr;

/// Foreign embedding-related environment variables that ee detects but ignores.
///
/// These are analyst traps from other embedding stacks. ee only checks whether
/// they are present so `ee doctor` can disclose that they do not affect the
/// bundled local embedder.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum EmbeddingTrapEnvVar {
    /// `EMBEDDING_MODEL`
    EmbeddingModel,
    /// `OPENAI_API_KEY`
    OpenAiApiKey,
}

impl EmbeddingTrapEnvVar {
    /// Return all detected-but-ignored embedding variables in stable order.
    #[must_use]
    pub const fn all() -> &'static [Self] {
        &[Self::EmbeddingModel, Self::OpenAiApiKey]
    }

    /// Stable environment variable name.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::EmbeddingModel => "EMBEDDING_MODEL",
            Self::OpenAiApiKey => "OPENAI_API_KEY",
        }
    }

    /// Human-readable explanation for why this variable is only detected.
    #[must_use]
    pub const fn description(self) -> &'static str {
        match self {
            Self::EmbeddingModel => {
                "`ee doctor` detects presence only; ee uses the bundled local embedder instead."
            }
            Self::OpenAiApiKey => {
                "`ee doctor` detects presence only; local semantic retrieval never consumes API keys."
            }
        }
    }

    /// Broad documentation category for ignored embedding-config traps.
    #[must_use]
    pub const fn category(self) -> &'static str {
        "embeddings"
    }

    /// Return whether this trap variable is present without exposing its value.
    #[must_use]
    pub fn is_present(self) -> bool {
        std::env::var_os(self.name()).is_some()
    }
}

/// Every `EE_*` environment variable honored by ee.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum EnvVar {
    /// `EE_AGENT_NAME`
    AgentName,
    /// `EE_AGENT_MODE`
    AgentMode,
    /// `EE_AMBIENT_CONTEXT`
    AmbientContext,
    /// `EE_AMBIENT_CONTEXT_STATE_DIR`
    AmbientContextStateDir,
    /// `EE_AMBIENT_CONTEXT_VERBOSITY`
    AmbientContextVerbosity,
    /// `EE_ADAPTIVE_BACKOFF_MS`
    AdaptiveBackoffMs,
    /// `EE_ADAPTIVE_NOISY_P99_MS`
    AdaptiveNoisyP99Ms,
    /// `EE_AUDIT_LANE_BATCH_MAX`
    AuditLaneBatchMax,
    /// `EE_AUDIT_LANE_CAPACITY`
    AuditLaneCapacity,
    /// `EE_AUDIT_LANE_FLUSH_MS`
    AuditLaneFlushMs,
    /// `EE_CASS_BINARY`
    CassBinary,
    /// `EE_CASS_TIMEOUT_SECS`
    CassTimeoutSecs,
    /// `EE_CURATION_AUTO_PROMOTE_CONFIDENCE_FLOOR`
    CurationAutoPromoteConfidenceFloor,
    /// `EE_CURATION_AUTO_PROMOTE_MAX_PER_RUN`
    CurationAutoPromoteMaxPerRun,
    /// `EE_CURATION_DERIVED_PREVIEW_LIMIT`
    CurationDerivedPreviewLimit,
    /// `EE_DAEMON_ENABLE_ECHO`
    DaemonEnableEcho,
    /// `EE_DAEMON_MAX_INFLIGHT`
    DaemonMaxInflight,
    /// `EE_DAEMON_SEARCH_TIMEOUT_MS`
    DaemonSearchTimeoutMs,
    /// `EE_DAEMON_WARM`
    DaemonWarm,
    /// `EE_DATABASE_PATH`
    DatabasePath,
    /// `EE_DEMO_EVIDENCE_ROOT`
    DemoEvidenceRoot,
    /// `EE_DIAG_FORCE_CAPABILITY_GAP`
    DiagForceCapabilityGap,
    /// `EE_DISABLE_ADAPTIVE`
    DisableAdaptive,
    /// `EE_DISABLE_TOON`
    DisableToon,
    /// `EE_DISABLE_REMEMBER_SEARCH_NEIGHBORS`
    DisableRememberSearchNeighbors,
    /// `EE_DOCTOR_BLAST_RADIUS`
    DoctorBlastRadius,
    /// `EE_E2E_RETENTION_MANIFEST`
    E2eRetentionManifest,
    /// `EE_EMBED_BACKEND`
    EmbedBackend,
    /// `EE_EMBED_DEDUP_COSINE_FLOOR`
    EmbedDedupCosineFloor,
    /// `EE_EMBED_DEDUP_ENABLED`
    EmbedDedupEnabled,
    /// `EE_EMBED_DEDUP_HAMMING_K`
    EmbedDedupHammingK,
    /// `EE_EMBED_DOWNLOAD`
    EmbedDownload,
    /// `EE_EMBED_MODEL_DIR`
    EmbedModelDir,
    /// `EE_EMBED_MODEL_PATH`
    EmbedModelPath,
    /// `EE_EMBED_REMOTE_API_KEY`
    EmbedRemoteApiKey,
    /// `EE_EMBED_REMOTE_DIMENSION`
    EmbedRemoteDimension,
    /// `EE_EMBED_REMOTE_MODEL`
    EmbedRemoteModel,
    /// `EE_EMBED_REMOTE_URL`
    EmbedRemoteUrl,
    /// `EE_EXPERIMENTAL_TRIAD`
    ExperimentalTriad,
    /// `EE_FLIGHT_RECORDER`
    FlightRecorder,
    /// `EE_FLIGHT_RECORDER_DIR`
    FlightRecorderDir,
    /// `EE_FLIGHT_RECORDER_RETENTION_DAYS`
    FlightRecorderRetentionDays,
    /// `EE_FORMAT`
    Format,
    /// `EE_GRAPH_MEMORY_DEGRADED_BELOW_PCT`
    GraphMemoryDegradedBelowPct,
    /// `EE_GRAPH_MEMORY_GROWTH_MULTIPLIER_BASIS_POINTS`
    GraphMemoryGrowthMultiplierBasisPoints,
    /// `EE_GRAPH_MEMORY_PER_ALGORITHM_CAP_MB`
    GraphMemoryPerAlgorithmCapMb,
    /// `EE_GRAPH_MEMORY_SNAPSHOT_CAP_MB`
    GraphMemorySnapshotCapMb,
    /// `EE_GRAPH_NUMA_PIN_DISABLE`
    GraphNumaPinDisable,
    /// `EE_GRAPH_NUMA_PIN_NODE`
    GraphNumaPinNode,
    /// `EE_GRAPH_NUMA_PIN_POPULATE`
    GraphNumaPinPopulate,
    /// `EE_GRAPH_WITNESSES_RETENTION_DAYS`
    GraphWitnessesRetentionDays,
    /// `EE_HARMFUL_BURST_WINDOW_SECONDS`
    HarmfulBurstWindowSeconds,
    /// `EE_HARMFUL_PER_SOURCE_PER_HOUR`
    HarmfulPerSourcePerHour,
    /// `EE_HOOK_MODE`
    HookMode,
    /// `EE_INDEX_DIR`
    IndexDir,
    /// `EE_INDEX_PUBLISH_LOCK_RETRY_ATTEMPTS`
    IndexPublishLockRetryAttempts,
    /// `EE_JSON`
    Json,
    /// `EE_JOURNAL_ENABLED`
    JournalEnabled,
    /// `EE_JOURNAL_RETENTION_DAYS`
    JournalRetentionDays,
    /// `EE_L2_PACK_CACHE_BYTES`
    L2PackCacheBytes,
    /// `EE_L2_PACK_CACHE_DIR`
    L2PackCacheDir,
    /// `EE_L2_PACK_CACHE_DISABLE`
    L2PackCacheDisable,
    /// `EE_LEGACY_SELECTION_CERTIFICATE`
    LegacySelectionCertificate,
    /// `EE_LEXICAL_INDEX_HUGEPAGES`
    LexicalIndexHugepages,
    /// `EE_LEXICAL_INDEX_PIN_RAM`
    LexicalIndexPinRam,
    /// `EE_LOG_FORMAT`
    LogFormat,
    /// `EE_LOG_JSON`
    LogJson,
    /// `EE_MAX_OUTPUT_TOKENS`
    MaxOutputTokens,
    /// `EE_MAX_TOKENS`
    MaxTokens,
    /// `EE_MCP_MAX_REQUEST_BYTES`
    McpMaxRequestBytes,
    /// `EE_MESH_DISCOVERY_CACHE_TTL_SECONDS`
    MeshDiscoveryCacheTtlSeconds,
    /// `EE_MESH_DRIFT_SOFT_STALE_AFTER`
    MeshDriftSoftStaleAfter,
    /// `EE_MESH_DRIFT_SOFT_STALE_AFTER_SECONDS`
    MeshDriftSoftStaleAfterSeconds,
    /// `EE_MESH_DRIFT_HARD_STALE_AFTER`
    MeshDriftHardStaleAfter,
    /// `EE_MESH_DRIFT_HARD_STALE_AFTER_SECONDS`
    MeshDriftHardStaleAfterSeconds,
    /// `EE_MESH_ENABLED`
    MeshEnabled,
    /// `EE_MESH_HELLO_PORT`
    MeshHelloPort,
    /// `EE_MESH_HELLO_RESPONDER_DISABLED`
    MeshHelloResponderDisabled,
    /// `EE_MESH_MODE`
    MeshMode,
    /// `EE_MESH_TRANSPORT_DISABLED`
    MeshTransportDisabled,
    /// `EE_NO_COLOR`
    NoColor,
    /// `EE_OUTPUT_FORMAT`
    OutputFormat,
    /// `EE_PROFILE`
    Profile,
    /// `EE_PPR_CACHE_ENTRIES`
    PprCacheEntries,
    /// `EE_QUERY_PLAN_CACHE_ENTRIES`
    QueryPlanCacheEntries,
    /// `EE_QUERY_MISS_RETENTION_DAYS`
    QueryMissRetentionDays,
    /// `EE_READ_POOL_DISABLE_PIN`
    ReadPoolDisablePin,
    /// `EE_READ_POOL_ACQUIRE_TIMEOUT_MS`
    ReadPoolAcquireTimeoutMs,
    /// `EE_READ_POOL_IDLE_TIMEOUT_S`
    ReadPoolIdleTimeoutSeconds,
    /// `EE_READ_POOL_MAX_PIN_SECONDS`
    ReadPoolMaxPinSeconds,
    /// `EE_READ_POOL_SIZE`
    ReadPoolSize,
    /// `EE_REFLECTION_CONSUMED_RETENTION_DAYS`
    ReflectionConsumedRetentionDays,
    /// `EE_REFLECTION_EXPIRED_RETENTION_DAYS`
    ReflectionExpiredRetentionDays,
    /// `EE_REFLECTION_HMAC_KEY_ID`
    ReflectionHmacKeyId,
    /// `EE_REFLECTION_HMAC_KEY_PATH`
    ReflectionHmacKeyPath,
    /// `EE_REFLECTION_HMAC_ROTATION_GRACE_SECONDS`
    ReflectionHmacRotationGraceSeconds,
    /// `EE_REFLECTION_REQUEST_LIST_LIMIT`
    ReflectionRequestListLimit,
    /// `EE_REFLECTION_REQUEST_SHOW_SOURCE_LIMIT`
    ReflectionRequestShowSourceLimit,
    /// `EE_REFLECTION_REQUEST_TTL_SECONDS`
    ReflectionRequestTtlSeconds,
    /// `EE_REFLECTION_SOURCE_BUDGET_BYTES`
    ReflectionSourceBudgetBytes,
    /// `EE_REMEMBER_CURATION_SYNC_BUDGET_MS`
    RememberCurationSyncBudgetMs,
    /// `EE_SECURITY_PROFILE`
    SecurityProfile,
    /// `EE_SERVE_TOKEN`
    ServeToken,
    /// `EE_SCIENCE_BACKEND_PATH`
    ScienceBackendPath,
    /// `EE_SHARD_FANOUT_ENABLED`
    ShardFanoutEnabled,
    /// `EE_SHARDS_DIR`
    ShardsDir,
    /// `EE_TEST_LOG_LEVEL`
    TestLogLevel,
    /// `EE_TEST_LOG_PATH`
    TestLogPath,
    /// `EE_TEST_LOG_TEST_ID`
    TestLogTestId,
    /// `EE_TAILSCALE_BINARY_OVERRIDE`
    TailscaleBinaryOverride,
    /// `EE_TAILSCALE_PROBE_TIMEOUT_MS`
    TailscaleProbeTimeoutMs,
    /// `EE_TAILSCALE_PROBE_SOCKET_OVERRIDE`
    TailscaleProbeSocketOverride,
    /// `EE_TAILSCALE_DISCOVERY_MODE`
    TailscaleDiscoveryMode,
    /// `EE_TAILSCALE_PEER_PROBE_TIMEOUT_MS`
    TailscalePeerProbeTimeoutMs,
    /// `EE_TAILSCALE_DISCOVERY_BUDGET_MS`
    TailscaleDiscoveryBudgetMs,
    /// `EE_TAILSCALE_RESPOND_MODE`
    TailscaleRespondMode,
    /// `EE_WORKSPACE_HYGIENE_ALWAYS_REVIEW_PATTERNS`
    WorkspaceHygieneAlwaysReviewPatterns,
    /// `EE_WORKSPACE_HYGIENE_GENERATED_PATTERNS`
    WorkspaceHygieneGeneratedPatterns,
    /// `EE_WORKSPACE_HYGIENE_LOCAL_MACHINE_PATTERNS`
    WorkspaceHygieneLocalMachinePatterns,
    /// `EE_WORKSPACE_HYGIENE_SCRATCH_PATTERNS`
    WorkspaceHygieneScratchPatterns,
    /// `EE_WAL_CHECKPOINT_BYTES_THRESHOLD`
    WalCheckpointBytesThreshold,
    /// `EE_WRITE_GROUP_COMMIT_ENABLED`
    WriteGroupCommitEnabled,
    /// `EE_WRITE_GROUP_COMMIT_BATCH_WINDOW_MS`
    WriteGroupCommitBatchWindowMs,
    /// `EE_WRITE_GROUP_COMMIT_MAX_BATCH_SIZE`
    WriteGroupCommitMaxBatchSize,
    /// `EE_WRITE_GROUP_COMMIT_MAX_INFLIGHT_BYTES`
    WriteGroupCommitMaxInflightBytes,
    /// `EE_WORKSPACE`
    Workspace,
    /// `EE_WORKSPACE_CLOSE_DRAIN_TIMEOUT_S`
    WorkspaceCloseDrainTimeoutSeconds,
    /// `EE_WORKSPACE_REGISTRY`
    WorkspaceRegistry,
}

impl EnvVar {
    /// Return all registered variables in stable display order.
    #[must_use]
    pub const fn all() -> &'static [Self] {
        &[
            Self::AgentName,
            Self::AgentMode,
            Self::AmbientContext,
            Self::AmbientContextStateDir,
            Self::AmbientContextVerbosity,
            Self::AdaptiveBackoffMs,
            Self::AdaptiveNoisyP99Ms,
            Self::AuditLaneBatchMax,
            Self::AuditLaneCapacity,
            Self::AuditLaneFlushMs,
            Self::CassBinary,
            Self::CassTimeoutSecs,
            Self::CurationAutoPromoteConfidenceFloor,
            Self::CurationAutoPromoteMaxPerRun,
            Self::CurationDerivedPreviewLimit,
            Self::DaemonEnableEcho,
            Self::DaemonMaxInflight,
            Self::DaemonSearchTimeoutMs,
            Self::DaemonWarm,
            Self::DatabasePath,
            Self::DemoEvidenceRoot,
            Self::DiagForceCapabilityGap,
            Self::DisableAdaptive,
            Self::DisableToon,
            Self::DisableRememberSearchNeighbors,
            Self::DoctorBlastRadius,
            Self::E2eRetentionManifest,
            Self::EmbedBackend,
            Self::EmbedDedupCosineFloor,
            Self::EmbedDedupEnabled,
            Self::EmbedDedupHammingK,
            Self::EmbedDownload,
            Self::EmbedModelDir,
            Self::EmbedModelPath,
            Self::EmbedRemoteApiKey,
            Self::EmbedRemoteDimension,
            Self::EmbedRemoteModel,
            Self::EmbedRemoteUrl,
            Self::ExperimentalTriad,
            Self::FlightRecorder,
            Self::FlightRecorderDir,
            Self::FlightRecorderRetentionDays,
            Self::Format,
            Self::GraphMemoryDegradedBelowPct,
            Self::GraphMemoryGrowthMultiplierBasisPoints,
            Self::GraphMemoryPerAlgorithmCapMb,
            Self::GraphMemorySnapshotCapMb,
            Self::GraphNumaPinDisable,
            Self::GraphNumaPinNode,
            Self::GraphNumaPinPopulate,
            Self::GraphWitnessesRetentionDays,
            Self::HarmfulBurstWindowSeconds,
            Self::HarmfulPerSourcePerHour,
            Self::HookMode,
            Self::IndexDir,
            Self::IndexPublishLockRetryAttempts,
            Self::Json,
            Self::JournalEnabled,
            Self::JournalRetentionDays,
            Self::L2PackCacheBytes,
            Self::L2PackCacheDir,
            Self::L2PackCacheDisable,
            Self::LegacySelectionCertificate,
            Self::LexicalIndexHugepages,
            Self::LexicalIndexPinRam,
            Self::LogFormat,
            Self::LogJson,
            Self::MaxOutputTokens,
            Self::MaxTokens,
            Self::McpMaxRequestBytes,
            Self::MeshDiscoveryCacheTtlSeconds,
            Self::MeshDriftSoftStaleAfter,
            Self::MeshDriftSoftStaleAfterSeconds,
            Self::MeshDriftHardStaleAfter,
            Self::MeshDriftHardStaleAfterSeconds,
            Self::MeshEnabled,
            Self::MeshHelloPort,
            Self::MeshHelloResponderDisabled,
            Self::MeshMode,
            Self::MeshTransportDisabled,
            Self::NoColor,
            Self::OutputFormat,
            Self::Profile,
            Self::PprCacheEntries,
            Self::QueryPlanCacheEntries,
            Self::QueryMissRetentionDays,
            Self::ReadPoolDisablePin,
            Self::ReadPoolAcquireTimeoutMs,
            Self::ReadPoolIdleTimeoutSeconds,
            Self::ReadPoolMaxPinSeconds,
            Self::ReadPoolSize,
            Self::ReflectionConsumedRetentionDays,
            Self::ReflectionExpiredRetentionDays,
            Self::ReflectionHmacKeyId,
            Self::ReflectionHmacKeyPath,
            Self::ReflectionHmacRotationGraceSeconds,
            Self::ReflectionRequestListLimit,
            Self::ReflectionRequestShowSourceLimit,
            Self::ReflectionRequestTtlSeconds,
            Self::ReflectionSourceBudgetBytes,
            Self::RememberCurationSyncBudgetMs,
            Self::SecurityProfile,
            Self::ServeToken,
            Self::ScienceBackendPath,
            Self::ShardFanoutEnabled,
            Self::ShardsDir,
            Self::TestLogLevel,
            Self::TestLogPath,
            Self::TestLogTestId,
            Self::TailscaleBinaryOverride,
            Self::TailscaleProbeTimeoutMs,
            Self::TailscaleProbeSocketOverride,
            Self::TailscaleDiscoveryMode,
            Self::TailscalePeerProbeTimeoutMs,
            Self::TailscaleDiscoveryBudgetMs,
            Self::TailscaleRespondMode,
            Self::WorkspaceHygieneAlwaysReviewPatterns,
            Self::WorkspaceHygieneGeneratedPatterns,
            Self::WorkspaceHygieneLocalMachinePatterns,
            Self::WorkspaceHygieneScratchPatterns,
            Self::WalCheckpointBytesThreshold,
            Self::WriteGroupCommitEnabled,
            Self::WriteGroupCommitBatchWindowMs,
            Self::WriteGroupCommitMaxBatchSize,
            Self::WriteGroupCommitMaxInflightBytes,
            Self::Workspace,
            Self::WorkspaceCloseDrainTimeoutSeconds,
            Self::WorkspaceRegistry,
        ]
    }

    /// Stable environment variable name.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::AgentName => "EE_AGENT_NAME",
            Self::AgentMode => "EE_AGENT_MODE",
            Self::AmbientContext => "EE_AMBIENT_CONTEXT",
            Self::AmbientContextStateDir => "EE_AMBIENT_CONTEXT_STATE_DIR",
            Self::AmbientContextVerbosity => "EE_AMBIENT_CONTEXT_VERBOSITY",
            Self::AdaptiveBackoffMs => "EE_ADAPTIVE_BACKOFF_MS",
            Self::AdaptiveNoisyP99Ms => "EE_ADAPTIVE_NOISY_P99_MS",
            Self::AuditLaneBatchMax => "EE_AUDIT_LANE_BATCH_MAX",
            Self::AuditLaneCapacity => "EE_AUDIT_LANE_CAPACITY",
            Self::AuditLaneFlushMs => "EE_AUDIT_LANE_FLUSH_MS",
            Self::CassBinary => "EE_CASS_BINARY",
            Self::CassTimeoutSecs => "EE_CASS_TIMEOUT_SECS",
            Self::CurationAutoPromoteConfidenceFloor => "EE_CURATION_AUTO_PROMOTE_CONFIDENCE_FLOOR",
            Self::CurationAutoPromoteMaxPerRun => "EE_CURATION_AUTO_PROMOTE_MAX_PER_RUN",
            Self::CurationDerivedPreviewLimit => "EE_CURATION_DERIVED_PREVIEW_LIMIT",
            Self::DaemonEnableEcho => "EE_DAEMON_ENABLE_ECHO",
            Self::DaemonMaxInflight => "EE_DAEMON_MAX_INFLIGHT",
            Self::DaemonSearchTimeoutMs => "EE_DAEMON_SEARCH_TIMEOUT_MS",
            Self::DaemonWarm => "EE_DAEMON_WARM",
            Self::DatabasePath => "EE_DATABASE_PATH",
            Self::DemoEvidenceRoot => "EE_DEMO_EVIDENCE_ROOT",
            Self::DiagForceCapabilityGap => "EE_DIAG_FORCE_CAPABILITY_GAP",
            Self::DisableAdaptive => "EE_DISABLE_ADAPTIVE",
            Self::DisableToon => "EE_DISABLE_TOON",
            Self::DisableRememberSearchNeighbors => "EE_DISABLE_REMEMBER_SEARCH_NEIGHBORS",
            Self::DoctorBlastRadius => "EE_DOCTOR_BLAST_RADIUS",
            Self::E2eRetentionManifest => "EE_E2E_RETENTION_MANIFEST",
            Self::EmbedBackend => "EE_EMBED_BACKEND",
            Self::EmbedDedupCosineFloor => "EE_EMBED_DEDUP_COSINE_FLOOR",
            Self::EmbedDedupEnabled => "EE_EMBED_DEDUP_ENABLED",
            Self::EmbedDedupHammingK => "EE_EMBED_DEDUP_HAMMING_K",
            Self::EmbedDownload => "EE_EMBED_DOWNLOAD",
            Self::EmbedModelDir => "EE_EMBED_MODEL_DIR",
            Self::EmbedModelPath => "EE_EMBED_MODEL_PATH",
            Self::EmbedRemoteApiKey => "EE_EMBED_REMOTE_API_KEY",
            Self::EmbedRemoteDimension => "EE_EMBED_REMOTE_DIMENSION",
            Self::EmbedRemoteModel => "EE_EMBED_REMOTE_MODEL",
            Self::EmbedRemoteUrl => "EE_EMBED_REMOTE_URL",
            Self::ExperimentalTriad => "EE_EXPERIMENTAL_TRIAD",
            Self::FlightRecorder => "EE_FLIGHT_RECORDER",
            Self::FlightRecorderDir => "EE_FLIGHT_RECORDER_DIR",
            Self::FlightRecorderRetentionDays => "EE_FLIGHT_RECORDER_RETENTION_DAYS",
            Self::Format => "EE_FORMAT",
            Self::GraphMemoryDegradedBelowPct => "EE_GRAPH_MEMORY_DEGRADED_BELOW_PCT",
            Self::GraphMemoryGrowthMultiplierBasisPoints => {
                "EE_GRAPH_MEMORY_GROWTH_MULTIPLIER_BASIS_POINTS"
            }
            Self::GraphMemoryPerAlgorithmCapMb => "EE_GRAPH_MEMORY_PER_ALGORITHM_CAP_MB",
            Self::GraphMemorySnapshotCapMb => "EE_GRAPH_MEMORY_SNAPSHOT_CAP_MB",
            Self::GraphNumaPinDisable => "EE_GRAPH_NUMA_PIN_DISABLE",
            Self::GraphNumaPinNode => "EE_GRAPH_NUMA_PIN_NODE",
            Self::GraphNumaPinPopulate => "EE_GRAPH_NUMA_PIN_POPULATE",
            Self::GraphWitnessesRetentionDays => "EE_GRAPH_WITNESSES_RETENTION_DAYS",
            Self::HarmfulBurstWindowSeconds => "EE_HARMFUL_BURST_WINDOW_SECONDS",
            Self::HarmfulPerSourcePerHour => "EE_HARMFUL_PER_SOURCE_PER_HOUR",
            Self::HookMode => "EE_HOOK_MODE",
            Self::IndexDir => "EE_INDEX_DIR",
            Self::IndexPublishLockRetryAttempts => "EE_INDEX_PUBLISH_LOCK_RETRY_ATTEMPTS",
            Self::Json => "EE_JSON",
            Self::JournalEnabled => "EE_JOURNAL_ENABLED",
            Self::JournalRetentionDays => "EE_JOURNAL_RETENTION_DAYS",
            Self::L2PackCacheBytes => "EE_L2_PACK_CACHE_BYTES",
            Self::L2PackCacheDir => "EE_L2_PACK_CACHE_DIR",
            Self::L2PackCacheDisable => "EE_L2_PACK_CACHE_DISABLE",
            Self::LegacySelectionCertificate => "EE_LEGACY_SELECTION_CERTIFICATE",
            Self::LexicalIndexHugepages => "EE_LEXICAL_INDEX_HUGEPAGES",
            Self::LexicalIndexPinRam => "EE_LEXICAL_INDEX_PIN_RAM",
            Self::LogFormat => "EE_LOG_FORMAT",
            Self::LogJson => "EE_LOG_JSON",
            Self::MaxOutputTokens => "EE_MAX_OUTPUT_TOKENS",
            Self::MaxTokens => "EE_MAX_TOKENS",
            Self::McpMaxRequestBytes => "EE_MCP_MAX_REQUEST_BYTES",
            Self::MeshDiscoveryCacheTtlSeconds => "EE_MESH_DISCOVERY_CACHE_TTL_SECONDS",
            Self::MeshDriftSoftStaleAfter => "EE_MESH_DRIFT_SOFT_STALE_AFTER",
            Self::MeshDriftSoftStaleAfterSeconds => "EE_MESH_DRIFT_SOFT_STALE_AFTER_SECONDS",
            Self::MeshDriftHardStaleAfter => "EE_MESH_DRIFT_HARD_STALE_AFTER",
            Self::MeshDriftHardStaleAfterSeconds => "EE_MESH_DRIFT_HARD_STALE_AFTER_SECONDS",
            Self::MeshEnabled => "EE_MESH_ENABLED",
            Self::MeshHelloPort => "EE_MESH_HELLO_PORT",
            Self::MeshHelloResponderDisabled => "EE_MESH_HELLO_RESPONDER_DISABLED",
            Self::MeshMode => "EE_MESH_MODE",
            Self::MeshTransportDisabled => "EE_MESH_TRANSPORT_DISABLED",
            Self::NoColor => "EE_NO_COLOR",
            Self::OutputFormat => "EE_OUTPUT_FORMAT",
            Self::Profile => "EE_PROFILE",
            Self::PprCacheEntries => "EE_PPR_CACHE_ENTRIES",
            Self::QueryPlanCacheEntries => "EE_QUERY_PLAN_CACHE_ENTRIES",
            Self::QueryMissRetentionDays => "EE_QUERY_MISS_RETENTION_DAYS",
            Self::ReadPoolDisablePin => "EE_READ_POOL_DISABLE_PIN",
            Self::ReadPoolAcquireTimeoutMs => "EE_READ_POOL_ACQUIRE_TIMEOUT_MS",
            Self::ReadPoolIdleTimeoutSeconds => "EE_READ_POOL_IDLE_TIMEOUT_S",
            Self::ReadPoolMaxPinSeconds => "EE_READ_POOL_MAX_PIN_SECONDS",
            Self::ReadPoolSize => "EE_READ_POOL_SIZE",
            Self::ReflectionConsumedRetentionDays => "EE_REFLECTION_CONSUMED_RETENTION_DAYS",
            Self::ReflectionExpiredRetentionDays => "EE_REFLECTION_EXPIRED_RETENTION_DAYS",
            Self::ReflectionHmacKeyId => "EE_REFLECTION_HMAC_KEY_ID",
            Self::ReflectionHmacKeyPath => "EE_REFLECTION_HMAC_KEY_PATH",
            Self::ReflectionHmacRotationGraceSeconds => "EE_REFLECTION_HMAC_ROTATION_GRACE_SECONDS",
            Self::ReflectionRequestListLimit => "EE_REFLECTION_REQUEST_LIST_LIMIT",
            Self::ReflectionRequestShowSourceLimit => "EE_REFLECTION_REQUEST_SHOW_SOURCE_LIMIT",
            Self::ReflectionRequestTtlSeconds => "EE_REFLECTION_REQUEST_TTL_SECONDS",
            Self::ReflectionSourceBudgetBytes => "EE_REFLECTION_SOURCE_BUDGET_BYTES",
            Self::RememberCurationSyncBudgetMs => "EE_REMEMBER_CURATION_SYNC_BUDGET_MS",
            Self::SecurityProfile => "EE_SECURITY_PROFILE",
            Self::ServeToken => "EE_SERVE_TOKEN",
            Self::ScienceBackendPath => "EE_SCIENCE_BACKEND_PATH",
            Self::ShardFanoutEnabled => "EE_SHARD_FANOUT_ENABLED",
            Self::ShardsDir => "EE_SHARDS_DIR",
            Self::TestLogLevel => "EE_TEST_LOG_LEVEL",
            Self::TestLogPath => "EE_TEST_LOG_PATH",
            Self::TestLogTestId => "EE_TEST_LOG_TEST_ID",
            Self::TailscaleBinaryOverride => "EE_TAILSCALE_BINARY_OVERRIDE",
            Self::TailscaleProbeTimeoutMs => "EE_TAILSCALE_PROBE_TIMEOUT_MS",
            Self::TailscaleProbeSocketOverride => "EE_TAILSCALE_PROBE_SOCKET_OVERRIDE",
            Self::TailscaleDiscoveryMode => "EE_TAILSCALE_DISCOVERY_MODE",
            Self::TailscalePeerProbeTimeoutMs => "EE_TAILSCALE_PEER_PROBE_TIMEOUT_MS",
            Self::TailscaleDiscoveryBudgetMs => "EE_TAILSCALE_DISCOVERY_BUDGET_MS",
            Self::TailscaleRespondMode => "EE_TAILSCALE_RESPOND_MODE",
            Self::WorkspaceHygieneAlwaysReviewPatterns => {
                "EE_WORKSPACE_HYGIENE_ALWAYS_REVIEW_PATTERNS"
            }
            Self::WorkspaceHygieneGeneratedPatterns => "EE_WORKSPACE_HYGIENE_GENERATED_PATTERNS",
            Self::WorkspaceHygieneLocalMachinePatterns => {
                "EE_WORKSPACE_HYGIENE_LOCAL_MACHINE_PATTERNS"
            }
            Self::WorkspaceHygieneScratchPatterns => "EE_WORKSPACE_HYGIENE_SCRATCH_PATTERNS",
            Self::WalCheckpointBytesThreshold => "EE_WAL_CHECKPOINT_BYTES_THRESHOLD",
            Self::WriteGroupCommitEnabled => "EE_WRITE_GROUP_COMMIT_ENABLED",
            Self::WriteGroupCommitBatchWindowMs => "EE_WRITE_GROUP_COMMIT_BATCH_WINDOW_MS",
            Self::WriteGroupCommitMaxBatchSize => "EE_WRITE_GROUP_COMMIT_MAX_BATCH_SIZE",
            Self::WriteGroupCommitMaxInflightBytes => "EE_WRITE_GROUP_COMMIT_MAX_INFLIGHT_BYTES",
            Self::Workspace => "EE_WORKSPACE",
            Self::WorkspaceCloseDrainTimeoutSeconds => "EE_WORKSPACE_CLOSE_DRAIN_TIMEOUT_S",
            Self::WorkspaceRegistry => "EE_WORKSPACE_REGISTRY",
        }
    }

    /// Human-readable control surface description.
    #[must_use]
    pub const fn description(self) -> &'static str {
        match self {
            Self::AgentName => "Identify the current agent for scoped memory retrieval.",
            Self::AgentMode => "Use agent-oriented output defaults.",
            Self::AmbientContext => "Enable or disable proactive ambient context hook injection.",
            Self::AmbientContextStateDir => {
                "Override the ambient hook de-duplication state directory."
            }
            Self::AmbientContextVerbosity => {
                "Select quiet, standard, or verbose ambient hook budgets."
            }
            Self::AdaptiveBackoffMs => {
                "Override the SRR5 noisy-neighbor soft backoff delay in milliseconds."
            }
            Self::AdaptiveNoisyP99Ms => {
                "Override the SRR5 per-agent p99 latency threshold for noisy-neighbor backoff."
            }
            Self::AuditLaneBatchMax => "Override the audit-lane writer batch size before flushing.",
            Self::AuditLaneCapacity => "Override the audit-lane producer queue capacity.",
            Self::AuditLaneFlushMs => {
                "Override the audit-lane time-based flush interval in milliseconds."
            }
            Self::WalCheckpointBytesThreshold => {
                "Override the WAL checkpoint warning threshold in bytes."
            }
            Self::WriteGroupCommitEnabled => {
                "Enable bounded group-commit coalescing for durable writes."
            }
            Self::WriteGroupCommitBatchWindowMs => {
                "Override the maximum group-commit batch dwell time in milliseconds."
            }
            Self::WriteGroupCommitMaxBatchSize => {
                "Override the maximum durable writes coalesced into one group commit."
            }
            Self::WriteGroupCommitMaxInflightBytes => {
                "Override the pending payload byte ceiling for group-commit intake."
            }
            Self::CassBinary => "Override the trusted cass import binary path.",
            Self::CassTimeoutSecs => {
                "Override the CASS subprocess timeout in seconds for import and discovery calls."
            }
            Self::CurationAutoPromoteConfidenceFloor => {
                "Override the minimum confidence required by curation auto-promotion."
            }
            Self::CurationAutoPromoteMaxPerRun => {
                "Override the maximum curation candidates auto-promotion may accept per run."
            }
            Self::CurationDerivedPreviewLimit => {
                "Override the derived-candidate preview/reject listing limit."
            }
            Self::DaemonEnableEcho => "Enable the diagnostic `ee.daemon.echo` round-trip method.",
            Self::DaemonMaxInflight => {
                "Override the cap on in-flight `ee daemon` worker threads; saturated accepts emit `daemon_overloaded`."
            }
            Self::DaemonSearchTimeoutMs => {
                "Override the bounded deadline `ee search --use-daemon` gives the daemon before falling back to in-process search."
            }
            Self::DaemonWarm => {
                "Set to `off` to stop a workspace-bound `ee daemon` from warming its search stack at startup."
            }
            Self::DatabasePath => "Override the configured storage database path.",
            Self::DemoEvidenceRoot => "Override the demo evidence storage root.",
            Self::DiagForceCapabilityGap => {
                "Force selected capability probes to report build-gap diagnostics."
            }
            Self::DisableToon => "Disable TOON output capability reporting and auto-selection.",
            Self::DisableAdaptive => {
                "Disable SRR5 swarm adaptive prefetch and scheduling without editing config."
            }
            Self::DisableRememberSearchNeighbors => {
                "Disable Frankensearch neighbors during remember-time proposal."
            }
            Self::DoctorBlastRadius => {
                "Override the doctor fix blast-radius roots with colon-separated absolute paths."
            }
            Self::E2eRetentionManifest => {
                "Override the retained-artifact manifest path used by diagnostics."
            }
            Self::EmbedDedupCosineFloor => {
                "Set the cosine-similarity floor for insert-time embedding dedup confirmation."
            }
            Self::EmbedBackend => {
                "Select the embedding backend: local for the bundled model, or remote for an OpenAI-compatible endpoint."
            }
            Self::EmbedDedupEnabled => {
                "Enable insert-time embedding deduplication after storage and write-path gates are wired."
            }
            Self::EmbedDedupHammingK => {
                "Set the maximum SimHash Hamming distance admitted to dedup cosine confirmation."
            }
            Self::EmbedDownload => {
                "Control bundled embedding model download behavior with auto or off."
            }
            Self::EmbedModelDir => {
                "Override the bundled embedding model cache directory used by ee."
            }
            Self::EmbedModelPath => {
                "Fault-injection path used to simulate an unavailable search embedder; this does not load alternate models."
            }
            Self::EmbedRemoteApiKey => {
                "Optional bearer token sent to the remote embedding endpoint; the value is never printed."
            }
            Self::EmbedRemoteDimension => {
                "Pin the remote embedding dimension instead of discovering it from the first response."
            }
            Self::EmbedRemoteModel => {
                "Model tag requested from the remote embedding endpoint, for example all-minilm."
            }
            Self::EmbedRemoteUrl => {
                "Base URL or full endpoint of an OpenAI-compatible /v1/embeddings server."
            }
            Self::ExperimentalTriad => {
                "Compatibility no-op for the promoted ee pack/note/why aliases."
            }
            Self::FlightRecorder => {
                "Enable the redacted command flight recorder for ee subcommands."
            }
            Self::FlightRecorderDir => {
                "Override the directory where flight recorder traces are written."
            }
            Self::FlightRecorderRetentionDays => {
                "Override the flight recorder trace retention window in days."
            }
            Self::Format => "Select the default output renderer.",
            Self::GraphMemoryDegradedBelowPct => {
                "Override the graph snapshot advisory threshold as a percent of the snapshot cap."
            }
            Self::GraphMemoryGrowthMultiplierBasisPoints => {
                "Override the graph snapshot in-build growth tripwire ratio in basis points."
            }
            Self::GraphMemoryPerAlgorithmCapMb => {
                "Override the per-algorithm graph working-set cap in MiB."
            }
            Self::GraphMemorySnapshotCapMb => "Override the graph snapshot admission cap in MiB.",
            Self::GraphNumaPinDisable => {
                "Disable graph snapshot NUMA pinning without editing config."
            }
            Self::GraphNumaPinNode => {
                "Select auto NUMA placement or an explicit non-negative NUMA node for graph snapshot pinning."
            }
            Self::GraphNumaPinPopulate => {
                "Control whether graph snapshot loading pre-faults pages during NUMA pinning."
            }
            Self::GraphWitnessesRetentionDays => {
                "Override the default graph algorithm witness retention window in days."
            }
            Self::HarmfulBurstWindowSeconds => {
                "Override the harmful feedback burst window in seconds."
            }
            Self::HarmfulPerSourcePerHour => "Override the harmful feedback rate limit per source.",
            Self::HookMode => "Use hook-oriented machine output defaults.",
            Self::IndexDir => "Override the configured search index directory.",
            Self::IndexPublishLockRetryAttempts => {
                "Override index publish advisory-lock retry attempts."
            }
            Self::Json => "Request JSON output from renderer auto-detection.",
            Self::JournalEnabled => "Enable or disable append-only agent journal capture.",
            Self::JournalRetentionDays => {
                "Override the append-only journal retention window in days."
            }
            Self::L2PackCacheBytes => "Override the L2 pack cache byte cap per workspace.",
            Self::L2PackCacheDir => "Override the L2 pack cache root directory.",
            Self::L2PackCacheDisable => "Disable L2 pack cache lookup and writes.",
            Self::LegacySelectionCertificate => {
                "Include the legacy selectionCertificate field in context JSON."
            }
            Self::LexicalIndexHugepages => {
                "Request transparent hugepage hints for opt-in lexical index RAM-tier pinning."
            }
            Self::LexicalIndexPinRam => "Opt in to lexical index RAM-tier page-cache population.",
            Self::LogFormat => "Select structured log format.",
            Self::LogJson => "Enable JSON command-start logs on stderr.",
            Self::MaxOutputTokens => {
                "Cap estimated response tokens for machine output (output governor ceiling)."
            }
            Self::MaxTokens => "Override the default context pack token budget.",
            Self::McpMaxRequestBytes => {
                "Override the MCP stdio JSON-RPC request and response byte cap."
            }
            Self::MeshDiscoveryCacheTtlSeconds => {
                "Override the mesh autodiscovery cache TTL in seconds."
            }
            Self::MeshDriftSoftStaleAfter => {
                "Override missed mesh hello probes before soft-stale drift grace."
            }
            Self::MeshDriftSoftStaleAfterSeconds => {
                "Override seconds since last successful mesh probe before soft-stale drift grace."
            }
            Self::MeshDriftHardStaleAfter => {
                "Override missed mesh hello probes before hard-stale drift."
            }
            Self::MeshDriftHardStaleAfterSeconds => {
                "Override seconds since last successful mesh probe before hard-stale drift."
            }
            Self::MeshEnabled => "Enable optional mesh-memory surfaces.",
            Self::MeshHelloPort => {
                "Override the mesh hello responder bind port on the local Tailscale address."
            }
            Self::MeshHelloResponderDisabled => {
                "Disable the mesh hello responder lifecycle job while leaving other mesh surfaces enabled."
            }
            Self::MeshMode => "Select the default mesh command mode.",
            Self::MeshTransportDisabled => {
                "Disable authenticated mesh TCP connect and accepted-session handling before network or authentication work."
            }
            Self::NoColor => "Disable colored diagnostics.",
            Self::OutputFormat => "Select the default output renderer.",
            Self::Profile => "Override the default context pack profile.",
            Self::PprCacheEntries => "Override the in-process PPR prefetch cache entry cap.",
            Self::QueryPlanCacheEntries => {
                "Override the in-process EQL query plan cache entry cap."
            }
            Self::QueryMissRetentionDays => {
                "Override the query-miss ledger retention window used by ee learn gaps."
            }
            Self::ReadPoolDisablePin => "Disable read-side snapshot pinning.",
            Self::ReadPoolAcquireTimeoutMs => {
                "Override the read-side connection pool acquire timeout in milliseconds."
            }
            Self::ReadPoolIdleTimeoutSeconds => {
                "Override the read-side connection pool idle timeout in seconds."
            }
            Self::ReadPoolMaxPinSeconds => {
                "Override the read-side snapshot pin maximum lifetime in seconds."
            }
            Self::ReadPoolSize => "Override the read-side connection pool size.",
            Self::ReflectionConsumedRetentionDays => {
                "Override retention for consumed reflection requests in days."
            }
            Self::ReflectionExpiredRetentionDays => {
                "Override retention for expired reflection requests in days."
            }
            Self::ReflectionHmacKeyId => "Select the reflection request HMAC key identifier.",
            Self::ReflectionHmacKeyPath => {
                "Select the reflection request HMAC key file path without exposing key material."
            }
            Self::ReflectionHmacRotationGraceSeconds => {
                "Override reflection HMAC key rotation grace in seconds."
            }
            Self::ReflectionRequestListLimit => {
                "Override the default reflection request list limit."
            }
            Self::ReflectionRequestShowSourceLimit => {
                "Override how many source-package entries reflection request show may include."
            }
            Self::ReflectionRequestTtlSeconds => {
                "Override the default reflection request TTL in seconds."
            }
            Self::ReflectionSourceBudgetBytes => {
                "Override the reflection source-package byte budget."
            }
            Self::RememberCurationSyncBudgetMs => {
                "Override remember-time curation sync budget in milliseconds."
            }
            Self::SecurityProfile => "Select security profile.",
            Self::ServeToken => {
                "Configure the bearer token required by the localhost serve adapter."
            }
            Self::ScienceBackendPath => {
                "Configure an optional science analytics backend path; missing paths report backend-unavailable."
            }
            Self::ShardFanoutEnabled => {
                "Enable read-only shard fan-out planning and, after migration, per-workspace shard routing."
            }
            Self::ShardsDir => {
                "Override the per-workspace shard directory used by shard fan-out planning."
            }
            Self::TestLogLevel => "Control structured test-log verbosity.",
            Self::TestLogPath => "Enable structured test logging at this JSONL path.",
            Self::TestLogTestId => "Name the active structured test-log scenario.",
            Self::TailscaleBinaryOverride => {
                "Test-only override for the tailscale binary used by fake-tailnet harnesses."
            }
            Self::TailscaleProbeTimeoutMs => "Override the local Tailscale probe timeout budget.",
            Self::TailscaleProbeSocketOverride => {
                "Test-only override for fake mesh hello responder socket discovery."
            }
            Self::TailscaleDiscoveryMode => {
                "Select the caller-side mesh peer discovery policy (service_tag, auto_admit, allowlist)."
            }
            Self::TailscalePeerProbeTimeoutMs => {
                "Override the per-peer Tailscale hello probe timeout budget."
            }
            Self::TailscaleDiscoveryBudgetMs => {
                "Override the total Tailscale peer autodiscovery wall-clock budget."
            }
            Self::TailscaleRespondMode => {
                "Select the responder-side mesh discovery consent policy (service_tag, auto_admit, allowlist)."
            }
            Self::WorkspaceHygieneAlwaysReviewPatterns => {
                "Add local workspace-hygiene patterns that force matching paths into human review."
            }
            Self::WorkspaceHygieneGeneratedPatterns => {
                "Add local workspace-hygiene generated-artifact path patterns."
            }
            Self::WorkspaceHygieneLocalMachinePatterns => {
                "Add local workspace-hygiene machine-local artifact path patterns."
            }
            Self::WorkspaceHygieneScratchPatterns => {
                "Add local workspace-hygiene scratch-artifact path patterns."
            }
            Self::Workspace => "Override workspace root discovery.",
            Self::WorkspaceCloseDrainTimeoutSeconds => {
                "Override workspace-close wait time for read snapshot pins in seconds."
            }
            Self::WorkspaceRegistry => "Override the workspace alias registry database path.",
        }
    }

    /// Default value, when the variable has a registry-defined default.
    #[must_use]
    pub const fn default_value(self) -> Option<&'static str> {
        match self {
            Self::AmbientContext => Some("true"),
            Self::AmbientContextVerbosity => Some("standard"),
            Self::AdaptiveBackoffMs => Some("25"),
            Self::AdaptiveNoisyP99Ms => Some("200"),
            Self::MeshMode => Some("off"),
            Self::MeshEnabled => Some("false"),
            Self::ShardFanoutEnabled => Some("false"),
            Self::AuditLaneBatchMax => Some("64"),
            Self::AuditLaneCapacity => Some("1024"),
            Self::AuditLaneFlushMs => Some("5"),
            Self::TailscaleProbeTimeoutMs => Some("1500"),
            Self::MeshDiscoveryCacheTtlSeconds => Some("30"),
            Self::MeshDriftSoftStaleAfter => Some("1"),
            Self::MeshDriftSoftStaleAfterSeconds => Some("300"),
            Self::MeshDriftHardStaleAfter => Some("3"),
            Self::MeshDriftHardStaleAfterSeconds => Some("3600"),
            Self::MeshHelloPort => Some("41888"),
            Self::MeshHelloResponderDisabled => Some("false"),
            Self::MeshTransportDisabled => Some("false"),
            Self::TailscaleDiscoveryMode => Some("service_tag"),
            Self::TailscalePeerProbeTimeoutMs => Some("750"),
            Self::TailscaleDiscoveryBudgetMs => Some("5000"),
            Self::TailscaleRespondMode => Some("service_tag"),
            Self::EmbedBackend => Some("local"),
            Self::EmbedDedupCosineFloor => Some("0.97"),
            Self::EmbedDedupEnabled => Some("false"),
            Self::EmbedDedupHammingK => Some("12"),
            Self::EmbedDownload => Some("auto"),
            Self::FlightRecorder => Some("false"),
            Self::FlightRecorderRetentionDays => Some("7"),
            Self::LexicalIndexHugepages => Some("false"),
            Self::LexicalIndexPinRam => Some("false"),
            Self::PprCacheEntries => Some("4096"),
            Self::QueryPlanCacheEntries => Some("1024"),
            Self::QueryMissRetentionDays => Some("30"),
            Self::GraphMemoryDegradedBelowPct => Some("80"),
            Self::GraphMemoryGrowthMultiplierBasisPoints => Some("15000"),
            Self::GraphMemoryPerAlgorithmCapMb => Some("100"),
            Self::GraphMemorySnapshotCapMb => Some("250"),
            Self::GraphNumaPinDisable => Some("false"),
            Self::GraphNumaPinNode => Some("auto"),
            Self::GraphNumaPinPopulate => Some("true"),
            Self::GraphWitnessesRetentionDays => Some("30"),
            Self::ReadPoolAcquireTimeoutMs => Some("5000"),
            Self::ReadPoolMaxPinSeconds => Some("30"),
            Self::WalCheckpointBytesThreshold => Some("67108864"),
            Self::WriteGroupCommitEnabled => Some("false"),
            Self::WriteGroupCommitBatchWindowMs => Some("2"),
            Self::WriteGroupCommitMaxBatchSize => Some("64"),
            Self::WriteGroupCommitMaxInflightBytes => Some("4194304"),
            Self::WorkspaceCloseDrainTimeoutSeconds => Some("5"),
            Self::IndexPublishLockRetryAttempts => Some("200"),
            Self::JournalEnabled => Some("true"),
            Self::JournalRetentionDays => Some("14"),
            Self::CurationAutoPromoteConfidenceFloor => Some("0.80"),
            Self::CurationAutoPromoteMaxPerRun => Some("10"),
            Self::CurationDerivedPreviewLimit => Some("20"),
            Self::ReflectionConsumedRetentionDays => Some("30"),
            Self::ReflectionExpiredRetentionDays => Some("7"),
            Self::ReflectionHmacRotationGraceSeconds => Some("86400"),
            Self::ReflectionRequestListLimit => Some("50"),
            Self::ReflectionRequestShowSourceLimit => Some("20"),
            Self::ReflectionRequestTtlSeconds => Some("86400"),
            Self::ReflectionSourceBudgetBytes => Some("65536"),
            Self::RememberCurationSyncBudgetMs => Some("50"),
            Self::McpMaxRequestBytes => Some("16777216"),
            Self::DaemonEnableEcho => Some("false"),
            Self::DaemonMaxInflight => Some("32"),
            Self::DaemonSearchTimeoutMs => Some("5000"),
            Self::DaemonWarm => Some("on"),
            Self::DisableAdaptive => Some("false"),
            Self::CassTimeoutSecs => Some("30"),
            _ => None,
        }
    }

    /// Whether capabilities output may include this variable's current value.
    #[must_use]
    pub const fn exposes_value(self) -> bool {
        !matches!(
            self,
            Self::EmbedRemoteApiKey | Self::ReflectionHmacKeyPath | Self::ServeToken
        )
    }

    /// Broad documentation category for agent docs and env-var catalogs.
    #[must_use]
    pub const fn category(self) -> &'static str {
        match self {
            Self::AmbientContext | Self::AmbientContextStateDir | Self::AmbientContextVerbosity => {
                "hooks"
            }
            Self::CassBinary | Self::CassTimeoutSecs => "integration",
            Self::CurationAutoPromoteConfidenceFloor
            | Self::CurationAutoPromoteMaxPerRun
            | Self::CurationDerivedPreviewLimit
            | Self::RememberCurationSyncBudgetMs => "curation",
            Self::DatabasePath
            | Self::DemoEvidenceRoot
            | Self::DoctorBlastRadius
            | Self::E2eRetentionManifest
            | Self::FlightRecorderDir
            | Self::IndexDir
            | Self::L2PackCacheDir
            | Self::ReflectionHmacKeyPath
            | Self::ShardsDir
            | Self::Workspace
            | Self::WorkspaceRegistry => "paths",
            Self::DaemonEnableEcho | Self::DiagForceCapabilityGap => "diagnostics",
            Self::DaemonSearchTimeoutMs | Self::DaemonWarm => "performance",
            Self::AgentMode
            | Self::AgentName
            | Self::DisableToon
            | Self::ExperimentalTriad
            | Self::Format
            | Self::HookMode
            | Self::Json
            | Self::LegacySelectionCertificate
            | Self::MaxOutputTokens
            | Self::NoColor
            | Self::OutputFormat => "output",
            Self::FlightRecorder
            | Self::FlightRecorderRetentionDays
            | Self::LogFormat
            | Self::LogJson
            | Self::TestLogLevel
            | Self::TestLogPath
            | Self::TestLogTestId => "diagnostics",
            Self::EmbedBackend
            | Self::EmbedDedupCosineFloor
            | Self::EmbedDedupEnabled
            | Self::EmbedDedupHammingK
            | Self::EmbedDownload
            | Self::EmbedModelDir
            | Self::EmbedModelPath
            | Self::EmbedRemoteApiKey
            | Self::EmbedRemoteDimension
            | Self::EmbedRemoteModel
            | Self::EmbedRemoteUrl => "embeddings",
            Self::JournalEnabled => "memory",
            Self::MeshEnabled
            | Self::MeshMode
            | Self::MeshDiscoveryCacheTtlSeconds
            | Self::MeshDriftSoftStaleAfter
            | Self::MeshDriftSoftStaleAfterSeconds
            | Self::MeshDriftHardStaleAfter
            | Self::MeshDriftHardStaleAfterSeconds
            | Self::MeshHelloPort
            | Self::MeshHelloResponderDisabled
            | Self::MeshTransportDisabled
            | Self::TailscaleBinaryOverride
            | Self::TailscaleProbeTimeoutMs
            | Self::TailscaleProbeSocketOverride
            | Self::TailscaleDiscoveryMode
            | Self::TailscalePeerProbeTimeoutMs
            | Self::TailscaleDiscoveryBudgetMs
            | Self::TailscaleRespondMode => "mesh",
            Self::ReflectionConsumedRetentionDays
            | Self::ReflectionExpiredRetentionDays
            | Self::ReflectionHmacKeyId
            | Self::ReflectionHmacRotationGraceSeconds
            | Self::ReflectionRequestListLimit
            | Self::ReflectionRequestShowSourceLimit
            | Self::ReflectionRequestTtlSeconds
            | Self::ReflectionSourceBudgetBytes => "reflection",
            Self::HarmfulBurstWindowSeconds
            | Self::AdaptiveBackoffMs
            | Self::AdaptiveNoisyP99Ms
            | Self::AuditLaneBatchMax
            | Self::AuditLaneCapacity
            | Self::AuditLaneFlushMs
            | Self::DaemonMaxInflight
            | Self::GraphMemoryDegradedBelowPct
            | Self::GraphMemoryGrowthMultiplierBasisPoints
            | Self::GraphMemoryPerAlgorithmCapMb
            | Self::GraphMemorySnapshotCapMb
            | Self::GraphNumaPinDisable
            | Self::GraphNumaPinNode
            | Self::GraphNumaPinPopulate
            | Self::GraphWitnessesRetentionDays
            | Self::HarmfulPerSourcePerHour
            | Self::L2PackCacheBytes
            | Self::L2PackCacheDisable
            | Self::LexicalIndexHugepages
            | Self::LexicalIndexPinRam
            | Self::MaxTokens
            | Self::McpMaxRequestBytes
            | Self::Profile
            | Self::PprCacheEntries
            | Self::QueryPlanCacheEntries
            | Self::QueryMissRetentionDays
            | Self::ReadPoolDisablePin
            | Self::ReadPoolAcquireTimeoutMs
            | Self::ReadPoolIdleTimeoutSeconds
            | Self::ReadPoolMaxPinSeconds
            | Self::ReadPoolSize
            | Self::WalCheckpointBytesThreshold
            | Self::WriteGroupCommitEnabled
            | Self::WriteGroupCommitBatchWindowMs
            | Self::WriteGroupCommitMaxBatchSize
            | Self::WriteGroupCommitMaxInflightBytes
            | Self::WorkspaceCloseDrainTimeoutSeconds
            | Self::DisableAdaptive
            | Self::DisableRememberSearchNeighbors
            | Self::IndexPublishLockRetryAttempts => "tuning",
            Self::JournalRetentionDays => "tuning",
            Self::ScienceBackendPath => "integration",
            Self::ShardFanoutEnabled => "storage",
            Self::SecurityProfile
            | Self::ServeToken
            | Self::WorkspaceHygieneAlwaysReviewPatterns
            | Self::WorkspaceHygieneGeneratedPatterns
            | Self::WorkspaceHygieneLocalMachinePatterns
            | Self::WorkspaceHygieneScratchPatterns => "policy",
        }
    }

    /// Parse this variable through [`FromStr`].
    #[must_use]
    pub fn parse_into<T>(self) -> Option<T>
    where
        T: FromStr,
    {
        read(self).and_then(|value| value.parse::<T>().ok())
    }
}

/// Read an `EE_*` environment variable as UTF-8.
#[must_use]
pub fn read(var: EnvVar) -> Option<String> {
    read_os(var).and_then(|value| value.into_string().ok())
}

/// Read an `EE_*` environment variable as an OS string.
#[must_use]
pub fn read_os(var: EnvVar) -> Option<OsString> {
    let value = std::env::var_os(var.name());
    trace_env_read(var, value.as_ref(), "process_env");
    value
}

/// Read an `EE_*` environment variable or its registry-defined default.
#[must_use]
pub fn read_or_default(var: EnvVar) -> Option<String> {
    if let Some(value) = read(var) {
        return Some(value);
    }

    let default = var.default_value().map(str::to_owned);
    if let Some(value) = default.as_deref() {
        tracing::trace!(
            var_name = var.name(),
            found = true,
            value_hash = %hash_bytes(value.as_bytes()),
            source = "registry_default",
            "ee_env_registry_read"
        );
    }
    default
}

/// Return whether an `EE_*` environment variable is present.
#[must_use]
pub fn is_set(var: EnvVar) -> bool {
    read_os(var).is_some()
}

fn trace_env_read(var: EnvVar, value: Option<&OsString>, source: &'static str) {
    let value_hash = value.map(|value| hash_os_value(value.as_os_str()));
    tracing::trace!(
        var_name = var.name(),
        found = value.is_some(),
        value_hash = value_hash.as_deref().unwrap_or(""),
        source,
        "ee_env_registry_read"
    );
}

fn hash_bytes(bytes: &[u8]) -> String {
    format!("blake3:{}", blake3::hash(bytes).to_hex())
}

#[cfg(unix)]
fn hash_os_value(value: &std::ffi::OsStr) -> String {
    use std::os::unix::ffi::OsStrExt;

    hash_bytes(value.as_bytes())
}

#[cfg(not(unix))]
fn hash_os_value(value: &std::ffi::OsStr) -> String {
    hash_bytes(value.to_string_lossy().as_bytes())
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;

    use super::{EmbeddingTrapEnvVar, EnvVar};

    type TestResult = Result<(), String>;

    #[test]
    fn every_env_var_has_name_and_description() -> TestResult {
        for var in EnvVar::all() {
            if !var.name().starts_with("EE_") {
                return Err(format!("{} does not start with EE_", var.name()));
            }
            if var.description().trim().is_empty() {
                return Err(format!("{} has an empty description", var.name()));
            }
        }
        Ok(())
    }

    #[test]
    fn env_var_names_are_unique() -> TestResult {
        let mut names = BTreeSet::new();
        for var in EnvVar::all() {
            if !names.insert(var.name()) {
                return Err(format!("duplicate env var registered: {}", var.name()));
            }
        }
        Ok(())
    }

    #[test]
    fn embedding_trap_env_vars_are_registered_outside_the_runtime_ee_surface() -> TestResult {
        let mut names = BTreeSet::new();
        for var in EmbeddingTrapEnvVar::all() {
            let name = var.name();
            if name.starts_with("EE_") {
                return Err(format!("{name} must not be a runtime EE_* override"));
            }
            if !names.insert(name) {
                return Err(format!(
                    "duplicate embedding trap env var registered: {name}"
                ));
            }
            if var.category() != "embeddings" {
                return Err(format!("{name} must be categorized as embeddings"));
            }
            if var.description().trim().is_empty() {
                return Err(format!("{name} is missing a description"));
            }
        }
        let expected = BTreeSet::from(["EMBEDDING_MODEL", "OPENAI_API_KEY"]);
        if names == expected {
            Ok(())
        } else {
            Err(format!(
                "detected-but-ignored embedding env registry drifted: {names:?}"
            ))
        }
    }

    #[test]
    fn ambient_context_env_vars_are_registered_with_defaults() -> TestResult {
        let expected = [
            (EnvVar::AmbientContext, "EE_AMBIENT_CONTEXT", Some("true")),
            (
                EnvVar::AmbientContextVerbosity,
                "EE_AMBIENT_CONTEXT_VERBOSITY",
                Some("standard"),
            ),
            (
                EnvVar::AmbientContextStateDir,
                "EE_AMBIENT_CONTEXT_STATE_DIR",
                None,
            ),
        ];

        for (var, name, default) in expected {
            if !EnvVar::all().contains(&var) {
                return Err(format!("{name} missing from registry order"));
            }
            if var.name() != name {
                return Err(format!("unexpected env name for {var:?}: {}", var.name()));
            }
            if var.default_value() != default {
                return Err(format!("{name} default drifted"));
            }
            if var.category() != "hooks" {
                return Err(format!("{name} must be categorized as hooks"));
            }
            if !var.exposes_value() {
                return Err(format!("{name} should expose non-secret effective values"));
            }
        }
        Ok(())
    }

    #[test]
    fn registry_default_is_available() -> TestResult {
        let value = EnvVar::RememberCurationSyncBudgetMs
            .default_value()
            .ok_or_else(|| "remember curation budget default missing".to_owned())?;
        if value == "50" {
            Ok(())
        } else {
            Err(format!(
                "unexpected remember curation budget default: {value}"
            ))
        }
    }

    #[test]
    fn curation_policy_env_vars_are_registered_with_defaults() -> TestResult {
        let expected = [
            (
                EnvVar::CurationDerivedPreviewLimit,
                "EE_CURATION_DERIVED_PREVIEW_LIMIT",
                "20",
            ),
            (
                EnvVar::CurationAutoPromoteMaxPerRun,
                "EE_CURATION_AUTO_PROMOTE_MAX_PER_RUN",
                "10",
            ),
            (
                EnvVar::CurationAutoPromoteConfidenceFloor,
                "EE_CURATION_AUTO_PROMOTE_CONFIDENCE_FLOOR",
                "0.80",
            ),
        ];

        for (var, name, default) in expected {
            if !EnvVar::all().contains(&var) {
                return Err(format!("{name} missing from registry order"));
            }
            if var.name() != name {
                return Err(format!("unexpected env name for {var:?}: {}", var.name()));
            }
            if var.default_value() != Some(default) {
                return Err(format!("{name} default drifted"));
            }
            if var.category() != "curation" {
                return Err(format!("{name} must be categorized as curation"));
            }
        }
        Ok(())
    }

    #[test]
    fn journal_env_vars_are_registered_with_defaults() -> TestResult {
        let expected = [
            (
                EnvVar::JournalEnabled,
                "EE_JOURNAL_ENABLED",
                "true",
                "memory",
            ),
            (
                EnvVar::JournalRetentionDays,
                "EE_JOURNAL_RETENTION_DAYS",
                "14",
                "tuning",
            ),
        ];

        for (var, name, default, category) in expected {
            if !EnvVar::all().contains(&var) {
                return Err(format!("{name} missing from registry order"));
            }
            if var.name() != name {
                return Err(format!("unexpected env name for {var:?}: {}", var.name()));
            }
            if var.default_value() != Some(default) {
                return Err(format!("{name} default drifted"));
            }
            if var.category() != category {
                return Err(format!("{name} must be categorized as {category}"));
            }
            if !var.exposes_value() {
                return Err(format!("{name} should expose non-secret effective values"));
            }
        }
        Ok(())
    }

    #[test]
    fn swarm_adaptive_env_vars_are_registered_with_defaults() -> TestResult {
        let expected = [
            (EnvVar::AdaptiveBackoffMs, "EE_ADAPTIVE_BACKOFF_MS", "25"),
            (
                EnvVar::AdaptiveNoisyP99Ms,
                "EE_ADAPTIVE_NOISY_P99_MS",
                "200",
            ),
            (EnvVar::DisableAdaptive, "EE_DISABLE_ADAPTIVE", "false"),
        ];

        for (var, name, default) in expected {
            if !EnvVar::all().contains(&var) {
                return Err(format!("{name} missing from registry order"));
            }
            if var.name() != name {
                return Err(format!("unexpected env name for {var:?}: {}", var.name()));
            }
            if var.default_value() != Some(default) {
                return Err(format!("{name} default drifted"));
            }
            if var.category() != "tuning" {
                return Err(format!("{name} must be categorized as tuning"));
            }
            if !var.exposes_value() {
                return Err(format!("{name} should expose non-secret effective values"));
            }
        }
        Ok(())
    }

    #[test]
    fn graph_numa_pin_env_vars_are_registered_with_defaults() -> TestResult {
        let expected = [
            (
                EnvVar::GraphNumaPinDisable,
                "EE_GRAPH_NUMA_PIN_DISABLE",
                "false",
            ),
            (EnvVar::GraphNumaPinNode, "EE_GRAPH_NUMA_PIN_NODE", "auto"),
            (
                EnvVar::GraphNumaPinPopulate,
                "EE_GRAPH_NUMA_PIN_POPULATE",
                "true",
            ),
        ];

        for (var, name, default) in expected {
            if !EnvVar::all().contains(&var) {
                return Err(format!("{name} missing from registry order"));
            }
            if var.name() != name {
                return Err(format!("unexpected env name for {var:?}: {}", var.name()));
            }
            if var.default_value() != Some(default) {
                return Err(format!("{name} default drifted"));
            }
            if var.category() != "tuning" {
                return Err(format!("{name} must be categorized as tuning"));
            }
        }
        Ok(())
    }

    #[test]
    fn reflection_policy_env_vars_are_registered_with_safe_exposure() -> TestResult {
        let expected = [
            (
                EnvVar::ReflectionSourceBudgetBytes,
                "EE_REFLECTION_SOURCE_BUDGET_BYTES",
                "65536",
            ),
            (
                EnvVar::ReflectionRequestTtlSeconds,
                "EE_REFLECTION_REQUEST_TTL_SECONDS",
                "86400",
            ),
            (
                EnvVar::ReflectionRequestListLimit,
                "EE_REFLECTION_REQUEST_LIST_LIMIT",
                "50",
            ),
            (
                EnvVar::ReflectionRequestShowSourceLimit,
                "EE_REFLECTION_REQUEST_SHOW_SOURCE_LIMIT",
                "20",
            ),
            (
                EnvVar::ReflectionExpiredRetentionDays,
                "EE_REFLECTION_EXPIRED_RETENTION_DAYS",
                "7",
            ),
            (
                EnvVar::ReflectionConsumedRetentionDays,
                "EE_REFLECTION_CONSUMED_RETENTION_DAYS",
                "30",
            ),
            (
                EnvVar::ReflectionHmacRotationGraceSeconds,
                "EE_REFLECTION_HMAC_ROTATION_GRACE_SECONDS",
                "86400",
            ),
        ];

        for (var, name, default) in expected {
            if !EnvVar::all().contains(&var) {
                return Err(format!("{name} missing from registry order"));
            }
            if var.name() != name {
                return Err(format!("unexpected env name for {var:?}: {}", var.name()));
            }
            if var.default_value() != Some(default) {
                return Err(format!("{name} default drifted"));
            }
            if var.category() != "reflection" {
                return Err(format!("{name} must be categorized as reflection"));
            }
            if !var.exposes_value() {
                return Err(format!("{name} should expose non-secret effective values"));
            }
        }

        for var in [EnvVar::ReflectionHmacKeyId, EnvVar::ReflectionHmacKeyPath] {
            if !EnvVar::all().contains(&var) {
                return Err(format!("{} missing from registry order", var.name()));
            }
            if var.default_value().is_some() {
                return Err(format!("{} must not have a baked-in default", var.name()));
            }
        }
        if EnvVar::ReflectionHmacKeyId.category() != "reflection" {
            return Err("EE_REFLECTION_HMAC_KEY_ID must be categorized as reflection".to_owned());
        }
        if EnvVar::ReflectionHmacKeyPath.category() != "paths" {
            return Err("EE_REFLECTION_HMAC_KEY_PATH must be categorized as paths".to_owned());
        }
        if EnvVar::ReflectionHmacKeyPath.exposes_value() {
            return Err("EE_REFLECTION_HMAC_KEY_PATH must not expose currentValue".to_owned());
        }
        Ok(())
    }

    #[test]
    fn shard_fanout_env_vars_are_registered() -> TestResult {
        if !EnvVar::all().contains(&EnvVar::ShardFanoutEnabled) {
            return Err("EE_SHARD_FANOUT_ENABLED missing from registry order".to_owned());
        }
        if !EnvVar::all().contains(&EnvVar::ShardsDir) {
            return Err("EE_SHARDS_DIR missing from registry order".to_owned());
        }
        if EnvVar::ShardFanoutEnabled.default_value() != Some("false") {
            return Err("EE_SHARD_FANOUT_ENABLED must default to false".to_owned());
        }
        if EnvVar::ShardsDir.category() != "paths" {
            return Err("EE_SHARDS_DIR must be categorized as a path override".to_owned());
        }
        Ok(())
    }

    #[test]
    fn embed_dedup_env_vars_are_registered_disabled_by_default() -> TestResult {
        if !EnvVar::all().contains(&EnvVar::EmbedDedupEnabled) {
            return Err("EE_EMBED_DEDUP_ENABLED missing from registry order".to_owned());
        }
        if !EnvVar::all().contains(&EnvVar::EmbedDedupHammingK) {
            return Err("EE_EMBED_DEDUP_HAMMING_K missing from registry order".to_owned());
        }
        if !EnvVar::all().contains(&EnvVar::EmbedDedupCosineFloor) {
            return Err("EE_EMBED_DEDUP_COSINE_FLOOR missing from registry order".to_owned());
        }
        if EnvVar::EmbedDedupEnabled.default_value() != Some("false") {
            return Err("EE_EMBED_DEDUP_ENABLED must default to false".to_owned());
        }
        if EnvVar::EmbedDedupHammingK.default_value() != Some("12") {
            return Err("EE_EMBED_DEDUP_HAMMING_K must default to 12".to_owned());
        }
        if EnvVar::EmbedDedupCosineFloor.default_value() != Some("0.97") {
            return Err("EE_EMBED_DEDUP_COSINE_FLOOR must default to 0.97".to_owned());
        }
        if EnvVar::EmbedDedupEnabled.category() != "embeddings" {
            return Err("embed dedup vars must be categorized as embeddings".to_owned());
        }
        Ok(())
    }

    #[test]
    fn embed_download_env_vars_are_registered_with_safe_defaults() -> TestResult {
        if !EnvVar::all().contains(&EnvVar::EmbedDownload) {
            return Err("EE_EMBED_DOWNLOAD missing from registry order".to_owned());
        }
        if !EnvVar::all().contains(&EnvVar::EmbedModelDir) {
            return Err("EE_EMBED_MODEL_DIR missing from registry order".to_owned());
        }
        if EnvVar::EmbedDownload.name() != "EE_EMBED_DOWNLOAD" {
            return Err("EE_EMBED_DOWNLOAD name mismatch".to_owned());
        }
        if EnvVar::EmbedModelDir.name() != "EE_EMBED_MODEL_DIR" {
            return Err("EE_EMBED_MODEL_DIR name mismatch".to_owned());
        }
        if EnvVar::EmbedDownload.default_value() != Some("auto") {
            return Err("EE_EMBED_DOWNLOAD must default to auto".to_owned());
        }
        if EnvVar::EmbedModelDir.default_value().is_some() {
            return Err("EE_EMBED_MODEL_DIR must not have a baked-in path default".to_owned());
        }
        if EnvVar::EmbedDownload.category() != "embeddings" {
            return Err("EE_EMBED_DOWNLOAD must be categorized as embeddings".to_owned());
        }
        if EnvVar::EmbedModelDir.category() != "embeddings" {
            return Err("EE_EMBED_MODEL_DIR must be categorized as embeddings".to_owned());
        }
        Ok(())
    }

    #[test]
    fn flight_recorder_env_vars_are_registered_disabled_by_default() -> TestResult {
        if !EnvVar::all().contains(&EnvVar::FlightRecorder) {
            return Err("EE_FLIGHT_RECORDER missing from registry order".to_owned());
        }
        if !EnvVar::all().contains(&EnvVar::FlightRecorderDir) {
            return Err("EE_FLIGHT_RECORDER_DIR missing from registry order".to_owned());
        }
        if !EnvVar::all().contains(&EnvVar::FlightRecorderRetentionDays) {
            return Err("EE_FLIGHT_RECORDER_RETENTION_DAYS missing from registry order".to_owned());
        }
        if EnvVar::FlightRecorder.default_value() != Some("false") {
            return Err("EE_FLIGHT_RECORDER must default to false".to_owned());
        }
        if EnvVar::FlightRecorderRetentionDays.default_value() != Some("7") {
            return Err("EE_FLIGHT_RECORDER_RETENTION_DAYS must default to 7".to_owned());
        }
        if EnvVar::FlightRecorder.category() != "diagnostics" {
            return Err("EE_FLIGHT_RECORDER must be categorized as diagnostics".to_owned());
        }
        if EnvVar::FlightRecorderRetentionDays.category() != "diagnostics" {
            return Err(
                "EE_FLIGHT_RECORDER_RETENTION_DAYS must be categorized as diagnostics".to_owned(),
            );
        }
        if EnvVar::FlightRecorderDir.category() != "paths" {
            return Err("EE_FLIGHT_RECORDER_DIR must be categorized as a path override".to_owned());
        }
        Ok(())
    }

    #[test]
    fn mesh_discovery_cache_and_drift_grace_env_vars_are_registered() -> TestResult {
        let expected = [
            (
                EnvVar::MeshDiscoveryCacheTtlSeconds,
                "EE_MESH_DISCOVERY_CACHE_TTL_SECONDS",
                "30",
            ),
            (
                EnvVar::MeshDriftSoftStaleAfter,
                "EE_MESH_DRIFT_SOFT_STALE_AFTER",
                "1",
            ),
            (
                EnvVar::MeshDriftSoftStaleAfterSeconds,
                "EE_MESH_DRIFT_SOFT_STALE_AFTER_SECONDS",
                "300",
            ),
            (
                EnvVar::MeshDriftHardStaleAfter,
                "EE_MESH_DRIFT_HARD_STALE_AFTER",
                "3",
            ),
            (
                EnvVar::MeshDriftHardStaleAfterSeconds,
                "EE_MESH_DRIFT_HARD_STALE_AFTER_SECONDS",
                "3600",
            ),
        ];

        for (var, name, default) in expected {
            if !EnvVar::all().contains(&var) {
                return Err(format!("{name} missing from registry order"));
            }
            if var.name() != name {
                return Err(format!("unexpected env name for {var:?}: {}", var.name()));
            }
            if var.default_value() != Some(default) {
                return Err(format!("{name} default drifted"));
            }
            if var.category() != "mesh" {
                return Err(format!("{name} must be categorized as mesh"));
            }
        }
        Ok(())
    }

    #[test]
    fn sensitive_env_vars_do_not_expose_values() -> TestResult {
        if EnvVar::ServeToken.exposes_value() {
            return Err("EE_SERVE_TOKEN must not expose currentValue".to_owned());
        }
        if EnvVar::ReflectionHmacKeyPath.exposes_value() {
            return Err("EE_REFLECTION_HMAC_KEY_PATH must not expose currentValue".to_owned());
        }
        Ok(())
    }
}