greentic-runner-host 1.2.2

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

use crate::runtime::block_on;
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use greentic_secrets_lib::env::EnvSecretsManager;
use greentic_secrets_lib::{SecretScope, SecretsManager};
use greentic_types::TenantCtx;
use lru::LruCache;
use parking_lot::Mutex;

/// Shared secrets manager handle used by the host.
pub type DynSecretsManager = Arc<dyn SecretsManager>;

/// Supported secrets backend kinds recognised by the runner.
#[derive(Clone, Debug)]
pub enum SecretsBackend {
    Env,
    /// HTTP secrets broker (greentic-secrets-broker). The `endpoint` is the
    /// base URL (e.g. `http://secrets-broker:8080`) and `token` is the Bearer
    /// auth token (may be empty for unauthenticated local deployments).
    Broker {
        endpoint: String,
        token: String,
    },
}

impl SecretsBackend {
    pub fn from_env(value: Option<String>) -> Result<Self> {
        match value
            .unwrap_or_else(|| "env".into())
            .trim()
            .to_ascii_lowercase()
            .as_str()
        {
            "" | "env" => Ok(SecretsBackend::Env),
            "broker" => Self::broker_from_strings(
                "broker",
                std::env::var("SECRETS_BROKER_ENDPOINT")
                    .unwrap_or_default()
                    .as_str(),
                std::env::var("SECRETS_BROKER_TOKEN")
                    .unwrap_or_default()
                    .as_str(),
            ),
            other => Err(anyhow!("unsupported SECRETS_BACKEND `{other}`")),
        }
    }

    /// Pure constructor used by both `from_env` and tests. Validates that
    /// `endpoint` is non-empty; `token` may be empty for unauthenticated use.
    /// `kind` is passed solely for error-message context.
    pub(crate) fn broker_from_strings(kind: &str, endpoint: &str, token: &str) -> Result<Self> {
        let endpoint = endpoint.trim().trim_end_matches('/');
        if endpoint.is_empty() {
            return Err(anyhow!(
                "SECRETS_BACKEND={kind} requires SECRETS_BROKER_ENDPOINT to be set"
            ));
        }
        Ok(SecretsBackend::Broker {
            endpoint: endpoint.to_owned(),
            token: token.to_owned(),
        })
    }

    pub fn from_config(cfg: &greentic_config_types::SecretsBackendRefConfig) -> Result<Self> {
        match cfg.kind.trim().to_ascii_lowercase().as_str() {
            "" | "none" | "env" => Ok(SecretsBackend::Env),
            // `SecretsBackendRefConfig` has no dedicated endpoint/token fields.
            // When kind="broker", use `reference` as the endpoint (if set) and
            // fall back to SECRETS_BROKER_ENDPOINT from the environment.
            // Token always comes from SECRETS_BROKER_TOKEN env.
            "broker" => {
                let endpoint = cfg
                    .reference
                    .as_deref()
                    .unwrap_or("")
                    .trim()
                    .trim_end_matches('/');
                let endpoint = if endpoint.is_empty() {
                    std::env::var("SECRETS_BROKER_ENDPOINT").unwrap_or_default()
                } else {
                    endpoint.to_owned()
                };
                let token = std::env::var("SECRETS_BROKER_TOKEN").unwrap_or_default();
                Self::broker_from_strings("broker", &endpoint, &token)
            }
            other => Err(anyhow!("unsupported secrets backend `{other}`")),
        }
    }

    pub fn build_manager(&self) -> Result<DynSecretsManager> {
        let inner: DynSecretsManager = match self {
            SecretsBackend::Env => {
                ensure_env_secrets_allowed()?;
                Arc::new(EnvSecretsManager)
            }
            SecretsBackend::Broker { endpoint, token } => Arc::new(
                crate::secrets_broker::BrokerSecretsManager::new(endpoint, token),
            ),
        };
        Ok(CachingSecretsManager::wrap(inner))
    }
}

pub fn default_manager() -> Result<DynSecretsManager> {
    SecretsBackend::Env.build_manager()
}

// ---------------------------------------------------------------------------
// Caching wrapper
// ---------------------------------------------------------------------------

const DEFAULT_CACHE_TTL_SECS: u64 = 300;
const DEFAULT_CACHE_MAX_ENTRIES: usize = 512;

fn cache_ttl() -> Duration {
    let secs = std::env::var("SECRETS_CACHE_TTL_SECS")
        .ok()
        .and_then(|v| v.parse::<u64>().ok())
        .unwrap_or(DEFAULT_CACHE_TTL_SECS);
    Duration::from_secs(secs)
}

fn cache_max_entries() -> NonZeroUsize {
    let n = std::env::var("SECRETS_CACHE_MAX_ENTRIES")
        .ok()
        .and_then(|v| v.parse::<usize>().ok())
        .filter(|&v| v > 0)
        .unwrap_or(DEFAULT_CACHE_MAX_ENTRIES);
    NonZeroUsize::new(n).expect("cache max entries must be > 0")
}

struct CacheEntry {
    data: Vec<u8>,
    inserted_at: Instant,
}

/// A [`SecretsManager`] wrapper that caches read results in an LRU cache with
/// a time-to-live. Writes and deletes invalidate the corresponding entry so
/// subsequent reads always see the latest value.
pub struct CachingSecretsManager {
    inner: DynSecretsManager,
    cache: Mutex<LruCache<String, CacheEntry>>,
    ttl: Duration,
    /// Bumped by every write/delete. A read only populates the cache when no
    /// write landed while its backend fetch was in flight, so a stale value
    /// fetched before a write cannot overwrite the invalidation.
    generation: AtomicU64,
}

impl CachingSecretsManager {
    pub fn wrap(inner: DynSecretsManager) -> DynSecretsManager {
        Self::wrap_with(inner, cache_ttl(), cache_max_entries())
    }

    fn wrap_with(inner: DynSecretsManager, ttl: Duration, max: NonZeroUsize) -> DynSecretsManager {
        if ttl.is_zero() {
            tracing::info!("secrets cache disabled (TTL=0)");
            return inner;
        }
        tracing::info!(
            ttl_secs = ttl.as_secs(),
            max_entries = max.get(),
            "secrets value cache enabled"
        );
        Arc::new(Self {
            inner,
            cache: Mutex::new(LruCache::new(max)),
            ttl,
            generation: AtomicU64::new(0),
        })
    }
}

#[async_trait]
impl SecretsManager for CachingSecretsManager {
    async fn read(&self, path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
        // Check cache first.
        {
            let mut cache = self.cache.lock();
            if let Some(entry) = cache.get(path) {
                if entry.inserted_at.elapsed() < self.ttl {
                    return Ok(entry.data.clone());
                }
                // Expired — remove and fall through.
                cache.pop(path);
            }
        }

        let generation = self.generation.load(Ordering::SeqCst);
        let data = self.inner.read(path).await?;

        {
            let mut cache = self.cache.lock();
            // Writers bump the generation before and after touching the
            // backend and pop the entry afterwards, so a read that raced a
            // write sees a changed generation and skips the insert.
            if self.generation.load(Ordering::SeqCst) == generation {
                cache.put(
                    path.to_owned(),
                    CacheEntry {
                        data: data.clone(),
                        inserted_at: Instant::now(),
                    },
                );
            }
        }
        Ok(data)
    }

    async fn write(&self, path: &str, bytes: &[u8]) -> greentic_secrets_lib::Result<()> {
        self.generation.fetch_add(1, Ordering::SeqCst);
        let result = self.inner.write(path, bytes).await;
        // Invalidate (also after a failed write: its outcome is unknown) so
        // the next read sees the fresh value.
        self.generation.fetch_add(1, Ordering::SeqCst);
        self.cache.lock().pop(path);
        result
    }

    async fn delete(&self, path: &str) -> greentic_secrets_lib::Result<()> {
        self.generation.fetch_add(1, Ordering::SeqCst);
        let result = self.inner.delete(path).await;
        self.generation.fetch_add(1, Ordering::SeqCst);
        self.cache.lock().pop(path);
        result
    }
}

fn normalize_pack_segment(pack_id: &str) -> String {
    pack_id
        .chars()
        .map(|ch| {
            let ch = ch.to_ascii_lowercase();
            match ch {
                'a'..='z' | '0'..='9' | '_' | '-' => ch,
                _ => '_',
            }
        })
        .collect()
}

/// Marker between the pack segment and the unit segment in a unit-scoped pack
/// segment: `<pack>_unit_<unit slug>_<unit hash>`.
///
/// A SINGLE underscore, not a double one. `greentic_secrets_lib`'s
/// `canonical_secret_name` — which greentic-setup / greentic-deployer /
/// greentic-start run over a secret name — **collapses runs of `_`**, so a
/// `__unit_` marker is not a fixed point of it: one side would write
/// `pack__unit_x` and the other would read `pack_unit_x`, at addresses that
/// never meet, with nothing failing at any layer.
const UNIT_PACK_SEGMENT_MARKER: &str = "_unit_";

/// Longest slug kept from the pack id / the unit id before their hash
/// suffixes. Bounds the segment on a long deployment name.
const UNIT_SEGMENT_SLUG_MAX: usize = 40;

/// Bytes of `sha256(..)` rendered as a hash suffix (12 lowercase hex chars).
const UNIT_SEGMENT_HASH_BYTES: usize = 6;

/// Lowercase `[a-z0-9_]` slug: every ASCII alphanumeric is lowercased, every
/// other character becomes `_`, runs of `_` collapse to one, leading/trailing
/// `_` are trimmed, the result is cut to `max` bytes and re-trimmed.
///
/// Collapsing and trimming are what make the output a FIXED POINT of
/// `greentic_secrets_lib::canonical_secret_name` (which collapses and trims),
/// and restricting to `[a-z0-9_]` is what makes it a fixed point of
/// [`canonicalize_secret_key`] (which maps everything else to `_`). Hyphens
/// are deliberately NOT kept, unlike [`normalize_pack_segment`]: the spec
/// canonicalizer maps `-` to `_`, so a surviving hyphen would break the fixed
/// point.
fn underscore_slug(raw: &str, max: usize) -> String {
    let mut slug = String::with_capacity(raw.len());
    for ch in raw.chars() {
        let mapped = if ch.is_ascii_alphanumeric() {
            ch.to_ascii_lowercase()
        } else {
            '_'
        };
        if mapped == '_' && (slug.is_empty() || slug.ends_with('_')) {
            continue;
        }
        slug.push(mapped);
    }
    // ASCII-only by construction, so a byte cut never splits a char.
    slug.truncate(max);
    slug.trim_end_matches('_').to_string()
}

/// First [`UNIT_SEGMENT_HASH_BYTES`] bytes of `sha256(raw)`, lowercase hex.
fn short_hash(raw: &str) -> String {
    use sha2::{Digest, Sha256};
    let digest = Sha256::digest(raw.as_bytes());
    digest[..UNIT_SEGMENT_HASH_BYTES]
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

/// The PACK segment a deployed unit's own copy of a pack secret lives under:
/// `<pack slug>_unit_<unit slug>_<unit hash>`.
///
/// THE one normalisation for this address — the designer (which stages the
/// value) and greentic-setup / greentic-deployer / greentic-start must produce
/// exactly this string, so they should call this function rather than copy it.
/// It is the pack-secret counterpart of
/// `greentic_aw_runtime::mcp_secrets::mcp_unit_segment`, and differs from it in
/// exactly one way that matters: an MCP secret's NAME is written and read
/// VERBATIM by admin, so that segment may use `-`; a pack secret's address is
/// canonicalized on both sides, so this one may not.
///
/// The full URI is
/// `secrets://<env>/<tenant>/<team|_>/<this segment>/<canonical key>` — the
/// unit rides in the CATEGORY (pack) segment, not in a sixth segment, because
/// `greentic_secrets_lib`'s `SecretUri::parse` accepts exactly five and rejects
/// `ExtraSegments`.
///
/// Rules, applied to the trimmed inputs:
///
/// 1. the pack id and the unit id are each reduced by [`underscore_slug`];
/// 2. the unit ALWAYS carries a `sha256` suffix, so two unit ids the slug
///    alone would merge (`Web Assistant` / `web-assistant`, or two ids sharing
///    a 40-byte prefix) still get different segments — and so no two
///    `(pack, unit)` pairs can produce one string by splitting at a different
///    `_unit_`;
/// 3. the pack id likewise carries a `sha256` suffix of the RAW id whenever
///    its slug is lossy (differs from the id: case, punctuation, collapsed or
///    truncated), so `my.pack` / `my_pack` cannot share an address. A pack id
///    that is already its own slug is left unhashed. BREAKING for lossy pack
///    ids' existing per-unit secrets (they must be re-staged); see
///    `docs/audit-breaking-changes.md`. No read fallback to the old address:
///    it is exactly the address the colliding ids share;
/// 4. a pack id whose slug is empty (punctuation only) falls back to
///    `pack_<hash>` rather than an empty leading segment, which would put a
///    leading `_` in the output and break the fixed point.
///
/// Returns `None` for a blank pack id or a blank unit id: there is no unit
/// scope then, and the caller must fall through to the bare pack segment.
pub fn unit_pack_segment(pack_id: &str, unit_id: &str) -> Option<String> {
    let pack_raw = pack_id.trim();
    let unit_raw = unit_id.trim();
    if pack_raw.is_empty() || unit_raw.is_empty() {
        return None;
    }

    let pack_slug = underscore_slug(pack_raw, UNIT_SEGMENT_SLUG_MAX);
    // A slug that differs from the raw id (case folded, punctuation mapped to
    // `_`, runs collapsed, or cut at the length cap) can be shared by several
    // distinct pack ids: `my.pack` / `my_pack` / `My-Pack`, or two ids with
    // one 40-byte prefix. Hash the RAW id in whenever the slug is lossy so
    // those never meet on one per-unit address. A lossless slug (already
    // `[a-z0-9_]`, canonical, within the cap) is the id itself, so it keeps
    // its historical, unhashed address.
    let pack_part = if pack_slug.is_empty() {
        format!("pack_{}", short_hash(pack_raw))
    } else if pack_slug == pack_raw {
        pack_slug
    } else {
        format!("{pack_slug}_{}", short_hash(pack_raw))
    };

    let unit_hash = short_hash(unit_raw);
    let unit_slug = underscore_slug(unit_raw, UNIT_SEGMENT_SLUG_MAX);
    let unit_part = if unit_slug.is_empty() {
        unit_hash
    } else {
        format!("{unit_slug}_{unit_hash}")
    };

    Some(format!("{pack_part}{UNIT_PACK_SEGMENT_MARKER}{unit_part}"))
}

/// The secret URI for one deployed unit's own copy of a pack secret:
/// [`scoped_secret_path_for_pack`] with the pack segment replaced by
/// [`unit_pack_segment`]. `Ok(None)` when there is no unit scope to build.
pub fn scoped_secret_path_for_unit(
    ctx: &TenantCtx,
    pack_id: &str,
    unit_id: &str,
    key: &str,
) -> Result<Option<String>> {
    match unit_pack_segment(pack_id, unit_id) {
        // The unit segment is already `[a-z0-9_]`, so re-normalising it inside
        // `scoped_secret_path_for_pack` is the identity — which is the whole
        // point of the fixed-point rule above.
        Some(segment) => scoped_secret_path_for_pack(ctx, &segment, key).map(Some),
        None => Ok(None),
    }
}

/// Every URI a pack-secret read will try, in order:
///
/// 1. the UNIT scope — `<pack>_unit_<unit>` — when a unit is known;
/// 2. today's bare pack scope.
///
/// REVIEW BY 2026-12-18: candidate 2 is a COMPATIBILITY fallback when a unit is
/// known, not a design choice. It exists so an environment staged before the
/// unit scope existed keeps its credential when its runner moves; the next
/// stage writes the unit-scoped address. Once every lane stages unit-scoped
/// pack secrets (greentic-designer `per-unit-setup-isolation` Phase 2), the
/// fallback lets one unit silently read a value another unit's writer left at
/// the shared address — decide then whether to drop it for the unit case.
/// (Candidate 2 remains the ONLY candidate when no unit is known — the legacy
/// tenant-only runtime and the process-level serve path.)
fn pack_secret_path_candidates(
    ctx: &TenantCtx,
    pack_id: &str,
    unit_id: Option<&str>,
    key: &str,
) -> Result<Vec<String>> {
    let bare = scoped_secret_path_for_pack(ctx, pack_id, key)?;
    let unit = match unit_id {
        Some(unit) => scoped_secret_path_for_unit(ctx, pack_id, unit, key)?,
        None => None,
    };
    Ok(match unit {
        // A unit URI equal to the bare one would make the fallback a duplicate
        // read rather than a fallback; it cannot happen (the unit segment always
        // carries `_unit_<hash>`) but the guard keeps that a fact, not a hope.
        Some(unit) if unit != bare => vec![unit, bare],
        _ => vec![bare],
    })
}

/// Read a pack secret for one deployed unit: the unit scope first, then the
/// bare pack scope (see [`pack_secret_path_candidates`]). First hit wins.
///
/// `unit_id` is the running revision's `bundle_id` — the deployment name,
/// unique within an environment — taken from the runtime that built this pack,
/// never from a process environment variable: one greentic-start process serves
/// every revision of an environment, so an env var cannot differ per unit.
///
/// There is no case where a previously-resolving secret stops resolving: the
/// bare scope is still tried, and only after the unit scope misses.
pub fn read_pack_secret_blocking(
    manager: &DynSecretsManager,
    ctx: &TenantCtx,
    pack_id: &str,
    unit_id: Option<&str>,
    key: &str,
) -> std::result::Result<Vec<u8>, PackSecretError> {
    let candidates = pack_secret_path_candidates(ctx, pack_id, unit_id, key)
        .map_err(|err| PackSecretError::Backend(err.to_string()))?;
    let mut failures = Vec::new();
    for candidate in &candidates {
        match block_on(manager.read(candidate.as_str())) {
            Ok(bytes) => return Ok(bytes),
            Err(err) => failures.push(err),
        }
    }
    Err(classify_pack_secret_failures(&candidates, failures))
}

/// Why [`read_pack_secret_blocking`] failed. Typed so callers can tell a real
/// miss from a permission or backend failure without parsing a message.
#[derive(Debug, thiserror::Error)]
pub enum PackSecretError {
    /// Every scope tried reported the secret as absent.
    #[error("no secret at {0}")]
    NotFound(String),
    /// At least one scope refused the read.
    #[error("secret read denied: {0}")]
    Denied(String),
    /// At least one scope failed for a reason other than absence or denial.
    #[error("secret backend error: {0}")]
    Backend(String),
}

/// A miss is only a miss when EVERY scope said so: a denied or failing scope
/// says nothing about whether a value exists there, so it must not be folded
/// into "not found" by whichever scope happened to be tried last.
fn classify_pack_secret_failures(
    candidates: &[String],
    failures: Vec<greentic_secrets_lib::SecretError>,
) -> PackSecretError {
    let mut denied: Option<String> = None;
    let mut backend: Option<String> = None;
    for failure in failures {
        match failure {
            greentic_secrets_lib::SecretError::NotFound(_) => {}
            greentic_secrets_lib::SecretError::Permission(detail) => {
                denied.get_or_insert(detail);
            }
            other => {
                backend.get_or_insert(other.to_string());
            }
        }
    }
    if let Some(detail) = denied {
        return PackSecretError::Denied(detail);
    }
    if let Some(detail) = backend {
        return PackSecretError::Backend(detail);
    }
    PackSecretError::NotFound(candidates.join(" or "))
}

/// Write a pack secret for one deployed unit.
///
/// **The unit scope is the ONLY write target when a unit is known** — there is
/// deliberately no write-through to the bare pack address. A component writing
/// its refreshed token back must not overwrite the value every other unit of
/// the same pack reads; that is the isolation this whole address exists for.
/// With no unit known the write lands at the bare address exactly as before.
pub fn write_pack_secret_blocking(
    manager: &DynSecretsManager,
    ctx: &TenantCtx,
    pack_id: &str,
    unit_id: Option<&str>,
    key: &str,
    value: &[u8],
) -> Result<()> {
    let target = match unit_id {
        Some(unit) => scoped_secret_path_for_unit(ctx, pack_id, unit, key)?,
        None => None,
    };
    let target = match target {
        Some(target) => target,
        None => scoped_secret_path_for_pack(ctx, pack_id, key)?,
    };
    block_on(manager.write(target.as_str(), value)).map_err(|err| anyhow!(err.to_string()))?;
    Ok(())
}

/// The address an agentic worker's bound extension TOOL secret resolves at.
///
/// An AW tool extension asks for `secret://<provider>/<key>`, and
/// `runner::agent_node::StoreToolSecretsBackend` maps that reference onto a
/// store URI. This is THE function that builds it — the designer stages the
/// value through it too (it links this crate), so a writer can never spell an
/// address the reader does not ask for. That failure is silent at every layer:
/// the deploy reports the value staged, the worker boots, and the tool is
/// dropped from the LLM's list with a `warn` line nobody reads.
///
/// Two shapes, differing in exactly ONE segment:
///
/// ```text
/// unit-scoped   secrets://<env>/<tenant>/_/<unit_pack_segment(provider, unit)>/<key>
/// env-wide      secrets://<env>/<tenant>/_/<provider>/<key>
/// ```
///
/// The unit rides in the CATEGORY segment for the same reason
/// [`unit_pack_segment`] gives: `greentic_secrets_lib`'s `SecretUri::parse`
/// accepts exactly five segments and rejects a sixth. Reusing that function
/// rather than minting a second slug-and-hash rule is deliberate — it is
/// already pinned as a fixed point of BOTH canonicalizers
/// ([`canonicalize_secret_key`] here, `canonical_secret_name` in
/// greentic-setup / greentic-deployer / greentic-start), so the segment
/// survives every hop between the designer's `op secrets put` and this read.
///
/// The `team` segment is the literal `_` and the `key` is VERBATIM, because
/// both are already true of the env-wide address this one sits beside. A read
/// tries the unit-scoped URI first and the env-wide one second, so the two
/// must differ in nothing else or the fallback would be a duplicate read
/// rather than a fallback.
///
/// `unit_id` is the running revision's `bundle_id` — the same identity
/// [`read_pack_secret_blocking`] scopes a pack secret by and billing
/// attributes spend to. `None` (or blank) yields the env-wide address, which
/// is the only address on the legacy tenant-only path and the process-level
/// serve path.
///
/// Returns `None` for a blank provider or a blank key: there is no address to
/// build, and inventing one would write where nothing reads.
pub fn agent_tool_secret_uri(
    env: &str,
    tenant: &str,
    provider: &str,
    key: &str,
    unit_id: Option<&str>,
) -> Option<String> {
    let provider = provider.trim();
    let key = key.trim();
    if provider.is_empty() || key.is_empty() {
        return None;
    }
    let category = match unit_id.and_then(|unit| unit_pack_segment(provider, unit)) {
        Some(segment) => segment,
        None => provider.to_string(),
    };
    // Provider and key come from pack / agent config; env and tenant from the
    // host. The category is either the raw provider or a generated unit
    // segment; every segment lands verbatim in the URI, so an unsafe value
    // (`..`, `/`, `%2e%2e`) yields no address rather than one in another
    // tenant's path.
    if ![env, tenant, category.as_str(), key]
        .into_iter()
        .all(crate::secrets_broker::is_safe_secret_segment)
    {
        return None;
    }
    Some(format!("secrets://{env}/{tenant}/_/{category}/{key}"))
}

pub fn canonicalize_secret_key(raw: &str) -> String {
    raw.trim()
        .chars()
        .map(|ch| {
            let ch = ch.to_ascii_lowercase();
            match ch {
                'a'..='z' | '0'..='9' | '_' => ch,
                _ => '_',
            }
        })
        .collect()
}

fn normalize_team_segment(team: Option<&str>) -> String {
    match team
        .map(str::trim)
        .filter(|value| !value.is_empty() && !value.eq_ignore_ascii_case("default"))
    {
        Some(value) => value.to_string(),
        None => "_".to_string(),
    }
}

pub fn scoped_secret_path_for_pack(ctx: &TenantCtx, pack_id: &str, key: &str) -> Result<String> {
    let key = key.trim();
    if key.is_empty() {
        return Err(anyhow!("secret key must not be empty"));
    }
    let safe_key = canonicalize_secret_key(key);
    let team = ctx.team_id.as_ref().or(ctx.team.as_ref());
    let scope = SecretScope {
        env: ctx.env.as_str().to_string(),
        tenant: ctx.tenant.as_str().to_string(),
        team: team.map(|value| value.as_str().to_string()),
    };
    let team_segment = normalize_team_segment(scope.team.as_deref());
    // `pack_id` and the key are normalised to `[a-z0-9_-]` below, so they cannot
    // escape; env / tenant / team are written verbatim and must be checked.
    for (label, value) in [
        ("env", scope.env.as_str()),
        ("tenant", scope.tenant.as_str()),
        ("team", team_segment.as_str()),
    ] {
        if !crate::secrets_broker::is_safe_secret_segment(value) {
            return Err(anyhow!(
                "secret {label} is not a safe secret-path segment; refusing to build a secrets uri"
            ));
        }
    }
    let pack_segment = pack_id.trim();
    if pack_segment.is_empty() {
        return Err(anyhow!("pack_id must not be empty for scoped secrets"));
    }
    let pack_segment = normalize_pack_segment(pack_segment);
    Ok(format!(
        "secrets://{}/{}/{}/{}/{}",
        scope.env, scope.tenant, team_segment, pack_segment, safe_key
    ))
}

pub fn read_secret_blocking(
    manager: &DynSecretsManager,
    ctx: &TenantCtx,
    pack_id: &str,
    key: &str,
) -> Result<Vec<u8>> {
    let scoped_key = scoped_secret_path_for_pack(ctx, pack_id, key)?;
    let bytes =
        block_on(manager.read(scoped_key.as_str())).map_err(|err| anyhow!(err.to_string()))?;
    Ok(bytes)
}

pub fn write_secret_blocking(
    manager: &DynSecretsManager,
    ctx: &TenantCtx,
    pack_id: &str,
    key: &str,
    value: &[u8],
) -> Result<()> {
    let scoped_key = scoped_secret_path_for_pack(ctx, pack_id, key)?;
    block_on(manager.write(scoped_key.as_str(), value)).map_err(|err| anyhow!(err.to_string()))?;
    Ok(())
}

fn ensure_env_secrets_allowed() -> Result<()> {
    check_env_secrets_allowed(crate::config::greentic_env().as_deref())
}

/// `env` is the already-normalised `GREENTIC_ENV` (`None` = unset OR blank).
fn check_env_secrets_allowed(env: Option<&str>) -> Result<()> {
    // A blank value is "not configured", the same branch as unset: it keeps the
    // documented `local` default (and the warning) rather than being refused as
    // an env named "". This is exactly as permissive as unset, no more.
    let env = match env {
        Some(value) => value.to_string(),
        None => {
            // Documented default, kept for local dev flows. Failing closed is
            // safer for production but changes behaviour (deferred).
            tracing::warn!(
                "GREENTIC_ENV is unset: assuming `local` and allowing the env secrets backend; \
                 set GREENTIC_ENV explicitly in deployed environments"
            );
            "local".to_string()
        }
    };
    let env = env.trim().to_ascii_lowercase();
    if matches!(env.as_str(), "local" | "dev" | "test") {
        Ok(())
    } else {
        Err(anyhow!(
            "env secrets backend is disabled for env '{env}' (dev/test only)"
        ))
    }
}

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

    #[test]
    fn blank_takes_the_same_branch_as_unset() {
        for raw in [None, Some(""), Some("   ")] {
            assert!(
                check_env_secrets_allowed(non_blank(raw).as_deref()).is_ok(),
                "{raw:?}"
            );
        }
    }

    #[test]
    fn deployed_envs_are_still_refused() {
        for raw in ["prod", "staging", " Prod "] {
            assert!(
                check_env_secrets_allowed(non_blank(Some(raw)).as_deref()).is_err(),
                "{raw}"
            );
        }
        assert!(check_env_secrets_allowed(Some("dev")).is_ok());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use greentic_config_types::SecretsBackendRefConfig;
    use greentic_types::{EnvId, TeamId, TenantId, UserId};
    use std::sync::atomic::{AtomicUsize, Ordering};

    fn tenant_ctx() -> greentic_types::TenantCtx {
        greentic_types::TenantCtx::new(
            EnvId::new("local").expect("env"),
            TenantId::new("tenant-a").expect("tenant"),
        )
        .with_team(Some(TeamId::new("team-a").expect("team")))
        .with_user(Some(UserId::new("user-a").expect("user")))
    }

    #[test]
    fn scoped_secret_path_normalizes_pack_and_key_segments() {
        let path =
            scoped_secret_path_for_pack(&tenant_ctx(), "My Pack/Prod", " API/KEY value ").unwrap();
        assert_eq!(
            path,
            "secrets://local/tenant-a/team-a/my_pack_prod/api_key_value"
        );
    }

    #[test]
    fn scoped_secret_path_rejects_empty_inputs() {
        let ctx = tenant_ctx();
        assert!(scoped_secret_path_for_pack(&ctx, "demo", "   ").is_err());
        assert!(scoped_secret_path_for_pack(&ctx, "   ", "key").is_err());
    }

    #[test]
    fn scoped_secret_path_maps_default_team_to_underscore() {
        let ctx = greentic_types::TenantCtx::new(
            EnvId::new("dev").expect("env"),
            TenantId::new("demo").expect("tenant"),
        )
        .with_team(Some(TeamId::new("default").expect("team")));
        let path = scoped_secret_path_for_pack(&ctx, "ollama-runtime-repro", "ollama_api_key")
            .expect("scoped secret path");
        assert_eq!(
            path,
            "secrets://dev/demo/_/ollama-runtime-repro/ollama_api_key"
        );
    }

    #[test]
    fn scoped_secret_path_canonicalizes_provider_secret_keys() {
        let ctx = greentic_types::TenantCtx::new(
            EnvId::new("dev").expect("env"),
            TenantId::new("demo").expect("tenant"),
        )
        .with_team(Some(TeamId::new("default").expect("team")))
        .with_user(Some(UserId::new("operator").expect("user")));
        let path = scoped_secret_path_for_pack(&ctx, "ollama-runtime-repro", "OLLAMA_API_KEY")
            .expect("scoped secret path");
        assert_eq!(
            path,
            "secrets://dev/demo/_/ollama-runtime-repro/ollama_api_key"
        );
    }

    // ── unit-scoped pack segment ────────────────────────────────────────

    /// The property the whole address depends on: the segment must survive
    /// BOTH canonicalizers untouched. The runner applies
    /// [`canonicalize_secret_key`]; greentic-setup / greentic-deployer /
    /// greentic-start apply `greentic_secrets_lib::canonical_secret_name`,
    /// which additionally COLLAPSES runs of `_` and trims them. A segment that
    /// is not a fixed point of both produces an address one side writes and the
    /// other never reads, with nothing failing at any layer — which is why this
    /// is asserted explicitly rather than left implied by the character set.
    #[test]
    fn the_unit_segment_is_a_fixed_point_of_both_canonicalizers() {
        let ids = [
            ("pack.dw.support", "web-assistant"),
            ("My Pack/Prod", "Web Assistant (prod)"),
            ("demo  pack", "unit_01JTKS.v2"),
            ("pack--x", "ÜNÏCÖDÉ-Ünit"),
            ("a.b-c_d", "---"),
            ("...", "a/b/c@d"),
            ("ollama-runtime-repro", "   x   "),
            (
                "a-very-long-pack-id-that-exceeds-the-slug-limit-by-a-lot-of-bytes",
                "a-very-long-deployment-name-that-exceeds-the-slug-limit-by-a-lot",
            ),
        ];
        for (pack, unit) in ids {
            let segment = unit_pack_segment(pack, unit).expect("segment");
            assert_eq!(
                canonicalize_secret_key(&segment),
                segment,
                "`{pack}` / `{unit}` is not a fixed point of canonicalize_secret_key"
            );
            assert_eq!(
                greentic_secrets_lib::spec::canonical_secret_name(&segment),
                segment,
                "`{pack}` / `{unit}` is not a fixed point of canonical_secret_name"
            );
            // And it must still be a legal URI component.
            assert!(
                segment
                    .chars()
                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'),
                "`{pack}` / `{unit}` -> `{segment}`"
            );
            assert!(!segment.starts_with('_') && !segment.ends_with('_'));
            assert!(!segment.contains("__"));
        }
    }

    /// A whole URI built from the segment must parse, and must round-trip
    /// through `normalize_pack_segment` (which `scoped_secret_path_for_pack`
    /// re-applies) unchanged.
    #[test]
    fn a_unit_scoped_uri_parses_and_re_normalizes_to_itself() {
        let ctx = tenant_ctx();
        for (pack, unit) in [("pack.dw.support", "web-assistant"), ("...", "a/b@c")] {
            let segment = unit_pack_segment(pack, unit).expect("segment");
            assert_eq!(normalize_pack_segment(&segment), segment);
            let uri = scoped_secret_path_for_unit(&ctx, pack, unit, "HUBSPOT/ACCESS_TOKEN")
                .expect("uri")
                .expect("some");
            assert!(
                greentic_secrets_lib::spec::SecretUri::parse(&uri).is_ok(),
                "`{uri}` is not a valid secret URI"
            );
            assert!(uri.ends_with("/hubspot_access_token"), "got {uri}");
        }
    }

    #[test]
    fn the_unit_segment_is_deterministic_and_carries_a_hash() {
        let a = unit_pack_segment("demo", "web-assistant").expect("segment");
        assert_eq!(
            a,
            unit_pack_segment("demo", "web-assistant").expect("again")
        );
        assert_eq!(
            a,
            unit_pack_segment("  demo  ", "  web-assistant  ").expect("trimmed")
        );
        let unit_part = a.strip_prefix("demo_unit_").expect("marker");
        let (slug, hash) = unit_part.rsplit_once('_').expect("hash suffix");
        assert_eq!(slug, "web_assistant");
        assert_eq!(hash.len(), UNIT_SEGMENT_HASH_BYTES * 2);
        assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));
    }

    /// Pinned literals, so a change to the rule is a visible, deliberate diff:
    /// every downstream writer stages under exactly these strings.
    #[test]
    fn the_unit_segment_matches_the_pinned_values() {
        assert_eq!(
            unit_pack_segment("demo", "web-assistant").expect("segment"),
            "demo_unit_web_assistant_9456a3393b7e"
        );
        assert_eq!(
            unit_pack_segment("pack.dw.support", "Web Assistant (prod)").expect("segment"),
            "pack_dw_support_339461568342_unit_web_assistant_prod_3ee04e3f306a"
        );
    }

    #[test]
    fn ids_the_slug_would_merge_still_get_distinct_segments() {
        // The hash is what separates these; the slug alone merges every pair,
        // and the last pair also proves a `_unit_` inside a pack id cannot be
        // confused with the marker.
        let pairs = [
            (("demo", "Web Assistant"), ("demo", "web-assistant")),
            (("demo", "web.assistant"), ("demo", "web_assistant")),
            (("demo", "a/b"), ("demo", "a-b")),
            (("demo", "unit_b"), ("demo_unit_b", "unit")),
            (
                (
                    "demo",
                    "a-very-long-deployment-name-over-the-slug-limit-one",
                ),
                (
                    "demo",
                    "a-very-long-deployment-name-over-the-slug-limit-two",
                ),
            ),
        ];
        for ((pack_l, unit_l), (pack_r, unit_r)) in pairs {
            assert_ne!(
                unit_pack_segment(pack_l, unit_l),
                unit_pack_segment(pack_r, unit_r),
                "`{pack_l}`/`{unit_l}` and `{pack_r}`/`{unit_r}` must not share a segment"
            );
        }
    }

    #[test]
    fn lossy_pack_slugs_do_not_collide_but_lossless_ids_stay_unhashed() {
        let a = unit_pack_segment("my.pack", "u").expect("a");
        let b = unit_pack_segment("my_pack", "u").expect("b");
        let c = unit_pack_segment("My-Pack", "u").expect("c");
        assert_ne!(a, b);
        assert_ne!(a, c);
        assert_ne!(b, c);
        // Lossless id: historical address, no pack hash.
        assert!(b.starts_with("my_pack_unit_"), "got {b}");
        let long_a = format!("{}-one", "x".repeat(44));
        let long_b = format!("{}-two", "x".repeat(44));
        assert_ne!(
            unit_pack_segment(&long_a, "u"),
            unit_pack_segment(&long_b, "u"),
            "ids sharing a 40-byte prefix must not collide"
        );
        for id in ["my.pack", "My-Pack", long_a.as_str()] {
            let seg = unit_pack_segment(id, "u").expect("seg");
            assert_eq!(canonicalize_secret_key(&seg), seg);
            assert_eq!(greentic_secrets_lib::spec::canonical_secret_name(&seg), seg);
        }
    }

    #[test]
    fn a_punctuation_only_pack_id_does_not_produce_a_leading_underscore() {
        let segment = unit_pack_segment("...", "unit-a").expect("segment");
        assert!(segment.starts_with("pack_"), "got {segment}");
        assert_ne!(
            unit_pack_segment("...", "unit-a"),
            unit_pack_segment("///", "unit-a"),
            "two punctuation-only pack ids must not collapse together"
        );
    }

    #[test]
    fn a_blank_pack_or_unit_id_has_no_unit_scope() {
        assert!(unit_pack_segment("demo", "").is_none());
        assert!(unit_pack_segment("demo", "   ").is_none());
        assert!(unit_pack_segment("", "unit-a").is_none());
        assert!(unit_pack_segment("   ", "unit-a").is_none());
        assert!(
            scoped_secret_path_for_unit(&tenant_ctx(), "demo", "  ", "key")
                .expect("ok")
                .is_none()
        );
    }

    // ── the agentic-worker bound-tool address ───────────────────────────

    /// The env-wide shape is unchanged, byte for byte: it is the address every
    /// worker deployed before this change already reads, and a deploy staged
    /// against it must keep resolving.
    #[test]
    fn the_bare_agent_tool_address_is_unchanged() {
        assert_eq!(
            agent_tool_secret_uri("dev", "acme", "tavily", "api_key", None).expect("uri"),
            "secrets://dev/acme/_/tavily/api_key"
        );
        // A blank unit is the same as no unit — there is no scope to build.
        assert_eq!(
            agent_tool_secret_uri("dev", "acme", "tavily", "api_key", Some("   ")).expect("uri"),
            "secrets://dev/acme/_/tavily/api_key"
        );
    }

    /// The unit-scoped shape differs from the env-wide one in exactly ONE
    /// segment. If it differed in any other, the read's second candidate would
    /// be a different address rather than the fallback it is meant to be.
    #[test]
    fn the_unit_scoped_agent_tool_address_differs_only_in_the_category() {
        let bare =
            agent_tool_secret_uri("dev", "acme", "tavily", "api_key", None).expect("bare uri");
        let scoped = agent_tool_secret_uri("dev", "acme", "tavily", "api_key", Some("web-chat"))
            .expect("unit uri");
        assert_ne!(bare, scoped);

        let bare_parts: Vec<&str> = bare.split('/').collect();
        let scoped_parts: Vec<&str> = scoped.split('/').collect();
        assert_eq!(bare_parts.len(), scoped_parts.len());
        let differing: Vec<usize> = bare_parts
            .iter()
            .zip(&scoped_parts)
            .enumerate()
            .filter(|(_, (a, b))| a != b)
            .map(|(i, _)| i)
            .collect();
        assert_eq!(differing.len(), 1, "{bare} vs {scoped}");
        assert_eq!(
            scoped_parts[differing[0]],
            unit_pack_segment("tavily", "web-chat").expect("segment")
        );
    }

    /// The property the whole address depends on. The category segment travels
    /// through `greentic-setup` / `greentic-deployer` / `greentic-start` on the
    /// way to the store, and through [`canonicalize_secret_key`] on some read
    /// paths here; a segment that is not a fixed point of both is an address
    /// one side writes and the other never reads, with nothing red anywhere.
    #[test]
    fn the_agent_tool_category_is_a_fixed_point_of_both_canonicalizers() {
        for (provider, unit) in [
            ("tavily", "web-chat"),
            ("HubSpot", "Web Assistant (prod)"),
            ("greentic.hubspot", "unit_01JTKS.v2"),
            ("a-b_c", "ÜNÏCÖDÉ-Ünit"),
            ("...", "a/b@c"),
        ] {
            let uri =
                agent_tool_secret_uri("dev", "acme", provider, "api_key", Some(unit)).expect("uri");
            let category = uri.split('/').nth(5).expect("category segment");
            assert_eq!(canonicalize_secret_key(category), category, "{uri}");
            assert_eq!(
                greentic_secrets_lib::spec::canonical_secret_name(category),
                category,
                "{uri}"
            );
            assert!(
                greentic_secrets_lib::spec::SecretUri::parse(&uri).is_ok(),
                "`{uri}` is not a valid secret URI"
            );
        }
    }

    /// Two units of one environment asking for the SAME `<provider>/<key>`
    /// address two different places. This is the whole point: before it, both
    /// projected onto one URI and the second staged value won silently.
    #[test]
    fn two_units_one_provider_and_key_are_two_addresses() {
        let a = agent_tool_secret_uri("dev", "acme", "hubspot", "access_token", Some("sales-bot"))
            .expect("a");
        let b = agent_tool_secret_uri(
            "dev",
            "acme",
            "hubspot",
            "access_token",
            Some("support-bot"),
        )
        .expect("b");
        let shared =
            agent_tool_secret_uri("dev", "acme", "hubspot", "access_token", None).expect("shared");
        assert_ne!(a, b);
        assert_ne!(a, shared);
        assert_ne!(b, shared);
    }

    #[test]
    fn unsafe_segments_have_no_agent_tool_address() {
        for bad in ["..", "a/b", "%2e%2e", "../x", ".h"] {
            assert!(agent_tool_secret_uri("dev", "acme", bad, "api_key", None).is_none());
            assert!(agent_tool_secret_uri("dev", "acme", "tavily", bad, None).is_none());
            assert!(agent_tool_secret_uri(bad, "acme", "tavily", "api_key", None).is_none());
            assert!(agent_tool_secret_uri("dev", bad, "tavily", "api_key", None).is_none());
        }
    }

    #[test]
    fn scoped_pack_path_normalises_hostile_pack_id() {
        let ctx = greentic_types::TenantCtx::new(
            EnvId::new("dev").expect("env"),
            TenantId::new("acme").expect("tenant"),
        );
        let path = scoped_secret_path_for_pack(&ctx, "../../evil/pack%2e", "k")
            .expect("pack_id is normalised, not rejected");
        assert!(!path.contains(".."), "{path}");
        assert!(!path.contains('%'), "{path}");
        assert_eq!(path.matches('/').count(), 6, "{path}");
    }

    #[test]
    fn a_blank_provider_or_key_has_no_agent_tool_address() {
        assert!(agent_tool_secret_uri("dev", "acme", "", "api_key", Some("u")).is_none());
        assert!(agent_tool_secret_uri("dev", "acme", "tavily", "   ", Some("u")).is_none());
    }

    #[test]
    fn candidates_put_the_unit_scope_first_and_keep_the_bare_scope() {
        let ctx = tenant_ctx();
        let with_unit =
            pack_secret_path_candidates(&ctx, "demo", Some("unit-a"), "API_KEY").expect("uris");
        assert_eq!(
            with_unit,
            vec![
                scoped_secret_path_for_unit(&ctx, "demo", "unit-a", "API_KEY")
                    .expect("ok")
                    .expect("some"),
                scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare"),
            ]
        );

        let without_unit =
            pack_secret_path_candidates(&ctx, "demo", None, "API_KEY").expect("uris");
        assert_eq!(
            without_unit,
            vec![scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare")],
            "no unit known must keep today's single candidate exactly"
        );
    }

    /// A secrets manager holding exactly the URIs it was given, recording reads.
    struct MapSecrets {
        entries: std::collections::HashMap<String, Vec<u8>>,
        seen: Mutex<Vec<String>>,
        written: Mutex<Vec<(String, Vec<u8>)>>,
    }

    impl MapSecrets {
        fn with(pairs: &[(&str, &str)]) -> Arc<Self> {
            Arc::new(Self {
                entries: pairs
                    .iter()
                    .map(|(k, v)| ((*k).to_string(), v.as_bytes().to_vec()))
                    .collect(),
                seen: Mutex::new(Vec::new()),
                written: Mutex::new(Vec::new()),
            })
        }
    }

    #[async_trait]
    impl SecretsManager for MapSecrets {
        async fn read(&self, path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
            self.seen.lock().push(path.to_string());
            self.entries
                .get(path)
                .cloned()
                .ok_or_else(|| greentic_secrets_lib::SecretError::NotFound(path.to_string()))
        }
        async fn write(&self, path: &str, bytes: &[u8]) -> greentic_secrets_lib::Result<()> {
            self.written.lock().push((path.to_string(), bytes.to_vec()));
            Ok(())
        }
        async fn delete(&self, _: &str) -> greentic_secrets_lib::Result<()> {
            Ok(())
        }
    }

    fn unit_uri(ctx: &TenantCtx, pack: &str, unit: &str, key: &str) -> String {
        scoped_secret_path_for_unit(ctx, pack, unit, key)
            .expect("ok")
            .expect("some")
    }

    #[test]
    fn the_unit_scope_wins_over_the_bare_pack_scope() {
        let ctx = tenant_ctx();
        let unit = unit_uri(&ctx, "demo", "unit-a", "API_KEY");
        let bare = scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare");
        let secrets = MapSecrets::with(&[
            (unit.as_str(), "unit-value"),
            (bare.as_str(), "shared-value"),
        ]);
        let manager: DynSecretsManager = secrets.clone();
        let got =
            read_pack_secret_blocking(&manager, &ctx, "demo", Some("unit-a"), "API_KEY").unwrap();
        assert_eq!(got, b"unit-value".to_vec());
        assert_eq!(
            secrets.seen.lock().as_slice(),
            &[unit],
            "the bare scope must not be read once the unit scope hits"
        );
    }

    #[test]
    fn a_missing_unit_scope_falls_back_to_the_bare_pack_scope() {
        let ctx = tenant_ctx();
        let unit = unit_uri(&ctx, "demo", "unit-a", "API_KEY");
        let bare = scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare");
        let secrets = MapSecrets::with(&[(bare.as_str(), "shared-value")]);
        let manager: DynSecretsManager = secrets.clone();
        let got =
            read_pack_secret_blocking(&manager, &ctx, "demo", Some("unit-a"), "API_KEY").unwrap();
        assert_eq!(got, b"shared-value".to_vec());
        assert_eq!(secrets.seen.lock().as_slice(), &[unit, bare]);
    }

    #[test]
    fn two_units_of_one_pack_resolve_their_own_values() {
        let ctx = tenant_ctx();
        let a = unit_uri(&ctx, "demo", "unit-a", "API_KEY");
        let b = unit_uri(&ctx, "demo", "unit-b", "API_KEY");
        let bare = scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare");
        assert_ne!(a, b);
        let secrets = MapSecrets::with(&[
            (a.as_str(), "token-a"),
            (b.as_str(), "token-b"),
            (bare.as_str(), "shared-value"),
        ]);
        let manager: DynSecretsManager = secrets.clone();
        for (unit, expected) in [("unit-a", "token-a"), ("unit-b", "token-b")] {
            let got =
                read_pack_secret_blocking(&manager, &ctx, "demo", Some(unit), "API_KEY").unwrap();
            assert_eq!(got, expected.as_bytes().to_vec(), "unit {unit}");
        }
    }

    #[test]
    fn no_unit_reads_exactly_todays_address() {
        let ctx = tenant_ctx();
        let bare = scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare");
        let secrets = MapSecrets::with(&[(bare.as_str(), "shared-value")]);
        let manager: DynSecretsManager = secrets.clone();
        let got = read_pack_secret_blocking(&manager, &ctx, "demo", None, "API_KEY").unwrap();
        assert_eq!(got, b"shared-value".to_vec());
        assert_eq!(secrets.seen.lock().as_slice(), &[bare]);
    }

    #[test]
    fn a_total_miss_names_every_uri_tried() {
        let ctx = tenant_ctx();
        let secrets = MapSecrets::with(&[]);
        let manager: DynSecretsManager = secrets.clone();
        let err = read_pack_secret_blocking(&manager, &ctx, "demo", Some("unit-a"), "API_KEY")
            .expect_err("no value anywhere");
        let rendered = err.to_string();
        assert!(
            rendered.contains(&unit_uri(&ctx, "demo", "unit-a", "API_KEY"))
                && rendered
                    .contains(&scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare")),
            "got: {rendered}"
        );
    }

    #[test]
    fn a_write_lands_at_the_unit_address_only() {
        let ctx = tenant_ctx();
        let secrets = MapSecrets::with(&[]);
        let manager: DynSecretsManager = secrets.clone();
        write_pack_secret_blocking(&manager, &ctx, "demo", Some("unit-a"), "API_KEY", b"fresh")
            .unwrap();
        assert_eq!(
            secrets.written.lock().as_slice(),
            &[(
                unit_uri(&ctx, "demo", "unit-a", "API_KEY"),
                b"fresh".to_vec()
            )],
            "a unit write must never touch the address other units read"
        );
    }

    #[test]
    fn a_write_with_no_unit_lands_at_the_bare_address() {
        let ctx = tenant_ctx();
        let secrets = MapSecrets::with(&[]);
        let manager: DynSecretsManager = secrets.clone();
        write_pack_secret_blocking(&manager, &ctx, "demo", None, "API_KEY", b"fresh").unwrap();
        assert_eq!(
            secrets.written.lock().as_slice(),
            &[(
                scoped_secret_path_for_pack(&ctx, "demo", "API_KEY").expect("bare"),
                b"fresh".to_vec()
            )]
        );
    }

    #[test]
    fn from_env_parses_broker() {
        // Test purely via the internal helper — avoids unsafe env mutation
        // (crate uses #![deny(unsafe_code)]).
        let b = SecretsBackend::broker_from_strings("broker", "http://localhost:9", "").unwrap();
        assert!(matches!(b, SecretsBackend::Broker { .. }));
    }

    #[test]
    fn from_env_broker_rejects_empty_endpoint() {
        let err = SecretsBackend::broker_from_strings("broker", "", "").unwrap_err();
        assert!(
            err.to_string().contains("SECRETS_BROKER_ENDPOINT"),
            "error was: {err}"
        );
    }

    #[test]
    fn from_config_parses_broker() {
        let b = SecretsBackend::from_config(&SecretsBackendRefConfig {
            kind: "broker".into(),
            reference: Some("http://localhost:9".into()),
        })
        .unwrap();
        assert!(matches!(b, SecretsBackend::Broker { .. }));
    }

    #[test]
    fn backend_parsers_reject_unknown_kinds() {
        let err =
            SecretsBackend::from_env(Some("vault".into())).expect_err("backend should be rejected");
        assert!(err.to_string().contains("unsupported SECRETS_BACKEND"));

        let err = SecretsBackend::from_config(&SecretsBackendRefConfig {
            kind: "vault".into(),
            reference: None,
        })
        .expect_err("backend config should be rejected");
        assert!(err.to_string().contains("unsupported secrets backend"));
    }

    #[test]
    fn backend_parsers_accept_default_aliases() {
        assert!(matches!(
            SecretsBackend::from_env(Some("".into())).unwrap(),
            SecretsBackend::Env
        ));
        assert!(matches!(
            SecretsBackend::from_config(&SecretsBackendRefConfig {
                kind: "none".into(),
                reference: None,
            })
            .unwrap(),
            SecretsBackend::Env
        ));
    }

    // -----------------------------------------------------------------------
    // CachingSecretsManager tests
    // -----------------------------------------------------------------------

    /// In-memory mock that counts how many times `read` is called.
    struct CountingManager {
        read_count: AtomicUsize,
    }

    impl CountingManager {
        fn new() -> Arc<Self> {
            Arc::new(Self {
                read_count: AtomicUsize::new(0),
            })
        }

        fn reads(&self) -> usize {
            self.read_count.load(Ordering::SeqCst)
        }
    }

    #[async_trait]
    impl SecretsManager for CountingManager {
        async fn read(&self, _path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
            self.read_count.fetch_add(1, Ordering::SeqCst);
            Ok(b"secret-value".to_vec())
        }

        async fn write(&self, _path: &str, _bytes: &[u8]) -> greentic_secrets_lib::Result<()> {
            Ok(())
        }

        async fn delete(&self, _path: &str) -> greentic_secrets_lib::Result<()> {
            Ok(())
        }
    }

    fn make_cached(inner: Arc<CountingManager>) -> CachingSecretsManager {
        CachingSecretsManager {
            inner: inner as DynSecretsManager,
            cache: Mutex::new(LruCache::new(NonZeroUsize::new(64).unwrap())),
            ttl: Duration::from_secs(300),
            generation: AtomicU64::new(0),
        }
    }

    #[tokio::test]
    async fn cached_read_avoids_backend_on_second_call() {
        let inner = CountingManager::new();
        let cached = make_cached(Arc::clone(&inner));

        let v1 = cached.read("secrets://dev/t/team/pack/key").await.unwrap();
        let v2 = cached.read("secrets://dev/t/team/pack/key").await.unwrap();
        assert_eq!(v1, v2);
        assert_eq!(inner.reads(), 1, "second read should hit cache");
    }

    #[tokio::test]
    async fn write_invalidates_cache() {
        let inner = CountingManager::new();
        let cached = make_cached(Arc::clone(&inner));

        cached.read("secrets://dev/t/team/pack/key").await.unwrap();
        assert_eq!(inner.reads(), 1);

        cached
            .write("secrets://dev/t/team/pack/key", b"new")
            .await
            .unwrap();
        cached.read("secrets://dev/t/team/pack/key").await.unwrap();
        assert_eq!(inner.reads(), 2, "read after write should bypass cache");
    }

    #[tokio::test]
    async fn delete_invalidates_cache() {
        let inner = CountingManager::new();
        let cached = make_cached(Arc::clone(&inner));

        cached.read("secrets://dev/t/team/pack/key").await.unwrap();
        cached
            .delete("secrets://dev/t/team/pack/key")
            .await
            .unwrap();
        cached.read("secrets://dev/t/team/pack/key").await.unwrap();
        assert_eq!(inner.reads(), 2, "read after delete should bypass cache");
    }

    #[tokio::test]
    async fn expired_entry_triggers_backend_read() {
        let inner = CountingManager::new();
        let cached = CachingSecretsManager {
            inner: Arc::clone(&inner) as DynSecretsManager,
            cache: Mutex::new(LruCache::new(NonZeroUsize::new(64).unwrap())),
            ttl: Duration::from_millis(1), // expires almost immediately
            generation: AtomicU64::new(0),
        };

        cached.read("secrets://dev/t/team/pack/key").await.unwrap();
        std::thread::sleep(Duration::from_millis(5));
        cached.read("secrets://dev/t/team/pack/key").await.unwrap();
        assert_eq!(inner.reads(), 2, "expired entry should re-fetch");
    }

    /// Backend whose first read returns the old value only after the test lets
    /// it go, modelling a slow read racing a write.
    struct GatedManager {
        value: Mutex<Vec<u8>>,
        started: tokio::sync::Notify,
        release: tokio::sync::Notify,
        first: AtomicUsize,
    }

    #[async_trait]
    impl SecretsManager for GatedManager {
        async fn read(&self, _path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
            let snapshot = self.value.lock().clone();
            if self.first.fetch_add(1, Ordering::SeqCst) == 0 {
                self.started.notify_one();
                self.release.notified().await;
            }
            Ok(snapshot)
        }

        async fn write(&self, _path: &str, bytes: &[u8]) -> greentic_secrets_lib::Result<()> {
            *self.value.lock() = bytes.to_vec();
            Ok(())
        }

        async fn delete(&self, _path: &str) -> greentic_secrets_lib::Result<()> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn stale_read_does_not_repopulate_cache_after_write() {
        let inner = Arc::new(GatedManager {
            value: Mutex::new(b"old".to_vec()),
            started: tokio::sync::Notify::new(),
            release: tokio::sync::Notify::new(),
            first: AtomicUsize::new(0),
        });
        let cached = Arc::new(CachingSecretsManager {
            inner: Arc::clone(&inner) as DynSecretsManager,
            cache: Mutex::new(LruCache::new(NonZeroUsize::new(8).unwrap())),
            ttl: Duration::from_secs(300),
            generation: AtomicU64::new(0),
        });

        let reader = {
            let cached = Arc::clone(&cached);
            tokio::spawn(async move { cached.read("secrets://dev/t/_/p/k").await })
        };
        inner.started.notified().await;
        cached.write("secrets://dev/t/_/p/k", b"new").await.unwrap();
        inner.release.notify_one();
        let stale = reader.await.unwrap().unwrap();
        assert_eq!(stale, b"old");

        let fresh = cached.read("secrets://dev/t/_/p/k").await.unwrap();
        assert_eq!(fresh, b"new", "stale value must not be cached");
    }

    #[test]
    fn wrap_with_zero_ttl_returns_inner_directly() {
        let inner: DynSecretsManager = CountingManager::new();
        let ptr_before = Arc::as_ptr(&inner);
        let wrapped = CachingSecretsManager::wrap_with(
            Arc::clone(&inner),
            Duration::ZERO,
            NonZeroUsize::new(64).unwrap(),
        );
        let ptr_after = Arc::as_ptr(&wrapped);
        // When TTL is 0, wrap should return the same Arc (no caching layer).
        assert_eq!(ptr_before, ptr_after);
    }
}

#[cfg(test)]
mod pack_secret_error_tests {
    use super::*;
    use greentic_secrets_lib::SecretError;

    fn candidates() -> Vec<String> {
        vec!["secrets://a".to_string(), "secrets://b".to_string()]
    }

    #[test]
    fn not_found_only_when_every_scope_is_not_found() {
        let err = classify_pack_secret_failures(
            &candidates(),
            vec![
                SecretError::NotFound("a".into()),
                SecretError::NotFound("b".into()),
            ],
        );
        assert!(matches!(err, PackSecretError::NotFound(_)));
    }

    #[test]
    fn permission_error_is_not_masked_by_a_later_not_found() {
        let err = classify_pack_secret_failures(
            &candidates(),
            vec![
                SecretError::Permission("no".into()),
                SecretError::NotFound("b".into()),
            ],
        );
        assert!(matches!(err, PackSecretError::Denied(_)));
    }

    #[test]
    fn words_like_missing_in_a_backend_message_do_not_become_not_found() {
        let err = classify_pack_secret_failures(
            &candidates(),
            vec![
                SecretError::Backend("config missing".into()),
                SecretError::NotFound("b".into()),
            ],
        );
        assert!(matches!(err, PackSecretError::Backend(_)));
    }
}