khive-runtime 0.10.0

Composable Service API: entity/note CRUD, graph traversal, hybrid search, curation.
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
//! RuntimeConfig, BackendId, NamespaceToken, and embedding model helpers.

use std::sync::Arc;

use khive_db::StorageBackend;
pub use khive_db::WalCeilingSource;
use khive_gate::{ActorRef, AllowAllGate, GateRef};
use khive_types::Namespace;
use lattice_embed::EmbeddingModel;

use crate::error::RuntimeResult;

// ---- BackendId ----

/// Identifies a named backend in a multi-backend deployment.
///
/// The `main` backend is the default single-backend name. Multi-backend deployments
/// assign each `[[backends]]` entry a distinct `BackendId`. The
/// `SubstrateCoordinator` in `kkernel`
/// uses `BackendId` for node-to-backend resolution and cross-backend edge routing.
///
/// A single-backend `KhiveRuntime` always has the `main` backend id by default.
/// The boot path in `kkernel` or `khive-mcp` sets the id via `RuntimeConfig::backend_id`
/// when constructing per-pack runtimes.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct BackendId(String);

/// Validation error returned when a backend identifier is rejected.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum BackendIdError {
    /// The supplied identifier was empty or contained only whitespace.
    #[error("backend id must not be empty or whitespace-only")]
    Empty,
}

impl BackendId {
    /// The default single-backend name.
    pub const MAIN: &'static str = "main";

    /// Parse a nonempty backend identifier.
    pub fn parse(name: impl Into<String>) -> Result<Self, BackendIdError> {
        let name = name.into();
        if name.trim().is_empty() {
            return Err(BackendIdError::Empty);
        }
        Ok(Self(name))
    }

    /// The default `main` backend id.
    pub fn main() -> Self {
        Self(Self::MAIN.to_string())
    }

    /// Return the backend name as a `&str`.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl TryFrom<String> for BackendId {
    type Error = BackendIdError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

impl TryFrom<&str> for BackendId {
    type Error = BackendIdError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

impl std::str::FromStr for BackendId {
    type Err = BackendIdError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::parse(value)
    }
}

impl std::fmt::Display for BackendId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

#[cfg(test)]
mod backend_id_tests {
    use super::BackendId;

    #[test]
    fn empty_and_whitespace_only_backend_ids_are_rejected() {
        for invalid in ["", " ", "\t\n"] {
            assert!(
                BackendId::parse(invalid).is_err(),
                "backend id {invalid:?} must be rejected"
            );
        }
    }

    #[test]
    fn nonempty_backend_id_round_trips() {
        let id = BackendId::parse("archive").expect("valid backend id");
        assert_eq!(id.as_str(), "archive");
        assert_eq!(id.to_string(), "archive");
    }
}

// ---- Sealed token ----

mod private {
    #[derive(Clone, Debug)]
    pub(crate) struct Sealed;
}

/// Authorization proof that a caller is permitted to access a specific namespace.
///
/// Created by [`crate::VerbRegistry::dispatch`] after the gate approves the request.
/// The sealed inner field prevents external code from constructing a token
/// without going through the authorization path.
///
/// The `namespace` field is the **write namespace**: all records created via
/// this token land in that namespace. `visible` is the **read visibility set**:
/// list/search/get operations will return records from any namespace in this
/// set. The write namespace is always a member of the visible set.
///
/// Single-namespace behaviour (backward-compatible default): `visible` contains
/// exactly `[namespace]` — identical to the old strict-equality checks.
#[derive(Clone, Debug)]
pub struct NamespaceToken {
    namespace: Namespace,
    gate_namespace: Namespace,
    gate_explicit_namespace: Option<String>,
    request_id: Option<u64>,
    visible: Vec<Namespace>,
    actor: ActorRef,
    process_ref: Option<String>,
    _sealed: private::Sealed,
}

impl NamespaceToken {
    /// Mint an authorized token with an extended visibility set.
    ///
    /// `extra_visible` lists namespaces beyond the primary that the token may
    /// read. The primary namespace is always included in the visible set
    /// regardless of what `extra_visible` contains. Duplicates are removed.
    pub(crate) fn mint_with_visibility(
        namespace: Namespace,
        extra_visible: Vec<Namespace>,
        actor: ActorRef,
    ) -> Self {
        let mut visible = vec![namespace.clone()];
        for ns in extra_visible {
            if !visible.contains(&ns) {
                visible.push(ns);
            }
        }
        debug_assert!(!visible.is_empty(), "visible set must be non-empty");
        Self {
            gate_namespace: namespace.clone(),
            gate_explicit_namespace: None,
            request_id: None,
            namespace,
            visible,
            actor,
            process_ref: None,
            _sealed: private::Sealed,
        }
    }

    /// Mint an authorized token. Only callable from within `khive-runtime`.
    ///
    /// The visible set defaults to `[namespace]` — backward-compatible with
    /// single-namespace enforcement.
    pub(crate) fn mint_authorized(namespace: Namespace, actor: ActorRef) -> Self {
        Self::mint_with_visibility(namespace, vec![], actor)
    }

    /// Convenience constructor for the local namespace with an anonymous actor.
    ///
    /// Only callable from within `khive-runtime`. External callers must use
    /// [`KhiveRuntime::authorize`] to mint tokens.
    // Used only in #[cfg(test)] blocks within this crate's src/ files.
    #[allow(dead_code)]
    pub(crate) fn local() -> Self {
        Self::mint_authorized(Namespace::local(), ActorRef::anonymous())
    }

    /// Convenience constructor for a specific namespace with an anonymous actor.
    ///
    /// Only callable from within `khive-runtime`. External callers must use
    /// [`KhiveRuntime::authorize`] to mint tokens.
    // Used only in #[cfg(test)] blocks within this crate's src/ files.
    #[allow(dead_code)]
    pub(crate) fn for_namespace(ns: Namespace) -> Self {
        Self::mint_authorized(ns, ActorRef::anonymous())
    }

    /// Return the write namespace this token authorises.
    ///
    /// All records created via this token land in this namespace.
    pub fn namespace(&self) -> &Namespace {
        &self.namespace
    }

    /// Return the namespace used by the originating dispatch's Gate check.
    /// It can differ from the primary storage namespace on an implicit request.
    /// Tokens minted directly, or reminted by `with_namespace`, use their primary.
    pub fn gate_namespace(&self) -> &Namespace {
        &self.gate_namespace
    }

    pub(crate) fn with_gate_namespace(mut self, namespace: Namespace) -> Self {
        self.gate_namespace = namespace;
        self
    }

    /// The exact submitted namespace argument, if the caller supplied one.
    /// Pack handlers normally receive params after dispatch strips this key.
    pub(crate) fn gate_explicit_namespace(&self) -> Option<&str> {
        self.gate_explicit_namespace.as_deref()
    }

    pub(crate) fn with_gate_explicit_namespace(mut self, namespace: Option<String>) -> Self {
        self.gate_explicit_namespace = namespace;
        self
    }

    /// Correlates handler-internal Gate consultations with their dispatch audit.
    pub(crate) fn request_id(&self) -> Option<u64> {
        self.request_id
    }

    pub(crate) fn with_request_id(mut self, request_id: Option<u64>) -> Self {
        self.request_id = request_id;
        self
    }

    /// Return the read-visibility set.
    ///
    /// List, search, and get operations must accept records whose namespace is
    /// a member of this set. The write namespace is always included.
    pub fn visible_namespaces(&self) -> &[Namespace] {
        &self.visible
    }

    /// Return a deduplicated list of visible namespace strings (borrowed).
    ///
    /// Convenience for passing directly to storage layer filters.
    pub fn visible_namespace_strs(&self) -> Vec<&str> {
        self.visible.iter().map(|ns| ns.as_str()).collect()
    }

    /// Return the actor reference embedded in this token.
    pub fn actor(&self) -> &ActorRef {
        &self.actor
    }

    /// Return the originating process's opaque attribution reference, when set.
    ///
    /// This is request metadata only. It never participates in gate checks,
    /// namespace visibility, or actor identity.
    pub fn process_ref(&self) -> Option<&str> {
        self.process_ref.as_deref()
    }

    pub(crate) fn with_process_ref(mut self, process_ref: Option<String>) -> Self {
        self.process_ref = process_ref;
        self
    }

    /// Return a new token with the same actor but a different namespace.
    /// The Gate namespace metadata is reset to the new primary namespace.
    ///
    /// The visible set is replaced with `[ns]`: this is a full read+write token
    /// for `ns`, not a type-enforced write-only or append-only capability. It is
    /// a capability-transfer primitive, not a policy gate: callers must enforce
    /// any ACL check before calling this and use the minted token only within
    /// the intended narrow scope (e.g. a single `create_note` call). A future
    /// security model should replace this pattern with a type-enforced
    /// append-only capability that goes through the Gate.
    pub fn with_namespace(&self, ns: Namespace) -> Self {
        Self::mint_authorized(ns, self.actor.clone()).with_process_ref(self.process_ref.clone())
    }
}

/// Read the optional request-origin process reference without normalization.
///
/// A non-Unicode environment value cannot be represented in JSON and is
/// treated as absent after emitting a warning that does not expose its bytes.
pub fn process_ref_from_env() -> Option<String> {
    match std::env::var("KHIVE_PROCESS_REF") {
        Ok(value) => Some(value),
        Err(std::env::VarError::NotPresent) => None,
        Err(std::env::VarError::NotUnicode(_)) => {
            tracing::warn!(
                "KHIVE_PROCESS_REF is not valid Unicode and cannot be represented in request metadata"
            );
            None
        }
    }
}

// ---- RuntimeConfig ----

/// Runtime configuration.
///
/// The `db_path` field remains for backward compatibility and as input to the
/// supported async khive-mcp/kkernel host builders. Direct backend assembly is
/// reserved for an already-coordinated database; use
/// [`crate::KhiveRuntime::from_prepared_backend`] when that precondition has
/// been established. `embedding_model` remains as the primary-model config
/// shorthand beside the provider registry.
#[derive(Clone, Debug)]
pub struct RuntimeConfig {
    /// Named custody references; secret material stays inside credential providers.
    pub credentials: Vec<crate::credentials::CredentialConfig>,
    /// Configured receipt key ring. Absence never generates a replacement key.
    pub visibility_receipts: Option<crate::credentials::VisibilityReceiptConfig>,

    pub mounts: Vec<crate::mount_config::MountConfig>,

    /// Path to the SQLite database file. `None` = in-memory (tests).
    ///
    /// Production boot passes this value to the async khive-mcp/kkernel host
    /// builders, which coordinate V21 before constructing runtimes. Tests and
    /// already-current single-backend callers may still use it directly.
    pub db_path: Option<std::path::PathBuf>,
    /// The WAL ceiling applied to this runtime's implicit main backend.
    /// Zero means disabled, including for a read-only backend that retains a
    /// nonzero configured value only for operator reporting.
    pub wal_ceiling_bytes: u64,
    /// The configured value before read-only writer-policy suppression.
    pub wal_ceiling_configured_bytes: u64,
    /// Where the configured ceiling came from.
    pub wal_ceiling_source: WalCeilingSource,
    /// Construction-time snapshot of the environment fallback. The host uses
    /// this same value to resolve every named backend before forwarding or
    /// opening it, without rereading mutable process environment.
    pub wal_ceiling_env_raw: Option<String>,
    /// One snapshot for named backend resolution and daemon compatibility.
    pub disk_guard_environment: khive_db::DiskGuardEnvironment,
    /// Captured implicit-main policy, or an explicit caller-supplied policy.
    pub disk_guard_config: Option<khive_db::EffectiveDiskGuardConfig>,
    /// Directory for the SQLite volume lock files, captured with the rest of
    /// boot configuration from [`crate::daemon::volume_lock_dir`]. `None` means
    /// no directory could be resolved; every writable file-backed open then
    /// fails with a configuration error naming `KHIVE_VOLUME_LOCK_DIR`.
    pub volume_lock_dir: Option<std::path::PathBuf>,
    /// Namespace used when no explicit namespace is provided.
    pub default_namespace: Namespace,
    /// Local embedding model. `None` alone does not disable embedding: setting
    /// only this field to `None` while `additional_embedding_models` is
    /// non-empty still registers those models. Both `embedding_model` and
    /// `additional_embedding_models` must be empty to disable built-in
    /// embedding model registration, at which point `hybrid_search` falls back
    /// to text-only. Use [`RuntimeConfig::no_embeddings`] to clear both fields
    /// together — it is the canonical constructor for this. Custom embedder
    /// providers registered later by packs are not affected by this field.
    ///
    /// Deprecated: embedding engines move to a per-pack `EmbedderRegistry`.
    /// This field persists for backward compatibility until the embedder registry
    /// is fully plumbed.
    pub embedding_model: Option<EmbeddingModel>,
    /// Additional embedding models to make available by request name.
    ///
    /// `embedding_model` remains the default used by existing `embed()` and
    /// `embed_batch()` callers. This list adds non-default models that can be
    /// selected with `embedder(name)`, `embed_with_model(...)`, memory
    /// `remember.embedding_model`, and memory `recall.embedding_model`.
    pub additional_embedding_models: Vec<EmbeddingModel>,
    /// Authorization gate consulted before each verb dispatch.
    /// Default: `AllowAllGate` (permissive). For production policy enforcement,
    /// plug in a Rego- or capability-witness-backed impl.
    pub gate: GateRef,
    /// Names of packs the transport layer should register into the VerbRegistry.
    /// The transport layer (e.g. `khive-mcp`) reads this list and instantiates
    /// the matching concrete pack types. Unknown names are reported as errors
    /// by the transport, not silently ignored.
    /// Defaults to the shipped production set returned by
    /// [`RuntimeConfig::built_in_packs`].
    pub packs: Vec<String>,
    /// Resolved aggregate admission budget for resident digest-verified blob
    /// buffers (ADR-160 D3), in raw bytes.
    ///
    /// `[runtime].blob_hydration_bytes` may raise or lower the built-in 256 MiB
    /// value, but config validation guarantees enough room for one maximum-size
    /// whole-blob read.
    pub blob_hydration_bytes: u64,
    /// Identifies this runtime's backend in a multi-backend deployment.
    ///
    /// Set by the boot path when constructing per-pack runtimes from `khive.toml`.
    /// Single-backend deployments use the default `BackendId::MAIN`.
    pub backend_id: BackendId,
    /// Brain profile to use for `memory.feedback` / `knowledge.feedback` and
    /// recall-time score boosting (ADR-035 §Brain profile configuration).
    ///
    /// Resolution order (highest to lowest, ADR-035): CLI flag, then
    /// `runtime.brain_profile` in project/global `khive.toml`, then the
    /// `KHIVE_BRAIN_PROFILE` env var as fallback default. Callers must keep
    /// env OUT of the base config they pass in (see `khive-mcp` serve.rs).
    /// 1. `--brain-profile` CLI flag (explicit only)
    /// 2. Namespace-bound profile resolved via `brain.resolve` at feedback time
    /// 3. Pack-local global tuning prior (default fallback)
    pub brain_profile: Option<String>,
    /// Operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
    ///
    /// OSS dispatch widens the DEFAULT multi-record read scope to
    /// `['local'] ∪ visible_namespaces`. Writes remain pinned to `'local'`.
    /// An explicit `namespace=` request param is a precise single-namespace
    /// escape and is not widened. Populated from `actor.visible_namespaces`
    /// in `khive.toml`.
    pub visible_namespaces: Vec<Namespace>,
    /// Namespaces this actor's comm.send/reply may deliver messages INTO
    /// (outbound, sender-side). Populated from `actor.allowed_outbound_namespaces`
    /// in `khive.toml`. Empty by default — cross-namespace delivery denied
    /// unless explicitly declared. The comm handler uses an ordinary
    /// `NamespaceToken` (minted via `with_namespace`) in an append-only manner;
    /// the token itself is NOT type-enforced write-only. The recipient-side
    /// `allowed_inbound_namespaces` (bilateral mutual opt-in) is reserved for
    /// a future cloud-path authorization ADR (not yet written).
    pub allowed_outbound_namespaces: Vec<Namespace>,
    /// Configured actor identity label (ADR-057). Populated from `[actor] id` in
    /// `khive.toml`. When `Some`, `authorize()` mints tokens carrying this actor
    /// label so that `comm.inbox` filters by `to_actor` instead of falling back to
    /// the party-line "local" behavior. When `None` (default), tokens carry
    /// `ActorRef::anonymous()` and inbox is scoped to party-line messages —
    /// those addressed to `"local"` or carrying no `to_actor` stamp.
    pub actor_id: Option<String>,
    /// Resolved `[brain]` policy from the serving process's configuration.
    pub brain: crate::engine_config::BrainSectionConfig,
    /// Resolved `[git_write]` policy allowlist (ADR-108 Amendment), populated
    /// from `khive.toml`'s `[[git_write.allowed]]` entries by
    /// [`runtime_config_from_khive_config`]. Threaded through so
    /// `khive-pack-git`'s write-verb handlers read an already-resolved policy
    /// instead of re-running config discovery (which would ignore an
    /// explicit `--config` path not also exported as `KHIVE_CONFIG`).
    pub git_write: crate::engine_config::GitWriteSectionConfig,
    /// Effective `[blob]` file-transfer opt-in, resolved with the exact environment
    /// opt-in during construction and retained by the blob pack.
    pub blob: crate::engine_config::BlobSectionConfig,
    /// Resolved `[exec]` sandbox section (ADR-181), threaded through like
    /// `git_write` so the exec pack reads an already-resolved config.
    pub exec: crate::engine_config::ExecSectionConfig,
    /// Resolved carrier and failure policy for telemetry emission.
    pub telemetry: crate::telemetry_config::TelemetryConfig,
    /// Resolved rendering timezone (ADR-169), consumed today by date-only
    /// `parse_due` anchoring. Populated from `[display] timezone` in
    /// `khive.toml` by [`runtime_config_from_khive_config`]; when absent,
    /// resolves once to the host's local IANA zone (falling back to UTC when
    /// the host zone cannot be determined) via [`resolve_default_display_timezone`].
    pub display_timezone: chrono_tz::Tz,
    /// Events-daemon split (ADR-170). `None` = legacy behavior: events persist
    /// in the main store. `Some` routes event persistence to the events database —
    /// forwarded over the events daemon socket in daemon deployments, opened
    /// directly in embedded/one-shot contexts. Populated by the transport
    /// hosts (khive-mcp serve, kkernel exec); tests and in-memory runtimes
    /// leave it `None`.
    pub events_split: Option<crate::events_split::EventsSplitConfig>,
    /// Resolved `[web]` policy (ADR-175 Amendment 1), threaded through like
    /// `exec`/`git_write` so `khive-pack-web` reads an already-resolved config.
    pub web: crate::engine_config::WebSectionConfig,
}

/// Parse a comma- or whitespace-separated pack list from a single string.
///
/// Empty entries are dropped, surrounding whitespace is trimmed.
pub fn parse_pack_list(s: &str) -> Vec<String> {
    s.split(|c: char| c == ',' || c.is_whitespace())
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_owned)
        .collect()
}

const ANN_REBUILD_THRESHOLD_DEFAULT: f64 = 0.20;

/// Read the ANN tail-rebuild fraction on each invocation (ADR-079 Amendment 2).
///
/// ADR-079's `ann_rebuild_threshold` default rationale describes the raw-row
/// policy, its workload assumptions and its coupled maintenance/visibility roles.
///
/// The exact environment value must parse as `f64` and lie in `(0, 1]`;
/// unset, non-Unicode, malformed and out-of-range values use `0.20`.
/// This reader deliberately does not trim or cache the value.
pub fn ann_rebuild_threshold_from_env() -> f64 {
    std::env::var("KHIVE_ANN_REBUILD_THRESHOLD")
        .ok()
        .and_then(|v| v.parse::<f64>().ok())
        .filter(|v| *v > 0.0 && *v <= 1.0)
        .unwrap_or(ANN_REBUILD_THRESHOLD_DEFAULT)
}

#[cfg(test)]
#[path = "config/ann_rebuild_threshold_tests.rs"]
mod ann_rebuild_threshold_tests;

/// Interpret the construction-time `KHIVE_ANN_FRESH_TAIL` value.
///
/// Preserve the escape hatch's existing semantics while moving its read out of
/// request serving: only `0` disables; unset and every other value enable.
fn ann_fresh_tail_enabled_from_value(value: Option<&str>) -> bool {
    value != Some("0")
}

/// Sample ADR-118's fresh-tail escape hatch for runtime construction.
///
/// Callers must retain the returned value for the runtime's lifetime instead
/// of re-reading the environment on a serving path. Only the exact value `0`
/// disables; unset and every other value enable.
pub fn ann_fresh_tail_enabled_from_env() -> bool {
    let value = std::env::var("KHIVE_ANN_FRESH_TAIL").ok();
    ann_fresh_tail_enabled_from_value(value.as_deref())
}

/// Resolve the host's local IANA zone name once, for [`RuntimeConfig`]'s
/// default `display_timezone` (ADR-169). Falls back to UTC when the host
/// zone cannot be determined (e.g. `TZ`/`/etc/localtime` unreadable) or does
/// not parse as a known `chrono_tz::Tz` — this must never panic or block
/// construction of a default `RuntimeConfig`.
pub fn resolve_default_display_timezone() -> chrono_tz::Tz {
    iana_time_zone::get_timezone()
        .ok()
        .and_then(|name| name.parse::<chrono_tz::Tz>().ok())
        .unwrap_or(chrono_tz::Tz::UTC)
}

impl Default for RuntimeConfig {
    fn default() -> Self {
        let db_path = std::env::var("HOME")
            .ok()
            .map(|h| std::path::PathBuf::from(h).join(".khive/khive.db"));
        let embedding_model = std::env::var("KHIVE_EMBEDDING_MODEL")
            .ok()
            .and_then(|s| s.parse().ok())
            .or(Some(EmbeddingModel::AllMiniLmL6V2));
        // Ships single-engine. A second engine is embedded on every write and
        // searched on every read, which is cost a deployment should opt into
        // rather than inherit: set KHIVE_ADDITIONAL_EMBEDDING_MODELS to add one.
        let additional_embedding_models = std::env::var("KHIVE_ADDITIONAL_EMBEDDING_MODELS")
            .ok()
            .map(|s| parse_embedding_model_list(&s))
            .unwrap_or_default();
        let packs = std::env::var("KHIVE_PACKS")
            .ok()
            .map(|s| parse_pack_list(&s))
            .filter(|v| !v.is_empty())
            .unwrap_or_else(Self::built_in_packs);
        let brain_profile = std::env::var("KHIVE_BRAIN_PROFILE")
            .ok()
            .filter(|s| !s.trim().is_empty());
        let actor_id = std::env::var("KHIVE_ACTOR")
            .ok()
            .filter(|s| !s.trim().is_empty());
        Self {
            credentials: Vec::new(),
            visibility_receipts: None,
            db_path,
            wal_ceiling_bytes: 0,
            wal_ceiling_configured_bytes: 0,
            wal_ceiling_source: WalCeilingSource::Default,
            wal_ceiling_env_raw: std::env::var_os("KHIVE_SQLITE_WAL_CEILING_BYTES")
                .map(|value| value.to_string_lossy().into_owned()),
            disk_guard_environment: khive_db::DiskGuardEnvironment::capture(),
            disk_guard_config: None,
            volume_lock_dir: crate::daemon::volume_lock_dir().ok(),
            default_namespace: Namespace::local(),
            embedding_model,
            additional_embedding_models,
            gate: Arc::new(AllowAllGate),
            packs,
            blob_hydration_bytes: crate::blob::DEFAULT_BLOB_HYDRATION_BYTES,
            backend_id: BackendId::main(),
            brain_profile,
            visible_namespaces: vec![],
            allowed_outbound_namespaces: vec![],
            actor_id,
            brain: crate::engine_config::BrainSectionConfig::default(),
            git_write: crate::engine_config::GitWriteSectionConfig::default(),
            blob: crate::engine_config::BlobSectionConfig {
                file_transfers: std::env::var("KHIVE_FILE_TRANSFERS")
                    .map(|value| value == "1")
                    .unwrap_or(false),
            },
            exec: crate::engine_config::ExecSectionConfig::default(),
            telemetry: crate::telemetry_config::TelemetryConfig::default(),
            mounts: Vec::new(),
            display_timezone: resolve_default_display_timezone(),
            events_split: None,
            web: crate::engine_config::WebSectionConfig::default(),
        }
    }
}

impl RuntimeConfig {
    /// The WAL ceiling policy this config asks its implicit main backend to
    /// open with. Preserves a configured ceiling for read-only reporting while
    /// ensuring a directly constructed config cannot silently drop a nonzero
    /// effective value: when the configured value is zero, the effective
    /// `wal_ceiling_bytes` is used. Host openers validate the captured
    /// environment through [`Self::resolve_wal_ceiling_policy`] first.
    pub fn wal_ceiling_policy(&self) -> khive_db::WalCeilingPolicy {
        khive_db::WalCeilingPolicy {
            bytes: if self.wal_ceiling_configured_bytes == 0 {
                self.wal_ceiling_bytes
            } else {
                self.wal_ceiling_configured_bytes
            },
            source: self.wal_ceiling_source,
        }
    }

    /// Resolve the implicit backend against the config's captured environment,
    /// retaining configured bytes separately from a read-only writer policy.
    pub fn resolve_wal_ceiling_policy(
        &mut self,
        read_only: bool,
    ) -> RuntimeResult<khive_db::WalCeilingPolicy> {
        let policy = self.wal_ceiling_policy();
        let backend_field = match self.wal_ceiling_source {
            WalCeilingSource::BackendField => Some(policy.bytes),
            WalCeilingSource::Environment if self.wal_ceiling_env_raw.is_some() => None,
            _ if policy.bytes != 0 => Some(policy.bytes),
            _ => None,
        };
        let kind = if self.db_path.is_some() {
            crate::BackendKind::Sqlite
        } else {
            crate::BackendKind::Memory
        };
        let resolved = crate::resolve_wal_ceiling(
            backend_field,
            self.wal_ceiling_env_raw.as_deref(),
            self.backend_id.as_str(),
            kind,
            true,
            read_only,
        )
        .map_err(|error| khive_db::SqliteError::InvalidConfig(error.to_string()))?;
        self.wal_ceiling_configured_bytes = resolved.configured_bytes;
        self.wal_ceiling_bytes = resolved.effective_bytes;
        self.wal_ceiling_source = resolved.source;
        Ok(self.wal_ceiling_policy())
    }

    /// Resolve the implicit backend's disk reserve and guard deadline from the
    /// config's captured environment, unless a caller already supplied a policy.
    /// Read-only and in-memory backends have no writer to guard.
    pub fn resolve_disk_guard_policy(
        &mut self,
        read_only: bool,
    ) -> RuntimeResult<Option<khive_db::EffectiveDiskGuardConfig>> {
        if self.db_path.is_none() {
            if self
                .disk_guard_config
                .is_some_and(|policy| policy.reserve_bytes != 0)
            {
                return Err(khive_db::SqliteError::InvalidConfig(
                    "nonzero disk_reserve_bytes requires a file-backed SQLite backend".into(),
                )
                .into());
            }
            return Ok(None);
        }
        if read_only {
            return Ok(None);
        }
        let policy = match self.disk_guard_config {
            Some(policy) => {
                policy.validate()?;
                policy
            }
            None => self.disk_guard_environment.resolve(None, None)?,
        };
        self.disk_guard_config = Some(policy);
        Ok(Some(policy))
    }

    /// Pack-registry discovery has no file-backed writer to govern.
    pub fn for_metadata_registry(mut self) -> Self {
        self.db_path = None;
        self.wal_ceiling_bytes = 0;
        self.wal_ceiling_configured_bytes = 0;
        self.wal_ceiling_source = WalCeilingSource::BackendField;
        self.disk_guard_config = None;
        self.embedding_model = None;
        self.additional_embedding_models.clear();
        self
    }

    /// Return the shipped pack set used when no CLI, environment, or
    /// configuration-file selection is present.
    pub fn built_in_packs() -> Vec<String> {
        [
            "kg",
            "gtd",
            "memory",
            "brain",
            "comm",
            "schedule",
            "knowledge",
            "session",
            "tool",
            "exec",
            "git",
            "code",
            "workspace",
            "blob",
        ]
        .into_iter()
        .map(String::from)
        .collect()
    }

    /// Build a `RuntimeConfig` with embedding disabled entirely.
    ///
    /// `embedding_model` and `additional_embedding_models` are computed
    /// independently inside [`Default::default`], so `RuntimeConfig {
    /// embedding_model: None, ..RuntimeConfig::default() }` does NOT produce a
    /// model-less runtime: `additional_embedding_models` still carries its
    /// env-driven fallback seed, and the note-write path fans out embedding to
    /// every registered model regardless of `embedding_model`: so the first
    /// `memory.remember` on a machine without local model files hard-fails
    /// instead of degrading to FTS-only.
    ///
    /// This constructor clears both fields together and ignores
    /// `KHIVE_ADDITIONAL_EMBEDDING_MODELS` unconditionally: the caller wants
    /// zero embedders, not "zero unless the environment disagrees". Use it on
    /// model-less machines (CI runners, fresh installs without local model
    /// files) instead of the two-field struct-update form.
    pub fn no_embeddings() -> Self {
        Self {
            embedding_model: None,
            additional_embedding_models: Vec::new(),
            ..Self::default()
        }
    }
}

/// Expand a leading `~` to `$HOME` in a path.
///
/// This is the single shared expansion point for every `RuntimeConfig.db_path`
/// construction site (CLI `--db`, `KHIVE_DB`, declared `[[backends]].path`).
/// [`resolve_db_anchor`] calls it so a `~`-prefixed override is expanded once,
/// at resolution, before the path ever reaches boot (single- or multi-backend),
/// `compute_config_id` fingerprinting, or the `--db` override equivalence
/// guard — those consumers then agree on one expanded path instead of a raw
/// `~` diverging from its already-expanded equivalent.
pub fn expand_tilde(path: &std::path::Path) -> std::path::PathBuf {
    let s = path.to_string_lossy();
    if let Some(rest) = s.strip_prefix("~/") {
        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
        std::path::PathBuf::from(format!("{home}/{rest}"))
    } else if s == "~" {
        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
        std::path::PathBuf::from(home)
    } else {
        path.to_path_buf()
    }
}

/// Resolve the `--db`/`KHIVE_DB` value into the anchor path used for tier-3
/// project-local `.khive/config.toml` discovery, mirroring the precedence
/// `kkernel mcp` and `kkernel exec` use to open the database itself:
/// `:memory:` has no file to anchor on (`None`); an explicit path anchors on
/// that path (with a leading `~` expanded via [`expand_tilde`]); an unset
/// value falls back to `$HOME/.khive/khive.db`, or `./.khive/khive.db` when
/// `HOME` is unset.
///
/// Always resolves to a concrete anchor (unlike a 2-arm "override the
/// default?" resolver): when `HOME` is unset this falls back to
/// `./.khive/khive.db` rather than `None`, deliberately diverging from
/// `RuntimeConfig::default()`: a caller anchoring config discovery needs a
/// concrete directory to search even without `HOME`.
pub fn resolve_db_anchor(db: Option<&str>) -> Option<std::path::PathBuf> {
    match db {
        Some(":memory:") => None,
        Some(path) => Some(expand_tilde(std::path::Path::new(path))),
        None => {
            let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
            Some(std::path::PathBuf::from(format!("{home}/.khive/khive.db")))
        }
    }
}

/// Assert that a resolved `db_path`: which `compute_config_id` folds into a
/// process's `config_id`: agrees with what [`resolve_db_anchor`] derives from
/// the same raw `--db`/`KHIVE_DB` input.
///
/// This compatibility entry point preserves the raw-string API. Construction
/// paths that already captured the anchor should call
/// [`assert_captured_db_anchor_consistent`] so they do not re-read mutable
/// process environment.
pub fn assert_db_anchor_consistent(
    resolved_db_path: Option<&std::path::Path>,
    args_db: Option<&str>,
) -> anyhow::Result<()> {
    let db_anchor = resolve_db_anchor(args_db);
    assert_captured_db_anchor_consistent(resolved_db_path, db_anchor.as_deref())
}

/// Assert that a resolved `db_path`: which `compute_config_id` folds into a
/// process's `config_id`: agrees with the database anchor captured from the
/// same `--db`/`KHIVE_DB` input at the construction boundary.
///
/// Guards against a construction path recomputing `db_path` independently of
/// `resolve_db_anchor`: left unchecked, that would silently desync `config_id`
/// from a daemon or peer sharing the same database instead of failing loud.
/// The caller passes the captured anchor so validation never re-reads mutable
/// process environment. Inert (`Ok(())`) when the anchor itself is `None` (the
/// `:memory:` sentinel) since there is nothing to compare against.
pub fn assert_captured_db_anchor_consistent(
    resolved_db_path: Option<&std::path::Path>,
    db_anchor: Option<&std::path::Path>,
) -> anyhow::Result<()> {
    let Some(anchor) = db_anchor else {
        return Ok(());
    };
    if resolved_db_path != Some(anchor) {
        anyhow::bail!(
            "db-path resolution drift at server construction: resolved db_path {:?} \
             does not match the canonical anchor {:?} computed by resolve_db_anchor \
             from the same --db input; this construction path likely recomputed the \
             db path independently instead of routing through the shared resolver, \
             which would desynchronize config_id from other processes sharing the \
             same database",
            resolved_db_path,
            anchor
        );
    }
    Ok(())
}

/// Resolve the per-connection attribution actor from the project/cwd-anchored
/// config tier, independently of the database-anchored config load that
/// governs `config_id`.
///
/// The database-anchored config load keeps `config_id` coherent between a
/// short-lived client and a long-running daemon sharing one database, but
/// when many per-project connections share one database under a single
/// `HOME` (the daemon-multiplexed fleet case), that shared config carries no
/// `[actor]` block, so every connection's write-stamp attribution collapses
/// to the default identity.
///
/// This performs a separate, cwd-anchored lookup (`db_path: None`) and reads
/// only `[actor].id`: it must not perturb `config_id` or `default_namespace`,
/// which remain governed exclusively by the database-anchored load.
///
/// `config_path` is the same explicit `--config`/`KHIVE_CONFIG` override the
/// caller's database-anchored load receives, so an explicit override wins
/// here too.
///
/// Returns `Ok(None)` when no project-anchored config exists, or it exists
/// but carries no non-empty `[actor].id`: callers fall through to their own
/// env/anonymous tiers in that case. A `config_path` naming a file that does
/// not exist is a loud error (`ExplicitConfigMissing`), matching the
/// database-anchored load's explicit-tier contract (ADR-035) — in production
/// that load errors first, so this lookup only ever sees an existing file.
pub fn resolve_project_actor_id(
    config_path: Option<&std::path::Path>,
) -> Result<Option<String>, crate::engine_config::ConfigError> {
    let khive_cfg = crate::engine_config::KhiveConfig::load_with_home_fallback(config_path, None)?;
    Ok(khive_cfg
        .and_then(|cfg| cfg.actor.id)
        .filter(|s| !s.trim().is_empty()))
}

// ---- Embedding model helpers ----

/// Sanitize an embedding model name into a valid SQL table suffix.
/// e.g. `bge-small-en-v1.5` -> `bge_small_en_v1_5`
pub(crate) fn vec_model_key(model: EmbeddingModel) -> String {
    sanitize_key(&model.to_string())
}

pub(crate) fn sanitize_key(s: &str) -> String {
    s.chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
        .collect()
}

pub(crate) fn build_embedder_registry(
    config: &RuntimeConfig,
) -> (crate::embedder_registry::EmbedderRegistry, Arc<str>) {
    use crate::embedder_registry::{EmbedderRegistry, LatticeEmbedderProvider};
    let mut registry = EmbedderRegistry::new();
    for model in configured_embedding_models(config) {
        registry.register_builtin(LatticeEmbedderProvider::new(model));
    }
    let default_embedder_name = config
        .embedding_model
        .map(|model| Arc::<str>::from(model.to_string()))
        .unwrap_or_else(|| Arc::<str>::from(""));
    (registry, default_embedder_name)
}

fn configured_embedding_models(config: &RuntimeConfig) -> Vec<EmbeddingModel> {
    let mut models: Vec<EmbeddingModel> = Vec::new();
    if let Some(model) = config.embedding_model {
        models.push(model);
    }
    for model in config.additional_embedding_models.iter().copied() {
        if !models.contains(&model) {
            models.push(model);
        }
    }
    models
}

pub(crate) fn register_configured_embedding_models(
    backend: &StorageBackend,
    config: &RuntimeConfig,
) -> RuntimeResult<()> {
    for model in configured_embedding_models(config) {
        backend.register_embedding_model(
            &model.to_string(),
            model.model_id(),
            model.key_version(),
            model.dimensions() as u32,
        )?;
    }
    Ok(())
}

/// Build a `RuntimeConfig` from a parsed `KhiveConfig`.
///
/// For each `[[engines]]` entry:
/// - The engine flagged `default = true` becomes `RuntimeConfig::embedding_model`.
/// - All other engines become `RuntimeConfig::additional_embedding_models`.
///
/// `KhiveConfig::validate()` rejects an unrecognized engine model at load time.
/// A caller-constructed config that bypasses validation still skips an invalid
/// engine with a warning here.
///
/// If `khive_cfg.engines` is empty, the returned `RuntimeConfig` uses the
/// env-var-derived defaults from `RuntimeConfig::default()`.
///
/// When both a config file and `KHIVE_EMBEDDING_MODEL` env var are present,
/// the caller is responsible for emitting a warning that env vars are overridden.
/// This function purely converts `KhiveConfig` to `RuntimeConfig` fields.
pub fn runtime_config_from_khive_config(
    khive_cfg: &crate::engine_config::KhiveConfig,
    base: RuntimeConfig,
) -> RuntimeConfig {
    // `[actor] id` never becomes the storage namespace (writes always pin to
    // `local`); it only widens the read visible-set below.
    let default_namespace = base.default_namespace.clone();
    let mounts = khive_cfg.mounts.clone();
    let credentials = khive_cfg.credentials.clone();
    let visibility_receipts = khive_cfg.visibility_receipts.clone();

    // base.brain_profile must carry only the explicit CLI tier, never an env
    // value: env sits below toml in precedence and is applied later by the MCP resolver.
    let brain_profile = base.brain_profile.clone().or_else(|| {
        khive_cfg
            .runtime
            .brain_profile
            .clone()
            .filter(|s| !s.trim().is_empty())
    });

    let visible_namespaces: Vec<Namespace> = khive_cfg
        .actor
        .visible_namespaces
        .as_deref()
        .unwrap_or_default()
        .iter()
        .filter_map(|s| match Namespace::parse(s) {
            Ok(ns) => Some(ns),
            Err(e) => {
                tracing::warn!(ns = %s, error = %e, "actor.visible_namespaces: invalid namespace; skipped");
                None
            }
        })
        .collect();

    // Fold actor.id's namespace into visible_namespaces so default reads widen
    // to {local} ∪ {actor namespace}; skipped when it parses to `local` (would
    // duplicate the primary namespace already minted) or is already present.
    let visible_namespaces = if let Some(id) = khive_cfg.actor.id.as_deref() {
        match Namespace::parse(id) {
            Ok(actor_ns) if actor_ns != Namespace::local() => {
                let mut v = visible_namespaces;
                if !v.contains(&actor_ns) {
                    v.push(actor_ns);
                }
                v
            }
            _ => visible_namespaces,
        }
    } else {
        visible_namespaces
    };

    // KhiveConfig::validate() guarantees these are valid Namespace strings, so
    // parse failures here are unreachable for validated configs; filter_map+warn
    // guards against a validation bug panicking instead.
    let allowed_outbound_namespaces: Vec<Namespace> = khive_cfg
        .actor
        .allowed_outbound_namespaces
        .iter()
        .filter_map(|s| match Namespace::parse(s) {
            Ok(ns) => Some(ns),
            Err(e) => {
                tracing::warn!(ns = %s, error = %e, "actor.allowed_outbound_namespaces: invalid namespace; skipped");
                None
            }
        })
        .collect();

    // Precedence: TOML `[actor] id` > `base.actor_id` (env/CLI-resolved) >
    // anonymous. Falls back to `base.actor_id` rather than `None` when
    // `[actor] id` is absent: otherwise an env-resolved actor like
    // `KHIVE_ACTOR` is silently dropped whenever a project config exists
    // without an `[actor]` block.
    let actor_id = khive_cfg
        .actor
        .id
        .clone()
        .filter(|s| !s.trim().is_empty())
        .or_else(|| base.actor_id.clone());

    let gate = khive_cfg
        .gate
        .as_ref()
        .map(|gate| {
            Arc::new(khive_gate::CallerEnrollmentGate::with_write_denials(
                gate.granted_actors.clone(),
                gate.grant_unattributed,
                gate.deny_writes_for.clone(),
            )) as GateRef
        })
        .unwrap_or_else(|| base.gate.clone());
    let gate = crate::mailbox_view::configured_mailbox_gate(&khive_cfg.actor, gate);

    let brain = khive_cfg.brain.clone();
    let git_write = khive_cfg.git_write.clone();
    let blob = crate::engine_config::BlobSectionConfig {
        file_transfers: khive_cfg.blob.file_transfers || base.blob.file_transfers,
    };
    let exec = khive_cfg.exec.clone();
    let telemetry = khive_cfg.telemetry.clone();
    let web = khive_cfg.web.clone();
    let blob_hydration_bytes = khive_cfg
        .runtime
        .blob_hydration_bytes
        .unwrap_or(base.blob_hydration_bytes);

    // KhiveConfig::validate() guarantees a present timezone parses as a valid
    // chrono_tz::Tz, so the fallback to base.display_timezone below is only
    // reachable for an unvalidated caller-constructed KhiveConfig, not a
    // config loaded via KhiveConfig::load.
    let display_timezone = khive_cfg
        .display
        .timezone
        .as_deref()
        .and_then(|s| s.parse::<chrono_tz::Tz>().ok())
        .unwrap_or(base.display_timezone);

    if khive_cfg.engines.is_empty() {
        return RuntimeConfig {
            credentials,
            visibility_receipts,
            default_namespace,
            brain_profile,
            visible_namespaces,
            allowed_outbound_namespaces,
            actor_id,
            gate,
            brain,
            git_write,
            blob,
            exec,
            telemetry,
            mounts,
            blob_hydration_bytes,
            display_timezone,
            web,
            ..base
        };
    }

    let mut embedding_model: Option<EmbeddingModel> = None;
    let mut additional: Vec<EmbeddingModel> = Vec::new();

    for engine in &khive_cfg.engines {
        match parse_embedding_model_alias(&engine.model) {
            Some(model) => {
                if engine.default {
                    embedding_model = Some(model);
                } else {
                    additional.push(model);
                }
            }
            None => {
                tracing::warn!(
                    engine = %engine.name,
                    model = %engine.model,
                    "engine config: unknown model name; engine will be skipped"
                );
            }
        }
    }

    RuntimeConfig {
        credentials,
        visibility_receipts,
        embedding_model,
        additional_embedding_models: additional,
        default_namespace,
        brain_profile,
        visible_namespaces,
        allowed_outbound_namespaces,
        actor_id,
        gate,
        brain,
        git_write,
        blob,
        exec,
        telemetry,
        mounts,
        blob_hydration_bytes,
        display_timezone,
        web,
        ..base
    }
}

#[cfg(test)]
mod display_timezone_tests {
    use super::resolve_default_display_timezone;

    // The host's actual zone is environment-dependent (CI runners are
    // typically UTC), so this only asserts the resolver always produces some
    // valid, non-panicking Tz — never that it matches a specific zone.
    #[test]
    fn resolve_default_display_timezone_never_panics() {
        let _tz = resolve_default_display_timezone();
    }
}

/// Parse a comma- or whitespace-separated list of embedding model names.
fn parse_embedding_model_list(s: &str) -> Vec<EmbeddingModel> {
    parse_pack_list(s)
        .into_iter()
        .filter_map(|raw| {
            let parsed = parse_embedding_model_alias(&raw);
            if parsed.is_none() && !raw.trim().is_empty() {
                tracing::warn!(
                    model = %raw,
                    "KHIVE_ADDITIONAL_EMBEDDING_MODELS contains unknown model name; ignored. \
                     Valid forms: short alias like 'paraphrase' or a fully-qualified key \
                     from lattice_embed::EmbeddingModel::from_str."
                );
            }
            parsed
        })
        .collect()
}

pub(crate) fn parse_embedding_model_alias(name: &str) -> Option<EmbeddingModel> {
    let normalized = name.trim().to_ascii_lowercase().replace('_', "-");
    match normalized.as_str() {
        "paraphrase" => Some(EmbeddingModel::ParaphraseMultilingualMiniLmL12V2),
        _ => normalized.parse().ok(),
    }
}

#[cfg(test)]
mod resolve_db_anchor_tests {
    use super::resolve_db_anchor;

    #[test]
    fn memory_sentinel_maps_to_none() {
        assert_eq!(resolve_db_anchor(Some(":memory:")), None);
    }

    #[test]
    fn explicit_path_maps_to_some() {
        assert_eq!(
            resolve_db_anchor(Some("/tmp/khive-anchor-test.db")),
            Some(std::path::PathBuf::from("/tmp/khive-anchor-test.db"))
        );
    }

    #[test]
    fn absent_maps_to_home_default() {
        let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
        let expected = std::path::PathBuf::from(format!("{home}/.khive/khive.db"));
        assert_eq!(resolve_db_anchor(None), Some(expected));
    }
}

#[cfg(test)]
mod assert_db_anchor_consistent_tests {
    use super::{assert_captured_db_anchor_consistent, resolve_db_anchor};
    use crate::assert_db_anchor_consistent;

    #[test]
    fn diverging_db_path_is_rejected_naming_both_paths() {
        let args_db = "/tmp/khive-anchor-guard-real.db";
        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
        let wrong = std::path::PathBuf::from("/tmp/khive-anchor-guard-wrong.db");

        let err =
            assert_captured_db_anchor_consistent(Some(wrong.as_path()), Some(anchor.as_path()))
                .expect_err("a resolved db_path diverging from the anchor must be rejected");

        let msg = err.to_string();
        assert!(
            msg.contains(&wrong.display().to_string()),
            "error must name the resolved (wrong) path: {msg}"
        );
        assert!(
            msg.contains(&anchor.display().to_string()),
            "error must name the canonical anchor path: {msg}"
        );
    }

    #[test]
    fn matching_explicit_db_path_passes() {
        let args_db = "/tmp/khive-anchor-guard-consistent.db";
        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
        assert!(assert_captured_db_anchor_consistent(
            Some(anchor.as_path()),
            Some(anchor.as_path())
        )
        .is_ok());
    }

    #[test]
    fn memory_sentinel_anchor_is_inert() {
        // `resolve_db_anchor(":memory:")` yields `None` — there is no canonical
        // path to assert against, so the guard passes regardless of what
        // `resolved_db_path` happens to carry.
        let bogus = std::path::PathBuf::from("/tmp/should-not-matter.db");
        assert!(assert_captured_db_anchor_consistent(Some(bogus.as_path()), None).is_ok());
        assert!(assert_captured_db_anchor_consistent(None, None).is_ok());
    }

    #[test]
    fn normal_boot_with_db_unset_passes_silently() {
        // Mirrors a normal boot with `--db` unset: `resolve_db_anchor(None)`
        // always resolves to `Some(..)` (HOME-set or -unset both produce a
        // concrete anchor), so a runtime whose resolved `db_path` matches
        // passes silently.
        let anchor = resolve_db_anchor(None);
        assert!(assert_captured_db_anchor_consistent(anchor.as_deref(), anchor.as_deref()).is_ok());
    }

    #[test]
    fn public_compatibility_wrapper_accepts_path_and_memory_sentinel() {
        let args_db = "/tmp/khive-anchor-guard-public-api.db";
        let anchor = resolve_db_anchor(Some(args_db)).expect("explicit path always anchors");
        assert!(assert_db_anchor_consistent(Some(anchor.as_path()), Some(args_db)).is_ok());

        let unrelated = std::path::Path::new("/tmp/khive-anchor-guard-unrelated.db");
        assert!(assert_db_anchor_consistent(Some(unrelated), Some(":memory:")).is_ok());
    }
}

#[cfg(test)]
mod resolve_project_actor_id_tests {
    use super::resolve_project_actor_id;

    fn write_toml(dir: &tempfile::TempDir, body: &str) -> std::path::PathBuf {
        let path = dir.path().join("config.toml");
        std::fs::write(&path, body).expect("write config.toml");
        path
    }

    #[test]
    fn extracts_non_empty_actor_id_from_explicit_path() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = write_toml(&dir, "[actor]\nid = \"lambda:explicit-actor\"\n");

        assert_eq!(
            resolve_project_actor_id(Some(&path)).expect("no error"),
            Some("lambda:explicit-actor".to_string())
        );
    }

    #[test]
    fn missing_explicit_path_fails_loud() {
        // The explicit tier is enforced inside the loader
        // (`KhiveConfig::load_with_home_fallback_and_source` returns
        // `ExplicitConfigMissing`): a nonexistent explicit path is an error,
        // never a silent `None` (ADR-035).
        let missing = std::path::PathBuf::from("/nonexistent/khive-project-actor-test/config.toml");
        let err = resolve_project_actor_id(Some(&missing))
            .expect_err("a missing explicit path must fail loud");
        assert!(
            matches!(
                err,
                crate::engine_config::ConfigError::ExplicitConfigMissing { .. }
            ),
            "expected ExplicitConfigMissing, got {err:?}"
        );
    }

    #[test]
    fn propagates_load_error_for_invalid_actor_id() {
        // `KhiveConfig::load`'s `validate()` rejects an empty `[actor] id` before
        // the emptiness filter in `resolve_project_actor_id` ever sees it; this
        // asserts the error surfaces rather than being swallowed into `Ok(None)`.
        let dir = tempfile::tempdir().expect("tempdir");
        let path = write_toml(&dir, "[actor]\nid = \"\"\n");

        let err = resolve_project_actor_id(Some(&path)).expect_err("invalid actor.id must error");
        let root = match &err {
            crate::engine_config::ConfigError::InFile { source, .. } => source.as_ref(),
            other => other,
        };
        assert!(
            matches!(
                root,
                crate::engine_config::ConfigError::InvalidActorId { .. }
            ),
            "expected InvalidActorId, got {err:?}"
        );
    }

    #[test]
    fn returns_none_when_config_has_no_actor_section() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = write_toml(
            &dir,
            "[[engines]]\nname = \"primary\"\nmodel = \"bge-small-en-v1.5\"\ndefault = true\n",
        );

        assert_eq!(
            resolve_project_actor_id(Some(&path)).expect("no error"),
            None,
            "a config file with no [actor] section must resolve to None"
        );
    }
}

#[cfg(test)]
mod no_embeddings_tests {
    use super::*;
    use serial_test::serial;

    #[test]
    fn no_embeddings_clears_both_fields() {
        let config = RuntimeConfig::no_embeddings();
        assert_eq!(config.embedding_model, None);
        assert!(config.additional_embedding_models.is_empty());
        assert!(
            configured_embedding_models(&config).is_empty(),
            "no_embeddings() must yield zero configured embedders"
        );
    }

    #[test]
    fn blob_hydration_default_is_four_portable_whole_objects() {
        assert_eq!(
            RuntimeConfig::default().blob_hydration_bytes,
            4 * khive_storage::MAX_BLOB_WHOLE_BYTES
        );
    }

    #[test]
    #[serial]
    fn no_embeddings_ignores_additional_env_override() {
        // no_embeddings() is an unconditional opt-out: even if the caller's
        // environment sets KHIVE_ADDITIONAL_EMBEDDING_MODELS, the resulting
        // config must still report zero embedders.
        std::env::set_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS", "paraphrase");
        let config = RuntimeConfig::no_embeddings();
        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");

        assert!(config.additional_embedding_models.is_empty());
        assert!(configured_embedding_models(&config).is_empty());
    }

    #[test]
    #[serial]
    fn default_computes_additional_models_independently_of_no_embeddings() {
        // `Default` must keep computing `embedding_model` and
        // `additional_embedding_models` independently; `no_embeddings()` is a
        // separate opt-out constructor, not a change to `Default`'s seeding.
        // The env var is SET here rather than cleared: since Default now ships
        // no secondary engine, an unset env would make Default and
        // no_embeddings() indistinguishable and the test would stop
        // discriminating the thing it exists to discriminate.
        std::env::set_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS", "paraphrase");
        let config = RuntimeConfig::default();
        let buggy_form = RuntimeConfig {
            embedding_model: None,
            ..RuntimeConfig::default()
        };
        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");

        assert_eq!(
            config.additional_embedding_models,
            vec![EmbeddingModel::ParaphraseMultilingualMiniLmL12V2]
        );

        // Overriding only `embedding_model` via struct-update syntax does not
        // clear `additional_embedding_models`.
        assert!(
            !buggy_form.additional_embedding_models.is_empty(),
            "Default's independent-field seeding must remain unchanged; \
             no_embeddings() is the fix, not a change to Default"
        );
    }

    #[test]
    #[serial]
    fn default_ships_a_single_engine_when_env_unset() {
        // A secondary engine is embedded on every write and searched on every
        // read. That cost is opted into, not inherited.
        std::env::remove_var("KHIVE_ADDITIONAL_EMBEDDING_MODELS");
        let config = RuntimeConfig::default();

        assert!(
            config.additional_embedding_models.is_empty(),
            "shipped default must register one engine; a second is opt-in via \
             KHIVE_ADDITIONAL_EMBEDDING_MODELS"
        );
        assert_eq!(
            configured_embedding_models(&config),
            vec![EmbeddingModel::AllMiniLmL6V2]
        );
    }
}

#[cfg(test)]
mod ann_fresh_tail_config_tests {
    use super::ann_fresh_tail_enabled_from_value;

    #[test]
    fn only_exact_zero_disables_fresh_tail() {
        assert!(ann_fresh_tail_enabled_from_value(None));
        assert!(!ann_fresh_tail_enabled_from_value(Some("0")));
        assert!(ann_fresh_tail_enabled_from_value(Some("1")));
        assert!(ann_fresh_tail_enabled_from_value(Some("false")));
        assert!(ann_fresh_tail_enabled_from_value(Some(" 0")));
    }
}

#[cfg(test)]
mod configured_embedding_models_order_tests {
    use super::*;

    /// Issue #1115: the configured engine list must preserve declaration
    /// order (primary first, then `additional_embedding_models` in order)
    /// instead of alphabetizing — any consumer that treats the list as
    /// ordered (e.g. recall fan-out) otherwise gets the wrong primary.
    #[test]
    fn preserves_primary_first_then_additional_in_declared_order() {
        let config = RuntimeConfig {
            embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
            additional_embedding_models: vec![
                EmbeddingModel::Qwen3Embedding4B,
                EmbeddingModel::BgeSmallEnV15,
            ],
            ..RuntimeConfig::default()
        };

        assert_eq!(
            configured_embedding_models(&config),
            vec![
                EmbeddingModel::AllMiniLmL6V2,
                EmbeddingModel::Qwen3Embedding4B,
                EmbeddingModel::BgeSmallEnV15,
            ],
            "order must be primary-first, then additional models as declared, \
             not alphabetized"
        );
    }

    /// A model repeated in both `embedding_model` and `additional_embedding_models`
    /// must be deduped to a single entry, keeping its first (primary) position.
    #[test]
    fn dedupes_model_shared_between_primary_and_additional() {
        let config = RuntimeConfig {
            embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
            additional_embedding_models: vec![
                EmbeddingModel::AllMiniLmL6V2,
                EmbeddingModel::BgeSmallEnV15,
            ],
            ..RuntimeConfig::default()
        };

        assert_eq!(
            configured_embedding_models(&config),
            vec![EmbeddingModel::AllMiniLmL6V2, EmbeddingModel::BgeSmallEnV15],
            "the shared model must appear once, in its primary position"
        );
    }
}