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};
29#[allow(deprecated)]
31pub use khive_types::VerbDef;
32
33use crate::validation::ValidationRule;
34
35#[derive(Debug, Default, Clone)]
45pub struct SchemaPlan {
46 pub pack: &'static str,
48 pub statements: &'static [&'static str],
52}
53
54impl SchemaPlan {
55 pub const fn empty() -> Self {
60 Self {
61 pack: "",
62 statements: &[],
63 }
64 }
65
66 pub fn is_empty(&self) -> bool {
68 self.statements.is_empty()
69 }
70}
71
72#[async_trait]
79pub trait DispatchHook: Send + Sync {
80 async fn on_dispatch(&self, view: &EventView);
85}
86
87use crate::error::{
88 CircularPackDependency, MissingPackDependencies, MissingPackDependency, RuntimeError,
89};
90use crate::KhiveRuntime;
91
92#[async_trait]
101pub trait PackRuntime: Send + Sync {
102 fn name(&self) -> &str;
104
105 fn note_kinds(&self) -> &'static [&'static str];
107
108 fn entity_kinds(&self) -> &'static [&'static str];
110
111 fn brain_consumer_kinds(&self) -> &'static [&'static str] {
114 &[]
115 }
116
117 fn handlers(&self) -> &'static [HandlerDef];
119
120 fn edge_rules(&self) -> &'static [EdgeEndpointRule] {
124 &[]
125 }
126
127 fn entity_types(&self) -> &'static [EntityTypeDef] {
131 &[]
132 }
133
134 fn requires(&self) -> &'static [&'static str] {
137 &[]
138 }
139
140 fn note_kind_specs(&self) -> &'static [NoteKindSpec] {
147 &[]
148 }
149
150 fn kind_hook(&self, _kind: &str) -> Option<Arc<dyn KindHook>> {
158 None
159 }
160
161 fn schema_plan(&self) -> SchemaPlan {
177 SchemaPlan::empty()
178 }
179
180 fn validation_rules(&self) -> &'static [ValidationRule] {
188 &[]
189 }
190
191 fn register_embedders(&self, _runtime: &KhiveRuntime) {}
197
198 fn register_entity_type_validator(&self, _runtime: &KhiveRuntime) {}
204
205 fn register_entity_type_validator_with_types(
212 &self,
213 runtime: &KhiveRuntime,
214 _pack_entity_types: &[EntityTypeDef],
215 ) {
216 self.register_entity_type_validator(runtime);
217 }
218
219 fn register_note_mutation_hook(&self, _runtime: &KhiveRuntime) {}
226
227 async fn warm(&self) {}
231
232 fn registered_embedding_model_names(&self) -> Vec<String> {
237 Vec::new()
238 }
239
240 async fn dispatch(
247 &self,
248 verb: &str,
249 params: Value,
250 registry: &VerbRegistry,
251 token: &NamespaceToken,
252 ) -> Result<Value, RuntimeError>;
253}
254
255#[async_trait]
271pub trait KindHook: Send + Sync + std::fmt::Debug {
272 async fn prepare_create(
278 &self,
279 runtime: &KhiveRuntime,
280 args: &mut Value,
281 ) -> Result<(), RuntimeError>;
282
283 async fn after_create(
292 &self,
293 runtime: &KhiveRuntime,
294 id: uuid::Uuid,
295 args: &Value,
296 ) -> Result<(), RuntimeError>;
297
298 async fn validate_note_update(
304 &self,
305 _runtime: &KhiveRuntime,
306 _token: &NamespaceToken,
307 _note: &khive_storage::Note,
308 _properties: Option<&Value>,
309 ) -> Result<(), RuntimeError> {
310 Ok(())
311 }
312
313 async fn validate_links(
318 &self,
319 _runtime: &KhiveRuntime,
320 _token: &NamespaceToken,
321 _links: &[crate::LinkSpec],
322 ) -> Result<(), RuntimeError> {
323 Ok(())
324 }
325}
326
327#[async_trait]
335pub trait PackByIdResolver: Send + Sync {
336 async fn resolve_by_id(
346 &self,
347 id: uuid::Uuid,
348 ) -> Result<Option<crate::Resolved>, crate::RuntimeError>;
349
350 async fn resolve_by_id_including_deleted(
355 &self,
356 id: uuid::Uuid,
357 ) -> Result<Option<crate::Resolved>, crate::RuntimeError> {
358 self.resolve_by_id(id).await
359 }
360
361 async fn delete_by_id(
370 &self,
371 id: uuid::Uuid,
372 hard: bool,
373 ) -> Result<serde_json::Value, crate::RuntimeError>;
374}
375
376pub struct VerbRegistryBuilder {
381 packs: Vec<Box<dyn PackRuntime>>,
382 resolvers: Vec<(String, Box<dyn PackByIdResolver>)>,
383 gate: GateRef,
384 default_namespace: String,
385 visible_namespaces: Vec<Namespace>,
393 actor_id: Option<String>,
396 event_store: Option<Arc<dyn EventStore>>,
403 dispatch_hook: Option<Arc<dyn DispatchHook>>,
409}
410
411impl VerbRegistryBuilder {
412 pub fn new() -> Self {
414 Self {
415 packs: Vec::new(),
416 resolvers: Vec::new(),
417 gate: std::sync::Arc::new(AllowAllGate),
418 default_namespace: Namespace::local().as_str().to_string(),
419 visible_namespaces: vec![],
420 actor_id: None,
421 event_store: None,
422 dispatch_hook: None,
423 }
424 }
425
426 pub fn with_visible_namespaces(&mut self, ns: Vec<Namespace>) -> &mut Self {
434 self.visible_namespaces = ns;
435 self
436 }
437
438 pub fn with_actor_id(&mut self, actor_id: Option<String>) -> &mut Self {
445 self.actor_id = actor_id;
446 self
447 }
448
449 pub fn register<P: khive_types::Pack + PackRuntime + 'static>(&mut self, pack: P) -> &mut Self {
452 self.packs.push(Box::new(pack));
453 self
454 }
455
456 pub(crate) fn register_boxed(&mut self, pack: Box<dyn PackRuntime>) -> &mut Self {
463 self.packs.push(pack);
464 self
465 }
466
467 pub fn register_resolver(
472 &mut self,
473 name: impl Into<String>,
474 resolver: Box<dyn PackByIdResolver>,
475 ) -> &mut Self {
476 self.resolvers.push((name.into(), resolver));
477 self
478 }
479
480 pub fn with_gate(&mut self, gate: GateRef) -> &mut Self {
487 self.gate = gate;
488 self
489 }
490
491 pub fn with_default_namespace(&mut self, ns: impl Into<String>) -> &mut Self {
496 self.default_namespace = ns.into();
497 self
498 }
499
500 pub fn with_event_store(&mut self, store: Arc<dyn EventStore>) -> &mut Self {
509 self.event_store = Some(store);
510 self
511 }
512
513 pub fn with_dispatch_hook(&mut self, hook: Arc<dyn DispatchHook>) -> &mut Self {
524 self.dispatch_hook = Some(hook);
525 self
526 }
527
528 pub fn build(self) -> Result<VerbRegistry, RuntimeError> {
534 let packs = self.packs;
535 let mut name_to_idx: HashMap<&str, usize> = HashMap::with_capacity(packs.len());
536 for (idx, pack) in packs.iter().enumerate() {
537 if let Some(prev_idx) = name_to_idx.insert(pack.name(), idx) {
538 return Err(RuntimeError::PackRedeclared {
539 name: pack.name().to_string(),
540 first_idx: prev_idx,
541 second_idx: idx,
542 });
543 }
544 }
545
546 let mut missing: Vec<MissingPackDependency> = Vec::new();
547 let mut indegree = vec![0usize; packs.len()];
548 let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); packs.len()];
549
550 for (idx, pack) in packs.iter().enumerate() {
551 for &requires in pack.requires() {
552 match name_to_idx.get(requires).copied() {
553 Some(dep_idx) => {
554 dependents[dep_idx].push(idx);
555 indegree[idx] += 1;
556 }
557 None => missing.push(MissingPackDependency {
558 from: pack.name().to_string(),
559 requires: requires.to_string(),
560 }),
561 }
562 }
563 }
564
565 if !missing.is_empty() {
566 return if missing.len() == 1 {
567 Err(RuntimeError::MissingPackDependency(missing.remove(0)))
568 } else {
569 Err(RuntimeError::MissingPackDependencies(
570 MissingPackDependencies { missing },
571 ))
572 };
573 }
574
575 let mut ready: VecDeque<usize> = indegree
576 .iter()
577 .enumerate()
578 .filter_map(|(idx, degree)| (*degree == 0).then_some(idx))
579 .collect();
580 let mut ordered_indices = Vec::with_capacity(packs.len());
581
582 while let Some(idx) = ready.pop_front() {
583 ordered_indices.push(idx);
584 for &dep_idx in &dependents[idx] {
585 indegree[dep_idx] -= 1;
586 if indegree[dep_idx] == 0 {
587 ready.push_back(dep_idx);
588 }
589 }
590 }
591
592 if ordered_indices.len() != packs.len() {
593 let cycle_nodes: HashSet<usize> = indegree
594 .iter()
595 .enumerate()
596 .filter_map(|(idx, degree)| (*degree > 0).then_some(idx))
597 .collect();
598 let cycle = find_pack_dependency_cycle(&packs, &name_to_idx, &cycle_nodes);
599 return Err(RuntimeError::CircularPackDependency(
600 CircularPackDependency { cycle },
601 ));
602 }
603
604 let mut slots: Vec<Option<Box<dyn PackRuntime>>> = packs.into_iter().map(Some).collect();
605 let ordered_packs: Vec<Box<dyn PackRuntime>> = ordered_indices
606 .into_iter()
607 .map(|idx| slots[idx].take().expect("topological index must exist"))
608 .collect();
609
610 validate_unique_note_kinds(&ordered_packs)?;
611 validate_unique_verb_names(&ordered_packs)?;
612 validate_unique_entity_types(&ordered_packs)?;
613 validate_brain_consumer_kinds(&ordered_packs)?;
614
615 let available_verbs: Vec<&'static str> = ordered_packs
616 .iter()
617 .flat_map(|p| p.handlers().iter())
618 .filter(|h| matches!(h.visibility, Visibility::Verb))
619 .map(|h| h.name)
620 .collect();
621
622 Ok(VerbRegistry {
623 packs: Arc::new(ordered_packs),
624 resolvers: Arc::new(self.resolvers),
625 gate: self.gate,
626 default_namespace: self.default_namespace,
627 visible_namespaces: self.visible_namespaces,
628 actor_id: self.actor_id,
629 event_store: self.event_store,
630 dispatch_hook: self.dispatch_hook,
631 available_verbs: Arc::new(available_verbs),
632 reference_ring: Arc::new(crate::reference_ring::ReferenceRing::new()),
633 })
634 }
635}
636
637fn validate_unique_note_kinds(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
643 let mut seen: HashMap<&str, &str> = HashMap::new();
644 for pack in packs {
645 for &kind in pack.note_kinds() {
646 if let Some(first_pack) = seen.insert(kind, pack.name()) {
647 return Err(RuntimeError::InvalidInput(format!(
648 "duplicate note kind {kind:?}: claimed by both {first_pack:?} and {:?}",
649 pack.name()
650 )));
651 }
652 }
653 }
654 Ok(())
655}
656
657fn validate_brain_consumer_kinds(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
664 for pack in packs {
665 for &kind in pack.brain_consumer_kinds() {
666 if kind == "*" || kind.trim().is_empty() || kind.trim() != kind {
667 return Err(RuntimeError::InvalidInput(format!(
668 "pack {:?} declares invalid brain consumer kind {kind:?}; declarations must be non-empty exact wire values and must not use the registry-owned \"*\" wildcard",
669 pack.name()
670 )));
671 }
672 }
673 }
674 Ok(())
675}
676
677fn validate_unique_verb_names(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
684 let mut seen: HashMap<&str, &str> = HashMap::new();
685 for pack in packs {
686 for handler in pack.handlers() {
687 if !matches!(handler.visibility, Visibility::Verb) {
688 continue;
689 }
690 if let Some(first_pack) = seen.insert(handler.name, pack.name()) {
691 return Err(RuntimeError::VerbCollision {
692 verb: handler.name.to_string(),
693 first_pack: first_pack.to_string(),
694 second_pack: pack.name().to_string(),
695 });
696 }
697 }
698 }
699 Ok(())
700}
701
702fn validate_unique_entity_types(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
712 let owned_defs = packs
713 .iter()
714 .flat_map(|p| p.entity_types().iter().map(move |def| (p.name(), def)));
715 khive_types::EntityTypeRegistry::check_extra_collisions(owned_defs)
716 .map_err(RuntimeError::InvalidInput)
717}
718
719fn find_pack_dependency_cycle(
720 packs: &[Box<dyn PackRuntime>],
721 name_to_idx: &HashMap<&str, usize>,
722 cycle_nodes: &HashSet<usize>,
723) -> Vec<String> {
724 fn visit(
725 idx: usize,
726 packs: &[Box<dyn PackRuntime>],
727 name_to_idx: &HashMap<&str, usize>,
728 cycle_nodes: &HashSet<usize>,
729 visiting: &mut Vec<usize>,
730 visited: &mut HashSet<usize>,
731 ) -> Option<Vec<String>> {
732 if let Some(pos) = visiting.iter().position(|&seen| seen == idx) {
733 let mut cycle: Vec<String> = visiting[pos..]
734 .iter()
735 .map(|&i| packs[i].name().to_string())
736 .collect();
737 cycle.push(packs[idx].name().to_string());
738 return Some(cycle);
739 }
740 if !visited.insert(idx) {
741 return None;
742 }
743 visiting.push(idx);
744 for &req in packs[idx].requires() {
745 let Some(&dep_idx) = name_to_idx.get(req) else {
746 continue;
747 };
748 if cycle_nodes.contains(&dep_idx) {
749 if let Some(cycle) =
750 visit(dep_idx, packs, name_to_idx, cycle_nodes, visiting, visited)
751 {
752 return Some(cycle);
753 }
754 }
755 }
756 visiting.pop();
757 None
758 }
759
760 let mut visited = HashSet::new();
761 for &idx in cycle_nodes {
762 let mut visiting = Vec::new();
763 if let Some(cycle) = visit(
764 idx,
765 packs,
766 name_to_idx,
767 cycle_nodes,
768 &mut visiting,
769 &mut visited,
770 ) {
771 return cycle;
772 }
773 }
774 cycle_nodes
775 .iter()
776 .map(|&idx| packs[idx].name().to_string())
777 .collect()
778}
779
780impl Default for VerbRegistryBuilder {
781 fn default() -> Self {
782 Self::new()
783 }
784}
785
786#[derive(Clone)]
790pub struct VerbRegistry {
791 packs: std::sync::Arc<Vec<Box<dyn PackRuntime>>>,
792 resolvers: std::sync::Arc<Vec<(String, Box<dyn PackByIdResolver>)>>,
794 gate: GateRef,
795 default_namespace: String,
796 visible_namespaces: Vec<Namespace>,
803 actor_id: Option<String>,
807 event_store: Option<Arc<dyn EventStore>>,
809 dispatch_hook: Option<Arc<dyn DispatchHook>>,
811 available_verbs: Arc<Vec<&'static str>>,
816 reference_ring: Arc<crate::reference_ring::ReferenceRing>,
821}
822
823#[derive(Debug, Clone, Default)]
838pub struct RequestIdentity {
839 pub namespace: String,
843 pub actor_id: Option<String>,
847 pub visible_namespaces: Vec<String>,
853 pub process_ref: Option<String>,
858 pub request_id: Option<u64>,
866}
867
868impl RequestIdentity {
869 pub fn from_token(token: &NamespaceToken) -> Self {
883 Self {
884 namespace: token.namespace().as_str().to_string(),
885 actor_id: token.actor().binding_id().map(str::to_string),
886 visible_namespaces: token
887 .visible_namespaces()
888 .iter()
889 .map(|namespace| namespace.as_str().to_string())
890 .collect(),
891 process_ref: token.process_ref().map(str::to_owned),
892 request_id: None,
893 }
894 }
895}
896
897#[derive(Debug, Clone, PartialEq, Eq)]
906pub struct VerifiedActor(String);
907
908impl VerifiedActor {
909 pub fn new(id: impl Into<String>) -> Result<Self, RuntimeError> {
914 let id = id.into();
915 if id.trim().is_empty() {
916 return Err(RuntimeError::InvalidInput(
917 "VerifiedActor: identifier must not be empty or whitespace-only".to_string(),
918 ));
919 }
920 Ok(Self(id))
921 }
922
923 pub fn as_str(&self) -> &str {
925 &self.0
926 }
927
928 fn into_inner(self) -> String {
929 self.0
930 }
931}
932
933#[derive(Debug)]
936pub struct PackSchemaCollisionError {
937 pub pack_a: &'static str,
939 pub pack_b: &'static str,
941 pub table: String,
943}
944
945impl std::fmt::Display for PackSchemaCollisionError {
946 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
947 if self.pack_a == self.pack_b {
948 write!(
949 f,
950 "pack schema boot failure for pack {:?}: {}",
951 self.pack_a, self.table
952 )
953 } else {
954 write!(
955 f,
956 "pack schema collision: packs {:?} and {:?} both declare table {:?} \
957 on the same backend — move one pack to a separate backend or rename the table",
958 self.pack_a, self.pack_b, self.table
959 )
960 }
961 }
962}
963
964impl std::error::Error for PackSchemaCollisionError {}
965
966fn extract_table_names(stmt: &str) -> Vec<String> {
972 let normalized = stmt.split_whitespace().collect::<Vec<_>>().join(" ");
973 let upper = normalized.to_ascii_uppercase();
974 let table_name = if let Some(rest) = upper.strip_prefix("CREATE VIRTUAL TABLE IF NOT EXISTS ") {
975 rest.split_whitespace().next()
976 } else if let Some(rest) = upper.strip_prefix("CREATE VIRTUAL TABLE ") {
977 rest.split_whitespace().next()
978 } else if let Some(rest) = upper.strip_prefix("CREATE TABLE IF NOT EXISTS ") {
979 rest.split_whitespace().next()
980 } else if let Some(rest) = upper.strip_prefix("CREATE TABLE ") {
981 rest.split_whitespace().next()
982 } else {
983 None
984 };
985 match table_name {
986 Some(name) => {
987 let clean = name.trim_matches(|c: char| c == '(' || c == ';');
988 if clean.is_empty() {
989 vec![]
990 } else {
991 vec![clean.to_ascii_lowercase()]
992 }
993 }
994 None => vec![],
995 }
996}
997
998fn endpoint_kind_label(kind: &EndpointKind) -> String {
1001 match kind {
1002 EndpointKind::EntityOfKind(k) => format!("entity:{k}"),
1003 EndpointKind::NoteOfKind(k) => format!("note:{k}"),
1004 EndpointKind::EntityOfType { kind, entity_type } => {
1005 format!("entity:{kind}({entity_type})")
1006 }
1007 }
1008}
1009
1010pub(crate) const SPECIAL_RELATIONS: &[khive_types::EdgeRelation] = &[
1018 khive_types::EdgeRelation::Supersedes,
1019 khive_types::EdgeRelation::Supports,
1020 khive_types::EdgeRelation::Refutes,
1021];
1022
1023pub(crate) fn is_special_relation(relation: khive_types::EdgeRelation) -> bool {
1024 SPECIAL_RELATIONS.contains(&relation)
1025}
1026
1027fn edge_endpoint_table(packs: &[Box<dyn PackRuntime>]) -> Vec<Value> {
1045 let mut rows: Vec<Value> = crate::operations::base_entity_endpoint_rules()
1046 .iter()
1047 .map(|(src, rel, tgt)| {
1048 serde_json::json!({
1049 "relation": rel.as_str(),
1050 "source": format!("entity:{src}"),
1051 "target": format!("entity:{tgt}"),
1052 })
1053 })
1054 .collect();
1055
1056 for rel in SPECIAL_RELATIONS {
1057 rows.push(serde_json::json!({
1058 "relation": rel.as_str(),
1059 "source": "note:*",
1060 "target": "note:*",
1061 }));
1062 }
1063
1064 for pack in packs.iter() {
1065 for rule in pack.edge_rules().iter() {
1066 if is_special_relation(rule.relation) {
1067 continue;
1068 }
1069 rows.push(serde_json::json!({
1070 "relation": rule.relation.as_str(),
1071 "source": endpoint_kind_label(&rule.source),
1072 "target": endpoint_kind_label(&rule.target),
1073 }));
1074 }
1075 }
1076
1077 rows.push(serde_json::json!({
1078 "relation": "annotates",
1079 "source": "note:*",
1080 "target": "any (entity, note, edge, or event)",
1081 }));
1082
1083 rows
1084}
1085
1086impl VerbRegistry {
1087 pub fn default_namespace(&self) -> &str {
1093 &self.default_namespace
1094 }
1095
1096 pub fn actor_id(&self) -> Option<&str> {
1100 self.actor_id.as_deref()
1101 }
1102
1103 pub fn visible_namespaces(&self) -> &[Namespace] {
1107 &self.visible_namespaces
1108 }
1109
1110 pub fn event_store(&self) -> Option<Arc<dyn EventStore>> {
1119 self.event_store.clone()
1120 }
1121
1122 pub fn describe_verb(&self, verb: &str) -> Result<Value, RuntimeError> {
1132 for pack in self.packs.iter() {
1133 for handler in pack.handlers().iter() {
1134 if handler.name == verb {
1135 let category = format!("{:?}", handler.category);
1136 let params_arr: Vec<Value> = handler
1137 .params
1138 .iter()
1139 .map(|p| {
1140 serde_json::json!({
1141 "name": p.name,
1142 "type": p.param_type,
1143 "required": p.required,
1144 "description": p.description,
1145 })
1146 })
1147 .collect();
1148 if matches!(handler.visibility, Visibility::Subhandler) {
1153 return Ok(serde_json::json!({
1154 "verb": verb,
1155 "pack": pack.name(),
1156 "description": handler.description,
1157 "category": category,
1158 "params": params_arr,
1159 "visibility": "internal",
1160 "callable_via_mcp": false,
1161 "note": "This is an internal subhandler. Calling it via the MCP \
1162 request surface returns permission denied. It can only be \
1163 invoked by internal runtime callers.",
1164 }));
1165 }
1166 let mut envelope = serde_json::json!({
1167 "verb": verb,
1168 "pack": pack.name(),
1169 "description": handler.description,
1170 "category": category,
1171 "params": params_arr,
1172 });
1173 if verb == "link" {
1174 envelope["endpoint_rules"] = Value::Array(edge_endpoint_table(&self.packs));
1175 }
1176 return Ok(envelope);
1177 }
1178 }
1179 }
1180 Err(RuntimeError::InvalidInput(format!(
1184 "unknown verb {verb:?}; available: {}",
1185 self.available_verbs.join(", ")
1186 )))
1187 }
1188
1189 pub fn authorize_namespace(&self, ns: Namespace) -> Result<(), RuntimeError> {
1197 let actor = crate::actor_identity::resolve_actor(self.actor_id.as_deref());
1198 let req = GateRequest::new(actor, ns, "authorize", serde_json::Value::Null);
1199 match self.gate.check(&req) {
1200 Ok(decision) if decision.is_allow() => Ok(()),
1201 Ok(GateDecision::Deny { reason }) => Err(RuntimeError::PermissionDenied {
1202 verb: "authorize".to_string(),
1203 reason,
1204 }),
1205 Ok(_) => Err(RuntimeError::PermissionDenied {
1206 verb: "authorize".to_string(),
1207 reason: "gate denied".to_string(),
1208 }),
1209 Err(e) => Err(RuntimeError::Internal(format!("gate error: {e}"))),
1210 }
1211 }
1212
1213 pub async fn dispatch_intercepted_with_identity<F, Fut>(
1221 &self,
1222 verb: &str,
1223 params: &Value,
1224 identity: Option<&RequestIdentity>,
1225 dispatch: F,
1226 ) -> Result<Value, RuntimeError>
1227 where
1228 F: FnOnce(Namespace) -> Fut,
1229 Fut: std::future::Future<Output = Result<Value, RuntimeError>>,
1230 {
1231 let request_id = identity.and_then(|id| id.request_id);
1232 let gate_req = self.gate_request_with_identity(verb, params, identity)?;
1233 let deferred_audit = match self.gate.check(&gate_req) {
1234 Ok(decision) => {
1235 let audit = AuditEvent::from_check(&gate_req, &decision, self.gate.impl_name());
1236 tracing::info!(
1237 audit_event = %serde_json::to_string(&audit)
1238 .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
1239 "gate.check"
1240 );
1241 if let GateDecision::Deny { reason } = decision {
1242 if let Some(store) = &self.event_store {
1243 let event = build_audit_storage_event(
1244 &gate_req,
1245 &audit,
1246 EventOutcome::Denied,
1247 Some(crate::cost_unit::base_resource_payload(request_id)),
1248 );
1249 append_audit_event_best_effort(store, event, verb).await;
1250 }
1251 return Err(RuntimeError::PermissionDenied {
1252 verb: verb.to_string(),
1253 reason,
1254 });
1255 }
1256 Some(audit)
1257 }
1258 Err(err) => {
1259 tracing::warn!(verb, error = %err, "gate check failed (fail-open)");
1260 None
1261 }
1262 };
1263
1264 let started = Instant::now();
1265 let result = dispatch(gate_req.namespace.clone()).await;
1266 let duration_us = started.elapsed().as_micros() as i64;
1267 if let Some(audit) = deferred_audit {
1268 self.persist_intercepted_audit(
1269 verb,
1270 &gate_req,
1271 audit,
1272 &result,
1273 duration_us,
1274 request_id,
1275 )
1276 .await;
1277 }
1278 result
1279 }
1280
1281 async fn persist_intercepted_audit(
1282 &self,
1283 verb: &str,
1284 gate_req: &GateRequest,
1285 audit: AuditEvent,
1286 result: &Result<Value, RuntimeError>,
1287 duration_us: i64,
1288 request_id: Option<u64>,
1289 ) {
1290 let Some(store) = &self.event_store else {
1291 return;
1292 };
1293 let event = match result {
1294 Ok(value) if verb == "link" && gate_req.args.get("links").is_none() => {
1295 let resource = crate::cost_unit::resource_payload(
1296 verb,
1297 &gate_req.args,
1298 value,
1299 || 0,
1300 request_id,
1301 );
1302 match link_audit_success_from_result(audit.clone(), value) {
1303 Some((edge_id, mut payload)) => {
1304 if let Value::Object(ref mut map) = payload {
1305 map.insert("resource".to_string(), resource);
1306 }
1307 Event::new(
1308 gate_req.namespace.as_str(),
1309 gate_req.verb.as_str(),
1310 EventKind::Audit,
1311 SubstrateKind::Event,
1312 format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
1313 )
1314 .with_outcome(EventOutcome::Success)
1315 .with_target(edge_id)
1316 .with_payload(payload)
1317 .with_payload_schema_version(2)
1318 .with_duration_us(duration_us)
1319 }
1320 None => build_audit_storage_event(
1321 gate_req,
1322 &audit,
1323 EventOutcome::Success,
1324 Some(resource),
1325 )
1326 .with_duration_us(duration_us),
1327 }
1328 }
1329 Ok(value) => build_audit_storage_event(
1330 gate_req,
1331 &audit,
1332 EventOutcome::Success,
1333 Some(crate::cost_unit::resource_payload(
1334 verb,
1335 &gate_req.args,
1336 value,
1337 || 0,
1338 request_id,
1339 )),
1340 )
1341 .with_duration_us(duration_us),
1342 Err(_) => build_audit_storage_event(
1343 gate_req,
1344 &audit,
1345 EventOutcome::Error,
1346 Some(crate::cost_unit::base_resource_payload(request_id)),
1347 )
1348 .with_duration_us(duration_us),
1349 };
1350 append_audit_event_best_effort(store, event, verb).await;
1351 }
1352
1353 fn gate_request_with_identity(
1354 &self,
1355 verb: &str,
1356 params: &Value,
1357 identity: Option<&RequestIdentity>,
1358 ) -> Result<GateRequest, RuntimeError> {
1359 let default_namespace = identity
1360 .map(|id| id.namespace.as_str())
1361 .unwrap_or(self.default_namespace.as_str());
1362 let namespace = resolve_explicit_namespace(params, default_namespace)?;
1363 let actor_id = identity
1364 .map(|id| id.actor_id.as_deref())
1365 .unwrap_or(self.actor_id.as_deref());
1366 let actor = crate::actor_identity::resolve_actor(actor_id);
1367 Ok(GateRequest::new(actor, namespace, verb, params.clone()))
1368 }
1369
1370 pub async fn dispatch(&self, verb: &str, params: Value) -> Result<Value, RuntimeError> {
1380 self.dispatch_with_identity(verb, params, None).await
1381 }
1382
1383 pub async fn dispatch_with_identity(
1395 &self,
1396 verb: &str,
1397 params: Value,
1398 identity: Option<RequestIdentity>,
1399 ) -> Result<Value, RuntimeError> {
1400 if params.get("help").and_then(Value::as_bool) == Some(true) {
1402 return self.describe_verb(verb);
1403 }
1404 let explicit_namespace = params.get("namespace").is_some_and(Value::is_string);
1415 let request_id: Option<u64> = identity.as_ref().and_then(|id| id.request_id);
1419 let gate_req = self.gate_request_with_identity(verb, ¶ms, identity.as_ref())?;
1425 let ns = gate_req.namespace.clone();
1426 let resolved_actor = gate_req.actor.clone();
1427
1428 let (gate_blocked, mut deferred_audit) = match self.gate.check(&gate_req) {
1434 Ok(decision) => {
1435 let is_deny = matches!(decision, GateDecision::Deny { .. });
1436
1437 let audit = AuditEvent::from_check(&gate_req, &decision, self.gate.impl_name());
1439 tracing::info!(
1440 audit_event = %serde_json::to_string(&audit)
1441 .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
1442 "gate.check"
1443 );
1444
1445 if let Some(store) = &self.event_store {
1454 if crate::config_ledger::PENDING
1455 .swap(false, std::sync::atomic::Ordering::AcqRel)
1456 {
1457 for (key, value) in crate::config_ledger::drain_config_locked() {
1458 let payload = serde_json::json!({ "key": key, "value": value });
1459 let storage_event = Event::new(
1460 gate_req.namespace.as_str(),
1461 verb,
1462 EventKind::ConfigLocked,
1463 SubstrateKind::Event,
1464 format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
1465 )
1466 .with_payload(payload);
1467 append_audit_event_best_effort(store, storage_event, verb).await;
1468 }
1469 }
1470 }
1471
1472 let defer_audit = !is_deny;
1487
1488 if !defer_audit {
1490 if let Some(store) = &self.event_store {
1491 let storage_event = build_audit_storage_event(
1497 &gate_req,
1498 &audit,
1499 EventOutcome::Denied,
1500 Some(crate::cost_unit::base_resource_payload(request_id)),
1501 );
1502 append_audit_event_best_effort(store, storage_event, verb).await;
1503 }
1504 }
1505
1506 let reason = if is_deny {
1507 let reason = match decision {
1508 GateDecision::Deny { reason } => reason,
1509 _ => String::new(),
1510 };
1511 Some(reason)
1512 } else {
1513 None
1514 };
1515 let deferred = if defer_audit { Some(audit) } else { None };
1516 (reason, deferred)
1517 }
1518 Err(err) => {
1519 tracing::warn!(verb, error = %err, "gate check failed (fail-open)");
1522 (None, None)
1523 }
1524 };
1525
1526 if let Some(reason) = gate_blocked {
1528 return Err(RuntimeError::PermissionDenied {
1529 verb: verb.to_string(),
1530 reason,
1531 });
1532 }
1533
1534 let token = if explicit_namespace {
1560 NamespaceToken::mint_with_visibility(ns.clone(), vec![], resolved_actor)
1562 } else {
1563 let primary = Namespace::local();
1565 let mut extra_visible: Vec<Namespace> = match identity.as_ref() {
1566 Some(id) => id
1567 .visible_namespaces
1568 .iter()
1569 .filter_map(|s| match Namespace::parse(s) {
1570 Ok(parsed) => Some(parsed),
1571 Err(e) => {
1572 tracing::warn!(
1573 namespace = %s,
1574 error = %e,
1575 "dispatch_with_identity: skipping invalid visible_namespace \
1576 entry from per-request identity"
1577 );
1578 None
1579 }
1580 })
1581 .collect(),
1582 None => self.visible_namespaces.clone(),
1583 };
1584 extra_visible.push(Namespace::local()); NamespaceToken::mint_with_visibility(primary, extra_visible, resolved_actor)
1586 }
1587 .with_process_ref(match identity.as_ref() {
1588 Some(id) => id.process_ref.clone(),
1589 None => crate::config::process_ref_from_env(),
1590 });
1591
1592 for pack in self.packs.iter() {
1593 if let Some(handler_def) = pack.handlers().iter().find(|v| v.name == verb) {
1594 let handler_accepts_namespace =
1604 handler_def.params.iter().any(|p| p.name == "namespace");
1605 let params = if !handler_accepts_namespace {
1606 if let Value::Object(mut map) = params {
1607 map.remove("namespace");
1608 Value::Object(map)
1609 } else {
1610 params
1611 }
1612 } else {
1613 params
1614 };
1615 let dispatch_start = Instant::now();
1616 let result = pack.dispatch(verb, params, self, &token).await;
1617 let dispatch_us = dispatch_start.elapsed().as_micros() as i64;
1618
1619 if let Some(audit) = deferred_audit.take() {
1628 if let Some(store) = &self.event_store {
1629 let is_link_singleton =
1630 verb == "link" && gate_req.args.get("links").is_none();
1631 match &result {
1632 Ok(ok_val) if is_link_singleton => {
1633 let resource = crate::cost_unit::resource_payload(
1641 verb,
1642 &gate_req.args,
1643 ok_val,
1644 || pack.registered_embedding_model_names().len() as i64,
1645 request_id,
1646 );
1647 match link_audit_success_from_result(audit.clone(), ok_val) {
1648 Some((edge_id, mut payload)) => {
1649 if let Value::Object(ref mut map) = payload {
1650 map.insert("resource".to_string(), resource);
1651 }
1652 let storage_event = Event::new(
1653 gate_req.namespace.as_str(),
1654 gate_req.verb.as_str(),
1655 EventKind::Audit,
1656 SubstrateKind::Event,
1657 format!(
1658 "{}:{}",
1659 gate_req.actor.kind, gate_req.actor.id
1660 ),
1661 )
1662 .with_outcome(EventOutcome::Success)
1663 .with_target(edge_id)
1664 .with_payload(payload)
1665 .with_payload_schema_version(2)
1666 .with_duration_us(dispatch_us);
1667 append_audit_event_best_effort(store, storage_event, verb)
1668 .await;
1669 }
1670 None => {
1671 tracing::warn!(
1672 verb,
1673 "link audit v2 enrichment parse failed; \
1674 falling back to v1 audit shape"
1675 );
1676 let storage_event = build_audit_storage_event(
1677 &gate_req,
1678 &audit,
1679 EventOutcome::Success,
1680 Some(resource),
1681 )
1682 .with_duration_us(dispatch_us);
1683 append_audit_event_best_effort(store, storage_event, verb)
1684 .await;
1685 }
1686 }
1687 }
1688 _ => {
1689 let (outcome, resource) = match &result {
1709 Ok(ok_val) => (
1710 EventOutcome::Success,
1711 Some(crate::cost_unit::resource_payload(
1712 verb,
1713 &gate_req.args,
1714 ok_val,
1715 || pack.registered_embedding_model_names().len() as i64,
1716 request_id,
1717 )),
1718 ),
1719 Err(_) => (
1720 EventOutcome::Error,
1721 Some(crate::cost_unit::base_resource_payload(request_id)),
1722 ),
1723 };
1724 let storage_event =
1725 build_audit_storage_event(&gate_req, &audit, outcome, resource)
1726 .with_duration_us(dispatch_us);
1727 append_audit_event_best_effort(store, storage_event, verb).await;
1728 }
1729 }
1730 }
1731 }
1732
1733 if let (Ok(ref ok_val), Some(hook)) = (&result, &self.dispatch_hook) {
1735 let mut dispatch_event = Event::new(
1736 ns.as_str(),
1737 verb,
1738 EventKind::Audit,
1739 SubstrateKind::Event,
1740 pack.name(),
1741 )
1742 .with_outcome(EventOutcome::Success)
1743 .with_duration_us(dispatch_us);
1744
1745 if verb == "memory.recall" {
1751 let first_result =
1752 ok_val.as_array().and_then(|arr| arr.first()).or_else(|| {
1753 ok_val
1754 .get("results")
1755 .and_then(Value::as_array)
1756 .and_then(|arr| arr.first())
1757 });
1758 let first_note_id = first_result
1759 .and_then(|v| v.get("id"))
1760 .and_then(|v| v.as_str())
1761 .and_then(|s| s.parse::<uuid::Uuid>().ok());
1762 if let Some(note_id) = first_note_id {
1763 dispatch_event = dispatch_event.with_target(note_id);
1764 }
1765 let mut payload = serde_json::Map::new();
1766 if let Some(profile_id) = first_result
1767 .and_then(|v| v.get("served_by_profile_id"))
1768 .and_then(Value::as_str)
1769 {
1770 payload.insert(
1771 "served_by_profile_id".to_string(),
1772 Value::String(profile_id.to_string()),
1773 );
1774 }
1775 if let Some(attribution) = first_result
1776 .and_then(|v| v.get("serve_attribution"))
1777 .and_then(Value::as_str)
1778 {
1779 payload.insert(
1780 "serve_attribution".to_string(),
1781 Value::String(attribution.to_string()),
1782 );
1783 }
1784 dispatch_event = dispatch_event.with_payload(Value::Object(payload));
1785 }
1788
1789 let dispatch_view = EventView {
1790 event: dispatch_event,
1791 observations: Vec::new(),
1792 };
1793 let hook = Arc::clone(hook);
1794 hook.on_dispatch(&dispatch_view).await;
1795 }
1796
1797 if let Ok(ref ok_val) = result {
1813 let admissions = crate::reference_ring::ring_admissions_for(verb, ok_val);
1814 if !admissions.is_empty() {
1815 let actor_key = format!("{}:{}", gate_req.actor.kind, gate_req.actor.id);
1816 for (id, name) in admissions {
1817 self.reference_ring.admit(
1818 token.namespace().as_str(),
1819 &actor_key,
1820 id,
1821 name,
1822 );
1823 }
1824 }
1825 }
1826
1827 return result;
1828 }
1829 }
1830
1831 if let Some(audit) = deferred_audit.take() {
1837 if let Some(store) = &self.event_store {
1838 let storage_event = build_audit_storage_event(
1844 &gate_req,
1845 &audit,
1846 EventOutcome::Error,
1847 Some(crate::cost_unit::base_resource_payload(request_id)),
1848 );
1849 append_audit_event_best_effort(store, storage_event, verb).await;
1850 }
1851 }
1852
1853 Err(RuntimeError::InvalidInput(format!(
1857 "unknown verb {verb:?}; available: {}",
1858 self.available_verbs.join(", ")
1859 )))
1860 }
1861
1862 pub async fn dispatch_as(
1880 &self,
1881 verb: &str,
1882 params: Value,
1883 verified_actor: VerifiedActor,
1884 ) -> Result<Value, RuntimeError> {
1885 let identity = RequestIdentity {
1886 namespace: self.default_namespace.clone(),
1887 actor_id: Some(verified_actor.into_inner()),
1888 visible_namespaces: self
1889 .visible_namespaces
1890 .iter()
1891 .map(|ns| ns.as_str().to_string())
1892 .collect(),
1893 process_ref: crate::config::process_ref_from_env(),
1894 request_id: None,
1895 };
1896 self.dispatch_with_identity(verb, params, Some(identity))
1897 .await
1898 }
1899
1900 pub fn resolvers(&self) -> &[(String, Box<dyn PackByIdResolver>)] {
1906 &self.resolvers
1907 }
1908
1909 pub fn reference_ring(&self) -> &Arc<crate::reference_ring::ReferenceRing> {
1914 &self.reference_ring
1915 }
1916
1917 pub fn find_kind_hook(&self, kind: &str) -> Option<Arc<dyn KindHook>> {
1924 for pack in self.packs.iter() {
1925 let owns = pack.note_kinds().contains(&kind) || pack.entity_kinds().contains(&kind);
1926 if owns {
1927 if let Some(hook) = pack.kind_hook(kind) {
1928 return Some(hook);
1929 }
1930 }
1931 }
1932 None
1933 }
1934
1935 pub async fn validate_note_update_hook(
1940 &self,
1941 runtime: &KhiveRuntime,
1942 token: &NamespaceToken,
1943 note: &khive_storage::Note,
1944 properties: Option<&Value>,
1945 ) -> Result<(), RuntimeError> {
1946 if let Some(hook) = self.find_kind_hook(¬e.kind) {
1947 hook.validate_note_update(runtime, token, note, properties)
1948 .await?;
1949 }
1950 Ok(())
1951 }
1952
1953 pub async fn validate_link_hooks(
1960 &self,
1961 runtime: &KhiveRuntime,
1962 token: &NamespaceToken,
1963 specs: &[LinkSpec],
1964 ) -> Result<(), RuntimeError> {
1965 let mut specs_by_kind: HashMap<String, Vec<LinkSpec>> = HashMap::new();
1966 for spec in specs {
1967 let Some(Resolved::Note(source)) = runtime.resolve_by_id(token, spec.source_id).await?
1968 else {
1969 continue;
1970 };
1971 specs_by_kind
1972 .entry(source.kind)
1973 .or_default()
1974 .push(spec.clone());
1975 }
1976 for (kind, kind_specs) in specs_by_kind {
1977 if let Some(hook) = self.find_kind_hook(&kind) {
1978 hook.validate_links(runtime, token, &kind_specs).await?;
1979 }
1980 }
1981 Ok(())
1982 }
1983
1984 pub fn has_verb(&self, verb: &str) -> bool {
1990 self.packs
1991 .iter()
1992 .flat_map(|p| p.handlers().iter())
1993 .any(|h| h.name == verb)
1994 }
1995
1996 pub fn all_verbs(&self) -> Vec<&'static HandlerDef> {
2002 self.packs
2003 .iter()
2004 .flat_map(|p| p.handlers().iter())
2005 .filter(|h| matches!(h.visibility, Visibility::Verb))
2006 .collect()
2007 }
2008
2009 pub fn all_verbs_with_names(&self) -> Vec<(&str, &'static HandlerDef)> {
2016 self.packs
2017 .iter()
2018 .flat_map(|p| p.handlers().iter().map(move |v| (p.name(), v)))
2019 .filter(|(_, h)| matches!(h.visibility, Visibility::Verb))
2020 .collect()
2021 }
2022
2023 pub fn all_handlers_with_names(&self) -> Vec<(&str, &'static HandlerDef)> {
2029 self.packs
2030 .iter()
2031 .flat_map(|p| p.handlers().iter().map(move |v| (p.name(), v)))
2032 .collect()
2033 }
2034
2035 pub fn all_note_kinds(&self) -> Vec<&'static str> {
2038 let mut seen = std::collections::HashSet::new();
2039 self.packs
2040 .iter()
2041 .flat_map(|p| p.note_kinds().iter().copied())
2042 .filter(|k| seen.insert(*k))
2043 .collect()
2044 }
2045
2046 pub fn all_entity_kinds(&self) -> Vec<&'static str> {
2049 let mut seen = std::collections::HashSet::new();
2050 self.packs
2051 .iter()
2052 .flat_map(|p| p.entity_kinds().iter().copied())
2053 .filter(|k| seen.insert(*k))
2054 .collect()
2055 }
2056
2057 pub fn all_brain_consumer_kinds(&self) -> Vec<&'static str> {
2060 let mut seen = std::collections::HashSet::new();
2061 self.packs
2062 .iter()
2063 .flat_map(|p| p.brain_consumer_kinds().iter().copied())
2064 .filter(|kind| seen.insert(*kind))
2065 .collect()
2066 }
2067
2068 pub fn pack_names(&self) -> Vec<&str> {
2070 self.packs.iter().map(|p| p.name()).collect()
2071 }
2072
2073 pub fn pack_requires(&self, name: &str) -> Option<&'static [&'static str]> {
2075 self.packs
2076 .iter()
2077 .find(|p| p.name() == name)
2078 .map(|p| p.requires())
2079 }
2080
2081 pub fn pack_note_kinds(&self, name: &str) -> Option<&'static [&'static str]> {
2086 self.packs
2087 .iter()
2088 .find(|p| p.name() == name)
2089 .map(|p| p.note_kinds())
2090 }
2091
2092 pub fn pack_entity_kinds(&self, name: &str) -> Option<&'static [&'static str]> {
2097 self.packs
2098 .iter()
2099 .find(|p| p.name() == name)
2100 .map(|p| p.entity_kinds())
2101 }
2102
2103 pub fn pack_verbs(&self, name: &str) -> Option<&'static [HandlerDef]> {
2108 self.packs
2109 .iter()
2110 .find(|p| p.name() == name)
2111 .map(|p| p.handlers())
2112 }
2113
2114 pub fn all_edge_rules(&self) -> Vec<EdgeEndpointRule> {
2120 self.packs
2121 .iter()
2122 .flat_map(|p| p.edge_rules().iter().copied())
2123 .collect()
2124 }
2125
2126 pub fn all_entity_types(&self) -> Vec<EntityTypeDef> {
2133 self.packs
2134 .iter()
2135 .flat_map(|p| p.entity_types().iter().cloned())
2136 .collect()
2137 }
2138
2139 pub fn all_note_kind_specs(&self) -> Vec<&'static NoteKindSpec> {
2143 self.packs
2144 .iter()
2145 .flat_map(|p| p.note_kind_specs().iter())
2146 .collect()
2147 }
2148
2149 pub fn all_validation_rules(&self) -> Vec<&'static ValidationRule> {
2155 self.packs
2156 .iter()
2157 .flat_map(|p| p.validation_rules().iter())
2158 .collect()
2159 }
2160
2161 pub fn all_schema_plans(&self) -> Vec<SchemaPlan> {
2168 self.packs.iter().map(|p| p.schema_plan()).collect()
2169 }
2170
2171 pub fn call_register_embedders(&self, runtime: &KhiveRuntime) {
2181 for pack in self.packs.iter() {
2182 pack.register_embedders(runtime);
2183 }
2184 }
2185
2186 pub fn call_register_entity_type_validators(&self, runtime: &KhiveRuntime) {
2200 let entity_types = self.all_entity_types();
2201 for pack in self.packs.iter() {
2202 pack.register_entity_type_validator_with_types(runtime, &entity_types);
2203 }
2204 }
2205
2206 pub fn call_register_note_mutation_hooks(&self, runtime: &KhiveRuntime) {
2217 for pack in self.packs.iter() {
2218 pack.register_note_mutation_hook(runtime);
2219 }
2220 }
2221
2222 pub async fn call_warm_all(&self) {
2226 for pack in self.packs.iter() {
2227 pack.warm().await;
2228 }
2229 }
2230
2231 pub fn presentation_policy_for(&self, verb: &str) -> khive_types::VerbPresentationPolicy {
2238 for pack in self.packs.iter() {
2239 if let Some(handler) = pack.handlers().iter().find(|h| h.name == verb) {
2240 return handler.presentation_policy();
2241 }
2242 }
2243 khive_types::VerbPresentationPolicy::Standard
2244 }
2245
2246 pub fn is_subhandler_verb(&self, verb: &str) -> bool {
2253 for pack in self.packs.iter() {
2254 if let Some(handler) = pack.handlers().iter().find(|h| h.name == verb) {
2255 return matches!(handler.visibility, Visibility::Subhandler);
2256 }
2257 }
2258 false
2259 }
2260
2261 pub fn apply_schema_plans(&self, backend: &khive_db::StorageBackend) {
2273 for plan in self.all_schema_plans() {
2274 if plan.is_empty() {
2275 continue;
2276 }
2277 if let Err(e) = backend.apply_pack_ddl_statements(plan.statements) {
2278 tracing::warn!(
2279 pack = plan.pack,
2280 error = %e,
2281 "failed to apply pack schema plan at startup (non-fatal)"
2282 );
2283 }
2284 }
2285 }
2286
2287 pub fn all_schema_plans_named(&self) -> Vec<(&'static str, SchemaPlan)> {
2293 self.packs
2294 .iter()
2295 .map(|p| {
2296 let plan = p.schema_plan();
2297 (plan.pack, plan)
2298 })
2299 .collect()
2300 }
2301
2302 pub fn apply_schema_plans_with_map(
2315 &self,
2316 backend_for_pack: &HashMap<&str, &khive_db::StorageBackend>,
2317 default_backend: &khive_db::StorageBackend,
2318 ) -> Result<(), crate::PackSchemaCollisionError> {
2319 let mut claimed: HashMap<(*const (), String), &'static str> = HashMap::new();
2322
2323 for (pack_name, plan) in self.all_schema_plans_named() {
2324 if plan.is_empty() {
2325 continue;
2326 }
2327 let backend = backend_for_pack
2328 .get(pack_name)
2329 .copied()
2330 .unwrap_or(default_backend);
2331 let backend_ptr = std::sync::Arc::as_ptr(&backend.pool_arc()) as *const ();
2332
2333 for stmt in plan.statements {
2335 for table_name in extract_table_names(stmt) {
2336 let key = (backend_ptr, table_name.clone());
2337 match claimed.entry(key) {
2338 std::collections::hash_map::Entry::Vacant(e) => {
2339 e.insert(pack_name);
2340 }
2341 std::collections::hash_map::Entry::Occupied(e) => {
2342 let prior_pack = *e.get();
2343 return Err(crate::PackSchemaCollisionError {
2344 pack_a: prior_pack,
2345 pack_b: pack_name,
2346 table: table_name,
2347 });
2348 }
2349 }
2350 }
2351 }
2352
2353 backend
2354 .apply_pack_ddl_statements(plan.statements)
2355 .map_err(|e| crate::PackSchemaCollisionError {
2356 pack_a: pack_name,
2357 pack_b: pack_name,
2358 table: format!("DDL error: {e}"),
2359 })?;
2360 }
2361 Ok(())
2362 }
2363}
2364
2365pub struct PackInstall {
2373 pub runtime: Box<dyn PackRuntime>,
2375 pub resolver: Option<Box<dyn PackByIdResolver>>,
2377 pub dispatch_hook: Option<Arc<dyn DispatchHook>>,
2379}
2380
2381pub trait PackFactory: Send + Sync + 'static {
2389 fn name(&self) -> &'static str;
2391
2392 fn requires(&self) -> &'static [&'static str] {
2399 &[]
2400 }
2401
2402 fn create(&self, runtime: KhiveRuntime) -> Box<dyn PackRuntime>;
2404
2405 fn create_install(&self, runtime: KhiveRuntime) -> PackInstall {
2414 let resolver = self.create_resolver(runtime.clone());
2415 PackInstall {
2416 runtime: self.create(runtime),
2417 resolver,
2418 dispatch_hook: None,
2419 }
2420 }
2421
2422 fn create_resolver(&self, _runtime: KhiveRuntime) -> Option<Box<dyn PackByIdResolver>> {
2428 None
2429 }
2430}
2431
2432pub struct PackRegistration(pub &'static dyn PackFactory);
2436
2437inventory::collect!(PackRegistration);
2438
2439#[derive(Debug)]
2441pub enum PackLoadError {
2442 UnknownPack(String),
2444 MissingDependency {
2446 pack: String,
2448 dep: String,
2450 },
2451}
2452
2453impl std::fmt::Display for PackLoadError {
2454 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2455 match self {
2456 PackLoadError::UnknownPack(name) => write!(f, "unknown pack {name:?}"),
2457 PackLoadError::MissingDependency { pack, dep } => write!(
2458 f,
2459 "pack {pack:?} requires {dep:?}, which is not in the requested pack list; \
2460 add --pack {dep} before --pack {pack}"
2461 ),
2462 }
2463 }
2464}
2465
2466impl std::error::Error for PackLoadError {}
2467
2468pub struct PackRegistry;
2473
2474impl PackRegistry {
2475 pub fn discovered_names() -> Vec<&'static str> {
2477 inventory::iter::<PackRegistration>
2478 .into_iter()
2479 .map(|r| r.0.name())
2480 .collect()
2481 }
2482
2483 pub fn register_packs(
2496 names: &[String],
2497 runtime: KhiveRuntime,
2498 builder: &mut VerbRegistryBuilder,
2499 ) -> Result<(), PackLoadError> {
2500 let all: Vec<&'static dyn PackFactory> = inventory::iter::<PackRegistration>
2502 .into_iter()
2503 .map(|r| r.0)
2504 .collect();
2505 let factory_for = |name: &str| -> Option<&'static dyn PackFactory> {
2506 all.iter().copied().find(|f| f.name() == name)
2507 };
2508
2509 let requested: std::collections::HashSet<&str> = names.iter().map(String::as_str).collect();
2511 for name in names {
2512 factory_for(name.as_str()).ok_or_else(|| PackLoadError::UnknownPack(name.clone()))?;
2513 }
2514
2515 for name in names {
2518 let factory = factory_for(name.as_str()).unwrap(); for &dep in factory.requires() {
2520 if !requested.contains(dep) {
2521 return Err(PackLoadError::MissingDependency {
2522 pack: name.clone(),
2523 dep: dep.to_string(),
2524 });
2525 }
2526 }
2527 }
2528
2529 for name in names {
2532 let factory = factory_for(name.as_str()).unwrap(); let install = factory.create_install(runtime.clone());
2534 builder.register_boxed(install.runtime);
2535 if let Some(resolver) = install.resolver {
2536 builder.register_resolver(name.clone(), resolver);
2537 }
2538 if let Some(hook) = install.dispatch_hook {
2539 builder.with_dispatch_hook(hook);
2540 }
2541 }
2542
2543 Ok(())
2544 }
2545
2546 pub fn register_packs_with_runtimes(
2556 names: &[String],
2557 runtimes: &HashMap<String, KhiveRuntime>,
2558 default_runtime: &KhiveRuntime,
2559 builder: &mut VerbRegistryBuilder,
2560 ) -> Result<(), PackLoadError> {
2561 let all: Vec<&'static dyn PackFactory> = inventory::iter::<PackRegistration>
2562 .into_iter()
2563 .map(|r| r.0)
2564 .collect();
2565 let factory_for = |name: &str| -> Option<&'static dyn PackFactory> {
2566 all.iter().copied().find(|f| f.name() == name)
2567 };
2568
2569 let requested: std::collections::HashSet<&str> = names.iter().map(String::as_str).collect();
2570 for name in names {
2571 factory_for(name.as_str()).ok_or_else(|| PackLoadError::UnknownPack(name.clone()))?;
2572 }
2573
2574 for name in names {
2575 let factory = factory_for(name.as_str()).unwrap();
2576 for &dep in factory.requires() {
2577 if !requested.contains(dep) {
2578 return Err(PackLoadError::MissingDependency {
2579 pack: name.clone(),
2580 dep: dep.to_string(),
2581 });
2582 }
2583 }
2584 }
2585
2586 for name in names {
2587 let factory = factory_for(name.as_str()).unwrap();
2588 let runtime = runtimes
2589 .get(name.as_str())
2590 .cloned()
2591 .unwrap_or_else(|| default_runtime.clone());
2592 let install = factory.create_install(runtime);
2593 builder.register_boxed(install.runtime);
2594 if let Some(resolver) = install.resolver {
2595 builder.register_resolver(name.clone(), resolver);
2596 }
2597 if let Some(hook) = install.dispatch_hook {
2598 builder.with_dispatch_hook(hook);
2599 }
2600 }
2601
2602 Ok(())
2603 }
2604}
2605
2606fn target_id_from_args(args: &serde_json::Value) -> Option<uuid::Uuid> {
2607 args.get("target_id")
2608 .and_then(serde_json::Value::as_str)
2609 .and_then(|s| s.parse::<uuid::Uuid>().ok())
2610}
2611
2612fn build_audit_storage_event(
2615 gate_req: &GateRequest,
2616 audit: &AuditEvent,
2617 outcome: EventOutcome,
2618 resource: Option<Value>,
2619) -> Event {
2620 let mut audit_data = serde_json::to_value(audit).unwrap_or_else(|e| {
2621 tracing::warn!(error = %e, "failed to serialize AuditEvent for EventStore");
2622 serde_json::Value::Null
2623 });
2624 if let Some(resource) = resource {
2625 if let Value::Object(ref mut map) = audit_data {
2626 map.insert("resource".to_string(), resource);
2627 }
2628 }
2629 let mut storage_event = Event::new(
2630 gate_req.namespace.as_str(),
2631 gate_req.verb.as_str(),
2632 EventKind::Audit,
2633 SubstrateKind::Event,
2634 format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
2635 )
2636 .with_outcome(outcome)
2637 .with_payload(audit_data);
2638 if let Some(target_id) = target_id_from_args(&gate_req.args) {
2639 storage_event = storage_event.with_target(target_id);
2640 }
2641 storage_event
2642}
2643
2644async fn append_audit_event_best_effort(store: &Arc<dyn EventStore>, event: Event, verb: &str) {
2649 if let Err(store_err) = store.append_event(event).await {
2650 tracing::warn!(
2651 verb,
2652 error = %store_err,
2653 "audit event store write failed (non-fatal)"
2654 );
2655 }
2656}
2657
2658#[derive(Debug, Clone, serde::Serialize)]
2661struct LinkAuditSuccessV2 {
2662 #[serde(flatten)]
2663 audit: AuditEvent,
2664 edge_id: uuid::Uuid,
2665 source_id: uuid::Uuid,
2666 target_id: uuid::Uuid,
2667 relation: String,
2668 weight: f64,
2669}
2670
2671fn link_audit_success_from_result(
2675 audit: AuditEvent,
2676 result: &serde_json::Value,
2677) -> Option<(uuid::Uuid, serde_json::Value)> {
2678 let edge_id = result.get("id")?.as_str()?.parse::<uuid::Uuid>().ok()?;
2679 let source_id = result
2680 .get("source_id")?
2681 .as_str()?
2682 .parse::<uuid::Uuid>()
2683 .ok()?;
2684 let target_id = result
2685 .get("target_id")?
2686 .as_str()?
2687 .parse::<uuid::Uuid>()
2688 .ok()?;
2689 let relation = result.get("relation")?.as_str()?.to_string();
2690 let weight = result.get("weight")?.as_f64()?;
2691 let enriched = LinkAuditSuccessV2 {
2692 audit,
2693 edge_id,
2694 source_id,
2695 target_id,
2696 relation,
2697 weight,
2698 };
2699 let payload = serde_json::to_value(&enriched).ok()?;
2700 Some((edge_id, payload))
2701}
2702
2703pub fn resolve_explicit_namespace(
2716 params: &Value,
2717 default_namespace: &str,
2718) -> Result<Namespace, RuntimeError> {
2719 match params.get("namespace") {
2720 None => Namespace::parse(default_namespace)
2721 .map_err(|e| RuntimeError::InvalidInput(format!("invalid namespace: {e}"))),
2722 Some(Value::String(ns_str)) => Namespace::parse(ns_str)
2723 .map_err(|e| RuntimeError::InvalidInput(format!("invalid namespace {ns_str:?}: {e}"))),
2724 Some(other) => Err(RuntimeError::InvalidInput(format!(
2725 "invalid namespace: expected string when present, got {}",
2726 json_type_name(other),
2727 ))),
2728 }
2729}
2730
2731pub fn json_type_name(v: &Value) -> &'static str {
2734 match v {
2735 Value::Null => "null",
2736 Value::Bool(_) => "boolean",
2737 Value::Number(_) => "number",
2738 Value::String(_) => "string",
2739 Value::Array(_) => "array",
2740 Value::Object(_) => "object",
2741 }
2742}
2743
2744#[cfg(test)]
2750mod tests {
2751 use super::*;
2752 use crate::ActorRef;
2753 use khive_types::Pack;
2754
2755 #[test]
2756 fn from_token_preserves_process_ref() {
2757 let with_ref = NamespaceToken::mint_authorized(
2758 Namespace::local(),
2759 ActorRef::new("agent", "provenance-carrier"),
2760 )
2761 .with_process_ref(Some("proc:origin-abc123".to_string()));
2762 let identity = RequestIdentity::from_token(&with_ref);
2763 assert_eq!(identity.process_ref.as_deref(), Some("proc:origin-abc123"));
2764
2765 let without_ref = NamespaceToken::mint_authorized(
2766 Namespace::local(),
2767 ActorRef::new("agent", "provenance-absent"),
2768 );
2769 let identity = RequestIdentity::from_token(&without_ref);
2770 assert_eq!(identity.process_ref, None);
2771 }
2772
2773 struct AlphaPack;
2774
2775 impl Pack for AlphaPack {
2776 const NAME: &'static str = "alpha";
2777 const NOTE_KINDS: &'static [&'static str] = &["memo", "log"];
2778 const ENTITY_KINDS: &'static [&'static str] = &["widget"];
2779 const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["recall", "search"];
2780 const HANDLERS: &'static [HandlerDef] = &[
2781 HandlerDef {
2782 name: "create",
2783 description: "create a widget",
2784 visibility: Visibility::Verb,
2785 category: VerbCategory::Commissive,
2786 params: &[],
2787 },
2788 HandlerDef {
2789 name: "list",
2790 description: "list widgets",
2791 visibility: Visibility::Verb,
2792 category: VerbCategory::Assertive,
2793 params: &[],
2794 },
2795 ];
2796 }
2797
2798 #[async_trait]
2799 impl PackRuntime for AlphaPack {
2800 fn name(&self) -> &str {
2801 AlphaPack::NAME
2802 }
2803 fn note_kinds(&self) -> &'static [&'static str] {
2804 AlphaPack::NOTE_KINDS
2805 }
2806 fn entity_kinds(&self) -> &'static [&'static str] {
2807 AlphaPack::ENTITY_KINDS
2808 }
2809 fn brain_consumer_kinds(&self) -> &'static [&'static str] {
2810 AlphaPack::BRAIN_CONSUMER_KINDS
2811 }
2812 fn handlers(&self) -> &'static [HandlerDef] {
2813 AlphaPack::HANDLERS
2814 }
2815 async fn dispatch(
2816 &self,
2817 verb: &str,
2818 _params: Value,
2819 _registry: &VerbRegistry,
2820 _token: &NamespaceToken,
2821 ) -> Result<Value, RuntimeError> {
2822 Ok(serde_json::json!({ "pack": "alpha", "verb": verb }))
2823 }
2824 }
2825
2826 struct SleepingPack;
2830
2831 impl Pack for SleepingPack {
2832 const NAME: &'static str = "sleeping";
2833 const NOTE_KINDS: &'static [&'static str] = &[];
2834 const ENTITY_KINDS: &'static [&'static str] = &[];
2835 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
2836 name: "slow_op",
2837 description: "sleeps before returning",
2838 visibility: Visibility::Verb,
2839 category: VerbCategory::Assertive,
2840 params: &[],
2841 }];
2842 }
2843
2844 #[async_trait]
2845 impl PackRuntime for SleepingPack {
2846 fn name(&self) -> &str {
2847 SleepingPack::NAME
2848 }
2849 fn note_kinds(&self) -> &'static [&'static str] {
2850 SleepingPack::NOTE_KINDS
2851 }
2852 fn entity_kinds(&self) -> &'static [&'static str] {
2853 SleepingPack::ENTITY_KINDS
2854 }
2855 fn handlers(&self) -> &'static [HandlerDef] {
2856 SleepingPack::HANDLERS
2857 }
2858 async fn dispatch(
2859 &self,
2860 verb: &str,
2861 _params: Value,
2862 _registry: &VerbRegistry,
2863 _token: &NamespaceToken,
2864 ) -> Result<Value, RuntimeError> {
2865 tokio::time::sleep(std::time::Duration::from_millis(20)).await;
2866 Ok(serde_json::json!({ "pack": "sleeping", "verb": verb }))
2867 }
2868 }
2869
2870 struct BetaPack;
2871
2872 impl Pack for BetaPack {
2873 const NAME: &'static str = "beta";
2874 const NOTE_KINDS: &'static [&'static str] = &["alert"];
2875 const ENTITY_KINDS: &'static [&'static str] = &["widget", "gadget"];
2876 const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["search", "knowledge_compose"];
2877 const HANDLERS: &'static [HandlerDef] = &[
2878 HandlerDef {
2879 name: "notify",
2880 description: "send alert",
2881 visibility: Visibility::Verb,
2882 category: VerbCategory::Commissive,
2883 params: &[],
2884 },
2885 HandlerDef {
2889 name: "create",
2890 description: "beta internal create (subhandler)",
2891 visibility: Visibility::Subhandler,
2892 category: VerbCategory::Commissive,
2893 params: &[],
2894 },
2895 ];
2896 }
2897
2898 fn build_registry() -> VerbRegistry {
2904 let mut builder = VerbRegistryBuilder::new();
2905 builder.register(AlphaPack);
2906 builder.register(BetaPack);
2907 builder.build().expect("registry builds without collision")
2908 }
2909
2910 struct CollidingPack;
2913
2914 impl Pack for CollidingPack {
2915 const NAME: &'static str = "colliding";
2916 const NOTE_KINDS: &'static [&'static str] = &[];
2917 const ENTITY_KINDS: &'static [&'static str] = &[];
2918 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
2919 name: "create",
2920 description: "duplicate Verb-visibility create",
2921 visibility: Visibility::Verb,
2922 category: VerbCategory::Commissive,
2923 params: &[],
2924 }];
2925 }
2926
2927 #[async_trait]
2928 impl PackRuntime for CollidingPack {
2929 fn name(&self) -> &str {
2930 Self::NAME
2931 }
2932 fn note_kinds(&self) -> &'static [&'static str] {
2933 Self::NOTE_KINDS
2934 }
2935 fn entity_kinds(&self) -> &'static [&'static str] {
2936 Self::ENTITY_KINDS
2937 }
2938 fn handlers(&self) -> &'static [HandlerDef] {
2939 Self::HANDLERS
2940 }
2941 async fn dispatch(
2942 &self,
2943 verb: &str,
2944 _params: Value,
2945 _registry: &VerbRegistry,
2946 _token: &NamespaceToken,
2947 ) -> Result<Value, RuntimeError> {
2948 Ok(serde_json::json!({ "pack": "colliding", "verb": verb }))
2949 }
2950 }
2951
2952 #[async_trait]
2953 impl PackRuntime for BetaPack {
2954 fn name(&self) -> &str {
2955 BetaPack::NAME
2956 }
2957 fn note_kinds(&self) -> &'static [&'static str] {
2958 BetaPack::NOTE_KINDS
2959 }
2960 fn entity_kinds(&self) -> &'static [&'static str] {
2961 BetaPack::ENTITY_KINDS
2962 }
2963 fn brain_consumer_kinds(&self) -> &'static [&'static str] {
2964 BetaPack::BRAIN_CONSUMER_KINDS
2965 }
2966 fn handlers(&self) -> &'static [HandlerDef] {
2967 BetaPack::HANDLERS
2968 }
2969 async fn dispatch(
2970 &self,
2971 verb: &str,
2972 _params: Value,
2973 _registry: &VerbRegistry,
2974 _token: &NamespaceToken,
2975 ) -> Result<Value, RuntimeError> {
2976 Ok(serde_json::json!({ "pack": "beta", "verb": verb }))
2977 }
2978 }
2979
2980 #[tokio::test]
2981 async fn dispatch_routes_to_correct_pack() {
2982 let reg = build_registry();
2983
2984 let res = reg.dispatch("list", Value::Null).await.unwrap();
2985 assert_eq!(res["pack"], "alpha");
2986
2987 let res = reg.dispatch("notify", Value::Null).await.unwrap();
2988 assert_eq!(res["pack"], "beta");
2989 }
2990
2991 #[test]
2995 fn verb_collision_is_boot_time_error() {
2996 let mut builder = VerbRegistryBuilder::new();
2997 builder.register(AlphaPack);
2998 builder.register(CollidingPack);
2999 let err = builder
3000 .build()
3001 .err()
3002 .expect("duplicate Verb-visibility handler must be rejected at build time");
3003 assert!(
3004 matches!(err, RuntimeError::VerbCollision { ref verb, .. } if verb == "create"),
3005 "expected VerbCollision for 'create', got {err:?}"
3006 );
3007 let msg = err.to_string();
3008 assert!(
3009 msg.contains("create"),
3010 "error must name the colliding verb: {msg}"
3011 );
3012 assert!(
3013 msg.contains("alpha") || msg.contains("colliding"),
3014 "error must name one of the conflicting packs: {msg}"
3015 );
3016 }
3017
3018 #[test]
3022 fn subhandler_same_name_across_packs_is_not_a_collision() {
3023 struct SubhandlerPack;
3024 impl Pack for SubhandlerPack {
3025 const NAME: &'static str = "subhandler_pack";
3026 const NOTE_KINDS: &'static [&'static str] = &[];
3027 const ENTITY_KINDS: &'static [&'static str] = &[];
3028 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
3029 name: "create",
3030 description: "internal create",
3031 visibility: Visibility::Subhandler,
3032 category: VerbCategory::Commissive,
3033 params: &[],
3034 }];
3035 }
3036 #[async_trait]
3037 impl PackRuntime for SubhandlerPack {
3038 fn name(&self) -> &str {
3039 Self::NAME
3040 }
3041 fn note_kinds(&self) -> &'static [&'static str] {
3042 Self::NOTE_KINDS
3043 }
3044 fn entity_kinds(&self) -> &'static [&'static str] {
3045 Self::ENTITY_KINDS
3046 }
3047 fn handlers(&self) -> &'static [HandlerDef] {
3048 Self::HANDLERS
3049 }
3050 async fn dispatch(
3051 &self,
3052 verb: &str,
3053 _: Value,
3054 _: &VerbRegistry,
3055 _: &NamespaceToken,
3056 ) -> Result<Value, RuntimeError> {
3057 Ok(serde_json::json!({"pack": "subhandler_pack", "verb": verb}))
3058 }
3059 }
3060 let mut builder = VerbRegistryBuilder::new();
3061 builder.register(AlphaPack); builder.register(SubhandlerPack); builder
3064 .build()
3065 .expect("subhandler same name must NOT be a collision");
3066 }
3067
3068 #[tokio::test]
3069 async fn dispatch_unknown_verb_returns_error() {
3070 let reg = build_registry();
3071
3072 let err = reg.dispatch("explode", Value::Null).await.unwrap_err();
3073 let msg = err.to_string();
3074 assert!(msg.contains("explode"));
3075 assert!(msg.contains("create"));
3076 }
3077
3078 #[test]
3083 fn all_verbs_aggregates_across_packs_excludes_subhandlers() {
3084 let reg = build_registry();
3085 let verbs: Vec<&str> = reg.all_verbs().iter().map(|v| v.name).collect();
3086 assert_eq!(verbs, vec!["create", "list", "notify"]);
3088 }
3089
3090 #[test]
3091 fn all_verbs_with_names_pairs_pack_name_excludes_subhandlers() {
3092 let reg = build_registry();
3093 let pairs: Vec<(&str, &str)> = reg
3094 .all_verbs_with_names()
3095 .iter()
3096 .map(|(pack, v)| (*pack, v.name))
3097 .collect();
3098 assert_eq!(
3100 pairs,
3101 vec![("alpha", "create"), ("alpha", "list"), ("beta", "notify"),]
3102 );
3103 }
3104
3105 #[test]
3106 fn all_handlers_with_names_includes_subhandlers() {
3107 let reg = build_registry();
3108 let pairs: Vec<(&str, &str)> = reg
3109 .all_handlers_with_names()
3110 .iter()
3111 .map(|(pack, v)| (*pack, v.name))
3112 .collect();
3113 assert_eq!(
3115 pairs,
3116 vec![
3117 ("alpha", "create"),
3118 ("alpha", "list"),
3119 ("beta", "notify"),
3120 ("beta", "create"),
3121 ]
3122 );
3123 }
3124
3125 #[test]
3126 fn note_kinds_are_ordered() {
3127 let reg = build_registry();
3128 let kinds = reg.all_note_kinds();
3129 assert_eq!(kinds, vec!["memo", "log", "alert"]);
3130 }
3131
3132 #[test]
3133 fn brain_consumer_kinds_are_ordered_and_deduplicated() {
3134 let reg = build_registry();
3135 assert_eq!(
3136 reg.all_brain_consumer_kinds(),
3137 vec!["recall", "search", "knowledge_compose"]
3138 );
3139 }
3140
3141 #[test]
3142 fn brain_consumer_kind_wildcard_is_rejected_at_build_time() {
3143 struct WildcardConsumerPack;
3144
3145 impl khive_types::Pack for WildcardConsumerPack {
3146 const NAME: &'static str = "wildcard-consumer";
3147 const NOTE_KINDS: &'static [&'static str] = &[];
3148 const ENTITY_KINDS: &'static [&'static str] = &[];
3149 const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["*"];
3150 const HANDLERS: &'static [HandlerDef] = &[];
3151 }
3152
3153 #[async_trait]
3154 impl PackRuntime for WildcardConsumerPack {
3155 fn name(&self) -> &str {
3156 Self::NAME
3157 }
3158 fn note_kinds(&self) -> &'static [&'static str] {
3159 Self::NOTE_KINDS
3160 }
3161 fn entity_kinds(&self) -> &'static [&'static str] {
3162 Self::ENTITY_KINDS
3163 }
3164 fn brain_consumer_kinds(&self) -> &'static [&'static str] {
3165 Self::BRAIN_CONSUMER_KINDS
3166 }
3167 fn handlers(&self) -> &'static [HandlerDef] {
3168 Self::HANDLERS
3169 }
3170 async fn dispatch(
3171 &self,
3172 _verb: &str,
3173 _params: Value,
3174 _registry: &VerbRegistry,
3175 _token: &NamespaceToken,
3176 ) -> Result<Value, RuntimeError> {
3177 Ok(Value::Null)
3178 }
3179 }
3180
3181 let mut builder = VerbRegistryBuilder::new();
3182 builder.register(WildcardConsumerPack);
3183 let Err(RuntimeError::InvalidInput(message)) = builder.build() else {
3184 panic!("registry must reject a pack-declared brain wildcard");
3185 };
3186 assert!(message.contains("wildcard-consumer"), "{message}");
3187 assert!(message.contains("registry-owned"), "{message}");
3188 }
3189
3190 #[test]
3191 fn note_kind_duplicate_rejected_at_build_time() {
3192 struct DupPack;
3193
3194 impl khive_types::Pack for DupPack {
3195 const NAME: &'static str = "dup";
3196 const NOTE_KINDS: &'static [&'static str] = &["memo"];
3198 const ENTITY_KINDS: &'static [&'static str] = &[];
3199 const HANDLERS: &'static [HandlerDef] = &[];
3200 }
3201
3202 #[async_trait]
3203 impl PackRuntime for DupPack {
3204 fn name(&self) -> &str {
3205 Self::NAME
3206 }
3207 fn note_kinds(&self) -> &'static [&'static str] {
3208 Self::NOTE_KINDS
3209 }
3210 fn entity_kinds(&self) -> &'static [&'static str] {
3211 Self::ENTITY_KINDS
3212 }
3213 fn handlers(&self) -> &'static [HandlerDef] {
3214 Self::HANDLERS
3215 }
3216 async fn dispatch(
3217 &self,
3218 _verb: &str,
3219 _params: Value,
3220 _registry: &VerbRegistry,
3221 _token: &NamespaceToken,
3222 ) -> Result<Value, RuntimeError> {
3223 Ok(Value::Null)
3224 }
3225 }
3226
3227 let mut builder = VerbRegistryBuilder::new();
3228 builder.register(AlphaPack);
3229 builder.register(DupPack);
3230 let err = builder
3231 .build()
3232 .err()
3233 .expect("duplicate note kind must be rejected");
3234 let msg = err.to_string();
3235 assert!(
3236 msg.contains("memo"),
3237 "error must name the duplicate kind: {msg}"
3238 );
3239 assert!(
3240 msg.contains("alpha") || msg.contains("dup"),
3241 "error must name one of the conflicting packs: {msg}"
3242 );
3243 }
3244
3245 #[test]
3246 fn entity_kinds_are_deduplicated() {
3247 let reg = build_registry();
3248 let kinds = reg.all_entity_kinds();
3249 assert_eq!(kinds, vec!["widget", "gadget"]);
3250 }
3251
3252 struct GammaPack;
3255
3256 impl Pack for GammaPack {
3257 const NAME: &'static str = "gamma";
3258 const NOTE_KINDS: &'static [&'static str] = &[];
3259 const ENTITY_KINDS: &'static [&'static str] = &[];
3260 const HANDLERS: &'static [HandlerDef] = &[];
3261 const ENTITY_TYPES: &'static [EntityTypeDef] = &[EntityTypeDef {
3262 kind: khive_types::EntityKind::Document,
3263 type_name: "gamma_report",
3264 aliases: &["gamma_rep"],
3265 }];
3266 }
3267
3268 #[async_trait]
3269 impl PackRuntime for GammaPack {
3270 fn name(&self) -> &str {
3271 Self::NAME
3272 }
3273 fn note_kinds(&self) -> &'static [&'static str] {
3274 Self::NOTE_KINDS
3275 }
3276 fn entity_kinds(&self) -> &'static [&'static str] {
3277 Self::ENTITY_KINDS
3278 }
3279 fn handlers(&self) -> &'static [HandlerDef] {
3280 Self::HANDLERS
3281 }
3282 fn entity_types(&self) -> &'static [EntityTypeDef] {
3283 Self::ENTITY_TYPES
3284 }
3285 async fn dispatch(
3286 &self,
3287 verb: &str,
3288 _params: Value,
3289 _registry: &VerbRegistry,
3290 _token: &NamespaceToken,
3291 ) -> Result<Value, RuntimeError> {
3292 Ok(serde_json::json!({ "pack": "gamma", "verb": verb }))
3293 }
3294 }
3295
3296 #[test]
3300 fn all_entity_types_empty_when_no_pack_declares_extras() {
3301 let reg = build_registry(); assert!(reg.all_entity_types().is_empty());
3303 let composed = khive_types::EntityTypeRegistry::with_extra(reg.all_entity_types());
3304 let resolved = composed
3305 .resolve(khive_types::EntityKind::Document, Some("paper"))
3306 .expect("builtin paper subtype must still resolve");
3307 assert_eq!(resolved.entity_type.as_deref(), Some("paper"));
3308 }
3309
3310 #[test]
3313 fn pack_declared_entity_type_validates_through_composed_registry() {
3314 let mut builder = VerbRegistryBuilder::new();
3315 builder.register(AlphaPack);
3316 builder.register(GammaPack);
3317 let reg = builder.build().expect("registry builds");
3318
3319 let extras = reg.all_entity_types();
3320 assert_eq!(extras.len(), 1);
3321
3322 let composed = khive_types::EntityTypeRegistry::with_extra(extras);
3323 let resolved = composed
3324 .resolve(khive_types::EntityKind::Document, Some("gamma_rep"))
3325 .expect("pack-declared alias must resolve through the composed registry");
3326 assert_eq!(resolved.entity_type.as_deref(), Some("gamma_report"));
3327
3328 let builtin_resolved = composed
3329 .resolve(khive_types::EntityKind::Document, Some("paper"))
3330 .expect("builtin subtype must remain resolvable when a pack adds extras");
3331 assert_eq!(builtin_resolved.entity_type.as_deref(), Some("paper"));
3332
3333 composed
3334 .resolve(khive_types::EntityKind::Document, Some("nonexistent_type"))
3335 .expect_err("undeclared entity_type must still be rejected");
3336 }
3337
3338 #[test]
3344 fn overlapping_pack_declared_entity_types_reject_at_boot() {
3345 struct DeltaPack;
3346 impl Pack for DeltaPack {
3347 const NAME: &'static str = "delta";
3348 const NOTE_KINDS: &'static [&'static str] = &[];
3349 const ENTITY_KINDS: &'static [&'static str] = &[];
3350 const HANDLERS: &'static [HandlerDef] = &[];
3351 const ENTITY_TYPES: &'static [EntityTypeDef] = &[EntityTypeDef {
3352 kind: khive_types::EntityKind::Document,
3353 type_name: "gamma_report",
3354 aliases: &["gamma_rep"],
3355 }];
3356 }
3357 #[async_trait]
3358 impl PackRuntime for DeltaPack {
3359 fn name(&self) -> &str {
3360 Self::NAME
3361 }
3362 fn note_kinds(&self) -> &'static [&'static str] {
3363 Self::NOTE_KINDS
3364 }
3365 fn entity_kinds(&self) -> &'static [&'static str] {
3366 Self::ENTITY_KINDS
3367 }
3368 fn handlers(&self) -> &'static [HandlerDef] {
3369 Self::HANDLERS
3370 }
3371 fn entity_types(&self) -> &'static [EntityTypeDef] {
3372 Self::ENTITY_TYPES
3373 }
3374 async fn dispatch(
3375 &self,
3376 verb: &str,
3377 _params: Value,
3378 _registry: &VerbRegistry,
3379 _token: &NamespaceToken,
3380 ) -> Result<Value, RuntimeError> {
3381 Ok(serde_json::json!({ "pack": "delta", "verb": verb }))
3382 }
3383 }
3384
3385 let mut builder = VerbRegistryBuilder::new();
3386 builder.register(GammaPack);
3387 builder.register(DeltaPack);
3388 let err = builder.build().err().expect(
3389 "overlapping ENTITY_TYPES declarations must fail at build, not silently compose",
3390 );
3391
3392 let msg = err.to_string();
3393 assert!(
3394 msg.contains("gamma") && msg.contains("delta"),
3395 "collision error must name both contributing packs: {msg}"
3396 );
3397 assert!(
3398 msg.contains("gamma_report"),
3399 "collision error must name the colliding entity_type key: {msg}"
3400 );
3401 }
3402
3403 use khive_gate::{Gate, GateError};
3406 use std::sync::atomic::{AtomicUsize, Ordering};
3407 use std::sync::Arc;
3408
3409 #[derive(Default, Debug)]
3410 struct CountingGate {
3411 calls: AtomicUsize,
3412 deny_verb: Option<&'static str>,
3413 }
3414
3415 impl Gate for CountingGate {
3416 fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
3417 self.calls.fetch_add(1, Ordering::SeqCst);
3418 if Some(req.verb.as_str()) == self.deny_verb {
3419 Ok(GateDecision::deny(format!("test deny for {}", req.verb)))
3420 } else {
3421 Ok(GateDecision::allow())
3422 }
3423 }
3424 }
3425
3426 #[tokio::test]
3427 async fn dispatch_consults_the_gate() {
3428 let gate = Arc::new(CountingGate::default());
3429 let mut builder = VerbRegistryBuilder::new();
3430 builder.register(AlphaPack);
3431 builder.with_gate(gate.clone());
3432 let reg = builder.build().expect("registry builds");
3433
3434 reg.dispatch("list", Value::Null).await.unwrap();
3435 reg.dispatch("create", Value::Null).await.unwrap();
3436 assert_eq!(
3437 gate.calls.load(Ordering::SeqCst),
3438 2,
3439 "gate should be consulted once per dispatch"
3440 );
3441 }
3442
3443 #[tokio::test]
3444 async fn dispatch_returns_permission_denied_on_deny_v03() {
3445 let gate = Arc::new(CountingGate {
3446 calls: AtomicUsize::new(0),
3447 deny_verb: Some("create"),
3448 });
3449 let mut builder = VerbRegistryBuilder::new();
3450 builder.register(AlphaPack);
3451 builder.with_gate(gate.clone());
3452 let reg = builder.build().expect("registry builds");
3453
3454 let err = reg.dispatch("create", Value::Null).await.unwrap_err();
3456 assert!(
3457 matches!(err, RuntimeError::PermissionDenied { ref verb, .. } if verb == "create"),
3458 "expected PermissionDenied, got {err:?}"
3459 );
3460 let msg = err.to_string();
3461 assert!(
3462 msg.contains("create"),
3463 "error message must name the verb: {msg}"
3464 );
3465 assert!(
3466 msg.contains("test deny for create"),
3467 "error message must carry the deny reason: {msg}"
3468 );
3469 assert_eq!(gate.calls.load(Ordering::SeqCst), 1);
3470 }
3471
3472 #[tokio::test]
3473 async fn dispatch_allow_verb_succeeds_even_with_deny_gate_for_other_verb() {
3474 let gate = Arc::new(CountingGate {
3476 calls: AtomicUsize::new(0),
3477 deny_verb: Some("create"),
3478 });
3479 let mut builder = VerbRegistryBuilder::new();
3480 builder.register(AlphaPack);
3481 builder.with_gate(gate.clone());
3482 let reg = builder.build().expect("registry builds");
3483
3484 let res = reg.dispatch("list", Value::Null).await.unwrap();
3485 assert_eq!(res["pack"], "alpha");
3486 }
3487
3488 #[tokio::test]
3489 async fn dispatch_uses_allow_all_gate_by_default() {
3490 let reg = build_registry();
3492 let res = reg.dispatch("list", Value::Null).await.unwrap();
3493 assert_eq!(res["pack"], "alpha");
3494 }
3495
3496 #[derive(Default, Debug)]
3499 struct NamespaceCapturingGate {
3500 seen: std::sync::Mutex<Vec<String>>,
3501 }
3502
3503 impl Gate for NamespaceCapturingGate {
3504 fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
3505 self.seen
3506 .lock()
3507 .unwrap()
3508 .push(req.namespace.as_str().to_string());
3509 Ok(GateDecision::allow())
3510 }
3511 }
3512
3513 #[tokio::test]
3514 async fn dispatch_propagates_params_namespace_to_gate() {
3515 let gate = Arc::new(NamespaceCapturingGate::default());
3516 let mut builder = VerbRegistryBuilder::new();
3517 builder.register(AlphaPack);
3518 builder.with_gate(gate.clone());
3519 builder.with_default_namespace("tenant-x");
3520 let reg = builder.build().expect("registry builds");
3521
3522 reg.dispatch("list", serde_json::json!({"namespace": "tenant-y"}))
3524 .await
3525 .unwrap();
3526 reg.dispatch("list", Value::Null).await.unwrap();
3528 let err = reg
3530 .dispatch("list", serde_json::json!({"namespace": ""}))
3531 .await
3532 .unwrap_err();
3533 assert!(
3534 matches!(err, RuntimeError::InvalidInput(_)),
3535 "empty namespace must return InvalidInput, got {err:?}"
3536 );
3537
3538 let seen = gate.seen.lock().unwrap().clone();
3539 assert_eq!(seen, vec!["tenant-y", "tenant-x"]);
3540 }
3541
3542 #[tokio::test]
3543 async fn dispatch_falls_back_to_local_when_no_default_set() {
3544 let gate = Arc::new(NamespaceCapturingGate::default());
3546 let mut builder = VerbRegistryBuilder::new();
3547 builder.register(AlphaPack);
3548 builder.with_gate(gate.clone());
3549 let reg = builder.build().expect("registry builds");
3550
3551 reg.dispatch("list", Value::Null).await.unwrap();
3552 let seen = gate.seen.lock().unwrap().clone();
3553 assert_eq!(seen, vec!["local"]);
3554 }
3555
3556 #[tokio::test]
3562 async fn namespace_null_rejected_not_coerced() {
3563 let cases: Vec<(&str, Value)> = vec![
3564 ("null", Value::Null),
3565 ("number", serde_json::json!(42)),
3566 ("boolean", serde_json::json!(true)),
3567 ("array", serde_json::json!(["local"])),
3568 ("object", serde_json::json!({"ns": "local"})),
3569 ];
3570
3571 for (label, ns_value) in cases {
3572 let gate = Arc::new(NamespaceCapturingGate::default());
3573 let mut builder = VerbRegistryBuilder::new();
3574 builder.register(AlphaPack);
3575 builder.with_gate(gate.clone());
3576 builder.with_default_namespace("tenant-x");
3577 let reg = builder.build().expect("registry builds");
3578
3579 let err = reg
3580 .dispatch("list", serde_json::json!({"namespace": ns_value}))
3581 .await
3582 .unwrap_err();
3583 assert!(
3584 matches!(err, RuntimeError::InvalidInput(_)),
3585 "case {label}: expected InvalidInput, got {err:?}"
3586 );
3587
3588 let seen = gate.seen.lock().unwrap().clone();
3592 assert!(
3593 seen.is_empty(),
3594 "case {label}: gate must not be consulted for malformed namespace, saw {seen:?}"
3595 );
3596 }
3597 }
3598
3599 use khive_gate::{AuditDecision, AuditEvent, Obligation};
3602
3603 #[derive(Default, Debug)]
3605 struct AuditCapturingGate {
3606 events: std::sync::Mutex<Vec<AuditEvent>>,
3607 deny_verb: Option<&'static str>,
3608 }
3609
3610 impl Gate for AuditCapturingGate {
3611 fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
3612 let decision = if Some(req.verb.as_str()) == self.deny_verb {
3613 GateDecision::deny("test deny")
3614 } else {
3615 GateDecision::allow_with(vec![Obligation::Audit {
3616 tag: format!("{}.check", req.verb),
3617 }])
3618 };
3619 let ev = AuditEvent::from_check(req, &decision, self.impl_name());
3621 self.events.lock().unwrap().push(ev);
3622 Ok(decision)
3623 }
3624
3625 fn impl_name(&self) -> &'static str {
3626 "AuditCapturingGate"
3627 }
3628 }
3629
3630 #[tokio::test]
3631 async fn dispatch_emits_one_audit_event_per_call() {
3632 let gate = Arc::new(AuditCapturingGate::default());
3633 let mut builder = VerbRegistryBuilder::new();
3634 builder.register(AlphaPack);
3635 builder.with_gate(gate.clone());
3636 let reg = builder.build().expect("registry builds");
3637
3638 reg.dispatch("list", Value::Null).await.unwrap();
3639 reg.dispatch("create", Value::Null).await.unwrap();
3640
3641 let evs = gate.events.lock().unwrap();
3642 assert_eq!(evs.len(), 2, "exactly one audit event per dispatch call");
3643 }
3644
3645 #[tokio::test]
3646 async fn dispatch_audit_event_allow_carries_obligations() {
3647 let gate = Arc::new(AuditCapturingGate::default());
3648 let mut builder = VerbRegistryBuilder::new();
3649 builder.register(AlphaPack);
3650 builder.with_gate(gate.clone());
3651 let reg = builder.build().expect("registry builds");
3652
3653 reg.dispatch("list", Value::Null).await.unwrap();
3654
3655 let evs = gate.events.lock().unwrap();
3656 let ev = &evs[0];
3657 assert_eq!(ev.verb, "list");
3658 assert_eq!(ev.decision, AuditDecision::Allow);
3659 assert!(ev.deny_reason.is_none());
3660 assert_eq!(ev.obligations.len(), 1);
3661 assert_eq!(ev.gate_impl, "AuditCapturingGate");
3662 }
3663
3664 #[tokio::test]
3665 async fn dispatch_audit_event_deny_carries_reason() {
3666 let gate = Arc::new(AuditCapturingGate {
3667 events: Default::default(),
3668 deny_verb: Some("create"),
3669 });
3670 let mut builder = VerbRegistryBuilder::new();
3671 builder.register(AlphaPack);
3672 builder.with_gate(gate.clone());
3673 let reg = builder.build().expect("registry builds");
3674
3675 let err = reg.dispatch("create", Value::Null).await.unwrap_err();
3678 assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
3679
3680 let evs = gate.events.lock().unwrap();
3681 let ev = &evs[0];
3682 assert_eq!(ev.verb, "create");
3683 assert_eq!(ev.decision, AuditDecision::Deny);
3684 assert_eq!(ev.deny_reason.as_deref(), Some("test deny"));
3685 assert!(ev.obligations.is_empty());
3686 }
3687
3688 #[tokio::test]
3689 async fn dispatch_audit_event_fields_match_gate_request() {
3690 let gate = Arc::new(AuditCapturingGate::default());
3691 let mut builder = VerbRegistryBuilder::new();
3692 builder.register(AlphaPack);
3693 builder.with_gate(gate.clone());
3694 builder.with_default_namespace("tenant-z");
3695 let reg = builder.build().expect("registry builds");
3696
3697 reg.dispatch("list", serde_json::json!({"namespace": "tenant-q"}))
3698 .await
3699 .unwrap();
3700
3701 let evs = gate.events.lock().unwrap();
3702 let ev = &evs[0];
3703 assert_eq!(ev.namespace, "tenant-q");
3705 assert_eq!(ev.verb, "list");
3706 assert_eq!(ev.actor.kind, "anonymous");
3707 }
3708
3709 #[derive(Default, Debug)]
3713 struct ActorCapturingGate {
3714 requests: std::sync::Mutex<Vec<GateRequest>>,
3715 }
3716
3717 impl Gate for ActorCapturingGate {
3718 fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
3719 self.requests.lock().unwrap().push(req.clone());
3720 Ok(GateDecision::allow())
3721 }
3722 }
3723
3724 #[tokio::test]
3728 async fn gate_request_carries_configured_actor_when_actor_id_is_set() {
3729 let gate = Arc::new(ActorCapturingGate::default());
3730 let mut builder = VerbRegistryBuilder::new();
3731 builder.register(AlphaPack);
3732 builder.with_gate(gate.clone());
3733 builder.with_actor_id(Some("team-abc:implementer".to_string()));
3734 let reg = builder.build().expect("registry builds");
3735
3736 reg.dispatch("list", Value::Null).await.unwrap();
3737
3738 let reqs = gate.requests.lock().unwrap();
3739 assert_eq!(reqs.len(), 1);
3740 let req = &reqs[0];
3741 assert_eq!(
3742 req.actor.kind, "actor",
3743 "gate request must carry kind='actor' when actor_id is configured"
3744 );
3745 assert_eq!(
3746 req.actor.id, "team-abc:implementer",
3747 "gate request must carry the configured actor id"
3748 );
3749 }
3750
3751 #[tokio::test]
3754 async fn gate_request_carries_anonymous_when_no_actor_id_configured() {
3755 let gate = Arc::new(ActorCapturingGate::default());
3756 let mut builder = VerbRegistryBuilder::new();
3757 builder.register(AlphaPack);
3758 builder.with_gate(gate.clone());
3759 let reg = builder.build().expect("registry builds");
3761
3762 reg.dispatch("list", Value::Null).await.unwrap();
3763
3764 let reqs = gate.requests.lock().unwrap();
3765 assert_eq!(reqs.len(), 1);
3766 let req = &reqs[0];
3767 assert_eq!(
3768 req.actor.kind, "anonymous",
3769 "gate request must carry anonymous actor when no actor_id is configured"
3770 );
3771 assert_eq!(req.actor.id, "local");
3772 }
3773
3774 struct TokenCapturingPack {
3777 actors: Arc<std::sync::Mutex<Vec<khive_gate::ActorRef>>>,
3778 }
3779
3780 impl Pack for TokenCapturingPack {
3781 const NAME: &'static str = "alpha";
3782 const NOTE_KINDS: &'static [&'static str] = &[];
3783 const ENTITY_KINDS: &'static [&'static str] = &[];
3784 const HANDLERS: &'static [HandlerDef] = AlphaPack::HANDLERS;
3785 }
3786
3787 #[async_trait]
3788 impl PackRuntime for TokenCapturingPack {
3789 fn name(&self) -> &str {
3790 Self::NAME
3791 }
3792 fn note_kinds(&self) -> &'static [&'static str] {
3793 Self::NOTE_KINDS
3794 }
3795 fn entity_kinds(&self) -> &'static [&'static str] {
3796 Self::ENTITY_KINDS
3797 }
3798 fn handlers(&self) -> &'static [HandlerDef] {
3799 Self::HANDLERS
3800 }
3801 async fn dispatch(
3802 &self,
3803 verb: &str,
3804 _params: Value,
3805 _registry: &VerbRegistry,
3806 token: &NamespaceToken,
3807 ) -> Result<Value, RuntimeError> {
3808 self.actors.lock().unwrap().push(token.actor().clone());
3809 Ok(serde_json::json!({ "pack": "alpha", "verb": verb }))
3810 }
3811 }
3812
3813 #[tokio::test]
3822 async fn gate_actor_and_token_actor_are_identical_when_actor_id_is_set() {
3823 let gate = Arc::new(ActorCapturingGate::default());
3824 let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
3825 let pack = TokenCapturingPack {
3826 actors: actors.clone(),
3827 };
3828 let mut builder = VerbRegistryBuilder::new();
3829 builder.register(pack);
3830 builder.with_gate(gate.clone());
3831 builder.with_actor_id(Some("actor-alpha".to_string()));
3832 let reg = builder.build().expect("registry builds");
3833
3834 reg.dispatch("list", Value::Null).await.unwrap();
3835
3836 let reqs = gate.requests.lock().unwrap();
3837 let gate_actor = reqs[0].actor.clone();
3838 drop(reqs);
3839
3840 let captured = actors.lock().unwrap();
3841 let token_actor = captured[0].clone();
3842
3843 assert_eq!(
3844 gate_actor.kind, token_actor.kind,
3845 "gate request actor and storage token actor must carry the same kind"
3846 );
3847 assert_eq!(
3848 gate_actor.id, token_actor.id,
3849 "gate request actor and storage token actor must carry the same id"
3850 );
3851 assert_eq!(gate_actor.id, "actor-alpha");
3852 }
3853
3854 #[tokio::test]
3857 async fn gate_actor_and_token_actor_are_identical_when_anonymous() {
3858 let gate = Arc::new(ActorCapturingGate::default());
3859 let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
3860 let pack = TokenCapturingPack {
3861 actors: actors.clone(),
3862 };
3863 let mut builder = VerbRegistryBuilder::new();
3864 builder.register(pack);
3865 builder.with_gate(gate.clone());
3866 let reg = builder.build().expect("registry builds");
3867
3868 reg.dispatch("list", Value::Null).await.unwrap();
3869
3870 let reqs = gate.requests.lock().unwrap();
3871 let gate_actor = reqs[0].actor.clone();
3872 drop(reqs);
3873
3874 let captured = actors.lock().unwrap();
3875 let token_actor = captured[0].clone();
3876
3877 assert_eq!(gate_actor.kind, token_actor.kind);
3878 assert_eq!(gate_actor.id, token_actor.id);
3879 assert_eq!(gate_actor.id, "local");
3880 }
3881
3882 #[tokio::test]
3889 async fn dispatch_as_threads_verified_actor_into_token() {
3890 let gate = Arc::new(ActorCapturingGate::default());
3891 let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
3892 let pack = TokenCapturingPack {
3893 actors: actors.clone(),
3894 };
3895 let mut builder = VerbRegistryBuilder::new();
3896 builder.register(pack);
3897 builder.with_gate(gate.clone());
3898 let reg = builder.build().expect("registry builds");
3899
3900 reg.dispatch_as(
3901 "list",
3902 Value::Null,
3903 VerifiedActor::new("gateway:principal-42").unwrap(),
3904 )
3905 .await
3906 .unwrap();
3907
3908 let reqs = gate.requests.lock().unwrap();
3909 assert_eq!(reqs[0].actor.kind, "actor");
3910 assert_eq!(reqs[0].actor.id, "gateway:principal-42");
3911 drop(reqs);
3912
3913 let captured = actors.lock().unwrap();
3914 assert_eq!(captured[0].kind, "actor");
3915 assert_eq!(
3916 captured[0].id, "gateway:principal-42",
3917 "the storage token actor must be the verified_actor supplied to dispatch_as, \
3918 matching exactly what pack handlers read as the acting principal"
3919 );
3920 }
3921
3922 #[tokio::test]
3927 async fn dispatch_as_does_not_change_plain_dispatch_behavior() {
3928 let gate = Arc::new(ActorCapturingGate::default());
3929 let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
3930 let pack = TokenCapturingPack {
3931 actors: actors.clone(),
3932 };
3933 let mut builder = VerbRegistryBuilder::new();
3934 builder.register(pack);
3935 builder.with_gate(gate.clone());
3936 builder.with_actor_id(Some("baked-actor".to_string()));
3937 let reg = builder.build().expect("registry builds");
3938
3939 reg.dispatch_as(
3940 "list",
3941 Value::Null,
3942 VerifiedActor::new("verified-actor").unwrap(),
3943 )
3944 .await
3945 .unwrap();
3946 reg.dispatch("list", Value::Null).await.unwrap();
3947
3948 let captured = actors.lock().unwrap();
3949 assert_eq!(captured.len(), 2);
3950 assert_eq!(captured[0].id, "verified-actor", "dispatch_as call");
3951 assert_eq!(
3952 captured[1].id, "baked-actor",
3953 "a later plain dispatch() call must still use the registry's baked \
3954 actor_id, unaffected by the prior dispatch_as call"
3955 );
3956 }
3957
3958 #[tokio::test]
3965 async fn dispatch_as_ignores_actor_key_in_params() {
3966 let gate = Arc::new(ActorCapturingGate::default());
3967 let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
3968 let pack = TokenCapturingPack {
3969 actors: actors.clone(),
3970 };
3971 let mut builder = VerbRegistryBuilder::new();
3972 builder.register(pack);
3973 builder.with_gate(gate.clone());
3974 let reg = builder.build().expect("registry builds");
3975
3976 reg.dispatch_as(
3977 "list",
3978 serde_json::json!({"actor": "spoofed-actor"}),
3979 VerifiedActor::new("verified-actor").unwrap(),
3980 )
3981 .await
3982 .unwrap();
3983
3984 let captured = actors.lock().unwrap();
3985 assert_eq!(
3986 captured[0].id, "verified-actor",
3987 "an 'actor' key inside params must never override the verified_actor \
3988 argument threaded through dispatch_as"
3989 );
3990 }
3991
3992 #[test]
3995 fn verified_actor_rejects_empty_identifier() {
3996 let err = VerifiedActor::new("").unwrap_err();
3997 assert!(
3998 matches!(err, RuntimeError::InvalidInput(_)),
3999 "expected InvalidInput, got {err:?}"
4000 );
4001 }
4002
4003 #[test]
4006 fn verified_actor_rejects_whitespace_only_identifier() {
4007 let err = VerifiedActor::new(" ").unwrap_err();
4008 assert!(
4009 matches!(err, RuntimeError::InvalidInput(_)),
4010 "expected InvalidInput, got {err:?}"
4011 );
4012 }
4013
4014 #[tokio::test]
4028 async fn rego_gate_missing_entrypoint_returns_permission_denied() {
4029 use khive_gate_rego::RegoGate;
4030
4031 let policy = r#"
4037 package khive.gate
4038 import rego.v1
4039 verdict := "allow"
4040 "#;
4041 let gate = Arc::new(RegoGate::from_policy_str(policy).expect("policy compiles"));
4042
4043 let mut builder = VerbRegistryBuilder::new();
4044 builder.register(AlphaPack);
4045 builder.with_gate(gate);
4046 let reg = builder.build().expect("registry builds");
4047
4048 let err = reg.dispatch("create", Value::Null).await.unwrap_err();
4049 assert!(
4050 matches!(err, RuntimeError::PermissionDenied { ref verb, .. } if verb == "create"),
4051 "expected PermissionDenied for missing rego entrypoint, got {err:?}"
4052 );
4053 }
4054
4055 use std::sync::{Mutex as StdMutex, Once, OnceLock};
4067
4068 use serial_test::serial;
4069 use tracing::field::{Field, Visit};
4070
4071 #[derive(Clone, Debug, Default)]
4072 struct CapturedEvent {
4073 message: Option<String>,
4074 audit_event: Option<String>,
4075 }
4076
4077 #[derive(Default)]
4078 struct CapturedEventVisitor(CapturedEvent);
4079
4080 impl Visit for CapturedEventVisitor {
4081 fn record_str(&mut self, field: &Field, value: &str) {
4082 match field.name() {
4083 "message" => self.0.message = Some(value.to_string()),
4084 "audit_event" => self.0.audit_event = Some(value.to_string()),
4085 _ => {}
4086 }
4087 }
4088
4089 fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
4090 let formatted = format!("{value:?}");
4096 let cleaned = formatted
4097 .trim_start_matches('"')
4098 .trim_end_matches('"')
4099 .to_string();
4100 match field.name() {
4101 "message" => self.0.message = Some(cleaned),
4102 "audit_event" => self.0.audit_event = Some(cleaned),
4103 _ => {}
4104 }
4105 }
4106 }
4107
4108 struct CaptureSubscriber {
4121 events: Arc<StdMutex<Vec<CapturedEvent>>>,
4122 }
4123
4124 impl CaptureSubscriber {
4125 fn new(events: Arc<StdMutex<Vec<CapturedEvent>>>) -> Self {
4126 Self { events }
4127 }
4128 }
4129
4130 impl tracing::Subscriber for CaptureSubscriber {
4131 fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
4132 true
4133 }
4134 fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
4135 tracing::span::Id::from_u64(1)
4136 }
4137 fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
4138 fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
4139 fn event(&self, event: &tracing::Event<'_>) {
4140 let mut visitor = CapturedEventVisitor::default();
4141 event.record(&mut visitor);
4142 self.events.lock().unwrap().push(visitor.0);
4143 }
4144 fn enter(&self, _: &tracing::span::Id) {}
4145 fn exit(&self, _: &tracing::span::Id) {}
4146 }
4147
4148 static GLOBAL_CAPTURE: OnceLock<Arc<StdMutex<Vec<CapturedEvent>>>> = OnceLock::new();
4158 static GLOBAL_INIT: Once = Once::new();
4159
4160 fn global_capture() -> Arc<StdMutex<Vec<CapturedEvent>>> {
4161 GLOBAL_INIT.call_once(|| {
4162 let buffer = Arc::new(StdMutex::new(Vec::new()));
4163 let subscriber = CaptureSubscriber::new(Arc::clone(&buffer));
4164 let _ = tracing::subscriber::set_global_default(subscriber);
4169 let _ = GLOBAL_CAPTURE.set(buffer);
4170 });
4171 Arc::clone(GLOBAL_CAPTURE.get().expect("global capture initialized"))
4172 }
4173
4174 fn capture_dispatch_events<Fut>(future: Fut) -> Vec<CapturedEvent>
4179 where
4180 Fut: std::future::Future<Output = ()>,
4181 {
4182 let buffer = global_capture();
4183 buffer.lock().unwrap().clear();
4184
4185 let rt = tokio::runtime::Builder::new_current_thread()
4186 .enable_all()
4187 .build()
4188 .expect("build current-thread tokio runtime");
4189 rt.block_on(future);
4190
4191 let result = buffer.lock().unwrap().clone();
4192 result
4193 }
4194
4195 fn gate_check_events_for(events: &[CapturedEvent], gate_impl: &str) -> Vec<CapturedEvent> {
4202 events
4203 .iter()
4204 .filter(|e| e.message.as_deref() == Some("gate.check"))
4205 .filter(|e| {
4206 e.audit_event
4207 .as_deref()
4208 .and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok())
4209 .and_then(|v| {
4210 v.get("gate_impl")
4211 .and_then(|g| g.as_str().map(|s| s.to_string()))
4212 })
4213 .as_deref()
4214 == Some(gate_impl)
4215 })
4216 .cloned()
4217 .collect()
4218 }
4219
4220 #[test]
4221 #[serial]
4222 fn dispatch_tracing_emits_one_gate_check_event_on_allow() {
4223 #[derive(Debug)]
4224 struct TracingAllowGate;
4225 impl Gate for TracingAllowGate {
4226 fn check(&self, _: &GateRequest) -> Result<GateDecision, GateError> {
4227 Ok(GateDecision::allow())
4228 }
4229 fn impl_name(&self) -> &'static str {
4230 "TracingAllowGate"
4231 }
4232 }
4233
4234 let events = capture_dispatch_events(async {
4235 let mut builder = VerbRegistryBuilder::new();
4236 builder.register(AlphaPack);
4237 builder.with_gate(Arc::new(TracingAllowGate));
4238 builder.with_default_namespace("tenant-default");
4239 let reg = builder.build().expect("registry builds");
4240 reg.dispatch("list", serde_json::json!({"namespace": "tenant-q"}))
4241 .await
4242 .unwrap();
4243 });
4244
4245 let gate_events = gate_check_events_for(&events, "TracingAllowGate");
4246 assert_eq!(
4247 gate_events.len(),
4248 1,
4249 "exactly one gate.check tracing event per dispatch (allow); got {gate_events:?}"
4250 );
4251 let payload = gate_events[0]
4252 .audit_event
4253 .as_ref()
4254 .expect("gate.check event must carry an audit_event field");
4255 let audit: khive_gate::AuditEvent =
4256 serde_json::from_str(payload).expect("audit_event payload must decode to AuditEvent");
4257 assert_eq!(audit.decision, AuditDecision::Allow);
4258 assert_eq!(audit.verb, "list");
4259 assert_eq!(audit.namespace, "tenant-q");
4260 assert_eq!(audit.gate_impl, "TracingAllowGate");
4261 assert!(
4262 audit.deny_reason.is_none(),
4263 "deny_reason must be None on Allow"
4264 );
4265 }
4266
4267 use crate::runtime::NamespaceToken;
4270 use async_trait::async_trait;
4271 use khive_storage::{
4272 BatchWriteSummary, Event, EventFilter, EventStore, Page, PageRequest, SubstrateKind,
4273 };
4274 use khive_types::EventOutcome;
4275
4276 #[derive(Default, Debug)]
4278 struct MemoryEventStore {
4279 events: std::sync::Mutex<Vec<Event>>,
4280 }
4281
4282 #[async_trait]
4283 impl EventStore for MemoryEventStore {
4284 async fn append_event(&self, event: Event) -> khive_storage::StorageResult<()> {
4285 self.events.lock().unwrap().push(event);
4286 Ok(())
4287 }
4288 async fn append_events(
4289 &self,
4290 events: Vec<Event>,
4291 ) -> khive_storage::StorageResult<BatchWriteSummary> {
4292 let attempted = events.len() as u64;
4293 let affected = attempted;
4294 self.events.lock().unwrap().extend(events);
4295 Ok(BatchWriteSummary {
4296 attempted,
4297 affected,
4298 failed: 0,
4299 first_error: String::new(),
4300 })
4301 }
4302 async fn get_event(&self, id: uuid::Uuid) -> khive_storage::StorageResult<Option<Event>> {
4303 Ok(self
4304 .events
4305 .lock()
4306 .unwrap()
4307 .iter()
4308 .find(|e| e.id == id)
4309 .cloned())
4310 }
4311 async fn query_events(
4312 &self,
4313 _filter: EventFilter,
4314 _page: PageRequest,
4315 ) -> khive_storage::StorageResult<Page<Event>> {
4316 let items = self.events.lock().unwrap().clone();
4317 let total = items.len() as u64;
4318 Ok(Page {
4319 items,
4320 total: Some(total),
4321 })
4322 }
4323 async fn count_events(&self, _filter: EventFilter) -> khive_storage::StorageResult<u64> {
4324 Ok(self.events.lock().unwrap().len() as u64)
4325 }
4326 }
4327
4328 #[tokio::test]
4329 async fn allow_all_gate_default_remains_backward_compatible() {
4330 let mut builder = VerbRegistryBuilder::new();
4332 builder.register(AlphaPack);
4333 let reg = builder.build().expect("registry builds");
4334
4335 let res = reg.dispatch("list", Value::Null).await.unwrap();
4336 assert_eq!(
4337 res["pack"], "alpha",
4338 "AllowAllGate must allow every verb — backward compat guarantee"
4339 );
4340 let res = reg.dispatch("create", Value::Null).await.unwrap();
4341 assert_eq!(res["pack"], "alpha");
4342 }
4343
4344 #[tokio::test]
4345 async fn deny_gate_returns_permission_denied_pack_never_invoked() {
4346 #[derive(Debug)]
4347 struct AlwaysDenyGate;
4348 impl Gate for AlwaysDenyGate {
4349 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
4350 Ok(GateDecision::deny("test: always deny"))
4351 }
4352 }
4353
4354 #[derive(Debug)]
4356 struct TrackedPack {
4357 invoked: Arc<AtomicUsize>,
4358 }
4359
4360 impl khive_types::Pack for TrackedPack {
4361 const NAME: &'static str = "tracked";
4362 const NOTE_KINDS: &'static [&'static str] = &[];
4363 const ENTITY_KINDS: &'static [&'static str] = &[];
4364 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
4365 name: "guarded",
4366 description: "a guarded verb",
4367 visibility: Visibility::Verb,
4368 category: VerbCategory::Assertive,
4369 params: &[],
4370 }];
4371 }
4372
4373 #[async_trait]
4374 impl PackRuntime for TrackedPack {
4375 fn name(&self) -> &str {
4376 Self::NAME
4377 }
4378 fn note_kinds(&self) -> &'static [&'static str] {
4379 Self::NOTE_KINDS
4380 }
4381 fn entity_kinds(&self) -> &'static [&'static str] {
4382 Self::ENTITY_KINDS
4383 }
4384 fn handlers(&self) -> &'static [HandlerDef] {
4385 Self::HANDLERS
4386 }
4387 async fn dispatch(
4388 &self,
4389 _verb: &str,
4390 _params: Value,
4391 _registry: &VerbRegistry,
4392 _token: &NamespaceToken,
4393 ) -> Result<Value, RuntimeError> {
4394 self.invoked.fetch_add(1, Ordering::SeqCst);
4395 Ok(serde_json::json!({"invoked": true}))
4396 }
4397 }
4398
4399 let invoked = Arc::new(AtomicUsize::new(0));
4400 let mut builder = VerbRegistryBuilder::new();
4401 builder.register(TrackedPack {
4402 invoked: invoked.clone(),
4403 });
4404 builder.with_gate(Arc::new(AlwaysDenyGate));
4405 let reg = builder.build().expect("registry builds");
4406
4407 let err = reg.dispatch("guarded", Value::Null).await.unwrap_err();
4408 assert!(
4409 matches!(err, RuntimeError::PermissionDenied { ref verb, ref reason } if verb == "guarded" && reason.contains("always deny")),
4410 "expected PermissionDenied with verb=guarded and reason, got: {err:?}"
4411 );
4412 assert_eq!(
4413 invoked.load(Ordering::SeqCst),
4414 0,
4415 "pack dispatch MUST NOT be invoked when gate denies"
4416 );
4417 }
4418
4419 #[tokio::test]
4420 async fn audit_event_persists_to_event_store_on_allow() {
4421 let store = Arc::new(MemoryEventStore::default());
4422 let mut builder = VerbRegistryBuilder::new();
4423 builder.register(AlphaPack);
4424 builder.with_event_store(store.clone());
4425 let reg = builder.build().expect("registry builds");
4426
4427 reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
4428 .await
4429 .unwrap();
4430
4431 let count = store.count_events(EventFilter::default()).await.unwrap();
4432 assert_eq!(count, 1, "one audit event persisted to EventStore on allow");
4433
4434 let page = store
4435 .query_events(
4436 EventFilter::default(),
4437 PageRequest {
4438 limit: 10,
4439 offset: 0,
4440 },
4441 )
4442 .await
4443 .unwrap();
4444 let ev = &page.items[0];
4445 assert_eq!(ev.verb, "list");
4446 assert_eq!(ev.namespace, "test-ns");
4447 assert_eq!(ev.substrate, SubstrateKind::Event);
4448 assert_eq!(ev.outcome, EventOutcome::Success);
4449 }
4450
4451 #[tokio::test]
4452 async fn audit_event_duration_us_reflects_measured_dispatch_time() {
4453 let store = Arc::new(MemoryEventStore::default());
4459 let mut builder = VerbRegistryBuilder::new();
4460 builder.register(SleepingPack);
4461 builder.with_event_store(store.clone());
4462 let reg = builder.build().expect("registry builds");
4463
4464 reg.dispatch("slow_op", serde_json::json!({}))
4465 .await
4466 .unwrap();
4467
4468 let page = store
4469 .query_events(
4470 EventFilter::default(),
4471 PageRequest {
4472 limit: 10,
4473 offset: 0,
4474 },
4475 )
4476 .await
4477 .unwrap();
4478 assert_eq!(page.items.len(), 1);
4479 let ev = &page.items[0];
4480 assert!(
4481 ev.duration_us >= 10_000,
4482 "duration_us must reflect the ~20ms measured dispatch time, got {}",
4483 ev.duration_us
4484 );
4485 }
4486
4487 #[tokio::test]
4488 async fn dispatch_unknown_verb_allowed_by_gate_still_persists_audit_row() {
4489 let store = Arc::new(MemoryEventStore::default());
4494 let mut builder = VerbRegistryBuilder::new();
4495 builder.register(AlphaPack);
4496 builder.with_event_store(store.clone());
4497 let reg = builder.build().expect("registry builds");
4498
4499 let result = reg.dispatch("no_such_verb", serde_json::json!({})).await;
4500 assert!(result.is_err(), "unknown verb must still return an error");
4501
4502 let count = store.count_events(EventFilter::default()).await.unwrap();
4503 assert_eq!(
4504 count, 1,
4505 "an allowed-but-unknown verb must still persist one audit row"
4506 );
4507 let page = store
4508 .query_events(
4509 EventFilter::default(),
4510 PageRequest {
4511 limit: 10,
4512 offset: 0,
4513 },
4514 )
4515 .await
4516 .unwrap();
4517 assert_eq!(page.items[0].duration_us, 0);
4518 assert_eq!(page.items[0].outcome, EventOutcome::Error);
4522 }
4523
4524 #[tokio::test]
4525 async fn audit_event_persists_to_event_store_on_deny() {
4526 #[derive(Debug)]
4527 struct AlwaysDenyGate;
4528 impl Gate for AlwaysDenyGate {
4529 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
4530 Ok(GateDecision::deny("denied by test"))
4531 }
4532 }
4533
4534 let store = Arc::new(MemoryEventStore::default());
4535 let mut builder = VerbRegistryBuilder::new();
4536 builder.register(AlphaPack);
4537 builder.with_gate(Arc::new(AlwaysDenyGate));
4538 builder.with_event_store(store.clone());
4539 let reg = builder.build().expect("registry builds");
4540
4541 let err = reg
4543 .dispatch("list", serde_json::json!({"namespace": "test-ns"}))
4544 .await
4545 .unwrap_err();
4546 assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
4547
4548 let count = store.count_events(EventFilter::default()).await.unwrap();
4549 assert_eq!(count, 1, "one audit event persisted to EventStore on deny");
4550
4551 let page = store
4552 .query_events(
4553 EventFilter::default(),
4554 PageRequest {
4555 limit: 10,
4556 offset: 0,
4557 },
4558 )
4559 .await
4560 .unwrap();
4561 let ev = &page.items[0];
4562 assert_eq!(ev.verb, "list");
4563 assert_eq!(ev.outcome, EventOutcome::Denied);
4564 }
4565
4566 #[tokio::test]
4567 async fn gate_error_does_not_persist_to_event_store() {
4568 #[derive(Debug)]
4569 struct FailingGate;
4570 impl Gate for FailingGate {
4571 fn check(&self, _req: &GateRequest) -> Result<GateDecision, khive_gate::GateError> {
4572 Err(khive_gate::GateError::Internal("gate broken".into()))
4573 }
4574 }
4575
4576 let store = Arc::new(MemoryEventStore::default());
4577 let mut builder = VerbRegistryBuilder::new();
4578 builder.register(AlphaPack);
4579 builder.with_gate(Arc::new(FailingGate));
4580 builder.with_event_store(store.clone());
4581 let reg = builder.build().expect("registry builds");
4582
4583 let res = reg.dispatch("list", Value::Null).await.unwrap();
4585 assert_eq!(
4586 res["pack"], "alpha",
4587 "gate error must fail-open, not block dispatch"
4588 );
4589
4590 let count = store.count_events(EventFilter::default()).await.unwrap();
4591 assert_eq!(
4592 count, 0,
4593 "gate infrastructure error must NOT produce an audit event in EventStore"
4594 );
4595 }
4596
4597 #[tokio::test]
4598 async fn no_event_store_configured_tracing_only() {
4599 let mut builder = VerbRegistryBuilder::new();
4603 builder.register(AlphaPack);
4604 let reg = builder.build().expect("registry builds");
4605
4606 let res = reg.dispatch("list", Value::Null).await.unwrap();
4607 assert_eq!(res["pack"], "alpha");
4608 }
4609
4610 #[test]
4611 #[serial]
4612 fn dispatch_tracing_emits_gate_check_event_with_deny_payload() {
4613 #[derive(Debug)]
4614 struct TracingDenyGate;
4615 impl Gate for TracingDenyGate {
4616 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
4617 Ok(GateDecision::deny("denied by test gate"))
4618 }
4619 fn impl_name(&self) -> &'static str {
4620 "TracingDenyGate"
4621 }
4622 }
4623
4624 let events = capture_dispatch_events(async {
4625 let mut builder = VerbRegistryBuilder::new();
4626 builder.register(AlphaPack);
4627 builder.with_gate(Arc::new(TracingDenyGate));
4628 let reg = builder.build().expect("registry builds");
4629 let _ = reg.dispatch("create", serde_json::Value::Null).await;
4632 });
4633
4634 let gate_events = gate_check_events_for(&events, "TracingDenyGate");
4635 assert_eq!(
4636 gate_events.len(),
4637 1,
4638 "exactly one gate.check tracing event per dispatch (deny); got {gate_events:?}"
4639 );
4640 let payload = gate_events[0]
4641 .audit_event
4642 .as_ref()
4643 .expect("gate.check event must carry an audit_event field on Deny");
4644 let audit: khive_gate::AuditEvent =
4645 serde_json::from_str(payload).expect("audit_event payload must decode to AuditEvent");
4646 assert_eq!(audit.decision, AuditDecision::Deny);
4647 assert_eq!(audit.deny_reason.as_deref(), Some("denied by test gate"));
4648 assert_eq!(audit.gate_impl, "TracingDenyGate");
4649 let payload_json: serde_json::Value =
4653 serde_json::from_str(payload).expect("payload must be valid JSON");
4654 assert_eq!(
4655 payload_json["obligations"],
4656 serde_json::Value::Array(Vec::new()),
4657 "obligations must be `[]` on Deny on the tracing payload, not omitted"
4658 );
4659 }
4660
4661 #[tokio::test]
4668 async fn audit_envelope_round_trips_deny_reason_and_gate_impl_through_event_store() {
4669 #[derive(Debug)]
4670 struct DenyGateWithName;
4671 impl Gate for DenyGateWithName {
4672 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
4673 Ok(GateDecision::deny("policy: write forbidden for anon"))
4674 }
4675 fn impl_name(&self) -> &'static str {
4676 "DenyGateWithName"
4677 }
4678 }
4679
4680 let store = Arc::new(MemoryEventStore::default());
4681 let mut builder = VerbRegistryBuilder::new();
4682 builder.register(AlphaPack);
4683 builder.with_gate(Arc::new(DenyGateWithName));
4684 builder.with_event_store(store.clone());
4685 let reg = builder.build().expect("registry builds");
4686
4687 let err = reg
4689 .dispatch("list", serde_json::json!({"namespace": "test-ns"}))
4690 .await
4691 .unwrap_err();
4692 assert!(
4693 matches!(err, RuntimeError::PermissionDenied { .. }),
4694 "expected PermissionDenied, got {err:?}"
4695 );
4696
4697 let page = store
4699 .query_events(
4700 EventFilter::default(),
4701 PageRequest {
4702 limit: 10,
4703 offset: 0,
4704 },
4705 )
4706 .await
4707 .unwrap();
4708 assert_eq!(
4709 page.items.len(),
4710 1,
4711 "one audit event must be persisted on deny"
4712 );
4713
4714 let ev = &page.items[0];
4715 assert_eq!(ev.outcome, EventOutcome::Denied);
4716
4717 let data = &ev.payload;
4719
4720 let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
4721 .expect("Event.payload must deserialize to AuditEvent");
4722
4723 assert_eq!(
4724 audit.deny_reason.as_deref(),
4725 Some("policy: write forbidden for anon"),
4726 "deny_reason must be preserved through EventStore"
4727 );
4728 assert_eq!(
4729 audit.gate_impl, "DenyGateWithName",
4730 "gate_impl must be preserved through EventStore"
4731 );
4732 assert_eq!(
4733 audit.decision,
4734 khive_gate::AuditDecision::Deny,
4735 "decision field must be preserved through EventStore"
4736 );
4737 }
4738
4739 #[tokio::test]
4740 async fn audit_envelope_round_trips_obligations_through_event_store() {
4741 use khive_gate::Obligation;
4742
4743 #[derive(Debug)]
4744 struct ObligationGate;
4745 impl Gate for ObligationGate {
4746 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
4747 Ok(GateDecision::allow_with(vec![Obligation::Audit {
4748 tag: "billing.meter".into(),
4749 }]))
4750 }
4751 fn impl_name(&self) -> &'static str {
4752 "ObligationGate"
4753 }
4754 }
4755
4756 let store = Arc::new(MemoryEventStore::default());
4757 let mut builder = VerbRegistryBuilder::new();
4758 builder.register(AlphaPack);
4759 builder.with_gate(Arc::new(ObligationGate));
4760 builder.with_event_store(store.clone());
4761 let reg = builder.build().expect("registry builds");
4762
4763 reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
4764 .await
4765 .unwrap();
4766
4767 let page = store
4768 .query_events(
4769 EventFilter::default(),
4770 PageRequest {
4771 limit: 10,
4772 offset: 0,
4773 },
4774 )
4775 .await
4776 .unwrap();
4777 assert_eq!(page.items.len(), 1);
4778
4779 let ev = &page.items[0];
4780 assert_eq!(ev.outcome, EventOutcome::Success);
4781
4782 let data = &ev.payload;
4783
4784 let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
4785 .expect("Event.payload must deserialize to AuditEvent");
4786
4787 assert_eq!(audit.gate_impl, "ObligationGate");
4788 assert_eq!(
4789 audit.obligations.len(),
4790 1,
4791 "obligations must be preserved through EventStore"
4792 );
4793 match &audit.obligations[0] {
4794 Obligation::Audit { tag } => assert_eq!(tag, "billing.meter"),
4795 other => panic!("expected Audit obligation, got {other:?}"),
4796 }
4797 }
4798
4799 #[tokio::test]
4807 async fn sql_backed_audit_envelope_round_trips_deny_reason_gate_impl_and_obligations() {
4808 #[derive(Debug)]
4809 struct SqlTestDenyGate;
4810 impl Gate for SqlTestDenyGate {
4811 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
4812 Ok(GateDecision::deny("sql-path: write denied"))
4813 }
4814 fn impl_name(&self) -> &'static str {
4815 "SqlTestDenyGate"
4816 }
4817 }
4818
4819 let rt = KhiveRuntime::memory().expect("in-memory runtime");
4823 let test_tok = NamespaceToken::for_namespace(Namespace::parse("test-ns").unwrap());
4824 let sql_store = rt
4825 .events(&test_tok)
4826 .expect("events_for_namespace must succeed");
4827
4828 let mut builder = VerbRegistryBuilder::new();
4829 builder.register(AlphaPack);
4830 builder.with_gate(Arc::new(SqlTestDenyGate));
4831 builder.with_event_store(sql_store.clone());
4832 let reg = builder.build().expect("registry builds");
4833
4834 let err = reg
4836 .dispatch("list", serde_json::json!({"namespace": "test-ns"}))
4837 .await
4838 .unwrap_err();
4839 assert!(
4840 matches!(err, RuntimeError::PermissionDenied { .. }),
4841 "expected PermissionDenied, got {err:?}"
4842 );
4843
4844 let page = sql_store
4846 .query_events(
4847 EventFilter::default(),
4848 PageRequest {
4849 limit: 10,
4850 offset: 0,
4851 },
4852 )
4853 .await
4854 .unwrap();
4855 assert_eq!(
4856 page.items.len(),
4857 1,
4858 "one audit event must be persisted on deny through SqlEventStore"
4859 );
4860
4861 let ev = &page.items[0];
4862 assert_eq!(ev.outcome, EventOutcome::Denied);
4863
4864 let data = &ev.payload;
4868
4869 let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
4870 .expect("Event.payload must deserialize to AuditEvent after SQL round-trip");
4871
4872 assert_eq!(
4873 audit.deny_reason.as_deref(),
4874 Some("sql-path: write denied"),
4875 "deny_reason must survive the SQL text round-trip"
4876 );
4877 assert_eq!(
4878 audit.gate_impl, "SqlTestDenyGate",
4879 "gate_impl must survive the SQL text round-trip"
4880 );
4881 assert_eq!(
4882 audit.decision,
4883 khive_gate::AuditDecision::Deny,
4884 "decision field must survive the SQL text round-trip"
4885 );
4886 assert!(
4889 audit.obligations.is_empty(),
4890 "obligations must be preserved as empty [] through SQL round-trip"
4891 );
4892 }
4893
4894 #[tokio::test]
4906 async fn sql_backed_audit_envelope_round_trips_non_empty_obligations() {
4907 use khive_gate::Obligation;
4908
4909 #[derive(Debug)]
4910 struct SqlTestAllowWithObligationGate;
4911 impl Gate for SqlTestAllowWithObligationGate {
4912 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
4913 Ok(GateDecision::allow_with(vec![Obligation::Audit {
4914 tag: "sql-path-billing.meter".into(),
4915 }]))
4916 }
4917 fn impl_name(&self) -> &'static str {
4918 "SqlTestAllowWithObligationGate"
4919 }
4920 }
4921
4922 let rt = KhiveRuntime::memory().expect("in-memory runtime");
4923 let test_tok = NamespaceToken::for_namespace(Namespace::parse("test-ns").unwrap());
4924 let sql_store = rt
4925 .events(&test_tok)
4926 .expect("events_for_namespace must succeed");
4927
4928 let mut builder = VerbRegistryBuilder::new();
4929 builder.register(AlphaPack);
4930 builder.with_gate(Arc::new(SqlTestAllowWithObligationGate));
4931 builder.with_event_store(sql_store.clone());
4932 let reg = builder.build().expect("registry builds");
4933
4934 reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
4936 .await
4937 .expect("dispatch must succeed when gate allows");
4938
4939 let page = sql_store
4941 .query_events(
4942 EventFilter::default(),
4943 PageRequest {
4944 limit: 10,
4945 offset: 0,
4946 },
4947 )
4948 .await
4949 .unwrap();
4950 assert_eq!(
4951 page.items.len(),
4952 1,
4953 "one audit event must be persisted on allow through SqlEventStore"
4954 );
4955
4956 let ev = &page.items[0];
4957 assert_eq!(ev.outcome, EventOutcome::Success);
4958
4959 let data = &ev.payload;
4960
4961 let obligations_raw = data
4966 .get("obligations")
4967 .expect("Event.data JSON must contain 'obligations' key");
4968 let obligations_arr = obligations_raw
4969 .as_array()
4970 .expect("'obligations' must be a JSON array");
4971 assert!(
4972 !obligations_arr.is_empty(),
4973 "raw Event.data['obligations'] must be non-empty after SQL round-trip"
4974 );
4975
4976 let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
4979 .expect("Event.data must deserialize to AuditEvent after SQL round-trip");
4980
4981 assert_eq!(
4982 audit.gate_impl, "SqlTestAllowWithObligationGate",
4983 "gate_impl must survive the SQL text round-trip"
4984 );
4985 assert_eq!(
4986 audit.decision,
4987 khive_gate::AuditDecision::Allow,
4988 "decision field must survive the SQL text round-trip"
4989 );
4990 assert_eq!(
4991 audit.obligations.len(),
4992 1,
4993 "obligations must be non-empty after SQL round-trip (not silently defaulted to [])"
4994 );
4995 match &audit.obligations[0] {
4996 Obligation::Audit { tag } => assert_eq!(
4997 tag, "sql-path-billing.meter",
4998 "Audit obligation tag must survive the SQL text round-trip"
4999 ),
5000 other => panic!("expected Audit obligation, got {other:?}"),
5001 }
5002 }
5003
5004 #[tokio::test]
5012 async fn audit_event_payload_shape_for_create_verb() {
5013 let store = Arc::new(MemoryEventStore::default());
5014 let mut builder = VerbRegistryBuilder::new();
5015 builder.register(AlphaPack);
5016 builder.with_event_store(store.clone());
5017 builder.with_default_namespace("test-ns");
5018 let reg = builder.build().expect("registry builds");
5019
5020 reg.dispatch("create", serde_json::json!({"namespace": "test-ns"}))
5023 .await
5024 .unwrap();
5025
5026 let count = store.count_events(EventFilter::default()).await.unwrap();
5027 assert_eq!(count, 1, "exactly one audit event for one dispatch");
5028
5029 let page = store
5030 .query_events(
5031 EventFilter::default(),
5032 PageRequest {
5033 limit: 10,
5034 offset: 0,
5035 },
5036 )
5037 .await
5038 .unwrap();
5039 let ev = &page.items[0];
5040
5041 assert_eq!(ev.verb, "create", "ev.verb must be the dispatched verb");
5043 assert_eq!(
5044 ev.outcome,
5045 EventOutcome::Success,
5046 "ev.outcome must be Success on allow"
5047 );
5048 assert_eq!(
5049 ev.namespace, "test-ns",
5050 "ev.namespace must match the dispatch namespace"
5051 );
5052
5053 let data = &ev.payload;
5055
5056 let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
5057 .expect("ev.payload must deserialize to AuditEvent");
5058
5059 assert_eq!(
5060 audit.decision,
5061 khive_gate::AuditDecision::Allow,
5062 "AuditEvent.decision must be Allow"
5063 );
5064 assert_eq!(audit.verb, "create", "AuditEvent.verb must be 'create'");
5065 assert_eq!(
5066 audit.namespace, "test-ns",
5067 "AuditEvent.namespace must be preserved"
5068 );
5069 assert_eq!(
5070 audit.gate_impl, "AllowAllGate",
5071 "AuditEvent.gate_impl must name the gate implementation"
5072 );
5073 assert!(
5074 audit.deny_reason.is_none(),
5075 "AuditEvent.deny_reason must be None on Allow"
5076 );
5077 let payload_json: serde_json::Value =
5079 serde_json::from_value(data.clone()).expect("data must be valid JSON");
5080 assert_eq!(
5081 payload_json["obligations"],
5082 serde_json::Value::Array(Vec::new()),
5083 "obligations must be [] on AllowAllGate"
5084 );
5085 }
5086
5087 struct EmbeddingAwarePack {
5094 models: Vec<String>,
5095 }
5096
5097 impl khive_types::Pack for EmbeddingAwarePack {
5098 const NAME: &'static str = "embedding_aware";
5099 const NOTE_KINDS: &'static [&'static str] = &[];
5100 const ENTITY_KINDS: &'static [&'static str] = &["widget"];
5101 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
5102 name: "create",
5103 description: "create a widget (embedding-aware stub)",
5104 visibility: Visibility::Verb,
5105 category: VerbCategory::Commissive,
5106 params: &[],
5107 }];
5108 }
5109
5110 #[async_trait]
5111 impl PackRuntime for EmbeddingAwarePack {
5112 fn name(&self) -> &str {
5113 Self::NAME
5114 }
5115 fn note_kinds(&self) -> &'static [&'static str] {
5116 Self::NOTE_KINDS
5117 }
5118 fn entity_kinds(&self) -> &'static [&'static str] {
5119 Self::ENTITY_KINDS
5120 }
5121 fn handlers(&self) -> &'static [HandlerDef] {
5122 Self::HANDLERS
5123 }
5124 fn registered_embedding_model_names(&self) -> Vec<String> {
5125 self.models.clone()
5126 }
5127 async fn dispatch(
5128 &self,
5129 verb: &str,
5130 _params: Value,
5131 _registry: &VerbRegistry,
5132 _token: &NamespaceToken,
5133 ) -> Result<Value, RuntimeError> {
5134 Ok(serde_json::json!({ "pack": "embedding_aware", "verb": verb }))
5135 }
5136 }
5137
5138 struct FailingProbePack;
5141
5142 impl khive_types::Pack for FailingProbePack {
5143 const NAME: &'static str = "failing_probe";
5144 const NOTE_KINDS: &'static [&'static str] = &[];
5145 const ENTITY_KINDS: &'static [&'static str] = &[];
5146 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
5147 name: "probe",
5148 description: "always fails",
5149 visibility: Visibility::Verb,
5150 category: VerbCategory::Assertive,
5151 params: &[],
5152 }];
5153 }
5154
5155 #[async_trait]
5156 impl PackRuntime for FailingProbePack {
5157 fn name(&self) -> &str {
5158 Self::NAME
5159 }
5160 fn note_kinds(&self) -> &'static [&'static str] {
5161 Self::NOTE_KINDS
5162 }
5163 fn entity_kinds(&self) -> &'static [&'static str] {
5164 Self::ENTITY_KINDS
5165 }
5166 fn handlers(&self) -> &'static [HandlerDef] {
5167 Self::HANDLERS
5168 }
5169 async fn dispatch(
5170 &self,
5171 _verb: &str,
5172 _params: Value,
5173 _registry: &VerbRegistry,
5174 _token: &NamespaceToken,
5175 ) -> Result<Value, RuntimeError> {
5176 Err(RuntimeError::InvalidInput("boom".into()))
5177 }
5178 }
5179
5180 #[tokio::test]
5181 async fn resource_cost_unit_present_on_non_embedding_successful_dispatch() {
5182 let store = Arc::new(MemoryEventStore::default());
5183 let mut builder = VerbRegistryBuilder::new();
5184 builder.register(AlphaPack);
5185 builder.with_event_store(store.clone());
5186 let reg = builder.build().expect("registry builds");
5187
5188 reg.dispatch("list", serde_json::json!({})).await.unwrap();
5189
5190 let page = store
5191 .query_events(
5192 EventFilter::default(),
5193 PageRequest {
5194 limit: 10,
5195 offset: 0,
5196 },
5197 )
5198 .await
5199 .unwrap();
5200 assert_eq!(page.items.len(), 1);
5201 assert_eq!(
5202 page.items[0].payload["resource"],
5203 serde_json::json!({"work_class": "interactive", "cost_unit": 1}),
5204 "non-embedding-bearing verb's resource.cost_unit must be base_weight(verb) alone"
5205 );
5206 }
5207
5208 #[tokio::test]
5209 async fn resource_cost_unit_scales_with_registered_model_count_for_create() {
5210 let store = Arc::new(MemoryEventStore::default());
5211 let mut builder = VerbRegistryBuilder::new();
5212 builder.register(EmbeddingAwarePack {
5213 models: vec!["all-minilm-l6-v2".into(), "paraphrase".into()],
5214 });
5215 builder.with_event_store(store.clone());
5216 let reg = builder.build().expect("registry builds");
5217
5218 reg.dispatch("create", serde_json::json!({"kind": "widget"}))
5219 .await
5220 .unwrap();
5221
5222 let page = store
5223 .query_events(
5224 EventFilter::default(),
5225 PageRequest {
5226 limit: 10,
5227 offset: 0,
5228 },
5229 )
5230 .await
5231 .unwrap();
5232 assert_eq!(
5234 page.items[0].payload["resource"],
5235 serde_json::json!({"work_class": "interactive", "cost_unit": 3}),
5236 );
5237 }
5238
5239 #[tokio::test]
5240 async fn resource_cost_unit_zero_registered_models_is_base_weight_only() {
5241 let store = Arc::new(MemoryEventStore::default());
5242 let mut builder = VerbRegistryBuilder::new();
5243 builder.register(EmbeddingAwarePack { models: vec![] });
5244 builder.with_event_store(store.clone());
5245 let reg = builder.build().expect("registry builds");
5246
5247 reg.dispatch("create", serde_json::json!({"kind": "widget"}))
5248 .await
5249 .unwrap();
5250
5251 let page = store
5252 .query_events(
5253 EventFilter::default(),
5254 PageRequest {
5255 limit: 10,
5256 offset: 0,
5257 },
5258 )
5259 .await
5260 .unwrap();
5261 assert_eq!(
5262 page.items[0].payload["resource"]["cost_unit"], 1,
5263 "zero registered embedding models must vanish the term, not error or omit"
5264 );
5265 }
5266
5267 #[tokio::test]
5268 async fn resource_work_class_present_cost_unit_absent_when_dispatch_returns_error() {
5269 let store = Arc::new(MemoryEventStore::default());
5270 let mut builder = VerbRegistryBuilder::new();
5271 builder.register(FailingProbePack);
5272 builder.with_event_store(store.clone());
5273 let reg = builder.build().expect("registry builds");
5274
5275 let err = reg
5276 .dispatch("probe", serde_json::json!({}))
5277 .await
5278 .unwrap_err();
5279 assert!(matches!(err, RuntimeError::InvalidInput(_)));
5280
5281 let page = store
5282 .query_events(
5283 EventFilter::default(),
5284 PageRequest {
5285 limit: 10,
5286 offset: 0,
5287 },
5288 )
5289 .await
5290 .unwrap();
5291 assert_eq!(page.items.len(), 1);
5292 assert_eq!(page.items[0].outcome, EventOutcome::Error);
5293 assert_eq!(
5298 page.items[0].payload["resource"],
5299 serde_json::json!({"work_class": "interactive"}),
5300 "resource must carry work_class with cost_unit OMITTED (never 0) on an \
5301 errored dispatch: {:?}",
5302 page.items[0].payload
5303 );
5304 }
5305
5306 #[tokio::test]
5307 async fn resource_work_class_present_cost_unit_absent_when_no_pack_owns_the_verb() {
5308 let store = Arc::new(MemoryEventStore::default());
5309 let mut builder = VerbRegistryBuilder::new();
5310 builder.register(AlphaPack);
5311 builder.with_event_store(store.clone());
5312 let reg = builder.build().expect("registry builds");
5313
5314 let _ = reg
5315 .dispatch("no_such_verb_resource_test", serde_json::json!({}))
5316 .await;
5317
5318 let page = store
5319 .query_events(
5320 EventFilter::default(),
5321 PageRequest {
5322 limit: 10,
5323 offset: 0,
5324 },
5325 )
5326 .await
5327 .unwrap();
5328 assert_eq!(page.items.len(), 1);
5329 assert_eq!(
5330 page.items[0].payload["resource"],
5331 serde_json::json!({"work_class": "interactive"})
5332 );
5333 }
5334
5335 #[tokio::test]
5336 async fn resource_work_class_present_cost_unit_absent_on_denied_dispatch() {
5337 #[derive(Debug)]
5338 struct AlwaysDenyGate;
5339 impl Gate for AlwaysDenyGate {
5340 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
5341 Ok(GateDecision::deny("test: always deny"))
5342 }
5343 }
5344 let store = Arc::new(MemoryEventStore::default());
5345 let mut builder = VerbRegistryBuilder::new();
5346 builder.register(AlphaPack);
5347 builder.with_gate(Arc::new(AlwaysDenyGate));
5348 builder.with_event_store(store.clone());
5349 let reg = builder.build().expect("registry builds");
5350
5351 let _ = reg.dispatch("list", serde_json::json!({})).await;
5352
5353 let page = store
5354 .query_events(
5355 EventFilter::default(),
5356 PageRequest {
5357 limit: 10,
5358 offset: 0,
5359 },
5360 )
5361 .await
5362 .unwrap();
5363 assert_eq!(page.items.len(), 1);
5364 assert_eq!(page.items[0].outcome, EventOutcome::Denied);
5365 assert_eq!(
5366 page.items[0].payload["resource"],
5367 serde_json::json!({"work_class": "interactive"})
5368 );
5369 }
5370
5371 #[tokio::test]
5372 async fn resource_cost_unit_present_on_link_singleton_success() {
5373 let store = Arc::new(MemoryEventStore::default());
5374 let edge_id = uuid::Uuid::new_v4();
5375 let source_id = uuid::Uuid::new_v4();
5376 let target_id = uuid::Uuid::new_v4();
5377 let edge_json = serde_json::json!({
5378 "id": edge_id,
5379 "namespace": "local",
5380 "source_id": source_id,
5381 "target_id": target_id,
5382 "relation": "depends_on",
5383 "weight": 1.0,
5384 });
5385 let mut builder = VerbRegistryBuilder::new();
5386 builder.register(LinkResultPack::ok(edge_json));
5387 builder.with_event_store(store.clone());
5388 let reg = builder.build().expect("registry builds");
5389
5390 reg.dispatch(
5391 "link",
5392 serde_json::json!({
5393 "source_id": source_id,
5394 "target_id": target_id,
5395 "relation": "depends_on",
5396 }),
5397 )
5398 .await
5399 .unwrap();
5400
5401 let page = store
5402 .query_events(
5403 EventFilter::default(),
5404 PageRequest {
5405 limit: 10,
5406 offset: 0,
5407 },
5408 )
5409 .await
5410 .unwrap();
5411 assert_eq!(
5412 page.items[0].payload["resource"],
5413 serde_json::json!({"work_class": "interactive", "cost_unit": 1}),
5414 "link has no embedding-bearing path -> base_weight(link) alone, even on the v2-enriched singleton path"
5415 );
5416 }
5417
5418 #[tokio::test]
5419 async fn resource_work_class_present_cost_unit_absent_on_link_dispatch_failure() {
5420 let store = Arc::new(MemoryEventStore::default());
5421 let mut builder = VerbRegistryBuilder::new();
5422 builder.register(LinkResultPack::err("target endpoint not found"));
5423 builder.with_event_store(store.clone());
5424 let reg = builder.build().expect("registry builds");
5425
5426 let _ = reg
5427 .dispatch(
5428 "link",
5429 serde_json::json!({
5430 "source_id": "note:alpha",
5431 "target_id": "note:missing",
5432 "relation": "depends_on",
5433 }),
5434 )
5435 .await;
5436
5437 let page = store
5438 .query_events(
5439 EventFilter::default(),
5440 PageRequest {
5441 limit: 10,
5442 offset: 0,
5443 },
5444 )
5445 .await
5446 .unwrap();
5447 assert_eq!(page.items.len(), 1);
5448 assert_eq!(
5449 page.items[0].payload["resource"],
5450 serde_json::json!({"work_class": "interactive"})
5451 );
5452 }
5453
5454 #[tokio::test]
5456 async fn audit_event_threads_target_id_from_dispatch_args() {
5457 let store = Arc::new(MemoryEventStore::default());
5458 let target = uuid::Uuid::new_v4();
5459 let mut builder = VerbRegistryBuilder::new();
5460 builder.register(AlphaPack);
5461 builder.with_event_store(store.clone());
5462 builder.with_default_namespace("test-ns");
5463 let reg = builder.build().expect("registry builds");
5464
5465 reg.dispatch(
5466 "create",
5467 serde_json::json!({"namespace": "test-ns", "target_id": target}),
5468 )
5469 .await
5470 .unwrap();
5471
5472 let page = store
5473 .query_events(
5474 EventFilter::default(),
5475 PageRequest {
5476 offset: 0,
5477 limit: 10,
5478 },
5479 )
5480 .await
5481 .unwrap();
5482 assert_eq!(
5483 page.items[0].target_id,
5484 Some(target),
5485 "#282: audit event must carry target_id from dispatch params"
5486 );
5487 }
5488
5489 struct LinkResultPack {
5495 result: std::sync::Mutex<Option<Result<Value, RuntimeError>>>,
5496 }
5497
5498 impl LinkResultPack {
5499 fn ok(value: Value) -> Self {
5500 Self {
5501 result: std::sync::Mutex::new(Some(Ok(value))),
5502 }
5503 }
5504 fn err(message: &str) -> Self {
5505 Self {
5506 result: std::sync::Mutex::new(Some(Err(RuntimeError::InvalidInput(
5507 message.to_string(),
5508 )))),
5509 }
5510 }
5511 }
5512
5513 impl khive_types::Pack for LinkResultPack {
5514 const NAME: &'static str = "kg";
5515 const NOTE_KINDS: &'static [&'static str] = &[];
5516 const ENTITY_KINDS: &'static [&'static str] = &[];
5517 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
5518 name: "link",
5519 description: "test link handler",
5520 visibility: Visibility::Verb,
5521 category: VerbCategory::Commissive,
5522 params: &[],
5523 }];
5524 }
5525
5526 #[async_trait]
5527 impl PackRuntime for LinkResultPack {
5528 fn name(&self) -> &str {
5529 Self::NAME
5530 }
5531 fn note_kinds(&self) -> &'static [&'static str] {
5532 Self::NOTE_KINDS
5533 }
5534 fn entity_kinds(&self) -> &'static [&'static str] {
5535 Self::ENTITY_KINDS
5536 }
5537 fn handlers(&self) -> &'static [HandlerDef] {
5538 Self::HANDLERS
5539 }
5540 async fn dispatch(
5541 &self,
5542 _verb: &str,
5543 _params: Value,
5544 _registry: &VerbRegistry,
5545 _token: &NamespaceToken,
5546 ) -> Result<Value, RuntimeError> {
5547 self.result
5548 .lock()
5549 .unwrap()
5550 .take()
5551 .expect("LinkResultPack dispatch called more than once in a test")
5552 }
5553 }
5554
5555 #[tokio::test]
5556 async fn link_audit_enriches_successful_singleton_with_edge_v2() {
5557 let store = Arc::new(MemoryEventStore::default());
5558 let edge_id = uuid::Uuid::new_v4();
5559 let source_id = uuid::Uuid::new_v4();
5560 let target_id = uuid::Uuid::new_v4();
5561 let edge_json = serde_json::json!({
5562 "id": edge_id,
5563 "namespace": "local",
5564 "source_id": source_id,
5565 "target_id": target_id,
5566 "relation": "depends_on",
5567 "weight": 1.0,
5568 });
5569 let mut builder = VerbRegistryBuilder::new();
5570 builder.register(LinkResultPack::ok(edge_json));
5571 builder.with_event_store(store.clone());
5572 builder.with_default_namespace("test-ns");
5573 let reg = builder.build().expect("registry builds");
5574
5575 reg.dispatch(
5576 "link",
5577 serde_json::json!({
5578 "source_id": source_id,
5579 "target_id": target_id,
5580 "relation": "depends_on",
5581 }),
5582 )
5583 .await
5584 .unwrap();
5585
5586 let count = store.count_events(EventFilter::default()).await.unwrap();
5587 assert_eq!(
5588 count, 1,
5589 "exactly one deferred audit row must be persisted for a successful singleton link"
5590 );
5591 let page = store
5592 .query_events(
5593 EventFilter::default(),
5594 PageRequest {
5595 limit: 10,
5596 offset: 0,
5597 },
5598 )
5599 .await
5600 .unwrap();
5601 let ev = &page.items[0];
5602 assert_eq!(ev.verb, "link");
5603 assert_eq!(ev.outcome, EventOutcome::Success);
5604 assert_eq!(
5605 ev.payload_schema_version, 2,
5606 "successful singleton link uses audit schema v2"
5607 );
5608 assert_eq!(
5609 ev.target_id,
5610 Some(edge_id),
5611 "target_id must be the created/resolved edge id, not a raw caller arg"
5612 );
5613 assert_eq!(ev.payload["edge_id"], serde_json::json!(edge_id));
5614 assert_eq!(ev.payload["source_id"], serde_json::json!(source_id));
5615 assert_eq!(ev.payload["target_id"], serde_json::json!(target_id));
5616 assert_eq!(ev.payload["relation"], "depends_on");
5617 assert_eq!(ev.payload["weight"], 1.0);
5618 assert_eq!(ev.payload["verb"], "link");
5620 assert_eq!(ev.payload["decision"], "allow");
5621 assert!(ev.payload.get("gate_impl").is_some());
5622 }
5623
5624 #[tokio::test]
5625 async fn link_audit_falls_back_to_v1_when_dispatch_fails() {
5626 let store = Arc::new(MemoryEventStore::default());
5627 let mut builder = VerbRegistryBuilder::new();
5628 builder.register(LinkResultPack::err("target endpoint not found"));
5629 builder.with_event_store(store.clone());
5630 builder.with_default_namespace("test-ns");
5631 let reg = builder.build().expect("registry builds");
5632
5633 let err = reg
5634 .dispatch(
5635 "link",
5636 serde_json::json!({
5637 "source_id": "note:alpha",
5638 "target_id": "note:missing",
5639 "relation": "depends_on",
5640 }),
5641 )
5642 .await
5643 .unwrap_err();
5644 assert!(
5645 matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("not found")),
5646 "the original dispatch error must be returned unchanged"
5647 );
5648
5649 let page = store
5650 .query_events(
5651 EventFilter::default(),
5652 PageRequest {
5653 limit: 10,
5654 offset: 0,
5655 },
5656 )
5657 .await
5658 .unwrap();
5659 assert_eq!(
5660 page.items.len(),
5661 1,
5662 "a v1 fallback audit row must still be persisted on dispatch failure"
5663 );
5664 let ev = &page.items[0];
5665 assert_eq!(
5666 ev.payload_schema_version, 1,
5667 "failed link keeps the v1 audit shape"
5668 );
5669 assert_eq!(
5672 ev.outcome,
5673 EventOutcome::Error,
5674 "outcome reflects the dispatch result (Err), not the gate decision (Allow)"
5675 );
5676 assert!(
5677 ev.duration_us >= 0,
5678 "duration_us must still be populated (measured, not the Event::new \
5679 default sentinel) on a failed dispatch"
5680 );
5681 assert!(
5682 ev.target_id.is_none(),
5683 "non-UUID caller-supplied ids do not spuriously populate target_id"
5684 );
5685 assert!(
5686 ev.payload.get("edge_id").is_none(),
5687 "v1 fallback must not carry edge enrichment fields"
5688 );
5689 let _: khive_gate::AuditEvent = serde_json::from_value(ev.payload.clone())
5690 .expect("v1 fallback payload must deserialize as AuditEvent");
5691 }
5692
5693 #[tokio::test]
5694 async fn link_audit_falls_back_to_v1_when_result_missing_edge_fields() {
5695 let store = Arc::new(MemoryEventStore::default());
5696 let target_arg = uuid::Uuid::new_v4();
5697 let mut builder = VerbRegistryBuilder::new();
5698 builder.register(LinkResultPack::ok(serde_json::json!({"ok": true})));
5699 builder.with_event_store(store.clone());
5700 builder.with_default_namespace("test-ns");
5701 let reg = builder.build().expect("registry builds");
5702
5703 reg.dispatch(
5704 "link",
5705 serde_json::json!({
5706 "source_id": uuid::Uuid::new_v4(),
5707 "target_id": target_arg,
5708 "relation": "depends_on",
5709 }),
5710 )
5711 .await
5712 .unwrap();
5713
5714 let page = store
5715 .query_events(
5716 EventFilter::default(),
5717 PageRequest {
5718 limit: 10,
5719 offset: 0,
5720 },
5721 )
5722 .await
5723 .unwrap();
5724 assert_eq!(page.items.len(), 1);
5725 let ev = &page.items[0];
5726 assert_eq!(
5727 ev.payload_schema_version, 1,
5728 "an unparsable success result falls back to v1 rather than dropping the audit row"
5729 );
5730 assert_eq!(ev.outcome, EventOutcome::Success);
5731 assert_eq!(
5732 ev.target_id,
5733 Some(target_arg),
5734 "v1 fallback still extracts target_id from the raw dispatch args"
5735 );
5736 assert!(ev.payload.get("edge_id").is_none());
5737 }
5738
5739 #[tokio::test]
5740 async fn link_audit_bulk_links_get_no_enrichment() {
5741 let store = Arc::new(MemoryEventStore::default());
5742 let mut builder = VerbRegistryBuilder::new();
5743 builder.register(LinkResultPack::ok(serde_json::json!({
5744 "attempted": 2, "created": 2, "skipped": 0, "failed": 0
5745 })));
5746 builder.with_event_store(store.clone());
5747 builder.with_default_namespace("test-ns");
5748 let reg = builder.build().expect("registry builds");
5749
5750 reg.dispatch(
5751 "link",
5752 serde_json::json!({
5753 "links": [
5754 {"source_id": "a", "target_id": "b", "relation": "depends_on"},
5755 {"source_id": "c", "target_id": "d", "relation": "depends_on"},
5756 ],
5757 }),
5758 )
5759 .await
5760 .unwrap();
5761
5762 let count = store.count_events(EventFilter::default()).await.unwrap();
5763 assert_eq!(
5764 count, 1,
5765 "bulk `links` gets exactly one v1 audit row (deferred until dispatch \
5766 resolves like every other Allow-outcome row since ADR-103 Stage 1, \
5767 but never v2-enriched — enrichment is singleton-`link`-only)"
5768 );
5769 let page = store
5770 .query_events(
5771 EventFilter::default(),
5772 PageRequest {
5773 limit: 10,
5774 offset: 0,
5775 },
5776 )
5777 .await
5778 .unwrap();
5779 let ev = &page.items[0];
5780 assert_eq!(
5781 ev.payload_schema_version, 1,
5782 "bulk link mode is out of scope for #676's events.target_id enrichment"
5783 );
5784 assert!(ev.target_id.is_none());
5785 }
5786
5787 #[test]
5788 fn link_audit_success_from_result_extracts_edge_fields() {
5789 let gate_req = GateRequest::new(
5790 ActorRef::anonymous(),
5791 Namespace::local(),
5792 "link",
5793 serde_json::json!({}),
5794 );
5795 let decision = GateDecision::Allow {
5796 obligations: vec![],
5797 };
5798 let audit = AuditEvent::from_check(&gate_req, &decision, "AllowAllGate");
5799
5800 let edge_id = uuid::Uuid::new_v4();
5801 let source_id = uuid::Uuid::new_v4();
5802 let target_id = uuid::Uuid::new_v4();
5803 let result = serde_json::json!({
5804 "id": edge_id,
5805 "source_id": source_id,
5806 "target_id": target_id,
5807 "relation": "depends_on",
5808 "weight": 0.5,
5809 });
5810
5811 let (returned_id, payload) = link_audit_success_from_result(audit, &result)
5812 .expect("well-formed edge JSON must produce an enriched payload");
5813 assert_eq!(returned_id, edge_id);
5814 assert_eq!(payload["edge_id"], serde_json::json!(edge_id));
5815 assert_eq!(payload["relation"], "depends_on");
5816 assert_eq!(payload["weight"], 0.5);
5817 assert_eq!(
5818 payload["verb"], "link",
5819 "v1 AuditEvent fields must flatten into the v2 payload"
5820 );
5821 }
5822
5823 #[test]
5824 fn link_audit_success_from_result_rejects_incomplete_or_malformed_result() {
5825 let gate_req = GateRequest::new(
5826 ActorRef::anonymous(),
5827 Namespace::local(),
5828 "link",
5829 serde_json::json!({}),
5830 );
5831 let decision = GateDecision::Allow {
5832 obligations: vec![],
5833 };
5834 let audit = AuditEvent::from_check(&gate_req, &decision, "AllowAllGate");
5835
5836 assert!(
5837 link_audit_success_from_result(
5838 audit.clone(),
5839 &serde_json::json!({"id": uuid::Uuid::new_v4()}),
5840 )
5841 .is_none(),
5842 "missing source_id/target_id/relation/weight must not enrich"
5843 );
5844 assert!(
5845 link_audit_success_from_result(audit, &serde_json::json!({"id": "not-a-uuid"}))
5846 .is_none(),
5847 "a non-UUID id must not enrich"
5848 );
5849 }
5850
5851 async fn first_event(store: &Arc<MemoryEventStore>) -> Event {
5861 let page = store
5862 .query_events(
5863 EventFilter::default(),
5864 PageRequest {
5865 limit: 10,
5866 offset: 0,
5867 },
5868 )
5869 .await
5870 .unwrap();
5871 assert_eq!(
5872 page.items.len(),
5873 1,
5874 "expected exactly one persisted audit event"
5875 );
5876 page.items[0].clone()
5877 }
5878
5879 #[tokio::test]
5880 async fn dispatch_with_identity_stamps_request_id_on_success() {
5881 let store = Arc::new(MemoryEventStore::default());
5882 let mut builder = VerbRegistryBuilder::new();
5883 builder.register(AlphaPack);
5884 builder.with_event_store(store.clone());
5885 let reg = builder.build().expect("registry builds");
5886
5887 reg.dispatch_with_identity(
5888 "list",
5889 serde_json::json!({"namespace": "test-ns"}),
5890 Some(RequestIdentity {
5891 request_id: Some(101),
5892 ..Default::default()
5893 }),
5894 )
5895 .await
5896 .unwrap();
5897
5898 let ev = first_event(&store).await;
5899 assert_eq!(ev.outcome, EventOutcome::Success);
5900 assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(101));
5901 }
5902
5903 #[tokio::test]
5904 async fn dispatch_with_identity_stamps_request_id_on_dispatch_error() {
5905 let store = Arc::new(MemoryEventStore::default());
5906 let mut builder = VerbRegistryBuilder::new();
5907 builder.register(FailingProbePack);
5908 builder.with_event_store(store.clone());
5909 let reg = builder.build().expect("registry builds");
5910
5911 let err = reg
5912 .dispatch_with_identity(
5913 "probe",
5914 serde_json::json!({"namespace": "test-ns"}),
5915 Some(RequestIdentity {
5916 request_id: Some(102),
5917 ..Default::default()
5918 }),
5919 )
5920 .await
5921 .unwrap_err();
5922 assert!(matches!(err, RuntimeError::InvalidInput(_)));
5923
5924 let ev = first_event(&store).await;
5925 assert_eq!(ev.outcome, EventOutcome::Error);
5926 assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(102));
5927 }
5928
5929 #[tokio::test]
5930 async fn dispatch_with_identity_stamps_request_id_on_denied() {
5931 #[derive(Debug)]
5932 struct AlwaysDenyGate;
5933 impl Gate for AlwaysDenyGate {
5934 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
5935 Ok(GateDecision::deny("denied by test"))
5936 }
5937 }
5938
5939 let store = Arc::new(MemoryEventStore::default());
5940 let mut builder = VerbRegistryBuilder::new();
5941 builder.register(AlphaPack);
5942 builder.with_gate(Arc::new(AlwaysDenyGate));
5943 builder.with_event_store(store.clone());
5944 let reg = builder.build().expect("registry builds");
5945
5946 let err = reg
5947 .dispatch_with_identity(
5948 "list",
5949 serde_json::json!({"namespace": "test-ns"}),
5950 Some(RequestIdentity {
5951 request_id: Some(103),
5952 ..Default::default()
5953 }),
5954 )
5955 .await
5956 .unwrap_err();
5957 assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
5958
5959 let ev = first_event(&store).await;
5960 assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(103));
5961 }
5962
5963 #[tokio::test]
5964 async fn dispatch_with_identity_stamps_request_id_on_link_v2_success() {
5965 let store = Arc::new(MemoryEventStore::default());
5966 let edge_id = uuid::Uuid::new_v4();
5967 let source_id = uuid::Uuid::new_v4();
5968 let target_id = uuid::Uuid::new_v4();
5969 let edge_json = serde_json::json!({
5970 "id": edge_id,
5971 "namespace": "local",
5972 "source_id": source_id,
5973 "target_id": target_id,
5974 "relation": "depends_on",
5975 "weight": 1.0,
5976 });
5977 let mut builder = VerbRegistryBuilder::new();
5978 builder.register(LinkResultPack::ok(edge_json));
5979 builder.with_event_store(store.clone());
5980 builder.with_default_namespace("test-ns");
5981 let reg = builder.build().expect("registry builds");
5982
5983 reg.dispatch_with_identity(
5984 "link",
5985 serde_json::json!({
5986 "source_id": source_id,
5987 "target_id": target_id,
5988 "relation": "depends_on",
5989 }),
5990 Some(RequestIdentity {
5991 namespace: "test-ns".to_string(),
5992 request_id: Some(104),
5993 ..Default::default()
5994 }),
5995 )
5996 .await
5997 .unwrap();
5998
5999 let ev = first_event(&store).await;
6000 assert_eq!(
6001 ev.payload_schema_version, 2,
6002 "successful singleton link uses audit schema v2"
6003 );
6004 assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(104));
6005 }
6006
6007 #[tokio::test]
6008 async fn dispatch_with_identity_stamps_request_id_on_link_v1_fallback() {
6009 let store = Arc::new(MemoryEventStore::default());
6010 let mut builder = VerbRegistryBuilder::new();
6011 builder.register(LinkResultPack::err("target endpoint not found"));
6012 builder.with_event_store(store.clone());
6013 builder.with_default_namespace("test-ns");
6014 let reg = builder.build().expect("registry builds");
6015
6016 let err = reg
6017 .dispatch_with_identity(
6018 "link",
6019 serde_json::json!({
6020 "source_id": "note:alpha",
6021 "target_id": "note:missing",
6022 "relation": "depends_on",
6023 }),
6024 Some(RequestIdentity {
6025 namespace: "test-ns".to_string(),
6026 request_id: Some(105),
6027 ..Default::default()
6028 }),
6029 )
6030 .await
6031 .unwrap_err();
6032 assert!(matches!(err, RuntimeError::InvalidInput(_)));
6033
6034 let ev = first_event(&store).await;
6035 assert_eq!(
6036 ev.payload_schema_version, 1,
6037 "failed link keeps the v1 audit shape"
6038 );
6039 assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(105));
6040 }
6041
6042 #[tokio::test]
6043 async fn dispatch_with_identity_stamps_request_id_on_unknown_verb() {
6044 let store = Arc::new(MemoryEventStore::default());
6045 let mut builder = VerbRegistryBuilder::new();
6046 builder.register(AlphaPack);
6047 builder.with_event_store(store.clone());
6048 let reg = builder.build().expect("registry builds");
6049
6050 let err = reg
6051 .dispatch_with_identity(
6052 "no_such_verb",
6053 serde_json::json!({}),
6054 Some(RequestIdentity {
6055 namespace: Namespace::local().as_str().to_string(),
6056 request_id: Some(106),
6057 ..Default::default()
6058 }),
6059 )
6060 .await
6061 .unwrap_err();
6062 assert!(matches!(err, RuntimeError::InvalidInput(_)));
6063
6064 let ev = first_event(&store).await;
6065 assert_eq!(ev.outcome, EventOutcome::Error);
6066 assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(106));
6067 }
6068
6069 #[tokio::test]
6070 async fn dispatch_with_identity_omits_request_id_key_when_absent() {
6071 let store = Arc::new(MemoryEventStore::default());
6072 let mut builder = VerbRegistryBuilder::new();
6073 builder.register(AlphaPack);
6074 builder.with_event_store(store.clone());
6075 let reg = builder.build().expect("registry builds");
6076
6077 reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
6079 .await
6080 .unwrap();
6081
6082 let ev = first_event(&store).await;
6083 let resource = ev.payload["resource"]
6084 .as_object()
6085 .expect("resource must be an object");
6086 assert!(
6087 !resource.contains_key("request_id"),
6088 "request_id key must be entirely absent when no id is supplied, \
6089 not present as null or 0: got {resource:?}"
6090 );
6091 }
6092}
6093
6094#[cfg(test)]
6097mod dep_tests {
6098 use super::*;
6099 use async_trait::async_trait;
6100 use khive_types::Pack;
6101 use serde_json::Value;
6102
6103 struct KgDepPack;
6104 struct MemoryDepPack;
6105 struct ADepPack;
6106 struct BDepPack;
6107
6108 impl Pack for KgDepPack {
6109 const NAME: &'static str = "kg_dep";
6110 const NOTE_KINDS: &'static [&'static str] = &["observation"];
6111 const ENTITY_KINDS: &'static [&'static str] = &["concept"];
6112 const HANDLERS: &'static [HandlerDef] = &[];
6113 }
6114
6115 impl Pack for MemoryDepPack {
6116 const NAME: &'static str = "memory_dep";
6117 const NOTE_KINDS: &'static [&'static str] = &["memory"];
6118 const ENTITY_KINDS: &'static [&'static str] = &[];
6119 const HANDLERS: &'static [HandlerDef] = &[];
6120 const REQUIRES: &'static [&'static str] = &["kg_dep"];
6121 }
6122
6123 impl Pack for ADepPack {
6124 const NAME: &'static str = "pack_a";
6125 const NOTE_KINDS: &'static [&'static str] = &[];
6126 const ENTITY_KINDS: &'static [&'static str] = &[];
6127 const HANDLERS: &'static [HandlerDef] = &[];
6128 const REQUIRES: &'static [&'static str] = &["pack_b"];
6129 }
6130
6131 impl Pack for BDepPack {
6132 const NAME: &'static str = "pack_b";
6133 const NOTE_KINDS: &'static [&'static str] = &[];
6134 const ENTITY_KINDS: &'static [&'static str] = &[];
6135 const HANDLERS: &'static [HandlerDef] = &[];
6136 const REQUIRES: &'static [&'static str] = &["pack_a"];
6137 }
6138
6139 #[async_trait]
6140 impl PackRuntime for KgDepPack {
6141 fn name(&self) -> &str {
6142 Self::NAME
6143 }
6144 fn note_kinds(&self) -> &'static [&'static str] {
6145 Self::NOTE_KINDS
6146 }
6147 fn entity_kinds(&self) -> &'static [&'static str] {
6148 Self::ENTITY_KINDS
6149 }
6150 fn handlers(&self) -> &'static [HandlerDef] {
6151 Self::HANDLERS
6152 }
6153 async fn dispatch(
6154 &self,
6155 verb: &str,
6156 _: Value,
6157 _: &VerbRegistry,
6158 _: &NamespaceToken,
6159 ) -> Result<Value, RuntimeError> {
6160 Err(RuntimeError::InvalidInput(format!(
6161 "KgDepPack has no verbs: {verb}"
6162 )))
6163 }
6164 }
6165
6166 #[async_trait]
6167 impl PackRuntime for MemoryDepPack {
6168 fn name(&self) -> &str {
6169 Self::NAME
6170 }
6171 fn note_kinds(&self) -> &'static [&'static str] {
6172 Self::NOTE_KINDS
6173 }
6174 fn entity_kinds(&self) -> &'static [&'static str] {
6175 Self::ENTITY_KINDS
6176 }
6177 fn handlers(&self) -> &'static [HandlerDef] {
6178 Self::HANDLERS
6179 }
6180 fn requires(&self) -> &'static [&'static str] {
6181 Self::REQUIRES
6182 }
6183 async fn dispatch(
6184 &self,
6185 verb: &str,
6186 _: Value,
6187 _: &VerbRegistry,
6188 _: &NamespaceToken,
6189 ) -> Result<Value, RuntimeError> {
6190 Err(RuntimeError::InvalidInput(format!(
6191 "MemoryDepPack has no verbs: {verb}"
6192 )))
6193 }
6194 }
6195
6196 #[async_trait]
6197 impl PackRuntime for ADepPack {
6198 fn name(&self) -> &str {
6199 Self::NAME
6200 }
6201 fn note_kinds(&self) -> &'static [&'static str] {
6202 Self::NOTE_KINDS
6203 }
6204 fn entity_kinds(&self) -> &'static [&'static str] {
6205 Self::ENTITY_KINDS
6206 }
6207 fn handlers(&self) -> &'static [HandlerDef] {
6208 Self::HANDLERS
6209 }
6210 fn requires(&self) -> &'static [&'static str] {
6211 Self::REQUIRES
6212 }
6213 async fn dispatch(
6214 &self,
6215 verb: &str,
6216 _: Value,
6217 _: &VerbRegistry,
6218 _: &NamespaceToken,
6219 ) -> Result<Value, RuntimeError> {
6220 Err(RuntimeError::InvalidInput(format!(
6221 "ADepPack has no verbs: {verb}"
6222 )))
6223 }
6224 }
6225
6226 #[async_trait]
6227 impl PackRuntime for BDepPack {
6228 fn name(&self) -> &str {
6229 Self::NAME
6230 }
6231 fn note_kinds(&self) -> &'static [&'static str] {
6232 Self::NOTE_KINDS
6233 }
6234 fn entity_kinds(&self) -> &'static [&'static str] {
6235 Self::ENTITY_KINDS
6236 }
6237 fn handlers(&self) -> &'static [HandlerDef] {
6238 Self::HANDLERS
6239 }
6240 fn requires(&self) -> &'static [&'static str] {
6241 Self::REQUIRES
6242 }
6243 async fn dispatch(
6244 &self,
6245 verb: &str,
6246 _: Value,
6247 _: &VerbRegistry,
6248 _: &NamespaceToken,
6249 ) -> Result<Value, RuntimeError> {
6250 Err(RuntimeError::InvalidInput(format!(
6251 "BDepPack has no verbs: {verb}"
6252 )))
6253 }
6254 }
6255
6256 #[test]
6257 fn test_pack_deps_happy_path() {
6258 let mut builder = VerbRegistryBuilder::new();
6259 builder.register(MemoryDepPack);
6260 builder.register(KgDepPack);
6261 let reg = builder
6262 .build()
6263 .expect("kg_dep satisfies memory_dep dependency");
6264 assert_eq!(reg.pack_requires("memory_dep").unwrap(), &["kg_dep"]);
6265 let names = reg.pack_names();
6266 let kg_pos = names.iter().position(|&n| n == "kg_dep").unwrap();
6267 let mem_pos = names.iter().position(|&n| n == "memory_dep").unwrap();
6268 assert!(
6269 kg_pos < mem_pos,
6270 "kg_dep must be loaded before memory_dep; order: {names:?}"
6271 );
6272 }
6273
6274 #[test]
6275 fn test_pack_deps_missing() {
6276 let mut builder = VerbRegistryBuilder::new();
6277 builder.register(MemoryDepPack);
6278 let err = match builder.build() {
6279 Ok(_) => panic!("expected Err, got Ok"),
6280 Err(e) => e,
6281 };
6282 assert!(
6283 matches!(err, RuntimeError::MissingPackDependency(_)),
6284 "expected MissingPackDependency, got {err:?}"
6285 );
6286 let msg = err.to_string();
6287 assert!(
6288 msg.contains("memory_dep"),
6289 "error must name the dependent pack: {msg}"
6290 );
6291 assert!(
6292 msg.contains("kg_dep"),
6293 "error must name the missing dep: {msg}"
6294 );
6295 }
6296
6297 #[test]
6298 fn test_pack_deps_circular() {
6299 let mut builder = VerbRegistryBuilder::new();
6300 builder.register(ADepPack);
6301 builder.register(BDepPack);
6302 let err = match builder.build() {
6303 Ok(_) => panic!("expected Err, got Ok"),
6304 Err(e) => e,
6305 };
6306 assert!(
6307 matches!(err, RuntimeError::CircularPackDependency(_)),
6308 "expected CircularPackDependency, got {err:?}"
6309 );
6310 let msg = err.to_string();
6311 assert!(msg.contains("pack_a"), "error must name pack_a: {msg}");
6312 assert!(msg.contains("pack_b"), "error must name pack_b: {msg}");
6313 }
6314
6315 #[test]
6316 fn test_pack_deps_no_deps() {
6317 struct NoDepsA;
6318 struct NoDepsB;
6319
6320 impl Pack for NoDepsA {
6321 const NAME: &'static str = "no_deps_a";
6322 const NOTE_KINDS: &'static [&'static str] = &[];
6323 const ENTITY_KINDS: &'static [&'static str] = &[];
6324 const HANDLERS: &'static [HandlerDef] = &[];
6325 }
6326
6327 impl Pack for NoDepsB {
6328 const NAME: &'static str = "no_deps_b";
6329 const NOTE_KINDS: &'static [&'static str] = &[];
6330 const ENTITY_KINDS: &'static [&'static str] = &[];
6331 const HANDLERS: &'static [HandlerDef] = &[];
6332 }
6333
6334 #[async_trait]
6335 impl PackRuntime for NoDepsA {
6336 fn name(&self) -> &str {
6337 Self::NAME
6338 }
6339 fn note_kinds(&self) -> &'static [&'static str] {
6340 Self::NOTE_KINDS
6341 }
6342 fn entity_kinds(&self) -> &'static [&'static str] {
6343 Self::ENTITY_KINDS
6344 }
6345 fn handlers(&self) -> &'static [HandlerDef] {
6346 Self::HANDLERS
6347 }
6348 async fn dispatch(
6349 &self,
6350 verb: &str,
6351 _: Value,
6352 _: &VerbRegistry,
6353 _: &NamespaceToken,
6354 ) -> Result<Value, RuntimeError> {
6355 Err(RuntimeError::InvalidInput(format!("NoDepsA: {verb}")))
6356 }
6357 }
6358
6359 #[async_trait]
6360 impl PackRuntime for NoDepsB {
6361 fn name(&self) -> &str {
6362 Self::NAME
6363 }
6364 fn note_kinds(&self) -> &'static [&'static str] {
6365 Self::NOTE_KINDS
6366 }
6367 fn entity_kinds(&self) -> &'static [&'static str] {
6368 Self::ENTITY_KINDS
6369 }
6370 fn handlers(&self) -> &'static [HandlerDef] {
6371 Self::HANDLERS
6372 }
6373 async fn dispatch(
6374 &self,
6375 verb: &str,
6376 _: Value,
6377 _: &VerbRegistry,
6378 _: &NamespaceToken,
6379 ) -> Result<Value, RuntimeError> {
6380 Err(RuntimeError::InvalidInput(format!("NoDepsB: {verb}")))
6381 }
6382 }
6383
6384 let mut builder = VerbRegistryBuilder::new();
6385 builder.register(NoDepsA);
6386 builder.register(NoDepsB);
6387 let reg = builder.build().expect("packs with REQUIRES=&[] build");
6388 assert_eq!(reg.pack_requires("no_deps_a").unwrap(), &[] as &[&str]);
6389 assert_eq!(reg.pack_requires("no_deps_b").unwrap(), &[] as &[&str]);
6390 }
6391}
6392
6393#[cfg(test)]
6396mod hook_tests {
6397 use super::*;
6398 use async_trait::async_trait;
6399 use khive_types::Pack;
6400 use std::sync::atomic::{AtomicUsize, Ordering};
6401 use std::sync::Mutex as StdMutex;
6402
6403 struct SimplePack;
6404
6405 impl Pack for SimplePack {
6406 const NAME: &'static str = "simple";
6407 const NOTE_KINDS: &'static [&'static str] = &[];
6408 const ENTITY_KINDS: &'static [&'static str] = &[];
6409 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
6410 name: "ping",
6411 description: "ping",
6412 visibility: Visibility::Verb,
6413 category: VerbCategory::Assertive,
6414 params: &[],
6415 }];
6416 }
6417
6418 #[async_trait]
6419 impl PackRuntime for SimplePack {
6420 fn name(&self) -> &str {
6421 SimplePack::NAME
6422 }
6423 fn note_kinds(&self) -> &'static [&'static str] {
6424 SimplePack::NOTE_KINDS
6425 }
6426 fn entity_kinds(&self) -> &'static [&'static str] {
6427 SimplePack::ENTITY_KINDS
6428 }
6429 fn handlers(&self) -> &'static [HandlerDef] {
6430 SimplePack::HANDLERS
6431 }
6432 async fn dispatch(
6433 &self,
6434 verb: &str,
6435 _params: Value,
6436 _registry: &VerbRegistry,
6437 _token: &NamespaceToken,
6438 ) -> Result<Value, RuntimeError> {
6439 Ok(serde_json::json!({ "verb": verb }))
6440 }
6441 }
6442
6443 struct RecallPack;
6444
6445 impl Pack for RecallPack {
6446 const NAME: &'static str = "memory";
6447 const NOTE_KINDS: &'static [&'static str] = &[];
6448 const ENTITY_KINDS: &'static [&'static str] = &[];
6449 const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
6450 name: "memory.recall",
6451 description: "test recall",
6452 visibility: Visibility::Verb,
6453 category: VerbCategory::Assertive,
6454 params: &[],
6455 }];
6456 }
6457
6458 #[async_trait]
6459 impl PackRuntime for RecallPack {
6460 fn name(&self) -> &str {
6461 RecallPack::NAME
6462 }
6463 fn note_kinds(&self) -> &'static [&'static str] {
6464 RecallPack::NOTE_KINDS
6465 }
6466 fn entity_kinds(&self) -> &'static [&'static str] {
6467 RecallPack::ENTITY_KINDS
6468 }
6469 fn handlers(&self) -> &'static [HandlerDef] {
6470 RecallPack::HANDLERS
6471 }
6472 async fn dispatch(
6473 &self,
6474 _verb: &str,
6475 params: Value,
6476 _registry: &VerbRegistry,
6477 _token: &NamespaceToken,
6478 ) -> Result<Value, RuntimeError> {
6479 let hit = serde_json::json!({
6480 "id": uuid::Uuid::new_v4().to_string(),
6481 "served_by_profile_id": "custom-recall-v1",
6482 "serve_attribution": "profile",
6483 });
6484 if params.get("verbose").and_then(Value::as_bool) == Some(true) {
6485 Ok(serde_json::json!({"results": [hit]}))
6486 } else {
6487 Ok(serde_json::json!([hit]))
6488 }
6489 }
6490 }
6491
6492 #[derive(Default)]
6493 struct EventCapturingHook {
6494 event: StdMutex<Option<Event>>,
6495 }
6496
6497 #[async_trait]
6498 impl DispatchHook for EventCapturingHook {
6499 async fn on_dispatch(&self, view: &EventView) {
6500 *self.event.lock().unwrap() = Some(view.event.clone());
6501 }
6502 }
6503
6504 #[derive(Default)]
6506 struct CountingHook {
6507 calls: AtomicUsize,
6508 last_verb: StdMutex<String>,
6509 }
6510
6511 #[async_trait]
6512 impl DispatchHook for CountingHook {
6513 async fn on_dispatch(&self, view: &EventView) {
6514 self.calls.fetch_add(1, Ordering::SeqCst);
6515 *self.last_verb.lock().unwrap() = view.event.verb.clone();
6516 }
6517 }
6518
6519 #[tokio::test]
6520 async fn dispatch_hook_fires_on_successful_dispatch() {
6521 let hook = Arc::new(CountingHook::default());
6522 let mut builder = VerbRegistryBuilder::new();
6523 builder.register(SimplePack);
6524 builder.with_dispatch_hook(hook.clone());
6525 let reg = builder.build().expect("registry builds");
6526
6527 reg.dispatch("ping", Value::Null).await.unwrap();
6528
6529 assert_eq!(
6530 hook.calls.load(Ordering::SeqCst),
6531 1,
6532 "hook must fire once per successful dispatch"
6533 );
6534 assert_eq!(
6535 hook.last_verb.lock().unwrap().as_str(),
6536 "ping",
6537 "hook event must carry the dispatched verb"
6538 );
6539 }
6540
6541 #[tokio::test]
6542 async fn dispatch_hook_fires_multiple_times() {
6543 let hook = Arc::new(CountingHook::default());
6544 let mut builder = VerbRegistryBuilder::new();
6545 builder.register(SimplePack);
6546 builder.with_dispatch_hook(hook.clone());
6547 let reg = builder.build().expect("registry builds");
6548
6549 reg.dispatch("ping", Value::Null).await.unwrap();
6550 reg.dispatch("ping", Value::Null).await.unwrap();
6551 reg.dispatch("ping", Value::Null).await.unwrap();
6552
6553 assert_eq!(
6554 hook.calls.load(Ordering::SeqCst),
6555 3,
6556 "hook must fire once per successful dispatch"
6557 );
6558 }
6559
6560 #[tokio::test]
6561 async fn recall_hook_copies_serve_attribution_from_bare_and_verbose_results() {
6562 let hook = Arc::new(EventCapturingHook::default());
6563 let mut builder = VerbRegistryBuilder::new();
6564 builder.register(RecallPack);
6565 builder.with_dispatch_hook(hook.clone());
6566 let reg = builder.build().expect("registry builds");
6567
6568 for params in [serde_json::json!({}), serde_json::json!({"verbose": true})] {
6569 reg.dispatch("memory.recall", params)
6570 .await
6571 .expect("recall dispatch");
6572 let event = hook.event.lock().unwrap().clone().expect("hook event");
6573 assert!(
6574 event.target_id.is_some(),
6575 "first recall id must become target"
6576 );
6577 assert_eq!(
6578 event.payload["served_by_profile_id"],
6579 serde_json::json!("custom-recall-v1")
6580 );
6581 assert_eq!(
6582 event.payload["serve_attribution"],
6583 serde_json::json!("profile")
6584 );
6585 }
6586 }
6587
6588 #[tokio::test]
6589 async fn dispatch_hook_does_not_fire_on_unknown_verb() {
6590 let hook = Arc::new(CountingHook::default());
6591 let mut builder = VerbRegistryBuilder::new();
6592 builder.register(SimplePack);
6593 builder.with_dispatch_hook(hook.clone());
6594 let reg = builder.build().expect("registry builds");
6595
6596 let _ = reg.dispatch("nonexistent", Value::Null).await;
6597
6598 assert_eq!(
6599 hook.calls.load(Ordering::SeqCst),
6600 0,
6601 "hook must NOT fire for unknown verb (dispatch returns error)"
6602 );
6603 }
6604
6605 #[tokio::test]
6606 async fn dispatch_hook_does_not_fire_on_gate_deny() {
6607 use khive_gate::{Gate, GateDecision, GateError};
6608
6609 #[derive(Debug)]
6610 struct AlwaysDenyGate;
6611 impl Gate for AlwaysDenyGate {
6612 fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
6613 Ok(GateDecision::deny("test deny"))
6614 }
6615 }
6616
6617 let hook = Arc::new(CountingHook::default());
6618 let mut builder = VerbRegistryBuilder::new();
6619 builder.register(SimplePack);
6620 builder.with_gate(Arc::new(AlwaysDenyGate));
6621 builder.with_dispatch_hook(hook.clone());
6622 let reg = builder.build().expect("registry builds");
6623
6624 let err = reg.dispatch("ping", Value::Null).await.unwrap_err();
6625 assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
6626
6627 assert_eq!(
6628 hook.calls.load(Ordering::SeqCst),
6629 0,
6630 "hook must NOT fire when gate denies dispatch"
6631 );
6632 }
6633
6634 #[tokio::test]
6635 async fn dispatch_hook_event_carries_namespace_from_params() {
6636 let hook = Arc::new(CountingHook::default());
6637
6638 #[derive(Default)]
6639 struct NsCapturingHook {
6640 ns: StdMutex<String>,
6641 }
6642
6643 #[async_trait]
6644 impl DispatchHook for NsCapturingHook {
6645 async fn on_dispatch(&self, view: &EventView) {
6646 *self.ns.lock().unwrap() = view.event.namespace.clone();
6647 }
6648 }
6649
6650 let ns_hook = Arc::new(NsCapturingHook::default());
6651 let mut builder = VerbRegistryBuilder::new();
6652 builder.register(SimplePack);
6653 builder.with_dispatch_hook(ns_hook.clone());
6654 let reg = builder.build().expect("registry builds");
6655
6656 reg.dispatch("ping", serde_json::json!({"namespace": "tenant-abc"}))
6657 .await
6658 .unwrap();
6659
6660 assert_eq!(
6661 ns_hook.ns.lock().unwrap().as_str(),
6662 "tenant-abc",
6663 "dispatch hook event must carry the resolved namespace"
6664 );
6665
6666 drop(hook);
6668 }
6669
6670 #[tokio::test]
6671 async fn no_dispatch_hook_configured_dispatch_succeeds() {
6672 let mut builder = VerbRegistryBuilder::new();
6674 builder.register(SimplePack);
6675 let reg = builder.build().expect("registry builds");
6677
6678 let res = reg.dispatch("ping", Value::Null).await.unwrap();
6679 assert_eq!(res["verb"], "ping");
6680 }
6681}
6682
6683#[cfg(test)]
6686mod help_tests {
6687 use super::*;
6688 use async_trait::async_trait;
6689 use khive_types::Pack;
6690 use std::sync::{
6691 atomic::{AtomicUsize, Ordering},
6692 Arc,
6693 };
6694
6695 static CREATE_PARAMS: [ParamDef; 2] = [
6700 ParamDef {
6701 name: "kind",
6702 param_type: "string",
6703 required: true,
6704 description: "Granular kind (concept | document | ...).",
6705 },
6706 ParamDef {
6707 name: "name",
6708 param_type: "string",
6709 required: false,
6710 description: "Human-readable name.",
6711 },
6712 ];
6713
6714 static RECALL_PARAMS: [ParamDef; 2] = [
6715 ParamDef {
6716 name: "query",
6717 param_type: "string",
6718 required: true,
6719 description: "Semantic recall query.",
6720 },
6721 ParamDef {
6722 name: "limit",
6723 param_type: "integer",
6724 required: false,
6725 description: "Maximum memories to return.",
6726 },
6727 ];
6728
6729 static EMBED_PARAMS: [ParamDef; 0] = [];
6732
6733 struct HelpPack {
6734 invocations: Arc<AtomicUsize>,
6735 }
6736
6737 impl Pack for HelpPack {
6738 const NAME: &'static str = "helptest";
6739 const NOTE_KINDS: &'static [&'static str] = &[];
6740 const ENTITY_KINDS: &'static [&'static str] = &[];
6741 const HANDLERS: &'static [HandlerDef] = &[
6742 HandlerDef {
6743 name: "create",
6744 description: "Create an entity or note",
6745 visibility: Visibility::Verb,
6746 category: VerbCategory::Commissive,
6747 params: &CREATE_PARAMS,
6748 },
6749 HandlerDef {
6750 name: "recall",
6751 description: "Recall memory notes with decay-aware hybrid ranking",
6752 visibility: Visibility::Verb,
6753 category: VerbCategory::Assertive,
6754 params: &RECALL_PARAMS,
6755 },
6756 HandlerDef {
6759 name: "recall.embed",
6760 description: "Return the embedding vector used by memory recall",
6761 visibility: Visibility::Subhandler,
6762 category: VerbCategory::Assertive,
6763 params: &EMBED_PARAMS,
6764 },
6765 HandlerDef {
6766 name: "link",
6767 description: "Create a typed directed edge",
6768 visibility: Visibility::Verb,
6769 category: VerbCategory::Commissive,
6770 params: &[],
6771 },
6772 ];
6773 }
6774
6775 static HELP_EDGE_RULES: [EdgeEndpointRule; 2] = [
6783 EdgeEndpointRule {
6784 relation: khive_types::EdgeRelation::DependsOn,
6785 source: EndpointKind::NoteOfKind("task"),
6786 target: EndpointKind::NoteOfKind("task"),
6787 },
6788 EdgeEndpointRule {
6789 relation: khive_types::EdgeRelation::Supersedes,
6790 source: EndpointKind::NoteOfKind("task"),
6791 target: EndpointKind::NoteOfKind("task"),
6792 },
6793 ];
6794
6795 #[async_trait]
6796 impl PackRuntime for HelpPack {
6797 fn name(&self) -> &str {
6798 HelpPack::NAME
6799 }
6800 fn note_kinds(&self) -> &'static [&'static str] {
6801 HelpPack::NOTE_KINDS
6802 }
6803 fn entity_kinds(&self) -> &'static [&'static str] {
6804 HelpPack::ENTITY_KINDS
6805 }
6806 fn handlers(&self) -> &'static [HandlerDef] {
6807 HelpPack::HANDLERS
6808 }
6809 fn edge_rules(&self) -> &'static [EdgeEndpointRule] {
6810 &HELP_EDGE_RULES
6811 }
6812 async fn dispatch(
6813 &self,
6814 verb: &str,
6815 _params: Value,
6816 _registry: &VerbRegistry,
6817 _token: &NamespaceToken,
6818 ) -> Result<Value, RuntimeError> {
6819 self.invocations.fetch_add(1, Ordering::SeqCst);
6820 Ok(serde_json::json!({ "pack": "helptest", "verb": verb }))
6821 }
6822 }
6823
6824 fn build_help_registry(invocations: Arc<AtomicUsize>) -> VerbRegistry {
6825 let mut builder = VerbRegistryBuilder::new();
6826 builder.register(HelpPack { invocations });
6827 builder.build().expect("help registry builds")
6828 }
6829
6830 #[tokio::test]
6833 async fn test_help_true_returns_schema_for_kg_create() {
6834 let invocations = Arc::new(AtomicUsize::new(0));
6835 let reg = build_help_registry(invocations.clone());
6836
6837 let result = reg
6838 .dispatch("create", serde_json::json!({ "help": true }))
6839 .await
6840 .expect("help=true must succeed for a known verb");
6841
6842 assert_eq!(result["verb"], "create", "envelope must name the verb");
6844 assert_eq!(
6845 result["pack"], "helptest",
6846 "envelope must name the owning pack"
6847 );
6848 assert!(
6849 result["description"].as_str().is_some(),
6850 "description must be a string"
6851 );
6852
6853 let params = result["params"]
6855 .as_array()
6856 .expect("params must be a JSON array");
6857 assert!(!params.is_empty(), "params array must not be empty");
6858
6859 let kind_param = params.iter().find(|p| p["name"] == "kind");
6861 assert!(
6862 kind_param.is_some(),
6863 "params array must include the 'kind' parameter"
6864 );
6865 let kind_param = kind_param.unwrap();
6866 assert_eq!(
6867 kind_param["required"],
6868 serde_json::json!(true),
6869 "'kind' must be required"
6870 );
6871 assert_eq!(kind_param["type"], "string", "'kind' type must be 'string'");
6872 }
6873
6874 #[tokio::test]
6876 async fn test_help_true_returns_schema_for_recall() {
6877 let invocations = Arc::new(AtomicUsize::new(0));
6878 let reg = build_help_registry(invocations.clone());
6879
6880 let result = reg
6881 .dispatch("recall", serde_json::json!({ "help": true }))
6882 .await
6883 .expect("help=true must succeed for recall");
6884
6885 assert_eq!(result["verb"], "recall");
6886 assert_eq!(result["pack"], "helptest");
6887
6888 let params = result["params"]
6889 .as_array()
6890 .expect("params must be a JSON array");
6891
6892 let query_param = params.iter().find(|p| p["name"] == "query");
6894 assert!(query_param.is_some(), "params must include 'query'");
6895 let query_param = query_param.unwrap();
6896 assert_eq!(
6897 query_param["required"],
6898 serde_json::json!(true),
6899 "'query' must be required"
6900 );
6901
6902 let limit_param = params.iter().find(|p| p["name"] == "limit");
6904 assert!(limit_param.is_some(), "params must include 'limit'");
6905 let limit_param = limit_param.unwrap();
6906 assert_eq!(
6907 limit_param["required"],
6908 serde_json::json!(false),
6909 "'limit' must be optional"
6910 );
6911 }
6912
6913 #[tokio::test]
6919 async fn test_link_help_true_exposes_endpoint_rules() {
6920 let invocations = Arc::new(AtomicUsize::new(0));
6921 let reg = build_help_registry(invocations.clone());
6922
6923 let result = reg
6924 .dispatch("link", serde_json::json!({ "help": true }))
6925 .await
6926 .expect("help=true must succeed for link");
6927
6928 assert_eq!(result["verb"], "link");
6929 let rules = result["endpoint_rules"]
6930 .as_array()
6931 .expect("link help must include an endpoint_rules array");
6932 assert!(!rules.is_empty(), "endpoint_rules must not be empty");
6933
6934 assert!(
6936 rules.iter().any(|r| r["relation"] == "contains"
6937 && r["source"] == "entity:concept"
6938 && r["target"] == "entity:concept"),
6939 "endpoint_rules must include the base 'contains' entity rule; got {rules:#?}"
6940 );
6941
6942 assert!(
6944 rules.iter().any(|r| r["relation"] == "depends_on"
6945 && r["source"] == "note:task"
6946 && r["target"] == "note:task"),
6947 "endpoint_rules must include the pack-declared depends_on rule; got {rules:#?}"
6948 );
6949
6950 assert!(
6952 rules
6953 .iter()
6954 .any(|r| r["relation"] == "annotates" && r["source"] == "note:*"),
6955 "endpoint_rules must document the annotates note-to-any rule; got {rules:#?}"
6956 );
6957
6958 assert_eq!(
6960 invocations.load(Ordering::SeqCst),
6961 0,
6962 "link(help=true) must not invoke pack dispatch"
6963 );
6964 }
6965
6966 #[tokio::test]
6985 async fn test_link_help_true_matches_special_relation_validator_set() {
6986 let invocations = Arc::new(AtomicUsize::new(0));
6987 let reg = build_help_registry(invocations.clone());
6988
6989 let result = reg
6990 .dispatch("link", serde_json::json!({ "help": true }))
6991 .await
6992 .expect("help=true must succeed for link");
6993
6994 let rules = result["endpoint_rules"]
6995 .as_array()
6996 .expect("link help must include an endpoint_rules array");
6997
6998 for relation in ["supersedes", "supports", "refutes"] {
6999 assert!(
7001 rules.iter().any(|r| r["relation"] == relation
7002 && r["source"] == "note:*"
7003 && r["target"] == "note:*"),
7004 "endpoint_rules must include the note:*->note:* row for '{relation}' \
7005 (validator accepts any note->note pair unconditionally); got {rules:#?}"
7006 );
7007
7008 assert!(
7013 !rules.iter().any(|r| r["relation"] == relation
7014 && r["source"] == "note:task"
7015 && r["target"] == "note:task"),
7016 "endpoint_rules must NOT advertise a pack EDGE_RULES row for special \
7017 relation '{relation}' — validate_edge_relation_endpoints never consults \
7018 pack_rule_allows for supersedes/supports/refutes; got {rules:#?}"
7019 );
7020 }
7021
7022 for (relation, kind) in [
7025 ("supersedes", "concept"),
7026 ("supports", "concept"),
7027 ("refutes", "concept"),
7028 ] {
7029 assert!(
7030 rules.iter().any(|r| r["relation"] == relation
7031 && r["source"] == format!("entity:{kind}")
7032 && r["target"] == "entity:concept"),
7033 "endpoint_rules must include the base entity:{kind}->entity:concept row \
7034 for '{relation}'; got {rules:#?}"
7035 );
7036 }
7037 }
7038
7039 #[test]
7040 fn special_relation_predicate_matches_the_dedicated_validator_set() {
7041 for relation in khive_types::EdgeRelation::ALL {
7042 assert_eq!(
7043 is_special_relation(relation),
7044 matches!(
7045 relation,
7046 khive_types::EdgeRelation::Supersedes
7047 | khive_types::EdgeRelation::Supports
7048 | khive_types::EdgeRelation::Refutes
7049 ),
7050 "unexpected special-relation classification for {relation}"
7051 );
7052 }
7053 }
7054
7055 #[tokio::test]
7058 async fn test_help_true_does_not_execute_the_verb() {
7059 let invocations = Arc::new(AtomicUsize::new(0));
7060 let reg = build_help_registry(invocations.clone());
7061
7062 reg.dispatch("create", serde_json::json!({ "help": true }))
7064 .await
7065 .expect("help=true must succeed");
7066 reg.dispatch("recall", serde_json::json!({ "help": true }))
7067 .await
7068 .expect("help=true must succeed");
7069
7070 assert_eq!(
7071 invocations.load(Ordering::SeqCst),
7072 0,
7073 "pack dispatch MUST NOT be invoked when help=true; \
7074 got {} invocation(s)",
7075 invocations.load(Ordering::SeqCst)
7076 );
7077
7078 reg.dispatch("create", serde_json::json!({}))
7080 .await
7081 .expect("normal dispatch must succeed");
7082 assert_eq!(
7083 invocations.load(Ordering::SeqCst),
7084 1,
7085 "pack dispatch must fire exactly once for a normal call"
7086 );
7087 }
7088
7089 #[tokio::test]
7098 async fn help_true_on_subhandler_returns_callable_via_mcp_false() {
7099 let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
7100
7101 let result = reg
7102 .dispatch("recall.embed", serde_json::json!({ "help": true }))
7103 .await
7104 .expect("help=true on subhandler must succeed (no permission check on help path)");
7105
7106 assert_eq!(
7107 result["callable_via_mcp"],
7108 serde_json::json!(false),
7109 "subhandler help must carry callable_via_mcp: false"
7110 );
7111 assert_eq!(
7112 result["visibility"], "internal",
7113 "subhandler help must carry visibility: internal"
7114 );
7115 assert_eq!(result["verb"], "recall.embed");
7118 assert_eq!(result["pack"], "helptest");
7119 }
7120
7121 #[tokio::test]
7123 async fn help_true_on_public_verb_does_not_have_callable_via_mcp_false() {
7124 let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
7125
7126 let result = reg
7127 .dispatch("create", serde_json::json!({ "help": true }))
7128 .await
7129 .expect("help=true on public verb must succeed");
7130
7131 assert_ne!(
7133 result.get("callable_via_mcp"),
7134 Some(&serde_json::json!(false)),
7135 "public verb help must NOT carry callable_via_mcp: false"
7136 );
7137 assert_ne!(
7139 result.get("visibility"),
7140 Some(&serde_json::json!("internal")),
7141 "public verb help must NOT carry visibility: internal"
7142 );
7143 }
7144
7145 #[tokio::test]
7147 async fn help_true_on_unknown_verb_returns_error() {
7148 let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
7149
7150 let err = reg
7151 .dispatch("nonexistent_verb", serde_json::json!({ "help": true }))
7152 .await
7153 .unwrap_err();
7154
7155 assert!(
7156 matches!(err, RuntimeError::InvalidInput(_)),
7157 "help=true on unknown verb must return InvalidInput, got {err:?}"
7158 );
7159 let msg = err.to_string();
7160 assert!(
7161 msg.contains("nonexistent_verb"),
7162 "error must name the unknown verb: {msg}"
7163 );
7164 }
7165
7166 #[tokio::test]
7168 async fn help_true_on_subhandler_includes_params_field() {
7169 let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
7170
7171 let result = reg
7172 .dispatch("recall.embed", serde_json::json!({ "help": true }))
7173 .await
7174 .expect("help=true on subhandler must succeed");
7175
7176 let params = result
7178 .get("params")
7179 .expect("subhandler help must include 'params' field");
7180 assert!(
7181 params.is_array(),
7182 "subhandler help params must be a JSON array"
7183 );
7184 }
7185
7186 #[tokio::test]
7191 async fn help_true_unknown_verb_available_list_excludes_subhandlers() {
7192 let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
7193
7194 let err = reg
7195 .dispatch("not_a_verb", serde_json::json!({ "help": true }))
7196 .await
7197 .unwrap_err();
7198
7199 let msg = err.to_string();
7200 assert!(
7203 !msg.contains("recall.embed"),
7204 "unknown-verb help error must not advertise subhandler recall.embed: {msg}"
7205 );
7206 assert!(
7208 msg.contains("create"),
7209 "unknown-verb help error must still list public verb 'create': {msg}"
7210 );
7211 assert!(
7212 msg.contains("recall"),
7213 "unknown-verb help error must still list public verb 'recall': {msg}"
7214 );
7215 }
7216
7217 #[tokio::test]
7219 async fn dispatch_unknown_verb_available_list_excludes_subhandlers() {
7220 let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
7221
7222 let err = reg
7223 .dispatch("not_a_verb", serde_json::json!({}))
7224 .await
7225 .unwrap_err();
7226
7227 let msg = err.to_string();
7228 assert!(
7231 !msg.contains("recall.embed"),
7232 "dispatch unknown-verb error must not advertise subhandler recall.embed: {msg}"
7233 );
7234 assert!(
7236 msg.contains("create"),
7237 "dispatch unknown-verb error must still list public verb 'create': {msg}"
7238 );
7239 assert!(
7240 msg.contains("recall"),
7241 "dispatch unknown-verb error must still list public verb 'recall': {msg}"
7242 );
7243 }
7244
7245 struct SchemaPack {
7249 pack_name: &'static str,
7250 statements: &'static [&'static str],
7251 }
7252
7253 impl Pack for SchemaPack {
7254 const NAME: &'static str = "schema-pack";
7255 const NOTE_KINDS: &'static [&'static str] = &[];
7256 const ENTITY_KINDS: &'static [&'static str] = &[];
7257 const HANDLERS: &'static [HandlerDef] = &[];
7258 }
7259
7260 #[async_trait]
7261 impl PackRuntime for SchemaPack {
7262 fn name(&self) -> &str {
7263 self.pack_name
7264 }
7265 fn note_kinds(&self) -> &'static [&'static str] {
7266 &[]
7267 }
7268 fn entity_kinds(&self) -> &'static [&'static str] {
7269 &[]
7270 }
7271 fn handlers(&self) -> &'static [HandlerDef] {
7272 &[]
7273 }
7274 fn schema_plan(&self) -> SchemaPlan {
7275 SchemaPlan {
7276 pack: self.pack_name,
7277 statements: self.statements,
7278 }
7279 }
7280 async fn dispatch(
7281 &self,
7282 verb: &str,
7283 _params: Value,
7284 _registry: &VerbRegistry,
7285 _token: &NamespaceToken,
7286 ) -> Result<Value, RuntimeError> {
7287 Ok(serde_json::json!({ "pack": self.pack_name, "verb": verb }))
7288 }
7289 }
7290
7291 #[test]
7294 fn all_schema_plans_named_returns_correct_pairs() {
7295 let mut builder = VerbRegistryBuilder::new();
7296 builder.register_boxed(Box::new(SchemaPack {
7297 pack_name: "alpha",
7298 statements: &["CREATE TABLE IF NOT EXISTS t_alpha (id INTEGER PRIMARY KEY)"],
7299 }));
7300 builder.register_boxed(Box::new(SchemaPack {
7301 pack_name: "beta",
7302 statements: &[],
7303 }));
7304 let reg = builder.build().expect("registry builds");
7305
7306 let named = reg.all_schema_plans_named();
7307 assert_eq!(named.len(), 2);
7308
7309 let alpha_entry = named.iter().find(|(n, _)| *n == "alpha");
7310 let beta_entry = named.iter().find(|(n, _)| *n == "beta");
7311
7312 assert!(alpha_entry.is_some(), "alpha must appear in named plans");
7313 assert!(beta_entry.is_some(), "beta must appear in named plans");
7314
7315 let (_, alpha_plan) = alpha_entry.unwrap();
7316 assert_eq!(alpha_plan.statements.len(), 1);
7317 assert!(!alpha_plan.is_empty());
7318
7319 let (_, beta_plan) = beta_entry.unwrap();
7320 assert!(beta_plan.is_empty());
7321 }
7322
7323 #[tokio::test]
7340 async fn apply_schema_plans_with_map_routes_to_correct_backend() {
7341 use khive_storage::types::{SqlStatement, SqlValue};
7342
7343 let default_backend = khive_db::StorageBackend::memory().expect("default memory backend");
7344 let pack_backend =
7345 khive_db::StorageBackend::memory().expect("pack-specific memory backend");
7346
7347 let mut builder = VerbRegistryBuilder::new();
7348 builder.register_boxed(Box::new(SchemaPack {
7349 pack_name: "routed",
7350 statements: &["CREATE TABLE IF NOT EXISTS t_routed (id INTEGER PRIMARY KEY)"],
7351 }));
7352 let reg = builder.build().expect("registry builds");
7353
7354 let mut backend_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
7355 backend_map.insert("routed", &pack_backend);
7356
7357 reg.apply_schema_plans_with_map(&backend_map, &default_backend)
7358 .expect("schema application must not collide");
7359
7360 let mut writer = pack_backend.sql().writer().await.expect("writer");
7362 let result = writer
7363 .execute(SqlStatement {
7364 sql: "INSERT INTO t_routed (id) VALUES (?1)".into(),
7365 params: vec![SqlValue::Integer(1)],
7366 label: None,
7367 })
7368 .await;
7369 assert!(
7370 result.is_ok(),
7371 "t_routed must exist on pack_backend after routing: {result:?}"
7372 );
7373
7374 let mut default_writer = default_backend.sql().writer().await.expect("writer");
7376 let default_result = default_writer
7377 .execute(SqlStatement {
7378 sql: "INSERT INTO t_routed (id) VALUES (?1)".into(),
7379 params: vec![SqlValue::Integer(2)],
7380 label: None,
7381 })
7382 .await;
7383 assert!(
7384 default_result.is_err(),
7385 "t_routed must NOT exist on default_backend (table should not be there)"
7386 );
7387 }
7388
7389 #[tokio::test]
7392 async fn apply_schema_plans_with_map_falls_back_to_default_for_unmapped_packs() {
7393 use khive_storage::types::{SqlStatement, SqlValue};
7394
7395 let default_backend = khive_db::StorageBackend::memory().expect("default memory backend");
7396
7397 let mut builder = VerbRegistryBuilder::new();
7398 builder.register_boxed(Box::new(SchemaPack {
7399 pack_name: "unmapped",
7400 statements: &["CREATE TABLE IF NOT EXISTS t_unmapped (id INTEGER PRIMARY KEY)"],
7401 }));
7402 let reg = builder.build().expect("registry builds");
7403
7404 let backend_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
7405 reg.apply_schema_plans_with_map(&backend_map, &default_backend)
7406 .expect("schema application must not collide");
7407
7408 let mut writer = default_backend.sql().writer().await.expect("writer");
7410 let result = writer
7411 .execute(SqlStatement {
7412 sql: "INSERT INTO t_unmapped (id) VALUES (?1)".into(),
7413 params: vec![SqlValue::Integer(1)],
7414 label: None,
7415 })
7416 .await;
7417 assert!(
7418 result.is_ok(),
7419 "t_unmapped must exist on default_backend for unmapped pack: {result:?}"
7420 );
7421 }
7422
7423 #[test]
7428 fn apply_schema_plans_with_map_collision_is_an_error() {
7429 let backend = khive_db::StorageBackend::memory().expect("memory backend");
7430 let empty_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
7431
7432 let mut builder = VerbRegistryBuilder::new();
7433 builder.register_boxed(Box::new(SchemaPack {
7434 pack_name: "pack_alpha",
7435 statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
7436 }));
7437 builder.register_boxed(Box::new(SchemaPack {
7438 pack_name: "pack_beta",
7439 statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
7440 }));
7441 let registry = builder.build().expect("registry builds");
7442
7443 let result = registry.apply_schema_plans_with_map(&empty_map, &backend);
7444 assert!(
7445 result.is_err(),
7446 "two packs declaring the same table on the same backend must produce a collision error"
7447 );
7448 let err = result.unwrap_err();
7449 let msg = err.to_string();
7450 assert!(
7451 msg.contains("pack_alpha"),
7452 "collision error must name first pack; got: {msg}"
7453 );
7454 assert!(
7455 msg.contains("pack_beta"),
7456 "collision error must name second pack; got: {msg}"
7457 );
7458 assert!(
7459 msg.contains("collision_table"),
7460 "collision error must name the table; got: {msg}"
7461 );
7462 }
7463}