1use std::collections::{HashMap, HashSet, VecDeque};
14use std::sync::Arc;
15use std::time::Instant;
16
17use crate::operations::{LinkSpec, Resolved};
18use crate::runtime::NamespaceToken;
19use async_trait::async_trait;
20use khive_gate::{AllowAllGate, AuditEvent, GateDecision, GateRef, GateRequest};
21use khive_storage::{Event, EventStore, EventView, SubstrateKind};
22use khive_types::{EventKind, EventOutcome, Namespace};
23use serde_json::Value;
24
25pub use khive_types::{
26 EdgeEndpointRule, EndpointKind, EntityTypeDef, HandlerDef, NoteKindSpec, NoteLifecycleSpec,
27 PackSchemaPlan, ParamDef, VerbCategory, VerbPresentationPolicy, Visibility,
28 RESERVED_ENVELOPE_ARGS,
29};
30#[allow(deprecated)]
32pub use khive_types::VerbDef;
33
34use crate::validation::ValidationRule;
35
36pub const GENERIC_CRUD_PACK: &str = "kg";
44
45pub const AUDIT_PERSISTENCE_SKIPPED_READ_ONLY: &str = "audit_persistence_skipped_read_only";
48
49const FULL_UUID_IDENTIFIER_HELP: &str = "A complete UUID spelling accepted by the consuming \
50 parameter directly names one globally unique record; direct UUID lookup is not a namespace \
51 search. Strict identifier responses use canonical lowercase dashed UUIDs.";
52const SHORT_PREFIX_IDENTIFIER_HELP: &str = "A short UUID prefix is at least 8 hexadecimal \
53 characters without dashes that do not parse as a complete UUID. It is a resolution, not a \
54 direct identifier; a 32-character compact UUID is complete input instead. Its lookup scope belongs to the consuming parameter: \
55 operations governed by ADR-007's by-ID contract resolve without a namespace filter, while \
56 other resolvers may search only the caller's primary namespace. A prefix can be missing or \
57 ambiguous.";
58const IDENTIFIER_PARAMETER_HELP: &str = "A parameter that requires a full UUID rejects prefixes \
59 and explains the resolution consequence. Its corresponding response field remains a \
60 canonical full UUID so the value can be submitted again.";
61
62fn identifier_resolution_help() -> Value {
63 serde_json::json!({
64 "full_uuid": FULL_UUID_IDENTIFIER_HELP,
65 "short_prefix": SHORT_PREFIX_IDENTIFIER_HELP,
66 "parameter_rule": IDENTIFIER_PARAMETER_HELP,
67 })
68}
69
70#[derive(Debug, Default, Clone)]
80pub struct SchemaPlan {
81 pub pack: &'static str,
83 pub statements: &'static [&'static str],
87}
88
89impl SchemaPlan {
90 pub const fn empty() -> Self {
95 Self {
96 pack: "",
97 statements: &[],
98 }
99 }
100
101 pub fn is_empty(&self) -> bool {
103 self.statements.is_empty()
104 }
105}
106
107#[async_trait]
114pub trait DispatchHook: Send + Sync {
115 async fn on_dispatch(&self, view: &EventView);
120}
121
122use crate::error::{
123 CircularPackDependency, MissingPackDependencies, MissingPackDependency, RuntimeError,
124};
125use crate::KhiveRuntime;
126
127#[async_trait]
136pub trait PackRuntime: Send + Sync {
137 fn name(&self) -> &str;
139
140 fn note_kinds(&self) -> &'static [&'static str];
142
143 fn entity_kinds(&self) -> &'static [&'static str];
145
146 fn brain_consumer_kinds(&self) -> &'static [&'static str] {
149 &[]
150 }
151
152 fn handlers(&self) -> &'static [HandlerDef];
154
155 fn edge_rules(&self) -> &'static [EdgeEndpointRule] {
159 &[]
160 }
161
162 fn entity_types(&self) -> &'static [EntityTypeDef] {
166 &[]
167 }
168
169 fn requires(&self) -> &'static [&'static str] {
172 &[]
173 }
174
175 fn note_kind_specs(&self) -> &'static [NoteKindSpec] {
182 &[]
183 }
184
185 fn kind_hook(&self, _kind: &str) -> Option<Arc<dyn KindHook>> {
193 None
194 }
195
196 fn accept_channel_ingest_capability(&self, _capability: ChannelIngestCapability) {}
209
210 fn schema_plan(&self) -> SchemaPlan {
226 SchemaPlan::empty()
227 }
228
229 fn validation_rules(&self) -> &'static [ValidationRule] {
237 &[]
238 }
239
240 fn register_embedders(&self, _runtime: &KhiveRuntime) {}
246
247 fn register_entity_type_validator(&self, _runtime: &KhiveRuntime) {}
253
254 fn register_entity_type_validator_with_types(
261 &self,
262 runtime: &KhiveRuntime,
263 _pack_entity_types: &[EntityTypeDef],
264 ) {
265 self.register_entity_type_validator(runtime);
266 }
267
268 fn register_note_mutation_hook(&self, _runtime: &KhiveRuntime) {}
275
276 fn register_note_write_validator(&self, _runtime: &KhiveRuntime) {}
287
288 async fn warm(&self) {}
292
293 fn registered_embedding_model_names(&self) -> Vec<String> {
298 Vec::new()
299 }
300
301 async fn dispatch(
308 &self,
309 verb: &str,
310 params: Value,
311 registry: &VerbRegistry,
312 token: &NamespaceToken,
313 ) -> Result<Value, RuntimeError>;
314}
315
316#[async_trait]
332pub trait KindHook: Send + Sync + std::fmt::Debug {
333 async fn prepare_create(
339 &self,
340 runtime: &KhiveRuntime,
341 args: &mut Value,
342 ) -> Result<(), RuntimeError>;
343
344 async fn after_create(
353 &self,
354 runtime: &KhiveRuntime,
355 id: uuid::Uuid,
356 args: &Value,
357 ) -> Result<(), RuntimeError>;
358
359 async fn prepare_note_update(
366 &self,
367 runtime: &KhiveRuntime,
368 token: &NamespaceToken,
369 note: &khive_storage::Note,
370 args: &mut Value,
371 ) -> Result<(), RuntimeError> {
372 let properties = args.get("properties").filter(|value| !value.is_null());
373 self.validate_note_update(runtime, token, note, properties)
374 .await
375 }
376
377 async fn validate_note_update(
383 &self,
384 _runtime: &KhiveRuntime,
385 _token: &NamespaceToken,
386 _note: &khive_storage::Note,
387 _properties: Option<&Value>,
388 ) -> Result<(), RuntimeError> {
389 Ok(())
390 }
391
392 async fn validate_links(
397 &self,
398 _runtime: &KhiveRuntime,
399 _token: &NamespaceToken,
400 _links: &[crate::LinkSpec],
401 ) -> Result<(), RuntimeError> {
402 Ok(())
403 }
404}
405
406#[async_trait]
414pub trait PackByIdResolver: Send + Sync {
415 async fn resolve_by_id(
425 &self,
426 id: uuid::Uuid,
427 ) -> Result<Option<crate::Resolved>, crate::RuntimeError>;
428
429 async fn resolve_by_id_including_deleted(
434 &self,
435 id: uuid::Uuid,
436 ) -> Result<Option<crate::Resolved>, crate::RuntimeError> {
437 self.resolve_by_id(id).await
438 }
439
440 async fn delete_by_id(
449 &self,
450 id: uuid::Uuid,
451 hard: bool,
452 ) -> Result<serde_json::Value, crate::RuntimeError>;
453}
454
455pub struct VerbRegistryBuilder {
460 packs: Vec<Box<dyn PackRuntime>>,
461 resolvers: Vec<(String, Box<dyn PackByIdResolver>)>,
462 gate: GateRef,
463 default_namespace: String,
464 visible_namespaces: Vec<Namespace>,
472 actor_id: Option<String>,
475 event_store: Option<Arc<dyn EventStore>>,
482 audit_store_read_only: bool,
485 dispatch_hook: Option<Arc<dyn DispatchHook>>,
491 audit_batch_config: Option<crate::audit_batch::AuditBatchConfig>,
495}
496
497impl VerbRegistryBuilder {
498 pub fn new() -> Self {
500 Self {
501 packs: Vec::new(),
502 resolvers: Vec::new(),
503 gate: std::sync::Arc::new(AllowAllGate),
504 default_namespace: Namespace::local().as_str().to_string(),
505 visible_namespaces: vec![],
506 actor_id: None,
507 event_store: None,
508 audit_store_read_only: false,
509 dispatch_hook: None,
510 audit_batch_config: None,
511 }
512 }
513
514 pub fn with_visible_namespaces(&mut self, ns: Vec<Namespace>) -> &mut Self {
522 self.visible_namespaces = ns;
523 self
524 }
525
526 pub fn with_actor_id(&mut self, actor_id: Option<String>) -> &mut Self {
533 self.actor_id = actor_id;
534 self
535 }
536
537 pub fn register<P: khive_types::Pack + PackRuntime + 'static>(&mut self, pack: P) -> &mut Self {
540 self.packs.push(Box::new(pack));
541 self
542 }
543
544 pub(crate) fn register_boxed(&mut self, pack: Box<dyn PackRuntime>) -> &mut Self {
551 self.packs.push(pack);
552 self
553 }
554
555 pub fn register_resolver(
560 &mut self,
561 name: impl Into<String>,
562 resolver: Box<dyn PackByIdResolver>,
563 ) -> &mut Self {
564 self.resolvers.push((name.into(), resolver));
565 self
566 }
567
568 pub fn with_gate(&mut self, gate: GateRef) -> &mut Self {
574 self.gate = gate;
575 self
576 }
577
578 pub fn with_default_namespace(&mut self, ns: impl Into<String>) -> &mut Self {
583 self.default_namespace = ns.into();
584 self
585 }
586
587 pub fn with_event_store(&mut self, store: Arc<dyn EventStore>) -> &mut Self {
597 self.event_store = Some(store);
598 self.audit_store_read_only = false;
599 self
600 }
601
602 pub fn with_audit_batch_config(
609 &mut self,
610 config: crate::audit_batch::AuditBatchConfig,
611 ) -> &mut Self {
612 self.audit_batch_config = Some(config);
613 self
614 }
615
616 pub fn with_read_only_audit_store(&mut self) -> &mut Self {
622 self.event_store = None;
623 self.audit_store_read_only = true;
624 self
625 }
626
627 pub fn with_dispatch_hook(&mut self, hook: Arc<dyn DispatchHook>) -> &mut Self {
638 self.dispatch_hook = Some(hook);
639 self
640 }
641
642 pub fn build(self) -> Result<VerbRegistry, RuntimeError> {
648 let packs = self.packs;
649 let mut name_to_idx: HashMap<&str, usize> = HashMap::with_capacity(packs.len());
650 for (idx, pack) in packs.iter().enumerate() {
651 if let Some(prev_idx) = name_to_idx.insert(pack.name(), idx) {
652 return Err(RuntimeError::PackRedeclared {
653 name: pack.name().to_string(),
654 first_idx: prev_idx,
655 second_idx: idx,
656 });
657 }
658 }
659
660 for pack in &packs {
664 for handler in pack.handlers() {
665 for parameter in handler.params {
666 if RESERVED_ENVELOPE_ARGS.contains(¶meter.name) {
667 return Err(RuntimeError::ReservedEnvelopeParam {
668 pack: pack.name().to_string(),
669 verb: handler.name.to_string(),
670 param: parameter.name.to_string(),
671 });
672 }
673 }
674 }
675 }
676
677 let mut missing: Vec<MissingPackDependency> = Vec::new();
678 let mut indegree = vec![0usize; packs.len()];
679 let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); packs.len()];
680
681 for (idx, pack) in packs.iter().enumerate() {
682 for &requires in pack.requires() {
683 match name_to_idx.get(requires).copied() {
684 Some(dep_idx) => {
685 dependents[dep_idx].push(idx);
686 indegree[idx] += 1;
687 }
688 None => missing.push(MissingPackDependency {
689 from: pack.name().to_string(),
690 requires: requires.to_string(),
691 }),
692 }
693 }
694 }
695
696 if !missing.is_empty() {
697 return if missing.len() == 1 {
698 Err(RuntimeError::MissingPackDependency(missing.remove(0)))
699 } else {
700 Err(RuntimeError::MissingPackDependencies(
701 MissingPackDependencies { missing },
702 ))
703 };
704 }
705
706 let mut ready: VecDeque<usize> = indegree
707 .iter()
708 .enumerate()
709 .filter_map(|(idx, degree)| (*degree == 0).then_some(idx))
710 .collect();
711 let mut ordered_indices = Vec::with_capacity(packs.len());
712
713 while let Some(idx) = ready.pop_front() {
714 ordered_indices.push(idx);
715 for &dep_idx in &dependents[idx] {
716 indegree[dep_idx] -= 1;
717 if indegree[dep_idx] == 0 {
718 ready.push_back(dep_idx);
719 }
720 }
721 }
722
723 if ordered_indices.len() != packs.len() {
724 let cycle_nodes: HashSet<usize> = indegree
725 .iter()
726 .enumerate()
727 .filter_map(|(idx, degree)| (*degree > 0).then_some(idx))
728 .collect();
729 let cycle = find_pack_dependency_cycle(&packs, &name_to_idx, &cycle_nodes);
730 return Err(RuntimeError::CircularPackDependency(
731 CircularPackDependency { cycle },
732 ));
733 }
734
735 let mut slots: Vec<Option<Box<dyn PackRuntime>>> = packs.into_iter().map(Some).collect();
736 let ordered_packs: Vec<Box<dyn PackRuntime>> = ordered_indices
737 .into_iter()
738 .map(|idx| slots[idx].take().expect("topological index must exist"))
739 .collect();
740
741 validate_unique_note_kinds(&ordered_packs)?;
742 validate_unique_verb_names(&ordered_packs)?;
743 validate_unique_entity_types(&ordered_packs)?;
744 validate_brain_consumer_kinds(&ordered_packs)?;
745
746 let available_verbs: Vec<&'static str> = ordered_packs
747 .iter()
748 .flat_map(|p| p.handlers().iter())
749 .filter(|h| matches!(h.visibility, Visibility::Verb))
750 .map(|h| h.name)
751 .collect();
752
753 if let Some(store) = &self.event_store {
765 if !store.supports_idempotent_audit_batch() {
766 return Err(RuntimeError::IncompatibleEventStore(
767 "the configured EventStore does not implement ADR-133's \
768 preflight_event/append_events_idempotent pair \
769 (supports_idempotent_audit_batch() returned false); every \
770 audited dispatch would silently lose its audit row while \
771 still reporting success. Implement both methods and \
772 override supports_idempotent_audit_batch() to opt in, or \
773 do not call with_event_store() for this backend."
774 .to_string(),
775 ));
776 }
777 }
778 let audit_batch = self.event_store.clone().map(|store| {
779 crate::audit_batch::AuditBatch::new(
780 store,
781 self.audit_batch_config.clone().unwrap_or_default(),
782 )
783 });
784
785 Ok(VerbRegistry {
786 packs: Arc::new(ordered_packs),
787 resolvers: Arc::new(self.resolvers),
788 gate: self.gate,
789 default_namespace: self.default_namespace,
790 visible_namespaces: self.visible_namespaces,
791 actor_id: self.actor_id,
792 event_store: self.event_store,
793 audit_store_read_only: self.audit_store_read_only,
794 dispatch_hook: self.dispatch_hook,
795 available_verbs: Arc::new(available_verbs),
796 reference_ring: Arc::new(crate::reference_ring::ReferenceRing::new()),
797 audit_batch,
798 })
799 }
800}
801
802fn validate_unique_note_kinds(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
808 let mut seen: HashMap<&str, &str> = HashMap::new();
809 for pack in packs {
810 for &kind in pack.note_kinds() {
811 if let Some(first_pack) = seen.insert(kind, pack.name()) {
812 return Err(RuntimeError::InvalidInput(format!(
813 "duplicate note kind {kind:?}: claimed by both {first_pack:?} and {:?}",
814 pack.name()
815 )));
816 }
817 }
818 }
819 Ok(())
820}
821
822fn validate_brain_consumer_kinds(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
829 for pack in packs {
830 for &kind in pack.brain_consumer_kinds() {
831 if kind == "*" || kind.trim().is_empty() || kind.trim() != kind {
832 return Err(RuntimeError::InvalidInput(format!(
833 "pack {:?} declares invalid brain consumer kind {kind:?}; declarations must be non-empty exact wire values and must not use the registry-owned \"*\" wildcard",
834 pack.name()
835 )));
836 }
837 }
838 }
839 Ok(())
840}
841
842fn validate_unique_verb_names(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
849 let mut seen: HashMap<&str, &str> = HashMap::new();
850 for pack in packs {
851 for handler in pack.handlers() {
852 if !matches!(handler.visibility, Visibility::Verb) {
853 continue;
854 }
855 if let Some(first_pack) = seen.insert(handler.name, pack.name()) {
856 return Err(RuntimeError::VerbCollision {
857 verb: handler.name.to_string(),
858 first_pack: first_pack.to_string(),
859 second_pack: pack.name().to_string(),
860 });
861 }
862 }
863 }
864 Ok(())
865}
866
867fn validate_unique_entity_types(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
877 let owned_defs = packs
878 .iter()
879 .flat_map(|p| p.entity_types().iter().map(move |def| (p.name(), def)));
880 khive_types::EntityTypeRegistry::check_extra_collisions(owned_defs)
881 .map_err(RuntimeError::InvalidInput)
882}
883
884fn find_pack_dependency_cycle(
885 packs: &[Box<dyn PackRuntime>],
886 name_to_idx: &HashMap<&str, usize>,
887 cycle_nodes: &HashSet<usize>,
888) -> Vec<String> {
889 fn visit(
890 idx: usize,
891 packs: &[Box<dyn PackRuntime>],
892 name_to_idx: &HashMap<&str, usize>,
893 cycle_nodes: &HashSet<usize>,
894 visiting: &mut Vec<usize>,
895 visited: &mut HashSet<usize>,
896 ) -> Option<Vec<String>> {
897 if let Some(pos) = visiting.iter().position(|&seen| seen == idx) {
898 let mut cycle: Vec<String> = visiting[pos..]
899 .iter()
900 .map(|&i| packs[i].name().to_string())
901 .collect();
902 cycle.push(packs[idx].name().to_string());
903 return Some(cycle);
904 }
905 if !visited.insert(idx) {
906 return None;
907 }
908 visiting.push(idx);
909 for &req in packs[idx].requires() {
910 let Some(&dep_idx) = name_to_idx.get(req) else {
911 continue;
912 };
913 if cycle_nodes.contains(&dep_idx) {
914 if let Some(cycle) =
915 visit(dep_idx, packs, name_to_idx, cycle_nodes, visiting, visited)
916 {
917 return Some(cycle);
918 }
919 }
920 }
921 visiting.pop();
922 None
923 }
924
925 let mut visited = HashSet::new();
926 for &idx in cycle_nodes {
927 let mut visiting = Vec::new();
928 if let Some(cycle) = visit(
929 idx,
930 packs,
931 name_to_idx,
932 cycle_nodes,
933 &mut visiting,
934 &mut visited,
935 ) {
936 return cycle;
937 }
938 }
939 cycle_nodes
940 .iter()
941 .map(|&idx| packs[idx].name().to_string())
942 .collect()
943}
944
945impl Default for VerbRegistryBuilder {
946 fn default() -> Self {
947 Self::new()
948 }
949}
950
951#[derive(Clone)]
955pub struct VerbRegistry {
956 packs: std::sync::Arc<Vec<Box<dyn PackRuntime>>>,
957 resolvers: std::sync::Arc<Vec<(String, Box<dyn PackByIdResolver>)>>,
959 gate: GateRef,
960 default_namespace: String,
961 visible_namespaces: Vec<Namespace>,
968 actor_id: Option<String>,
972 event_store: Option<Arc<dyn EventStore>>,
974 audit_store_read_only: bool,
977 dispatch_hook: Option<Arc<dyn DispatchHook>>,
979 available_verbs: Arc<Vec<&'static str>>,
984 reference_ring: Arc<crate::reference_ring::ReferenceRing>,
989 audit_batch: Option<Arc<crate::audit_batch::AuditBatch>>,
994}
995
996#[derive(Debug, Clone, PartialEq)]
1003pub struct InterceptedDispatchResult<M> {
1004 pub result: Value,
1006 pub metadata: M,
1008}
1009
1010impl<M> InterceptedDispatchResult<M> {
1011 pub fn new(result: Value, metadata: M) -> Self {
1013 Self { result, metadata }
1014 }
1015}
1016
1017#[derive(Debug, Clone, Default)]
1032pub struct RequestIdentity {
1033 pub namespace: String,
1037 pub actor_id: Option<String>,
1041 pub visible_namespaces: Vec<String>,
1047 pub process_ref: Option<String>,
1052 pub request_id: Option<u64>,
1062}
1063
1064impl RequestIdentity {
1065 pub fn from_token(token: &NamespaceToken) -> Self {
1079 Self {
1080 namespace: token.namespace().as_str().to_string(),
1081 actor_id: token.actor().binding_id().map(str::to_string),
1082 visible_namespaces: token
1083 .visible_namespaces()
1084 .iter()
1085 .map(|namespace| namespace.as_str().to_string())
1086 .collect(),
1087 process_ref: token.process_ref().map(str::to_owned),
1088 request_id: None,
1089 }
1090 }
1091}
1092
1093#[derive(Debug, Clone, PartialEq, Eq)]
1102pub struct VerifiedActor(String);
1103
1104impl VerifiedActor {
1105 pub fn new(id: impl Into<String>) -> Result<Self, RuntimeError> {
1110 let id = id.into();
1111 if id.trim().is_empty() {
1112 return Err(RuntimeError::InvalidInput(
1113 "VerifiedActor: identifier must not be empty or whitespace-only".to_string(),
1114 ));
1115 }
1116 Ok(Self(id))
1117 }
1118
1119 pub fn as_str(&self) -> &str {
1121 &self.0
1122 }
1123
1124 fn into_inner(self) -> String {
1125 self.0
1126 }
1127}
1128
1129#[derive(Debug)]
1132pub struct PackSchemaCollisionError {
1133 pub pack_a: &'static str,
1135 pub pack_b: &'static str,
1137 pub table: String,
1139}
1140
1141impl std::fmt::Display for PackSchemaCollisionError {
1142 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1143 if self.pack_a == self.pack_b {
1144 write!(
1145 f,
1146 "pack schema boot failure for pack {:?}: {}",
1147 self.pack_a, self.table
1148 )
1149 } else {
1150 write!(
1151 f,
1152 "pack schema collision: packs {:?} and {:?} both declare table {:?} \
1153 on the same backend — move one pack to a separate backend or rename the table",
1154 self.pack_a, self.pack_b, self.table
1155 )
1156 }
1157 }
1158}
1159
1160impl std::error::Error for PackSchemaCollisionError {}
1161
1162fn extract_table_names(stmt: &str) -> Vec<String> {
1168 let normalized = stmt.split_whitespace().collect::<Vec<_>>().join(" ");
1169 let upper = normalized.to_ascii_uppercase();
1170 let table_name = if let Some(rest) = upper.strip_prefix("CREATE VIRTUAL TABLE IF NOT EXISTS ") {
1171 rest.split_whitespace().next()
1172 } else if let Some(rest) = upper.strip_prefix("CREATE VIRTUAL TABLE ") {
1173 rest.split_whitespace().next()
1174 } else if let Some(rest) = upper.strip_prefix("CREATE TABLE IF NOT EXISTS ") {
1175 rest.split_whitespace().next()
1176 } else if let Some(rest) = upper.strip_prefix("CREATE TABLE ") {
1177 rest.split_whitespace().next()
1178 } else {
1179 None
1180 };
1181 match table_name {
1182 Some(name) => {
1183 let clean = name.trim_matches(|c: char| c == '(' || c == ';');
1184 if clean.is_empty() {
1185 vec![]
1186 } else {
1187 vec![clean.to_ascii_lowercase()]
1188 }
1189 }
1190 None => vec![],
1191 }
1192}
1193
1194fn endpoint_kind_label(kind: &EndpointKind) -> String {
1197 match kind {
1198 EndpointKind::EntityOfKind(k) => format!("entity:{k}"),
1199 EndpointKind::NoteOfKind(k) => format!("note:{k}"),
1200 EndpointKind::EntityOfType { kind, entity_type } => {
1201 format!("entity:{kind}({entity_type})")
1202 }
1203 }
1204}
1205
1206pub(crate) const SPECIAL_RELATIONS: &[khive_types::EdgeRelation] = &[
1214 khive_types::EdgeRelation::Supersedes,
1215 khive_types::EdgeRelation::Supports,
1216 khive_types::EdgeRelation::Refutes,
1217];
1218
1219pub(crate) fn is_special_relation(relation: khive_types::EdgeRelation) -> bool {
1220 SPECIAL_RELATIONS.contains(&relation)
1221}
1222
1223fn edge_endpoint_table(packs: &[Box<dyn PackRuntime>]) -> Vec<Value> {
1241 let mut rows: Vec<Value> = crate::operations::base_entity_endpoint_rules()
1242 .iter()
1243 .map(|(src, rel, tgt)| {
1244 serde_json::json!({
1245 "relation": rel.as_str(),
1246 "source": format!("entity:{src}"),
1247 "target": format!("entity:{tgt}"),
1248 })
1249 })
1250 .collect();
1251
1252 for rel in SPECIAL_RELATIONS {
1253 rows.push(serde_json::json!({
1254 "relation": rel.as_str(),
1255 "source": "note:*",
1256 "target": "note:*",
1257 }));
1258 }
1259
1260 for pack in packs.iter() {
1261 for rule in pack.edge_rules().iter() {
1262 if is_special_relation(rule.relation) {
1263 continue;
1264 }
1265 rows.push(serde_json::json!({
1266 "relation": rule.relation.as_str(),
1267 "source": endpoint_kind_label(&rule.source),
1268 "target": endpoint_kind_label(&rule.target),
1269 }));
1270 }
1271 }
1272
1273 rows.push(serde_json::json!({
1274 "relation": "annotates",
1275 "source": "note:*",
1276 "target": "any (entity, note, edge, or event)",
1277 }));
1278
1279 rows
1280}
1281
1282impl VerbRegistry {
1283 pub fn default_namespace(&self) -> &str {
1289 &self.default_namespace
1290 }
1291
1292 pub fn actor_id(&self) -> Option<&str> {
1296 self.actor_id.as_deref()
1297 }
1298
1299 pub fn visible_namespaces(&self) -> &[Namespace] {
1303 &self.visible_namespaces
1304 }
1305
1306 pub fn event_store(&self) -> Option<Arc<dyn EventStore>> {
1316 self.event_store.clone()
1317 }
1318
1319 pub fn audit_batch_metrics(&self) -> Option<khive_db::diagnostics::RuntimeAuditBatchMetrics> {
1336 self.audit_batch.as_ref().map(|batch| {
1337 let m = batch.health_metrics();
1338 khive_db::diagnostics::RuntimeAuditBatchMetrics {
1339 flush_failures: m.flush_failures,
1340 degraded_rows: m.degraded_rows,
1341 degraded: m.degraded,
1342 admission_refused_obligations: audit_admission_refused_obligation_count(),
1343 admission_unresolved_obligations: audit_admission_unresolved_obligation_count(),
1344 }
1345 })
1346 }
1347
1348 pub fn audit_batch_handle(&self) -> Option<Arc<crate::audit_batch::AuditBatch>> {
1355 self.audit_batch.clone()
1356 }
1357
1358 pub async fn shutdown_audit_batch(
1366 &self,
1367 ) -> Result<(), crate::audit_batch::AuditTerminalReason> {
1368 use crate::audit_batch::AuditBatchControl;
1369 match &self.audit_batch {
1370 Some(audit_batch) => audit_batch.close_and_drain().await,
1371 None => Ok(()),
1372 }
1373 }
1374
1375 pub fn audit_persistence_advisory(&self) -> Option<Value> {
1381 self.audit_store_read_only.then(|| {
1382 serde_json::json!({
1383 "code": AUDIT_PERSISTENCE_SKIPPED_READ_ONLY,
1384 "severity": "warning",
1385 "component": "audit_event_store",
1386 "reason": "read_only_backend",
1387 "message": "operation completed, but its dispatch audit event was not persisted because the audit backend is read-only",
1388 })
1389 })
1390 }
1391
1392 const ADMISSION_DEGRADE_SAFE_VERBS: &'static [&'static str] = &[
1424 "get",
1425 "list",
1426 "stats",
1427 "search",
1428 "neighbors",
1429 "traverse",
1430 "context",
1431 "query",
1432 "resolve",
1433 "whoami",
1434 "verbs",
1435 ];
1436
1437 fn admission_degrade_safe(&self, verb: &str) -> bool {
1453 if !Self::ADMISSION_DEGRADE_SAFE_VERBS.contains(&verb) {
1454 return false;
1455 }
1456 self.packs
1457 .iter()
1458 .find_map(|pack| pack.handlers().iter().find(|h| h.name == verb))
1459 .is_some_and(|handler| handler.category == VerbCategory::Assertive)
1460 }
1461
1462 pub fn describe_verb(&self, verb: &str) -> Result<Value, RuntimeError> {
1473 for pack in self.packs.iter() {
1474 for handler in pack.handlers().iter() {
1475 if handler.name == verb {
1476 let category = format!("{:?}", handler.category);
1477 let params_arr: Vec<Value> = handler
1478 .params
1479 .iter()
1480 .map(|p| {
1481 serde_json::json!({
1482 "name": p.name,
1483 "type": p.param_type,
1484 "required": p.required,
1485 "description": p.description,
1486 })
1487 })
1488 .collect();
1489 if matches!(handler.visibility, Visibility::Subhandler) {
1494 return Ok(serde_json::json!({
1495 "verb": verb,
1496 "pack": pack.name(),
1497 "description": handler.description,
1498 "category": category,
1499 "params": params_arr,
1500 "identifier_resolution": identifier_resolution_help(),
1501 "visibility": "internal",
1502 "callable_via_mcp": false,
1503 "note": "This is an internal subhandler. Calling it via the MCP \
1504 request surface returns permission denied. It can only be \
1505 invoked by internal runtime callers.",
1506 }));
1507 }
1508 let mut envelope = serde_json::json!({
1509 "verb": verb,
1510 "pack": pack.name(),
1511 "description": handler.description,
1512 "category": category,
1513 "params": params_arr,
1514 "identifier_resolution": identifier_resolution_help(),
1515 });
1516 if verb == "link" {
1517 envelope["endpoint_rules"] = Value::Array(edge_endpoint_table(&self.packs));
1518 }
1519 return Ok(envelope);
1520 }
1521 }
1522 }
1523 Err(RuntimeError::UnknownVerb(format!(
1527 "unknown verb {verb:?}; available: {}",
1528 self.available_verbs.join(", ")
1529 )))
1530 }
1531
1532 pub fn authorize_namespace(&self, ns: Namespace) -> Result<(), RuntimeError> {
1542 let actor = crate::actor_identity::resolve_actor(self.actor_id.as_deref());
1543 let req = GateRequest::new(actor, ns, "authorize", serde_json::Value::Null);
1544 match self.gate.check(&req) {
1545 Ok(decision) if decision.is_allow() => Ok(()),
1546 Ok(GateDecision::Deny { reason }) => Err(RuntimeError::PermissionDenied {
1547 verb: "authorize".to_string(),
1548 reason,
1549 }),
1550 Ok(_) => Err(RuntimeError::PermissionDenied {
1551 verb: "authorize".to_string(),
1552 reason: "gate denied".to_string(),
1553 }),
1554 Err(e) => {
1555 tracing::warn!(
1556 error = %crate::secret_gate::bounded_masked_log_text(&e.to_string()),
1557 "authorize_namespace: gate check failed (fail-closed)"
1558 );
1559 Err(RuntimeError::Internal(format!(
1560 "gate error: {}",
1561 e.wire_reason()
1562 )))
1563 }
1564 }
1565 }
1566
1567 pub async fn dispatch_intercepted_with_identity<F, Fut>(
1577 &self,
1578 verb: &str,
1579 params: &Value,
1580 identity: Option<&RequestIdentity>,
1581 dispatch: F,
1582 ) -> Result<Value, RuntimeError>
1583 where
1584 F: FnOnce(Namespace) -> Fut,
1585 Fut: std::future::Future<Output = Result<Value, RuntimeError>>,
1586 {
1587 self.dispatch_intercepted_with_metadata_with_identity(
1588 verb,
1589 params,
1590 identity,
1591 |namespace| async move {
1592 dispatch(namespace)
1593 .await
1594 .map(|result| InterceptedDispatchResult::new(result, ()))
1595 },
1596 )
1597 .await
1598 .map(|outcome| outcome.result)
1599 }
1600
1601 pub async fn dispatch_intercepted_with_metadata_with_identity<M, F, Fut>(
1608 &self,
1609 verb: &str,
1610 params: &Value,
1611 identity: Option<&RequestIdentity>,
1612 dispatch: F,
1613 ) -> Result<InterceptedDispatchResult<M>, RuntimeError>
1614 where
1615 F: FnOnce(Namespace) -> Fut,
1616 Fut: std::future::Future<Output = Result<InterceptedDispatchResult<M>, RuntimeError>>,
1617 {
1618 let request_id = identity.and_then(|id| id.request_id);
1619 let gate_req = self.gate_request_with_identity(verb, params, identity)?;
1620 let mut deferred_audit = match self.gate.check(&gate_req) {
1621 Ok(decision) => {
1622 let audit = AuditEvent::from_check(&gate_req, &decision, self.gate.impl_name());
1623 tracing::info!(
1624 audit_event = %serde_json::to_string(&audit)
1625 .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
1626 "gate.check"
1627 );
1628 if let GateDecision::Deny { reason } = decision {
1629 if let Some(store) = &self.event_store {
1630 let event = build_audit_storage_event(
1631 &gate_req,
1632 &audit,
1633 EventOutcome::Denied,
1634 Some(crate::cost_unit::base_resource_payload(request_id)),
1635 );
1636 let _ = append_audit_event_best_effort(
1643 self.audit_batch.as_ref(),
1644 store,
1645 event,
1646 verb,
1647 crate::audit_batch::AuditProducer::GateDenied,
1648 false,
1649 )
1650 .await;
1651 }
1652 return Err(RuntimeError::PermissionDenied {
1653 verb: verb.to_string(),
1654 reason,
1655 });
1656 }
1657 Some(audit)
1658 }
1659 Err(err) => {
1660 return Err(self
1661 .gate_unavailable_error(&gate_req, &err, request_id)
1662 .await);
1663 }
1664 };
1665
1666 let started = Instant::now();
1667 let mut result = dispatch(gate_req.namespace.clone()).await;
1668 let duration_us = started.elapsed().as_micros() as i64;
1669 let receipt_outcome = if verb == "git.digest" && result.is_ok() {
1670 let resource = result.as_ref().ok().map(|outcome| {
1671 crate::cost_unit::resource_payload(
1672 verb,
1673 &gate_req.args,
1674 &outcome.result,
1675 || 0,
1676 request_id,
1677 )
1678 });
1679 let mut receipt_result: Result<Value, RuntimeError> = match result.as_mut() {
1684 Ok(outcome) => Ok(std::mem::take(&mut outcome.result)),
1685 Err(_) => unreachable!("git.digest receipt path is guarded by result.is_ok()"),
1686 };
1687 let outcome = persist_git_digest_receipt(
1688 self.event_store.as_ref(),
1689 self.audit_batch.as_ref(),
1690 &gate_req,
1691 deferred_audit.as_ref(),
1692 &mut receipt_result,
1693 duration_us,
1694 resource,
1695 )
1696 .await;
1697 match receipt_result {
1698 Ok(receipted_result) => {
1699 if let Ok(intercepted) = &mut result {
1700 intercepted.result = receipted_result;
1701 }
1702 }
1703 Err(error) => result = Err(error),
1704 }
1705 Some(outcome)
1706 } else {
1707 None
1708 };
1709 if receipt_outcome.is_none()
1710 || receipt_outcome == Some(GitDigestReceiptOutcome::BuildRejected)
1711 {
1712 if let Some(audit) = deferred_audit.take() {
1713 let audit_outcome = self
1714 .persist_intercepted_audit(
1715 verb,
1716 &gate_req,
1717 audit,
1718 result.as_ref().map(|outcome| &outcome.result),
1719 duration_us,
1720 request_id,
1721 )
1722 .await;
1723 result = fold_audit_obligation(result, audit_outcome);
1724 }
1725 }
1726 result
1727 }
1728
1729 async fn persist_intercepted_audit(
1730 &self,
1731 verb: &str,
1732 gate_req: &GateRequest,
1733 audit: AuditEvent,
1734 result: Result<&Value, &RuntimeError>,
1735 duration_us: i64,
1736 request_id: Option<u64>,
1737 ) -> Result<(), RuntimeError> {
1738 let Some(store) = &self.event_store else {
1739 return Ok(());
1740 };
1741 let event = match result {
1742 Ok(value) if verb == "link" && gate_req.args.get("links").is_none() => {
1743 let resource = crate::cost_unit::resource_payload(
1744 verb,
1745 &gate_req.args,
1746 value,
1747 || 0,
1748 request_id,
1749 );
1750 match link_audit_success_from_result(audit.clone(), value) {
1751 Some((edge_id, mut payload)) => {
1752 if let Value::Object(ref mut map) = payload {
1753 map.insert("resource".to_string(), resource);
1754 }
1755 Event::new(
1756 gate_req.namespace.as_str(),
1757 gate_req.verb.as_str(),
1758 EventKind::Audit,
1759 SubstrateKind::Event,
1760 format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
1761 )
1762 .with_outcome(EventOutcome::Success)
1763 .with_target(edge_id)
1764 .with_payload(payload)
1765 .with_payload_schema_version(2)
1766 .with_duration_us(duration_us)
1767 }
1768 None => build_audit_storage_event(
1769 gate_req,
1770 &audit,
1771 EventOutcome::Success,
1772 Some(resource),
1773 )
1774 .with_duration_us(duration_us),
1775 }
1776 }
1777 Ok(value) => build_audit_storage_event(
1778 gate_req,
1779 &audit,
1780 EventOutcome::Success,
1781 Some(crate::cost_unit::resource_payload(
1782 verb,
1783 &gate_req.args,
1784 value,
1785 || 0,
1786 request_id,
1787 )),
1788 )
1789 .with_duration_us(duration_us),
1790 Err(_) => build_audit_storage_event(
1791 gate_req,
1792 &audit,
1793 EventOutcome::Error,
1794 Some(crate::cost_unit::base_resource_payload(request_id)),
1795 )
1796 .with_duration_us(duration_us),
1797 };
1798 let producer = if result.is_ok() {
1799 crate::audit_batch::AuditProducer::DispatchSucceeded
1800 } else {
1801 crate::audit_batch::AuditProducer::DispatchFailed
1802 };
1803 append_audit_event_best_effort(
1804 self.audit_batch.as_ref(),
1805 store,
1806 event,
1807 verb,
1808 producer,
1809 self.admission_degrade_safe(verb),
1810 )
1811 .await
1812 }
1813
1814 fn gate_request_with_identity(
1815 &self,
1816 verb: &str,
1817 params: &Value,
1818 identity: Option<&RequestIdentity>,
1819 ) -> Result<GateRequest, RuntimeError> {
1820 let default_namespace = identity
1821 .map(|id| id.namespace.as_str())
1822 .unwrap_or(self.default_namespace.as_str());
1823 let namespace = resolve_explicit_namespace(params, default_namespace)?;
1824 let actor_id = identity
1825 .map(|id| id.actor_id.as_deref())
1826 .unwrap_or(self.actor_id.as_deref());
1827 let actor = crate::actor_identity::resolve_actor(actor_id);
1828 Ok(GateRequest::new(actor, namespace, verb, params.clone()))
1829 }
1830
1831 async fn gate_unavailable_error(
1832 &self,
1833 gate_req: &GateRequest,
1834 error: &khive_gate::GateError,
1835 request_id: Option<u64>,
1836 ) -> RuntimeError {
1837 let audit = AuditEvent::gate_unavailable(gate_req, self.gate.impl_name());
1838 tracing::info!(
1839 audit_event = %serde_json::to_string(&audit)
1840 .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
1841 "gate.check"
1842 );
1843 tracing::warn!(
1844 verb = %gate_req.verb,
1845 error = %crate::secret_gate::bounded_masked_log_text(&error.to_string()),
1846 "gate check failed (fail-closed)"
1847 );
1848 if let Some(store) = &self.event_store {
1849 let event = build_audit_storage_event(
1850 gate_req,
1851 &audit,
1852 EventOutcome::Error,
1853 Some(crate::cost_unit::base_resource_payload(request_id)),
1854 );
1855 let _ = append_audit_event_best_effort(
1856 self.audit_batch.as_ref(),
1857 store,
1858 event,
1859 gate_req.verb.as_str(),
1860 crate::audit_batch::AuditProducer::GateUnavailable,
1861 false,
1862 )
1863 .await;
1864 }
1865 RuntimeError::GateUnavailable {
1866 verb: gate_req.verb.clone(),
1867 reason: error.wire_reason().to_string(),
1873 }
1874 }
1875
1876 pub async fn dispatch(&self, verb: &str, params: Value) -> Result<Value, RuntimeError> {
1886 self.dispatch_with_identity(verb, params, None).await
1887 }
1888
1889 pub async fn dispatch_with_identity(
1901 &self,
1902 verb: &str,
1903 params: Value,
1904 identity: Option<RequestIdentity>,
1905 ) -> Result<Value, RuntimeError> {
1906 if params.get("help").and_then(Value::as_bool) == Some(true) {
1908 return self.describe_verb(verb);
1909 }
1910 let explicit_namespace = params.get("namespace").is_some_and(Value::is_string);
1921 let request_id: Option<u64> = identity.as_ref().and_then(|id| id.request_id);
1925 let gate_req = self.gate_request_with_identity(verb, ¶ms, identity.as_ref())?;
1931 let ns = gate_req.namespace.clone();
1932 let resolved_actor = gate_req.actor.clone();
1933
1934 let (gate_blocked, mut deferred_audit) = match self.gate.check(&gate_req) {
1940 Ok(decision) => {
1941 let is_deny = matches!(decision, GateDecision::Deny { .. });
1942
1943 let audit = AuditEvent::from_check(&gate_req, &decision, self.gate.impl_name());
1945 tracing::info!(
1946 audit_event = %serde_json::to_string(&audit)
1947 .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
1948 "gate.check"
1949 );
1950
1951 if let Some(store) = &self.event_store {
1965 if crate::config_ledger::PENDING
1966 .swap(false, std::sync::atomic::Ordering::AcqRel)
1967 {
1968 for (key, value) in crate::config_ledger::drain_config_locked() {
1969 let payload = serde_json::json!({ "key": key, "value": value });
1970 let storage_event = Event::new(
1971 gate_req.namespace.as_str(),
1972 "config.lock",
1973 EventKind::ConfigLocked,
1974 SubstrateKind::Event,
1975 format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
1976 )
1977 .with_payload(payload);
1978 let _ = append_audit_event_best_effort(
1982 self.audit_batch.as_ref(),
1983 store,
1984 storage_event,
1985 "config.lock",
1986 crate::audit_batch::AuditProducer::ConfigLocked,
1987 false,
1988 )
1989 .await;
1990 }
1991 }
1992 }
1993
1994 let defer_audit = !is_deny;
2011
2012 if !defer_audit {
2014 if let Some(store) = &self.event_store {
2015 let storage_event = build_audit_storage_event(
2021 &gate_req,
2022 &audit,
2023 EventOutcome::Denied,
2024 Some(crate::cost_unit::base_resource_payload(request_id)),
2025 );
2026 let _ = append_audit_event_best_effort(
2030 self.audit_batch.as_ref(),
2031 store,
2032 storage_event,
2033 verb,
2034 crate::audit_batch::AuditProducer::GateDenied,
2035 false,
2036 )
2037 .await;
2038 }
2039 }
2040
2041 let reason = if is_deny {
2042 let reason = match decision {
2043 GateDecision::Deny { reason } => reason,
2044 _ => String::new(),
2045 };
2046 Some(reason)
2047 } else {
2048 None
2049 };
2050 let deferred = if defer_audit { Some(audit) } else { None };
2051 (reason, deferred)
2052 }
2053 Err(err) => {
2054 return Err(self
2055 .gate_unavailable_error(&gate_req, &err, request_id)
2056 .await);
2057 }
2058 };
2059
2060 if let Some(reason) = gate_blocked {
2062 return Err(RuntimeError::PermissionDenied {
2063 verb: verb.to_string(),
2064 reason,
2065 });
2066 }
2067
2068 let token = if explicit_namespace {
2094 NamespaceToken::mint_with_visibility(ns.clone(), vec![], resolved_actor)
2096 } else {
2097 let primary = Namespace::local();
2099 let mut extra_visible: Vec<Namespace> = match identity.as_ref() {
2100 Some(id) => id
2101 .visible_namespaces
2102 .iter()
2103 .filter_map(|s| match Namespace::parse(s) {
2104 Ok(parsed) => Some(parsed),
2105 Err(e) => {
2106 tracing::warn!(
2107 namespace = %s,
2108 error = %e,
2109 "dispatch_with_identity: skipping invalid visible_namespace \
2110 entry from per-request identity"
2111 );
2112 None
2113 }
2114 })
2115 .collect(),
2116 None => self.visible_namespaces.clone(),
2117 };
2118 extra_visible.push(Namespace::local()); NamespaceToken::mint_with_visibility(primary, extra_visible, resolved_actor)
2120 }
2121 .with_process_ref(match identity.as_ref() {
2122 Some(id) => id.process_ref.clone(),
2123 None => crate::config::process_ref_from_env(),
2124 });
2125
2126 for pack in self.packs.iter() {
2127 if let Some(handler_def) = pack.handlers().iter().find(|v| v.name == verb) {
2128 let handler_accepts_namespace =
2138 handler_def.params.iter().any(|p| p.name == "namespace");
2139 let params = if !handler_accepts_namespace {
2140 if let Value::Object(mut map) = params {
2141 map.remove("namespace");
2142 Value::Object(map)
2143 } else {
2144 params
2145 }
2146 } else {
2147 params
2148 };
2149 let dispatch_start = Instant::now();
2150 let mut result = pack.dispatch(verb, params, self, &token).await;
2151 let dispatch_us = dispatch_start.elapsed().as_micros() as i64;
2152
2153 let git_digest_receipt_outcome = if verb == "git.digest" && result.is_ok() {
2160 let resource = result.as_ref().ok().map(|value| {
2161 crate::cost_unit::resource_payload(
2162 verb,
2163 &gate_req.args,
2164 value,
2165 || pack.registered_embedding_model_names().len() as i64,
2166 request_id,
2167 )
2168 });
2169 Some(
2170 persist_git_digest_receipt(
2171 self.event_store.as_ref(),
2172 self.audit_batch.as_ref(),
2173 &gate_req,
2174 deferred_audit.as_ref(),
2175 &mut result,
2176 dispatch_us,
2177 resource,
2178 )
2179 .await,
2180 )
2181 } else {
2182 None
2183 };
2184
2185 let needs_generic_audit = git_digest_receipt_outcome.is_none()
2194 || git_digest_receipt_outcome == Some(GitDigestReceiptOutcome::BuildRejected);
2195 if let (true, Some(audit)) = (needs_generic_audit, deferred_audit.take()) {
2196 if let Some(store) = &self.event_store {
2197 let is_link_singleton =
2198 verb == "link" && gate_req.args.get("links").is_none();
2199 let audit_outcome: Result<(), RuntimeError> = match &result {
2204 Ok(ok_val) if is_link_singleton => {
2205 let resource = crate::cost_unit::resource_payload(
2213 verb,
2214 &gate_req.args,
2215 ok_val,
2216 || pack.registered_embedding_model_names().len() as i64,
2217 request_id,
2218 );
2219 match link_audit_success_from_result(audit.clone(), ok_val) {
2220 Some((edge_id, mut payload)) => {
2221 if let Value::Object(ref mut map) = payload {
2222 map.insert("resource".to_string(), resource);
2223 }
2224 let storage_event = Event::new(
2225 gate_req.namespace.as_str(),
2226 gate_req.verb.as_str(),
2227 EventKind::Audit,
2228 SubstrateKind::Event,
2229 format!(
2230 "{}:{}",
2231 gate_req.actor.kind, gate_req.actor.id
2232 ),
2233 )
2234 .with_outcome(EventOutcome::Success)
2235 .with_target(edge_id)
2236 .with_payload(payload)
2237 .with_payload_schema_version(2)
2238 .with_duration_us(dispatch_us);
2239 append_audit_event_best_effort(
2240 self.audit_batch.as_ref(),
2241 store,
2242 storage_event,
2243 verb,
2244 crate::audit_batch::AuditProducer::DispatchSucceeded,
2245 self.admission_degrade_safe(verb),
2246 )
2247 .await
2248 }
2249 None => {
2250 tracing::warn!(
2251 verb,
2252 "link audit v2 enrichment parse failed; \
2253 falling back to v1 audit shape"
2254 );
2255 let storage_event = build_audit_storage_event(
2256 &gate_req,
2257 &audit,
2258 EventOutcome::Success,
2259 Some(resource),
2260 )
2261 .with_duration_us(dispatch_us);
2262 append_audit_event_best_effort(
2263 self.audit_batch.as_ref(),
2264 store,
2265 storage_event,
2266 verb,
2267 crate::audit_batch::AuditProducer::DispatchSucceeded,
2268 self.admission_degrade_safe(verb),
2269 )
2270 .await
2271 }
2272 }
2273 }
2274 _ => {
2275 let (outcome, resource) = match &result {
2295 Ok(ok_val) => (
2296 EventOutcome::Success,
2297 Some(crate::cost_unit::resource_payload(
2298 verb,
2299 &gate_req.args,
2300 ok_val,
2301 || pack.registered_embedding_model_names().len() as i64,
2302 request_id,
2303 )),
2304 ),
2305 Err(_) => (
2306 EventOutcome::Error,
2307 Some(crate::cost_unit::base_resource_payload(request_id)),
2308 ),
2309 };
2310 let producer = if result.is_ok() {
2311 crate::audit_batch::AuditProducer::DispatchSucceeded
2312 } else {
2313 crate::audit_batch::AuditProducer::DispatchFailed
2314 };
2315 let storage_event =
2316 build_audit_storage_event(&gate_req, &audit, outcome, resource)
2317 .with_duration_us(dispatch_us);
2318 append_audit_event_best_effort(
2319 self.audit_batch.as_ref(),
2320 store,
2321 storage_event,
2322 verb,
2323 producer,
2324 self.admission_degrade_safe(verb),
2325 )
2326 .await
2327 }
2328 };
2329 result = fold_audit_obligation(result, audit_outcome);
2335 }
2336 }
2337
2338 if let (Ok(ref ok_val), Some(hook)) = (&result, &self.dispatch_hook) {
2340 let mut dispatch_event = Event::new(
2341 ns.as_str(),
2342 verb,
2343 EventKind::Audit,
2344 SubstrateKind::Event,
2345 pack.name(),
2346 )
2347 .with_outcome(EventOutcome::Success)
2348 .with_duration_us(dispatch_us);
2349
2350 if verb == "memory.recall" {
2356 let first_result =
2357 ok_val.as_array().and_then(|arr| arr.first()).or_else(|| {
2358 ok_val
2359 .get("results")
2360 .and_then(Value::as_array)
2361 .and_then(|arr| arr.first())
2362 });
2363 let first_note_id = first_result
2364 .and_then(|v| v.get("id"))
2365 .and_then(|v| v.as_str())
2366 .and_then(|s| s.parse::<uuid::Uuid>().ok());
2367 if let Some(note_id) = first_note_id {
2368 dispatch_event = dispatch_event.with_target(note_id);
2369 }
2370 let mut payload = serde_json::Map::new();
2371 if let Some(profile_id) = first_result
2372 .and_then(|v| v.get("served_by_profile_id"))
2373 .and_then(Value::as_str)
2374 {
2375 payload.insert(
2376 "served_by_profile_id".to_string(),
2377 Value::String(profile_id.to_string()),
2378 );
2379 }
2380 if let Some(attribution) = first_result
2381 .and_then(|v| v.get("serve_attribution"))
2382 .and_then(Value::as_str)
2383 {
2384 payload.insert(
2385 "serve_attribution".to_string(),
2386 Value::String(attribution.to_string()),
2387 );
2388 }
2389 dispatch_event = dispatch_event.with_payload(Value::Object(payload));
2390 }
2393
2394 let dispatch_view = EventView {
2395 event: dispatch_event,
2396 observations: Vec::new(),
2397 };
2398 let hook = Arc::clone(hook);
2399 hook.on_dispatch(&dispatch_view).await;
2400 }
2401
2402 if let Ok(ref ok_val) = result {
2418 let admissions = crate::reference_ring::ring_admissions_for(verb, ok_val);
2419 if !admissions.is_empty() {
2420 let actor_key = format!("{}:{}", gate_req.actor.kind, gate_req.actor.id);
2421 for (id, name) in admissions {
2422 self.reference_ring.admit(
2423 token.namespace().as_str(),
2424 &actor_key,
2425 id,
2426 name,
2427 );
2428 }
2429 }
2430 }
2431
2432 return result;
2433 }
2434 }
2435
2436 if let Some(audit) = deferred_audit.take() {
2442 if let Some(store) = &self.event_store {
2443 let storage_event = build_audit_storage_event(
2449 &gate_req,
2450 &audit,
2451 EventOutcome::Error,
2452 Some(crate::cost_unit::base_resource_payload(request_id)),
2453 );
2454 let _ = append_audit_event_best_effort(
2458 self.audit_batch.as_ref(),
2459 store,
2460 storage_event,
2461 verb,
2462 crate::audit_batch::AuditProducer::UnknownVerb,
2463 false,
2464 )
2465 .await;
2466 }
2467 }
2468
2469 Err(RuntimeError::UnknownVerb(format!(
2473 "unknown verb {verb:?}; available: {}",
2474 self.available_verbs.join(", ")
2475 )))
2476 }
2477
2478 pub async fn dispatch_as(
2496 &self,
2497 verb: &str,
2498 params: Value,
2499 verified_actor: VerifiedActor,
2500 ) -> Result<Value, RuntimeError> {
2501 let identity = RequestIdentity {
2502 namespace: self.default_namespace.clone(),
2503 actor_id: Some(verified_actor.into_inner()),
2504 visible_namespaces: self
2505 .visible_namespaces
2506 .iter()
2507 .map(|ns| ns.as_str().to_string())
2508 .collect(),
2509 process_ref: crate::config::process_ref_from_env(),
2510 request_id: None,
2511 };
2512 self.dispatch_with_identity(verb, params, Some(identity))
2513 .await
2514 }
2515
2516 pub fn resolvers(&self) -> &[(String, Box<dyn PackByIdResolver>)] {
2522 &self.resolvers
2523 }
2524
2525 pub fn reference_ring(&self) -> &Arc<crate::reference_ring::ReferenceRing> {
2530 &self.reference_ring
2531 }
2532
2533 pub fn find_kind_hook(&self, kind: &str) -> Option<Arc<dyn KindHook>> {
2540 for pack in self.packs.iter() {
2541 let owns = pack.note_kinds().contains(&kind) || pack.entity_kinds().contains(&kind);
2542 if owns {
2543 if let Some(hook) = pack.kind_hook(kind) {
2544 return Some(hook);
2545 }
2546 }
2547 }
2548 None
2549 }
2550
2551 pub async fn prepare_note_update_hook(
2556 &self,
2557 runtime: &KhiveRuntime,
2558 token: &NamespaceToken,
2559 note: &khive_storage::Note,
2560 args: &mut Value,
2561 ) -> Result<(), RuntimeError> {
2562 if let Some(hook) = self.find_kind_hook(¬e.kind) {
2563 hook.prepare_note_update(runtime, token, note, args).await?;
2564 }
2565 Ok(())
2566 }
2567
2568 pub async fn validate_note_update_hook(
2576 &self,
2577 runtime: &KhiveRuntime,
2578 token: &NamespaceToken,
2579 note: &khive_storage::Note,
2580 properties: Option<&Value>,
2581 ) -> Result<(), RuntimeError> {
2582 if let Some(hook) = self.find_kind_hook(¬e.kind) {
2583 hook.validate_note_update(runtime, token, note, properties)
2584 .await?;
2585 }
2586 Ok(())
2587 }
2588
2589 pub async fn validate_link_hooks(
2596 &self,
2597 runtime: &KhiveRuntime,
2598 token: &NamespaceToken,
2599 specs: &[LinkSpec],
2600 ) -> Result<(), RuntimeError> {
2601 let mut specs_by_kind: HashMap<String, Vec<LinkSpec>> = HashMap::new();
2602 for spec in specs {
2603 let Some(Resolved::Note(source)) = runtime.resolve_by_id(token, spec.source_id).await?
2604 else {
2605 continue;
2606 };
2607 specs_by_kind
2608 .entry(source.kind)
2609 .or_default()
2610 .push(spec.clone());
2611 }
2612 for (kind, kind_specs) in specs_by_kind {
2613 if let Some(hook) = self.find_kind_hook(&kind) {
2614 hook.validate_links(runtime, token, &kind_specs).await?;
2615 }
2616 }
2617 Ok(())
2618 }
2619
2620 pub fn has_verb(&self, verb: &str) -> bool {
2626 self.packs
2627 .iter()
2628 .flat_map(|p| p.handlers().iter())
2629 .any(|h| h.name == verb)
2630 }
2631
2632 pub fn all_verbs(&self) -> Vec<&'static HandlerDef> {
2638 self.packs
2639 .iter()
2640 .flat_map(|p| p.handlers().iter())
2641 .filter(|h| matches!(h.visibility, Visibility::Verb))
2642 .collect()
2643 }
2644
2645 pub fn all_verbs_with_names(&self) -> Vec<(&str, &'static HandlerDef)> {
2652 self.packs
2653 .iter()
2654 .flat_map(|p| p.handlers().iter().map(move |v| (p.name(), v)))
2655 .filter(|(_, h)| matches!(h.visibility, Visibility::Verb))
2656 .collect()
2657 }
2658
2659 pub fn all_handlers_with_names(&self) -> Vec<(&str, &'static HandlerDef)> {
2665 self.packs
2666 .iter()
2667 .flat_map(|p| p.handlers().iter().map(move |v| (p.name(), v)))
2668 .collect()
2669 }
2670
2671 pub fn all_note_kinds(&self) -> Vec<&'static str> {
2674 let mut seen = std::collections::HashSet::new();
2675 self.packs
2676 .iter()
2677 .flat_map(|p| p.note_kinds().iter().copied())
2678 .filter(|k| seen.insert(*k))
2679 .collect()
2680 }
2681
2682 pub fn pack_owned_note_kinds(&self) -> Vec<&'static str> {
2694 let generic: std::collections::HashSet<&'static str> = self
2695 .packs
2696 .iter()
2697 .filter(|p| p.name() == GENERIC_CRUD_PACK)
2698 .flat_map(|p| p.note_kinds().iter().copied())
2699 .collect();
2700 let mut seen = std::collections::HashSet::new();
2701 self.packs
2702 .iter()
2703 .filter(|p| p.name() != GENERIC_CRUD_PACK)
2704 .flat_map(|p| p.note_kinds().iter().copied())
2705 .filter(|k| !generic.contains(k) && seen.insert(*k))
2706 .collect()
2707 }
2708
2709 pub fn all_entity_kinds(&self) -> Vec<&'static str> {
2712 let mut seen = std::collections::HashSet::new();
2713 self.packs
2714 .iter()
2715 .flat_map(|p| p.entity_kinds().iter().copied())
2716 .filter(|k| seen.insert(*k))
2717 .collect()
2718 }
2719
2720 pub fn all_brain_consumer_kinds(&self) -> Vec<&'static str> {
2723 let mut seen = std::collections::HashSet::new();
2724 self.packs
2725 .iter()
2726 .flat_map(|p| p.brain_consumer_kinds().iter().copied())
2727 .filter(|kind| seen.insert(*kind))
2728 .collect()
2729 }
2730
2731 pub fn pack_names(&self) -> Vec<&str> {
2733 self.packs.iter().map(|p| p.name()).collect()
2734 }
2735
2736 pub fn pack_requires(&self, name: &str) -> Option<&'static [&'static str]> {
2738 self.packs
2739 .iter()
2740 .find(|p| p.name() == name)
2741 .map(|p| p.requires())
2742 }
2743
2744 pub fn pack_note_kinds(&self, name: &str) -> Option<&'static [&'static str]> {
2749 self.packs
2750 .iter()
2751 .find(|p| p.name() == name)
2752 .map(|p| p.note_kinds())
2753 }
2754
2755 pub fn pack_entity_kinds(&self, name: &str) -> Option<&'static [&'static str]> {
2760 self.packs
2761 .iter()
2762 .find(|p| p.name() == name)
2763 .map(|p| p.entity_kinds())
2764 }
2765
2766 pub fn pack_verbs(&self, name: &str) -> Option<&'static [HandlerDef]> {
2771 self.packs
2772 .iter()
2773 .find(|p| p.name() == name)
2774 .map(|p| p.handlers())
2775 }
2776
2777 pub fn all_edge_rules(&self) -> Vec<EdgeEndpointRule> {
2783 self.packs
2784 .iter()
2785 .flat_map(|p| p.edge_rules().iter().copied())
2786 .collect()
2787 }
2788
2789 pub fn all_entity_types(&self) -> Vec<EntityTypeDef> {
2796 self.packs
2797 .iter()
2798 .flat_map(|p| p.entity_types().iter().cloned())
2799 .collect()
2800 }
2801
2802 pub fn all_note_kind_specs(&self) -> Vec<&'static NoteKindSpec> {
2806 self.packs
2807 .iter()
2808 .flat_map(|p| p.note_kind_specs().iter())
2809 .collect()
2810 }
2811
2812 pub fn all_validation_rules(&self) -> Vec<&'static ValidationRule> {
2818 self.packs
2819 .iter()
2820 .flat_map(|p| p.validation_rules().iter())
2821 .collect()
2822 }
2823
2824 pub fn all_schema_plans(&self) -> Vec<SchemaPlan> {
2831 self.packs.iter().map(|p| p.schema_plan()).collect()
2832 }
2833
2834 pub fn call_register_embedders(&self, runtime: &KhiveRuntime) {
2844 for pack in self.packs.iter() {
2845 pack.register_embedders(runtime);
2846 }
2847 }
2848
2849 pub fn call_register_entity_type_validators(&self, runtime: &KhiveRuntime) {
2863 let entity_types = self.all_entity_types();
2864 for pack in self.packs.iter() {
2865 pack.register_entity_type_validator_with_types(runtime, &entity_types);
2866 }
2867 }
2868
2869 pub fn call_register_note_mutation_hooks(&self, runtime: &KhiveRuntime) {
2880 for pack in self.packs.iter() {
2881 pack.register_note_mutation_hook(runtime);
2882 }
2883 }
2884
2885 pub fn call_register_note_write_validators(&self, runtime: &KhiveRuntime) {
2893 for pack in self.packs.iter() {
2894 pack.register_note_write_validator(runtime);
2895 }
2896 }
2897
2898 pub async fn call_warm_all(&self) {
2902 for pack in self.packs.iter() {
2903 pack.warm().await;
2904 }
2905 }
2906
2907 pub fn presentation_policy_for(&self, verb: &str) -> khive_types::VerbPresentationPolicy {
2914 for pack in self.packs.iter() {
2915 if let Some(handler) = pack.handlers().iter().find(|h| h.name == verb) {
2916 return handler.presentation_policy();
2917 }
2918 }
2919 khive_types::VerbPresentationPolicy::Standard
2920 }
2921
2922 pub fn is_subhandler_verb(&self, verb: &str) -> bool {
2929 for pack in self.packs.iter() {
2930 if let Some(handler) = pack.handlers().iter().find(|h| h.name == verb) {
2931 return matches!(handler.visibility, Visibility::Subhandler);
2932 }
2933 }
2934 false
2935 }
2936
2937 pub fn apply_schema_plans(&self, backend: &khive_db::StorageBackend) {
2949 if backend.is_read_only() {
2950 tracing::info!(
2951 "skipping pack schema plans because the backend is read-only; snapshot schema is used as-is"
2952 );
2953 return;
2954 }
2955 for plan in self.all_schema_plans() {
2956 if plan.is_empty() {
2957 continue;
2958 }
2959 if let Err(e) = backend.apply_pack_ddl_statements(plan.statements) {
2960 tracing::warn!(
2961 pack = plan.pack,
2962 error = %e,
2963 "failed to apply pack schema plan at startup (non-fatal)"
2964 );
2965 }
2966 }
2967 }
2968
2969 pub fn all_schema_plans_named(&self) -> Vec<(&'static str, SchemaPlan)> {
2975 self.packs
2976 .iter()
2977 .map(|p| {
2978 let plan = p.schema_plan();
2979 (plan.pack, plan)
2980 })
2981 .collect()
2982 }
2983
2984 pub fn apply_schema_plans_with_map(
2997 &self,
2998 backend_for_pack: &HashMap<&str, &khive_db::StorageBackend>,
2999 default_backend: &khive_db::StorageBackend,
3000 ) -> Result<(), crate::PackSchemaCollisionError> {
3001 let mut claimed: HashMap<(*const (), String), &'static str> = HashMap::new();
3004
3005 for (pack_name, plan) in self.all_schema_plans_named() {
3006 if plan.is_empty() {
3007 continue;
3008 }
3009 let backend = backend_for_pack
3010 .get(pack_name)
3011 .copied()
3012 .unwrap_or(default_backend);
3013 let backend_ptr = std::sync::Arc::as_ptr(&backend.pool_arc()) as *const ();
3014
3015 for stmt in plan.statements {
3017 for table_name in extract_table_names(stmt) {
3018 let key = (backend_ptr, table_name.clone());
3019 match claimed.entry(key) {
3020 std::collections::hash_map::Entry::Vacant(e) => {
3021 e.insert(pack_name);
3022 }
3023 std::collections::hash_map::Entry::Occupied(e) => {
3024 let prior_pack = *e.get();
3025 return Err(crate::PackSchemaCollisionError {
3026 pack_a: prior_pack,
3027 pack_b: pack_name,
3028 table: table_name,
3029 });
3030 }
3031 }
3032 }
3033 }
3034
3035 if backend.is_read_only() {
3036 tracing::info!(
3037 pack = pack_name,
3038 "skipping pack schema plan because its assigned backend is read-only"
3039 );
3040 continue;
3041 }
3042
3043 backend
3044 .apply_pack_ddl_statements(plan.statements)
3045 .map_err(|e| crate::PackSchemaCollisionError {
3046 pack_a: pack_name,
3047 pack_b: pack_name,
3048 table: format!("DDL error: {e}"),
3049 })?;
3050 }
3051 Ok(())
3052 }
3053}
3054
3055pub struct PackInstall {
3063 pub runtime: Box<dyn PackRuntime>,
3065 pub resolver: Option<Box<dyn PackByIdResolver>>,
3067 pub dispatch_hook: Option<Arc<dyn DispatchHook>>,
3069}
3070
3071pub struct ChannelIngestCapability {
3099 pub(crate) _sealed: (),
3100}
3101
3102impl ChannelIngestCapability {
3103 pub fn grant_for_direct_composition() -> Self {
3111 Self { _sealed: () }
3112 }
3113}
3114
3115pub(crate) const CHANNEL_INGEST_CAPABLE_PACKS: &[&str] = &["comm"];
3117
3118pub trait PackFactory: Send + Sync + 'static {
3119 fn name(&self) -> &'static str;
3121
3122 fn requires(&self) -> &'static [&'static str] {
3129 &[]
3130 }
3131
3132 fn create(&self, runtime: KhiveRuntime) -> Box<dyn PackRuntime>;
3134
3135 fn create_install(&self, runtime: KhiveRuntime) -> PackInstall {
3144 let resolver = self.create_resolver(runtime.clone());
3145 PackInstall {
3146 runtime: self.create(runtime),
3147 resolver,
3148 dispatch_hook: None,
3149 }
3150 }
3151
3152 fn create_resolver(&self, _runtime: KhiveRuntime) -> Option<Box<dyn PackByIdResolver>> {
3158 None
3159 }
3160}
3161
3162pub struct PackRegistration(pub &'static dyn PackFactory);
3166
3167inventory::collect!(PackRegistration);
3168
3169#[derive(Debug)]
3171pub enum PackLoadError {
3172 UnknownPack(String),
3174 MissingDependency {
3176 pack: String,
3178 dep: String,
3180 },
3181}
3182
3183impl std::fmt::Display for PackLoadError {
3184 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3185 match self {
3186 PackLoadError::UnknownPack(name) => write!(f, "unknown pack {name:?}"),
3187 PackLoadError::MissingDependency { pack, dep } => write!(
3188 f,
3189 "pack {pack:?} requires {dep:?}, which is not in the requested pack list; \
3190 add --pack {dep} before --pack {pack}"
3191 ),
3192 }
3193 }
3194}
3195
3196impl std::error::Error for PackLoadError {}
3197
3198pub struct PackRegistry;
3203
3204impl PackRegistry {
3205 pub fn discovered_names() -> Vec<&'static str> {
3207 inventory::iter::<PackRegistration>
3208 .into_iter()
3209 .map(|r| r.0.name())
3210 .collect()
3211 }
3212
3213 pub fn register_packs(
3226 names: &[String],
3227 runtime: KhiveRuntime,
3228 builder: &mut VerbRegistryBuilder,
3229 ) -> Result<(), PackLoadError> {
3230 let all: Vec<&'static dyn PackFactory> = inventory::iter::<PackRegistration>
3232 .into_iter()
3233 .map(|r| r.0)
3234 .collect();
3235 let factory_for = |name: &str| -> Option<&'static dyn PackFactory> {
3236 all.iter().copied().find(|f| f.name() == name)
3237 };
3238
3239 let requested: std::collections::HashSet<&str> = names.iter().map(String::as_str).collect();
3241 for name in names {
3242 factory_for(name.as_str()).ok_or_else(|| PackLoadError::UnknownPack(name.clone()))?;
3243 }
3244
3245 for name in names {
3248 let factory = factory_for(name.as_str()).unwrap(); for &dep in factory.requires() {
3250 if !requested.contains(dep) {
3251 return Err(PackLoadError::MissingDependency {
3252 pack: name.clone(),
3253 dep: dep.to_string(),
3254 });
3255 }
3256 }
3257 }
3258
3259 for name in names {
3262 let factory = factory_for(name.as_str()).unwrap(); let install = factory.create_install(runtime.clone());
3264 if CHANNEL_INGEST_CAPABLE_PACKS.contains(&name.as_str()) {
3265 install
3266 .runtime
3267 .accept_channel_ingest_capability(ChannelIngestCapability { _sealed: () });
3268 }
3269 builder.register_boxed(install.runtime);
3270 if let Some(resolver) = install.resolver {
3271 builder.register_resolver(name.clone(), resolver);
3272 }
3273 if let Some(hook) = install.dispatch_hook {
3274 builder.with_dispatch_hook(hook);
3275 }
3276 }
3277
3278 Ok(())
3279 }
3280
3281 pub fn register_packs_with_runtimes(
3291 names: &[String],
3292 runtimes: &HashMap<String, KhiveRuntime>,
3293 default_runtime: &KhiveRuntime,
3294 builder: &mut VerbRegistryBuilder,
3295 ) -> Result<(), PackLoadError> {
3296 let all: Vec<&'static dyn PackFactory> = inventory::iter::<PackRegistration>
3297 .into_iter()
3298 .map(|r| r.0)
3299 .collect();
3300 let factory_for = |name: &str| -> Option<&'static dyn PackFactory> {
3301 all.iter().copied().find(|f| f.name() == name)
3302 };
3303
3304 let requested: std::collections::HashSet<&str> = names.iter().map(String::as_str).collect();
3305 for name in names {
3306 factory_for(name.as_str()).ok_or_else(|| PackLoadError::UnknownPack(name.clone()))?;
3307 }
3308
3309 for name in names {
3310 let factory = factory_for(name.as_str()).unwrap();
3311 for &dep in factory.requires() {
3312 if !requested.contains(dep) {
3313 return Err(PackLoadError::MissingDependency {
3314 pack: name.clone(),
3315 dep: dep.to_string(),
3316 });
3317 }
3318 }
3319 }
3320
3321 for name in names {
3322 let factory = factory_for(name.as_str()).unwrap();
3323 let runtime = runtimes
3324 .get(name.as_str())
3325 .cloned()
3326 .unwrap_or_else(|| default_runtime.clone());
3327 let install = factory.create_install(runtime);
3328 if CHANNEL_INGEST_CAPABLE_PACKS.contains(&name.as_str()) {
3329 install
3330 .runtime
3331 .accept_channel_ingest_capability(ChannelIngestCapability { _sealed: () });
3332 }
3333 builder.register_boxed(install.runtime);
3334 if let Some(resolver) = install.resolver {
3335 builder.register_resolver(name.clone(), resolver);
3336 }
3337 if let Some(hook) = install.dispatch_hook {
3338 builder.with_dispatch_hook(hook);
3339 }
3340 }
3341
3342 Ok(())
3343 }
3344}
3345
3346fn target_id_from_args(args: &serde_json::Value) -> Option<uuid::Uuid> {
3347 args.get("target_id")
3348 .and_then(serde_json::Value::as_str)
3349 .and_then(|s| s.parse::<uuid::Uuid>().ok())
3350}
3351
3352fn build_audit_storage_event(
3355 gate_req: &GateRequest,
3356 audit: &AuditEvent,
3357 outcome: EventOutcome,
3358 resource: Option<Value>,
3359) -> Event {
3360 let mut audit_data = serde_json::to_value(audit).unwrap_or_else(|e| {
3361 tracing::warn!(error = %e, "failed to serialize AuditEvent for EventStore");
3362 serde_json::Value::Null
3363 });
3364 if let Some(resource) = resource {
3365 if let Value::Object(ref mut map) = audit_data {
3366 map.insert("resource".to_string(), resource);
3367 }
3368 }
3369 let mut storage_event = Event::new(
3370 gate_req.namespace.as_str(),
3371 gate_req.verb.as_str(),
3372 EventKind::Audit,
3373 SubstrateKind::Event,
3374 format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
3375 )
3376 .with_outcome(outcome)
3377 .with_payload(audit_data);
3378 if let Some(target_id) = target_id_from_args(&gate_req.args) {
3379 storage_event = storage_event.with_target(target_id);
3380 }
3381 storage_event
3382}
3383
3384static AUDIT_APPEND_FAILURES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3392
3393pub(crate) fn audit_append_failure_count() -> u64 {
3394 AUDIT_APPEND_FAILURES.load(std::sync::atomic::Ordering::Relaxed)
3395}
3396
3397static AUDIT_OBLIGATION_APPEND_FAILURES: std::sync::atomic::AtomicU64 =
3409 std::sync::atomic::AtomicU64::new(0);
3410
3411#[cfg(test)]
3416pub(crate) fn audit_obligation_append_failure_count() -> u64 {
3417 AUDIT_OBLIGATION_APPEND_FAILURES.load(std::sync::atomic::Ordering::Relaxed)
3418}
3419
3420static AUDIT_ADMISSION_REFUSED_OBLIGATIONS: std::sync::atomic::AtomicU64 =
3448 std::sync::atomic::AtomicU64::new(0);
3449
3450pub fn audit_admission_refused_obligation_count() -> u64 {
3451 AUDIT_ADMISSION_REFUSED_OBLIGATIONS.load(std::sync::atomic::Ordering::Relaxed)
3452}
3453
3454static AUDIT_ADMISSION_UNRESOLVED_OBLIGATIONS: std::sync::atomic::AtomicU64 =
3469 std::sync::atomic::AtomicU64::new(0);
3470
3471pub fn audit_admission_unresolved_obligation_count() -> u64 {
3472 AUDIT_ADMISSION_UNRESOLVED_OBLIGATIONS.load(std::sync::atomic::Ordering::Relaxed)
3473}
3474
3475const GIT_DIGEST_RECEIPT_FAILURE: &str =
3476 "git_digest_receipt_persist_failed: git.digest writes may have committed, but no durable \
3477 success receipt was confirmed; inspect ingest state before retrying";
3478
3479#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3482enum GitDigestReceiptOutcome {
3483 Persisted,
3485 BuildRejected,
3489 PersistenceUnavailable,
3493}
3494
3495async fn persist_git_digest_receipt(
3506 store: Option<&Arc<dyn EventStore>>,
3507 audit_batch: Option<&Arc<crate::audit_batch::AuditBatch>>,
3508 gate_req: &GateRequest,
3509 audit: Option<&AuditEvent>,
3510 result: &mut Result<Value, RuntimeError>,
3511 duration_us: i64,
3512 resource: Option<Value>,
3513) -> GitDigestReceiptOutcome {
3514 let Ok(report) = result else {
3515 return GitDigestReceiptOutcome::PersistenceUnavailable;
3516 };
3517 let Some(store) = store else {
3518 tracing::error!(
3519 verb = "git.digest",
3520 "durable receipt store is not configured"
3521 );
3522 *result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
3523 return GitDigestReceiptOutcome::PersistenceUnavailable;
3524 };
3525 let Some(audit) = audit else {
3526 tracing::error!(
3527 verb = "git.digest",
3528 "durable receipt cannot be built because the gate produced no audit decision"
3529 );
3530 *result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
3531 return GitDigestReceiptOutcome::PersistenceUnavailable;
3532 };
3533
3534 let Some(report_object) = report.as_object_mut() else {
3535 tracing::error!(
3536 verb = "git.digest",
3537 "digest handler returned a non-object report"
3538 );
3539 *result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
3540 return GitDigestReceiptOutcome::BuildRejected;
3541 };
3542 let Some(project_id) = report_object
3543 .get("project_id")
3544 .and_then(Value::as_str)
3545 .and_then(|raw| raw.parse::<uuid::Uuid>().ok())
3546 else {
3547 tracing::error!(
3548 verb = "git.digest",
3549 "digest handler report omitted a valid project_id"
3550 );
3551 *result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
3552 return GitDigestReceiptOutcome::BuildRejected;
3553 };
3554
3555 let mut event = Event::new(
3558 gate_req.namespace.as_str(),
3559 gate_req.verb.as_str(),
3560 EventKind::Audit,
3561 SubstrateKind::Event,
3562 format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
3563 )
3564 .with_outcome(EventOutcome::Success)
3565 .with_target(project_id)
3566 .with_payload_schema_version(2)
3567 .with_duration_us(duration_us);
3568 let receipt_id = event.id;
3569 report_object.insert(
3570 "receipt_id".to_string(),
3571 Value::String(receipt_id.to_string()),
3572 );
3573
3574 let mut payload = serde_json::to_value(audit).unwrap_or_else(|serialize_err| {
3575 tracing::error!(
3576 verb = "git.digest",
3577 error = %serialize_err,
3578 "failed to serialize gate audit for durable digest receipt"
3579 );
3580 Value::Null
3581 });
3582 let Value::Object(payload_object) = &mut payload else {
3583 tracing::error!(
3584 verb = "git.digest",
3585 "gate audit serialization did not produce an object"
3586 );
3587 *result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
3588 return GitDigestReceiptOutcome::BuildRejected;
3589 };
3590 if let Some(resource) = resource {
3591 payload_object.insert("resource".to_string(), resource);
3592 }
3593 payload_object.insert("result".to_string(), report.clone());
3594 event.payload = payload;
3595
3596 let submit_result = if let Some(audit_batch) = audit_batch {
3603 use crate::audit_batch::AuditBatchControl;
3604 audit_batch
3605 .submit(crate::audit_batch::PreparedAuditRow {
3606 event,
3607 producer: crate::audit_batch::AuditProducer::GitDigestReceipt,
3608 })
3609 .await
3610 .map(|_outcome| ())
3611 .map_err(|reason| format!("{reason:?}"))
3612 } else {
3613 store.append_event(event).await.map_err(|e| e.to_string())
3614 };
3615 if let Err(store_err) = submit_result {
3616 AUDIT_OBLIGATION_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3621 tracing::error!(
3622 verb = "git.digest",
3623 error = %store_err,
3624 receipt_id = %receipt_id,
3625 "durable digest receipt append failed"
3626 );
3627 *result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
3628 return GitDigestReceiptOutcome::PersistenceUnavailable;
3629 }
3630 GitDigestReceiptOutcome::Persisted
3631}
3632
3633async fn append_audit_event_best_effort(
3679 audit_batch: Option<&Arc<crate::audit_batch::AuditBatch>>,
3680 store: &Arc<dyn EventStore>,
3681 event: Event,
3682 verb: &str,
3683 producer: crate::audit_batch::AuditProducer,
3684 degrade_allowlisted: bool,
3685) -> Result<(), RuntimeError> {
3686 use crate::audit_batch::{
3687 classify, AuditBatchControl, AuditProducer, AuditProductionClass, AuditTerminalReason,
3688 };
3689
3690 let is_obligation = classify(producer) == AuditProductionClass::DispatchObligation;
3691 let admission_degrade_eligible =
3692 degrade_allowlisted && producer == AuditProducer::DispatchSucceeded;
3693
3694 if let Some(audit_batch) = audit_batch {
3695 if let Err(reason) = audit_batch
3696 .submit(crate::audit_batch::PreparedAuditRow { event, producer })
3697 .await
3698 {
3699 if is_obligation {
3700 if admission_degrade_eligible {
3716 match reason {
3717 AuditTerminalReason::QueueAdmissionExhausted => {
3718 AUDIT_ADMISSION_REFUSED_OBLIGATIONS
3719 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3720 tracing::warn!(
3721 verb,
3722 reason = ?reason,
3723 "read verb's audit obligation row was refused before \
3724 enqueue under audit-lane admission pressure; dispatch \
3725 still reports its own result (non-fatal)"
3726 );
3727 return Ok(());
3728 }
3729 AuditTerminalReason::AdmissionDeadlineExpired => {
3730 AUDIT_ADMISSION_UNRESOLVED_OBLIGATIONS
3731 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3732 tracing::warn!(
3733 verb,
3734 reason = ?reason,
3735 "read verb's audit obligation row was still enqueued and \
3736 unresolved when the caller's admission wait deadline \
3737 elapsed; it may still commit. Dispatch still reports its \
3738 own result (non-fatal)"
3739 );
3740 return Ok(());
3741 }
3742 _ => {}
3743 }
3744 }
3745 AUDIT_OBLIGATION_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3746 tracing::error!(
3747 verb,
3748 reason = ?reason,
3749 "audit obligation batch submission failed; failing dispatch"
3750 );
3751 return Err(RuntimeError::Internal(format!(
3752 "audit obligation commit failed for verb {verb:?}: {reason:?}"
3753 )));
3754 }
3755 AUDIT_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3756 tracing::warn!(
3757 verb,
3758 reason = ?reason,
3759 "audit event batch submission failed (non-fatal)"
3760 );
3761 }
3762 return Ok(());
3763 }
3764
3765 if let Err(store_err) = store.append_event(event).await {
3766 if is_obligation {
3767 AUDIT_OBLIGATION_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3768 tracing::error!(
3769 verb,
3770 error = %store_err,
3771 "audit obligation store write failed; failing dispatch"
3772 );
3773 return Err(RuntimeError::Internal(format!(
3774 "audit obligation commit failed for verb {verb:?}: {store_err}"
3775 )));
3776 }
3777 AUDIT_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3778 tracing::warn!(
3779 verb,
3780 error = %store_err,
3781 "audit event store write failed (non-fatal)"
3782 );
3783 }
3784 Ok(())
3785}
3786
3787fn fold_audit_obligation<T>(
3795 result: Result<T, RuntimeError>,
3796 audit_outcome: Result<(), RuntimeError>,
3797) -> Result<T, RuntimeError> {
3798 match (result, audit_outcome) {
3799 (Ok(value), Ok(())) => Ok(value),
3800 (Ok(_), Err(audit_err)) => Err(audit_err),
3801 (Err(err), _) => Err(err),
3802 }
3803}
3804
3805#[derive(Debug, Clone, serde::Serialize)]
3808struct LinkAuditSuccessV2 {
3809 #[serde(flatten)]
3810 audit: AuditEvent,
3811 edge_id: uuid::Uuid,
3812 source_id: uuid::Uuid,
3813 target_id: uuid::Uuid,
3814 relation: String,
3815 weight: f64,
3816}
3817
3818fn link_audit_success_from_result(
3822 audit: AuditEvent,
3823 result: &serde_json::Value,
3824) -> Option<(uuid::Uuid, serde_json::Value)> {
3825 let edge_id = result.get("id")?.as_str()?.parse::<uuid::Uuid>().ok()?;
3826 let source_id = result
3827 .get("source_id")?
3828 .as_str()?
3829 .parse::<uuid::Uuid>()
3830 .ok()?;
3831 let target_id = result
3832 .get("target_id")?
3833 .as_str()?
3834 .parse::<uuid::Uuid>()
3835 .ok()?;
3836 let relation = result.get("relation")?.as_str()?.to_string();
3837 let weight = result.get("weight")?.as_f64()?;
3838 let enriched = LinkAuditSuccessV2 {
3839 audit,
3840 edge_id,
3841 source_id,
3842 target_id,
3843 relation,
3844 weight,
3845 };
3846 let payload = serde_json::to_value(&enriched).ok()?;
3847 Some((edge_id, payload))
3848}
3849
3850pub fn resolve_explicit_namespace(
3863 params: &Value,
3864 default_namespace: &str,
3865) -> Result<Namespace, RuntimeError> {
3866 match params.get("namespace") {
3867 None => Namespace::parse(default_namespace)
3868 .map_err(|e| RuntimeError::InvalidInput(format!("invalid namespace: {e}"))),
3869 Some(Value::String(ns_str)) => Namespace::parse(ns_str)
3870 .map_err(|e| RuntimeError::InvalidInput(format!("invalid namespace {ns_str:?}: {e}"))),
3871 Some(other) => Err(RuntimeError::InvalidInput(format!(
3872 "invalid namespace: expected string when present, got {}",
3873 json_type_name(other),
3874 ))),
3875 }
3876}
3877
3878pub fn json_type_name(v: &Value) -> &'static str {
3881 match v {
3882 Value::Null => "null",
3883 Value::Bool(_) => "boolean",
3884 Value::Number(_) => "number",
3885 Value::String(_) => "string",
3886 Value::Array(_) => "array",
3887 Value::Object(_) => "object",
3888 }
3889}
3890
3891#[cfg(test)]
3897pub(crate) mod tests {
3898 use super::*;
3899 use crate::ActorRef;
3900 use khive_types::Pack;
3901
3902 const KNOWN_INCIDENTAL_WRITE_VERBS: &[&str] = &["memory.recall", "db_diagnostics"];
3912
3913 #[test]
3939 fn admission_degrade_safe_verbs_are_registered_assertive() {
3940 let path = concat!(
3941 env!("CARGO_MANIFEST_DIR"),
3942 "/../khive-pack-kg/src/handler_defs.rs"
3943 );
3944 let source =
3945 std::fs::read_to_string(path).unwrap_or_else(|e| panic!("failed to read {path}: {e}"));
3946
3947 for verb in VerbRegistry::ADMISSION_DEGRADE_SAFE_VERBS {
3948 assert!(
3949 !KNOWN_INCIDENTAL_WRITE_VERBS.contains(verb),
3950 "admission-degrade-safe verb {verb:?} is a known incidental-write verb \
3951 (khive#2147/khive#2217 round 1); it must not be re-added to \
3952 ADMISSION_DEGRADE_SAFE_VERBS even though it is VerbCategory::Assertive"
3953 );
3954 let needle = format!("\n name: \"{verb}\",");
3961 let name_pos = source.find(&needle).unwrap_or_else(|| {
3962 panic!(
3963 "admission-degrade-safe verb {verb:?} has no top-level `HandlerDef` in \
3964 khive-pack-kg/src/handler_defs.rs; update the allowlist or this \
3965 census's source path"
3966 )
3967 });
3968 let block_end = source[name_pos..]
3974 .find("HandlerDef {")
3975 .map(|offset| name_pos + offset)
3976 .unwrap_or(source.len());
3977 let block = &source[name_pos..block_end];
3978 assert!(
3979 block.contains("VerbCategory::Assertive"),
3980 "admission-degrade-safe verb {verb:?} is declared in \
3981 khive-pack-kg/src/handler_defs.rs but is not VerbCategory::Assertive; \
3982 admission degradation must not silently apply to a write-capable verb"
3983 );
3984 }
3985 }
3986
3987 static COMM_PROBE_GRANTED: std::sync::atomic::AtomicBool =
3988 std::sync::atomic::AtomicBool::new(false);
3989 static OTHER_PROBE_GRANTED: std::sync::atomic::AtomicBool =
3990 std::sync::atomic::AtomicBool::new(false);
3991
3992 struct CommProbeFactory;
3996 struct OtherProbeFactory;
3997
3998 fn probe_pack(
3999 _runtime: KhiveRuntime,
4000 grant_flag: &'static std::sync::atomic::AtomicBool,
4001 ) -> Box<dyn PackRuntime> {
4002 struct ProbePack {
4003 grant_flag: &'static std::sync::atomic::AtomicBool,
4004 }
4005 #[async_trait::async_trait]
4006 impl PackRuntime for ProbePack {
4007 fn name(&self) -> &str {
4008 "probe"
4009 }
4010 fn note_kinds(&self) -> &'static [&'static str] {
4011 &[]
4012 }
4013 fn entity_kinds(&self) -> &'static [&'static str] {
4014 &[]
4015 }
4016 fn handlers(&self) -> &'static [HandlerDef] {
4017 &[]
4018 }
4019 fn accept_channel_ingest_capability(&self, _capability: ChannelIngestCapability) {
4020 self.grant_flag
4021 .store(true, std::sync::atomic::Ordering::SeqCst);
4022 }
4023 async fn dispatch(
4024 &self,
4025 _verb: &str,
4026 _params: serde_json::Value,
4027 _registry: &VerbRegistry,
4028 _token: &NamespaceToken,
4029 ) -> Result<serde_json::Value, crate::RuntimeError> {
4030 Err(crate::RuntimeError::InvalidInput("probe".into()))
4031 }
4032 }
4033 Box::new(ProbePack { grant_flag })
4034 }
4035
4036 impl PackFactory for CommProbeFactory {
4037 fn name(&self) -> &'static str {
4038 "comm"
4039 }
4040 fn create(&self, runtime: KhiveRuntime) -> Box<dyn PackRuntime> {
4041 probe_pack(runtime, &COMM_PROBE_GRANTED)
4042 }
4043 }
4044
4045 impl PackFactory for OtherProbeFactory {
4046 fn name(&self) -> &'static str {
4047 "grant-probe-other"
4048 }
4049 fn create(&self, runtime: KhiveRuntime) -> Box<dyn PackRuntime> {
4050 probe_pack(runtime, &OTHER_PROBE_GRANTED)
4051 }
4052 }
4053
4054 inventory::submit! { PackRegistration(&CommProbeFactory) }
4055 inventory::submit! { PackRegistration(&OtherProbeFactory) }
4056
4057 #[test]
4058 fn channel_ingest_grant_reaches_only_allowlisted_pack_names() {
4059 let runtime = KhiveRuntime::memory().unwrap();
4060 let mut builder = VerbRegistryBuilder::new();
4061 PackRegistry::register_packs(
4062 &["comm".to_string(), "grant-probe-other".to_string()],
4063 runtime,
4064 &mut builder,
4065 )
4066 .expect("probe registration succeeds");
4067 assert!(
4068 COMM_PROBE_GRANTED.load(std::sync::atomic::Ordering::SeqCst),
4069 "the comm-named factory must receive the channel-ingest grant"
4070 );
4071 assert!(
4072 !OTHER_PROBE_GRANTED.load(std::sync::atomic::Ordering::SeqCst),
4073 "a factory outside CHANNEL_INGEST_CAPABLE_PACKS must never be granted"
4074 );
4075 }
4076
4077 #[test]
4078 fn from_token_preserves_process_ref() {
4079 let with_ref = NamespaceToken::mint_authorized(
4080 Namespace::local(),
4081 ActorRef::new("agent", "provenance-carrier"),
4082 )
4083 .with_process_ref(Some("proc:origin-abc123".to_string()));
4084 let identity = RequestIdentity::from_token(&with_ref);
4085 assert_eq!(identity.process_ref.as_deref(), Some("proc:origin-abc123"));
4086
4087 let without_ref = NamespaceToken::mint_authorized(
4088 Namespace::local(),
4089 ActorRef::new("agent", "provenance-absent"),
4090 );
4091 let identity = RequestIdentity::from_token(&without_ref);
4092 assert_eq!(identity.process_ref, None);
4093 }
4094
4095 struct AlphaPack;
4096
4097 impl Pack for AlphaPack {
4098 const NAME: &'static str = "alpha";
4099 const NOTE_KINDS: &'static [&'static str] = &["memo", "log"];
4100 const ENTITY_KINDS: &'static [&'static str] = &["widget"];
4101 const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["recall", "search"];
4102 const HANDLERS: &'static [HandlerDef] = &[
4103 HandlerDef {
4104 name: "create",
4105 description: "create a widget",
4106 visibility: Visibility::Verb,
4107 category: VerbCategory::Commissive,
4108 params: &[],
4109 },
4110 HandlerDef {
4111 name: "list",
4112 description: "list widgets",
4113 visibility: Visibility::Verb,
4114 category: VerbCategory::Assertive,
4115 params: &[],
4116 },
4117 ];
4118 }
4119
4120 #[async_trait]
4121 impl PackRuntime for AlphaPack {
4122 fn name(&self) -> &str {
4123 AlphaPack::NAME
4124 }
4125 fn note_kinds(&self) -> &'static [&'static str] {
4126 AlphaPack::NOTE_KINDS
4127 }
4128 fn entity_kinds(&self) -> &'static [&'static str] {
4129 AlphaPack::ENTITY_KINDS
4130 }
4131 fn brain_consumer_kinds(&self) -> &'static [&'static str] {
4132 AlphaPack::BRAIN_CONSUMER_KINDS
4133 }
4134 fn handlers(&self) -> &'static [HandlerDef] {
4135 AlphaPack::HANDLERS
4136 }
4137 async fn dispatch(
4138 &self,
4139 verb: &str,
4140 _params: Value,
4141 _registry: &VerbRegistry,
4142 _token: &NamespaceToken,
4143 ) -> Result<Value, RuntimeError> {
4144 Ok(serde_json::json!({ "pack": "alpha", "verb": verb }))
4145 }
4146 }
4147
4148 #[derive(Debug)]
4149 struct GateErrorTrackingPack {
4150 invoked: Arc<AtomicUsize>,
4151 }
4152
4153 impl Pack for GateErrorTrackingPack {
4154 const NAME: &'static str = "gate_error_tracking";
4155 const NOTE_KINDS: &'static [&'static str] = &[];
4156 const ENTITY_KINDS: &'static [&'static str] = &[];
4157 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
4158 name: "guarded",
4159 description: "track whether gate-error dispatch reaches the handler",
4160 visibility: Visibility::Verb,
4161 category: VerbCategory::Assertive,
4162 params: &[],
4163 }];
4164 }
4165
4166 #[async_trait]
4167 impl PackRuntime for GateErrorTrackingPack {
4168 fn name(&self) -> &str {
4169 Self::NAME
4170 }
4171
4172 fn note_kinds(&self) -> &'static [&'static str] {
4173 Self::NOTE_KINDS
4174 }
4175
4176 fn entity_kinds(&self) -> &'static [&'static str] {
4177 Self::ENTITY_KINDS
4178 }
4179
4180 fn handlers(&self) -> &'static [HandlerDef] {
4181 Self::HANDLERS
4182 }
4183
4184 async fn dispatch(
4185 &self,
4186 _verb: &str,
4187 _params: Value,
4188 _registry: &VerbRegistry,
4189 _token: &NamespaceToken,
4190 ) -> Result<Value, RuntimeError> {
4191 self.invoked.fetch_add(1, Ordering::SeqCst);
4192 Ok(serde_json::json!({"invoked": true}))
4193 }
4194 }
4195
4196 struct SleepingPack;
4200
4201 impl Pack for SleepingPack {
4202 const NAME: &'static str = "sleeping";
4203 const NOTE_KINDS: &'static [&'static str] = &[];
4204 const ENTITY_KINDS: &'static [&'static str] = &[];
4205 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
4206 name: "slow_op",
4207 description: "sleeps before returning",
4208 visibility: Visibility::Verb,
4209 category: VerbCategory::Assertive,
4210 params: &[],
4211 }];
4212 }
4213
4214 #[async_trait]
4215 impl PackRuntime for SleepingPack {
4216 fn name(&self) -> &str {
4217 SleepingPack::NAME
4218 }
4219 fn note_kinds(&self) -> &'static [&'static str] {
4220 SleepingPack::NOTE_KINDS
4221 }
4222 fn entity_kinds(&self) -> &'static [&'static str] {
4223 SleepingPack::ENTITY_KINDS
4224 }
4225 fn handlers(&self) -> &'static [HandlerDef] {
4226 SleepingPack::HANDLERS
4227 }
4228 async fn dispatch(
4229 &self,
4230 verb: &str,
4231 _params: Value,
4232 _registry: &VerbRegistry,
4233 _token: &NamespaceToken,
4234 ) -> Result<Value, RuntimeError> {
4235 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
4236 Ok(serde_json::json!({ "pack": "sleeping", "verb": verb }))
4237 }
4238 }
4239
4240 struct BetaPack;
4241
4242 impl Pack for BetaPack {
4243 const NAME: &'static str = "beta";
4244 const NOTE_KINDS: &'static [&'static str] = &["alert"];
4245 const ENTITY_KINDS: &'static [&'static str] = &["widget", "gadget"];
4246 const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["search", "knowledge_compose"];
4247 const HANDLERS: &'static [HandlerDef] = &[
4248 HandlerDef {
4249 name: "notify",
4250 description: "send alert",
4251 visibility: Visibility::Verb,
4252 category: VerbCategory::Commissive,
4253 params: &[],
4254 },
4255 HandlerDef {
4259 name: "create",
4260 description: "beta internal create (subhandler)",
4261 visibility: Visibility::Subhandler,
4262 category: VerbCategory::Commissive,
4263 params: &[],
4264 },
4265 ];
4266 }
4267
4268 fn build_registry() -> VerbRegistry {
4274 let mut builder = VerbRegistryBuilder::new();
4275 builder.register(AlphaPack);
4276 builder.register(BetaPack);
4277 builder.build().expect("registry builds without collision")
4278 }
4279
4280 struct CollidingPack;
4283
4284 impl Pack for CollidingPack {
4285 const NAME: &'static str = "colliding";
4286 const NOTE_KINDS: &'static [&'static str] = &[];
4287 const ENTITY_KINDS: &'static [&'static str] = &[];
4288 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
4289 name: "create",
4290 description: "duplicate Verb-visibility create",
4291 visibility: Visibility::Verb,
4292 category: VerbCategory::Commissive,
4293 params: &[],
4294 }];
4295 }
4296
4297 #[async_trait]
4298 impl PackRuntime for CollidingPack {
4299 fn name(&self) -> &str {
4300 Self::NAME
4301 }
4302 fn note_kinds(&self) -> &'static [&'static str] {
4303 Self::NOTE_KINDS
4304 }
4305 fn entity_kinds(&self) -> &'static [&'static str] {
4306 Self::ENTITY_KINDS
4307 }
4308 fn handlers(&self) -> &'static [HandlerDef] {
4309 Self::HANDLERS
4310 }
4311 async fn dispatch(
4312 &self,
4313 verb: &str,
4314 _params: Value,
4315 _registry: &VerbRegistry,
4316 _token: &NamespaceToken,
4317 ) -> Result<Value, RuntimeError> {
4318 Ok(serde_json::json!({ "pack": "colliding", "verb": verb }))
4319 }
4320 }
4321
4322 struct ReservedEnvelopeParamPack;
4323
4324 impl Pack for ReservedEnvelopeParamPack {
4325 const NAME: &'static str = "reserved-envelope-param";
4326 const NOTE_KINDS: &'static [&'static str] = &[];
4327 const ENTITY_KINDS: &'static [&'static str] = &[];
4328 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
4329 name: "broken.serve",
4330 description: "declares a transport-owned argument",
4331 visibility: Visibility::Verb,
4332 category: VerbCategory::Commissive,
4333 params: &[ParamDef {
4334 name: "presentation",
4335 param_type: "object",
4336 required: false,
4337 description: "invalid collision with the request envelope",
4338 }],
4339 }];
4340 }
4341
4342 #[async_trait]
4343 impl PackRuntime for ReservedEnvelopeParamPack {
4344 fn name(&self) -> &str {
4345 Self::NAME
4346 }
4347 fn note_kinds(&self) -> &'static [&'static str] {
4348 Self::NOTE_KINDS
4349 }
4350 fn entity_kinds(&self) -> &'static [&'static str] {
4351 Self::ENTITY_KINDS
4352 }
4353 fn handlers(&self) -> &'static [HandlerDef] {
4354 Self::HANDLERS
4355 }
4356 async fn dispatch(
4357 &self,
4358 _verb: &str,
4359 _params: Value,
4360 _registry: &VerbRegistry,
4361 _token: &NamespaceToken,
4362 ) -> Result<Value, RuntimeError> {
4363 unreachable!("invalid handler metadata must fail before dispatch")
4364 }
4365 }
4366
4367 #[async_trait]
4368 impl PackRuntime for BetaPack {
4369 fn name(&self) -> &str {
4370 BetaPack::NAME
4371 }
4372 fn note_kinds(&self) -> &'static [&'static str] {
4373 BetaPack::NOTE_KINDS
4374 }
4375 fn entity_kinds(&self) -> &'static [&'static str] {
4376 BetaPack::ENTITY_KINDS
4377 }
4378 fn brain_consumer_kinds(&self) -> &'static [&'static str] {
4379 BetaPack::BRAIN_CONSUMER_KINDS
4380 }
4381 fn handlers(&self) -> &'static [HandlerDef] {
4382 BetaPack::HANDLERS
4383 }
4384 async fn dispatch(
4385 &self,
4386 verb: &str,
4387 _params: Value,
4388 _registry: &VerbRegistry,
4389 _token: &NamespaceToken,
4390 ) -> Result<Value, RuntimeError> {
4391 Ok(serde_json::json!({ "pack": "beta", "verb": verb }))
4392 }
4393 }
4394
4395 #[tokio::test]
4396 async fn dispatch_routes_to_correct_pack() {
4397 let reg = build_registry();
4398
4399 let res = reg.dispatch("list", Value::Null).await.unwrap();
4400 assert_eq!(res["pack"], "alpha");
4401
4402 let res = reg.dispatch("notify", Value::Null).await.unwrap();
4403 assert_eq!(res["pack"], "beta");
4404 }
4405
4406 #[test]
4410 fn verb_collision_is_boot_time_error() {
4411 let mut builder = VerbRegistryBuilder::new();
4412 builder.register(AlphaPack);
4413 builder.register(CollidingPack);
4414 let err = builder
4415 .build()
4416 .err()
4417 .expect("duplicate Verb-visibility handler must be rejected at build time");
4418 assert!(
4419 matches!(err, RuntimeError::VerbCollision { ref verb, .. } if verb == "create"),
4420 "expected VerbCollision for 'create', got {err:?}"
4421 );
4422 let msg = err.to_string();
4423 assert!(
4424 msg.contains("create"),
4425 "error must name the colliding verb: {msg}"
4426 );
4427 assert!(
4428 msg.contains("alpha") || msg.contains("colliding"),
4429 "error must name one of the conflicting packs: {msg}"
4430 );
4431 }
4432
4433 #[test]
4434 fn reserved_request_envelope_param_is_boot_time_error() {
4435 let mut builder = VerbRegistryBuilder::new();
4436 builder.register(ReservedEnvelopeParamPack);
4437 let error = builder
4438 .build()
4439 .err()
4440 .expect("transport-owned parameter names must fail registry construction");
4441 assert!(
4442 matches!(
4443 error,
4444 RuntimeError::ReservedEnvelopeParam {
4445 ref pack,
4446 ref verb,
4447 ref param,
4448 } if pack == "reserved-envelope-param"
4449 && verb == "broken.serve"
4450 && param == "presentation"
4451 ),
4452 "unexpected error: {error:?}"
4453 );
4454 }
4455
4456 #[test]
4457 fn reserved_request_envelope_param_is_boot_time_error_for_subhandler() {
4458 struct ReservedEnvelopeSubhandlerParamPack;
4459
4460 impl Pack for ReservedEnvelopeSubhandlerParamPack {
4461 const NAME: &'static str = "reserved-envelope-subhandler-param";
4462 const NOTE_KINDS: &'static [&'static str] = &[];
4463 const ENTITY_KINDS: &'static [&'static str] = &[];
4464 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
4465 name: "broken.internal",
4466 description: "declares a transport-owned argument on an internal handler",
4467 visibility: Visibility::Subhandler,
4468 category: VerbCategory::Assertive,
4469 params: &[ParamDef {
4470 name: "presentation_per_op",
4471 param_type: "string",
4472 required: false,
4473 description: "invalid collision with the request envelope",
4474 }],
4475 }];
4476 }
4477
4478 #[async_trait]
4479 impl PackRuntime for ReservedEnvelopeSubhandlerParamPack {
4480 fn name(&self) -> &str {
4481 Self::NAME
4482 }
4483 fn note_kinds(&self) -> &'static [&'static str] {
4484 Self::NOTE_KINDS
4485 }
4486 fn entity_kinds(&self) -> &'static [&'static str] {
4487 Self::ENTITY_KINDS
4488 }
4489 fn handlers(&self) -> &'static [HandlerDef] {
4490 Self::HANDLERS
4491 }
4492 async fn dispatch(
4493 &self,
4494 _verb: &str,
4495 _params: Value,
4496 _registry: &VerbRegistry,
4497 _token: &NamespaceToken,
4498 ) -> Result<Value, RuntimeError> {
4499 unreachable!("invalid handler metadata must fail before dispatch")
4500 }
4501 }
4502
4503 let mut builder = VerbRegistryBuilder::new();
4504 builder.register(ReservedEnvelopeSubhandlerParamPack);
4505 let error = builder
4506 .build()
4507 .err()
4508 .expect("transport-owned parameter names must fail registry construction");
4509 assert!(
4510 matches!(
4511 error,
4512 RuntimeError::ReservedEnvelopeParam {
4513 ref pack,
4514 ref verb,
4515 ref param,
4516 } if pack == "reserved-envelope-subhandler-param"
4517 && verb == "broken.internal"
4518 && param == "presentation_per_op"
4519 ),
4520 "unexpected error: {error:?}"
4521 );
4522 }
4523
4524 #[test]
4528 fn subhandler_same_name_across_packs_is_not_a_collision() {
4529 struct SubhandlerPack;
4530 impl Pack for SubhandlerPack {
4531 const NAME: &'static str = "subhandler_pack";
4532 const NOTE_KINDS: &'static [&'static str] = &[];
4533 const ENTITY_KINDS: &'static [&'static str] = &[];
4534 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
4535 name: "create",
4536 description: "internal create",
4537 visibility: Visibility::Subhandler,
4538 category: VerbCategory::Commissive,
4539 params: &[],
4540 }];
4541 }
4542 #[async_trait]
4543 impl PackRuntime for SubhandlerPack {
4544 fn name(&self) -> &str {
4545 Self::NAME
4546 }
4547 fn note_kinds(&self) -> &'static [&'static str] {
4548 Self::NOTE_KINDS
4549 }
4550 fn entity_kinds(&self) -> &'static [&'static str] {
4551 Self::ENTITY_KINDS
4552 }
4553 fn handlers(&self) -> &'static [HandlerDef] {
4554 Self::HANDLERS
4555 }
4556 async fn dispatch(
4557 &self,
4558 verb: &str,
4559 _: Value,
4560 _: &VerbRegistry,
4561 _: &NamespaceToken,
4562 ) -> Result<Value, RuntimeError> {
4563 Ok(serde_json::json!({"pack": "subhandler_pack", "verb": verb}))
4564 }
4565 }
4566 let mut builder = VerbRegistryBuilder::new();
4567 builder.register(AlphaPack); builder.register(SubhandlerPack); builder
4570 .build()
4571 .expect("subhandler same name must NOT be a collision");
4572 }
4573
4574 #[tokio::test]
4575 async fn dispatch_unknown_verb_returns_error() {
4576 let reg = build_registry();
4577
4578 let err = reg.dispatch("explode", Value::Null).await.unwrap_err();
4579 let msg = err.to_string();
4580 assert!(msg.contains("explode"));
4581 assert!(msg.contains("create"));
4582 }
4583
4584 #[test]
4589 fn all_verbs_aggregates_across_packs_excludes_subhandlers() {
4590 let reg = build_registry();
4591 let verbs: Vec<&str> = reg.all_verbs().iter().map(|v| v.name).collect();
4592 assert_eq!(verbs, vec!["create", "list", "notify"]);
4594 }
4595
4596 #[test]
4597 fn all_verbs_with_names_pairs_pack_name_excludes_subhandlers() {
4598 let reg = build_registry();
4599 let pairs: Vec<(&str, &str)> = reg
4600 .all_verbs_with_names()
4601 .iter()
4602 .map(|(pack, v)| (*pack, v.name))
4603 .collect();
4604 assert_eq!(
4606 pairs,
4607 vec![("alpha", "create"), ("alpha", "list"), ("beta", "notify"),]
4608 );
4609 }
4610
4611 #[test]
4612 fn all_handlers_with_names_includes_subhandlers() {
4613 let reg = build_registry();
4614 let pairs: Vec<(&str, &str)> = reg
4615 .all_handlers_with_names()
4616 .iter()
4617 .map(|(pack, v)| (*pack, v.name))
4618 .collect();
4619 assert_eq!(
4621 pairs,
4622 vec![
4623 ("alpha", "create"),
4624 ("alpha", "list"),
4625 ("beta", "notify"),
4626 ("beta", "create"),
4627 ]
4628 );
4629 }
4630
4631 #[test]
4632 fn note_kinds_are_ordered() {
4633 let reg = build_registry();
4634 let kinds = reg.all_note_kinds();
4635 assert_eq!(kinds, vec!["memo", "log", "alert"]);
4636 }
4637
4638 #[test]
4639 fn brain_consumer_kinds_are_ordered_and_deduplicated() {
4640 let reg = build_registry();
4641 assert_eq!(
4642 reg.all_brain_consumer_kinds(),
4643 vec!["recall", "search", "knowledge_compose"]
4644 );
4645 }
4646
4647 #[test]
4648 fn brain_consumer_kind_wildcard_is_rejected_at_build_time() {
4649 struct WildcardConsumerPack;
4650
4651 impl khive_types::Pack for WildcardConsumerPack {
4652 const NAME: &'static str = "wildcard-consumer";
4653 const NOTE_KINDS: &'static [&'static str] = &[];
4654 const ENTITY_KINDS: &'static [&'static str] = &[];
4655 const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["*"];
4656 const HANDLERS: &'static [HandlerDef] = &[];
4657 }
4658
4659 #[async_trait]
4660 impl PackRuntime for WildcardConsumerPack {
4661 fn name(&self) -> &str {
4662 Self::NAME
4663 }
4664 fn note_kinds(&self) -> &'static [&'static str] {
4665 Self::NOTE_KINDS
4666 }
4667 fn entity_kinds(&self) -> &'static [&'static str] {
4668 Self::ENTITY_KINDS
4669 }
4670 fn brain_consumer_kinds(&self) -> &'static [&'static str] {
4671 Self::BRAIN_CONSUMER_KINDS
4672 }
4673 fn handlers(&self) -> &'static [HandlerDef] {
4674 Self::HANDLERS
4675 }
4676 async fn dispatch(
4677 &self,
4678 _verb: &str,
4679 _params: Value,
4680 _registry: &VerbRegistry,
4681 _token: &NamespaceToken,
4682 ) -> Result<Value, RuntimeError> {
4683 Ok(Value::Null)
4684 }
4685 }
4686
4687 let mut builder = VerbRegistryBuilder::new();
4688 builder.register(WildcardConsumerPack);
4689 let Err(RuntimeError::InvalidInput(message)) = builder.build() else {
4690 panic!("registry must reject a pack-declared brain wildcard");
4691 };
4692 assert!(message.contains("wildcard-consumer"), "{message}");
4693 assert!(message.contains("registry-owned"), "{message}");
4694 }
4695
4696 #[test]
4697 fn note_kind_duplicate_rejected_at_build_time() {
4698 struct DupPack;
4699
4700 impl khive_types::Pack for DupPack {
4701 const NAME: &'static str = "dup";
4702 const NOTE_KINDS: &'static [&'static str] = &["memo"];
4704 const ENTITY_KINDS: &'static [&'static str] = &[];
4705 const HANDLERS: &'static [HandlerDef] = &[];
4706 }
4707
4708 #[async_trait]
4709 impl PackRuntime for DupPack {
4710 fn name(&self) -> &str {
4711 Self::NAME
4712 }
4713 fn note_kinds(&self) -> &'static [&'static str] {
4714 Self::NOTE_KINDS
4715 }
4716 fn entity_kinds(&self) -> &'static [&'static str] {
4717 Self::ENTITY_KINDS
4718 }
4719 fn handlers(&self) -> &'static [HandlerDef] {
4720 Self::HANDLERS
4721 }
4722 async fn dispatch(
4723 &self,
4724 _verb: &str,
4725 _params: Value,
4726 _registry: &VerbRegistry,
4727 _token: &NamespaceToken,
4728 ) -> Result<Value, RuntimeError> {
4729 Ok(Value::Null)
4730 }
4731 }
4732
4733 let mut builder = VerbRegistryBuilder::new();
4734 builder.register(AlphaPack);
4735 builder.register(DupPack);
4736 let err = builder
4737 .build()
4738 .err()
4739 .expect("duplicate note kind must be rejected");
4740 let msg = err.to_string();
4741 assert!(
4742 msg.contains("memo"),
4743 "error must name the duplicate kind: {msg}"
4744 );
4745 assert!(
4746 msg.contains("alpha") || msg.contains("dup"),
4747 "error must name one of the conflicting packs: {msg}"
4748 );
4749 }
4750
4751 #[test]
4752 fn entity_kinds_are_deduplicated() {
4753 let reg = build_registry();
4754 let kinds = reg.all_entity_kinds();
4755 assert_eq!(kinds, vec!["widget", "gadget"]);
4756 }
4757
4758 struct GammaPack;
4761
4762 impl Pack for GammaPack {
4763 const NAME: &'static str = "gamma";
4764 const NOTE_KINDS: &'static [&'static str] = &[];
4765 const ENTITY_KINDS: &'static [&'static str] = &[];
4766 const HANDLERS: &'static [HandlerDef] = &[];
4767 const ENTITY_TYPES: &'static [EntityTypeDef] = &[EntityTypeDef {
4768 kind: khive_types::EntityKind::Document,
4769 type_name: "gamma_report",
4770 aliases: &["gamma_rep"],
4771 }];
4772 }
4773
4774 #[async_trait]
4775 impl PackRuntime for GammaPack {
4776 fn name(&self) -> &str {
4777 Self::NAME
4778 }
4779 fn note_kinds(&self) -> &'static [&'static str] {
4780 Self::NOTE_KINDS
4781 }
4782 fn entity_kinds(&self) -> &'static [&'static str] {
4783 Self::ENTITY_KINDS
4784 }
4785 fn handlers(&self) -> &'static [HandlerDef] {
4786 Self::HANDLERS
4787 }
4788 fn entity_types(&self) -> &'static [EntityTypeDef] {
4789 Self::ENTITY_TYPES
4790 }
4791 async fn dispatch(
4792 &self,
4793 verb: &str,
4794 _params: Value,
4795 _registry: &VerbRegistry,
4796 _token: &NamespaceToken,
4797 ) -> Result<Value, RuntimeError> {
4798 Ok(serde_json::json!({ "pack": "gamma", "verb": verb }))
4799 }
4800 }
4801
4802 #[test]
4806 fn all_entity_types_empty_when_no_pack_declares_extras() {
4807 let reg = build_registry(); assert!(reg.all_entity_types().is_empty());
4809 let composed = khive_types::EntityTypeRegistry::with_extra(reg.all_entity_types());
4810 let resolved = composed
4811 .resolve(khive_types::EntityKind::Document, Some("paper"))
4812 .expect("builtin paper subtype must still resolve");
4813 assert_eq!(resolved.entity_type.as_deref(), Some("paper"));
4814 }
4815
4816 #[test]
4819 fn pack_declared_entity_type_validates_through_composed_registry() {
4820 let mut builder = VerbRegistryBuilder::new();
4821 builder.register(AlphaPack);
4822 builder.register(GammaPack);
4823 let reg = builder.build().expect("registry builds");
4824
4825 let extras = reg.all_entity_types();
4826 assert_eq!(extras.len(), 1);
4827
4828 let composed = khive_types::EntityTypeRegistry::with_extra(extras);
4829 let resolved = composed
4830 .resolve(khive_types::EntityKind::Document, Some("gamma_rep"))
4831 .expect("pack-declared alias must resolve through the composed registry");
4832 assert_eq!(resolved.entity_type.as_deref(), Some("gamma_report"));
4833
4834 let builtin_resolved = composed
4835 .resolve(khive_types::EntityKind::Document, Some("paper"))
4836 .expect("builtin subtype must remain resolvable when a pack adds extras");
4837 assert_eq!(builtin_resolved.entity_type.as_deref(), Some("paper"));
4838
4839 composed
4840 .resolve(khive_types::EntityKind::Document, Some("nonexistent_type"))
4841 .expect_err("undeclared entity_type must still be rejected");
4842 }
4843
4844 #[test]
4850 fn overlapping_pack_declared_entity_types_reject_at_boot() {
4851 struct DeltaPack;
4852 impl Pack for DeltaPack {
4853 const NAME: &'static str = "delta";
4854 const NOTE_KINDS: &'static [&'static str] = &[];
4855 const ENTITY_KINDS: &'static [&'static str] = &[];
4856 const HANDLERS: &'static [HandlerDef] = &[];
4857 const ENTITY_TYPES: &'static [EntityTypeDef] = &[EntityTypeDef {
4858 kind: khive_types::EntityKind::Document,
4859 type_name: "gamma_report",
4860 aliases: &["gamma_rep"],
4861 }];
4862 }
4863 #[async_trait]
4864 impl PackRuntime for DeltaPack {
4865 fn name(&self) -> &str {
4866 Self::NAME
4867 }
4868 fn note_kinds(&self) -> &'static [&'static str] {
4869 Self::NOTE_KINDS
4870 }
4871 fn entity_kinds(&self) -> &'static [&'static str] {
4872 Self::ENTITY_KINDS
4873 }
4874 fn handlers(&self) -> &'static [HandlerDef] {
4875 Self::HANDLERS
4876 }
4877 fn entity_types(&self) -> &'static [EntityTypeDef] {
4878 Self::ENTITY_TYPES
4879 }
4880 async fn dispatch(
4881 &self,
4882 verb: &str,
4883 _params: Value,
4884 _registry: &VerbRegistry,
4885 _token: &NamespaceToken,
4886 ) -> Result<Value, RuntimeError> {
4887 Ok(serde_json::json!({ "pack": "delta", "verb": verb }))
4888 }
4889 }
4890
4891 let mut builder = VerbRegistryBuilder::new();
4892 builder.register(GammaPack);
4893 builder.register(DeltaPack);
4894 let err = builder.build().err().expect(
4895 "overlapping ENTITY_TYPES declarations must fail at build, not silently compose",
4896 );
4897
4898 let msg = err.to_string();
4899 assert!(
4900 msg.contains("gamma") && msg.contains("delta"),
4901 "collision error must name both contributing packs: {msg}"
4902 );
4903 assert!(
4904 msg.contains("gamma_report"),
4905 "collision error must name the colliding entity_type key: {msg}"
4906 );
4907 }
4908
4909 use khive_gate::{Gate, GateError};
4912 use std::sync::atomic::{AtomicUsize, Ordering};
4913 use std::sync::Arc;
4914
4915 #[derive(Default, Debug)]
4916 struct CountingGate {
4917 calls: AtomicUsize,
4918 deny_verb: Option<&'static str>,
4919 }
4920
4921 impl Gate for CountingGate {
4922 fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
4923 self.calls.fetch_add(1, Ordering::SeqCst);
4924 if Some(req.verb.as_str()) == self.deny_verb {
4925 Ok(GateDecision::deny(format!("test deny for {}", req.verb)))
4926 } else {
4927 Ok(GateDecision::allow())
4928 }
4929 }
4930 }
4931
4932 #[tokio::test]
4933 async fn dispatch_consults_the_gate() {
4934 let gate = Arc::new(CountingGate::default());
4935 let mut builder = VerbRegistryBuilder::new();
4936 builder.register(AlphaPack);
4937 builder.with_gate(gate.clone());
4938 let reg = builder.build().expect("registry builds");
4939
4940 reg.dispatch("list", Value::Null).await.unwrap();
4941 reg.dispatch("create", Value::Null).await.unwrap();
4942 assert_eq!(
4943 gate.calls.load(Ordering::SeqCst),
4944 2,
4945 "gate should be consulted once per dispatch"
4946 );
4947 }
4948
4949 #[tokio::test]
4950 async fn dispatch_returns_permission_denied_on_deny_v03() {
4951 let gate = Arc::new(CountingGate {
4952 calls: AtomicUsize::new(0),
4953 deny_verb: Some("create"),
4954 });
4955 let mut builder = VerbRegistryBuilder::new();
4956 builder.register(AlphaPack);
4957 builder.with_gate(gate.clone());
4958 let reg = builder.build().expect("registry builds");
4959
4960 let err = reg.dispatch("create", Value::Null).await.unwrap_err();
4962 assert!(
4963 matches!(err, RuntimeError::PermissionDenied { ref verb, .. } if verb == "create"),
4964 "expected PermissionDenied, got {err:?}"
4965 );
4966 let msg = err.to_string();
4967 assert!(
4968 msg.contains("create"),
4969 "error message must name the verb: {msg}"
4970 );
4971 assert!(
4972 msg.contains("test deny for create"),
4973 "error message must carry the deny reason: {msg}"
4974 );
4975 assert_eq!(gate.calls.load(Ordering::SeqCst), 1);
4976 }
4977
4978 #[tokio::test]
4979 async fn dispatch_allow_verb_succeeds_even_with_deny_gate_for_other_verb() {
4980 let gate = Arc::new(CountingGate {
4982 calls: AtomicUsize::new(0),
4983 deny_verb: Some("create"),
4984 });
4985 let mut builder = VerbRegistryBuilder::new();
4986 builder.register(AlphaPack);
4987 builder.with_gate(gate.clone());
4988 let reg = builder.build().expect("registry builds");
4989
4990 let res = reg.dispatch("list", Value::Null).await.unwrap();
4991 assert_eq!(res["pack"], "alpha");
4992 }
4993
4994 #[tokio::test]
4995 async fn dispatch_uses_allow_all_gate_by_default() {
4996 let reg = build_registry();
4998 let res = reg.dispatch("list", Value::Null).await.unwrap();
4999 assert_eq!(res["pack"], "alpha");
5000 }
5001
5002 #[derive(Default, Debug)]
5005 struct NamespaceCapturingGate {
5006 seen: std::sync::Mutex<Vec<String>>,
5007 }
5008
5009 impl Gate for NamespaceCapturingGate {
5010 fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
5011 self.seen
5012 .lock()
5013 .unwrap()
5014 .push(req.namespace.as_str().to_string());
5015 Ok(GateDecision::allow())
5016 }
5017 }
5018
5019 #[tokio::test]
5020 async fn dispatch_propagates_params_namespace_to_gate() {
5021 let gate = Arc::new(NamespaceCapturingGate::default());
5022 let mut builder = VerbRegistryBuilder::new();
5023 builder.register(AlphaPack);
5024 builder.with_gate(gate.clone());
5025 builder.with_default_namespace("tenant-x");
5026 let reg = builder.build().expect("registry builds");
5027
5028 reg.dispatch("list", serde_json::json!({"namespace": "tenant-y"}))
5030 .await
5031 .unwrap();
5032 reg.dispatch("list", Value::Null).await.unwrap();
5034 let err = reg
5036 .dispatch("list", serde_json::json!({"namespace": ""}))
5037 .await
5038 .unwrap_err();
5039 assert!(
5040 matches!(err, RuntimeError::InvalidInput(_)),
5041 "empty namespace must return InvalidInput, got {err:?}"
5042 );
5043
5044 let seen = gate.seen.lock().unwrap().clone();
5045 assert_eq!(seen, vec!["tenant-y", "tenant-x"]);
5046 }
5047
5048 #[tokio::test]
5049 async fn dispatch_falls_back_to_local_when_no_default_set() {
5050 let gate = Arc::new(NamespaceCapturingGate::default());
5052 let mut builder = VerbRegistryBuilder::new();
5053 builder.register(AlphaPack);
5054 builder.with_gate(gate.clone());
5055 let reg = builder.build().expect("registry builds");
5056
5057 reg.dispatch("list", Value::Null).await.unwrap();
5058 let seen = gate.seen.lock().unwrap().clone();
5059 assert_eq!(seen, vec!["local"]);
5060 }
5061
5062 #[tokio::test]
5068 async fn namespace_null_rejected_not_coerced() {
5069 let cases: Vec<(&str, Value)> = vec![
5070 ("null", Value::Null),
5071 ("number", serde_json::json!(42)),
5072 ("boolean", serde_json::json!(true)),
5073 ("array", serde_json::json!(["local"])),
5074 ("object", serde_json::json!({"ns": "local"})),
5075 ];
5076
5077 for (label, ns_value) in cases {
5078 let gate = Arc::new(NamespaceCapturingGate::default());
5079 let mut builder = VerbRegistryBuilder::new();
5080 builder.register(AlphaPack);
5081 builder.with_gate(gate.clone());
5082 builder.with_default_namespace("tenant-x");
5083 let reg = builder.build().expect("registry builds");
5084
5085 let err = reg
5086 .dispatch("list", serde_json::json!({"namespace": ns_value}))
5087 .await
5088 .unwrap_err();
5089 assert!(
5090 matches!(err, RuntimeError::InvalidInput(_)),
5091 "case {label}: expected InvalidInput, got {err:?}"
5092 );
5093
5094 let seen = gate.seen.lock().unwrap().clone();
5098 assert!(
5099 seen.is_empty(),
5100 "case {label}: gate must not be consulted for malformed namespace, saw {seen:?}"
5101 );
5102 }
5103 }
5104
5105 use khive_gate::{AuditDecision, AuditEvent, Obligation};
5108
5109 #[derive(Default, Debug)]
5111 struct AuditCapturingGate {
5112 events: std::sync::Mutex<Vec<AuditEvent>>,
5113 deny_verb: Option<&'static str>,
5114 }
5115
5116 impl Gate for AuditCapturingGate {
5117 fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
5118 let decision = if Some(req.verb.as_str()) == self.deny_verb {
5119 GateDecision::deny("test deny")
5120 } else {
5121 GateDecision::allow_with(vec![Obligation::Audit {
5122 tag: format!("{}.check", req.verb),
5123 }])
5124 };
5125 let ev = AuditEvent::from_check(req, &decision, self.impl_name());
5127 self.events.lock().unwrap().push(ev);
5128 Ok(decision)
5129 }
5130
5131 fn impl_name(&self) -> &'static str {
5132 "AuditCapturingGate"
5133 }
5134 }
5135
5136 #[tokio::test]
5137 async fn dispatch_emits_one_audit_event_per_call() {
5138 let gate = Arc::new(AuditCapturingGate::default());
5139 let mut builder = VerbRegistryBuilder::new();
5140 builder.register(AlphaPack);
5141 builder.with_gate(gate.clone());
5142 let reg = builder.build().expect("registry builds");
5143
5144 reg.dispatch("list", Value::Null).await.unwrap();
5145 reg.dispatch("create", Value::Null).await.unwrap();
5146
5147 let evs = gate.events.lock().unwrap();
5148 assert_eq!(evs.len(), 2, "exactly one audit event per dispatch call");
5149 }
5150
5151 #[tokio::test]
5152 async fn dispatch_audit_event_allow_carries_obligations() {
5153 let gate = Arc::new(AuditCapturingGate::default());
5154 let mut builder = VerbRegistryBuilder::new();
5155 builder.register(AlphaPack);
5156 builder.with_gate(gate.clone());
5157 let reg = builder.build().expect("registry builds");
5158
5159 reg.dispatch("list", Value::Null).await.unwrap();
5160
5161 let evs = gate.events.lock().unwrap();
5162 let ev = &evs[0];
5163 assert_eq!(ev.verb, "list");
5164 assert_eq!(ev.decision, AuditDecision::Allow);
5165 assert!(ev.deny_reason.is_none());
5166 assert_eq!(ev.obligations.len(), 1);
5167 assert_eq!(ev.gate_impl, "AuditCapturingGate");
5168 }
5169
5170 #[tokio::test]
5171 async fn dispatch_audit_event_deny_carries_reason() {
5172 let gate = Arc::new(AuditCapturingGate {
5173 events: Default::default(),
5174 deny_verb: Some("create"),
5175 });
5176 let mut builder = VerbRegistryBuilder::new();
5177 builder.register(AlphaPack);
5178 builder.with_gate(gate.clone());
5179 let reg = builder.build().expect("registry builds");
5180
5181 let err = reg.dispatch("create", Value::Null).await.unwrap_err();
5184 assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
5185
5186 let evs = gate.events.lock().unwrap();
5187 let ev = &evs[0];
5188 assert_eq!(ev.verb, "create");
5189 assert_eq!(ev.decision, AuditDecision::Deny);
5190 assert_eq!(ev.deny_reason.as_deref(), Some("test deny"));
5191 assert!(ev.obligations.is_empty());
5192 }
5193
5194 #[tokio::test]
5195 async fn dispatch_audit_event_fields_match_gate_request() {
5196 let gate = Arc::new(AuditCapturingGate::default());
5197 let mut builder = VerbRegistryBuilder::new();
5198 builder.register(AlphaPack);
5199 builder.with_gate(gate.clone());
5200 builder.with_default_namespace("tenant-z");
5201 let reg = builder.build().expect("registry builds");
5202
5203 reg.dispatch("list", serde_json::json!({"namespace": "tenant-q"}))
5204 .await
5205 .unwrap();
5206
5207 let evs = gate.events.lock().unwrap();
5208 let ev = &evs[0];
5209 assert_eq!(ev.namespace, "tenant-q");
5211 assert_eq!(ev.verb, "list");
5212 assert_eq!(ev.actor.kind, "anonymous");
5213 }
5214
5215 #[derive(Default, Debug)]
5219 struct ActorCapturingGate {
5220 requests: std::sync::Mutex<Vec<GateRequest>>,
5221 }
5222
5223 impl Gate for ActorCapturingGate {
5224 fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
5225 self.requests.lock().unwrap().push(req.clone());
5226 Ok(GateDecision::allow())
5227 }
5228 }
5229
5230 #[tokio::test]
5234 async fn gate_request_carries_configured_actor_when_actor_id_is_set() {
5235 let gate = Arc::new(ActorCapturingGate::default());
5236 let mut builder = VerbRegistryBuilder::new();
5237 builder.register(AlphaPack);
5238 builder.with_gate(gate.clone());
5239 builder.with_actor_id(Some("team-abc:implementer".to_string()));
5240 let reg = builder.build().expect("registry builds");
5241
5242 reg.dispatch("list", Value::Null).await.unwrap();
5243
5244 let reqs = gate.requests.lock().unwrap();
5245 assert_eq!(reqs.len(), 1);
5246 let req = &reqs[0];
5247 assert_eq!(
5248 req.actor.kind, "actor",
5249 "gate request must carry kind='actor' when actor_id is configured"
5250 );
5251 assert_eq!(
5252 req.actor.id, "team-abc:implementer",
5253 "gate request must carry the configured actor id"
5254 );
5255 }
5256
5257 #[tokio::test]
5260 async fn gate_request_carries_anonymous_when_no_actor_id_configured() {
5261 let gate = Arc::new(ActorCapturingGate::default());
5262 let mut builder = VerbRegistryBuilder::new();
5263 builder.register(AlphaPack);
5264 builder.with_gate(gate.clone());
5265 let reg = builder.build().expect("registry builds");
5267
5268 reg.dispatch("list", Value::Null).await.unwrap();
5269
5270 let reqs = gate.requests.lock().unwrap();
5271 assert_eq!(reqs.len(), 1);
5272 let req = &reqs[0];
5273 assert_eq!(
5274 req.actor.kind, "anonymous",
5275 "gate request must carry anonymous actor when no actor_id is configured"
5276 );
5277 assert_eq!(req.actor.id, "local");
5278 }
5279
5280 struct TokenCapturingPack {
5283 actors: Arc<std::sync::Mutex<Vec<khive_gate::ActorRef>>>,
5284 }
5285
5286 impl Pack for TokenCapturingPack {
5287 const NAME: &'static str = "alpha";
5288 const NOTE_KINDS: &'static [&'static str] = &[];
5289 const ENTITY_KINDS: &'static [&'static str] = &[];
5290 const HANDLERS: &'static [HandlerDef] = AlphaPack::HANDLERS;
5291 }
5292
5293 #[async_trait]
5294 impl PackRuntime for TokenCapturingPack {
5295 fn name(&self) -> &str {
5296 Self::NAME
5297 }
5298 fn note_kinds(&self) -> &'static [&'static str] {
5299 Self::NOTE_KINDS
5300 }
5301 fn entity_kinds(&self) -> &'static [&'static str] {
5302 Self::ENTITY_KINDS
5303 }
5304 fn handlers(&self) -> &'static [HandlerDef] {
5305 Self::HANDLERS
5306 }
5307 async fn dispatch(
5308 &self,
5309 verb: &str,
5310 _params: Value,
5311 _registry: &VerbRegistry,
5312 token: &NamespaceToken,
5313 ) -> Result<Value, RuntimeError> {
5314 self.actors.lock().unwrap().push(token.actor().clone());
5315 Ok(serde_json::json!({ "pack": "alpha", "verb": verb }))
5316 }
5317 }
5318
5319 #[tokio::test]
5328 async fn gate_actor_and_token_actor_are_identical_when_actor_id_is_set() {
5329 let gate = Arc::new(ActorCapturingGate::default());
5330 let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
5331 let pack = TokenCapturingPack {
5332 actors: actors.clone(),
5333 };
5334 let mut builder = VerbRegistryBuilder::new();
5335 builder.register(pack);
5336 builder.with_gate(gate.clone());
5337 builder.with_actor_id(Some("actor-alpha".to_string()));
5338 let reg = builder.build().expect("registry builds");
5339
5340 reg.dispatch("list", Value::Null).await.unwrap();
5341
5342 let reqs = gate.requests.lock().unwrap();
5343 let gate_actor = reqs[0].actor.clone();
5344 drop(reqs);
5345
5346 let captured = actors.lock().unwrap();
5347 let token_actor = captured[0].clone();
5348
5349 assert_eq!(
5350 gate_actor.kind, token_actor.kind,
5351 "gate request actor and storage token actor must carry the same kind"
5352 );
5353 assert_eq!(
5354 gate_actor.id, token_actor.id,
5355 "gate request actor and storage token actor must carry the same id"
5356 );
5357 assert_eq!(gate_actor.id, "actor-alpha");
5358 }
5359
5360 #[tokio::test]
5363 async fn gate_actor_and_token_actor_are_identical_when_anonymous() {
5364 let gate = Arc::new(ActorCapturingGate::default());
5365 let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
5366 let pack = TokenCapturingPack {
5367 actors: actors.clone(),
5368 };
5369 let mut builder = VerbRegistryBuilder::new();
5370 builder.register(pack);
5371 builder.with_gate(gate.clone());
5372 let reg = builder.build().expect("registry builds");
5373
5374 reg.dispatch("list", Value::Null).await.unwrap();
5375
5376 let reqs = gate.requests.lock().unwrap();
5377 let gate_actor = reqs[0].actor.clone();
5378 drop(reqs);
5379
5380 let captured = actors.lock().unwrap();
5381 let token_actor = captured[0].clone();
5382
5383 assert_eq!(gate_actor.kind, token_actor.kind);
5384 assert_eq!(gate_actor.id, token_actor.id);
5385 assert_eq!(gate_actor.id, "local");
5386 }
5387
5388 #[tokio::test]
5395 async fn dispatch_as_threads_verified_actor_into_token() {
5396 let gate = Arc::new(ActorCapturingGate::default());
5397 let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
5398 let pack = TokenCapturingPack {
5399 actors: actors.clone(),
5400 };
5401 let mut builder = VerbRegistryBuilder::new();
5402 builder.register(pack);
5403 builder.with_gate(gate.clone());
5404 let reg = builder.build().expect("registry builds");
5405
5406 reg.dispatch_as(
5407 "list",
5408 Value::Null,
5409 VerifiedActor::new("gateway:principal-42").unwrap(),
5410 )
5411 .await
5412 .unwrap();
5413
5414 let reqs = gate.requests.lock().unwrap();
5415 assert_eq!(reqs[0].actor.kind, "actor");
5416 assert_eq!(reqs[0].actor.id, "gateway:principal-42");
5417 drop(reqs);
5418
5419 let captured = actors.lock().unwrap();
5420 assert_eq!(captured[0].kind, "actor");
5421 assert_eq!(
5422 captured[0].id, "gateway:principal-42",
5423 "the storage token actor must be the verified_actor supplied to dispatch_as, \
5424 matching exactly what pack handlers read as the acting principal"
5425 );
5426 }
5427
5428 #[tokio::test]
5433 async fn dispatch_as_does_not_change_plain_dispatch_behavior() {
5434 let gate = Arc::new(ActorCapturingGate::default());
5435 let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
5436 let pack = TokenCapturingPack {
5437 actors: actors.clone(),
5438 };
5439 let mut builder = VerbRegistryBuilder::new();
5440 builder.register(pack);
5441 builder.with_gate(gate.clone());
5442 builder.with_actor_id(Some("baked-actor".to_string()));
5443 let reg = builder.build().expect("registry builds");
5444
5445 reg.dispatch_as(
5446 "list",
5447 Value::Null,
5448 VerifiedActor::new("verified-actor").unwrap(),
5449 )
5450 .await
5451 .unwrap();
5452 reg.dispatch("list", Value::Null).await.unwrap();
5453
5454 let captured = actors.lock().unwrap();
5455 assert_eq!(captured.len(), 2);
5456 assert_eq!(captured[0].id, "verified-actor", "dispatch_as call");
5457 assert_eq!(
5458 captured[1].id, "baked-actor",
5459 "a later plain dispatch() call must still use the registry's baked \
5460 actor_id, unaffected by the prior dispatch_as call"
5461 );
5462 }
5463
5464 #[tokio::test]
5471 async fn dispatch_as_ignores_actor_key_in_params() {
5472 let gate = Arc::new(ActorCapturingGate::default());
5473 let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
5474 let pack = TokenCapturingPack {
5475 actors: actors.clone(),
5476 };
5477 let mut builder = VerbRegistryBuilder::new();
5478 builder.register(pack);
5479 builder.with_gate(gate.clone());
5480 let reg = builder.build().expect("registry builds");
5481
5482 reg.dispatch_as(
5483 "list",
5484 serde_json::json!({"actor": "spoofed-actor"}),
5485 VerifiedActor::new("verified-actor").unwrap(),
5486 )
5487 .await
5488 .unwrap();
5489
5490 let captured = actors.lock().unwrap();
5491 assert_eq!(
5492 captured[0].id, "verified-actor",
5493 "an 'actor' key inside params must never override the verified_actor \
5494 argument threaded through dispatch_as"
5495 );
5496 }
5497
5498 #[test]
5501 fn verified_actor_rejects_empty_identifier() {
5502 let err = VerifiedActor::new("").unwrap_err();
5503 assert!(
5504 matches!(err, RuntimeError::InvalidInput(_)),
5505 "expected InvalidInput, got {err:?}"
5506 );
5507 }
5508
5509 #[test]
5512 fn verified_actor_rejects_whitespace_only_identifier() {
5513 let err = VerifiedActor::new(" ").unwrap_err();
5514 assert!(
5515 matches!(err, RuntimeError::InvalidInput(_)),
5516 "expected InvalidInput, got {err:?}"
5517 );
5518 }
5519
5520 #[tokio::test]
5534 async fn rego_gate_missing_entrypoint_returns_permission_denied() {
5535 use khive_gate_rego::RegoGate;
5536
5537 let policy = r#"
5544 package khive.gate
5545 import rego.v1
5546 verdict := "allow"
5547 "#;
5548 let gate = Arc::new(RegoGate::from_policy_str(policy).expect("policy compiles"));
5549
5550 let mut builder = VerbRegistryBuilder::new();
5551 builder.register(AlphaPack);
5552 builder.with_gate(gate);
5553 let reg = builder.build().expect("registry builds");
5554
5555 let err = reg.dispatch("create", Value::Null).await.unwrap_err();
5556 assert!(
5557 matches!(err, RuntimeError::PermissionDenied { ref verb, ref reason }
5558 if verb == "create" && reason == "policy evaluation failed"),
5559 "expected PermissionDenied with the static classified reason for a missing rego entrypoint, got {err:?}"
5560 );
5561 }
5562
5563 use std::sync::{Mutex as StdMutex, Once, OnceLock};
5575
5576 use serial_test::serial;
5577 use tracing::field::{Field, Visit};
5578
5579 #[derive(Clone, Debug, Default)]
5580 struct CapturedEvent {
5581 message: Option<String>,
5582 audit_event: Option<String>,
5583 into_id: Option<String>,
5584 budget_rows: Option<u64>,
5585 }
5586
5587 #[derive(Default)]
5588 struct CapturedEventVisitor(CapturedEvent);
5589
5590 impl Visit for CapturedEventVisitor {
5591 fn record_str(&mut self, field: &Field, value: &str) {
5592 match field.name() {
5593 "message" => self.0.message = Some(value.to_string()),
5594 "audit_event" => self.0.audit_event = Some(value.to_string()),
5595 _ => {}
5596 }
5597 }
5598
5599 fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
5600 let formatted = format!("{value:?}");
5606 let cleaned = formatted
5607 .trim_start_matches('"')
5608 .trim_end_matches('"')
5609 .to_string();
5610 match field.name() {
5611 "message" => self.0.message = Some(cleaned),
5612 "audit_event" => self.0.audit_event = Some(cleaned),
5613 "into_id" => self.0.into_id = Some(cleaned),
5614 _ => {}
5615 }
5616 }
5617
5618 fn record_u64(&mut self, field: &Field, value: u64) {
5619 if field.name() == "budget_rows" {
5620 self.0.budget_rows = Some(value);
5621 }
5622 }
5623 }
5624
5625 struct CaptureSubscriber {
5638 events: Arc<StdMutex<Vec<CapturedEvent>>>,
5639 }
5640
5641 impl CaptureSubscriber {
5642 fn new(events: Arc<StdMutex<Vec<CapturedEvent>>>) -> Self {
5643 Self { events }
5644 }
5645 }
5646
5647 impl tracing::Subscriber for CaptureSubscriber {
5648 fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
5649 true
5650 }
5651 fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
5652 tracing::span::Id::from_u64(1)
5653 }
5654 fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
5655 fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
5656 fn event(&self, event: &tracing::Event<'_>) {
5657 let mut visitor = CapturedEventVisitor::default();
5658 event.record(&mut visitor);
5659 let captured = visitor.0;
5660 if let (Some(message), Some(into_id)) = (&captured.message, &captured.into_id) {
5664 if message.ends_with("transaction materialization budget") {
5665 budget_events_sink()
5666 .lock()
5667 .unwrap()
5668 .push(CapturedBudgetLog {
5669 message: message.clone(),
5670 into_id: into_id.clone(),
5671 budget_rows: captured.budget_rows.unwrap_or(0),
5672 });
5673 }
5674 }
5675 self.events.lock().unwrap().push(captured);
5676 }
5677 fn enter(&self, _: &tracing::span::Id) {}
5678 fn exit(&self, _: &tracing::span::Id) {}
5679 }
5680
5681 static GLOBAL_CAPTURE: OnceLock<Arc<StdMutex<Vec<CapturedEvent>>>> = OnceLock::new();
5691 static GLOBAL_INIT: Once = Once::new();
5692
5693 #[derive(Clone)]
5695 pub(crate) struct CapturedBudgetLog {
5696 pub(crate) message: String,
5697 pub(crate) into_id: String,
5698 pub(crate) budget_rows: u64,
5699 }
5700
5701 static BUDGET_EVENTS: OnceLock<Arc<StdMutex<Vec<CapturedBudgetLog>>>> = OnceLock::new();
5705
5706 fn budget_events_sink() -> Arc<StdMutex<Vec<CapturedBudgetLog>>> {
5707 Arc::clone(BUDGET_EVENTS.get_or_init(|| Arc::new(StdMutex::new(Vec::new()))))
5708 }
5709
5710 pub(crate) fn budget_log_events() -> Arc<StdMutex<Vec<CapturedBudgetLog>>> {
5715 let _ = global_capture();
5716 budget_events_sink()
5717 }
5718
5719 fn global_capture() -> Arc<StdMutex<Vec<CapturedEvent>>> {
5720 GLOBAL_INIT.call_once(|| {
5721 let buffer = Arc::new(StdMutex::new(Vec::new()));
5722 let subscriber = CaptureSubscriber::new(Arc::clone(&buffer));
5723 let _ = tracing::subscriber::set_global_default(subscriber);
5728 let _ = GLOBAL_CAPTURE.set(buffer);
5729 });
5730 Arc::clone(GLOBAL_CAPTURE.get().expect("global capture initialized"))
5731 }
5732
5733 fn capture_dispatch_events<Fut>(future: Fut) -> Vec<CapturedEvent>
5738 where
5739 Fut: std::future::Future<Output = ()>,
5740 {
5741 let buffer = global_capture();
5742 buffer.lock().unwrap().clear();
5743
5744 let rt = tokio::runtime::Builder::new_current_thread()
5745 .enable_all()
5746 .build()
5747 .expect("build current-thread tokio runtime");
5748 rt.block_on(future);
5749
5750 let result = buffer.lock().unwrap().clone();
5751 result
5752 }
5753
5754 fn gate_check_events_for(events: &[CapturedEvent], gate_impl: &str) -> Vec<CapturedEvent> {
5761 events
5762 .iter()
5763 .filter(|e| e.message.as_deref() == Some("gate.check"))
5764 .filter(|e| {
5765 e.audit_event
5766 .as_deref()
5767 .and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok())
5768 .and_then(|v| {
5769 v.get("gate_impl")
5770 .and_then(|g| g.as_str().map(|s| s.to_string()))
5771 })
5772 .as_deref()
5773 == Some(gate_impl)
5774 })
5775 .cloned()
5776 .collect()
5777 }
5778
5779 #[test]
5780 #[serial]
5781 fn dispatch_tracing_emits_one_gate_check_event_on_allow() {
5782 #[derive(Debug)]
5783 struct TracingAllowGate;
5784 impl Gate for TracingAllowGate {
5785 fn check(&self, _: &GateRequest) -> Result<GateDecision, GateError> {
5786 Ok(GateDecision::allow())
5787 }
5788 fn impl_name(&self) -> &'static str {
5789 "TracingAllowGate"
5790 }
5791 }
5792
5793 let events = capture_dispatch_events(async {
5794 let mut builder = VerbRegistryBuilder::new();
5795 builder.register(AlphaPack);
5796 builder.with_gate(Arc::new(TracingAllowGate));
5797 builder.with_default_namespace("tenant-default");
5798 let reg = builder.build().expect("registry builds");
5799 reg.dispatch("list", serde_json::json!({"namespace": "tenant-q"}))
5800 .await
5801 .unwrap();
5802 });
5803
5804 let gate_events = gate_check_events_for(&events, "TracingAllowGate");
5805 assert_eq!(
5806 gate_events.len(),
5807 1,
5808 "exactly one gate.check tracing event per dispatch (allow); got {gate_events:?}"
5809 );
5810 let payload = gate_events[0]
5811 .audit_event
5812 .as_ref()
5813 .expect("gate.check event must carry an audit_event field");
5814 let audit: khive_gate::AuditEvent =
5815 serde_json::from_str(payload).expect("audit_event payload must decode to AuditEvent");
5816 assert_eq!(audit.decision, AuditDecision::Allow);
5817 assert_eq!(audit.verb, "list");
5818 assert_eq!(audit.namespace, "tenant-q");
5819 assert_eq!(audit.gate_impl, "TracingAllowGate");
5820 assert!(
5821 audit.deny_reason.is_none(),
5822 "deny_reason must be None on Allow"
5823 );
5824 }
5825
5826 #[test]
5827 #[serial]
5828 fn dispatch_tracing_emits_one_gate_check_event_when_gate_is_unavailable() {
5829 #[derive(Debug)]
5830 struct TracingUnavailableGate;
5831 impl Gate for TracingUnavailableGate {
5832 fn check(&self, _: &GateRequest) -> Result<GateDecision, GateError> {
5833 Err(GateError::Internal("tracing gate broken".into()))
5834 }
5835
5836 fn impl_name(&self) -> &'static str {
5837 "TracingUnavailableGate"
5838 }
5839 }
5840
5841 let events = capture_dispatch_events(async {
5842 let mut builder = VerbRegistryBuilder::new();
5843 builder.register(AlphaPack);
5844 builder.with_gate(Arc::new(TracingUnavailableGate));
5845 let reg = builder.build().expect("registry builds");
5846 let error = reg
5847 .dispatch("list", Value::Null)
5848 .await
5849 .expect_err("gate outage must refuse dispatch");
5850 assert!(matches!(error, RuntimeError::GateUnavailable { .. }));
5851 });
5852
5853 let gate_events = gate_check_events_for(&events, "TracingUnavailableGate");
5854 assert_eq!(
5855 gate_events.len(),
5856 1,
5857 "exactly one gate.check tracing event per gate outage; got {gate_events:?}"
5858 );
5859 let payload = gate_events[0]
5860 .audit_event
5861 .as_ref()
5862 .expect("gate outage trace must carry an audit_event field");
5863 let audit: AuditEvent =
5864 serde_json::from_str(payload).expect("audit_event payload must decode");
5865 assert_eq!(audit.decision, AuditDecision::GateUnavailable);
5866 assert!(audit.deny_reason.is_none());
5867 assert!(audit.obligations.is_empty());
5868 assert_eq!(audit.gate_impl, "TracingUnavailableGate");
5869 }
5870
5871 use crate::runtime::NamespaceToken;
5874 use async_trait::async_trait;
5875 use khive_storage::{
5876 BatchWriteSummary, Event, EventFilter, EventStore, Page, PageRequest, SubstrateKind,
5877 };
5878 use khive_types::EventOutcome;
5879
5880 struct GitDigestResultPack {
5884 project_id: uuid::Uuid,
5885 }
5886
5887 impl Pack for GitDigestResultPack {
5888 const NAME: &'static str = "git";
5889 const NOTE_KINDS: &'static [&'static str] = &[];
5890 const ENTITY_KINDS: &'static [&'static str] = &[];
5891 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
5892 name: "git.digest",
5893 description: "return a deterministic digest report",
5894 visibility: Visibility::Verb,
5895 category: VerbCategory::Assertive,
5896 params: &[],
5897 }];
5898 }
5899
5900 #[async_trait]
5901 impl PackRuntime for GitDigestResultPack {
5902 fn name(&self) -> &str {
5903 Self::NAME
5904 }
5905 fn note_kinds(&self) -> &'static [&'static str] {
5906 Self::NOTE_KINDS
5907 }
5908 fn entity_kinds(&self) -> &'static [&'static str] {
5909 Self::ENTITY_KINDS
5910 }
5911 fn handlers(&self) -> &'static [HandlerDef] {
5912 Self::HANDLERS
5913 }
5914 async fn dispatch(
5915 &self,
5916 _verb: &str,
5917 _params: Value,
5918 _registry: &VerbRegistry,
5919 _token: &NamespaceToken,
5920 ) -> Result<Value, RuntimeError> {
5921 Ok(serde_json::json!({
5922 "project_id": self.project_id,
5923 "project_created": false,
5924 "commits_ingested": 2,
5925 "commits_skipped_existing": 1,
5926 "issues_ingested": 3,
5927 "issues_skipped_existing": 4,
5928 "prs_ingested": 5,
5929 "prs_skipped_existing": 6,
5930 "done": true,
5931 "history_exhausted": true,
5932 "sources": {
5933 "commits": {"state": "completed"},
5934 "issues": {"state": "completed"},
5935 "pull_requests": {"state": "completed"}
5936 },
5937 "warnings": []
5938 }))
5939 }
5940 }
5941
5942 struct MalformedGitDigestResultPack;
5946
5947 impl Pack for MalformedGitDigestResultPack {
5948 const NAME: &'static str = "malformed-git";
5949 const NOTE_KINDS: &'static [&'static str] = &[];
5950 const ENTITY_KINDS: &'static [&'static str] = &[];
5951 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
5952 name: "git.digest",
5953 description: "return a malformed digest report",
5954 visibility: Visibility::Verb,
5955 category: VerbCategory::Assertive,
5956 params: &[],
5957 }];
5958 }
5959
5960 #[async_trait]
5961 impl PackRuntime for MalformedGitDigestResultPack {
5962 fn name(&self) -> &str {
5963 Self::NAME
5964 }
5965 fn note_kinds(&self) -> &'static [&'static str] {
5966 Self::NOTE_KINDS
5967 }
5968 fn entity_kinds(&self) -> &'static [&'static str] {
5969 Self::ENTITY_KINDS
5970 }
5971 fn handlers(&self) -> &'static [HandlerDef] {
5972 Self::HANDLERS
5973 }
5974 async fn dispatch(
5975 &self,
5976 _verb: &str,
5977 _params: Value,
5978 _registry: &VerbRegistry,
5979 _token: &NamespaceToken,
5980 ) -> Result<Value, RuntimeError> {
5981 Ok(serde_json::json!({
5982 "project_id": "not-a-uuid",
5983 "done": true,
5984 }))
5985 }
5986 }
5987
5988 #[derive(Debug, Clone, PartialEq)]
5993 enum TraceEntry {
5994 Effect { name: String },
5996 Audit {
5999 kind: EventKind,
6000 outcome: EventOutcome,
6001 verb: String,
6002 cost_unit: Option<Value>,
6005 },
6006 }
6007
6008 #[derive(Default, Debug)]
6010 struct MemoryEventStore {
6011 events: std::sync::Mutex<Vec<Event>>,
6012 fail_appends: bool,
6013 fail_kind: Option<EventKind>,
6019 trace: Option<Arc<std::sync::Mutex<Vec<TraceEntry>>>>,
6032 }
6033
6034 impl MemoryEventStore {
6035 fn trace_submission(&self, events: &[Event]) {
6055 if let Some(trace) = &self.trace {
6056 let mut trace = trace.lock().expect("trace lock");
6057 for event in events {
6058 let cost_unit = event
6059 .payload
6060 .get("resource")
6061 .and_then(|resource| resource.get("cost_unit"))
6062 .cloned();
6063 trace.push(TraceEntry::Audit {
6064 kind: event.kind,
6065 outcome: event.outcome,
6066 verb: event.verb.clone(),
6067 cost_unit,
6068 });
6069 }
6070 }
6071 }
6072 }
6073
6074 #[async_trait]
6075 impl EventStore for MemoryEventStore {
6076 async fn append_event(&self, event: Event) -> khive_storage::StorageResult<()> {
6077 self.trace_submission(std::slice::from_ref(&event));
6078 if self.fail_appends || self.fail_kind == Some(event.kind) {
6079 return Err(khive_storage::StorageError::Internal(
6080 "injected audit append failure".to_string(),
6081 ));
6082 }
6083 self.events.lock().unwrap().push(event);
6084 Ok(())
6085 }
6086 async fn append_events(
6087 &self,
6088 events: Vec<Event>,
6089 ) -> khive_storage::StorageResult<BatchWriteSummary> {
6090 self.trace_submission(&events);
6091 let attempted = events.len() as u64;
6092 let affected = attempted;
6093 self.events.lock().unwrap().extend(events);
6094 Ok(BatchWriteSummary {
6095 attempted,
6096 affected,
6097 failed: 0,
6098 first_error: String::new(),
6099 })
6100 }
6101 async fn get_event(&self, id: uuid::Uuid) -> khive_storage::StorageResult<Option<Event>> {
6102 Ok(self
6103 .events
6104 .lock()
6105 .unwrap()
6106 .iter()
6107 .find(|e| e.id == id)
6108 .cloned())
6109 }
6110 async fn query_events(
6111 &self,
6112 _filter: EventFilter,
6113 _page: PageRequest,
6114 ) -> khive_storage::StorageResult<Page<Event>> {
6115 let items = self.events.lock().unwrap().clone();
6116 let total = items.len() as u64;
6117 Ok(Page {
6118 items,
6119 total: Some(total),
6120 })
6121 }
6122 async fn count_events(&self, _filter: EventFilter) -> khive_storage::StorageResult<u64> {
6123 Ok(self.events.lock().unwrap().len() as u64)
6124 }
6125
6126 fn preflight_event(&self, _event: &Event) -> khive_storage::StorageResult<()> {
6127 Ok(())
6128 }
6129
6130 async fn append_events_idempotent(
6131 &self,
6132 events: Vec<Event>,
6133 ) -> khive_storage::StorageResult<khive_storage::event::IdempotentEventBatchResult>
6134 {
6135 self.trace_submission(&events);
6136 if self.fail_appends
6137 || self
6138 .fail_kind
6139 .is_some_and(|kind| events.iter().any(|e| e.kind == kind))
6140 {
6141 return Err(khive_storage::StorageError::Internal(
6142 "injected audit append failure".to_string(),
6143 ));
6144 }
6145 let mut store = self.events.lock().unwrap();
6146 let mut rows = Vec::with_capacity(events.len());
6147 for event in events {
6148 if let Some(existing) = store.iter().find(|e| e.id == event.id) {
6149 if *existing == event {
6150 rows.push(
6151 khive_storage::event::EventAppendDisposition::AlreadyPresentIdentical,
6152 );
6153 } else {
6154 rows.push(khive_storage::event::EventAppendDisposition::IdentityConflict);
6155 }
6156 } else {
6157 store.push(event);
6158 rows.push(khive_storage::event::EventAppendDisposition::Inserted);
6159 }
6160 }
6161 Ok(khive_storage::event::IdempotentEventBatchResult { rows })
6162 }
6163
6164 fn supports_idempotent_audit_batch(&self) -> bool {
6165 true
6166 }
6167 }
6168
6169 fn only_git_digest_event(store: &MemoryEventStore) -> Event {
6170 let events: Vec<Event> = store
6171 .events
6172 .lock()
6173 .unwrap()
6174 .iter()
6175 .filter(|event| event.verb == "git.digest")
6176 .cloned()
6177 .collect();
6178 assert_eq!(
6179 events.len(),
6180 1,
6181 "expected exactly one git.digest receipt event"
6182 );
6183 events[0].clone()
6184 }
6185
6186 #[tokio::test]
6187 async fn git_digest_success_returns_complete_durable_receipt() {
6188 let project_id = uuid::Uuid::new_v4();
6189 let store = Arc::new(MemoryEventStore::default());
6190 let mut builder = VerbRegistryBuilder::new();
6191 builder.register(GitDigestResultPack { project_id });
6192 builder.with_event_store(store.clone());
6193 let registry = builder.build().expect("registry builds");
6194
6195 let result = registry
6196 .dispatch_with_identity(
6197 "git.digest",
6198 serde_json::json!({
6199 "source": "https://user:SECRET@example.invalid/org/repo",
6200 }),
6201 Some(RequestIdentity {
6202 namespace: Namespace::local().as_str().to_string(),
6203 request_id: Some(1_510),
6204 ..Default::default()
6205 }),
6206 )
6207 .await
6208 .expect("durably receipted digest succeeds");
6209 let receipt_id = result["receipt_id"]
6210 .as_str()
6211 .and_then(|raw| raw.parse::<uuid::Uuid>().ok())
6212 .expect("response has UUID receipt_id");
6213
6214 let event = only_git_digest_event(&store);
6215 assert_eq!(event.id, receipt_id);
6216 assert_eq!(event.target_id, Some(project_id));
6217 assert_eq!(event.verb, "git.digest");
6218 assert_eq!(event.outcome, EventOutcome::Success);
6219 assert_eq!(event.payload_schema_version, 2);
6220 assert_eq!(event.payload["result"], result);
6221 assert_eq!(event.payload["resource"]["request_id"], 1_510);
6222 assert_eq!(event.payload["result"]["commits_ingested"], 2);
6223 assert_eq!(event.payload["result"]["issues_ingested"], 3);
6224 assert_eq!(event.payload["result"]["prs_ingested"], 5);
6225 assert!(
6226 !event.payload.to_string().contains("SECRET"),
6227 "receipt must not persist the caller's source URL or credentials"
6228 );
6229 }
6230
6231 #[tokio::test]
6232 async fn malformed_git_digest_report_appends_one_generic_error_audit() {
6233 let store = Arc::new(MemoryEventStore::default());
6234 let mut builder = VerbRegistryBuilder::new();
6235 builder.register(MalformedGitDigestResultPack);
6236 builder.with_event_store(store.clone());
6237 let registry = builder.build().expect("registry builds");
6238
6239 let err = registry
6240 .dispatch("git.digest", serde_json::json!({}))
6241 .await
6242 .expect_err("malformed receipt identity must fail the response");
6243 assert!(matches!(
6244 err,
6245 RuntimeError::Internal(ref message)
6246 if message.starts_with("git_digest_receipt_persist_failed:")
6247 ));
6248
6249 let event = only_git_digest_event(&store);
6250 assert_eq!(event.outcome, EventOutcome::Error);
6251 assert_eq!(event.payload_schema_version, 1);
6252 assert!(
6253 event.payload.get("result").is_none(),
6254 "a generic Error audit must not masquerade as a success receipt"
6255 );
6256 let audit: AuditEvent =
6257 serde_json::from_value(event.payload).expect("generic payload remains an AuditEvent");
6258 assert_eq!(audit.verb, "git.digest");
6259 assert_eq!(audit.decision, AuditDecision::Allow);
6260 }
6261
6262 #[tokio::test]
6263 #[serial(audit_append_failures)]
6264 #[serial(audit_obligation_append_failures)]
6265 async fn git_digest_receipt_append_failure_never_returns_unqualified_success() {
6266 let before = audit_append_failure_count();
6267 let before_obligation = audit_obligation_append_failure_count();
6268 let store = Arc::new(MemoryEventStore {
6269 fail_appends: true,
6270 ..MemoryEventStore::default()
6271 });
6272 let mut builder = VerbRegistryBuilder::new();
6273 builder.register(GitDigestResultPack {
6274 project_id: uuid::Uuid::new_v4(),
6275 });
6276 builder.with_event_store(store);
6277 let registry = builder.build().expect("registry builds");
6278
6279 let err = registry
6280 .dispatch("git.digest", serde_json::json!({}))
6281 .await
6282 .expect_err("receipt persistence failure must fail the response");
6283 assert!(
6284 matches!(&err, RuntimeError::Internal(message)
6285 if message.starts_with("git_digest_receipt_persist_failed:")
6286 && message.contains("writes may have committed")),
6287 "error is stable, safe, and retry-aware: {err}"
6288 );
6289 assert_eq!(audit_append_failure_count(), before);
6294 assert_eq!(
6295 audit_obligation_append_failure_count(),
6296 before_obligation + 1
6297 );
6298 }
6299
6300 #[tokio::test]
6301 async fn git_digest_without_event_store_fails_safe_after_handler_success() {
6302 let mut builder = VerbRegistryBuilder::new();
6303 builder.register(GitDigestResultPack {
6304 project_id: uuid::Uuid::new_v4(),
6305 });
6306 let registry = builder.build().expect("registry builds");
6307
6308 let err = registry
6309 .dispatch("git.digest", serde_json::json!({}))
6310 .await
6311 .expect_err("a successful digest needs a durable store");
6312 assert!(matches!(
6313 err,
6314 RuntimeError::Internal(ref message)
6315 if message.starts_with("git_digest_receipt_persist_failed:")
6316 ));
6317 }
6318
6319 #[tokio::test]
6320 async fn git_digest_gate_unavailable_precedes_the_receipt_contract() {
6321 #[derive(Debug)]
6322 struct FailingGate;
6323 impl Gate for FailingGate {
6324 fn check(&self, _req: &GateRequest) -> Result<GateDecision, khive_gate::GateError> {
6325 Err(khive_gate::GateError::Internal(
6326 "injected gate failure".into(),
6327 ))
6328 }
6329 }
6330
6331 let store = Arc::new(MemoryEventStore::default());
6332 let mut builder = VerbRegistryBuilder::new();
6333 builder.register(GitDigestResultPack {
6334 project_id: uuid::Uuid::new_v4(),
6335 });
6336 builder.with_gate(Arc::new(FailingGate));
6337 builder.with_event_store(store.clone());
6338 let registry = builder.build().expect("registry builds");
6339
6340 let err = registry
6341 .dispatch("git.digest", serde_json::json!({}))
6342 .await
6343 .expect_err("gate unavailability must refuse before the handler or receipt path");
6344 assert!(matches!(
6345 err,
6346 RuntimeError::GateUnavailable { ref verb, ref reason }
6347 if verb == "git.digest"
6348 && reason == "gate backend unavailable"
6349 && !reason.contains("injected gate failure")
6350 ));
6351 let event = only_git_digest_event(&store);
6352 assert_eq!(event.outcome, EventOutcome::Error);
6353 assert_eq!(event.payload["decision"], "gate_unavailable");
6354 assert!(event.payload.get("result").is_none());
6355 }
6356
6357 #[tokio::test]
6358 async fn intercepted_gate_error_returns_typed_refusal_without_invoking_operation() {
6359 #[derive(Debug)]
6360 struct FailingGate;
6361 impl Gate for FailingGate {
6362 fn check(&self, _req: &GateRequest) -> Result<GateDecision, khive_gate::GateError> {
6363 Err(khive_gate::GateError::Internal(
6364 "intercepted gate broken".into(),
6365 ))
6366 }
6367 }
6368
6369 let invoked = Arc::new(AtomicUsize::new(0));
6370 let invoked_by_operation = Arc::clone(&invoked);
6371 let store = Arc::new(MemoryEventStore::default());
6372 let mut builder = VerbRegistryBuilder::new();
6373 builder.with_gate(Arc::new(FailingGate));
6374 builder.with_event_store(store.clone());
6375 let registry = builder.build().expect("registry builds");
6376 let identity = RequestIdentity {
6377 namespace: "identity-default".to_string(),
6378 request_id: Some(1_600),
6379 ..Default::default()
6380 };
6381
6382 let err = registry
6383 .dispatch_intercepted_with_identity(
6384 "list",
6385 &serde_json::json!({"namespace": "test-ns"}),
6386 Some(&identity),
6387 move |_namespace| {
6388 invoked_by_operation.fetch_add(1, Ordering::SeqCst);
6389 async move { Ok(serde_json::json!({"invoked": true})) }
6390 },
6391 )
6392 .await
6393 .expect_err("gate unavailability must refuse intercepted dispatch");
6394
6395 assert!(matches!(
6396 err,
6397 RuntimeError::GateUnavailable { ref verb, ref reason }
6398 if verb == "list"
6399 && reason == "gate backend unavailable"
6400 && !reason.contains("intercepted gate broken")
6401 ));
6402 assert_eq!(
6403 invoked.load(Ordering::SeqCst),
6404 0,
6405 "intercepted operation must not run after a gate infrastructure error"
6406 );
6407
6408 let events = store.events.lock().unwrap();
6409 assert_eq!(events.len(), 1);
6410 assert_eq!(events[0].verb, "list");
6411 assert_eq!(events[0].namespace, "test-ns");
6412 assert_eq!(events[0].outcome, EventOutcome::Error);
6413 assert_eq!(events[0].payload["decision"], "gate_unavailable");
6414 assert!(events[0].payload.get("deny_reason").is_none());
6415 assert_eq!(events[0].payload["resource"]["work_class"], "interactive");
6416 assert_eq!(events[0].payload["resource"]["request_id"], 1_600);
6417 assert!(events[0].payload["resource"].get("cost_unit").is_none());
6418 }
6419
6420 #[tokio::test]
6421 async fn intercepted_deny_remains_distinct_and_does_not_invoke_operation() {
6422 #[derive(Debug)]
6423 struct DenyingGate;
6424 impl Gate for DenyingGate {
6425 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
6426 Ok(GateDecision::deny("intercepted policy denied"))
6427 }
6428 }
6429
6430 let invoked = Arc::new(AtomicUsize::new(0));
6431 let invoked_by_operation = Arc::clone(&invoked);
6432 let store = Arc::new(MemoryEventStore::default());
6433 let mut builder = VerbRegistryBuilder::new();
6434 builder.with_gate(Arc::new(DenyingGate));
6435 builder.with_event_store(store.clone());
6436 let registry = builder.build().expect("registry builds");
6437
6438 let err = registry
6439 .dispatch_intercepted_with_identity("list", &Value::Null, None, move |_namespace| {
6440 invoked_by_operation.fetch_add(1, Ordering::SeqCst);
6441 async move { Ok(serde_json::json!({"invoked": true})) }
6442 })
6443 .await
6444 .expect_err("explicit gate denial must refuse intercepted dispatch");
6445
6446 assert!(matches!(
6447 err,
6448 RuntimeError::PermissionDenied { ref verb, ref reason }
6449 if verb == "list" && reason == "intercepted policy denied"
6450 ));
6451 assert_eq!(invoked.load(Ordering::SeqCst), 0);
6452
6453 let events = store.events.lock().unwrap();
6454 assert_eq!(events.len(), 1);
6455 assert_eq!(events[0].outcome, EventOutcome::Denied);
6456 assert_eq!(events[0].payload["decision"], "deny");
6457 assert_eq!(
6458 events[0].payload["deny_reason"],
6459 "intercepted policy denied"
6460 );
6461 }
6462
6463 #[tokio::test]
6464 async fn intercepted_git_digest_uses_the_same_receipt_contract() {
6465 let project_id = uuid::Uuid::new_v4();
6466 let store = Arc::new(MemoryEventStore::default());
6467 let mut builder = VerbRegistryBuilder::new();
6468 builder.with_event_store(store.clone());
6469 let registry = builder.build().expect("registry builds");
6470
6471 let result = registry
6472 .dispatch_intercepted_with_identity(
6473 "git.digest",
6474 &serde_json::json!({}),
6475 Some(&RequestIdentity {
6476 namespace: Namespace::local().as_str().to_string(),
6477 request_id: Some(1_647),
6478 ..Default::default()
6479 }),
6480 |_namespace| async move {
6481 Ok(serde_json::json!({
6482 "project_id": project_id,
6483 "commits_ingested": 7,
6484 "done": true,
6485 }))
6486 },
6487 )
6488 .await
6489 .expect("intercepted digest is durably receipted");
6490
6491 let event = only_git_digest_event(&store);
6492 assert_eq!(result["receipt_id"], serde_json::json!(event.id));
6493 assert_eq!(event.payload["result"], result);
6494 assert_eq!(event.payload["resource"]["request_id"], 1_647);
6495 }
6496
6497 #[tokio::test]
6498 async fn intercepted_git_digest_receipt_preserves_typed_metadata() {
6499 let project_id = uuid::Uuid::new_v4();
6500 let store = Arc::new(MemoryEventStore::default());
6501 let mut builder = VerbRegistryBuilder::new();
6502 builder.with_event_store(store.clone());
6503 let registry = builder.build().expect("registry builds");
6504
6505 let outcome = registry
6506 .dispatch_intercepted_with_metadata_with_identity(
6507 "git.digest",
6508 &serde_json::json!({}),
6509 None,
6510 |_namespace| async move {
6511 Ok(InterceptedDispatchResult::new(
6512 serde_json::json!({
6513 "project_id": project_id,
6514 "commits_ingested": 3,
6515 "done": true,
6516 }),
6517 vec!["backend-a".to_string(), "backend-b".to_string()],
6518 ))
6519 },
6520 )
6521 .await
6522 .expect("metadata-bearing digest is durably receipted");
6523
6524 let event = only_git_digest_event(&store);
6525 assert_eq!(outcome.result["receipt_id"], serde_json::json!(event.id));
6526 assert_eq!(event.payload["result"], outcome.result);
6527 assert_eq!(outcome.metadata, ["backend-a", "backend-b"]);
6528 }
6529
6530 #[tokio::test]
6531 async fn intercepted_malformed_git_digest_appends_one_generic_error_audit() {
6532 let store = Arc::new(MemoryEventStore::default());
6533 let mut builder = VerbRegistryBuilder::new();
6534 builder.with_event_store(store.clone());
6535 let registry = builder.build().expect("registry builds");
6536
6537 let err = registry
6538 .dispatch_intercepted_with_identity(
6539 "git.digest",
6540 &serde_json::json!({}),
6541 None,
6542 |_namespace| async {
6543 Ok(serde_json::json!({
6544 "project_id": "not-a-uuid",
6545 "done": true,
6546 }))
6547 },
6548 )
6549 .await
6550 .expect_err("malformed intercepted receipt must fail the response");
6551 assert!(matches!(
6552 err,
6553 RuntimeError::Internal(ref message)
6554 if message.starts_with("git_digest_receipt_persist_failed:")
6555 ));
6556
6557 let event = only_git_digest_event(&store);
6558 assert_eq!(event.outcome, EventOutcome::Error);
6559 assert_eq!(event.payload_schema_version, 1);
6560 assert!(event.payload.get("result").is_none());
6561 let audit: AuditEvent =
6562 serde_json::from_value(event.payload).expect("generic payload remains an AuditEvent");
6563 assert_eq!(audit.verb, "git.digest");
6564 assert_eq!(audit.decision, AuditDecision::Allow);
6565 }
6566
6567 #[tokio::test]
6568 async fn allow_all_gate_default_remains_backward_compatible() {
6569 let mut builder = VerbRegistryBuilder::new();
6571 builder.register(AlphaPack);
6572 let reg = builder.build().expect("registry builds");
6573
6574 let res = reg.dispatch("list", Value::Null).await.unwrap();
6575 assert_eq!(
6576 res["pack"], "alpha",
6577 "AllowAllGate must allow every verb — backward compat guarantee"
6578 );
6579 let res = reg.dispatch("create", Value::Null).await.unwrap();
6580 assert_eq!(res["pack"], "alpha");
6581 }
6582
6583 #[tokio::test]
6584 async fn deny_gate_returns_permission_denied_pack_never_invoked() {
6585 #[derive(Debug)]
6586 struct AlwaysDenyGate;
6587 impl Gate for AlwaysDenyGate {
6588 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
6589 Ok(GateDecision::deny("test: always deny"))
6590 }
6591 }
6592
6593 #[derive(Debug)]
6595 struct TrackedPack {
6596 invoked: Arc<AtomicUsize>,
6597 }
6598
6599 impl khive_types::Pack for TrackedPack {
6600 const NAME: &'static str = "tracked";
6601 const NOTE_KINDS: &'static [&'static str] = &[];
6602 const ENTITY_KINDS: &'static [&'static str] = &[];
6603 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
6604 name: "guarded",
6605 description: "a guarded verb",
6606 visibility: Visibility::Verb,
6607 category: VerbCategory::Assertive,
6608 params: &[],
6609 }];
6610 }
6611
6612 #[async_trait]
6613 impl PackRuntime for TrackedPack {
6614 fn name(&self) -> &str {
6615 Self::NAME
6616 }
6617 fn note_kinds(&self) -> &'static [&'static str] {
6618 Self::NOTE_KINDS
6619 }
6620 fn entity_kinds(&self) -> &'static [&'static str] {
6621 Self::ENTITY_KINDS
6622 }
6623 fn handlers(&self) -> &'static [HandlerDef] {
6624 Self::HANDLERS
6625 }
6626 async fn dispatch(
6627 &self,
6628 _verb: &str,
6629 _params: Value,
6630 _registry: &VerbRegistry,
6631 _token: &NamespaceToken,
6632 ) -> Result<Value, RuntimeError> {
6633 self.invoked.fetch_add(1, Ordering::SeqCst);
6634 Ok(serde_json::json!({"invoked": true}))
6635 }
6636 }
6637
6638 let invoked = Arc::new(AtomicUsize::new(0));
6639 let mut builder = VerbRegistryBuilder::new();
6640 builder.register(TrackedPack {
6641 invoked: invoked.clone(),
6642 });
6643 builder.with_gate(Arc::new(AlwaysDenyGate));
6644 let reg = builder.build().expect("registry builds");
6645
6646 let err = reg.dispatch("guarded", Value::Null).await.unwrap_err();
6647 assert!(
6648 matches!(err, RuntimeError::PermissionDenied { ref verb, ref reason } if verb == "guarded" && reason.contains("always deny")),
6649 "expected PermissionDenied with verb=guarded and reason, got: {err:?}"
6650 );
6651 assert_eq!(
6652 invoked.load(Ordering::SeqCst),
6653 0,
6654 "pack dispatch MUST NOT be invoked when gate denies"
6655 );
6656 }
6657
6658 #[tokio::test]
6659 async fn update_denial_precedes_id_existence_resolution() {
6660 #[derive(Debug)]
6661 struct AlwaysDenyUpdateGate {
6662 checked: Arc<AtomicUsize>,
6663 }
6664 impl Gate for AlwaysDenyUpdateGate {
6665 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
6666 self.checked.fetch_add(1, Ordering::SeqCst);
6667 Ok(GateDecision::deny("caller has no update capability"))
6668 }
6669 }
6670
6671 #[derive(Debug)]
6672 struct ExistenceOracleUpdatePack {
6673 existing_id: String,
6674 invoked: Arc<AtomicUsize>,
6675 }
6676
6677 impl khive_types::Pack for ExistenceOracleUpdatePack {
6678 const NAME: &'static str = "existence_oracle";
6679 const NOTE_KINDS: &'static [&'static str] = &[];
6680 const ENTITY_KINDS: &'static [&'static str] = &[];
6681 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
6682 name: "update",
6683 description: "distinguish a present id from an absent id",
6684 visibility: Visibility::Verb,
6685 category: VerbCategory::Declaration,
6686 params: &[],
6687 }];
6688 }
6689
6690 #[async_trait]
6691 impl PackRuntime for ExistenceOracleUpdatePack {
6692 fn name(&self) -> &str {
6693 Self::NAME
6694 }
6695 fn note_kinds(&self) -> &'static [&'static str] {
6696 Self::NOTE_KINDS
6697 }
6698 fn entity_kinds(&self) -> &'static [&'static str] {
6699 Self::ENTITY_KINDS
6700 }
6701 fn handlers(&self) -> &'static [HandlerDef] {
6702 Self::HANDLERS
6703 }
6704 async fn dispatch(
6705 &self,
6706 _verb: &str,
6707 params: Value,
6708 _registry: &VerbRegistry,
6709 _token: &NamespaceToken,
6710 ) -> Result<Value, RuntimeError> {
6711 self.invoked.fetch_add(1, Ordering::SeqCst);
6712 match params.get("id").and_then(Value::as_str) {
6713 Some(id) if id == self.existing_id => Ok(serde_json::json!({"updated": id})),
6714 _ => Err(RuntimeError::NotFound("record".to_string())),
6715 }
6716 }
6717 }
6718
6719 let existing_id = uuid::Uuid::new_v4().to_string();
6720 let absent_id = uuid::Uuid::new_v4().to_string();
6721 let invoked = Arc::new(AtomicUsize::new(0));
6722 let checked = Arc::new(AtomicUsize::new(0));
6723
6724 let pack = || ExistenceOracleUpdatePack {
6725 existing_id: existing_id.clone(),
6726 invoked: Arc::clone(&invoked),
6727 };
6728
6729 let mut control_builder = VerbRegistryBuilder::new();
6730 control_builder.register(pack());
6731 let control = control_builder.build().expect("control registry builds");
6732 control
6733 .dispatch("update", serde_json::json!({"id": existing_id.clone()}))
6734 .await
6735 .expect("positive control resolves the present id");
6736 assert!(matches!(
6737 control
6738 .dispatch("update", serde_json::json!({"id": absent_id.clone()}))
6739 .await,
6740 Err(RuntimeError::NotFound(_))
6741 ));
6742 assert_eq!(invoked.load(Ordering::SeqCst), 2);
6743
6744 let mut denied_builder = VerbRegistryBuilder::new();
6745 denied_builder.register(pack());
6746 denied_builder.with_gate(Arc::new(AlwaysDenyUpdateGate {
6747 checked: Arc::clone(&checked),
6748 }));
6749 let denied = denied_builder.build().expect("denied registry builds");
6750
6751 let present_error = denied
6752 .dispatch("update", serde_json::json!({"id": existing_id.clone()}))
6753 .await
6754 .expect_err("denied present-id update must not resolve the id");
6755 let absent_error = denied
6756 .dispatch("update", serde_json::json!({"id": absent_id.clone()}))
6757 .await
6758 .expect_err("denied absent-id update must not resolve the id");
6759
6760 let denial = |error: RuntimeError| match error {
6761 RuntimeError::PermissionDenied { verb, reason } => (verb, reason),
6762 other => panic!("expected gate refusal, got {other:?}"),
6763 };
6764 let present_denial = denial(present_error);
6765 let absent_denial = denial(absent_error);
6766 assert_eq!(present_denial.0, "update");
6767 assert_eq!(present_denial.1, "caller has no update capability");
6768 assert_eq!(present_denial, absent_denial);
6769 assert_eq!(
6770 checked.load(Ordering::SeqCst),
6771 2,
6772 "both denied requests must consult the configured gate"
6773 );
6774 assert_eq!(
6775 invoked.load(Ordering::SeqCst),
6776 2,
6777 "neither denied request may reach the existence oracle"
6778 );
6779 }
6780
6781 #[tokio::test]
6782 async fn audit_event_persists_to_event_store_on_allow() {
6783 let store = Arc::new(MemoryEventStore::default());
6784 let mut builder = VerbRegistryBuilder::new();
6785 builder.register(AlphaPack);
6786 builder.with_event_store(store.clone());
6787 let reg = builder.build().expect("registry builds");
6788
6789 reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
6790 .await
6791 .unwrap();
6792
6793 let count = store.count_events(EventFilter::default()).await.unwrap();
6794 assert_eq!(count, 1, "one audit event persisted to EventStore on allow");
6795
6796 let page = store
6797 .query_events(
6798 EventFilter::default(),
6799 PageRequest {
6800 limit: 10,
6801 offset: 0,
6802 },
6803 )
6804 .await
6805 .unwrap();
6806 let ev = &page.items[0];
6807 assert_eq!(ev.verb, "list");
6808 assert_eq!(ev.namespace, "test-ns");
6809 assert_eq!(ev.substrate, SubstrateKind::Event);
6810 assert_eq!(ev.outcome, EventOutcome::Success);
6811 }
6812
6813 #[tokio::test]
6814 #[serial(audit_append_failures)]
6815 #[serial(audit_obligation_append_failures)]
6816 async fn audit_append_failure_fails_an_obligation_bearing_dispatch() {
6817 let before = audit_append_failure_count();
6818 let before_obligation = audit_obligation_append_failure_count();
6819
6820 let successful_store = Arc::new(MemoryEventStore::default());
6821 let mut successful_builder = VerbRegistryBuilder::new();
6822 successful_builder.register(AlphaPack);
6823 successful_builder.with_event_store(successful_store);
6824 let successful_registry = successful_builder.build().expect("registry builds");
6825 successful_registry
6826 .dispatch("list", Value::Null)
6827 .await
6828 .expect("successful audit append must not affect dispatch");
6829 assert_eq!(
6830 audit_append_failure_count(),
6831 before,
6832 "successful audit appends must not increment the swallowed-failure counter"
6833 );
6834 assert_eq!(
6835 audit_obligation_append_failure_count(),
6836 before_obligation,
6837 "successful audit appends must not increment the obligation-failure counter"
6838 );
6839
6840 let failing_store = Arc::new(MemoryEventStore {
6846 fail_appends: true,
6847 ..MemoryEventStore::default()
6848 });
6849 let mut failing_builder = VerbRegistryBuilder::new();
6850 failing_builder.register(AlphaPack);
6851 failing_builder.with_event_store(failing_store);
6852 let failing_registry = failing_builder.build().expect("registry builds");
6853 let err = failing_registry
6854 .dispatch("list", Value::Null)
6855 .await
6856 .expect_err(
6857 "a persistent obligation-bearing audit commit failure must fail the dispatch",
6858 );
6859 assert!(
6860 matches!(&err, RuntimeError::Internal(message)
6861 if message.contains("audit obligation commit failed")),
6862 "error names the obligation failure so it is distinguishable from a handler error: {err}"
6863 );
6864
6865 assert_eq!(
6869 audit_append_failure_count(),
6870 before,
6871 "an obligation failure must never inflate the swallowed-failure counter"
6872 );
6873 assert_eq!(
6874 audit_obligation_append_failure_count(),
6875 before_obligation + 1,
6876 "the failed obligation append must remain visible to diagnostics"
6877 );
6878 }
6879
6880 #[tokio::test]
6910 #[serial(audit_append_failures)]
6911 #[serial(audit_obligation_append_failures)]
6912 #[serial(config_ledger)]
6918 async fn obligation_failure_reports_a_write_that_already_committed() {
6919 const RETURNED_TOTAL: u64 = 41;
6925
6926 #[derive(Debug)]
6927 struct RecordingWritePack {
6928 committed: Arc<std::sync::Mutex<Vec<TraceEntry>>>,
6929 }
6930
6931 impl Pack for RecordingWritePack {
6932 const NAME: &'static str = "recording_write";
6933 const NOTE_KINDS: &'static [&'static str] = &[];
6934 const ENTITY_KINDS: &'static [&'static str] = &[];
6935 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
6943 name: "knowledge.index",
6944 description: "record one committed write",
6945 visibility: Visibility::Verb,
6946 category: VerbCategory::Commissive,
6947 params: &[],
6948 }];
6949 }
6950
6951 #[async_trait]
6952 impl PackRuntime for RecordingWritePack {
6953 fn name(&self) -> &str {
6954 Self::NAME
6955 }
6956 fn note_kinds(&self) -> &'static [&'static str] {
6957 Self::NOTE_KINDS
6958 }
6959 fn entity_kinds(&self) -> &'static [&'static str] {
6960 Self::ENTITY_KINDS
6961 }
6962 fn handlers(&self) -> &'static [HandlerDef] {
6963 Self::HANDLERS
6964 }
6965 async fn dispatch(
6966 &self,
6967 _verb: &str,
6968 params: Value,
6969 _registry: &VerbRegistry,
6970 _token: &NamespaceToken,
6971 ) -> Result<Value, RuntimeError> {
6972 let name = params
6977 .get("name")
6978 .and_then(Value::as_str)
6979 .unwrap_or("unnamed")
6980 .to_string();
6981 self.committed
6982 .lock()
6983 .expect("committed lock")
6984 .push(TraceEntry::Effect { name: name.clone() });
6985 Ok(serde_json::json!({ "created": name, "total": RETURNED_TOTAL }))
6986 }
6987 }
6988
6989 let committed = Arc::new(std::sync::Mutex::new(Vec::new()));
6990 let failing_store = Arc::new(MemoryEventStore {
6991 fail_appends: true,
6992 trace: Some(Arc::clone(&committed)),
6993 ..MemoryEventStore::default()
6994 });
6995 let mut builder = VerbRegistryBuilder::new();
6996 builder.register(RecordingWritePack {
6997 committed: Arc::clone(&committed),
6998 });
6999 builder.with_event_store(failing_store);
7000 let registry = builder.build().expect("registry builds");
7001
7002 let err = registry
7003 .dispatch("knowledge.index", serde_json::json!({"name": "first"}))
7004 .await
7005 .expect_err("an obligation commit failure must fail the dispatch");
7006 assert!(
7007 matches!(&err, RuntimeError::Internal(message)
7008 if message.contains("audit obligation commit failed")),
7009 "the error must name the obligation failure, since that string is what tells a \
7010 caller the effect landed: {err}"
7011 );
7012
7013 let first_pass = committed.lock().expect("committed lock").clone();
7019 let first_effect = TraceEntry::Effect {
7020 name: "first".to_string(),
7021 };
7022 assert_eq!(
7023 first_pass.first(),
7024 Some(&first_effect),
7025 "the handler's effect must land FIRST: an implementation that submitted the \
7026 audit row before dispatching would satisfy every other assertion here"
7027 );
7028 let audit_rows: Vec<&TraceEntry> = first_pass
7029 .iter()
7030 .filter(|entry| matches!(entry, TraceEntry::Audit { .. }))
7031 .collect();
7032 assert!(
7033 !audit_rows.is_empty(),
7034 "an audit row must actually be SUBMITTED; without this assertion the test \
7035 passes against an implementation that returns the same error and never \
7036 builds a row at all, which is a different defect wearing the same error \
7037 string. Trace was {first_pass:?}"
7038 );
7039 let expected_cost_unit = serde_json::json!(RETURNED_TOTAL + 1);
7040 assert!(
7041 audit_rows.iter().any(|entry| matches!(
7042 entry,
7043 TraceEntry::Audit {
7044 outcome: EventOutcome::Success,
7045 verb,
7046 cost_unit: Some(cost_unit),
7047 ..
7048 } if verb.as_str() == "knowledge.index" && *cost_unit == expected_cost_unit
7049 )),
7050 "the submitted row must be the SUCCESS row for THIS verb, carrying a resource \
7051 computed FROM the handler's return value. The outcome alone is not enough: an \
7052 implementation that stamps Success on a row built without `ok_val` would \
7053 satisfy an outcome-only assertion while breaking the contract this test \
7054 exists for. The exact value is the discriminator, not the key's presence: \
7055 `resource_payload` inserts `cost_unit` unconditionally, so presence survives a \
7056 static `ok_val`, while {expected_cost_unit} is reachable only from the \
7057 returned `total` of {RETURNED_TOTAL} (`base_weight` 1 + `item_count` \
7058 {RETURNED_TOTAL} * `model_count` 1). Substituting a null or static result \
7059 collapses it to 1, and the error path's `base_resource_payload` omits the key \
7060 entirely (`cost_unit: None` here), so all three implementations are \
7061 distinguishable. Trace was {first_pass:?}"
7062 );
7063 assert_eq!(
7064 first_pass
7065 .iter()
7066 .filter(|entry| **entry == first_effect)
7067 .count(),
7068 1,
7069 "exactly one effect on the first pass"
7070 );
7071
7072 let _ = registry
7074 .dispatch("knowledge.index", serde_json::json!({"name": "first"}))
7075 .await
7076 .expect_err("the retry fails the same way");
7077 assert_eq!(
7078 committed
7079 .lock()
7080 .expect("committed lock")
7081 .iter()
7082 .filter(|entry| **entry == first_effect)
7083 .count(),
7084 2,
7085 "retrying this error double-writes; a caller must re-derive state instead of \
7086 resubmitting"
7087 );
7088 }
7089
7090 #[tokio::test]
7091 #[serial(config_ledger)]
7092 #[serial(audit_append_failures)]
7093 #[serial(audit_obligation_append_failures)]
7094 async fn config_locked_row_degrades_without_failing_the_dispatch_that_observed_it() {
7095 #[derive(Debug)]
7105 struct DenyGate;
7106 impl Gate for DenyGate {
7107 fn check(&self, _req: &GateRequest) -> Result<GateDecision, khive_gate::GateError> {
7108 Ok(GateDecision::Deny {
7109 reason: "denied for test".to_string(),
7110 })
7111 }
7112 }
7113
7114 crate::config_ledger::record_config_locked("adr133_test_key", "adr133_test_value");
7115
7116 let store = Arc::new(MemoryEventStore {
7117 fail_appends: true,
7118 ..MemoryEventStore::default()
7119 });
7120 let mut builder = VerbRegistryBuilder::new();
7121 builder.register(AlphaPack);
7122 builder.with_gate(Arc::new(DenyGate));
7123 builder.with_event_store(store);
7124 let registry = builder.build().expect("registry builds");
7125
7126 let err = registry
7127 .dispatch("list", Value::Null)
7128 .await
7129 .expect_err("the gate denies every request");
7130 assert!(
7131 matches!(err, RuntimeError::PermissionDenied { .. }),
7132 "a pure-observability row's failure must never surface as the dispatch error: {err}"
7133 );
7134
7135 let metrics = registry
7136 .audit_batch_metrics()
7137 .expect("with_event_store configures the ADR-133 seam");
7138 assert!(
7139 metrics.degraded,
7140 "the config-locked row's commit failure must be visible as degradation"
7141 );
7142 assert!(metrics.degraded_rows >= 1);
7143 }
7144
7145 #[tokio::test]
7146 #[serial(config_ledger)]
7147 #[serial(audit_append_failures)]
7148 async fn config_locked_row_failure_never_fails_a_dispatch_that_would_otherwise_succeed() {
7149 crate::config_ledger::record_config_locked(
7156 "adr133_success_path_key",
7157 "adr133_success_path_value",
7158 );
7159
7160 let store = Arc::new(MemoryEventStore {
7161 fail_kind: Some(EventKind::ConfigLocked),
7162 ..MemoryEventStore::default()
7163 });
7164 let mut builder = VerbRegistryBuilder::new();
7165 builder.register(AlphaPack);
7166 builder.with_event_store(store);
7167 let registry = builder.build().expect("registry builds");
7168
7169 let result = registry
7170 .dispatch("list", Value::Null)
7171 .await
7172 .expect("a config-locked row's commit failure must never fail an unrelated dispatch");
7173 assert_eq!(
7174 result,
7175 serde_json::json!({ "pack": "alpha", "verb": "list" })
7176 );
7177
7178 let metrics = registry
7179 .audit_batch_metrics()
7180 .expect("with_event_store configures the ADR-133 seam");
7181 assert!(
7182 metrics.degraded_rows >= 1,
7183 "the config-locked row's failure must remain visible as degradation"
7184 );
7185 }
7186
7187 #[derive(Default)]
7192 struct LegacyEventStore {
7193 events: std::sync::Mutex<Vec<Event>>,
7194 }
7195
7196 #[async_trait]
7197 impl EventStore for LegacyEventStore {
7198 async fn append_event(&self, event: Event) -> khive_storage::StorageResult<()> {
7199 self.events.lock().unwrap().push(event);
7200 Ok(())
7201 }
7202 async fn append_events(
7203 &self,
7204 events: Vec<Event>,
7205 ) -> khive_storage::StorageResult<BatchWriteSummary> {
7206 let attempted = events.len() as u64;
7207 self.events.lock().unwrap().extend(events);
7208 Ok(BatchWriteSummary {
7209 attempted,
7210 affected: attempted,
7211 failed: 0,
7212 first_error: String::new(),
7213 })
7214 }
7215 async fn get_event(&self, id: uuid::Uuid) -> khive_storage::StorageResult<Option<Event>> {
7216 Ok(self
7217 .events
7218 .lock()
7219 .unwrap()
7220 .iter()
7221 .find(|e| e.id == id)
7222 .cloned())
7223 }
7224 async fn query_events(
7225 &self,
7226 _filter: EventFilter,
7227 _page: PageRequest,
7228 ) -> khive_storage::StorageResult<Page<Event>> {
7229 let items = self.events.lock().unwrap().clone();
7230 let total = items.len() as u64;
7231 Ok(Page {
7232 items,
7233 total: Some(total),
7234 })
7235 }
7236 async fn count_events(&self, _filter: EventFilter) -> khive_storage::StorageResult<u64> {
7237 Ok(self.events.lock().unwrap().len() as u64)
7238 }
7239 }
7240
7241 #[test]
7242 fn build_rejects_a_configured_event_store_incompatible_with_the_audit_batch_seam() {
7243 let mut builder = VerbRegistryBuilder::new();
7244 builder.register(AlphaPack);
7245 builder.with_event_store(Arc::new(LegacyEventStore::default()));
7246 let err = match builder.build() {
7247 Ok(_) => {
7248 panic!("a store that cannot implement the seam must not build a healthy registry")
7249 }
7250 Err(err) => err,
7251 };
7252 assert!(
7253 matches!(&err, RuntimeError::IncompatibleEventStore(message)
7254 if message.contains("supports_idempotent_audit_batch")),
7255 "error names the missing capability so an operator can act on it: {err}"
7256 );
7257 }
7258
7259 #[tokio::test]
7260 #[serial(config_ledger)]
7261 #[serial(audit_append_failures)]
7262 #[serial(audit_obligation_append_failures)]
7263 async fn db_diagnostics_with_audit_metrics_reports_batch_failure_and_degradation() {
7264 crate::config_ledger::record_config_locked(
7271 "adr133_diag_test_key",
7272 "adr133_diag_test_value",
7273 );
7274 let store = Arc::new(MemoryEventStore {
7275 fail_appends: true,
7276 ..MemoryEventStore::default()
7277 });
7278 let mut builder = VerbRegistryBuilder::new();
7279 builder.register(AlphaPack);
7280 builder.with_event_store(store);
7281 let registry = builder.build().expect("registry builds");
7282 let _ = registry.dispatch("list", Value::Null).await;
7283
7284 let metrics = registry
7285 .audit_batch_metrics()
7286 .expect("with_event_store configures the ADR-133 seam");
7287 assert!(metrics.degraded, "the config-locked row must have degraded");
7288 assert!(metrics.degraded_rows >= 1);
7289 assert!(
7290 metrics.flush_failures >= 1,
7291 "the list dispatch's obligation row must count as a flush failure"
7292 );
7293
7294 let rt = KhiveRuntime::memory().expect("memory runtime should create");
7295 let report = rt
7296 .db_diagnostics_with_audit_metrics(Some(metrics))
7297 .await
7298 .expect("diagnostics succeed");
7299 assert_eq!(report.writer_contention.audit_degraded, Some(true));
7300 assert!(report.writer_contention.audit_degraded_rows.unwrap_or(0) >= 1);
7301 assert!(
7302 report
7303 .writer_contention
7304 .audit_batch_flush_failures
7305 .unwrap_or(0)
7306 >= 1
7307 );
7308 assert!(report
7309 .writer_contention
7310 .audit_batch_flush_failures_unavailable_reason
7311 .is_none());
7312 assert!(report
7313 .writer_contention
7314 .audit_degraded_unavailable_reason
7315 .is_none());
7316
7317 let bare_report = rt.db_diagnostics().await.expect("diagnostics succeed");
7323 assert!(bare_report.writer_contention.audit_degraded.is_none());
7324 assert!(bare_report
7325 .writer_contention
7326 .audit_degraded_unavailable_reason
7327 .is_some());
7328 assert!(bare_report
7329 .writer_contention
7330 .audit_admission_refused_obligations
7331 .is_none());
7332 assert!(bare_report
7333 .writer_contention
7334 .audit_admission_refused_obligations_unavailable_reason
7335 .is_some());
7336 assert!(bare_report
7337 .writer_contention
7338 .audit_admission_unresolved_obligations
7339 .is_none());
7340 assert!(bare_report
7341 .writer_contention
7342 .audit_admission_unresolved_obligations_unavailable_reason
7343 .is_some());
7344 }
7345
7346 #[tokio::test]
7347 async fn audit_event_duration_us_reflects_measured_dispatch_time() {
7348 let store = Arc::new(MemoryEventStore::default());
7354 let mut builder = VerbRegistryBuilder::new();
7355 builder.register(SleepingPack);
7356 builder.with_event_store(store.clone());
7357 let reg = builder.build().expect("registry builds");
7358
7359 reg.dispatch("slow_op", serde_json::json!({}))
7360 .await
7361 .unwrap();
7362
7363 let page = store
7364 .query_events(
7365 EventFilter::default(),
7366 PageRequest {
7367 limit: 10,
7368 offset: 0,
7369 },
7370 )
7371 .await
7372 .unwrap();
7373 assert_eq!(page.items.len(), 1);
7374 let ev = &page.items[0];
7375 assert!(
7376 ev.duration_us >= 10_000,
7377 "duration_us must reflect the ~20ms measured dispatch time, got {}",
7378 ev.duration_us
7379 );
7380 }
7381
7382 #[tokio::test]
7383 async fn dispatch_unknown_verb_allowed_by_gate_still_persists_audit_row() {
7384 let store = Arc::new(MemoryEventStore::default());
7389 let mut builder = VerbRegistryBuilder::new();
7390 builder.register(AlphaPack);
7391 builder.with_event_store(store.clone());
7392 let reg = builder.build().expect("registry builds");
7393
7394 let result = reg.dispatch("no_such_verb", serde_json::json!({})).await;
7395 assert!(result.is_err(), "unknown verb must still return an error");
7396
7397 let count = store.count_events(EventFilter::default()).await.unwrap();
7398 assert_eq!(
7399 count, 1,
7400 "an allowed-but-unknown verb must still persist one audit row"
7401 );
7402 let page = store
7403 .query_events(
7404 EventFilter::default(),
7405 PageRequest {
7406 limit: 10,
7407 offset: 0,
7408 },
7409 )
7410 .await
7411 .unwrap();
7412 assert_eq!(page.items[0].duration_us, 0);
7413 assert_eq!(page.items[0].outcome, EventOutcome::Error);
7417 }
7418
7419 #[tokio::test]
7420 async fn audit_event_persists_to_event_store_on_deny() {
7421 #[derive(Debug)]
7422 struct AlwaysDenyGate;
7423 impl Gate for AlwaysDenyGate {
7424 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7425 Ok(GateDecision::deny("denied by test"))
7426 }
7427 }
7428
7429 let store = Arc::new(MemoryEventStore::default());
7430 let mut builder = VerbRegistryBuilder::new();
7431 builder.register(AlphaPack);
7432 builder.with_gate(Arc::new(AlwaysDenyGate));
7433 builder.with_event_store(store.clone());
7434 let reg = builder.build().expect("registry builds");
7435
7436 let err = reg
7438 .dispatch("list", serde_json::json!({"namespace": "test-ns"}))
7439 .await
7440 .unwrap_err();
7441 assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
7442
7443 let count = store.count_events(EventFilter::default()).await.unwrap();
7444 assert_eq!(count, 1, "one audit event persisted to EventStore on deny");
7445
7446 let page = store
7447 .query_events(
7448 EventFilter::default(),
7449 PageRequest {
7450 limit: 10,
7451 offset: 0,
7452 },
7453 )
7454 .await
7455 .unwrap();
7456 let ev = &page.items[0];
7457 assert_eq!(ev.verb, "list");
7458 assert_eq!(ev.outcome, EventOutcome::Denied);
7459 }
7460
7461 #[tokio::test]
7462 async fn gate_error_returns_typed_refusal_without_invoking_pack() {
7463 #[derive(Debug)]
7464 struct FailingGate;
7465 impl Gate for FailingGate {
7466 fn check(&self, _req: &GateRequest) -> Result<GateDecision, khive_gate::GateError> {
7467 Err(khive_gate::GateError::Internal("gate broken".into()))
7468 }
7469 }
7470
7471 let store = Arc::new(MemoryEventStore::default());
7472 let invoked = Arc::new(AtomicUsize::new(0));
7473 let mut builder = VerbRegistryBuilder::new();
7474 builder.register(GateErrorTrackingPack {
7475 invoked: Arc::clone(&invoked),
7476 });
7477 builder.with_gate(Arc::new(FailingGate));
7478 builder.with_event_store(store.clone());
7479 let reg = builder.build().expect("registry builds");
7480
7481 let err = reg
7482 .dispatch("guarded", Value::Null)
7483 .await
7484 .expect_err("gate unavailability must refuse normal dispatch");
7485 assert!(matches!(
7486 err,
7487 RuntimeError::GateUnavailable { ref verb, ref reason }
7488 if verb == "guarded"
7489 && reason == "gate backend unavailable"
7490 && !reason.contains("gate broken")
7491 ));
7492 assert_eq!(
7493 invoked.load(Ordering::SeqCst),
7494 0,
7495 "pack handler must not run after a gate infrastructure error"
7496 );
7497
7498 let count = store.count_events(EventFilter::default()).await.unwrap();
7499 assert_eq!(count, 1, "gate infrastructure error must be audited");
7500 let page = store
7501 .query_events(
7502 EventFilter::default(),
7503 PageRequest {
7504 limit: 10,
7505 offset: 0,
7506 },
7507 )
7508 .await
7509 .unwrap();
7510 let event = &page.items[0];
7511 assert_eq!(event.verb, "guarded");
7512 assert_eq!(event.outcome, EventOutcome::Error);
7513 assert_eq!(event.payload["decision"], "gate_unavailable");
7514 assert!(event.payload.get("deny_reason").is_none());
7515 assert_eq!(event.payload["resource"]["work_class"], "interactive");
7516 assert!(event.payload["resource"].get("cost_unit").is_none());
7517 }
7518
7519 #[tokio::test]
7520 #[serial(audit_append_failures)]
7521 async fn gate_error_audit_failure_cannot_reopen_dispatch_or_replace_typed_error() {
7522 #[derive(Debug)]
7523 struct FailingGate;
7524 impl Gate for FailingGate {
7525 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7526 Err(GateError::Internal("gate still broken".into()))
7527 }
7528 }
7529
7530 let before = audit_append_failure_count();
7531 let invoked = Arc::new(AtomicUsize::new(0));
7532 let store = Arc::new(MemoryEventStore {
7533 fail_appends: true,
7534 ..MemoryEventStore::default()
7535 });
7536 let mut builder = VerbRegistryBuilder::new();
7537 builder.register(GateErrorTrackingPack {
7538 invoked: Arc::clone(&invoked),
7539 });
7540 builder.with_gate(Arc::new(FailingGate));
7541 builder.with_event_store(store);
7542 let registry = builder.build().expect("registry builds");
7543
7544 let error = registry
7545 .dispatch("guarded", Value::Null)
7546 .await
7547 .expect_err("audit persistence failure must not reopen dispatch");
7548
7549 assert!(matches!(
7550 error,
7551 RuntimeError::GateUnavailable { ref verb, ref reason }
7552 if verb == "guarded"
7553 && reason == "gate backend unavailable"
7554 && !reason.contains("gate still broken")
7555 ));
7556 assert_eq!(invoked.load(Ordering::SeqCst), 0);
7557 assert_eq!(
7558 audit_append_failure_count(),
7559 before + 1,
7560 "best-effort audit failure remains diagnostic without changing the refusal"
7561 );
7562 }
7563
7564 #[tokio::test]
7572 async fn gate_unavailable_reason_never_carries_backend_error_text() {
7573 const CANARY: &str = "postgres://svc:not-a-real-secret@internal-host";
7574
7575 #[derive(Debug)]
7576 struct FailingGate;
7577 impl Gate for FailingGate {
7578 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7579 Err(GateError::Internal(CANARY.to_string()))
7580 }
7581 }
7582
7583 let mut builder = VerbRegistryBuilder::new();
7584 builder.register(GateErrorTrackingPack {
7585 invoked: Arc::new(AtomicUsize::new(0)),
7586 });
7587 builder.with_gate(Arc::new(FailingGate));
7588 let registry = builder.build().expect("registry builds");
7589
7590 let err = registry
7591 .dispatch("guarded", Value::Null)
7592 .await
7593 .expect_err("gate unavailability must refuse dispatch");
7594
7595 let RuntimeError::GateUnavailable { reason, .. } = &err else {
7596 panic!("expected GateUnavailable, got {err:?}");
7597 };
7598 assert!(
7599 !reason.contains(CANARY),
7600 "caller-visible reason must not embed backend error text: {reason:?}"
7601 );
7602 assert!(
7603 !reason.contains("svc") && !reason.contains("internal-host"),
7604 "caller-visible reason must not embed backend error fragments: {reason:?}"
7605 );
7606 assert_eq!(reason, "gate backend unavailable");
7607
7608 let rendered = err.to_string();
7610 assert!(
7611 !rendered.contains(CANARY),
7612 "top-level Display must not embed backend error text either: {rendered:?}"
7613 );
7614 }
7615
7616 #[tokio::test]
7622 async fn gate_policy_error_classifies_distinctly_from_backend_unavailable() {
7623 #[derive(Debug)]
7624 struct PolicyBrokenGate;
7625 impl Gate for PolicyBrokenGate {
7626 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7627 Err(GateError::Policy(
7628 "rule set has no allow clause for this namespace".to_string(),
7629 ))
7630 }
7631 }
7632
7633 let mut builder = VerbRegistryBuilder::new();
7634 builder.register(GateErrorTrackingPack {
7635 invoked: Arc::new(AtomicUsize::new(0)),
7636 });
7637 builder.with_gate(Arc::new(PolicyBrokenGate));
7638 let registry = builder.build().expect("registry builds");
7639
7640 let err = registry
7641 .dispatch("guarded", Value::Null)
7642 .await
7643 .expect_err("gate unavailability must refuse dispatch");
7644
7645 assert!(matches!(
7646 err,
7647 RuntimeError::GateUnavailable { ref verb, ref reason }
7648 if verb == "guarded"
7649 && reason == "gate policy evaluation failed"
7650 && !reason.contains("rule set has no allow clause")
7651 ));
7652 }
7653
7654 #[tokio::test]
7655 async fn no_event_store_configured_tracing_only() {
7656 let mut builder = VerbRegistryBuilder::new();
7659 builder.register(AlphaPack);
7660 let reg = builder.build().expect("registry builds");
7661
7662 let res = reg.dispatch("list", Value::Null).await.unwrap();
7663 assert_eq!(res["pack"], "alpha");
7664 }
7665
7666 #[test]
7667 #[serial]
7668 fn dispatch_tracing_emits_gate_check_event_with_deny_payload() {
7669 #[derive(Debug)]
7670 struct TracingDenyGate;
7671 impl Gate for TracingDenyGate {
7672 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7673 Ok(GateDecision::deny("denied by test gate"))
7674 }
7675 fn impl_name(&self) -> &'static str {
7676 "TracingDenyGate"
7677 }
7678 }
7679
7680 let events = capture_dispatch_events(async {
7681 let mut builder = VerbRegistryBuilder::new();
7682 builder.register(AlphaPack);
7683 builder.with_gate(Arc::new(TracingDenyGate));
7684 let reg = builder.build().expect("registry builds");
7685 let _ = reg.dispatch("create", serde_json::Value::Null).await;
7688 });
7689
7690 let gate_events = gate_check_events_for(&events, "TracingDenyGate");
7691 assert_eq!(
7692 gate_events.len(),
7693 1,
7694 "exactly one gate.check tracing event per dispatch (deny); got {gate_events:?}"
7695 );
7696 let payload = gate_events[0]
7697 .audit_event
7698 .as_ref()
7699 .expect("gate.check event must carry an audit_event field on Deny");
7700 let audit: khive_gate::AuditEvent =
7701 serde_json::from_str(payload).expect("audit_event payload must decode to AuditEvent");
7702 assert_eq!(audit.decision, AuditDecision::Deny);
7703 assert_eq!(audit.deny_reason.as_deref(), Some("denied by test gate"));
7704 assert_eq!(audit.gate_impl, "TracingDenyGate");
7705 let payload_json: serde_json::Value =
7709 serde_json::from_str(payload).expect("payload must be valid JSON");
7710 assert_eq!(
7711 payload_json["obligations"],
7712 serde_json::Value::Array(Vec::new()),
7713 "obligations must be `[]` on Deny on the tracing payload, not omitted"
7714 );
7715 }
7716
7717 #[tokio::test]
7724 async fn audit_envelope_round_trips_deny_reason_and_gate_impl_through_event_store() {
7725 #[derive(Debug)]
7726 struct DenyGateWithName;
7727 impl Gate for DenyGateWithName {
7728 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7729 Ok(GateDecision::deny("policy: write forbidden for anon"))
7730 }
7731 fn impl_name(&self) -> &'static str {
7732 "DenyGateWithName"
7733 }
7734 }
7735
7736 let store = Arc::new(MemoryEventStore::default());
7737 let mut builder = VerbRegistryBuilder::new();
7738 builder.register(AlphaPack);
7739 builder.with_gate(Arc::new(DenyGateWithName));
7740 builder.with_event_store(store.clone());
7741 let reg = builder.build().expect("registry builds");
7742
7743 let err = reg
7745 .dispatch("list", serde_json::json!({"namespace": "test-ns"}))
7746 .await
7747 .unwrap_err();
7748 assert!(
7749 matches!(err, RuntimeError::PermissionDenied { .. }),
7750 "expected PermissionDenied, got {err:?}"
7751 );
7752
7753 let page = store
7755 .query_events(
7756 EventFilter::default(),
7757 PageRequest {
7758 limit: 10,
7759 offset: 0,
7760 },
7761 )
7762 .await
7763 .unwrap();
7764 assert_eq!(
7765 page.items.len(),
7766 1,
7767 "one audit event must be persisted on deny"
7768 );
7769
7770 let ev = &page.items[0];
7771 assert_eq!(ev.outcome, EventOutcome::Denied);
7772
7773 let data = &ev.payload;
7775
7776 let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
7777 .expect("Event.payload must deserialize to AuditEvent");
7778
7779 assert_eq!(
7780 audit.deny_reason.as_deref(),
7781 Some("policy: write forbidden for anon"),
7782 "deny_reason must be preserved through EventStore"
7783 );
7784 assert_eq!(
7785 audit.gate_impl, "DenyGateWithName",
7786 "gate_impl must be preserved through EventStore"
7787 );
7788 assert_eq!(
7789 audit.decision,
7790 khive_gate::AuditDecision::Deny,
7791 "decision field must be preserved through EventStore"
7792 );
7793 }
7794
7795 #[tokio::test]
7796 async fn audit_envelope_round_trips_obligations_through_event_store() {
7797 use khive_gate::Obligation;
7798
7799 #[derive(Debug)]
7800 struct ObligationGate;
7801 impl Gate for ObligationGate {
7802 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7803 Ok(GateDecision::allow_with(vec![Obligation::Audit {
7804 tag: "billing.meter".into(),
7805 }]))
7806 }
7807 fn impl_name(&self) -> &'static str {
7808 "ObligationGate"
7809 }
7810 }
7811
7812 let store = Arc::new(MemoryEventStore::default());
7813 let mut builder = VerbRegistryBuilder::new();
7814 builder.register(AlphaPack);
7815 builder.with_gate(Arc::new(ObligationGate));
7816 builder.with_event_store(store.clone());
7817 let reg = builder.build().expect("registry builds");
7818
7819 reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
7820 .await
7821 .unwrap();
7822
7823 let page = store
7824 .query_events(
7825 EventFilter::default(),
7826 PageRequest {
7827 limit: 10,
7828 offset: 0,
7829 },
7830 )
7831 .await
7832 .unwrap();
7833 assert_eq!(page.items.len(), 1);
7834
7835 let ev = &page.items[0];
7836 assert_eq!(ev.outcome, EventOutcome::Success);
7837
7838 let data = &ev.payload;
7839
7840 let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
7841 .expect("Event.payload must deserialize to AuditEvent");
7842
7843 assert_eq!(audit.gate_impl, "ObligationGate");
7844 assert_eq!(
7845 audit.obligations.len(),
7846 1,
7847 "obligations must be preserved through EventStore"
7848 );
7849 match &audit.obligations[0] {
7850 Obligation::Audit { tag } => assert_eq!(tag, "billing.meter"),
7851 other => panic!("expected Audit obligation, got {other:?}"),
7852 }
7853 }
7854
7855 #[tokio::test]
7863 async fn sql_backed_audit_envelope_round_trips_deny_reason_gate_impl_and_obligations() {
7864 #[derive(Debug)]
7865 struct SqlTestDenyGate;
7866 impl Gate for SqlTestDenyGate {
7867 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7868 Ok(GateDecision::deny("sql-path: write denied"))
7869 }
7870 fn impl_name(&self) -> &'static str {
7871 "SqlTestDenyGate"
7872 }
7873 }
7874
7875 let rt = KhiveRuntime::memory().expect("in-memory runtime");
7879 let test_tok = NamespaceToken::for_namespace(Namespace::parse("test-ns").unwrap());
7880 let sql_store = rt
7881 .events(&test_tok)
7882 .expect("events_for_namespace must succeed");
7883
7884 let mut builder = VerbRegistryBuilder::new();
7885 builder.register(AlphaPack);
7886 builder.with_gate(Arc::new(SqlTestDenyGate));
7887 builder.with_event_store(sql_store.clone());
7888 let reg = builder.build().expect("registry builds");
7889
7890 let err = reg
7892 .dispatch("list", serde_json::json!({"namespace": "test-ns"}))
7893 .await
7894 .unwrap_err();
7895 assert!(
7896 matches!(err, RuntimeError::PermissionDenied { .. }),
7897 "expected PermissionDenied, got {err:?}"
7898 );
7899
7900 let page = sql_store
7902 .query_events(
7903 EventFilter::default(),
7904 PageRequest {
7905 limit: 10,
7906 offset: 0,
7907 },
7908 )
7909 .await
7910 .unwrap();
7911 assert_eq!(
7912 page.items.len(),
7913 1,
7914 "one audit event must be persisted on deny through SqlEventStore"
7915 );
7916
7917 let ev = &page.items[0];
7918 assert_eq!(ev.outcome, EventOutcome::Denied);
7919
7920 let data = &ev.payload;
7924
7925 let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
7926 .expect("Event.payload must deserialize to AuditEvent after SQL round-trip");
7927
7928 assert_eq!(
7929 audit.deny_reason.as_deref(),
7930 Some("sql-path: write denied"),
7931 "deny_reason must survive the SQL text round-trip"
7932 );
7933 assert_eq!(
7934 audit.gate_impl, "SqlTestDenyGate",
7935 "gate_impl must survive the SQL text round-trip"
7936 );
7937 assert_eq!(
7938 audit.decision,
7939 khive_gate::AuditDecision::Deny,
7940 "decision field must survive the SQL text round-trip"
7941 );
7942 assert!(
7945 audit.obligations.is_empty(),
7946 "obligations must be preserved as empty [] through SQL round-trip"
7947 );
7948 }
7949
7950 #[tokio::test]
7962 async fn sql_backed_audit_envelope_round_trips_non_empty_obligations() {
7963 use khive_gate::Obligation;
7964
7965 #[derive(Debug)]
7966 struct SqlTestAllowWithObligationGate;
7967 impl Gate for SqlTestAllowWithObligationGate {
7968 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7969 Ok(GateDecision::allow_with(vec![Obligation::Audit {
7970 tag: "sql-path-billing.meter".into(),
7971 }]))
7972 }
7973 fn impl_name(&self) -> &'static str {
7974 "SqlTestAllowWithObligationGate"
7975 }
7976 }
7977
7978 let rt = KhiveRuntime::memory().expect("in-memory runtime");
7979 let test_tok = NamespaceToken::for_namespace(Namespace::parse("test-ns").unwrap());
7980 let sql_store = rt
7981 .events(&test_tok)
7982 .expect("events_for_namespace must succeed");
7983
7984 let mut builder = VerbRegistryBuilder::new();
7985 builder.register(AlphaPack);
7986 builder.with_gate(Arc::new(SqlTestAllowWithObligationGate));
7987 builder.with_event_store(sql_store.clone());
7988 let reg = builder.build().expect("registry builds");
7989
7990 reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
7992 .await
7993 .expect("dispatch must succeed when gate allows");
7994
7995 let page = sql_store
7997 .query_events(
7998 EventFilter::default(),
7999 PageRequest {
8000 limit: 10,
8001 offset: 0,
8002 },
8003 )
8004 .await
8005 .unwrap();
8006 assert_eq!(
8007 page.items.len(),
8008 1,
8009 "one audit event must be persisted on allow through SqlEventStore"
8010 );
8011
8012 let ev = &page.items[0];
8013 assert_eq!(ev.outcome, EventOutcome::Success);
8014
8015 let data = &ev.payload;
8016
8017 let obligations_raw = data
8022 .get("obligations")
8023 .expect("Event.data JSON must contain 'obligations' key");
8024 let obligations_arr = obligations_raw
8025 .as_array()
8026 .expect("'obligations' must be a JSON array");
8027 assert!(
8028 !obligations_arr.is_empty(),
8029 "raw Event.data['obligations'] must be non-empty after SQL round-trip"
8030 );
8031
8032 let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
8035 .expect("Event.data must deserialize to AuditEvent after SQL round-trip");
8036
8037 assert_eq!(
8038 audit.gate_impl, "SqlTestAllowWithObligationGate",
8039 "gate_impl must survive the SQL text round-trip"
8040 );
8041 assert_eq!(
8042 audit.decision,
8043 khive_gate::AuditDecision::Allow,
8044 "decision field must survive the SQL text round-trip"
8045 );
8046 assert_eq!(
8047 audit.obligations.len(),
8048 1,
8049 "obligations must be non-empty after SQL round-trip (not silently defaulted to [])"
8050 );
8051 match &audit.obligations[0] {
8052 Obligation::Audit { tag } => assert_eq!(
8053 tag, "sql-path-billing.meter",
8054 "Audit obligation tag must survive the SQL text round-trip"
8055 ),
8056 other => panic!("expected Audit obligation, got {other:?}"),
8057 }
8058 }
8059
8060 #[tokio::test]
8068 async fn audit_event_payload_shape_for_create_verb() {
8069 let store = Arc::new(MemoryEventStore::default());
8070 let mut builder = VerbRegistryBuilder::new();
8071 builder.register(AlphaPack);
8072 builder.with_event_store(store.clone());
8073 builder.with_default_namespace("test-ns");
8074 let reg = builder.build().expect("registry builds");
8075
8076 reg.dispatch("create", serde_json::json!({"namespace": "test-ns"}))
8079 .await
8080 .unwrap();
8081
8082 let count = store.count_events(EventFilter::default()).await.unwrap();
8083 assert_eq!(count, 1, "exactly one audit event for one dispatch");
8084
8085 let page = store
8086 .query_events(
8087 EventFilter::default(),
8088 PageRequest {
8089 limit: 10,
8090 offset: 0,
8091 },
8092 )
8093 .await
8094 .unwrap();
8095 let ev = &page.items[0];
8096
8097 assert_eq!(ev.verb, "create", "ev.verb must be the dispatched verb");
8099 assert_eq!(
8100 ev.outcome,
8101 EventOutcome::Success,
8102 "ev.outcome must be Success on allow"
8103 );
8104 assert_eq!(
8105 ev.namespace, "test-ns",
8106 "ev.namespace must match the dispatch namespace"
8107 );
8108
8109 let data = &ev.payload;
8111
8112 let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
8113 .expect("ev.payload must deserialize to AuditEvent");
8114
8115 assert_eq!(
8116 audit.decision,
8117 khive_gate::AuditDecision::Allow,
8118 "AuditEvent.decision must be Allow"
8119 );
8120 assert_eq!(audit.verb, "create", "AuditEvent.verb must be 'create'");
8121 assert_eq!(
8122 audit.namespace, "test-ns",
8123 "AuditEvent.namespace must be preserved"
8124 );
8125 assert_eq!(
8126 audit.gate_impl, "AllowAllGate",
8127 "AuditEvent.gate_impl must name the gate implementation"
8128 );
8129 assert!(
8130 audit.deny_reason.is_none(),
8131 "AuditEvent.deny_reason must be None on Allow"
8132 );
8133 let payload_json: serde_json::Value =
8135 serde_json::from_value(data.clone()).expect("data must be valid JSON");
8136 assert_eq!(
8137 payload_json["obligations"],
8138 serde_json::Value::Array(Vec::new()),
8139 "obligations must be [] on AllowAllGate"
8140 );
8141 }
8142
8143 struct EmbeddingAwarePack {
8150 models: Vec<String>,
8151 }
8152
8153 impl khive_types::Pack for EmbeddingAwarePack {
8154 const NAME: &'static str = "embedding_aware";
8155 const NOTE_KINDS: &'static [&'static str] = &[];
8156 const ENTITY_KINDS: &'static [&'static str] = &["widget"];
8157 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
8158 name: "create",
8159 description: "create a widget (embedding-aware stub)",
8160 visibility: Visibility::Verb,
8161 category: VerbCategory::Commissive,
8162 params: &[],
8163 }];
8164 }
8165
8166 #[async_trait]
8167 impl PackRuntime for EmbeddingAwarePack {
8168 fn name(&self) -> &str {
8169 Self::NAME
8170 }
8171 fn note_kinds(&self) -> &'static [&'static str] {
8172 Self::NOTE_KINDS
8173 }
8174 fn entity_kinds(&self) -> &'static [&'static str] {
8175 Self::ENTITY_KINDS
8176 }
8177 fn handlers(&self) -> &'static [HandlerDef] {
8178 Self::HANDLERS
8179 }
8180 fn registered_embedding_model_names(&self) -> Vec<String> {
8181 self.models.clone()
8182 }
8183 async fn dispatch(
8184 &self,
8185 verb: &str,
8186 _params: Value,
8187 _registry: &VerbRegistry,
8188 _token: &NamespaceToken,
8189 ) -> Result<Value, RuntimeError> {
8190 Ok(serde_json::json!({ "pack": "embedding_aware", "verb": verb }))
8191 }
8192 }
8193
8194 struct FailingProbePack;
8197
8198 impl khive_types::Pack for FailingProbePack {
8199 const NAME: &'static str = "failing_probe";
8200 const NOTE_KINDS: &'static [&'static str] = &[];
8201 const ENTITY_KINDS: &'static [&'static str] = &[];
8202 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
8203 name: "probe",
8204 description: "always fails",
8205 visibility: Visibility::Verb,
8206 category: VerbCategory::Assertive,
8207 params: &[],
8208 }];
8209 }
8210
8211 #[async_trait]
8212 impl PackRuntime for FailingProbePack {
8213 fn name(&self) -> &str {
8214 Self::NAME
8215 }
8216 fn note_kinds(&self) -> &'static [&'static str] {
8217 Self::NOTE_KINDS
8218 }
8219 fn entity_kinds(&self) -> &'static [&'static str] {
8220 Self::ENTITY_KINDS
8221 }
8222 fn handlers(&self) -> &'static [HandlerDef] {
8223 Self::HANDLERS
8224 }
8225 async fn dispatch(
8226 &self,
8227 _verb: &str,
8228 _params: Value,
8229 _registry: &VerbRegistry,
8230 _token: &NamespaceToken,
8231 ) -> Result<Value, RuntimeError> {
8232 Err(RuntimeError::InvalidInput("boom".into()))
8233 }
8234 }
8235
8236 #[tokio::test]
8237 async fn resource_cost_unit_present_on_non_embedding_successful_dispatch() {
8238 let store = Arc::new(MemoryEventStore::default());
8239 let mut builder = VerbRegistryBuilder::new();
8240 builder.register(AlphaPack);
8241 builder.with_event_store(store.clone());
8242 let reg = builder.build().expect("registry builds");
8243
8244 reg.dispatch("list", serde_json::json!({})).await.unwrap();
8245
8246 let page = store
8247 .query_events(
8248 EventFilter::default(),
8249 PageRequest {
8250 limit: 10,
8251 offset: 0,
8252 },
8253 )
8254 .await
8255 .unwrap();
8256 assert_eq!(page.items.len(), 1);
8257 assert_eq!(
8258 page.items[0].payload["resource"],
8259 serde_json::json!({"work_class": "interactive", "cost_unit": 1}),
8260 "non-embedding-bearing verb's resource.cost_unit must be base_weight(verb) alone"
8261 );
8262 }
8263
8264 #[tokio::test]
8265 async fn resource_cost_unit_scales_with_registered_model_count_for_create() {
8266 let store = Arc::new(MemoryEventStore::default());
8267 let mut builder = VerbRegistryBuilder::new();
8268 builder.register(EmbeddingAwarePack {
8269 models: vec!["all-minilm-l6-v2".into(), "paraphrase".into()],
8270 });
8271 builder.with_event_store(store.clone());
8272 let reg = builder.build().expect("registry builds");
8273
8274 reg.dispatch("create", serde_json::json!({"kind": "widget"}))
8275 .await
8276 .unwrap();
8277
8278 let page = store
8279 .query_events(
8280 EventFilter::default(),
8281 PageRequest {
8282 limit: 10,
8283 offset: 0,
8284 },
8285 )
8286 .await
8287 .unwrap();
8288 assert_eq!(
8290 page.items[0].payload["resource"],
8291 serde_json::json!({"work_class": "interactive", "cost_unit": 3}),
8292 );
8293 }
8294
8295 #[tokio::test]
8296 async fn resource_cost_unit_zero_registered_models_is_base_weight_only() {
8297 let store = Arc::new(MemoryEventStore::default());
8298 let mut builder = VerbRegistryBuilder::new();
8299 builder.register(EmbeddingAwarePack { models: vec![] });
8300 builder.with_event_store(store.clone());
8301 let reg = builder.build().expect("registry builds");
8302
8303 reg.dispatch("create", serde_json::json!({"kind": "widget"}))
8304 .await
8305 .unwrap();
8306
8307 let page = store
8308 .query_events(
8309 EventFilter::default(),
8310 PageRequest {
8311 limit: 10,
8312 offset: 0,
8313 },
8314 )
8315 .await
8316 .unwrap();
8317 assert_eq!(
8318 page.items[0].payload["resource"]["cost_unit"], 1,
8319 "zero registered embedding models must vanish the term, not error or omit"
8320 );
8321 }
8322
8323 #[tokio::test]
8324 async fn resource_work_class_present_cost_unit_absent_when_dispatch_returns_error() {
8325 let store = Arc::new(MemoryEventStore::default());
8326 let mut builder = VerbRegistryBuilder::new();
8327 builder.register(FailingProbePack);
8328 builder.with_event_store(store.clone());
8329 let reg = builder.build().expect("registry builds");
8330
8331 let err = reg
8332 .dispatch("probe", serde_json::json!({}))
8333 .await
8334 .unwrap_err();
8335 assert!(matches!(err, RuntimeError::InvalidInput(_)));
8336
8337 let page = store
8338 .query_events(
8339 EventFilter::default(),
8340 PageRequest {
8341 limit: 10,
8342 offset: 0,
8343 },
8344 )
8345 .await
8346 .unwrap();
8347 assert_eq!(page.items.len(), 1);
8348 assert_eq!(page.items[0].outcome, EventOutcome::Error);
8349 assert_eq!(
8354 page.items[0].payload["resource"],
8355 serde_json::json!({"work_class": "interactive"}),
8356 "resource must carry work_class with cost_unit OMITTED (never 0) on an \
8357 errored dispatch: {:?}",
8358 page.items[0].payload
8359 );
8360 }
8361
8362 #[tokio::test]
8363 async fn resource_work_class_present_cost_unit_absent_when_no_pack_owns_the_verb() {
8364 let store = Arc::new(MemoryEventStore::default());
8365 let mut builder = VerbRegistryBuilder::new();
8366 builder.register(AlphaPack);
8367 builder.with_event_store(store.clone());
8368 let reg = builder.build().expect("registry builds");
8369
8370 let _ = reg
8371 .dispatch("no_such_verb_resource_test", serde_json::json!({}))
8372 .await;
8373
8374 let page = store
8375 .query_events(
8376 EventFilter::default(),
8377 PageRequest {
8378 limit: 10,
8379 offset: 0,
8380 },
8381 )
8382 .await
8383 .unwrap();
8384 assert_eq!(page.items.len(), 1);
8385 assert_eq!(
8386 page.items[0].payload["resource"],
8387 serde_json::json!({"work_class": "interactive"})
8388 );
8389 }
8390
8391 #[tokio::test]
8392 async fn resource_work_class_present_cost_unit_absent_on_denied_dispatch() {
8393 #[derive(Debug)]
8394 struct AlwaysDenyGate;
8395 impl Gate for AlwaysDenyGate {
8396 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
8397 Ok(GateDecision::deny("test: always deny"))
8398 }
8399 }
8400 let store = Arc::new(MemoryEventStore::default());
8401 let mut builder = VerbRegistryBuilder::new();
8402 builder.register(AlphaPack);
8403 builder.with_gate(Arc::new(AlwaysDenyGate));
8404 builder.with_event_store(store.clone());
8405 let reg = builder.build().expect("registry builds");
8406
8407 let _ = reg.dispatch("list", serde_json::json!({})).await;
8408
8409 let page = store
8410 .query_events(
8411 EventFilter::default(),
8412 PageRequest {
8413 limit: 10,
8414 offset: 0,
8415 },
8416 )
8417 .await
8418 .unwrap();
8419 assert_eq!(page.items.len(), 1);
8420 assert_eq!(page.items[0].outcome, EventOutcome::Denied);
8421 assert_eq!(
8422 page.items[0].payload["resource"],
8423 serde_json::json!({"work_class": "interactive"})
8424 );
8425 }
8426
8427 #[tokio::test]
8428 async fn resource_cost_unit_present_on_link_singleton_success() {
8429 let store = Arc::new(MemoryEventStore::default());
8430 let edge_id = uuid::Uuid::new_v4();
8431 let source_id = uuid::Uuid::new_v4();
8432 let target_id = uuid::Uuid::new_v4();
8433 let edge_json = serde_json::json!({
8434 "id": edge_id,
8435 "namespace": "local",
8436 "source_id": source_id,
8437 "target_id": target_id,
8438 "relation": "depends_on",
8439 "weight": 1.0,
8440 });
8441 let mut builder = VerbRegistryBuilder::new();
8442 builder.register(LinkResultPack::ok(edge_json));
8443 builder.with_event_store(store.clone());
8444 let reg = builder.build().expect("registry builds");
8445
8446 reg.dispatch(
8447 "link",
8448 serde_json::json!({
8449 "source_id": source_id,
8450 "target_id": target_id,
8451 "relation": "depends_on",
8452 }),
8453 )
8454 .await
8455 .unwrap();
8456
8457 let page = store
8458 .query_events(
8459 EventFilter::default(),
8460 PageRequest {
8461 limit: 10,
8462 offset: 0,
8463 },
8464 )
8465 .await
8466 .unwrap();
8467 assert_eq!(
8468 page.items[0].payload["resource"],
8469 serde_json::json!({"work_class": "interactive", "cost_unit": 1}),
8470 "link has no embedding-bearing path -> base_weight(link) alone, even on the v2-enriched singleton path"
8471 );
8472 }
8473
8474 #[tokio::test]
8475 async fn resource_work_class_present_cost_unit_absent_on_link_dispatch_failure() {
8476 let store = Arc::new(MemoryEventStore::default());
8477 let mut builder = VerbRegistryBuilder::new();
8478 builder.register(LinkResultPack::err("target endpoint not found"));
8479 builder.with_event_store(store.clone());
8480 let reg = builder.build().expect("registry builds");
8481
8482 let _ = reg
8483 .dispatch(
8484 "link",
8485 serde_json::json!({
8486 "source_id": "note:alpha",
8487 "target_id": "note:missing",
8488 "relation": "depends_on",
8489 }),
8490 )
8491 .await;
8492
8493 let page = store
8494 .query_events(
8495 EventFilter::default(),
8496 PageRequest {
8497 limit: 10,
8498 offset: 0,
8499 },
8500 )
8501 .await
8502 .unwrap();
8503 assert_eq!(page.items.len(), 1);
8504 assert_eq!(
8505 page.items[0].payload["resource"],
8506 serde_json::json!({"work_class": "interactive"})
8507 );
8508 }
8509
8510 #[tokio::test]
8512 async fn audit_event_threads_target_id_from_dispatch_args() {
8513 let store = Arc::new(MemoryEventStore::default());
8514 let target = uuid::Uuid::new_v4();
8515 let mut builder = VerbRegistryBuilder::new();
8516 builder.register(AlphaPack);
8517 builder.with_event_store(store.clone());
8518 builder.with_default_namespace("test-ns");
8519 let reg = builder.build().expect("registry builds");
8520
8521 reg.dispatch(
8522 "create",
8523 serde_json::json!({"namespace": "test-ns", "target_id": target}),
8524 )
8525 .await
8526 .unwrap();
8527
8528 let page = store
8529 .query_events(
8530 EventFilter::default(),
8531 PageRequest {
8532 offset: 0,
8533 limit: 10,
8534 },
8535 )
8536 .await
8537 .unwrap();
8538 assert_eq!(
8539 page.items[0].target_id,
8540 Some(target),
8541 "#282: audit event must carry target_id from dispatch params"
8542 );
8543 }
8544
8545 struct LinkResultPack {
8551 result: std::sync::Mutex<Option<Result<Value, RuntimeError>>>,
8552 }
8553
8554 impl LinkResultPack {
8555 fn ok(value: Value) -> Self {
8556 Self {
8557 result: std::sync::Mutex::new(Some(Ok(value))),
8558 }
8559 }
8560 fn err(message: &str) -> Self {
8561 Self {
8562 result: std::sync::Mutex::new(Some(Err(RuntimeError::InvalidInput(
8563 message.to_string(),
8564 )))),
8565 }
8566 }
8567 }
8568
8569 impl khive_types::Pack for LinkResultPack {
8570 const NAME: &'static str = "kg";
8571 const NOTE_KINDS: &'static [&'static str] = &[];
8572 const ENTITY_KINDS: &'static [&'static str] = &[];
8573 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
8574 name: "link",
8575 description: "test link handler",
8576 visibility: Visibility::Verb,
8577 category: VerbCategory::Commissive,
8578 params: &[],
8579 }];
8580 }
8581
8582 #[async_trait]
8583 impl PackRuntime for LinkResultPack {
8584 fn name(&self) -> &str {
8585 Self::NAME
8586 }
8587 fn note_kinds(&self) -> &'static [&'static str] {
8588 Self::NOTE_KINDS
8589 }
8590 fn entity_kinds(&self) -> &'static [&'static str] {
8591 Self::ENTITY_KINDS
8592 }
8593 fn handlers(&self) -> &'static [HandlerDef] {
8594 Self::HANDLERS
8595 }
8596 async fn dispatch(
8597 &self,
8598 _verb: &str,
8599 _params: Value,
8600 _registry: &VerbRegistry,
8601 _token: &NamespaceToken,
8602 ) -> Result<Value, RuntimeError> {
8603 self.result
8604 .lock()
8605 .unwrap()
8606 .take()
8607 .expect("LinkResultPack dispatch called more than once in a test")
8608 }
8609 }
8610
8611 #[tokio::test]
8612 async fn link_audit_enriches_successful_singleton_with_edge_v2() {
8613 let store = Arc::new(MemoryEventStore::default());
8614 let edge_id = uuid::Uuid::new_v4();
8615 let source_id = uuid::Uuid::new_v4();
8616 let target_id = uuid::Uuid::new_v4();
8617 let edge_json = serde_json::json!({
8618 "id": edge_id,
8619 "namespace": "local",
8620 "source_id": source_id,
8621 "target_id": target_id,
8622 "relation": "depends_on",
8623 "weight": 1.0,
8624 });
8625 let mut builder = VerbRegistryBuilder::new();
8626 builder.register(LinkResultPack::ok(edge_json));
8627 builder.with_event_store(store.clone());
8628 builder.with_default_namespace("test-ns");
8629 let reg = builder.build().expect("registry builds");
8630
8631 reg.dispatch(
8632 "link",
8633 serde_json::json!({
8634 "source_id": source_id,
8635 "target_id": target_id,
8636 "relation": "depends_on",
8637 }),
8638 )
8639 .await
8640 .unwrap();
8641
8642 let count = store.count_events(EventFilter::default()).await.unwrap();
8643 assert_eq!(
8644 count, 1,
8645 "exactly one deferred audit row must be persisted for a successful singleton link"
8646 );
8647 let page = store
8648 .query_events(
8649 EventFilter::default(),
8650 PageRequest {
8651 limit: 10,
8652 offset: 0,
8653 },
8654 )
8655 .await
8656 .unwrap();
8657 let ev = &page.items[0];
8658 assert_eq!(ev.verb, "link");
8659 assert_eq!(ev.outcome, EventOutcome::Success);
8660 assert_eq!(
8661 ev.payload_schema_version, 2,
8662 "successful singleton link uses audit schema v2"
8663 );
8664 assert_eq!(
8665 ev.target_id,
8666 Some(edge_id),
8667 "target_id must be the created/resolved edge id, not a raw caller arg"
8668 );
8669 assert_eq!(ev.payload["edge_id"], serde_json::json!(edge_id));
8670 assert_eq!(ev.payload["source_id"], serde_json::json!(source_id));
8671 assert_eq!(ev.payload["target_id"], serde_json::json!(target_id));
8672 assert_eq!(ev.payload["relation"], "depends_on");
8673 assert_eq!(ev.payload["weight"], 1.0);
8674 assert_eq!(ev.payload["verb"], "link");
8676 assert_eq!(ev.payload["decision"], "allow");
8677 assert!(ev.payload.get("gate_impl").is_some());
8678 }
8679
8680 #[tokio::test]
8681 async fn link_audit_falls_back_to_v1_when_dispatch_fails() {
8682 let store = Arc::new(MemoryEventStore::default());
8683 let mut builder = VerbRegistryBuilder::new();
8684 builder.register(LinkResultPack::err("target endpoint not found"));
8685 builder.with_event_store(store.clone());
8686 builder.with_default_namespace("test-ns");
8687 let reg = builder.build().expect("registry builds");
8688
8689 let err = reg
8690 .dispatch(
8691 "link",
8692 serde_json::json!({
8693 "source_id": "note:alpha",
8694 "target_id": "note:missing",
8695 "relation": "depends_on",
8696 }),
8697 )
8698 .await
8699 .unwrap_err();
8700 assert!(
8701 matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("not found")),
8702 "the original dispatch error must be returned unchanged"
8703 );
8704
8705 let page = store
8706 .query_events(
8707 EventFilter::default(),
8708 PageRequest {
8709 limit: 10,
8710 offset: 0,
8711 },
8712 )
8713 .await
8714 .unwrap();
8715 assert_eq!(
8716 page.items.len(),
8717 1,
8718 "a v1 fallback audit row must still be persisted on dispatch failure"
8719 );
8720 let ev = &page.items[0];
8721 assert_eq!(
8722 ev.payload_schema_version, 1,
8723 "failed link keeps the v1 audit shape"
8724 );
8725 assert_eq!(
8728 ev.outcome,
8729 EventOutcome::Error,
8730 "outcome reflects the dispatch result (Err), not the gate decision (Allow)"
8731 );
8732 assert!(
8733 ev.duration_us >= 0,
8734 "duration_us must still be populated (measured, not the Event::new \
8735 default sentinel) on a failed dispatch"
8736 );
8737 assert!(
8738 ev.target_id.is_none(),
8739 "non-UUID caller-supplied ids do not spuriously populate target_id"
8740 );
8741 assert!(
8742 ev.payload.get("edge_id").is_none(),
8743 "v1 fallback must not carry edge enrichment fields"
8744 );
8745 let _: khive_gate::AuditEvent = serde_json::from_value(ev.payload.clone())
8746 .expect("v1 fallback payload must deserialize as AuditEvent");
8747 }
8748
8749 #[tokio::test]
8750 async fn link_audit_falls_back_to_v1_when_result_missing_edge_fields() {
8751 let store = Arc::new(MemoryEventStore::default());
8752 let target_arg = uuid::Uuid::new_v4();
8753 let mut builder = VerbRegistryBuilder::new();
8754 builder.register(LinkResultPack::ok(serde_json::json!({"ok": true})));
8755 builder.with_event_store(store.clone());
8756 builder.with_default_namespace("test-ns");
8757 let reg = builder.build().expect("registry builds");
8758
8759 reg.dispatch(
8760 "link",
8761 serde_json::json!({
8762 "source_id": uuid::Uuid::new_v4(),
8763 "target_id": target_arg,
8764 "relation": "depends_on",
8765 }),
8766 )
8767 .await
8768 .unwrap();
8769
8770 let page = store
8771 .query_events(
8772 EventFilter::default(),
8773 PageRequest {
8774 limit: 10,
8775 offset: 0,
8776 },
8777 )
8778 .await
8779 .unwrap();
8780 assert_eq!(page.items.len(), 1);
8781 let ev = &page.items[0];
8782 assert_eq!(
8783 ev.payload_schema_version, 1,
8784 "an unparsable success result falls back to v1 rather than dropping the audit row"
8785 );
8786 assert_eq!(ev.outcome, EventOutcome::Success);
8787 assert_eq!(
8788 ev.target_id,
8789 Some(target_arg),
8790 "v1 fallback still extracts target_id from the raw dispatch args"
8791 );
8792 assert!(ev.payload.get("edge_id").is_none());
8793 }
8794
8795 #[tokio::test]
8796 async fn link_audit_bulk_links_get_no_enrichment() {
8797 let store = Arc::new(MemoryEventStore::default());
8798 let mut builder = VerbRegistryBuilder::new();
8799 builder.register(LinkResultPack::ok(serde_json::json!({
8800 "attempted": 2, "created": 2, "skipped": 0, "failed": 0
8801 })));
8802 builder.with_event_store(store.clone());
8803 builder.with_default_namespace("test-ns");
8804 let reg = builder.build().expect("registry builds");
8805
8806 reg.dispatch(
8807 "link",
8808 serde_json::json!({
8809 "links": [
8810 {"source_id": "a", "target_id": "b", "relation": "depends_on"},
8811 {"source_id": "c", "target_id": "d", "relation": "depends_on"},
8812 ],
8813 }),
8814 )
8815 .await
8816 .unwrap();
8817
8818 let count = store.count_events(EventFilter::default()).await.unwrap();
8819 assert_eq!(
8820 count, 1,
8821 "bulk `links` gets exactly one v1 audit row (deferred until dispatch \
8822 resolves like every other Allow-outcome row since ADR-103 Stage 1, \
8823 but never v2-enriched — enrichment is singleton-`link`-only)"
8824 );
8825 let page = store
8826 .query_events(
8827 EventFilter::default(),
8828 PageRequest {
8829 limit: 10,
8830 offset: 0,
8831 },
8832 )
8833 .await
8834 .unwrap();
8835 let ev = &page.items[0];
8836 assert_eq!(
8837 ev.payload_schema_version, 1,
8838 "bulk link mode is out of scope for #676's events.target_id enrichment"
8839 );
8840 assert!(ev.target_id.is_none());
8841 }
8842
8843 #[test]
8844 fn link_audit_success_from_result_extracts_edge_fields() {
8845 let gate_req = GateRequest::new(
8846 ActorRef::anonymous(),
8847 Namespace::local(),
8848 "link",
8849 serde_json::json!({}),
8850 );
8851 let decision = GateDecision::Allow {
8852 obligations: vec![],
8853 };
8854 let audit = AuditEvent::from_check(&gate_req, &decision, "AllowAllGate");
8855
8856 let edge_id = uuid::Uuid::new_v4();
8857 let source_id = uuid::Uuid::new_v4();
8858 let target_id = uuid::Uuid::new_v4();
8859 let result = serde_json::json!({
8860 "id": edge_id,
8861 "source_id": source_id,
8862 "target_id": target_id,
8863 "relation": "depends_on",
8864 "weight": 0.5,
8865 });
8866
8867 let (returned_id, payload) = link_audit_success_from_result(audit, &result)
8868 .expect("well-formed edge JSON must produce an enriched payload");
8869 assert_eq!(returned_id, edge_id);
8870 assert_eq!(payload["edge_id"], serde_json::json!(edge_id));
8871 assert_eq!(payload["relation"], "depends_on");
8872 assert_eq!(payload["weight"], 0.5);
8873 assert_eq!(
8874 payload["verb"], "link",
8875 "v1 AuditEvent fields must flatten into the v2 payload"
8876 );
8877 }
8878
8879 #[test]
8880 fn link_audit_success_from_result_rejects_incomplete_or_malformed_result() {
8881 let gate_req = GateRequest::new(
8882 ActorRef::anonymous(),
8883 Namespace::local(),
8884 "link",
8885 serde_json::json!({}),
8886 );
8887 let decision = GateDecision::Allow {
8888 obligations: vec![],
8889 };
8890 let audit = AuditEvent::from_check(&gate_req, &decision, "AllowAllGate");
8891
8892 assert!(
8893 link_audit_success_from_result(
8894 audit.clone(),
8895 &serde_json::json!({"id": uuid::Uuid::new_v4()}),
8896 )
8897 .is_none(),
8898 "missing source_id/target_id/relation/weight must not enrich"
8899 );
8900 assert!(
8901 link_audit_success_from_result(audit, &serde_json::json!({"id": "not-a-uuid"}))
8902 .is_none(),
8903 "a non-UUID id must not enrich"
8904 );
8905 }
8906
8907 async fn first_event(store: &Arc<MemoryEventStore>) -> Event {
8917 let page = store
8918 .query_events(
8919 EventFilter::default(),
8920 PageRequest {
8921 limit: 10,
8922 offset: 0,
8923 },
8924 )
8925 .await
8926 .unwrap();
8927 assert_eq!(
8928 page.items.len(),
8929 1,
8930 "expected exactly one persisted audit event"
8931 );
8932 page.items[0].clone()
8933 }
8934
8935 #[tokio::test]
8936 async fn dispatch_with_identity_stamps_request_id_on_success() {
8937 let store = Arc::new(MemoryEventStore::default());
8938 let mut builder = VerbRegistryBuilder::new();
8939 builder.register(AlphaPack);
8940 builder.with_event_store(store.clone());
8941 let reg = builder.build().expect("registry builds");
8942
8943 reg.dispatch_with_identity(
8944 "list",
8945 serde_json::json!({"namespace": "test-ns"}),
8946 Some(RequestIdentity {
8947 request_id: Some(101),
8948 ..Default::default()
8949 }),
8950 )
8951 .await
8952 .unwrap();
8953
8954 let ev = first_event(&store).await;
8955 assert_eq!(ev.outcome, EventOutcome::Success);
8956 assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(101));
8957 }
8958
8959 #[tokio::test]
8960 async fn dispatch_with_identity_stamps_request_id_on_dispatch_error() {
8961 let store = Arc::new(MemoryEventStore::default());
8962 let mut builder = VerbRegistryBuilder::new();
8963 builder.register(FailingProbePack);
8964 builder.with_event_store(store.clone());
8965 let reg = builder.build().expect("registry builds");
8966
8967 let err = reg
8968 .dispatch_with_identity(
8969 "probe",
8970 serde_json::json!({"namespace": "test-ns"}),
8971 Some(RequestIdentity {
8972 request_id: Some(102),
8973 ..Default::default()
8974 }),
8975 )
8976 .await
8977 .unwrap_err();
8978 assert!(matches!(err, RuntimeError::InvalidInput(_)));
8979
8980 let ev = first_event(&store).await;
8981 assert_eq!(ev.outcome, EventOutcome::Error);
8982 assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(102));
8983 }
8984
8985 #[tokio::test]
8986 async fn dispatch_with_identity_stamps_request_id_on_denied() {
8987 #[derive(Debug)]
8988 struct AlwaysDenyGate;
8989 impl Gate for AlwaysDenyGate {
8990 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
8991 Ok(GateDecision::deny("denied by test"))
8992 }
8993 }
8994
8995 let store = Arc::new(MemoryEventStore::default());
8996 let mut builder = VerbRegistryBuilder::new();
8997 builder.register(AlphaPack);
8998 builder.with_gate(Arc::new(AlwaysDenyGate));
8999 builder.with_event_store(store.clone());
9000 let reg = builder.build().expect("registry builds");
9001
9002 let err = reg
9003 .dispatch_with_identity(
9004 "list",
9005 serde_json::json!({"namespace": "test-ns"}),
9006 Some(RequestIdentity {
9007 request_id: Some(103),
9008 ..Default::default()
9009 }),
9010 )
9011 .await
9012 .unwrap_err();
9013 assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
9014
9015 let ev = first_event(&store).await;
9016 assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(103));
9017 }
9018
9019 #[tokio::test]
9020 async fn dispatch_with_identity_stamps_request_id_on_link_v2_success() {
9021 let store = Arc::new(MemoryEventStore::default());
9022 let edge_id = uuid::Uuid::new_v4();
9023 let source_id = uuid::Uuid::new_v4();
9024 let target_id = uuid::Uuid::new_v4();
9025 let edge_json = serde_json::json!({
9026 "id": edge_id,
9027 "namespace": "local",
9028 "source_id": source_id,
9029 "target_id": target_id,
9030 "relation": "depends_on",
9031 "weight": 1.0,
9032 });
9033 let mut builder = VerbRegistryBuilder::new();
9034 builder.register(LinkResultPack::ok(edge_json));
9035 builder.with_event_store(store.clone());
9036 builder.with_default_namespace("test-ns");
9037 let reg = builder.build().expect("registry builds");
9038
9039 reg.dispatch_with_identity(
9040 "link",
9041 serde_json::json!({
9042 "source_id": source_id,
9043 "target_id": target_id,
9044 "relation": "depends_on",
9045 }),
9046 Some(RequestIdentity {
9047 namespace: "test-ns".to_string(),
9048 request_id: Some(104),
9049 ..Default::default()
9050 }),
9051 )
9052 .await
9053 .unwrap();
9054
9055 let ev = first_event(&store).await;
9056 assert_eq!(
9057 ev.payload_schema_version, 2,
9058 "successful singleton link uses audit schema v2"
9059 );
9060 assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(104));
9061 }
9062
9063 #[tokio::test]
9064 async fn dispatch_with_identity_stamps_request_id_on_link_v1_fallback() {
9065 let store = Arc::new(MemoryEventStore::default());
9066 let mut builder = VerbRegistryBuilder::new();
9067 builder.register(LinkResultPack::err("target endpoint not found"));
9068 builder.with_event_store(store.clone());
9069 builder.with_default_namespace("test-ns");
9070 let reg = builder.build().expect("registry builds");
9071
9072 let err = reg
9073 .dispatch_with_identity(
9074 "link",
9075 serde_json::json!({
9076 "source_id": "note:alpha",
9077 "target_id": "note:missing",
9078 "relation": "depends_on",
9079 }),
9080 Some(RequestIdentity {
9081 namespace: "test-ns".to_string(),
9082 request_id: Some(105),
9083 ..Default::default()
9084 }),
9085 )
9086 .await
9087 .unwrap_err();
9088 assert!(matches!(err, RuntimeError::InvalidInput(_)));
9089
9090 let ev = first_event(&store).await;
9091 assert_eq!(
9092 ev.payload_schema_version, 1,
9093 "failed link keeps the v1 audit shape"
9094 );
9095 assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(105));
9096 }
9097
9098 #[tokio::test]
9099 async fn dispatch_with_identity_stamps_request_id_on_unknown_verb() {
9100 let store = Arc::new(MemoryEventStore::default());
9101 let mut builder = VerbRegistryBuilder::new();
9102 builder.register(AlphaPack);
9103 builder.with_event_store(store.clone());
9104 let reg = builder.build().expect("registry builds");
9105
9106 let err = reg
9107 .dispatch_with_identity(
9108 "no_such_verb",
9109 serde_json::json!({}),
9110 Some(RequestIdentity {
9111 namespace: Namespace::local().as_str().to_string(),
9112 request_id: Some(106),
9113 ..Default::default()
9114 }),
9115 )
9116 .await
9117 .unwrap_err();
9118 assert!(matches!(err, RuntimeError::UnknownVerb(_)));
9119
9120 let ev = first_event(&store).await;
9121 assert_eq!(ev.outcome, EventOutcome::Error);
9122 assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(106));
9123 }
9124
9125 #[tokio::test]
9126 async fn dispatch_with_identity_omits_request_id_key_when_absent() {
9127 let store = Arc::new(MemoryEventStore::default());
9128 let mut builder = VerbRegistryBuilder::new();
9129 builder.register(AlphaPack);
9130 builder.with_event_store(store.clone());
9131 let reg = builder.build().expect("registry builds");
9132
9133 reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
9135 .await
9136 .unwrap();
9137
9138 let ev = first_event(&store).await;
9139 let resource = ev.payload["resource"]
9140 .as_object()
9141 .expect("resource must be an object");
9142 assert!(
9143 !resource.contains_key("request_id"),
9144 "request_id key must be entirely absent when no id is supplied, \
9145 not present as null or 0: got {resource:?}"
9146 );
9147 }
9148}
9149
9150#[cfg(test)]
9153mod dep_tests {
9154 use super::*;
9155 use async_trait::async_trait;
9156 use khive_types::Pack;
9157 use serde_json::Value;
9158
9159 struct KgDepPack;
9160 struct MemoryDepPack;
9161 struct ADepPack;
9162 struct BDepPack;
9163
9164 impl Pack for KgDepPack {
9165 const NAME: &'static str = "kg_dep";
9166 const NOTE_KINDS: &'static [&'static str] = &["observation"];
9167 const ENTITY_KINDS: &'static [&'static str] = &["concept"];
9168 const HANDLERS: &'static [HandlerDef] = &[];
9169 }
9170
9171 impl Pack for MemoryDepPack {
9172 const NAME: &'static str = "memory_dep";
9173 const NOTE_KINDS: &'static [&'static str] = &["memory"];
9174 const ENTITY_KINDS: &'static [&'static str] = &[];
9175 const HANDLERS: &'static [HandlerDef] = &[];
9176 const REQUIRES: &'static [&'static str] = &["kg_dep"];
9177 }
9178
9179 impl Pack for ADepPack {
9180 const NAME: &'static str = "pack_a";
9181 const NOTE_KINDS: &'static [&'static str] = &[];
9182 const ENTITY_KINDS: &'static [&'static str] = &[];
9183 const HANDLERS: &'static [HandlerDef] = &[];
9184 const REQUIRES: &'static [&'static str] = &["pack_b"];
9185 }
9186
9187 impl Pack for BDepPack {
9188 const NAME: &'static str = "pack_b";
9189 const NOTE_KINDS: &'static [&'static str] = &[];
9190 const ENTITY_KINDS: &'static [&'static str] = &[];
9191 const HANDLERS: &'static [HandlerDef] = &[];
9192 const REQUIRES: &'static [&'static str] = &["pack_a"];
9193 }
9194
9195 #[async_trait]
9196 impl PackRuntime for KgDepPack {
9197 fn name(&self) -> &str {
9198 Self::NAME
9199 }
9200 fn note_kinds(&self) -> &'static [&'static str] {
9201 Self::NOTE_KINDS
9202 }
9203 fn entity_kinds(&self) -> &'static [&'static str] {
9204 Self::ENTITY_KINDS
9205 }
9206 fn handlers(&self) -> &'static [HandlerDef] {
9207 Self::HANDLERS
9208 }
9209 async fn dispatch(
9210 &self,
9211 verb: &str,
9212 _: Value,
9213 _: &VerbRegistry,
9214 _: &NamespaceToken,
9215 ) -> Result<Value, RuntimeError> {
9216 Err(RuntimeError::InvalidInput(format!(
9217 "KgDepPack has no verbs: {verb}"
9218 )))
9219 }
9220 }
9221
9222 #[async_trait]
9223 impl PackRuntime for MemoryDepPack {
9224 fn name(&self) -> &str {
9225 Self::NAME
9226 }
9227 fn note_kinds(&self) -> &'static [&'static str] {
9228 Self::NOTE_KINDS
9229 }
9230 fn entity_kinds(&self) -> &'static [&'static str] {
9231 Self::ENTITY_KINDS
9232 }
9233 fn handlers(&self) -> &'static [HandlerDef] {
9234 Self::HANDLERS
9235 }
9236 fn requires(&self) -> &'static [&'static str] {
9237 Self::REQUIRES
9238 }
9239 async fn dispatch(
9240 &self,
9241 verb: &str,
9242 _: Value,
9243 _: &VerbRegistry,
9244 _: &NamespaceToken,
9245 ) -> Result<Value, RuntimeError> {
9246 Err(RuntimeError::InvalidInput(format!(
9247 "MemoryDepPack has no verbs: {verb}"
9248 )))
9249 }
9250 }
9251
9252 #[async_trait]
9253 impl PackRuntime for ADepPack {
9254 fn name(&self) -> &str {
9255 Self::NAME
9256 }
9257 fn note_kinds(&self) -> &'static [&'static str] {
9258 Self::NOTE_KINDS
9259 }
9260 fn entity_kinds(&self) -> &'static [&'static str] {
9261 Self::ENTITY_KINDS
9262 }
9263 fn handlers(&self) -> &'static [HandlerDef] {
9264 Self::HANDLERS
9265 }
9266 fn requires(&self) -> &'static [&'static str] {
9267 Self::REQUIRES
9268 }
9269 async fn dispatch(
9270 &self,
9271 verb: &str,
9272 _: Value,
9273 _: &VerbRegistry,
9274 _: &NamespaceToken,
9275 ) -> Result<Value, RuntimeError> {
9276 Err(RuntimeError::InvalidInput(format!(
9277 "ADepPack has no verbs: {verb}"
9278 )))
9279 }
9280 }
9281
9282 #[async_trait]
9283 impl PackRuntime for BDepPack {
9284 fn name(&self) -> &str {
9285 Self::NAME
9286 }
9287 fn note_kinds(&self) -> &'static [&'static str] {
9288 Self::NOTE_KINDS
9289 }
9290 fn entity_kinds(&self) -> &'static [&'static str] {
9291 Self::ENTITY_KINDS
9292 }
9293 fn handlers(&self) -> &'static [HandlerDef] {
9294 Self::HANDLERS
9295 }
9296 fn requires(&self) -> &'static [&'static str] {
9297 Self::REQUIRES
9298 }
9299 async fn dispatch(
9300 &self,
9301 verb: &str,
9302 _: Value,
9303 _: &VerbRegistry,
9304 _: &NamespaceToken,
9305 ) -> Result<Value, RuntimeError> {
9306 Err(RuntimeError::InvalidInput(format!(
9307 "BDepPack has no verbs: {verb}"
9308 )))
9309 }
9310 }
9311
9312 #[test]
9313 fn test_pack_deps_happy_path() {
9314 let mut builder = VerbRegistryBuilder::new();
9315 builder.register(MemoryDepPack);
9316 builder.register(KgDepPack);
9317 let reg = builder
9318 .build()
9319 .expect("kg_dep satisfies memory_dep dependency");
9320 assert_eq!(reg.pack_requires("memory_dep").unwrap(), &["kg_dep"]);
9321 let names = reg.pack_names();
9322 let kg_pos = names.iter().position(|&n| n == "kg_dep").unwrap();
9323 let mem_pos = names.iter().position(|&n| n == "memory_dep").unwrap();
9324 assert!(
9325 kg_pos < mem_pos,
9326 "kg_dep must be loaded before memory_dep; order: {names:?}"
9327 );
9328 }
9329
9330 #[test]
9331 fn test_pack_deps_missing() {
9332 let mut builder = VerbRegistryBuilder::new();
9333 builder.register(MemoryDepPack);
9334 let err = match builder.build() {
9335 Ok(_) => panic!("expected Err, got Ok"),
9336 Err(e) => e,
9337 };
9338 assert!(
9339 matches!(err, RuntimeError::MissingPackDependency(_)),
9340 "expected MissingPackDependency, got {err:?}"
9341 );
9342 let msg = err.to_string();
9343 assert!(
9344 msg.contains("memory_dep"),
9345 "error must name the dependent pack: {msg}"
9346 );
9347 assert!(
9348 msg.contains("kg_dep"),
9349 "error must name the missing dep: {msg}"
9350 );
9351 }
9352
9353 #[test]
9354 fn test_pack_deps_circular() {
9355 let mut builder = VerbRegistryBuilder::new();
9356 builder.register(ADepPack);
9357 builder.register(BDepPack);
9358 let err = match builder.build() {
9359 Ok(_) => panic!("expected Err, got Ok"),
9360 Err(e) => e,
9361 };
9362 assert!(
9363 matches!(err, RuntimeError::CircularPackDependency(_)),
9364 "expected CircularPackDependency, got {err:?}"
9365 );
9366 let msg = err.to_string();
9367 assert!(msg.contains("pack_a"), "error must name pack_a: {msg}");
9368 assert!(msg.contains("pack_b"), "error must name pack_b: {msg}");
9369 }
9370
9371 #[test]
9372 fn test_pack_deps_no_deps() {
9373 struct NoDepsA;
9374 struct NoDepsB;
9375
9376 impl Pack for NoDepsA {
9377 const NAME: &'static str = "no_deps_a";
9378 const NOTE_KINDS: &'static [&'static str] = &[];
9379 const ENTITY_KINDS: &'static [&'static str] = &[];
9380 const HANDLERS: &'static [HandlerDef] = &[];
9381 }
9382
9383 impl Pack for NoDepsB {
9384 const NAME: &'static str = "no_deps_b";
9385 const NOTE_KINDS: &'static [&'static str] = &[];
9386 const ENTITY_KINDS: &'static [&'static str] = &[];
9387 const HANDLERS: &'static [HandlerDef] = &[];
9388 }
9389
9390 #[async_trait]
9391 impl PackRuntime for NoDepsA {
9392 fn name(&self) -> &str {
9393 Self::NAME
9394 }
9395 fn note_kinds(&self) -> &'static [&'static str] {
9396 Self::NOTE_KINDS
9397 }
9398 fn entity_kinds(&self) -> &'static [&'static str] {
9399 Self::ENTITY_KINDS
9400 }
9401 fn handlers(&self) -> &'static [HandlerDef] {
9402 Self::HANDLERS
9403 }
9404 async fn dispatch(
9405 &self,
9406 verb: &str,
9407 _: Value,
9408 _: &VerbRegistry,
9409 _: &NamespaceToken,
9410 ) -> Result<Value, RuntimeError> {
9411 Err(RuntimeError::InvalidInput(format!("NoDepsA: {verb}")))
9412 }
9413 }
9414
9415 #[async_trait]
9416 impl PackRuntime for NoDepsB {
9417 fn name(&self) -> &str {
9418 Self::NAME
9419 }
9420 fn note_kinds(&self) -> &'static [&'static str] {
9421 Self::NOTE_KINDS
9422 }
9423 fn entity_kinds(&self) -> &'static [&'static str] {
9424 Self::ENTITY_KINDS
9425 }
9426 fn handlers(&self) -> &'static [HandlerDef] {
9427 Self::HANDLERS
9428 }
9429 async fn dispatch(
9430 &self,
9431 verb: &str,
9432 _: Value,
9433 _: &VerbRegistry,
9434 _: &NamespaceToken,
9435 ) -> Result<Value, RuntimeError> {
9436 Err(RuntimeError::InvalidInput(format!("NoDepsB: {verb}")))
9437 }
9438 }
9439
9440 let mut builder = VerbRegistryBuilder::new();
9441 builder.register(NoDepsA);
9442 builder.register(NoDepsB);
9443 let reg = builder.build().expect("packs with REQUIRES=&[] build");
9444 assert_eq!(reg.pack_requires("no_deps_a").unwrap(), &[] as &[&str]);
9445 assert_eq!(reg.pack_requires("no_deps_b").unwrap(), &[] as &[&str]);
9446 }
9447}
9448
9449#[cfg(test)]
9452mod hook_tests {
9453 use super::*;
9454 use async_trait::async_trait;
9455 use khive_types::Pack;
9456 use std::sync::atomic::{AtomicUsize, Ordering};
9457 use std::sync::Mutex as StdMutex;
9458
9459 struct SimplePack;
9460
9461 impl Pack for SimplePack {
9462 const NAME: &'static str = "simple";
9463 const NOTE_KINDS: &'static [&'static str] = &[];
9464 const ENTITY_KINDS: &'static [&'static str] = &[];
9465 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
9466 name: "ping",
9467 description: "ping",
9468 visibility: Visibility::Verb,
9469 category: VerbCategory::Assertive,
9470 params: &[],
9471 }];
9472 }
9473
9474 #[async_trait]
9475 impl PackRuntime for SimplePack {
9476 fn name(&self) -> &str {
9477 SimplePack::NAME
9478 }
9479 fn note_kinds(&self) -> &'static [&'static str] {
9480 SimplePack::NOTE_KINDS
9481 }
9482 fn entity_kinds(&self) -> &'static [&'static str] {
9483 SimplePack::ENTITY_KINDS
9484 }
9485 fn handlers(&self) -> &'static [HandlerDef] {
9486 SimplePack::HANDLERS
9487 }
9488 async fn dispatch(
9489 &self,
9490 verb: &str,
9491 _params: Value,
9492 _registry: &VerbRegistry,
9493 _token: &NamespaceToken,
9494 ) -> Result<Value, RuntimeError> {
9495 Ok(serde_json::json!({ "verb": verb }))
9496 }
9497 }
9498
9499 struct RecallPack;
9500
9501 impl Pack for RecallPack {
9502 const NAME: &'static str = "memory";
9503 const NOTE_KINDS: &'static [&'static str] = &[];
9504 const ENTITY_KINDS: &'static [&'static str] = &[];
9505 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
9506 name: "memory.recall",
9507 description: "test recall",
9508 visibility: Visibility::Verb,
9509 category: VerbCategory::Assertive,
9510 params: &[],
9511 }];
9512 }
9513
9514 #[async_trait]
9515 impl PackRuntime for RecallPack {
9516 fn name(&self) -> &str {
9517 RecallPack::NAME
9518 }
9519 fn note_kinds(&self) -> &'static [&'static str] {
9520 RecallPack::NOTE_KINDS
9521 }
9522 fn entity_kinds(&self) -> &'static [&'static str] {
9523 RecallPack::ENTITY_KINDS
9524 }
9525 fn handlers(&self) -> &'static [HandlerDef] {
9526 RecallPack::HANDLERS
9527 }
9528 async fn dispatch(
9529 &self,
9530 _verb: &str,
9531 params: Value,
9532 _registry: &VerbRegistry,
9533 _token: &NamespaceToken,
9534 ) -> Result<Value, RuntimeError> {
9535 let hit = serde_json::json!({
9536 "id": uuid::Uuid::new_v4().to_string(),
9537 "served_by_profile_id": "custom-recall-v1",
9538 "serve_attribution": "profile",
9539 });
9540 if params.get("verbose").and_then(Value::as_bool) == Some(true) {
9541 Ok(serde_json::json!({"results": [hit]}))
9542 } else {
9543 Ok(serde_json::json!([hit]))
9544 }
9545 }
9546 }
9547
9548 #[derive(Default)]
9549 struct EventCapturingHook {
9550 event: StdMutex<Option<Event>>,
9551 }
9552
9553 #[async_trait]
9554 impl DispatchHook for EventCapturingHook {
9555 async fn on_dispatch(&self, view: &EventView) {
9556 *self.event.lock().unwrap() = Some(view.event.clone());
9557 }
9558 }
9559
9560 #[derive(Default)]
9562 struct CountingHook {
9563 calls: AtomicUsize,
9564 last_verb: StdMutex<String>,
9565 }
9566
9567 #[async_trait]
9568 impl DispatchHook for CountingHook {
9569 async fn on_dispatch(&self, view: &EventView) {
9570 self.calls.fetch_add(1, Ordering::SeqCst);
9571 *self.last_verb.lock().unwrap() = view.event.verb.clone();
9572 }
9573 }
9574
9575 #[tokio::test]
9576 async fn dispatch_hook_fires_on_successful_dispatch() {
9577 let hook = Arc::new(CountingHook::default());
9578 let mut builder = VerbRegistryBuilder::new();
9579 builder.register(SimplePack);
9580 builder.with_dispatch_hook(hook.clone());
9581 let reg = builder.build().expect("registry builds");
9582
9583 reg.dispatch("ping", Value::Null).await.unwrap();
9584
9585 assert_eq!(
9586 hook.calls.load(Ordering::SeqCst),
9587 1,
9588 "hook must fire once per successful dispatch"
9589 );
9590 assert_eq!(
9591 hook.last_verb.lock().unwrap().as_str(),
9592 "ping",
9593 "hook event must carry the dispatched verb"
9594 );
9595 }
9596
9597 #[tokio::test]
9598 async fn dispatch_hook_fires_multiple_times() {
9599 let hook = Arc::new(CountingHook::default());
9600 let mut builder = VerbRegistryBuilder::new();
9601 builder.register(SimplePack);
9602 builder.with_dispatch_hook(hook.clone());
9603 let reg = builder.build().expect("registry builds");
9604
9605 reg.dispatch("ping", Value::Null).await.unwrap();
9606 reg.dispatch("ping", Value::Null).await.unwrap();
9607 reg.dispatch("ping", Value::Null).await.unwrap();
9608
9609 assert_eq!(
9610 hook.calls.load(Ordering::SeqCst),
9611 3,
9612 "hook must fire once per successful dispatch"
9613 );
9614 }
9615
9616 #[tokio::test]
9617 async fn recall_hook_copies_serve_attribution_from_bare_and_verbose_results() {
9618 let hook = Arc::new(EventCapturingHook::default());
9619 let mut builder = VerbRegistryBuilder::new();
9620 builder.register(RecallPack);
9621 builder.with_dispatch_hook(hook.clone());
9622 let reg = builder.build().expect("registry builds");
9623
9624 for params in [serde_json::json!({}), serde_json::json!({"verbose": true})] {
9625 reg.dispatch("memory.recall", params)
9626 .await
9627 .expect("recall dispatch");
9628 let event = hook.event.lock().unwrap().clone().expect("hook event");
9629 assert!(
9630 event.target_id.is_some(),
9631 "first recall id must become target"
9632 );
9633 assert_eq!(
9634 event.payload["served_by_profile_id"],
9635 serde_json::json!("custom-recall-v1")
9636 );
9637 assert_eq!(
9638 event.payload["serve_attribution"],
9639 serde_json::json!("profile")
9640 );
9641 }
9642 }
9643
9644 #[tokio::test]
9645 async fn dispatch_hook_does_not_fire_on_unknown_verb() {
9646 let hook = Arc::new(CountingHook::default());
9647 let mut builder = VerbRegistryBuilder::new();
9648 builder.register(SimplePack);
9649 builder.with_dispatch_hook(hook.clone());
9650 let reg = builder.build().expect("registry builds");
9651
9652 let _ = reg.dispatch("nonexistent", Value::Null).await;
9653
9654 assert_eq!(
9655 hook.calls.load(Ordering::SeqCst),
9656 0,
9657 "hook must NOT fire for unknown verb (dispatch returns error)"
9658 );
9659 }
9660
9661 #[tokio::test]
9662 async fn dispatch_hook_does_not_fire_on_gate_deny() {
9663 use khive_gate::{Gate, GateDecision, GateError};
9664
9665 #[derive(Debug)]
9666 struct AlwaysDenyGate;
9667 impl Gate for AlwaysDenyGate {
9668 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
9669 Ok(GateDecision::deny("test deny"))
9670 }
9671 }
9672
9673 let hook = Arc::new(CountingHook::default());
9674 let mut builder = VerbRegistryBuilder::new();
9675 builder.register(SimplePack);
9676 builder.with_gate(Arc::new(AlwaysDenyGate));
9677 builder.with_dispatch_hook(hook.clone());
9678 let reg = builder.build().expect("registry builds");
9679
9680 let err = reg.dispatch("ping", Value::Null).await.unwrap_err();
9681 assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
9682
9683 assert_eq!(
9684 hook.calls.load(Ordering::SeqCst),
9685 0,
9686 "hook must NOT fire when gate denies dispatch"
9687 );
9688 }
9689
9690 #[tokio::test]
9691 async fn dispatch_hook_event_carries_namespace_from_params() {
9692 let hook = Arc::new(CountingHook::default());
9693
9694 #[derive(Default)]
9695 struct NsCapturingHook {
9696 ns: StdMutex<String>,
9697 }
9698
9699 #[async_trait]
9700 impl DispatchHook for NsCapturingHook {
9701 async fn on_dispatch(&self, view: &EventView) {
9702 *self.ns.lock().unwrap() = view.event.namespace.clone();
9703 }
9704 }
9705
9706 let ns_hook = Arc::new(NsCapturingHook::default());
9707 let mut builder = VerbRegistryBuilder::new();
9708 builder.register(SimplePack);
9709 builder.with_dispatch_hook(ns_hook.clone());
9710 let reg = builder.build().expect("registry builds");
9711
9712 reg.dispatch("ping", serde_json::json!({"namespace": "tenant-abc"}))
9713 .await
9714 .unwrap();
9715
9716 assert_eq!(
9717 ns_hook.ns.lock().unwrap().as_str(),
9718 "tenant-abc",
9719 "dispatch hook event must carry the resolved namespace"
9720 );
9721
9722 drop(hook);
9724 }
9725
9726 #[tokio::test]
9727 async fn no_dispatch_hook_configured_dispatch_succeeds() {
9728 let mut builder = VerbRegistryBuilder::new();
9730 builder.register(SimplePack);
9731 let reg = builder.build().expect("registry builds");
9733
9734 let res = reg.dispatch("ping", Value::Null).await.unwrap();
9735 assert_eq!(res["verb"], "ping");
9736 }
9737}
9738
9739#[cfg(test)]
9742mod help_tests {
9743 use super::*;
9744 use async_trait::async_trait;
9745 use khive_types::Pack;
9746 use std::sync::{
9747 atomic::{AtomicUsize, Ordering},
9748 Arc,
9749 };
9750
9751 static CREATE_PARAMS: [ParamDef; 2] = [
9756 ParamDef {
9757 name: "kind",
9758 param_type: "string",
9759 required: true,
9760 description: "Granular kind (concept | document | ...).",
9761 },
9762 ParamDef {
9763 name: "name",
9764 param_type: "string",
9765 required: false,
9766 description: "Human-readable name.",
9767 },
9768 ];
9769
9770 static RECALL_PARAMS: [ParamDef; 2] = [
9771 ParamDef {
9772 name: "query",
9773 param_type: "string",
9774 required: true,
9775 description: "Semantic recall query.",
9776 },
9777 ParamDef {
9778 name: "limit",
9779 param_type: "integer",
9780 required: false,
9781 description: "Maximum memories to return.",
9782 },
9783 ];
9784
9785 static EMBED_PARAMS: [ParamDef; 0] = [];
9788
9789 struct HelpPack {
9790 invocations: Arc<AtomicUsize>,
9791 }
9792
9793 impl Pack for HelpPack {
9794 const NAME: &'static str = "helptest";
9795 const NOTE_KINDS: &'static [&'static str] = &[];
9796 const ENTITY_KINDS: &'static [&'static str] = &[];
9797 const HANDLERS: &'static [HandlerDef] = &[
9798 HandlerDef {
9799 name: "create",
9800 description: "Create an entity or note",
9801 visibility: Visibility::Verb,
9802 category: VerbCategory::Commissive,
9803 params: &CREATE_PARAMS,
9804 },
9805 HandlerDef {
9806 name: "recall",
9807 description: "Recall memory notes with decay-aware hybrid ranking",
9808 visibility: Visibility::Verb,
9809 category: VerbCategory::Assertive,
9810 params: &RECALL_PARAMS,
9811 },
9812 HandlerDef {
9815 name: "recall.embed",
9816 description: "Return the embedding vector used by memory recall",
9817 visibility: Visibility::Subhandler,
9818 category: VerbCategory::Assertive,
9819 params: &EMBED_PARAMS,
9820 },
9821 HandlerDef {
9822 name: "link",
9823 description: "Create a typed directed edge",
9824 visibility: Visibility::Verb,
9825 category: VerbCategory::Commissive,
9826 params: &[],
9827 },
9828 ];
9829 }
9830
9831 static HELP_EDGE_RULES: [EdgeEndpointRule; 2] = [
9839 EdgeEndpointRule {
9840 relation: khive_types::EdgeRelation::DependsOn,
9841 source: EndpointKind::NoteOfKind("task"),
9842 target: EndpointKind::NoteOfKind("task"),
9843 },
9844 EdgeEndpointRule {
9845 relation: khive_types::EdgeRelation::Supersedes,
9846 source: EndpointKind::NoteOfKind("task"),
9847 target: EndpointKind::NoteOfKind("task"),
9848 },
9849 ];
9850
9851 #[async_trait]
9852 impl PackRuntime for HelpPack {
9853 fn name(&self) -> &str {
9854 HelpPack::NAME
9855 }
9856 fn note_kinds(&self) -> &'static [&'static str] {
9857 HelpPack::NOTE_KINDS
9858 }
9859 fn entity_kinds(&self) -> &'static [&'static str] {
9860 HelpPack::ENTITY_KINDS
9861 }
9862 fn handlers(&self) -> &'static [HandlerDef] {
9863 HelpPack::HANDLERS
9864 }
9865 fn edge_rules(&self) -> &'static [EdgeEndpointRule] {
9866 &HELP_EDGE_RULES
9867 }
9868 async fn dispatch(
9869 &self,
9870 verb: &str,
9871 _params: Value,
9872 _registry: &VerbRegistry,
9873 _token: &NamespaceToken,
9874 ) -> Result<Value, RuntimeError> {
9875 self.invocations.fetch_add(1, Ordering::SeqCst);
9876 Ok(serde_json::json!({ "pack": "helptest", "verb": verb }))
9877 }
9878 }
9879
9880 fn build_help_registry(invocations: Arc<AtomicUsize>) -> VerbRegistry {
9881 let mut builder = VerbRegistryBuilder::new();
9882 builder.register(HelpPack { invocations });
9883 builder.build().expect("help registry builds")
9884 }
9885
9886 #[tokio::test]
9889 async fn test_help_true_returns_schema_for_kg_create() {
9890 let invocations = Arc::new(AtomicUsize::new(0));
9891 let reg = build_help_registry(invocations.clone());
9892
9893 let result = reg
9894 .dispatch("create", serde_json::json!({ "help": true }))
9895 .await
9896 .expect("help=true must succeed for a known verb");
9897
9898 assert_eq!(result["verb"], "create", "envelope must name the verb");
9900 assert_eq!(
9901 result["pack"], "helptest",
9902 "envelope must name the owning pack"
9903 );
9904 assert!(
9905 result["description"].as_str().is_some(),
9906 "description must be a string"
9907 );
9908
9909 let params = result["params"]
9911 .as_array()
9912 .expect("params must be a JSON array");
9913 assert!(!params.is_empty(), "params array must not be empty");
9914
9915 let kind_param = params.iter().find(|p| p["name"] == "kind");
9917 assert!(
9918 kind_param.is_some(),
9919 "params array must include the 'kind' parameter"
9920 );
9921 let kind_param = kind_param.unwrap();
9922 assert_eq!(
9923 kind_param["required"],
9924 serde_json::json!(true),
9925 "'kind' must be required"
9926 );
9927 assert_eq!(kind_param["type"], "string", "'kind' type must be 'string'");
9928
9929 let identifier_help = result["identifier_resolution"]
9930 .as_object()
9931 .expect("help=true must include the shared identifier contract");
9932 assert!(identifier_help["full_uuid"]
9933 .as_str()
9934 .is_some_and(|text| text.contains("globally unique")));
9935 assert!(identifier_help["short_prefix"]
9936 .as_str()
9937 .is_some_and(|text| text.contains("lookup scope belongs to the consuming parameter")));
9938 assert!(identifier_help["parameter_rule"]
9939 .as_str()
9940 .is_some_and(|text| text.contains("submitted again")));
9941 }
9942
9943 #[tokio::test]
9945 async fn test_help_true_returns_schema_for_recall() {
9946 let invocations = Arc::new(AtomicUsize::new(0));
9947 let reg = build_help_registry(invocations.clone());
9948
9949 let result = reg
9950 .dispatch("recall", serde_json::json!({ "help": true }))
9951 .await
9952 .expect("help=true must succeed for recall");
9953
9954 assert_eq!(result["verb"], "recall");
9955 assert_eq!(result["pack"], "helptest");
9956
9957 let params = result["params"]
9958 .as_array()
9959 .expect("params must be a JSON array");
9960
9961 let query_param = params.iter().find(|p| p["name"] == "query");
9963 assert!(query_param.is_some(), "params must include 'query'");
9964 let query_param = query_param.unwrap();
9965 assert_eq!(
9966 query_param["required"],
9967 serde_json::json!(true),
9968 "'query' must be required"
9969 );
9970
9971 let limit_param = params.iter().find(|p| p["name"] == "limit");
9973 assert!(limit_param.is_some(), "params must include 'limit'");
9974 let limit_param = limit_param.unwrap();
9975 assert_eq!(
9976 limit_param["required"],
9977 serde_json::json!(false),
9978 "'limit' must be optional"
9979 );
9980 }
9981
9982 #[tokio::test]
9988 async fn test_link_help_true_exposes_endpoint_rules() {
9989 let invocations = Arc::new(AtomicUsize::new(0));
9990 let reg = build_help_registry(invocations.clone());
9991
9992 let result = reg
9993 .dispatch("link", serde_json::json!({ "help": true }))
9994 .await
9995 .expect("help=true must succeed for link");
9996
9997 assert_eq!(result["verb"], "link");
9998 let rules = result["endpoint_rules"]
9999 .as_array()
10000 .expect("link help must include an endpoint_rules array");
10001 assert!(!rules.is_empty(), "endpoint_rules must not be empty");
10002
10003 assert!(
10005 rules.iter().any(|r| r["relation"] == "contains"
10006 && r["source"] == "entity:concept"
10007 && r["target"] == "entity:concept"),
10008 "endpoint_rules must include the base 'contains' entity rule; got {rules:#?}"
10009 );
10010
10011 assert!(
10013 rules.iter().any(|r| r["relation"] == "depends_on"
10014 && r["source"] == "note:task"
10015 && r["target"] == "note:task"),
10016 "endpoint_rules must include the pack-declared depends_on rule; got {rules:#?}"
10017 );
10018
10019 assert!(
10021 rules
10022 .iter()
10023 .any(|r| r["relation"] == "annotates" && r["source"] == "note:*"),
10024 "endpoint_rules must document the annotates note-to-any rule; got {rules:#?}"
10025 );
10026
10027 assert_eq!(
10029 invocations.load(Ordering::SeqCst),
10030 0,
10031 "link(help=true) must not invoke pack dispatch"
10032 );
10033 }
10034
10035 #[tokio::test]
10054 async fn test_link_help_true_matches_special_relation_validator_set() {
10055 let invocations = Arc::new(AtomicUsize::new(0));
10056 let reg = build_help_registry(invocations.clone());
10057
10058 let result = reg
10059 .dispatch("link", serde_json::json!({ "help": true }))
10060 .await
10061 .expect("help=true must succeed for link");
10062
10063 let rules = result["endpoint_rules"]
10064 .as_array()
10065 .expect("link help must include an endpoint_rules array");
10066
10067 for relation in ["supersedes", "supports", "refutes"] {
10068 assert!(
10070 rules.iter().any(|r| r["relation"] == relation
10071 && r["source"] == "note:*"
10072 && r["target"] == "note:*"),
10073 "endpoint_rules must include the note:*->note:* row for '{relation}' \
10074 (validator accepts any note->note pair unconditionally); got {rules:#?}"
10075 );
10076
10077 assert!(
10082 !rules.iter().any(|r| r["relation"] == relation
10083 && r["source"] == "note:task"
10084 && r["target"] == "note:task"),
10085 "endpoint_rules must NOT advertise a pack EDGE_RULES row for special \
10086 relation '{relation}' — validate_edge_relation_endpoints never consults \
10087 pack_rule_allows for supersedes/supports/refutes; got {rules:#?}"
10088 );
10089 }
10090
10091 for (relation, kind) in [
10094 ("supersedes", "concept"),
10095 ("supports", "concept"),
10096 ("refutes", "concept"),
10097 ] {
10098 assert!(
10099 rules.iter().any(|r| r["relation"] == relation
10100 && r["source"] == format!("entity:{kind}")
10101 && r["target"] == "entity:concept"),
10102 "endpoint_rules must include the base entity:{kind}->entity:concept row \
10103 for '{relation}'; got {rules:#?}"
10104 );
10105 }
10106 }
10107
10108 #[test]
10109 fn special_relation_predicate_matches_the_dedicated_validator_set() {
10110 for relation in khive_types::EdgeRelation::ALL {
10111 assert_eq!(
10112 is_special_relation(relation),
10113 matches!(
10114 relation,
10115 khive_types::EdgeRelation::Supersedes
10116 | khive_types::EdgeRelation::Supports
10117 | khive_types::EdgeRelation::Refutes
10118 ),
10119 "unexpected special-relation classification for {relation}"
10120 );
10121 }
10122 }
10123
10124 #[tokio::test]
10127 async fn test_help_true_does_not_execute_the_verb() {
10128 let invocations = Arc::new(AtomicUsize::new(0));
10129 let reg = build_help_registry(invocations.clone());
10130
10131 reg.dispatch("create", serde_json::json!({ "help": true }))
10133 .await
10134 .expect("help=true must succeed");
10135 reg.dispatch("recall", serde_json::json!({ "help": true }))
10136 .await
10137 .expect("help=true must succeed");
10138
10139 assert_eq!(
10140 invocations.load(Ordering::SeqCst),
10141 0,
10142 "pack dispatch MUST NOT be invoked when help=true; \
10143 got {} invocation(s)",
10144 invocations.load(Ordering::SeqCst)
10145 );
10146
10147 reg.dispatch("create", serde_json::json!({}))
10149 .await
10150 .expect("normal dispatch must succeed");
10151 assert_eq!(
10152 invocations.load(Ordering::SeqCst),
10153 1,
10154 "pack dispatch must fire exactly once for a normal call"
10155 );
10156 }
10157
10158 #[tokio::test]
10167 async fn help_true_on_subhandler_returns_callable_via_mcp_false() {
10168 let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
10169
10170 let result = reg
10171 .dispatch("recall.embed", serde_json::json!({ "help": true }))
10172 .await
10173 .expect("help=true on subhandler must succeed (no permission check on help path)");
10174
10175 assert_eq!(
10176 result["callable_via_mcp"],
10177 serde_json::json!(false),
10178 "subhandler help must carry callable_via_mcp: false"
10179 );
10180 assert_eq!(
10181 result["visibility"], "internal",
10182 "subhandler help must carry visibility: internal"
10183 );
10184 assert_eq!(result["verb"], "recall.embed");
10187 assert_eq!(result["pack"], "helptest");
10188 }
10189
10190 #[tokio::test]
10192 async fn help_true_on_public_verb_does_not_have_callable_via_mcp_false() {
10193 let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
10194
10195 let result = reg
10196 .dispatch("create", serde_json::json!({ "help": true }))
10197 .await
10198 .expect("help=true on public verb must succeed");
10199
10200 assert_ne!(
10202 result.get("callable_via_mcp"),
10203 Some(&serde_json::json!(false)),
10204 "public verb help must NOT carry callable_via_mcp: false"
10205 );
10206 assert_ne!(
10208 result.get("visibility"),
10209 Some(&serde_json::json!("internal")),
10210 "public verb help must NOT carry visibility: internal"
10211 );
10212 }
10213
10214 #[tokio::test]
10216 async fn help_true_on_unknown_verb_returns_error() {
10217 let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
10218
10219 let err = reg
10220 .dispatch("nonexistent_verb", serde_json::json!({ "help": true }))
10221 .await
10222 .unwrap_err();
10223
10224 assert!(
10225 matches!(err, RuntimeError::UnknownVerb(_)),
10226 "help=true on unknown verb must return UnknownVerb, got {err:?}"
10227 );
10228 let msg = err.to_string();
10229 assert!(
10230 msg.contains("nonexistent_verb"),
10231 "error must name the unknown verb: {msg}"
10232 );
10233 }
10234
10235 #[tokio::test]
10237 async fn help_true_on_subhandler_includes_params_field() {
10238 let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
10239
10240 let result = reg
10241 .dispatch("recall.embed", serde_json::json!({ "help": true }))
10242 .await
10243 .expect("help=true on subhandler must succeed");
10244
10245 let params = result
10247 .get("params")
10248 .expect("subhandler help must include 'params' field");
10249 assert!(
10250 params.is_array(),
10251 "subhandler help params must be a JSON array"
10252 );
10253 }
10254
10255 #[tokio::test]
10260 async fn help_true_unknown_verb_available_list_excludes_subhandlers() {
10261 let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
10262
10263 let err = reg
10264 .dispatch("not_a_verb", serde_json::json!({ "help": true }))
10265 .await
10266 .unwrap_err();
10267
10268 let msg = err.to_string();
10269 assert!(
10272 !msg.contains("recall.embed"),
10273 "unknown-verb help error must not advertise subhandler recall.embed: {msg}"
10274 );
10275 assert!(
10277 msg.contains("create"),
10278 "unknown-verb help error must still list public verb 'create': {msg}"
10279 );
10280 assert!(
10281 msg.contains("recall"),
10282 "unknown-verb help error must still list public verb 'recall': {msg}"
10283 );
10284 }
10285
10286 #[tokio::test]
10288 async fn dispatch_unknown_verb_available_list_excludes_subhandlers() {
10289 let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
10290
10291 let err = reg
10292 .dispatch("not_a_verb", serde_json::json!({}))
10293 .await
10294 .unwrap_err();
10295
10296 let msg = err.to_string();
10297 assert!(
10300 !msg.contains("recall.embed"),
10301 "dispatch unknown-verb error must not advertise subhandler recall.embed: {msg}"
10302 );
10303 assert!(
10305 msg.contains("create"),
10306 "dispatch unknown-verb error must still list public verb 'create': {msg}"
10307 );
10308 assert!(
10309 msg.contains("recall"),
10310 "dispatch unknown-verb error must still list public verb 'recall': {msg}"
10311 );
10312 }
10313
10314 struct SchemaPack {
10318 pack_name: &'static str,
10319 statements: &'static [&'static str],
10320 }
10321
10322 impl Pack for SchemaPack {
10323 const NAME: &'static str = "schema-pack";
10324 const NOTE_KINDS: &'static [&'static str] = &[];
10325 const ENTITY_KINDS: &'static [&'static str] = &[];
10326 const HANDLERS: &'static [HandlerDef] = &[];
10327 }
10328
10329 #[async_trait]
10330 impl PackRuntime for SchemaPack {
10331 fn name(&self) -> &str {
10332 self.pack_name
10333 }
10334 fn note_kinds(&self) -> &'static [&'static str] {
10335 &[]
10336 }
10337 fn entity_kinds(&self) -> &'static [&'static str] {
10338 &[]
10339 }
10340 fn handlers(&self) -> &'static [HandlerDef] {
10341 &[]
10342 }
10343 fn schema_plan(&self) -> SchemaPlan {
10344 SchemaPlan {
10345 pack: self.pack_name,
10346 statements: self.statements,
10347 }
10348 }
10349 async fn dispatch(
10350 &self,
10351 verb: &str,
10352 _params: Value,
10353 _registry: &VerbRegistry,
10354 _token: &NamespaceToken,
10355 ) -> Result<Value, RuntimeError> {
10356 Ok(serde_json::json!({ "pack": self.pack_name, "verb": verb }))
10357 }
10358 }
10359
10360 #[test]
10363 fn all_schema_plans_named_returns_correct_pairs() {
10364 let mut builder = VerbRegistryBuilder::new();
10365 builder.register_boxed(Box::new(SchemaPack {
10366 pack_name: "alpha",
10367 statements: &["CREATE TABLE IF NOT EXISTS t_alpha (id INTEGER PRIMARY KEY)"],
10368 }));
10369 builder.register_boxed(Box::new(SchemaPack {
10370 pack_name: "beta",
10371 statements: &[],
10372 }));
10373 let reg = builder.build().expect("registry builds");
10374
10375 let named = reg.all_schema_plans_named();
10376 assert_eq!(named.len(), 2);
10377
10378 let alpha_entry = named.iter().find(|(n, _)| *n == "alpha");
10379 let beta_entry = named.iter().find(|(n, _)| *n == "beta");
10380
10381 assert!(alpha_entry.is_some(), "alpha must appear in named plans");
10382 assert!(beta_entry.is_some(), "beta must appear in named plans");
10383
10384 let (_, alpha_plan) = alpha_entry.unwrap();
10385 assert_eq!(alpha_plan.statements.len(), 1);
10386 assert!(!alpha_plan.is_empty());
10387
10388 let (_, beta_plan) = beta_entry.unwrap();
10389 assert!(beta_plan.is_empty());
10390 }
10391
10392 #[tokio::test]
10409 async fn apply_schema_plans_with_map_routes_to_correct_backend() {
10410 use khive_storage::types::{SqlStatement, SqlValue};
10411
10412 let default_backend = khive_db::StorageBackend::memory().expect("default memory backend");
10413 let pack_backend =
10414 khive_db::StorageBackend::memory().expect("pack-specific memory backend");
10415
10416 let mut builder = VerbRegistryBuilder::new();
10417 builder.register_boxed(Box::new(SchemaPack {
10418 pack_name: "routed",
10419 statements: &["CREATE TABLE IF NOT EXISTS t_routed (id INTEGER PRIMARY KEY)"],
10420 }));
10421 let reg = builder.build().expect("registry builds");
10422
10423 let mut backend_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
10424 backend_map.insert("routed", &pack_backend);
10425
10426 reg.apply_schema_plans_with_map(&backend_map, &default_backend)
10427 .expect("schema application must not collide");
10428
10429 let mut writer = pack_backend.sql().writer().await.expect("writer");
10431 let result = writer
10432 .execute(SqlStatement {
10433 sql: "INSERT INTO t_routed (id) VALUES (?1)".into(),
10434 params: vec![SqlValue::Integer(1)],
10435 label: None,
10436 })
10437 .await;
10438 assert!(
10439 result.is_ok(),
10440 "t_routed must exist on pack_backend after routing: {result:?}"
10441 );
10442
10443 let mut default_writer = default_backend.sql().writer().await.expect("writer");
10445 let default_result = default_writer
10446 .execute(SqlStatement {
10447 sql: "INSERT INTO t_routed (id) VALUES (?1)".into(),
10448 params: vec![SqlValue::Integer(2)],
10449 label: None,
10450 })
10451 .await;
10452 assert!(
10453 default_result.is_err(),
10454 "t_routed must NOT exist on default_backend (table should not be there)"
10455 );
10456 }
10457
10458 #[tokio::test]
10461 async fn apply_schema_plans_with_map_falls_back_to_default_for_unmapped_packs() {
10462 use khive_storage::types::{SqlStatement, SqlValue};
10463
10464 let default_backend = khive_db::StorageBackend::memory().expect("default memory backend");
10465
10466 let mut builder = VerbRegistryBuilder::new();
10467 builder.register_boxed(Box::new(SchemaPack {
10468 pack_name: "unmapped",
10469 statements: &["CREATE TABLE IF NOT EXISTS t_unmapped (id INTEGER PRIMARY KEY)"],
10470 }));
10471 let reg = builder.build().expect("registry builds");
10472
10473 let backend_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
10474 reg.apply_schema_plans_with_map(&backend_map, &default_backend)
10475 .expect("schema application must not collide");
10476
10477 let mut writer = default_backend.sql().writer().await.expect("writer");
10479 let result = writer
10480 .execute(SqlStatement {
10481 sql: "INSERT INTO t_unmapped (id) VALUES (?1)".into(),
10482 params: vec![SqlValue::Integer(1)],
10483 label: None,
10484 })
10485 .await;
10486 assert!(
10487 result.is_ok(),
10488 "t_unmapped must exist on default_backend for unmapped pack: {result:?}"
10489 );
10490 }
10491
10492 #[test]
10497 fn apply_schema_plans_with_map_collision_is_an_error() {
10498 let backend = khive_db::StorageBackend::memory().expect("memory backend");
10499 let empty_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
10500
10501 let mut builder = VerbRegistryBuilder::new();
10502 builder.register_boxed(Box::new(SchemaPack {
10503 pack_name: "pack_alpha",
10504 statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
10505 }));
10506 builder.register_boxed(Box::new(SchemaPack {
10507 pack_name: "pack_beta",
10508 statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
10509 }));
10510 let registry = builder.build().expect("registry builds");
10511
10512 let result = registry.apply_schema_plans_with_map(&empty_map, &backend);
10513 assert!(
10514 result.is_err(),
10515 "two packs declaring the same table on the same backend must produce a collision error"
10516 );
10517 let err = result.unwrap_err();
10518 let msg = err.to_string();
10519 assert!(
10520 msg.contains("pack_alpha"),
10521 "collision error must name first pack; got: {msg}"
10522 );
10523 assert!(
10524 msg.contains("pack_beta"),
10525 "collision error must name second pack; got: {msg}"
10526 );
10527 assert!(
10528 msg.contains("collision_table"),
10529 "collision error must name the table; got: {msg}"
10530 );
10531 }
10532
10533 #[test]
10534 fn apply_schema_plans_with_map_read_only_collision_is_an_error_without_writes() {
10535 let dir = tempfile::tempdir().expect("tempdir");
10536 let path = dir.path().join("read_only_schema_collision.db");
10537 {
10538 let writable = khive_db::StorageBackend::sqlite(&path).expect("writable backend");
10539 writable.prepare_core_schema().expect("current schema");
10540 }
10541 #[cfg(unix)]
10542 {
10543 use std::os::unix::fs::PermissionsExt;
10544 for suffix in ["-wal", "-shm"] {
10545 let mut name = path.file_name().expect("db file name").to_os_string();
10546 name.push(suffix);
10547 let sidecar = path.parent().expect("db parent dir").join(name);
10548 if sidecar.exists() {
10549 let mut permissions = std::fs::metadata(&sidecar)
10550 .expect("sidecar metadata")
10551 .permissions();
10552 permissions.set_mode(0o444);
10553 std::fs::set_permissions(&sidecar, permissions).expect("freeze sidecar");
10554 }
10555 }
10556 }
10557 let backend = khive_db::StorageBackend::sqlite_read_only(&path).expect("read-only backend");
10558 let empty_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
10559
10560 let mut builder = VerbRegistryBuilder::new();
10561 builder.register_boxed(Box::new(SchemaPack {
10562 pack_name: "pack_alpha",
10563 statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
10564 }));
10565 builder.register_boxed(Box::new(SchemaPack {
10566 pack_name: "pack_beta",
10567 statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
10568 }));
10569 let registry = builder.build().expect("registry builds");
10570 let writes_before = backend.pool().writer_acquisition_snapshot();
10571
10572 let result = registry.apply_schema_plans_with_map(&empty_map, &backend);
10573
10574 let err = result.expect_err(
10575 "read-only topology must reject the same cross-pack collision as writable topology",
10576 );
10577 let msg = err.to_string();
10578 assert!(
10579 msg.contains("pack_alpha"),
10580 "collision error must name first pack; got: {msg}"
10581 );
10582 assert!(
10583 msg.contains("pack_beta"),
10584 "collision error must name second pack; got: {msg}"
10585 );
10586 assert!(
10587 msg.contains("collision_table"),
10588 "collision error must name the table; got: {msg}"
10589 );
10590 assert_eq!(
10591 backend.pool().writer_acquisition_snapshot(),
10592 writes_before,
10593 "read-only collision validation must not acquire a writer"
10594 );
10595 }
10596}