use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
use std::time::Instant;
use crate::operations::{LinkSpec, Resolved};
use crate::runtime::NamespaceToken;
use async_trait::async_trait;
use khive_gate::{AllowAllGate, AuditEvent, GateDecision, GateRef, GateRequest};
use khive_storage::{Event, EventStore, EventView, SubstrateKind};
use khive_types::{EventKind, EventOutcome, Namespace};
use serde_json::Value;
pub use khive_types::{
EdgeEndpointRule, EndpointKind, EntityTypeDef, HandlerDef, NoteKindSpec, NoteLifecycleSpec,
PackSchemaPlan, ParamDef, VerbCategory, VerbPresentationPolicy, Visibility,
RESERVED_ENVELOPE_ARGS,
};
#[allow(deprecated)]
pub use khive_types::VerbDef;
use crate::validation::ValidationRule;
pub const GENERIC_CRUD_PACK: &str = "kg";
pub const AUDIT_PERSISTENCE_SKIPPED_READ_ONLY: &str = "audit_persistence_skipped_read_only";
const FULL_UUID_IDENTIFIER_HELP: &str = "A complete UUID spelling accepted by the consuming \
parameter directly names one globally unique record; direct UUID lookup is not a namespace \
search. Strict identifier responses use canonical lowercase dashed UUIDs.";
const SHORT_PREFIX_IDENTIFIER_HELP: &str = "A short UUID prefix is at least 8 hexadecimal \
characters without dashes that do not parse as a complete UUID. It is a resolution, not a \
direct identifier; a 32-character compact UUID is complete input instead. Its lookup scope belongs to the consuming parameter: \
operations governed by ADR-007's by-ID contract resolve without a namespace filter, while \
other resolvers may search only the caller's primary namespace. A prefix can be missing or \
ambiguous.";
const IDENTIFIER_PARAMETER_HELP: &str = "A parameter that requires a full UUID rejects prefixes \
and explains the resolution consequence. Its corresponding response field remains a \
canonical full UUID so the value can be submitted again.";
fn identifier_resolution_help() -> Value {
serde_json::json!({
"full_uuid": FULL_UUID_IDENTIFIER_HELP,
"short_prefix": SHORT_PREFIX_IDENTIFIER_HELP,
"parameter_rule": IDENTIFIER_PARAMETER_HELP,
})
}
#[derive(Debug, Default, Clone)]
pub struct SchemaPlan {
pub pack: &'static str,
pub statements: &'static [&'static str],
}
impl SchemaPlan {
pub const fn empty() -> Self {
Self {
pack: "",
statements: &[],
}
}
pub fn is_empty(&self) -> bool {
self.statements.is_empty()
}
}
#[async_trait]
pub trait DispatchHook: Send + Sync {
async fn on_dispatch(&self, view: &EventView);
}
use crate::error::{
CircularPackDependency, MissingPackDependencies, MissingPackDependency, RuntimeError,
};
use crate::KhiveRuntime;
#[async_trait]
pub trait PackRuntime: Send + Sync {
fn name(&self) -> &str;
fn note_kinds(&self) -> &'static [&'static str];
fn entity_kinds(&self) -> &'static [&'static str];
fn brain_consumer_kinds(&self) -> &'static [&'static str] {
&[]
}
fn handlers(&self) -> &'static [HandlerDef];
fn edge_rules(&self) -> &'static [EdgeEndpointRule] {
&[]
}
fn entity_types(&self) -> &'static [EntityTypeDef] {
&[]
}
fn requires(&self) -> &'static [&'static str] {
&[]
}
fn note_kind_specs(&self) -> &'static [NoteKindSpec] {
&[]
}
fn kind_hook(&self, _kind: &str) -> Option<Arc<dyn KindHook>> {
None
}
fn accept_channel_ingest_capability(&self, _capability: ChannelIngestCapability) {}
fn schema_plan(&self) -> SchemaPlan {
SchemaPlan::empty()
}
fn validation_rules(&self) -> &'static [ValidationRule] {
&[]
}
fn register_embedders(&self, _runtime: &KhiveRuntime) {}
fn register_entity_type_validator(&self, _runtime: &KhiveRuntime) {}
fn register_entity_type_validator_with_types(
&self,
runtime: &KhiveRuntime,
_pack_entity_types: &[EntityTypeDef],
) {
self.register_entity_type_validator(runtime);
}
fn register_note_mutation_hook(&self, _runtime: &KhiveRuntime) {}
fn register_note_write_validator(&self, _runtime: &KhiveRuntime) {}
async fn warm(&self) {}
fn registered_embedding_model_names(&self) -> Vec<String> {
Vec::new()
}
async fn dispatch(
&self,
verb: &str,
params: Value,
registry: &VerbRegistry,
token: &NamespaceToken,
) -> Result<Value, RuntimeError>;
}
#[async_trait]
pub trait KindHook: Send + Sync + std::fmt::Debug {
async fn prepare_create(
&self,
runtime: &KhiveRuntime,
args: &mut Value,
) -> Result<(), RuntimeError>;
async fn after_create(
&self,
runtime: &KhiveRuntime,
id: uuid::Uuid,
args: &Value,
) -> Result<(), RuntimeError>;
async fn prepare_note_update(
&self,
runtime: &KhiveRuntime,
token: &NamespaceToken,
note: &khive_storage::Note,
args: &mut Value,
) -> Result<(), RuntimeError> {
let properties = args.get("properties").filter(|value| !value.is_null());
self.validate_note_update(runtime, token, note, properties)
.await
}
async fn validate_note_update(
&self,
_runtime: &KhiveRuntime,
_token: &NamespaceToken,
_note: &khive_storage::Note,
_properties: Option<&Value>,
) -> Result<(), RuntimeError> {
Ok(())
}
async fn validate_links(
&self,
_runtime: &KhiveRuntime,
_token: &NamespaceToken,
_links: &[crate::LinkSpec],
) -> Result<(), RuntimeError> {
Ok(())
}
}
#[async_trait]
pub trait PackByIdResolver: Send + Sync {
async fn resolve_by_id(
&self,
id: uuid::Uuid,
) -> Result<Option<crate::Resolved>, crate::RuntimeError>;
async fn resolve_by_id_including_deleted(
&self,
id: uuid::Uuid,
) -> Result<Option<crate::Resolved>, crate::RuntimeError> {
self.resolve_by_id(id).await
}
async fn delete_by_id(
&self,
id: uuid::Uuid,
hard: bool,
) -> Result<serde_json::Value, crate::RuntimeError>;
}
pub struct VerbRegistryBuilder {
packs: Vec<Box<dyn PackRuntime>>,
resolvers: Vec<(String, Box<dyn PackByIdResolver>)>,
gate: GateRef,
default_namespace: String,
visible_namespaces: Vec<Namespace>,
actor_id: Option<String>,
event_store: Option<Arc<dyn EventStore>>,
audit_store_read_only: bool,
dispatch_hook: Option<Arc<dyn DispatchHook>>,
audit_batch_config: Option<crate::audit_batch::AuditBatchConfig>,
}
impl VerbRegistryBuilder {
pub fn new() -> Self {
Self {
packs: Vec::new(),
resolvers: Vec::new(),
gate: std::sync::Arc::new(AllowAllGate),
default_namespace: Namespace::local().as_str().to_string(),
visible_namespaces: vec![],
actor_id: None,
event_store: None,
audit_store_read_only: false,
dispatch_hook: None,
audit_batch_config: None,
}
}
pub fn with_visible_namespaces(&mut self, ns: Vec<Namespace>) -> &mut Self {
self.visible_namespaces = ns;
self
}
pub fn with_actor_id(&mut self, actor_id: Option<String>) -> &mut Self {
self.actor_id = actor_id;
self
}
pub fn register<P: khive_types::Pack + PackRuntime + 'static>(&mut self, pack: P) -> &mut Self {
self.packs.push(Box::new(pack));
self
}
pub(crate) fn register_boxed(&mut self, pack: Box<dyn PackRuntime>) -> &mut Self {
self.packs.push(pack);
self
}
pub fn register_resolver(
&mut self,
name: impl Into<String>,
resolver: Box<dyn PackByIdResolver>,
) -> &mut Self {
self.resolvers.push((name.into(), resolver));
self
}
pub fn with_gate(&mut self, gate: GateRef) -> &mut Self {
self.gate = gate;
self
}
pub fn with_default_namespace(&mut self, ns: impl Into<String>) -> &mut Self {
self.default_namespace = ns.into();
self
}
pub fn with_event_store(&mut self, store: Arc<dyn EventStore>) -> &mut Self {
self.event_store = Some(store);
self.audit_store_read_only = false;
self
}
pub fn with_audit_batch_config(
&mut self,
config: crate::audit_batch::AuditBatchConfig,
) -> &mut Self {
self.audit_batch_config = Some(config);
self
}
pub fn with_read_only_audit_store(&mut self) -> &mut Self {
self.event_store = None;
self.audit_store_read_only = true;
self
}
pub fn with_dispatch_hook(&mut self, hook: Arc<dyn DispatchHook>) -> &mut Self {
self.dispatch_hook = Some(hook);
self
}
pub fn build(self) -> Result<VerbRegistry, RuntimeError> {
let packs = self.packs;
let mut name_to_idx: HashMap<&str, usize> = HashMap::with_capacity(packs.len());
for (idx, pack) in packs.iter().enumerate() {
if let Some(prev_idx) = name_to_idx.insert(pack.name(), idx) {
return Err(RuntimeError::PackRedeclared {
name: pack.name().to_string(),
first_idx: prev_idx,
second_idx: idx,
});
}
}
for pack in &packs {
for handler in pack.handlers() {
for parameter in handler.params {
if RESERVED_ENVELOPE_ARGS.contains(¶meter.name) {
return Err(RuntimeError::ReservedEnvelopeParam {
pack: pack.name().to_string(),
verb: handler.name.to_string(),
param: parameter.name.to_string(),
});
}
}
}
}
let mut missing: Vec<MissingPackDependency> = Vec::new();
let mut indegree = vec![0usize; packs.len()];
let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); packs.len()];
for (idx, pack) in packs.iter().enumerate() {
for &requires in pack.requires() {
match name_to_idx.get(requires).copied() {
Some(dep_idx) => {
dependents[dep_idx].push(idx);
indegree[idx] += 1;
}
None => missing.push(MissingPackDependency {
from: pack.name().to_string(),
requires: requires.to_string(),
}),
}
}
}
if !missing.is_empty() {
return if missing.len() == 1 {
Err(RuntimeError::MissingPackDependency(missing.remove(0)))
} else {
Err(RuntimeError::MissingPackDependencies(
MissingPackDependencies { missing },
))
};
}
let mut ready: VecDeque<usize> = indegree
.iter()
.enumerate()
.filter_map(|(idx, degree)| (*degree == 0).then_some(idx))
.collect();
let mut ordered_indices = Vec::with_capacity(packs.len());
while let Some(idx) = ready.pop_front() {
ordered_indices.push(idx);
for &dep_idx in &dependents[idx] {
indegree[dep_idx] -= 1;
if indegree[dep_idx] == 0 {
ready.push_back(dep_idx);
}
}
}
if ordered_indices.len() != packs.len() {
let cycle_nodes: HashSet<usize> = indegree
.iter()
.enumerate()
.filter_map(|(idx, degree)| (*degree > 0).then_some(idx))
.collect();
let cycle = find_pack_dependency_cycle(&packs, &name_to_idx, &cycle_nodes);
return Err(RuntimeError::CircularPackDependency(
CircularPackDependency { cycle },
));
}
let mut slots: Vec<Option<Box<dyn PackRuntime>>> = packs.into_iter().map(Some).collect();
let ordered_packs: Vec<Box<dyn PackRuntime>> = ordered_indices
.into_iter()
.map(|idx| slots[idx].take().expect("topological index must exist"))
.collect();
validate_unique_note_kinds(&ordered_packs)?;
validate_unique_verb_names(&ordered_packs)?;
validate_unique_entity_types(&ordered_packs)?;
validate_brain_consumer_kinds(&ordered_packs)?;
let available_verbs: Vec<&'static str> = ordered_packs
.iter()
.flat_map(|p| p.handlers().iter())
.filter(|h| matches!(h.visibility, Visibility::Verb))
.map(|h| h.name)
.collect();
if let Some(store) = &self.event_store {
if !store.supports_idempotent_audit_batch() {
return Err(RuntimeError::IncompatibleEventStore(
"the configured EventStore does not implement ADR-133's \
preflight_event/append_events_idempotent pair \
(supports_idempotent_audit_batch() returned false); every \
audited dispatch would silently lose its audit row while \
still reporting success. Implement both methods and \
override supports_idempotent_audit_batch() to opt in, or \
do not call with_event_store() for this backend."
.to_string(),
));
}
}
let audit_batch = self.event_store.clone().map(|store| {
crate::audit_batch::AuditBatch::new(
store,
self.audit_batch_config.clone().unwrap_or_default(),
)
});
Ok(VerbRegistry {
packs: Arc::new(ordered_packs),
resolvers: Arc::new(self.resolvers),
gate: self.gate,
default_namespace: self.default_namespace,
visible_namespaces: self.visible_namespaces,
actor_id: self.actor_id,
event_store: self.event_store,
audit_store_read_only: self.audit_store_read_only,
dispatch_hook: self.dispatch_hook,
available_verbs: Arc::new(available_verbs),
reference_ring: Arc::new(crate::reference_ring::ReferenceRing::new()),
audit_batch,
})
}
}
fn validate_unique_note_kinds(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
let mut seen: HashMap<&str, &str> = HashMap::new();
for pack in packs {
for &kind in pack.note_kinds() {
if let Some(first_pack) = seen.insert(kind, pack.name()) {
return Err(RuntimeError::InvalidInput(format!(
"duplicate note kind {kind:?}: claimed by both {first_pack:?} and {:?}",
pack.name()
)));
}
}
}
Ok(())
}
fn validate_brain_consumer_kinds(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
for pack in packs {
for &kind in pack.brain_consumer_kinds() {
if kind == "*" || kind.trim().is_empty() || kind.trim() != kind {
return Err(RuntimeError::InvalidInput(format!(
"pack {:?} declares invalid brain consumer kind {kind:?}; declarations must be non-empty exact wire values and must not use the registry-owned \"*\" wildcard",
pack.name()
)));
}
}
}
Ok(())
}
fn validate_unique_verb_names(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
let mut seen: HashMap<&str, &str> = HashMap::new();
for pack in packs {
for handler in pack.handlers() {
if !matches!(handler.visibility, Visibility::Verb) {
continue;
}
if let Some(first_pack) = seen.insert(handler.name, pack.name()) {
return Err(RuntimeError::VerbCollision {
verb: handler.name.to_string(),
first_pack: first_pack.to_string(),
second_pack: pack.name().to_string(),
});
}
}
}
Ok(())
}
fn validate_unique_entity_types(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
let owned_defs = packs
.iter()
.flat_map(|p| p.entity_types().iter().map(move |def| (p.name(), def)));
khive_types::EntityTypeRegistry::check_extra_collisions(owned_defs)
.map_err(RuntimeError::InvalidInput)
}
fn find_pack_dependency_cycle(
packs: &[Box<dyn PackRuntime>],
name_to_idx: &HashMap<&str, usize>,
cycle_nodes: &HashSet<usize>,
) -> Vec<String> {
fn visit(
idx: usize,
packs: &[Box<dyn PackRuntime>],
name_to_idx: &HashMap<&str, usize>,
cycle_nodes: &HashSet<usize>,
visiting: &mut Vec<usize>,
visited: &mut HashSet<usize>,
) -> Option<Vec<String>> {
if let Some(pos) = visiting.iter().position(|&seen| seen == idx) {
let mut cycle: Vec<String> = visiting[pos..]
.iter()
.map(|&i| packs[i].name().to_string())
.collect();
cycle.push(packs[idx].name().to_string());
return Some(cycle);
}
if !visited.insert(idx) {
return None;
}
visiting.push(idx);
for &req in packs[idx].requires() {
let Some(&dep_idx) = name_to_idx.get(req) else {
continue;
};
if cycle_nodes.contains(&dep_idx) {
if let Some(cycle) =
visit(dep_idx, packs, name_to_idx, cycle_nodes, visiting, visited)
{
return Some(cycle);
}
}
}
visiting.pop();
None
}
let mut visited = HashSet::new();
for &idx in cycle_nodes {
let mut visiting = Vec::new();
if let Some(cycle) = visit(
idx,
packs,
name_to_idx,
cycle_nodes,
&mut visiting,
&mut visited,
) {
return cycle;
}
}
cycle_nodes
.iter()
.map(|&idx| packs[idx].name().to_string())
.collect()
}
impl Default for VerbRegistryBuilder {
fn default() -> Self {
Self::new()
}
}
#[derive(Clone)]
pub struct VerbRegistry {
packs: std::sync::Arc<Vec<Box<dyn PackRuntime>>>,
resolvers: std::sync::Arc<Vec<(String, Box<dyn PackByIdResolver>)>>,
gate: GateRef,
default_namespace: String,
visible_namespaces: Vec<Namespace>,
actor_id: Option<String>,
event_store: Option<Arc<dyn EventStore>>,
audit_store_read_only: bool,
dispatch_hook: Option<Arc<dyn DispatchHook>>,
available_verbs: Arc<Vec<&'static str>>,
reference_ring: Arc<crate::reference_ring::ReferenceRing>,
audit_batch: Option<Arc<crate::audit_batch::AuditBatch>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct InterceptedDispatchResult<M> {
pub result: Value,
pub metadata: M,
}
impl<M> InterceptedDispatchResult<M> {
pub fn new(result: Value, metadata: M) -> Self {
Self { result, metadata }
}
}
#[derive(Debug, Clone, Default)]
pub struct RequestIdentity {
pub namespace: String,
pub actor_id: Option<String>,
pub visible_namespaces: Vec<String>,
pub process_ref: Option<String>,
pub request_id: Option<u64>,
}
impl RequestIdentity {
pub fn from_token(token: &NamespaceToken) -> Self {
Self {
namespace: token.namespace().as_str().to_string(),
actor_id: token.actor().binding_id().map(str::to_string),
visible_namespaces: token
.visible_namespaces()
.iter()
.map(|namespace| namespace.as_str().to_string())
.collect(),
process_ref: token.process_ref().map(str::to_owned),
request_id: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerifiedActor(String);
impl VerifiedActor {
pub fn new(id: impl Into<String>) -> Result<Self, RuntimeError> {
let id = id.into();
if id.trim().is_empty() {
return Err(RuntimeError::InvalidInput(
"VerifiedActor: identifier must not be empty or whitespace-only".to_string(),
));
}
Ok(Self(id))
}
pub fn as_str(&self) -> &str {
&self.0
}
fn into_inner(self) -> String {
self.0
}
}
#[derive(Debug)]
pub struct PackSchemaCollisionError {
pub pack_a: &'static str,
pub pack_b: &'static str,
pub table: String,
}
impl std::fmt::Display for PackSchemaCollisionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.pack_a == self.pack_b {
write!(
f,
"pack schema boot failure for pack {:?}: {}",
self.pack_a, self.table
)
} else {
write!(
f,
"pack schema collision: packs {:?} and {:?} both declare table {:?} \
on the same backend — move one pack to a separate backend or rename the table",
self.pack_a, self.pack_b, self.table
)
}
}
}
impl std::error::Error for PackSchemaCollisionError {}
fn extract_table_names(stmt: &str) -> Vec<String> {
let normalized = stmt.split_whitespace().collect::<Vec<_>>().join(" ");
let upper = normalized.to_ascii_uppercase();
let table_name = if let Some(rest) = upper.strip_prefix("CREATE VIRTUAL TABLE IF NOT EXISTS ") {
rest.split_whitespace().next()
} else if let Some(rest) = upper.strip_prefix("CREATE VIRTUAL TABLE ") {
rest.split_whitespace().next()
} else if let Some(rest) = upper.strip_prefix("CREATE TABLE IF NOT EXISTS ") {
rest.split_whitespace().next()
} else if let Some(rest) = upper.strip_prefix("CREATE TABLE ") {
rest.split_whitespace().next()
} else {
None
};
match table_name {
Some(name) => {
let clean = name.trim_matches(|c: char| c == '(' || c == ';');
if clean.is_empty() {
vec![]
} else {
vec![clean.to_ascii_lowercase()]
}
}
None => vec![],
}
}
fn endpoint_kind_label(kind: &EndpointKind) -> String {
match kind {
EndpointKind::EntityOfKind(k) => format!("entity:{k}"),
EndpointKind::NoteOfKind(k) => format!("note:{k}"),
EndpointKind::EntityOfType { kind, entity_type } => {
format!("entity:{kind}({entity_type})")
}
}
}
pub(crate) const SPECIAL_RELATIONS: &[khive_types::EdgeRelation] = &[
khive_types::EdgeRelation::Supersedes,
khive_types::EdgeRelation::Supports,
khive_types::EdgeRelation::Refutes,
];
pub(crate) fn is_special_relation(relation: khive_types::EdgeRelation) -> bool {
SPECIAL_RELATIONS.contains(&relation)
}
fn edge_endpoint_table(packs: &[Box<dyn PackRuntime>]) -> Vec<Value> {
let mut rows: Vec<Value> = crate::operations::base_entity_endpoint_rules()
.iter()
.map(|(src, rel, tgt)| {
serde_json::json!({
"relation": rel.as_str(),
"source": format!("entity:{src}"),
"target": format!("entity:{tgt}"),
})
})
.collect();
for rel in SPECIAL_RELATIONS {
rows.push(serde_json::json!({
"relation": rel.as_str(),
"source": "note:*",
"target": "note:*",
}));
}
for pack in packs.iter() {
for rule in pack.edge_rules().iter() {
if is_special_relation(rule.relation) {
continue;
}
rows.push(serde_json::json!({
"relation": rule.relation.as_str(),
"source": endpoint_kind_label(&rule.source),
"target": endpoint_kind_label(&rule.target),
}));
}
}
rows.push(serde_json::json!({
"relation": "annotates",
"source": "note:*",
"target": "any (entity, note, edge, or event)",
}));
rows
}
impl VerbRegistry {
pub fn default_namespace(&self) -> &str {
&self.default_namespace
}
pub fn actor_id(&self) -> Option<&str> {
self.actor_id.as_deref()
}
pub fn visible_namespaces(&self) -> &[Namespace] {
&self.visible_namespaces
}
pub fn event_store(&self) -> Option<Arc<dyn EventStore>> {
self.event_store.clone()
}
pub fn audit_batch_metrics(&self) -> Option<khive_db::diagnostics::RuntimeAuditBatchMetrics> {
self.audit_batch.as_ref().map(|batch| {
let m = batch.health_metrics();
khive_db::diagnostics::RuntimeAuditBatchMetrics {
flush_failures: m.flush_failures,
degraded_rows: m.degraded_rows,
degraded: m.degraded,
admission_refused_obligations: audit_admission_refused_obligation_count(),
admission_unresolved_obligations: audit_admission_unresolved_obligation_count(),
}
})
}
pub fn audit_batch_handle(&self) -> Option<Arc<crate::audit_batch::AuditBatch>> {
self.audit_batch.clone()
}
pub async fn shutdown_audit_batch(
&self,
) -> Result<(), crate::audit_batch::AuditTerminalReason> {
use crate::audit_batch::AuditBatchControl;
match &self.audit_batch {
Some(audit_batch) => audit_batch.close_and_drain().await,
None => Ok(()),
}
}
pub fn audit_persistence_advisory(&self) -> Option<Value> {
self.audit_store_read_only.then(|| {
serde_json::json!({
"code": AUDIT_PERSISTENCE_SKIPPED_READ_ONLY,
"severity": "warning",
"component": "audit_event_store",
"reason": "read_only_backend",
"message": "operation completed, but its dispatch audit event was not persisted because the audit backend is read-only",
})
})
}
const ADMISSION_DEGRADE_SAFE_VERBS: &'static [&'static str] = &[
"get",
"list",
"stats",
"search",
"neighbors",
"traverse",
"context",
"query",
"resolve",
"whoami",
"verbs",
];
fn admission_degrade_safe(&self, verb: &str) -> bool {
if !Self::ADMISSION_DEGRADE_SAFE_VERBS.contains(&verb) {
return false;
}
self.packs
.iter()
.find_map(|pack| pack.handlers().iter().find(|h| h.name == verb))
.is_some_and(|handler| handler.category == VerbCategory::Assertive)
}
pub fn describe_verb(&self, verb: &str) -> Result<Value, RuntimeError> {
for pack in self.packs.iter() {
for handler in pack.handlers().iter() {
if handler.name == verb {
let category = format!("{:?}", handler.category);
let params_arr: Vec<Value> = handler
.params
.iter()
.map(|p| {
serde_json::json!({
"name": p.name,
"type": p.param_type,
"required": p.required,
"description": p.description,
})
})
.collect();
if matches!(handler.visibility, Visibility::Subhandler) {
return Ok(serde_json::json!({
"verb": verb,
"pack": pack.name(),
"description": handler.description,
"category": category,
"params": params_arr,
"identifier_resolution": identifier_resolution_help(),
"visibility": "internal",
"callable_via_mcp": false,
"note": "This is an internal subhandler. Calling it via the MCP \
request surface returns permission denied. It can only be \
invoked by internal runtime callers.",
}));
}
let mut envelope = serde_json::json!({
"verb": verb,
"pack": pack.name(),
"description": handler.description,
"category": category,
"params": params_arr,
"identifier_resolution": identifier_resolution_help(),
});
if verb == "link" {
envelope["endpoint_rules"] = Value::Array(edge_endpoint_table(&self.packs));
}
return Ok(envelope);
}
}
}
Err(RuntimeError::UnknownVerb(format!(
"unknown verb {verb:?}; available: {}",
self.available_verbs.join(", ")
)))
}
pub fn authorize_namespace(&self, ns: Namespace) -> Result<(), RuntimeError> {
let actor = crate::actor_identity::resolve_actor(self.actor_id.as_deref());
let req = GateRequest::new(actor, ns, "authorize", serde_json::Value::Null);
match self.gate.check(&req) {
Ok(decision) if decision.is_allow() => Ok(()),
Ok(GateDecision::Deny { reason }) => Err(RuntimeError::PermissionDenied {
verb: "authorize".to_string(),
reason,
}),
Ok(_) => Err(RuntimeError::PermissionDenied {
verb: "authorize".to_string(),
reason: "gate denied".to_string(),
}),
Err(e) => {
tracing::warn!(
error = %crate::secret_gate::bounded_masked_log_text(&e.to_string()),
"authorize_namespace: gate check failed (fail-closed)"
);
Err(RuntimeError::Internal(format!(
"gate error: {}",
e.wire_reason()
)))
}
}
}
pub async fn dispatch_intercepted_with_identity<F, Fut>(
&self,
verb: &str,
params: &Value,
identity: Option<&RequestIdentity>,
dispatch: F,
) -> Result<Value, RuntimeError>
where
F: FnOnce(Namespace) -> Fut,
Fut: std::future::Future<Output = Result<Value, RuntimeError>>,
{
self.dispatch_intercepted_with_metadata_with_identity(
verb,
params,
identity,
|namespace| async move {
dispatch(namespace)
.await
.map(|result| InterceptedDispatchResult::new(result, ()))
},
)
.await
.map(|outcome| outcome.result)
}
pub async fn dispatch_intercepted_with_metadata_with_identity<M, F, Fut>(
&self,
verb: &str,
params: &Value,
identity: Option<&RequestIdentity>,
dispatch: F,
) -> Result<InterceptedDispatchResult<M>, RuntimeError>
where
F: FnOnce(Namespace) -> Fut,
Fut: std::future::Future<Output = Result<InterceptedDispatchResult<M>, RuntimeError>>,
{
let request_id = identity.and_then(|id| id.request_id);
let gate_req = self.gate_request_with_identity(verb, params, identity)?;
let mut deferred_audit = match self.gate.check(&gate_req) {
Ok(decision) => {
let audit = AuditEvent::from_check(&gate_req, &decision, self.gate.impl_name());
tracing::info!(
audit_event = %serde_json::to_string(&audit)
.unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
"gate.check"
);
if let GateDecision::Deny { reason } = decision {
if let Some(store) = &self.event_store {
let event = build_audit_storage_event(
&gate_req,
&audit,
EventOutcome::Denied,
Some(crate::cost_unit::base_resource_payload(request_id)),
);
let _ = append_audit_event_best_effort(
self.audit_batch.as_ref(),
store,
event,
verb,
crate::audit_batch::AuditProducer::GateDenied,
false,
)
.await;
}
return Err(RuntimeError::PermissionDenied {
verb: verb.to_string(),
reason,
});
}
Some(audit)
}
Err(err) => {
return Err(self
.gate_unavailable_error(&gate_req, &err, request_id)
.await);
}
};
let started = Instant::now();
let mut result = dispatch(gate_req.namespace.clone()).await;
let duration_us = started.elapsed().as_micros() as i64;
let receipt_outcome = if verb == "git.digest" && result.is_ok() {
let resource = result.as_ref().ok().map(|outcome| {
crate::cost_unit::resource_payload(
verb,
&gate_req.args,
&outcome.result,
|| 0,
request_id,
)
});
let mut receipt_result: Result<Value, RuntimeError> = match result.as_mut() {
Ok(outcome) => Ok(std::mem::take(&mut outcome.result)),
Err(_) => unreachable!("git.digest receipt path is guarded by result.is_ok()"),
};
let outcome = persist_git_digest_receipt(
self.event_store.as_ref(),
self.audit_batch.as_ref(),
&gate_req,
deferred_audit.as_ref(),
&mut receipt_result,
duration_us,
resource,
)
.await;
match receipt_result {
Ok(receipted_result) => {
if let Ok(intercepted) = &mut result {
intercepted.result = receipted_result;
}
}
Err(error) => result = Err(error),
}
Some(outcome)
} else {
None
};
if receipt_outcome.is_none()
|| receipt_outcome == Some(GitDigestReceiptOutcome::BuildRejected)
{
if let Some(audit) = deferred_audit.take() {
let audit_outcome = self
.persist_intercepted_audit(
verb,
&gate_req,
audit,
result.as_ref().map(|outcome| &outcome.result),
duration_us,
request_id,
)
.await;
result = fold_audit_obligation(result, audit_outcome);
}
}
result
}
async fn persist_intercepted_audit(
&self,
verb: &str,
gate_req: &GateRequest,
audit: AuditEvent,
result: Result<&Value, &RuntimeError>,
duration_us: i64,
request_id: Option<u64>,
) -> Result<(), RuntimeError> {
let Some(store) = &self.event_store else {
return Ok(());
};
let event = match result {
Ok(value) if verb == "link" && gate_req.args.get("links").is_none() => {
let resource = crate::cost_unit::resource_payload(
verb,
&gate_req.args,
value,
|| 0,
request_id,
);
match link_audit_success_from_result(audit.clone(), value) {
Some((edge_id, mut payload)) => {
if let Value::Object(ref mut map) = payload {
map.insert("resource".to_string(), resource);
}
Event::new(
gate_req.namespace.as_str(),
gate_req.verb.as_str(),
EventKind::Audit,
SubstrateKind::Event,
format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
)
.with_outcome(EventOutcome::Success)
.with_target(edge_id)
.with_payload(payload)
.with_payload_schema_version(2)
.with_duration_us(duration_us)
}
None => build_audit_storage_event(
gate_req,
&audit,
EventOutcome::Success,
Some(resource),
)
.with_duration_us(duration_us),
}
}
Ok(value) => build_audit_storage_event(
gate_req,
&audit,
EventOutcome::Success,
Some(crate::cost_unit::resource_payload(
verb,
&gate_req.args,
value,
|| 0,
request_id,
)),
)
.with_duration_us(duration_us),
Err(_) => build_audit_storage_event(
gate_req,
&audit,
EventOutcome::Error,
Some(crate::cost_unit::base_resource_payload(request_id)),
)
.with_duration_us(duration_us),
};
let producer = if result.is_ok() {
crate::audit_batch::AuditProducer::DispatchSucceeded
} else {
crate::audit_batch::AuditProducer::DispatchFailed
};
append_audit_event_best_effort(
self.audit_batch.as_ref(),
store,
event,
verb,
producer,
self.admission_degrade_safe(verb),
)
.await
}
fn gate_request_with_identity(
&self,
verb: &str,
params: &Value,
identity: Option<&RequestIdentity>,
) -> Result<GateRequest, RuntimeError> {
let default_namespace = identity
.map(|id| id.namespace.as_str())
.unwrap_or(self.default_namespace.as_str());
let namespace = resolve_explicit_namespace(params, default_namespace)?;
let actor_id = identity
.map(|id| id.actor_id.as_deref())
.unwrap_or(self.actor_id.as_deref());
let actor = crate::actor_identity::resolve_actor(actor_id);
Ok(GateRequest::new(actor, namespace, verb, params.clone()))
}
async fn gate_unavailable_error(
&self,
gate_req: &GateRequest,
error: &khive_gate::GateError,
request_id: Option<u64>,
) -> RuntimeError {
let audit = AuditEvent::gate_unavailable(gate_req, self.gate.impl_name());
tracing::info!(
audit_event = %serde_json::to_string(&audit)
.unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
"gate.check"
);
tracing::warn!(
verb = %gate_req.verb,
error = %crate::secret_gate::bounded_masked_log_text(&error.to_string()),
"gate check failed (fail-closed)"
);
if let Some(store) = &self.event_store {
let event = build_audit_storage_event(
gate_req,
&audit,
EventOutcome::Error,
Some(crate::cost_unit::base_resource_payload(request_id)),
);
let _ = append_audit_event_best_effort(
self.audit_batch.as_ref(),
store,
event,
gate_req.verb.as_str(),
crate::audit_batch::AuditProducer::GateUnavailable,
false,
)
.await;
}
RuntimeError::GateUnavailable {
verb: gate_req.verb.clone(),
reason: error.wire_reason().to_string(),
}
}
pub async fn dispatch(&self, verb: &str, params: Value) -> Result<Value, RuntimeError> {
self.dispatch_with_identity(verb, params, None).await
}
pub async fn dispatch_with_identity(
&self,
verb: &str,
params: Value,
identity: Option<RequestIdentity>,
) -> Result<Value, RuntimeError> {
if params.get("help").and_then(Value::as_bool) == Some(true) {
return self.describe_verb(verb);
}
let explicit_namespace = params.get("namespace").is_some_and(Value::is_string);
let request_id: Option<u64> = identity.as_ref().and_then(|id| id.request_id);
let gate_req = self.gate_request_with_identity(verb, ¶ms, identity.as_ref())?;
let ns = gate_req.namespace.clone();
let resolved_actor = gate_req.actor.clone();
let (gate_blocked, mut deferred_audit) = match self.gate.check(&gate_req) {
Ok(decision) => {
let is_deny = matches!(decision, GateDecision::Deny { .. });
let audit = AuditEvent::from_check(&gate_req, &decision, self.gate.impl_name());
tracing::info!(
audit_event = %serde_json::to_string(&audit)
.unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
"gate.check"
);
if let Some(store) = &self.event_store {
if crate::config_ledger::PENDING
.swap(false, std::sync::atomic::Ordering::AcqRel)
{
for (key, value) in crate::config_ledger::drain_config_locked() {
let payload = serde_json::json!({ "key": key, "value": value });
let storage_event = Event::new(
gate_req.namespace.as_str(),
"config.lock",
EventKind::ConfigLocked,
SubstrateKind::Event,
format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
)
.with_payload(payload);
let _ = append_audit_event_best_effort(
self.audit_batch.as_ref(),
store,
storage_event,
"config.lock",
crate::audit_batch::AuditProducer::ConfigLocked,
false,
)
.await;
}
}
}
let defer_audit = !is_deny;
if !defer_audit {
if let Some(store) = &self.event_store {
let storage_event = build_audit_storage_event(
&gate_req,
&audit,
EventOutcome::Denied,
Some(crate::cost_unit::base_resource_payload(request_id)),
);
let _ = append_audit_event_best_effort(
self.audit_batch.as_ref(),
store,
storage_event,
verb,
crate::audit_batch::AuditProducer::GateDenied,
false,
)
.await;
}
}
let reason = if is_deny {
let reason = match decision {
GateDecision::Deny { reason } => reason,
_ => String::new(),
};
Some(reason)
} else {
None
};
let deferred = if defer_audit { Some(audit) } else { None };
(reason, deferred)
}
Err(err) => {
return Err(self
.gate_unavailable_error(&gate_req, &err, request_id)
.await);
}
};
if let Some(reason) = gate_blocked {
return Err(RuntimeError::PermissionDenied {
verb: verb.to_string(),
reason,
});
}
let token = if explicit_namespace {
NamespaceToken::mint_with_visibility(ns.clone(), vec![], resolved_actor)
} else {
let primary = Namespace::local();
let mut extra_visible: Vec<Namespace> = match identity.as_ref() {
Some(id) => id
.visible_namespaces
.iter()
.filter_map(|s| match Namespace::parse(s) {
Ok(parsed) => Some(parsed),
Err(e) => {
tracing::warn!(
namespace = %s,
error = %e,
"dispatch_with_identity: skipping invalid visible_namespace \
entry from per-request identity"
);
None
}
})
.collect(),
None => self.visible_namespaces.clone(),
};
extra_visible.push(Namespace::local()); NamespaceToken::mint_with_visibility(primary, extra_visible, resolved_actor)
}
.with_process_ref(match identity.as_ref() {
Some(id) => id.process_ref.clone(),
None => crate::config::process_ref_from_env(),
});
for pack in self.packs.iter() {
if let Some(handler_def) = pack.handlers().iter().find(|v| v.name == verb) {
let handler_accepts_namespace =
handler_def.params.iter().any(|p| p.name == "namespace");
let params = if !handler_accepts_namespace {
if let Value::Object(mut map) = params {
map.remove("namespace");
Value::Object(map)
} else {
params
}
} else {
params
};
let dispatch_start = Instant::now();
let mut result = pack.dispatch(verb, params, self, &token).await;
let dispatch_us = dispatch_start.elapsed().as_micros() as i64;
let git_digest_receipt_outcome = if verb == "git.digest" && result.is_ok() {
let resource = result.as_ref().ok().map(|value| {
crate::cost_unit::resource_payload(
verb,
&gate_req.args,
value,
|| pack.registered_embedding_model_names().len() as i64,
request_id,
)
});
Some(
persist_git_digest_receipt(
self.event_store.as_ref(),
self.audit_batch.as_ref(),
&gate_req,
deferred_audit.as_ref(),
&mut result,
dispatch_us,
resource,
)
.await,
)
} else {
None
};
let needs_generic_audit = git_digest_receipt_outcome.is_none()
|| git_digest_receipt_outcome == Some(GitDigestReceiptOutcome::BuildRejected);
if let (true, Some(audit)) = (needs_generic_audit, deferred_audit.take()) {
if let Some(store) = &self.event_store {
let is_link_singleton =
verb == "link" && gate_req.args.get("links").is_none();
let audit_outcome: Result<(), RuntimeError> = match &result {
Ok(ok_val) if is_link_singleton => {
let resource = crate::cost_unit::resource_payload(
verb,
&gate_req.args,
ok_val,
|| pack.registered_embedding_model_names().len() as i64,
request_id,
);
match link_audit_success_from_result(audit.clone(), ok_val) {
Some((edge_id, mut payload)) => {
if let Value::Object(ref mut map) = payload {
map.insert("resource".to_string(), resource);
}
let storage_event = Event::new(
gate_req.namespace.as_str(),
gate_req.verb.as_str(),
EventKind::Audit,
SubstrateKind::Event,
format!(
"{}:{}",
gate_req.actor.kind, gate_req.actor.id
),
)
.with_outcome(EventOutcome::Success)
.with_target(edge_id)
.with_payload(payload)
.with_payload_schema_version(2)
.with_duration_us(dispatch_us);
append_audit_event_best_effort(
self.audit_batch.as_ref(),
store,
storage_event,
verb,
crate::audit_batch::AuditProducer::DispatchSucceeded,
self.admission_degrade_safe(verb),
)
.await
}
None => {
tracing::warn!(
verb,
"link audit v2 enrichment parse failed; \
falling back to v1 audit shape"
);
let storage_event = build_audit_storage_event(
&gate_req,
&audit,
EventOutcome::Success,
Some(resource),
)
.with_duration_us(dispatch_us);
append_audit_event_best_effort(
self.audit_batch.as_ref(),
store,
storage_event,
verb,
crate::audit_batch::AuditProducer::DispatchSucceeded,
self.admission_degrade_safe(verb),
)
.await
}
}
}
_ => {
let (outcome, resource) = match &result {
Ok(ok_val) => (
EventOutcome::Success,
Some(crate::cost_unit::resource_payload(
verb,
&gate_req.args,
ok_val,
|| pack.registered_embedding_model_names().len() as i64,
request_id,
)),
),
Err(_) => (
EventOutcome::Error,
Some(crate::cost_unit::base_resource_payload(request_id)),
),
};
let producer = if result.is_ok() {
crate::audit_batch::AuditProducer::DispatchSucceeded
} else {
crate::audit_batch::AuditProducer::DispatchFailed
};
let storage_event =
build_audit_storage_event(&gate_req, &audit, outcome, resource)
.with_duration_us(dispatch_us);
append_audit_event_best_effort(
self.audit_batch.as_ref(),
store,
storage_event,
verb,
producer,
self.admission_degrade_safe(verb),
)
.await
}
};
result = fold_audit_obligation(result, audit_outcome);
}
}
if let (Ok(ref ok_val), Some(hook)) = (&result, &self.dispatch_hook) {
let mut dispatch_event = Event::new(
ns.as_str(),
verb,
EventKind::Audit,
SubstrateKind::Event,
pack.name(),
)
.with_outcome(EventOutcome::Success)
.with_duration_us(dispatch_us);
if verb == "memory.recall" {
let first_result =
ok_val.as_array().and_then(|arr| arr.first()).or_else(|| {
ok_val
.get("results")
.and_then(Value::as_array)
.and_then(|arr| arr.first())
});
let first_note_id = first_result
.and_then(|v| v.get("id"))
.and_then(|v| v.as_str())
.and_then(|s| s.parse::<uuid::Uuid>().ok());
if let Some(note_id) = first_note_id {
dispatch_event = dispatch_event.with_target(note_id);
}
let mut payload = serde_json::Map::new();
if let Some(profile_id) = first_result
.and_then(|v| v.get("served_by_profile_id"))
.and_then(Value::as_str)
{
payload.insert(
"served_by_profile_id".to_string(),
Value::String(profile_id.to_string()),
);
}
if let Some(attribution) = first_result
.and_then(|v| v.get("serve_attribution"))
.and_then(Value::as_str)
{
payload.insert(
"serve_attribution".to_string(),
Value::String(attribution.to_string()),
);
}
dispatch_event = dispatch_event.with_payload(Value::Object(payload));
}
let dispatch_view = EventView {
event: dispatch_event,
observations: Vec::new(),
};
let hook = Arc::clone(hook);
hook.on_dispatch(&dispatch_view).await;
}
if let Ok(ref ok_val) = result {
let admissions = crate::reference_ring::ring_admissions_for(verb, ok_val);
if !admissions.is_empty() {
let actor_key = format!("{}:{}", gate_req.actor.kind, gate_req.actor.id);
for (id, name) in admissions {
self.reference_ring.admit(
token.namespace().as_str(),
&actor_key,
id,
name,
);
}
}
}
return result;
}
}
if let Some(audit) = deferred_audit.take() {
if let Some(store) = &self.event_store {
let storage_event = build_audit_storage_event(
&gate_req,
&audit,
EventOutcome::Error,
Some(crate::cost_unit::base_resource_payload(request_id)),
);
let _ = append_audit_event_best_effort(
self.audit_batch.as_ref(),
store,
storage_event,
verb,
crate::audit_batch::AuditProducer::UnknownVerb,
false,
)
.await;
}
}
Err(RuntimeError::UnknownVerb(format!(
"unknown verb {verb:?}; available: {}",
self.available_verbs.join(", ")
)))
}
pub async fn dispatch_as(
&self,
verb: &str,
params: Value,
verified_actor: VerifiedActor,
) -> Result<Value, RuntimeError> {
let identity = RequestIdentity {
namespace: self.default_namespace.clone(),
actor_id: Some(verified_actor.into_inner()),
visible_namespaces: self
.visible_namespaces
.iter()
.map(|ns| ns.as_str().to_string())
.collect(),
process_ref: crate::config::process_ref_from_env(),
request_id: None,
};
self.dispatch_with_identity(verb, params, Some(identity))
.await
}
pub fn resolvers(&self) -> &[(String, Box<dyn PackByIdResolver>)] {
&self.resolvers
}
pub fn reference_ring(&self) -> &Arc<crate::reference_ring::ReferenceRing> {
&self.reference_ring
}
pub fn find_kind_hook(&self, kind: &str) -> Option<Arc<dyn KindHook>> {
for pack in self.packs.iter() {
let owns = pack.note_kinds().contains(&kind) || pack.entity_kinds().contains(&kind);
if owns {
if let Some(hook) = pack.kind_hook(kind) {
return Some(hook);
}
}
}
None
}
pub async fn prepare_note_update_hook(
&self,
runtime: &KhiveRuntime,
token: &NamespaceToken,
note: &khive_storage::Note,
args: &mut Value,
) -> Result<(), RuntimeError> {
if let Some(hook) = self.find_kind_hook(¬e.kind) {
hook.prepare_note_update(runtime, token, note, args).await?;
}
Ok(())
}
pub async fn validate_note_update_hook(
&self,
runtime: &KhiveRuntime,
token: &NamespaceToken,
note: &khive_storage::Note,
properties: Option<&Value>,
) -> Result<(), RuntimeError> {
if let Some(hook) = self.find_kind_hook(¬e.kind) {
hook.validate_note_update(runtime, token, note, properties)
.await?;
}
Ok(())
}
pub async fn validate_link_hooks(
&self,
runtime: &KhiveRuntime,
token: &NamespaceToken,
specs: &[LinkSpec],
) -> Result<(), RuntimeError> {
let mut specs_by_kind: HashMap<String, Vec<LinkSpec>> = HashMap::new();
for spec in specs {
let Some(Resolved::Note(source)) = runtime.resolve_by_id(token, spec.source_id).await?
else {
continue;
};
specs_by_kind
.entry(source.kind)
.or_default()
.push(spec.clone());
}
for (kind, kind_specs) in specs_by_kind {
if let Some(hook) = self.find_kind_hook(&kind) {
hook.validate_links(runtime, token, &kind_specs).await?;
}
}
Ok(())
}
pub fn has_verb(&self, verb: &str) -> bool {
self.packs
.iter()
.flat_map(|p| p.handlers().iter())
.any(|h| h.name == verb)
}
pub fn all_verbs(&self) -> Vec<&'static HandlerDef> {
self.packs
.iter()
.flat_map(|p| p.handlers().iter())
.filter(|h| matches!(h.visibility, Visibility::Verb))
.collect()
}
pub fn all_verbs_with_names(&self) -> Vec<(&str, &'static HandlerDef)> {
self.packs
.iter()
.flat_map(|p| p.handlers().iter().map(move |v| (p.name(), v)))
.filter(|(_, h)| matches!(h.visibility, Visibility::Verb))
.collect()
}
pub fn all_handlers_with_names(&self) -> Vec<(&str, &'static HandlerDef)> {
self.packs
.iter()
.flat_map(|p| p.handlers().iter().map(move |v| (p.name(), v)))
.collect()
}
pub fn all_note_kinds(&self) -> Vec<&'static str> {
let mut seen = std::collections::HashSet::new();
self.packs
.iter()
.flat_map(|p| p.note_kinds().iter().copied())
.filter(|k| seen.insert(*k))
.collect()
}
pub fn pack_owned_note_kinds(&self) -> Vec<&'static str> {
let generic: std::collections::HashSet<&'static str> = self
.packs
.iter()
.filter(|p| p.name() == GENERIC_CRUD_PACK)
.flat_map(|p| p.note_kinds().iter().copied())
.collect();
let mut seen = std::collections::HashSet::new();
self.packs
.iter()
.filter(|p| p.name() != GENERIC_CRUD_PACK)
.flat_map(|p| p.note_kinds().iter().copied())
.filter(|k| !generic.contains(k) && seen.insert(*k))
.collect()
}
pub fn all_entity_kinds(&self) -> Vec<&'static str> {
let mut seen = std::collections::HashSet::new();
self.packs
.iter()
.flat_map(|p| p.entity_kinds().iter().copied())
.filter(|k| seen.insert(*k))
.collect()
}
pub fn all_brain_consumer_kinds(&self) -> Vec<&'static str> {
let mut seen = std::collections::HashSet::new();
self.packs
.iter()
.flat_map(|p| p.brain_consumer_kinds().iter().copied())
.filter(|kind| seen.insert(*kind))
.collect()
}
pub fn pack_names(&self) -> Vec<&str> {
self.packs.iter().map(|p| p.name()).collect()
}
pub fn pack_requires(&self, name: &str) -> Option<&'static [&'static str]> {
self.packs
.iter()
.find(|p| p.name() == name)
.map(|p| p.requires())
}
pub fn pack_note_kinds(&self, name: &str) -> Option<&'static [&'static str]> {
self.packs
.iter()
.find(|p| p.name() == name)
.map(|p| p.note_kinds())
}
pub fn pack_entity_kinds(&self, name: &str) -> Option<&'static [&'static str]> {
self.packs
.iter()
.find(|p| p.name() == name)
.map(|p| p.entity_kinds())
}
pub fn pack_verbs(&self, name: &str) -> Option<&'static [HandlerDef]> {
self.packs
.iter()
.find(|p| p.name() == name)
.map(|p| p.handlers())
}
pub fn all_edge_rules(&self) -> Vec<EdgeEndpointRule> {
self.packs
.iter()
.flat_map(|p| p.edge_rules().iter().copied())
.collect()
}
pub fn all_entity_types(&self) -> Vec<EntityTypeDef> {
self.packs
.iter()
.flat_map(|p| p.entity_types().iter().cloned())
.collect()
}
pub fn all_note_kind_specs(&self) -> Vec<&'static NoteKindSpec> {
self.packs
.iter()
.flat_map(|p| p.note_kind_specs().iter())
.collect()
}
pub fn all_validation_rules(&self) -> Vec<&'static ValidationRule> {
self.packs
.iter()
.flat_map(|p| p.validation_rules().iter())
.collect()
}
pub fn all_schema_plans(&self) -> Vec<SchemaPlan> {
self.packs.iter().map(|p| p.schema_plan()).collect()
}
pub fn call_register_embedders(&self, runtime: &KhiveRuntime) {
for pack in self.packs.iter() {
pack.register_embedders(runtime);
}
}
pub fn call_register_entity_type_validators(&self, runtime: &KhiveRuntime) {
let entity_types = self.all_entity_types();
for pack in self.packs.iter() {
pack.register_entity_type_validator_with_types(runtime, &entity_types);
}
}
pub fn call_register_note_mutation_hooks(&self, runtime: &KhiveRuntime) {
for pack in self.packs.iter() {
pack.register_note_mutation_hook(runtime);
}
}
pub fn call_register_note_write_validators(&self, runtime: &KhiveRuntime) {
for pack in self.packs.iter() {
pack.register_note_write_validator(runtime);
}
}
pub async fn call_warm_all(&self) {
for pack in self.packs.iter() {
pack.warm().await;
}
}
pub fn presentation_policy_for(&self, verb: &str) -> khive_types::VerbPresentationPolicy {
for pack in self.packs.iter() {
if let Some(handler) = pack.handlers().iter().find(|h| h.name == verb) {
return handler.presentation_policy();
}
}
khive_types::VerbPresentationPolicy::Standard
}
pub fn is_subhandler_verb(&self, verb: &str) -> bool {
for pack in self.packs.iter() {
if let Some(handler) = pack.handlers().iter().find(|h| h.name == verb) {
return matches!(handler.visibility, Visibility::Subhandler);
}
}
false
}
pub fn apply_schema_plans(&self, backend: &khive_db::StorageBackend) {
if backend.is_read_only() {
tracing::info!(
"skipping pack schema plans because the backend is read-only; snapshot schema is used as-is"
);
return;
}
for plan in self.all_schema_plans() {
if plan.is_empty() {
continue;
}
if let Err(e) = backend.apply_pack_ddl_statements(plan.statements) {
tracing::warn!(
pack = plan.pack,
error = %e,
"failed to apply pack schema plan at startup (non-fatal)"
);
}
}
}
pub fn all_schema_plans_named(&self) -> Vec<(&'static str, SchemaPlan)> {
self.packs
.iter()
.map(|p| {
let plan = p.schema_plan();
(plan.pack, plan)
})
.collect()
}
pub fn apply_schema_plans_with_map(
&self,
backend_for_pack: &HashMap<&str, &khive_db::StorageBackend>,
default_backend: &khive_db::StorageBackend,
) -> Result<(), crate::PackSchemaCollisionError> {
let mut claimed: HashMap<(*const (), String), &'static str> = HashMap::new();
for (pack_name, plan) in self.all_schema_plans_named() {
if plan.is_empty() {
continue;
}
let backend = backend_for_pack
.get(pack_name)
.copied()
.unwrap_or(default_backend);
let backend_ptr = std::sync::Arc::as_ptr(&backend.pool_arc()) as *const ();
for stmt in plan.statements {
for table_name in extract_table_names(stmt) {
let key = (backend_ptr, table_name.clone());
match claimed.entry(key) {
std::collections::hash_map::Entry::Vacant(e) => {
e.insert(pack_name);
}
std::collections::hash_map::Entry::Occupied(e) => {
let prior_pack = *e.get();
return Err(crate::PackSchemaCollisionError {
pack_a: prior_pack,
pack_b: pack_name,
table: table_name,
});
}
}
}
}
if backend.is_read_only() {
tracing::info!(
pack = pack_name,
"skipping pack schema plan because its assigned backend is read-only"
);
continue;
}
backend
.apply_pack_ddl_statements(plan.statements)
.map_err(|e| crate::PackSchemaCollisionError {
pack_a: pack_name,
pack_b: pack_name,
table: format!("DDL error: {e}"),
})?;
}
Ok(())
}
}
pub struct PackInstall {
pub runtime: Box<dyn PackRuntime>,
pub resolver: Option<Box<dyn PackByIdResolver>>,
pub dispatch_hook: Option<Arc<dyn DispatchHook>>,
}
pub struct ChannelIngestCapability {
pub(crate) _sealed: (),
}
impl ChannelIngestCapability {
pub fn grant_for_direct_composition() -> Self {
Self { _sealed: () }
}
}
pub(crate) const CHANNEL_INGEST_CAPABLE_PACKS: &[&str] = &["comm"];
pub trait PackFactory: Send + Sync + 'static {
fn name(&self) -> &'static str;
fn requires(&self) -> &'static [&'static str] {
&[]
}
fn create(&self, runtime: KhiveRuntime) -> Box<dyn PackRuntime>;
fn create_install(&self, runtime: KhiveRuntime) -> PackInstall {
let resolver = self.create_resolver(runtime.clone());
PackInstall {
runtime: self.create(runtime),
resolver,
dispatch_hook: None,
}
}
fn create_resolver(&self, _runtime: KhiveRuntime) -> Option<Box<dyn PackByIdResolver>> {
None
}
}
pub struct PackRegistration(pub &'static dyn PackFactory);
inventory::collect!(PackRegistration);
#[derive(Debug)]
pub enum PackLoadError {
UnknownPack(String),
MissingDependency {
pack: String,
dep: String,
},
}
impl std::fmt::Display for PackLoadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PackLoadError::UnknownPack(name) => write!(f, "unknown pack {name:?}"),
PackLoadError::MissingDependency { pack, dep } => write!(
f,
"pack {pack:?} requires {dep:?}, which is not in the requested pack list; \
add --pack {dep} before --pack {pack}"
),
}
}
}
impl std::error::Error for PackLoadError {}
pub struct PackRegistry;
impl PackRegistry {
pub fn discovered_names() -> Vec<&'static str> {
inventory::iter::<PackRegistration>
.into_iter()
.map(|r| r.0.name())
.collect()
}
pub fn register_packs(
names: &[String],
runtime: KhiveRuntime,
builder: &mut VerbRegistryBuilder,
) -> Result<(), PackLoadError> {
let all: Vec<&'static dyn PackFactory> = inventory::iter::<PackRegistration>
.into_iter()
.map(|r| r.0)
.collect();
let factory_for = |name: &str| -> Option<&'static dyn PackFactory> {
all.iter().copied().find(|f| f.name() == name)
};
let requested: std::collections::HashSet<&str> = names.iter().map(String::as_str).collect();
for name in names {
factory_for(name.as_str()).ok_or_else(|| PackLoadError::UnknownPack(name.clone()))?;
}
for name in names {
let factory = factory_for(name.as_str()).unwrap(); for &dep in factory.requires() {
if !requested.contains(dep) {
return Err(PackLoadError::MissingDependency {
pack: name.clone(),
dep: dep.to_string(),
});
}
}
}
for name in names {
let factory = factory_for(name.as_str()).unwrap(); let install = factory.create_install(runtime.clone());
if CHANNEL_INGEST_CAPABLE_PACKS.contains(&name.as_str()) {
install
.runtime
.accept_channel_ingest_capability(ChannelIngestCapability { _sealed: () });
}
builder.register_boxed(install.runtime);
if let Some(resolver) = install.resolver {
builder.register_resolver(name.clone(), resolver);
}
if let Some(hook) = install.dispatch_hook {
builder.with_dispatch_hook(hook);
}
}
Ok(())
}
pub fn register_packs_with_runtimes(
names: &[String],
runtimes: &HashMap<String, KhiveRuntime>,
default_runtime: &KhiveRuntime,
builder: &mut VerbRegistryBuilder,
) -> Result<(), PackLoadError> {
let all: Vec<&'static dyn PackFactory> = inventory::iter::<PackRegistration>
.into_iter()
.map(|r| r.0)
.collect();
let factory_for = |name: &str| -> Option<&'static dyn PackFactory> {
all.iter().copied().find(|f| f.name() == name)
};
let requested: std::collections::HashSet<&str> = names.iter().map(String::as_str).collect();
for name in names {
factory_for(name.as_str()).ok_or_else(|| PackLoadError::UnknownPack(name.clone()))?;
}
for name in names {
let factory = factory_for(name.as_str()).unwrap();
for &dep in factory.requires() {
if !requested.contains(dep) {
return Err(PackLoadError::MissingDependency {
pack: name.clone(),
dep: dep.to_string(),
});
}
}
}
for name in names {
let factory = factory_for(name.as_str()).unwrap();
let runtime = runtimes
.get(name.as_str())
.cloned()
.unwrap_or_else(|| default_runtime.clone());
let install = factory.create_install(runtime);
if CHANNEL_INGEST_CAPABLE_PACKS.contains(&name.as_str()) {
install
.runtime
.accept_channel_ingest_capability(ChannelIngestCapability { _sealed: () });
}
builder.register_boxed(install.runtime);
if let Some(resolver) = install.resolver {
builder.register_resolver(name.clone(), resolver);
}
if let Some(hook) = install.dispatch_hook {
builder.with_dispatch_hook(hook);
}
}
Ok(())
}
}
fn target_id_from_args(args: &serde_json::Value) -> Option<uuid::Uuid> {
args.get("target_id")
.and_then(serde_json::Value::as_str)
.and_then(|s| s.parse::<uuid::Uuid>().ok())
}
fn build_audit_storage_event(
gate_req: &GateRequest,
audit: &AuditEvent,
outcome: EventOutcome,
resource: Option<Value>,
) -> Event {
let mut audit_data = serde_json::to_value(audit).unwrap_or_else(|e| {
tracing::warn!(error = %e, "failed to serialize AuditEvent for EventStore");
serde_json::Value::Null
});
if let Some(resource) = resource {
if let Value::Object(ref mut map) = audit_data {
map.insert("resource".to_string(), resource);
}
}
let mut storage_event = Event::new(
gate_req.namespace.as_str(),
gate_req.verb.as_str(),
EventKind::Audit,
SubstrateKind::Event,
format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
)
.with_outcome(outcome)
.with_payload(audit_data);
if let Some(target_id) = target_id_from_args(&gate_req.args) {
storage_event = storage_event.with_target(target_id);
}
storage_event
}
static AUDIT_APPEND_FAILURES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
pub(crate) fn audit_append_failure_count() -> u64 {
AUDIT_APPEND_FAILURES.load(std::sync::atomic::Ordering::Relaxed)
}
static AUDIT_OBLIGATION_APPEND_FAILURES: std::sync::atomic::AtomicU64 =
std::sync::atomic::AtomicU64::new(0);
#[cfg(test)]
pub(crate) fn audit_obligation_append_failure_count() -> u64 {
AUDIT_OBLIGATION_APPEND_FAILURES.load(std::sync::atomic::Ordering::Relaxed)
}
static AUDIT_ADMISSION_REFUSED_OBLIGATIONS: std::sync::atomic::AtomicU64 =
std::sync::atomic::AtomicU64::new(0);
pub fn audit_admission_refused_obligation_count() -> u64 {
AUDIT_ADMISSION_REFUSED_OBLIGATIONS.load(std::sync::atomic::Ordering::Relaxed)
}
static AUDIT_ADMISSION_UNRESOLVED_OBLIGATIONS: std::sync::atomic::AtomicU64 =
std::sync::atomic::AtomicU64::new(0);
pub fn audit_admission_unresolved_obligation_count() -> u64 {
AUDIT_ADMISSION_UNRESOLVED_OBLIGATIONS.load(std::sync::atomic::Ordering::Relaxed)
}
const GIT_DIGEST_RECEIPT_FAILURE: &str =
"git_digest_receipt_persist_failed: git.digest writes may have committed, but no durable \
success receipt was confirmed; inspect ingest state before retrying";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum GitDigestReceiptOutcome {
Persisted,
BuildRejected,
PersistenceUnavailable,
}
async fn persist_git_digest_receipt(
store: Option<&Arc<dyn EventStore>>,
audit_batch: Option<&Arc<crate::audit_batch::AuditBatch>>,
gate_req: &GateRequest,
audit: Option<&AuditEvent>,
result: &mut Result<Value, RuntimeError>,
duration_us: i64,
resource: Option<Value>,
) -> GitDigestReceiptOutcome {
let Ok(report) = result else {
return GitDigestReceiptOutcome::PersistenceUnavailable;
};
let Some(store) = store else {
tracing::error!(
verb = "git.digest",
"durable receipt store is not configured"
);
*result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
return GitDigestReceiptOutcome::PersistenceUnavailable;
};
let Some(audit) = audit else {
tracing::error!(
verb = "git.digest",
"durable receipt cannot be built because the gate produced no audit decision"
);
*result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
return GitDigestReceiptOutcome::PersistenceUnavailable;
};
let Some(report_object) = report.as_object_mut() else {
tracing::error!(
verb = "git.digest",
"digest handler returned a non-object report"
);
*result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
return GitDigestReceiptOutcome::BuildRejected;
};
let Some(project_id) = report_object
.get("project_id")
.and_then(Value::as_str)
.and_then(|raw| raw.parse::<uuid::Uuid>().ok())
else {
tracing::error!(
verb = "git.digest",
"digest handler report omitted a valid project_id"
);
*result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
return GitDigestReceiptOutcome::BuildRejected;
};
let mut event = Event::new(
gate_req.namespace.as_str(),
gate_req.verb.as_str(),
EventKind::Audit,
SubstrateKind::Event,
format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
)
.with_outcome(EventOutcome::Success)
.with_target(project_id)
.with_payload_schema_version(2)
.with_duration_us(duration_us);
let receipt_id = event.id;
report_object.insert(
"receipt_id".to_string(),
Value::String(receipt_id.to_string()),
);
let mut payload = serde_json::to_value(audit).unwrap_or_else(|serialize_err| {
tracing::error!(
verb = "git.digest",
error = %serialize_err,
"failed to serialize gate audit for durable digest receipt"
);
Value::Null
});
let Value::Object(payload_object) = &mut payload else {
tracing::error!(
verb = "git.digest",
"gate audit serialization did not produce an object"
);
*result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
return GitDigestReceiptOutcome::BuildRejected;
};
if let Some(resource) = resource {
payload_object.insert("resource".to_string(), resource);
}
payload_object.insert("result".to_string(), report.clone());
event.payload = payload;
let submit_result = if let Some(audit_batch) = audit_batch {
use crate::audit_batch::AuditBatchControl;
audit_batch
.submit(crate::audit_batch::PreparedAuditRow {
event,
producer: crate::audit_batch::AuditProducer::GitDigestReceipt,
})
.await
.map(|_outcome| ())
.map_err(|reason| format!("{reason:?}"))
} else {
store.append_event(event).await.map_err(|e| e.to_string())
};
if let Err(store_err) = submit_result {
AUDIT_OBLIGATION_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
tracing::error!(
verb = "git.digest",
error = %store_err,
receipt_id = %receipt_id,
"durable digest receipt append failed"
);
*result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
return GitDigestReceiptOutcome::PersistenceUnavailable;
}
GitDigestReceiptOutcome::Persisted
}
async fn append_audit_event_best_effort(
audit_batch: Option<&Arc<crate::audit_batch::AuditBatch>>,
store: &Arc<dyn EventStore>,
event: Event,
verb: &str,
producer: crate::audit_batch::AuditProducer,
degrade_allowlisted: bool,
) -> Result<(), RuntimeError> {
use crate::audit_batch::{
classify, AuditBatchControl, AuditProducer, AuditProductionClass, AuditTerminalReason,
};
let is_obligation = classify(producer) == AuditProductionClass::DispatchObligation;
let admission_degrade_eligible =
degrade_allowlisted && producer == AuditProducer::DispatchSucceeded;
if let Some(audit_batch) = audit_batch {
if let Err(reason) = audit_batch
.submit(crate::audit_batch::PreparedAuditRow { event, producer })
.await
{
if is_obligation {
if admission_degrade_eligible {
match reason {
AuditTerminalReason::QueueAdmissionExhausted => {
AUDIT_ADMISSION_REFUSED_OBLIGATIONS
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
tracing::warn!(
verb,
reason = ?reason,
"read verb's audit obligation row was refused before \
enqueue under audit-lane admission pressure; dispatch \
still reports its own result (non-fatal)"
);
return Ok(());
}
AuditTerminalReason::AdmissionDeadlineExpired => {
AUDIT_ADMISSION_UNRESOLVED_OBLIGATIONS
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
tracing::warn!(
verb,
reason = ?reason,
"read verb's audit obligation row was still enqueued and \
unresolved when the caller's admission wait deadline \
elapsed; it may still commit. Dispatch still reports its \
own result (non-fatal)"
);
return Ok(());
}
_ => {}
}
}
AUDIT_OBLIGATION_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
tracing::error!(
verb,
reason = ?reason,
"audit obligation batch submission failed; failing dispatch"
);
return Err(RuntimeError::Internal(format!(
"audit obligation commit failed for verb {verb:?}: {reason:?}"
)));
}
AUDIT_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
tracing::warn!(
verb,
reason = ?reason,
"audit event batch submission failed (non-fatal)"
);
}
return Ok(());
}
if let Err(store_err) = store.append_event(event).await {
if is_obligation {
AUDIT_OBLIGATION_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
tracing::error!(
verb,
error = %store_err,
"audit obligation store write failed; failing dispatch"
);
return Err(RuntimeError::Internal(format!(
"audit obligation commit failed for verb {verb:?}: {store_err}"
)));
}
AUDIT_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
tracing::warn!(
verb,
error = %store_err,
"audit event store write failed (non-fatal)"
);
}
Ok(())
}
fn fold_audit_obligation<T>(
result: Result<T, RuntimeError>,
audit_outcome: Result<(), RuntimeError>,
) -> Result<T, RuntimeError> {
match (result, audit_outcome) {
(Ok(value), Ok(())) => Ok(value),
(Ok(_), Err(audit_err)) => Err(audit_err),
(Err(err), _) => Err(err),
}
}
#[derive(Debug, Clone, serde::Serialize)]
struct LinkAuditSuccessV2 {
#[serde(flatten)]
audit: AuditEvent,
edge_id: uuid::Uuid,
source_id: uuid::Uuid,
target_id: uuid::Uuid,
relation: String,
weight: f64,
}
fn link_audit_success_from_result(
audit: AuditEvent,
result: &serde_json::Value,
) -> Option<(uuid::Uuid, serde_json::Value)> {
let edge_id = result.get("id")?.as_str()?.parse::<uuid::Uuid>().ok()?;
let source_id = result
.get("source_id")?
.as_str()?
.parse::<uuid::Uuid>()
.ok()?;
let target_id = result
.get("target_id")?
.as_str()?
.parse::<uuid::Uuid>()
.ok()?;
let relation = result.get("relation")?.as_str()?.to_string();
let weight = result.get("weight")?.as_f64()?;
let enriched = LinkAuditSuccessV2 {
audit,
edge_id,
source_id,
target_id,
relation,
weight,
};
let payload = serde_json::to_value(&enriched).ok()?;
Some((edge_id, payload))
}
pub fn resolve_explicit_namespace(
params: &Value,
default_namespace: &str,
) -> Result<Namespace, RuntimeError> {
match params.get("namespace") {
None => Namespace::parse(default_namespace)
.map_err(|e| RuntimeError::InvalidInput(format!("invalid namespace: {e}"))),
Some(Value::String(ns_str)) => Namespace::parse(ns_str)
.map_err(|e| RuntimeError::InvalidInput(format!("invalid namespace {ns_str:?}: {e}"))),
Some(other) => Err(RuntimeError::InvalidInput(format!(
"invalid namespace: expected string when present, got {}",
json_type_name(other),
))),
}
}
pub fn json_type_name(v: &Value) -> &'static str {
match v {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::ActorRef;
use khive_types::Pack;
const KNOWN_INCIDENTAL_WRITE_VERBS: &[&str] = &["memory.recall", "db_diagnostics"];
#[test]
fn admission_degrade_safe_verbs_are_registered_assertive() {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../khive-pack-kg/src/handler_defs.rs"
);
let source =
std::fs::read_to_string(path).unwrap_or_else(|e| panic!("failed to read {path}: {e}"));
for verb in VerbRegistry::ADMISSION_DEGRADE_SAFE_VERBS {
assert!(
!KNOWN_INCIDENTAL_WRITE_VERBS.contains(verb),
"admission-degrade-safe verb {verb:?} is a known incidental-write verb \
(khive#2147/khive#2217 round 1); it must not be re-added to \
ADMISSION_DEGRADE_SAFE_VERBS even though it is VerbCategory::Assertive"
);
let needle = format!("\n name: \"{verb}\",");
let name_pos = source.find(&needle).unwrap_or_else(|| {
panic!(
"admission-degrade-safe verb {verb:?} has no top-level `HandlerDef` in \
khive-pack-kg/src/handler_defs.rs; update the allowlist or this \
census's source path"
)
});
let block_end = source[name_pos..]
.find("HandlerDef {")
.map(|offset| name_pos + offset)
.unwrap_or(source.len());
let block = &source[name_pos..block_end];
assert!(
block.contains("VerbCategory::Assertive"),
"admission-degrade-safe verb {verb:?} is declared in \
khive-pack-kg/src/handler_defs.rs but is not VerbCategory::Assertive; \
admission degradation must not silently apply to a write-capable verb"
);
}
}
static COMM_PROBE_GRANTED: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
static OTHER_PROBE_GRANTED: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
struct CommProbeFactory;
struct OtherProbeFactory;
fn probe_pack(
_runtime: KhiveRuntime,
grant_flag: &'static std::sync::atomic::AtomicBool,
) -> Box<dyn PackRuntime> {
struct ProbePack {
grant_flag: &'static std::sync::atomic::AtomicBool,
}
#[async_trait::async_trait]
impl PackRuntime for ProbePack {
fn name(&self) -> &str {
"probe"
}
fn note_kinds(&self) -> &'static [&'static str] {
&[]
}
fn entity_kinds(&self) -> &'static [&'static str] {
&[]
}
fn handlers(&self) -> &'static [HandlerDef] {
&[]
}
fn accept_channel_ingest_capability(&self, _capability: ChannelIngestCapability) {
self.grant_flag
.store(true, std::sync::atomic::Ordering::SeqCst);
}
async fn dispatch(
&self,
_verb: &str,
_params: serde_json::Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<serde_json::Value, crate::RuntimeError> {
Err(crate::RuntimeError::InvalidInput("probe".into()))
}
}
Box::new(ProbePack { grant_flag })
}
impl PackFactory for CommProbeFactory {
fn name(&self) -> &'static str {
"comm"
}
fn create(&self, runtime: KhiveRuntime) -> Box<dyn PackRuntime> {
probe_pack(runtime, &COMM_PROBE_GRANTED)
}
}
impl PackFactory for OtherProbeFactory {
fn name(&self) -> &'static str {
"grant-probe-other"
}
fn create(&self, runtime: KhiveRuntime) -> Box<dyn PackRuntime> {
probe_pack(runtime, &OTHER_PROBE_GRANTED)
}
}
inventory::submit! { PackRegistration(&CommProbeFactory) }
inventory::submit! { PackRegistration(&OtherProbeFactory) }
#[test]
fn channel_ingest_grant_reaches_only_allowlisted_pack_names() {
let runtime = KhiveRuntime::memory().unwrap();
let mut builder = VerbRegistryBuilder::new();
PackRegistry::register_packs(
&["comm".to_string(), "grant-probe-other".to_string()],
runtime,
&mut builder,
)
.expect("probe registration succeeds");
assert!(
COMM_PROBE_GRANTED.load(std::sync::atomic::Ordering::SeqCst),
"the comm-named factory must receive the channel-ingest grant"
);
assert!(
!OTHER_PROBE_GRANTED.load(std::sync::atomic::Ordering::SeqCst),
"a factory outside CHANNEL_INGEST_CAPABLE_PACKS must never be granted"
);
}
#[test]
fn from_token_preserves_process_ref() {
let with_ref = NamespaceToken::mint_authorized(
Namespace::local(),
ActorRef::new("agent", "provenance-carrier"),
)
.with_process_ref(Some("proc:origin-abc123".to_string()));
let identity = RequestIdentity::from_token(&with_ref);
assert_eq!(identity.process_ref.as_deref(), Some("proc:origin-abc123"));
let without_ref = NamespaceToken::mint_authorized(
Namespace::local(),
ActorRef::new("agent", "provenance-absent"),
);
let identity = RequestIdentity::from_token(&without_ref);
assert_eq!(identity.process_ref, None);
}
struct AlphaPack;
impl Pack for AlphaPack {
const NAME: &'static str = "alpha";
const NOTE_KINDS: &'static [&'static str] = &["memo", "log"];
const ENTITY_KINDS: &'static [&'static str] = &["widget"];
const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["recall", "search"];
const HANDLERS: &'static [HandlerDef] = &[
HandlerDef {
name: "create",
description: "create a widget",
visibility: Visibility::Verb,
category: VerbCategory::Commissive,
params: &[],
},
HandlerDef {
name: "list",
description: "list widgets",
visibility: Visibility::Verb,
category: VerbCategory::Assertive,
params: &[],
},
];
}
#[async_trait]
impl PackRuntime for AlphaPack {
fn name(&self) -> &str {
AlphaPack::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
AlphaPack::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
AlphaPack::ENTITY_KINDS
}
fn brain_consumer_kinds(&self) -> &'static [&'static str] {
AlphaPack::BRAIN_CONSUMER_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
AlphaPack::HANDLERS
}
async fn dispatch(
&self,
verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Ok(serde_json::json!({ "pack": "alpha", "verb": verb }))
}
}
#[derive(Debug)]
struct GateErrorTrackingPack {
invoked: Arc<AtomicUsize>,
}
impl Pack for GateErrorTrackingPack {
const NAME: &'static str = "gate_error_tracking";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "guarded",
description: "track whether gate-error dispatch reaches the handler",
visibility: Visibility::Verb,
category: VerbCategory::Assertive,
params: &[],
}];
}
#[async_trait]
impl PackRuntime for GateErrorTrackingPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
_verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
self.invoked.fetch_add(1, Ordering::SeqCst);
Ok(serde_json::json!({"invoked": true}))
}
}
struct SleepingPack;
impl Pack for SleepingPack {
const NAME: &'static str = "sleeping";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "slow_op",
description: "sleeps before returning",
visibility: Visibility::Verb,
category: VerbCategory::Assertive,
params: &[],
}];
}
#[async_trait]
impl PackRuntime for SleepingPack {
fn name(&self) -> &str {
SleepingPack::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
SleepingPack::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
SleepingPack::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
SleepingPack::HANDLERS
}
async fn dispatch(
&self,
verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
Ok(serde_json::json!({ "pack": "sleeping", "verb": verb }))
}
}
struct BetaPack;
impl Pack for BetaPack {
const NAME: &'static str = "beta";
const NOTE_KINDS: &'static [&'static str] = &["alert"];
const ENTITY_KINDS: &'static [&'static str] = &["widget", "gadget"];
const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["search", "knowledge_compose"];
const HANDLERS: &'static [HandlerDef] = &[
HandlerDef {
name: "notify",
description: "send alert",
visibility: Visibility::Verb,
category: VerbCategory::Commissive,
params: &[],
},
HandlerDef {
name: "create",
description: "beta internal create (subhandler)",
visibility: Visibility::Subhandler,
category: VerbCategory::Commissive,
params: &[],
},
];
}
fn build_registry() -> VerbRegistry {
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.register(BetaPack);
builder.build().expect("registry builds without collision")
}
struct CollidingPack;
impl Pack for CollidingPack {
const NAME: &'static str = "colliding";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "create",
description: "duplicate Verb-visibility create",
visibility: Visibility::Verb,
category: VerbCategory::Commissive,
params: &[],
}];
}
#[async_trait]
impl PackRuntime for CollidingPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Ok(serde_json::json!({ "pack": "colliding", "verb": verb }))
}
}
struct ReservedEnvelopeParamPack;
impl Pack for ReservedEnvelopeParamPack {
const NAME: &'static str = "reserved-envelope-param";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "broken.serve",
description: "declares a transport-owned argument",
visibility: Visibility::Verb,
category: VerbCategory::Commissive,
params: &[ParamDef {
name: "presentation",
param_type: "object",
required: false,
description: "invalid collision with the request envelope",
}],
}];
}
#[async_trait]
impl PackRuntime for ReservedEnvelopeParamPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
_verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
unreachable!("invalid handler metadata must fail before dispatch")
}
}
#[async_trait]
impl PackRuntime for BetaPack {
fn name(&self) -> &str {
BetaPack::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
BetaPack::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
BetaPack::ENTITY_KINDS
}
fn brain_consumer_kinds(&self) -> &'static [&'static str] {
BetaPack::BRAIN_CONSUMER_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
BetaPack::HANDLERS
}
async fn dispatch(
&self,
verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Ok(serde_json::json!({ "pack": "beta", "verb": verb }))
}
}
#[tokio::test]
async fn dispatch_routes_to_correct_pack() {
let reg = build_registry();
let res = reg.dispatch("list", Value::Null).await.unwrap();
assert_eq!(res["pack"], "alpha");
let res = reg.dispatch("notify", Value::Null).await.unwrap();
assert_eq!(res["pack"], "beta");
}
#[test]
fn verb_collision_is_boot_time_error() {
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.register(CollidingPack);
let err = builder
.build()
.err()
.expect("duplicate Verb-visibility handler must be rejected at build time");
assert!(
matches!(err, RuntimeError::VerbCollision { ref verb, .. } if verb == "create"),
"expected VerbCollision for 'create', got {err:?}"
);
let msg = err.to_string();
assert!(
msg.contains("create"),
"error must name the colliding verb: {msg}"
);
assert!(
msg.contains("alpha") || msg.contains("colliding"),
"error must name one of the conflicting packs: {msg}"
);
}
#[test]
fn reserved_request_envelope_param_is_boot_time_error() {
let mut builder = VerbRegistryBuilder::new();
builder.register(ReservedEnvelopeParamPack);
let error = builder
.build()
.err()
.expect("transport-owned parameter names must fail registry construction");
assert!(
matches!(
error,
RuntimeError::ReservedEnvelopeParam {
ref pack,
ref verb,
ref param,
} if pack == "reserved-envelope-param"
&& verb == "broken.serve"
&& param == "presentation"
),
"unexpected error: {error:?}"
);
}
#[test]
fn reserved_request_envelope_param_is_boot_time_error_for_subhandler() {
struct ReservedEnvelopeSubhandlerParamPack;
impl Pack for ReservedEnvelopeSubhandlerParamPack {
const NAME: &'static str = "reserved-envelope-subhandler-param";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "broken.internal",
description: "declares a transport-owned argument on an internal handler",
visibility: Visibility::Subhandler,
category: VerbCategory::Assertive,
params: &[ParamDef {
name: "presentation_per_op",
param_type: "string",
required: false,
description: "invalid collision with the request envelope",
}],
}];
}
#[async_trait]
impl PackRuntime for ReservedEnvelopeSubhandlerParamPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
_verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
unreachable!("invalid handler metadata must fail before dispatch")
}
}
let mut builder = VerbRegistryBuilder::new();
builder.register(ReservedEnvelopeSubhandlerParamPack);
let error = builder
.build()
.err()
.expect("transport-owned parameter names must fail registry construction");
assert!(
matches!(
error,
RuntimeError::ReservedEnvelopeParam {
ref pack,
ref verb,
ref param,
} if pack == "reserved-envelope-subhandler-param"
&& verb == "broken.internal"
&& param == "presentation_per_op"
),
"unexpected error: {error:?}"
);
}
#[test]
fn subhandler_same_name_across_packs_is_not_a_collision() {
struct SubhandlerPack;
impl Pack for SubhandlerPack {
const NAME: &'static str = "subhandler_pack";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "create",
description: "internal create",
visibility: Visibility::Subhandler,
category: VerbCategory::Commissive,
params: &[],
}];
}
#[async_trait]
impl PackRuntime for SubhandlerPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
verb: &str,
_: Value,
_: &VerbRegistry,
_: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Ok(serde_json::json!({"pack": "subhandler_pack", "verb": verb}))
}
}
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack); builder.register(SubhandlerPack); builder
.build()
.expect("subhandler same name must NOT be a collision");
}
#[tokio::test]
async fn dispatch_unknown_verb_returns_error() {
let reg = build_registry();
let err = reg.dispatch("explode", Value::Null).await.unwrap_err();
let msg = err.to_string();
assert!(msg.contains("explode"));
assert!(msg.contains("create"));
}
#[test]
fn all_verbs_aggregates_across_packs_excludes_subhandlers() {
let reg = build_registry();
let verbs: Vec<&str> = reg.all_verbs().iter().map(|v| v.name).collect();
assert_eq!(verbs, vec!["create", "list", "notify"]);
}
#[test]
fn all_verbs_with_names_pairs_pack_name_excludes_subhandlers() {
let reg = build_registry();
let pairs: Vec<(&str, &str)> = reg
.all_verbs_with_names()
.iter()
.map(|(pack, v)| (*pack, v.name))
.collect();
assert_eq!(
pairs,
vec![("alpha", "create"), ("alpha", "list"), ("beta", "notify"),]
);
}
#[test]
fn all_handlers_with_names_includes_subhandlers() {
let reg = build_registry();
let pairs: Vec<(&str, &str)> = reg
.all_handlers_with_names()
.iter()
.map(|(pack, v)| (*pack, v.name))
.collect();
assert_eq!(
pairs,
vec![
("alpha", "create"),
("alpha", "list"),
("beta", "notify"),
("beta", "create"),
]
);
}
#[test]
fn note_kinds_are_ordered() {
let reg = build_registry();
let kinds = reg.all_note_kinds();
assert_eq!(kinds, vec!["memo", "log", "alert"]);
}
#[test]
fn brain_consumer_kinds_are_ordered_and_deduplicated() {
let reg = build_registry();
assert_eq!(
reg.all_brain_consumer_kinds(),
vec!["recall", "search", "knowledge_compose"]
);
}
#[test]
fn brain_consumer_kind_wildcard_is_rejected_at_build_time() {
struct WildcardConsumerPack;
impl khive_types::Pack for WildcardConsumerPack {
const NAME: &'static str = "wildcard-consumer";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["*"];
const HANDLERS: &'static [HandlerDef] = &[];
}
#[async_trait]
impl PackRuntime for WildcardConsumerPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn brain_consumer_kinds(&self) -> &'static [&'static str] {
Self::BRAIN_CONSUMER_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
_verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Ok(Value::Null)
}
}
let mut builder = VerbRegistryBuilder::new();
builder.register(WildcardConsumerPack);
let Err(RuntimeError::InvalidInput(message)) = builder.build() else {
panic!("registry must reject a pack-declared brain wildcard");
};
assert!(message.contains("wildcard-consumer"), "{message}");
assert!(message.contains("registry-owned"), "{message}");
}
#[test]
fn note_kind_duplicate_rejected_at_build_time() {
struct DupPack;
impl khive_types::Pack for DupPack {
const NAME: &'static str = "dup";
const NOTE_KINDS: &'static [&'static str] = &["memo"];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[];
}
#[async_trait]
impl PackRuntime for DupPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
_verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Ok(Value::Null)
}
}
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.register(DupPack);
let err = builder
.build()
.err()
.expect("duplicate note kind must be rejected");
let msg = err.to_string();
assert!(
msg.contains("memo"),
"error must name the duplicate kind: {msg}"
);
assert!(
msg.contains("alpha") || msg.contains("dup"),
"error must name one of the conflicting packs: {msg}"
);
}
#[test]
fn entity_kinds_are_deduplicated() {
let reg = build_registry();
let kinds = reg.all_entity_kinds();
assert_eq!(kinds, vec!["widget", "gadget"]);
}
struct GammaPack;
impl Pack for GammaPack {
const NAME: &'static str = "gamma";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[];
const ENTITY_TYPES: &'static [EntityTypeDef] = &[EntityTypeDef {
kind: khive_types::EntityKind::Document,
type_name: "gamma_report",
aliases: &["gamma_rep"],
}];
}
#[async_trait]
impl PackRuntime for GammaPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
fn entity_types(&self) -> &'static [EntityTypeDef] {
Self::ENTITY_TYPES
}
async fn dispatch(
&self,
verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Ok(serde_json::json!({ "pack": "gamma", "verb": verb }))
}
}
#[test]
fn all_entity_types_empty_when_no_pack_declares_extras() {
let reg = build_registry(); assert!(reg.all_entity_types().is_empty());
let composed = khive_types::EntityTypeRegistry::with_extra(reg.all_entity_types());
let resolved = composed
.resolve(khive_types::EntityKind::Document, Some("paper"))
.expect("builtin paper subtype must still resolve");
assert_eq!(resolved.entity_type.as_deref(), Some("paper"));
}
#[test]
fn pack_declared_entity_type_validates_through_composed_registry() {
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.register(GammaPack);
let reg = builder.build().expect("registry builds");
let extras = reg.all_entity_types();
assert_eq!(extras.len(), 1);
let composed = khive_types::EntityTypeRegistry::with_extra(extras);
let resolved = composed
.resolve(khive_types::EntityKind::Document, Some("gamma_rep"))
.expect("pack-declared alias must resolve through the composed registry");
assert_eq!(resolved.entity_type.as_deref(), Some("gamma_report"));
let builtin_resolved = composed
.resolve(khive_types::EntityKind::Document, Some("paper"))
.expect("builtin subtype must remain resolvable when a pack adds extras");
assert_eq!(builtin_resolved.entity_type.as_deref(), Some("paper"));
composed
.resolve(khive_types::EntityKind::Document, Some("nonexistent_type"))
.expect_err("undeclared entity_type must still be rejected");
}
#[test]
fn overlapping_pack_declared_entity_types_reject_at_boot() {
struct DeltaPack;
impl Pack for DeltaPack {
const NAME: &'static str = "delta";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[];
const ENTITY_TYPES: &'static [EntityTypeDef] = &[EntityTypeDef {
kind: khive_types::EntityKind::Document,
type_name: "gamma_report",
aliases: &["gamma_rep"],
}];
}
#[async_trait]
impl PackRuntime for DeltaPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
fn entity_types(&self) -> &'static [EntityTypeDef] {
Self::ENTITY_TYPES
}
async fn dispatch(
&self,
verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Ok(serde_json::json!({ "pack": "delta", "verb": verb }))
}
}
let mut builder = VerbRegistryBuilder::new();
builder.register(GammaPack);
builder.register(DeltaPack);
let err = builder.build().err().expect(
"overlapping ENTITY_TYPES declarations must fail at build, not silently compose",
);
let msg = err.to_string();
assert!(
msg.contains("gamma") && msg.contains("delta"),
"collision error must name both contributing packs: {msg}"
);
assert!(
msg.contains("gamma_report"),
"collision error must name the colliding entity_type key: {msg}"
);
}
use khive_gate::{Gate, GateError};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
#[derive(Default, Debug)]
struct CountingGate {
calls: AtomicUsize,
deny_verb: Option<&'static str>,
}
impl Gate for CountingGate {
fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
self.calls.fetch_add(1, Ordering::SeqCst);
if Some(req.verb.as_str()) == self.deny_verb {
Ok(GateDecision::deny(format!("test deny for {}", req.verb)))
} else {
Ok(GateDecision::allow())
}
}
}
#[tokio::test]
async fn dispatch_consults_the_gate() {
let gate = Arc::new(CountingGate::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(gate.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("list", Value::Null).await.unwrap();
reg.dispatch("create", Value::Null).await.unwrap();
assert_eq!(
gate.calls.load(Ordering::SeqCst),
2,
"gate should be consulted once per dispatch"
);
}
#[tokio::test]
async fn dispatch_returns_permission_denied_on_deny_v03() {
let gate = Arc::new(CountingGate {
calls: AtomicUsize::new(0),
deny_verb: Some("create"),
});
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(gate.clone());
let reg = builder.build().expect("registry builds");
let err = reg.dispatch("create", Value::Null).await.unwrap_err();
assert!(
matches!(err, RuntimeError::PermissionDenied { ref verb, .. } if verb == "create"),
"expected PermissionDenied, got {err:?}"
);
let msg = err.to_string();
assert!(
msg.contains("create"),
"error message must name the verb: {msg}"
);
assert!(
msg.contains("test deny for create"),
"error message must carry the deny reason: {msg}"
);
assert_eq!(gate.calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn dispatch_allow_verb_succeeds_even_with_deny_gate_for_other_verb() {
let gate = Arc::new(CountingGate {
calls: AtomicUsize::new(0),
deny_verb: Some("create"),
});
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(gate.clone());
let reg = builder.build().expect("registry builds");
let res = reg.dispatch("list", Value::Null).await.unwrap();
assert_eq!(res["pack"], "alpha");
}
#[tokio::test]
async fn dispatch_uses_allow_all_gate_by_default() {
let reg = build_registry();
let res = reg.dispatch("list", Value::Null).await.unwrap();
assert_eq!(res["pack"], "alpha");
}
#[derive(Default, Debug)]
struct NamespaceCapturingGate {
seen: std::sync::Mutex<Vec<String>>,
}
impl Gate for NamespaceCapturingGate {
fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
self.seen
.lock()
.unwrap()
.push(req.namespace.as_str().to_string());
Ok(GateDecision::allow())
}
}
#[tokio::test]
async fn dispatch_propagates_params_namespace_to_gate() {
let gate = Arc::new(NamespaceCapturingGate::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(gate.clone());
builder.with_default_namespace("tenant-x");
let reg = builder.build().expect("registry builds");
reg.dispatch("list", serde_json::json!({"namespace": "tenant-y"}))
.await
.unwrap();
reg.dispatch("list", Value::Null).await.unwrap();
let err = reg
.dispatch("list", serde_json::json!({"namespace": ""}))
.await
.unwrap_err();
assert!(
matches!(err, RuntimeError::InvalidInput(_)),
"empty namespace must return InvalidInput, got {err:?}"
);
let seen = gate.seen.lock().unwrap().clone();
assert_eq!(seen, vec!["tenant-y", "tenant-x"]);
}
#[tokio::test]
async fn dispatch_falls_back_to_local_when_no_default_set() {
let gate = Arc::new(NamespaceCapturingGate::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(gate.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("list", Value::Null).await.unwrap();
let seen = gate.seen.lock().unwrap().clone();
assert_eq!(seen, vec!["local"]);
}
#[tokio::test]
async fn namespace_null_rejected_not_coerced() {
let cases: Vec<(&str, Value)> = vec![
("null", Value::Null),
("number", serde_json::json!(42)),
("boolean", serde_json::json!(true)),
("array", serde_json::json!(["local"])),
("object", serde_json::json!({"ns": "local"})),
];
for (label, ns_value) in cases {
let gate = Arc::new(NamespaceCapturingGate::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(gate.clone());
builder.with_default_namespace("tenant-x");
let reg = builder.build().expect("registry builds");
let err = reg
.dispatch("list", serde_json::json!({"namespace": ns_value}))
.await
.unwrap_err();
assert!(
matches!(err, RuntimeError::InvalidInput(_)),
"case {label}: expected InvalidInput, got {err:?}"
);
let seen = gate.seen.lock().unwrap().clone();
assert!(
seen.is_empty(),
"case {label}: gate must not be consulted for malformed namespace, saw {seen:?}"
);
}
}
use khive_gate::{AuditDecision, AuditEvent, Obligation};
#[derive(Default, Debug)]
struct AuditCapturingGate {
events: std::sync::Mutex<Vec<AuditEvent>>,
deny_verb: Option<&'static str>,
}
impl Gate for AuditCapturingGate {
fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
let decision = if Some(req.verb.as_str()) == self.deny_verb {
GateDecision::deny("test deny")
} else {
GateDecision::allow_with(vec![Obligation::Audit {
tag: format!("{}.check", req.verb),
}])
};
let ev = AuditEvent::from_check(req, &decision, self.impl_name());
self.events.lock().unwrap().push(ev);
Ok(decision)
}
fn impl_name(&self) -> &'static str {
"AuditCapturingGate"
}
}
#[tokio::test]
async fn dispatch_emits_one_audit_event_per_call() {
let gate = Arc::new(AuditCapturingGate::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(gate.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("list", Value::Null).await.unwrap();
reg.dispatch("create", Value::Null).await.unwrap();
let evs = gate.events.lock().unwrap();
assert_eq!(evs.len(), 2, "exactly one audit event per dispatch call");
}
#[tokio::test]
async fn dispatch_audit_event_allow_carries_obligations() {
let gate = Arc::new(AuditCapturingGate::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(gate.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("list", Value::Null).await.unwrap();
let evs = gate.events.lock().unwrap();
let ev = &evs[0];
assert_eq!(ev.verb, "list");
assert_eq!(ev.decision, AuditDecision::Allow);
assert!(ev.deny_reason.is_none());
assert_eq!(ev.obligations.len(), 1);
assert_eq!(ev.gate_impl, "AuditCapturingGate");
}
#[tokio::test]
async fn dispatch_audit_event_deny_carries_reason() {
let gate = Arc::new(AuditCapturingGate {
events: Default::default(),
deny_verb: Some("create"),
});
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(gate.clone());
let reg = builder.build().expect("registry builds");
let err = reg.dispatch("create", Value::Null).await.unwrap_err();
assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
let evs = gate.events.lock().unwrap();
let ev = &evs[0];
assert_eq!(ev.verb, "create");
assert_eq!(ev.decision, AuditDecision::Deny);
assert_eq!(ev.deny_reason.as_deref(), Some("test deny"));
assert!(ev.obligations.is_empty());
}
#[tokio::test]
async fn dispatch_audit_event_fields_match_gate_request() {
let gate = Arc::new(AuditCapturingGate::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(gate.clone());
builder.with_default_namespace("tenant-z");
let reg = builder.build().expect("registry builds");
reg.dispatch("list", serde_json::json!({"namespace": "tenant-q"}))
.await
.unwrap();
let evs = gate.events.lock().unwrap();
let ev = &evs[0];
assert_eq!(ev.namespace, "tenant-q");
assert_eq!(ev.verb, "list");
assert_eq!(ev.actor.kind, "anonymous");
}
#[derive(Default, Debug)]
struct ActorCapturingGate {
requests: std::sync::Mutex<Vec<GateRequest>>,
}
impl Gate for ActorCapturingGate {
fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
self.requests.lock().unwrap().push(req.clone());
Ok(GateDecision::allow())
}
}
#[tokio::test]
async fn gate_request_carries_configured_actor_when_actor_id_is_set() {
let gate = Arc::new(ActorCapturingGate::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(gate.clone());
builder.with_actor_id(Some("team-abc:implementer".to_string()));
let reg = builder.build().expect("registry builds");
reg.dispatch("list", Value::Null).await.unwrap();
let reqs = gate.requests.lock().unwrap();
assert_eq!(reqs.len(), 1);
let req = &reqs[0];
assert_eq!(
req.actor.kind, "actor",
"gate request must carry kind='actor' when actor_id is configured"
);
assert_eq!(
req.actor.id, "team-abc:implementer",
"gate request must carry the configured actor id"
);
}
#[tokio::test]
async fn gate_request_carries_anonymous_when_no_actor_id_configured() {
let gate = Arc::new(ActorCapturingGate::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(gate.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("list", Value::Null).await.unwrap();
let reqs = gate.requests.lock().unwrap();
assert_eq!(reqs.len(), 1);
let req = &reqs[0];
assert_eq!(
req.actor.kind, "anonymous",
"gate request must carry anonymous actor when no actor_id is configured"
);
assert_eq!(req.actor.id, "local");
}
struct TokenCapturingPack {
actors: Arc<std::sync::Mutex<Vec<khive_gate::ActorRef>>>,
}
impl Pack for TokenCapturingPack {
const NAME: &'static str = "alpha";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = AlphaPack::HANDLERS;
}
#[async_trait]
impl PackRuntime for TokenCapturingPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
verb: &str,
_params: Value,
_registry: &VerbRegistry,
token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
self.actors.lock().unwrap().push(token.actor().clone());
Ok(serde_json::json!({ "pack": "alpha", "verb": verb }))
}
}
#[tokio::test]
async fn gate_actor_and_token_actor_are_identical_when_actor_id_is_set() {
let gate = Arc::new(ActorCapturingGate::default());
let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
let pack = TokenCapturingPack {
actors: actors.clone(),
};
let mut builder = VerbRegistryBuilder::new();
builder.register(pack);
builder.with_gate(gate.clone());
builder.with_actor_id(Some("actor-alpha".to_string()));
let reg = builder.build().expect("registry builds");
reg.dispatch("list", Value::Null).await.unwrap();
let reqs = gate.requests.lock().unwrap();
let gate_actor = reqs[0].actor.clone();
drop(reqs);
let captured = actors.lock().unwrap();
let token_actor = captured[0].clone();
assert_eq!(
gate_actor.kind, token_actor.kind,
"gate request actor and storage token actor must carry the same kind"
);
assert_eq!(
gate_actor.id, token_actor.id,
"gate request actor and storage token actor must carry the same id"
);
assert_eq!(gate_actor.id, "actor-alpha");
}
#[tokio::test]
async fn gate_actor_and_token_actor_are_identical_when_anonymous() {
let gate = Arc::new(ActorCapturingGate::default());
let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
let pack = TokenCapturingPack {
actors: actors.clone(),
};
let mut builder = VerbRegistryBuilder::new();
builder.register(pack);
builder.with_gate(gate.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("list", Value::Null).await.unwrap();
let reqs = gate.requests.lock().unwrap();
let gate_actor = reqs[0].actor.clone();
drop(reqs);
let captured = actors.lock().unwrap();
let token_actor = captured[0].clone();
assert_eq!(gate_actor.kind, token_actor.kind);
assert_eq!(gate_actor.id, token_actor.id);
assert_eq!(gate_actor.id, "local");
}
#[tokio::test]
async fn dispatch_as_threads_verified_actor_into_token() {
let gate = Arc::new(ActorCapturingGate::default());
let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
let pack = TokenCapturingPack {
actors: actors.clone(),
};
let mut builder = VerbRegistryBuilder::new();
builder.register(pack);
builder.with_gate(gate.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch_as(
"list",
Value::Null,
VerifiedActor::new("gateway:principal-42").unwrap(),
)
.await
.unwrap();
let reqs = gate.requests.lock().unwrap();
assert_eq!(reqs[0].actor.kind, "actor");
assert_eq!(reqs[0].actor.id, "gateway:principal-42");
drop(reqs);
let captured = actors.lock().unwrap();
assert_eq!(captured[0].kind, "actor");
assert_eq!(
captured[0].id, "gateway:principal-42",
"the storage token actor must be the verified_actor supplied to dispatch_as, \
matching exactly what pack handlers read as the acting principal"
);
}
#[tokio::test]
async fn dispatch_as_does_not_change_plain_dispatch_behavior() {
let gate = Arc::new(ActorCapturingGate::default());
let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
let pack = TokenCapturingPack {
actors: actors.clone(),
};
let mut builder = VerbRegistryBuilder::new();
builder.register(pack);
builder.with_gate(gate.clone());
builder.with_actor_id(Some("baked-actor".to_string()));
let reg = builder.build().expect("registry builds");
reg.dispatch_as(
"list",
Value::Null,
VerifiedActor::new("verified-actor").unwrap(),
)
.await
.unwrap();
reg.dispatch("list", Value::Null).await.unwrap();
let captured = actors.lock().unwrap();
assert_eq!(captured.len(), 2);
assert_eq!(captured[0].id, "verified-actor", "dispatch_as call");
assert_eq!(
captured[1].id, "baked-actor",
"a later plain dispatch() call must still use the registry's baked \
actor_id, unaffected by the prior dispatch_as call"
);
}
#[tokio::test]
async fn dispatch_as_ignores_actor_key_in_params() {
let gate = Arc::new(ActorCapturingGate::default());
let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
let pack = TokenCapturingPack {
actors: actors.clone(),
};
let mut builder = VerbRegistryBuilder::new();
builder.register(pack);
builder.with_gate(gate.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch_as(
"list",
serde_json::json!({"actor": "spoofed-actor"}),
VerifiedActor::new("verified-actor").unwrap(),
)
.await
.unwrap();
let captured = actors.lock().unwrap();
assert_eq!(
captured[0].id, "verified-actor",
"an 'actor' key inside params must never override the verified_actor \
argument threaded through dispatch_as"
);
}
#[test]
fn verified_actor_rejects_empty_identifier() {
let err = VerifiedActor::new("").unwrap_err();
assert!(
matches!(err, RuntimeError::InvalidInput(_)),
"expected InvalidInput, got {err:?}"
);
}
#[test]
fn verified_actor_rejects_whitespace_only_identifier() {
let err = VerifiedActor::new(" ").unwrap_err();
assert!(
matches!(err, RuntimeError::InvalidInput(_)),
"expected InvalidInput, got {err:?}"
);
}
#[tokio::test]
async fn rego_gate_missing_entrypoint_returns_permission_denied() {
use khive_gate_rego::RegoGate;
let policy = r#"
package khive.gate
import rego.v1
verdict := "allow"
"#;
let gate = Arc::new(RegoGate::from_policy_str(policy).expect("policy compiles"));
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(gate);
let reg = builder.build().expect("registry builds");
let err = reg.dispatch("create", Value::Null).await.unwrap_err();
assert!(
matches!(err, RuntimeError::PermissionDenied { ref verb, ref reason }
if verb == "create" && reason == "policy evaluation failed"),
"expected PermissionDenied with the static classified reason for a missing rego entrypoint, got {err:?}"
);
}
use std::sync::{Mutex as StdMutex, Once, OnceLock};
use serial_test::serial;
use tracing::field::{Field, Visit};
#[derive(Clone, Debug, Default)]
struct CapturedEvent {
message: Option<String>,
audit_event: Option<String>,
into_id: Option<String>,
budget_rows: Option<u64>,
}
#[derive(Default)]
struct CapturedEventVisitor(CapturedEvent);
impl Visit for CapturedEventVisitor {
fn record_str(&mut self, field: &Field, value: &str) {
match field.name() {
"message" => self.0.message = Some(value.to_string()),
"audit_event" => self.0.audit_event = Some(value.to_string()),
_ => {}
}
}
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
let formatted = format!("{value:?}");
let cleaned = formatted
.trim_start_matches('"')
.trim_end_matches('"')
.to_string();
match field.name() {
"message" => self.0.message = Some(cleaned),
"audit_event" => self.0.audit_event = Some(cleaned),
"into_id" => self.0.into_id = Some(cleaned),
_ => {}
}
}
fn record_u64(&mut self, field: &Field, value: u64) {
if field.name() == "budget_rows" {
self.0.budget_rows = Some(value);
}
}
}
struct CaptureSubscriber {
events: Arc<StdMutex<Vec<CapturedEvent>>>,
}
impl CaptureSubscriber {
fn new(events: Arc<StdMutex<Vec<CapturedEvent>>>) -> Self {
Self { events }
}
}
impl tracing::Subscriber for CaptureSubscriber {
fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
true
}
fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
tracing::span::Id::from_u64(1)
}
fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
fn event(&self, event: &tracing::Event<'_>) {
let mut visitor = CapturedEventVisitor::default();
event.record(&mut visitor);
let captured = visitor.0;
if let (Some(message), Some(into_id)) = (&captured.message, &captured.into_id) {
if message.ends_with("transaction materialization budget") {
budget_events_sink()
.lock()
.unwrap()
.push(CapturedBudgetLog {
message: message.clone(),
into_id: into_id.clone(),
budget_rows: captured.budget_rows.unwrap_or(0),
});
}
}
self.events.lock().unwrap().push(captured);
}
fn enter(&self, _: &tracing::span::Id) {}
fn exit(&self, _: &tracing::span::Id) {}
}
static GLOBAL_CAPTURE: OnceLock<Arc<StdMutex<Vec<CapturedEvent>>>> = OnceLock::new();
static GLOBAL_INIT: Once = Once::new();
#[derive(Clone)]
pub(crate) struct CapturedBudgetLog {
pub(crate) message: String,
pub(crate) into_id: String,
pub(crate) budget_rows: u64,
}
static BUDGET_EVENTS: OnceLock<Arc<StdMutex<Vec<CapturedBudgetLog>>>> = OnceLock::new();
fn budget_events_sink() -> Arc<StdMutex<Vec<CapturedBudgetLog>>> {
Arc::clone(BUDGET_EVENTS.get_or_init(|| Arc::new(StdMutex::new(Vec::new()))))
}
pub(crate) fn budget_log_events() -> Arc<StdMutex<Vec<CapturedBudgetLog>>> {
let _ = global_capture();
budget_events_sink()
}
fn global_capture() -> Arc<StdMutex<Vec<CapturedEvent>>> {
GLOBAL_INIT.call_once(|| {
let buffer = Arc::new(StdMutex::new(Vec::new()));
let subscriber = CaptureSubscriber::new(Arc::clone(&buffer));
let _ = tracing::subscriber::set_global_default(subscriber);
let _ = GLOBAL_CAPTURE.set(buffer);
});
Arc::clone(GLOBAL_CAPTURE.get().expect("global capture initialized"))
}
fn capture_dispatch_events<Fut>(future: Fut) -> Vec<CapturedEvent>
where
Fut: std::future::Future<Output = ()>,
{
let buffer = global_capture();
buffer.lock().unwrap().clear();
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.expect("build current-thread tokio runtime");
rt.block_on(future);
let result = buffer.lock().unwrap().clone();
result
}
fn gate_check_events_for(events: &[CapturedEvent], gate_impl: &str) -> Vec<CapturedEvent> {
events
.iter()
.filter(|e| e.message.as_deref() == Some("gate.check"))
.filter(|e| {
e.audit_event
.as_deref()
.and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok())
.and_then(|v| {
v.get("gate_impl")
.and_then(|g| g.as_str().map(|s| s.to_string()))
})
.as_deref()
== Some(gate_impl)
})
.cloned()
.collect()
}
#[test]
#[serial]
fn dispatch_tracing_emits_one_gate_check_event_on_allow() {
#[derive(Debug)]
struct TracingAllowGate;
impl Gate for TracingAllowGate {
fn check(&self, _: &GateRequest) -> Result<GateDecision, GateError> {
Ok(GateDecision::allow())
}
fn impl_name(&self) -> &'static str {
"TracingAllowGate"
}
}
let events = capture_dispatch_events(async {
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(Arc::new(TracingAllowGate));
builder.with_default_namespace("tenant-default");
let reg = builder.build().expect("registry builds");
reg.dispatch("list", serde_json::json!({"namespace": "tenant-q"}))
.await
.unwrap();
});
let gate_events = gate_check_events_for(&events, "TracingAllowGate");
assert_eq!(
gate_events.len(),
1,
"exactly one gate.check tracing event per dispatch (allow); got {gate_events:?}"
);
let payload = gate_events[0]
.audit_event
.as_ref()
.expect("gate.check event must carry an audit_event field");
let audit: khive_gate::AuditEvent =
serde_json::from_str(payload).expect("audit_event payload must decode to AuditEvent");
assert_eq!(audit.decision, AuditDecision::Allow);
assert_eq!(audit.verb, "list");
assert_eq!(audit.namespace, "tenant-q");
assert_eq!(audit.gate_impl, "TracingAllowGate");
assert!(
audit.deny_reason.is_none(),
"deny_reason must be None on Allow"
);
}
#[test]
#[serial]
fn dispatch_tracing_emits_one_gate_check_event_when_gate_is_unavailable() {
#[derive(Debug)]
struct TracingUnavailableGate;
impl Gate for TracingUnavailableGate {
fn check(&self, _: &GateRequest) -> Result<GateDecision, GateError> {
Err(GateError::Internal("tracing gate broken".into()))
}
fn impl_name(&self) -> &'static str {
"TracingUnavailableGate"
}
}
let events = capture_dispatch_events(async {
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(Arc::new(TracingUnavailableGate));
let reg = builder.build().expect("registry builds");
let error = reg
.dispatch("list", Value::Null)
.await
.expect_err("gate outage must refuse dispatch");
assert!(matches!(error, RuntimeError::GateUnavailable { .. }));
});
let gate_events = gate_check_events_for(&events, "TracingUnavailableGate");
assert_eq!(
gate_events.len(),
1,
"exactly one gate.check tracing event per gate outage; got {gate_events:?}"
);
let payload = gate_events[0]
.audit_event
.as_ref()
.expect("gate outage trace must carry an audit_event field");
let audit: AuditEvent =
serde_json::from_str(payload).expect("audit_event payload must decode");
assert_eq!(audit.decision, AuditDecision::GateUnavailable);
assert!(audit.deny_reason.is_none());
assert!(audit.obligations.is_empty());
assert_eq!(audit.gate_impl, "TracingUnavailableGate");
}
use crate::runtime::NamespaceToken;
use async_trait::async_trait;
use khive_storage::{
BatchWriteSummary, Event, EventFilter, EventStore, Page, PageRequest, SubstrateKind,
};
use khive_types::EventOutcome;
struct GitDigestResultPack {
project_id: uuid::Uuid,
}
impl Pack for GitDigestResultPack {
const NAME: &'static str = "git";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "git.digest",
description: "return a deterministic digest report",
visibility: Visibility::Verb,
category: VerbCategory::Assertive,
params: &[],
}];
}
#[async_trait]
impl PackRuntime for GitDigestResultPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
_verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Ok(serde_json::json!({
"project_id": self.project_id,
"project_created": false,
"commits_ingested": 2,
"commits_skipped_existing": 1,
"issues_ingested": 3,
"issues_skipped_existing": 4,
"prs_ingested": 5,
"prs_skipped_existing": 6,
"done": true,
"history_exhausted": true,
"sources": {
"commits": {"state": "completed"},
"issues": {"state": "completed"},
"pull_requests": {"state": "completed"}
},
"warnings": []
}))
}
}
struct MalformedGitDigestResultPack;
impl Pack for MalformedGitDigestResultPack {
const NAME: &'static str = "malformed-git";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "git.digest",
description: "return a malformed digest report",
visibility: Visibility::Verb,
category: VerbCategory::Assertive,
params: &[],
}];
}
#[async_trait]
impl PackRuntime for MalformedGitDigestResultPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
_verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Ok(serde_json::json!({
"project_id": "not-a-uuid",
"done": true,
}))
}
}
#[derive(Debug, Clone, PartialEq)]
enum TraceEntry {
Effect { name: String },
Audit {
kind: EventKind,
outcome: EventOutcome,
verb: String,
cost_unit: Option<Value>,
},
}
#[derive(Default, Debug)]
struct MemoryEventStore {
events: std::sync::Mutex<Vec<Event>>,
fail_appends: bool,
fail_kind: Option<EventKind>,
trace: Option<Arc<std::sync::Mutex<Vec<TraceEntry>>>>,
}
impl MemoryEventStore {
fn trace_submission(&self, events: &[Event]) {
if let Some(trace) = &self.trace {
let mut trace = trace.lock().expect("trace lock");
for event in events {
let cost_unit = event
.payload
.get("resource")
.and_then(|resource| resource.get("cost_unit"))
.cloned();
trace.push(TraceEntry::Audit {
kind: event.kind,
outcome: event.outcome,
verb: event.verb.clone(),
cost_unit,
});
}
}
}
}
#[async_trait]
impl EventStore for MemoryEventStore {
async fn append_event(&self, event: Event) -> khive_storage::StorageResult<()> {
self.trace_submission(std::slice::from_ref(&event));
if self.fail_appends || self.fail_kind == Some(event.kind) {
return Err(khive_storage::StorageError::Internal(
"injected audit append failure".to_string(),
));
}
self.events.lock().unwrap().push(event);
Ok(())
}
async fn append_events(
&self,
events: Vec<Event>,
) -> khive_storage::StorageResult<BatchWriteSummary> {
self.trace_submission(&events);
let attempted = events.len() as u64;
let affected = attempted;
self.events.lock().unwrap().extend(events);
Ok(BatchWriteSummary {
attempted,
affected,
failed: 0,
first_error: String::new(),
})
}
async fn get_event(&self, id: uuid::Uuid) -> khive_storage::StorageResult<Option<Event>> {
Ok(self
.events
.lock()
.unwrap()
.iter()
.find(|e| e.id == id)
.cloned())
}
async fn query_events(
&self,
_filter: EventFilter,
_page: PageRequest,
) -> khive_storage::StorageResult<Page<Event>> {
let items = self.events.lock().unwrap().clone();
let total = items.len() as u64;
Ok(Page {
items,
total: Some(total),
})
}
async fn count_events(&self, _filter: EventFilter) -> khive_storage::StorageResult<u64> {
Ok(self.events.lock().unwrap().len() as u64)
}
fn preflight_event(&self, _event: &Event) -> khive_storage::StorageResult<()> {
Ok(())
}
async fn append_events_idempotent(
&self,
events: Vec<Event>,
) -> khive_storage::StorageResult<khive_storage::event::IdempotentEventBatchResult>
{
self.trace_submission(&events);
if self.fail_appends
|| self
.fail_kind
.is_some_and(|kind| events.iter().any(|e| e.kind == kind))
{
return Err(khive_storage::StorageError::Internal(
"injected audit append failure".to_string(),
));
}
let mut store = self.events.lock().unwrap();
let mut rows = Vec::with_capacity(events.len());
for event in events {
if let Some(existing) = store.iter().find(|e| e.id == event.id) {
if *existing == event {
rows.push(
khive_storage::event::EventAppendDisposition::AlreadyPresentIdentical,
);
} else {
rows.push(khive_storage::event::EventAppendDisposition::IdentityConflict);
}
} else {
store.push(event);
rows.push(khive_storage::event::EventAppendDisposition::Inserted);
}
}
Ok(khive_storage::event::IdempotentEventBatchResult { rows })
}
fn supports_idempotent_audit_batch(&self) -> bool {
true
}
}
fn only_git_digest_event(store: &MemoryEventStore) -> Event {
let events: Vec<Event> = store
.events
.lock()
.unwrap()
.iter()
.filter(|event| event.verb == "git.digest")
.cloned()
.collect();
assert_eq!(
events.len(),
1,
"expected exactly one git.digest receipt event"
);
events[0].clone()
}
#[tokio::test]
async fn git_digest_success_returns_complete_durable_receipt() {
let project_id = uuid::Uuid::new_v4();
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(GitDigestResultPack { project_id });
builder.with_event_store(store.clone());
let registry = builder.build().expect("registry builds");
let result = registry
.dispatch_with_identity(
"git.digest",
serde_json::json!({
"source": "https://user:SECRET@example.invalid/org/repo",
}),
Some(RequestIdentity {
namespace: Namespace::local().as_str().to_string(),
request_id: Some(1_510),
..Default::default()
}),
)
.await
.expect("durably receipted digest succeeds");
let receipt_id = result["receipt_id"]
.as_str()
.and_then(|raw| raw.parse::<uuid::Uuid>().ok())
.expect("response has UUID receipt_id");
let event = only_git_digest_event(&store);
assert_eq!(event.id, receipt_id);
assert_eq!(event.target_id, Some(project_id));
assert_eq!(event.verb, "git.digest");
assert_eq!(event.outcome, EventOutcome::Success);
assert_eq!(event.payload_schema_version, 2);
assert_eq!(event.payload["result"], result);
assert_eq!(event.payload["resource"]["request_id"], 1_510);
assert_eq!(event.payload["result"]["commits_ingested"], 2);
assert_eq!(event.payload["result"]["issues_ingested"], 3);
assert_eq!(event.payload["result"]["prs_ingested"], 5);
assert!(
!event.payload.to_string().contains("SECRET"),
"receipt must not persist the caller's source URL or credentials"
);
}
#[tokio::test]
async fn malformed_git_digest_report_appends_one_generic_error_audit() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(MalformedGitDigestResultPack);
builder.with_event_store(store.clone());
let registry = builder.build().expect("registry builds");
let err = registry
.dispatch("git.digest", serde_json::json!({}))
.await
.expect_err("malformed receipt identity must fail the response");
assert!(matches!(
err,
RuntimeError::Internal(ref message)
if message.starts_with("git_digest_receipt_persist_failed:")
));
let event = only_git_digest_event(&store);
assert_eq!(event.outcome, EventOutcome::Error);
assert_eq!(event.payload_schema_version, 1);
assert!(
event.payload.get("result").is_none(),
"a generic Error audit must not masquerade as a success receipt"
);
let audit: AuditEvent =
serde_json::from_value(event.payload).expect("generic payload remains an AuditEvent");
assert_eq!(audit.verb, "git.digest");
assert_eq!(audit.decision, AuditDecision::Allow);
}
#[tokio::test]
#[serial(audit_append_failures)]
#[serial(audit_obligation_append_failures)]
async fn git_digest_receipt_append_failure_never_returns_unqualified_success() {
let before = audit_append_failure_count();
let before_obligation = audit_obligation_append_failure_count();
let store = Arc::new(MemoryEventStore {
fail_appends: true,
..MemoryEventStore::default()
});
let mut builder = VerbRegistryBuilder::new();
builder.register(GitDigestResultPack {
project_id: uuid::Uuid::new_v4(),
});
builder.with_event_store(store);
let registry = builder.build().expect("registry builds");
let err = registry
.dispatch("git.digest", serde_json::json!({}))
.await
.expect_err("receipt persistence failure must fail the response");
assert!(
matches!(&err, RuntimeError::Internal(message)
if message.starts_with("git_digest_receipt_persist_failed:")
&& message.contains("writes may have committed")),
"error is stable, safe, and retry-aware: {err}"
);
assert_eq!(audit_append_failure_count(), before);
assert_eq!(
audit_obligation_append_failure_count(),
before_obligation + 1
);
}
#[tokio::test]
async fn git_digest_without_event_store_fails_safe_after_handler_success() {
let mut builder = VerbRegistryBuilder::new();
builder.register(GitDigestResultPack {
project_id: uuid::Uuid::new_v4(),
});
let registry = builder.build().expect("registry builds");
let err = registry
.dispatch("git.digest", serde_json::json!({}))
.await
.expect_err("a successful digest needs a durable store");
assert!(matches!(
err,
RuntimeError::Internal(ref message)
if message.starts_with("git_digest_receipt_persist_failed:")
));
}
#[tokio::test]
async fn git_digest_gate_unavailable_precedes_the_receipt_contract() {
#[derive(Debug)]
struct FailingGate;
impl Gate for FailingGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, khive_gate::GateError> {
Err(khive_gate::GateError::Internal(
"injected gate failure".into(),
))
}
}
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(GitDigestResultPack {
project_id: uuid::Uuid::new_v4(),
});
builder.with_gate(Arc::new(FailingGate));
builder.with_event_store(store.clone());
let registry = builder.build().expect("registry builds");
let err = registry
.dispatch("git.digest", serde_json::json!({}))
.await
.expect_err("gate unavailability must refuse before the handler or receipt path");
assert!(matches!(
err,
RuntimeError::GateUnavailable { ref verb, ref reason }
if verb == "git.digest"
&& reason == "gate backend unavailable"
&& !reason.contains("injected gate failure")
));
let event = only_git_digest_event(&store);
assert_eq!(event.outcome, EventOutcome::Error);
assert_eq!(event.payload["decision"], "gate_unavailable");
assert!(event.payload.get("result").is_none());
}
#[tokio::test]
async fn intercepted_gate_error_returns_typed_refusal_without_invoking_operation() {
#[derive(Debug)]
struct FailingGate;
impl Gate for FailingGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, khive_gate::GateError> {
Err(khive_gate::GateError::Internal(
"intercepted gate broken".into(),
))
}
}
let invoked = Arc::new(AtomicUsize::new(0));
let invoked_by_operation = Arc::clone(&invoked);
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.with_gate(Arc::new(FailingGate));
builder.with_event_store(store.clone());
let registry = builder.build().expect("registry builds");
let identity = RequestIdentity {
namespace: "identity-default".to_string(),
request_id: Some(1_600),
..Default::default()
};
let err = registry
.dispatch_intercepted_with_identity(
"list",
&serde_json::json!({"namespace": "test-ns"}),
Some(&identity),
move |_namespace| {
invoked_by_operation.fetch_add(1, Ordering::SeqCst);
async move { Ok(serde_json::json!({"invoked": true})) }
},
)
.await
.expect_err("gate unavailability must refuse intercepted dispatch");
assert!(matches!(
err,
RuntimeError::GateUnavailable { ref verb, ref reason }
if verb == "list"
&& reason == "gate backend unavailable"
&& !reason.contains("intercepted gate broken")
));
assert_eq!(
invoked.load(Ordering::SeqCst),
0,
"intercepted operation must not run after a gate infrastructure error"
);
let events = store.events.lock().unwrap();
assert_eq!(events.len(), 1);
assert_eq!(events[0].verb, "list");
assert_eq!(events[0].namespace, "test-ns");
assert_eq!(events[0].outcome, EventOutcome::Error);
assert_eq!(events[0].payload["decision"], "gate_unavailable");
assert!(events[0].payload.get("deny_reason").is_none());
assert_eq!(events[0].payload["resource"]["work_class"], "interactive");
assert_eq!(events[0].payload["resource"]["request_id"], 1_600);
assert!(events[0].payload["resource"].get("cost_unit").is_none());
}
#[tokio::test]
async fn intercepted_deny_remains_distinct_and_does_not_invoke_operation() {
#[derive(Debug)]
struct DenyingGate;
impl Gate for DenyingGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
Ok(GateDecision::deny("intercepted policy denied"))
}
}
let invoked = Arc::new(AtomicUsize::new(0));
let invoked_by_operation = Arc::clone(&invoked);
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.with_gate(Arc::new(DenyingGate));
builder.with_event_store(store.clone());
let registry = builder.build().expect("registry builds");
let err = registry
.dispatch_intercepted_with_identity("list", &Value::Null, None, move |_namespace| {
invoked_by_operation.fetch_add(1, Ordering::SeqCst);
async move { Ok(serde_json::json!({"invoked": true})) }
})
.await
.expect_err("explicit gate denial must refuse intercepted dispatch");
assert!(matches!(
err,
RuntimeError::PermissionDenied { ref verb, ref reason }
if verb == "list" && reason == "intercepted policy denied"
));
assert_eq!(invoked.load(Ordering::SeqCst), 0);
let events = store.events.lock().unwrap();
assert_eq!(events.len(), 1);
assert_eq!(events[0].outcome, EventOutcome::Denied);
assert_eq!(events[0].payload["decision"], "deny");
assert_eq!(
events[0].payload["deny_reason"],
"intercepted policy denied"
);
}
#[tokio::test]
async fn intercepted_git_digest_uses_the_same_receipt_contract() {
let project_id = uuid::Uuid::new_v4();
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.with_event_store(store.clone());
let registry = builder.build().expect("registry builds");
let result = registry
.dispatch_intercepted_with_identity(
"git.digest",
&serde_json::json!({}),
Some(&RequestIdentity {
namespace: Namespace::local().as_str().to_string(),
request_id: Some(1_647),
..Default::default()
}),
|_namespace| async move {
Ok(serde_json::json!({
"project_id": project_id,
"commits_ingested": 7,
"done": true,
}))
},
)
.await
.expect("intercepted digest is durably receipted");
let event = only_git_digest_event(&store);
assert_eq!(result["receipt_id"], serde_json::json!(event.id));
assert_eq!(event.payload["result"], result);
assert_eq!(event.payload["resource"]["request_id"], 1_647);
}
#[tokio::test]
async fn intercepted_git_digest_receipt_preserves_typed_metadata() {
let project_id = uuid::Uuid::new_v4();
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.with_event_store(store.clone());
let registry = builder.build().expect("registry builds");
let outcome = registry
.dispatch_intercepted_with_metadata_with_identity(
"git.digest",
&serde_json::json!({}),
None,
|_namespace| async move {
Ok(InterceptedDispatchResult::new(
serde_json::json!({
"project_id": project_id,
"commits_ingested": 3,
"done": true,
}),
vec!["backend-a".to_string(), "backend-b".to_string()],
))
},
)
.await
.expect("metadata-bearing digest is durably receipted");
let event = only_git_digest_event(&store);
assert_eq!(outcome.result["receipt_id"], serde_json::json!(event.id));
assert_eq!(event.payload["result"], outcome.result);
assert_eq!(outcome.metadata, ["backend-a", "backend-b"]);
}
#[tokio::test]
async fn intercepted_malformed_git_digest_appends_one_generic_error_audit() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.with_event_store(store.clone());
let registry = builder.build().expect("registry builds");
let err = registry
.dispatch_intercepted_with_identity(
"git.digest",
&serde_json::json!({}),
None,
|_namespace| async {
Ok(serde_json::json!({
"project_id": "not-a-uuid",
"done": true,
}))
},
)
.await
.expect_err("malformed intercepted receipt must fail the response");
assert!(matches!(
err,
RuntimeError::Internal(ref message)
if message.starts_with("git_digest_receipt_persist_failed:")
));
let event = only_git_digest_event(&store);
assert_eq!(event.outcome, EventOutcome::Error);
assert_eq!(event.payload_schema_version, 1);
assert!(event.payload.get("result").is_none());
let audit: AuditEvent =
serde_json::from_value(event.payload).expect("generic payload remains an AuditEvent");
assert_eq!(audit.verb, "git.digest");
assert_eq!(audit.decision, AuditDecision::Allow);
}
#[tokio::test]
async fn allow_all_gate_default_remains_backward_compatible() {
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
let reg = builder.build().expect("registry builds");
let res = reg.dispatch("list", Value::Null).await.unwrap();
assert_eq!(
res["pack"], "alpha",
"AllowAllGate must allow every verb — backward compat guarantee"
);
let res = reg.dispatch("create", Value::Null).await.unwrap();
assert_eq!(res["pack"], "alpha");
}
#[tokio::test]
async fn deny_gate_returns_permission_denied_pack_never_invoked() {
#[derive(Debug)]
struct AlwaysDenyGate;
impl Gate for AlwaysDenyGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
Ok(GateDecision::deny("test: always deny"))
}
}
#[derive(Debug)]
struct TrackedPack {
invoked: Arc<AtomicUsize>,
}
impl khive_types::Pack for TrackedPack {
const NAME: &'static str = "tracked";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "guarded",
description: "a guarded verb",
visibility: Visibility::Verb,
category: VerbCategory::Assertive,
params: &[],
}];
}
#[async_trait]
impl PackRuntime for TrackedPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
_verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
self.invoked.fetch_add(1, Ordering::SeqCst);
Ok(serde_json::json!({"invoked": true}))
}
}
let invoked = Arc::new(AtomicUsize::new(0));
let mut builder = VerbRegistryBuilder::new();
builder.register(TrackedPack {
invoked: invoked.clone(),
});
builder.with_gate(Arc::new(AlwaysDenyGate));
let reg = builder.build().expect("registry builds");
let err = reg.dispatch("guarded", Value::Null).await.unwrap_err();
assert!(
matches!(err, RuntimeError::PermissionDenied { ref verb, ref reason } if verb == "guarded" && reason.contains("always deny")),
"expected PermissionDenied with verb=guarded and reason, got: {err:?}"
);
assert_eq!(
invoked.load(Ordering::SeqCst),
0,
"pack dispatch MUST NOT be invoked when gate denies"
);
}
#[tokio::test]
async fn update_denial_precedes_id_existence_resolution() {
#[derive(Debug)]
struct AlwaysDenyUpdateGate {
checked: Arc<AtomicUsize>,
}
impl Gate for AlwaysDenyUpdateGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
self.checked.fetch_add(1, Ordering::SeqCst);
Ok(GateDecision::deny("caller has no update capability"))
}
}
#[derive(Debug)]
struct ExistenceOracleUpdatePack {
existing_id: String,
invoked: Arc<AtomicUsize>,
}
impl khive_types::Pack for ExistenceOracleUpdatePack {
const NAME: &'static str = "existence_oracle";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "update",
description: "distinguish a present id from an absent id",
visibility: Visibility::Verb,
category: VerbCategory::Declaration,
params: &[],
}];
}
#[async_trait]
impl PackRuntime for ExistenceOracleUpdatePack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
_verb: &str,
params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
self.invoked.fetch_add(1, Ordering::SeqCst);
match params.get("id").and_then(Value::as_str) {
Some(id) if id == self.existing_id => Ok(serde_json::json!({"updated": id})),
_ => Err(RuntimeError::NotFound("record".to_string())),
}
}
}
let existing_id = uuid::Uuid::new_v4().to_string();
let absent_id = uuid::Uuid::new_v4().to_string();
let invoked = Arc::new(AtomicUsize::new(0));
let checked = Arc::new(AtomicUsize::new(0));
let pack = || ExistenceOracleUpdatePack {
existing_id: existing_id.clone(),
invoked: Arc::clone(&invoked),
};
let mut control_builder = VerbRegistryBuilder::new();
control_builder.register(pack());
let control = control_builder.build().expect("control registry builds");
control
.dispatch("update", serde_json::json!({"id": existing_id.clone()}))
.await
.expect("positive control resolves the present id");
assert!(matches!(
control
.dispatch("update", serde_json::json!({"id": absent_id.clone()}))
.await,
Err(RuntimeError::NotFound(_))
));
assert_eq!(invoked.load(Ordering::SeqCst), 2);
let mut denied_builder = VerbRegistryBuilder::new();
denied_builder.register(pack());
denied_builder.with_gate(Arc::new(AlwaysDenyUpdateGate {
checked: Arc::clone(&checked),
}));
let denied = denied_builder.build().expect("denied registry builds");
let present_error = denied
.dispatch("update", serde_json::json!({"id": existing_id.clone()}))
.await
.expect_err("denied present-id update must not resolve the id");
let absent_error = denied
.dispatch("update", serde_json::json!({"id": absent_id.clone()}))
.await
.expect_err("denied absent-id update must not resolve the id");
let denial = |error: RuntimeError| match error {
RuntimeError::PermissionDenied { verb, reason } => (verb, reason),
other => panic!("expected gate refusal, got {other:?}"),
};
let present_denial = denial(present_error);
let absent_denial = denial(absent_error);
assert_eq!(present_denial.0, "update");
assert_eq!(present_denial.1, "caller has no update capability");
assert_eq!(present_denial, absent_denial);
assert_eq!(
checked.load(Ordering::SeqCst),
2,
"both denied requests must consult the configured gate"
);
assert_eq!(
invoked.load(Ordering::SeqCst),
2,
"neither denied request may reach the existence oracle"
);
}
#[tokio::test]
async fn audit_event_persists_to_event_store_on_allow() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
.await
.unwrap();
let count = store.count_events(EventFilter::default()).await.unwrap();
assert_eq!(count, 1, "one audit event persisted to EventStore on allow");
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
let ev = &page.items[0];
assert_eq!(ev.verb, "list");
assert_eq!(ev.namespace, "test-ns");
assert_eq!(ev.substrate, SubstrateKind::Event);
assert_eq!(ev.outcome, EventOutcome::Success);
}
#[tokio::test]
#[serial(audit_append_failures)]
#[serial(audit_obligation_append_failures)]
async fn audit_append_failure_fails_an_obligation_bearing_dispatch() {
let before = audit_append_failure_count();
let before_obligation = audit_obligation_append_failure_count();
let successful_store = Arc::new(MemoryEventStore::default());
let mut successful_builder = VerbRegistryBuilder::new();
successful_builder.register(AlphaPack);
successful_builder.with_event_store(successful_store);
let successful_registry = successful_builder.build().expect("registry builds");
successful_registry
.dispatch("list", Value::Null)
.await
.expect("successful audit append must not affect dispatch");
assert_eq!(
audit_append_failure_count(),
before,
"successful audit appends must not increment the swallowed-failure counter"
);
assert_eq!(
audit_obligation_append_failure_count(),
before_obligation,
"successful audit appends must not increment the obligation-failure counter"
);
let failing_store = Arc::new(MemoryEventStore {
fail_appends: true,
..MemoryEventStore::default()
});
let mut failing_builder = VerbRegistryBuilder::new();
failing_builder.register(AlphaPack);
failing_builder.with_event_store(failing_store);
let failing_registry = failing_builder.build().expect("registry builds");
let err = failing_registry
.dispatch("list", Value::Null)
.await
.expect_err(
"a persistent obligation-bearing audit commit failure must fail the dispatch",
);
assert!(
matches!(&err, RuntimeError::Internal(message)
if message.contains("audit obligation commit failed")),
"error names the obligation failure so it is distinguishable from a handler error: {err}"
);
assert_eq!(
audit_append_failure_count(),
before,
"an obligation failure must never inflate the swallowed-failure counter"
);
assert_eq!(
audit_obligation_append_failure_count(),
before_obligation + 1,
"the failed obligation append must remain visible to diagnostics"
);
}
#[tokio::test]
#[serial(audit_append_failures)]
#[serial(audit_obligation_append_failures)]
#[serial(config_ledger)]
async fn obligation_failure_reports_a_write_that_already_committed() {
const RETURNED_TOTAL: u64 = 41;
#[derive(Debug)]
struct RecordingWritePack {
committed: Arc<std::sync::Mutex<Vec<TraceEntry>>>,
}
impl Pack for RecordingWritePack {
const NAME: &'static str = "recording_write";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "knowledge.index",
description: "record one committed write",
visibility: Visibility::Verb,
category: VerbCategory::Commissive,
params: &[],
}];
}
#[async_trait]
impl PackRuntime for RecordingWritePack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
_verb: &str,
params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
let name = params
.get("name")
.and_then(Value::as_str)
.unwrap_or("unnamed")
.to_string();
self.committed
.lock()
.expect("committed lock")
.push(TraceEntry::Effect { name: name.clone() });
Ok(serde_json::json!({ "created": name, "total": RETURNED_TOTAL }))
}
}
let committed = Arc::new(std::sync::Mutex::new(Vec::new()));
let failing_store = Arc::new(MemoryEventStore {
fail_appends: true,
trace: Some(Arc::clone(&committed)),
..MemoryEventStore::default()
});
let mut builder = VerbRegistryBuilder::new();
builder.register(RecordingWritePack {
committed: Arc::clone(&committed),
});
builder.with_event_store(failing_store);
let registry = builder.build().expect("registry builds");
let err = registry
.dispatch("knowledge.index", serde_json::json!({"name": "first"}))
.await
.expect_err("an obligation commit failure must fail the dispatch");
assert!(
matches!(&err, RuntimeError::Internal(message)
if message.contains("audit obligation commit failed")),
"the error must name the obligation failure, since that string is what tells a \
caller the effect landed: {err}"
);
let first_pass = committed.lock().expect("committed lock").clone();
let first_effect = TraceEntry::Effect {
name: "first".to_string(),
};
assert_eq!(
first_pass.first(),
Some(&first_effect),
"the handler's effect must land FIRST: an implementation that submitted the \
audit row before dispatching would satisfy every other assertion here"
);
let audit_rows: Vec<&TraceEntry> = first_pass
.iter()
.filter(|entry| matches!(entry, TraceEntry::Audit { .. }))
.collect();
assert!(
!audit_rows.is_empty(),
"an audit row must actually be SUBMITTED; without this assertion the test \
passes against an implementation that returns the same error and never \
builds a row at all, which is a different defect wearing the same error \
string. Trace was {first_pass:?}"
);
let expected_cost_unit = serde_json::json!(RETURNED_TOTAL + 1);
assert!(
audit_rows.iter().any(|entry| matches!(
entry,
TraceEntry::Audit {
outcome: EventOutcome::Success,
verb,
cost_unit: Some(cost_unit),
..
} if verb.as_str() == "knowledge.index" && *cost_unit == expected_cost_unit
)),
"the submitted row must be the SUCCESS row for THIS verb, carrying a resource \
computed FROM the handler's return value. The outcome alone is not enough: an \
implementation that stamps Success on a row built without `ok_val` would \
satisfy an outcome-only assertion while breaking the contract this test \
exists for. The exact value is the discriminator, not the key's presence: \
`resource_payload` inserts `cost_unit` unconditionally, so presence survives a \
static `ok_val`, while {expected_cost_unit} is reachable only from the \
returned `total` of {RETURNED_TOTAL} (`base_weight` 1 + `item_count` \
{RETURNED_TOTAL} * `model_count` 1). Substituting a null or static result \
collapses it to 1, and the error path's `base_resource_payload` omits the key \
entirely (`cost_unit: None` here), so all three implementations are \
distinguishable. Trace was {first_pass:?}"
);
assert_eq!(
first_pass
.iter()
.filter(|entry| **entry == first_effect)
.count(),
1,
"exactly one effect on the first pass"
);
let _ = registry
.dispatch("knowledge.index", serde_json::json!({"name": "first"}))
.await
.expect_err("the retry fails the same way");
assert_eq!(
committed
.lock()
.expect("committed lock")
.iter()
.filter(|entry| **entry == first_effect)
.count(),
2,
"retrying this error double-writes; a caller must re-derive state instead of \
resubmitting"
);
}
#[tokio::test]
#[serial(config_ledger)]
#[serial(audit_append_failures)]
#[serial(audit_obligation_append_failures)]
async fn config_locked_row_degrades_without_failing_the_dispatch_that_observed_it() {
#[derive(Debug)]
struct DenyGate;
impl Gate for DenyGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, khive_gate::GateError> {
Ok(GateDecision::Deny {
reason: "denied for test".to_string(),
})
}
}
crate::config_ledger::record_config_locked("adr133_test_key", "adr133_test_value");
let store = Arc::new(MemoryEventStore {
fail_appends: true,
..MemoryEventStore::default()
});
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(Arc::new(DenyGate));
builder.with_event_store(store);
let registry = builder.build().expect("registry builds");
let err = registry
.dispatch("list", Value::Null)
.await
.expect_err("the gate denies every request");
assert!(
matches!(err, RuntimeError::PermissionDenied { .. }),
"a pure-observability row's failure must never surface as the dispatch error: {err}"
);
let metrics = registry
.audit_batch_metrics()
.expect("with_event_store configures the ADR-133 seam");
assert!(
metrics.degraded,
"the config-locked row's commit failure must be visible as degradation"
);
assert!(metrics.degraded_rows >= 1);
}
#[tokio::test]
#[serial(config_ledger)]
#[serial(audit_append_failures)]
async fn config_locked_row_failure_never_fails_a_dispatch_that_would_otherwise_succeed() {
crate::config_ledger::record_config_locked(
"adr133_success_path_key",
"adr133_success_path_value",
);
let store = Arc::new(MemoryEventStore {
fail_kind: Some(EventKind::ConfigLocked),
..MemoryEventStore::default()
});
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_event_store(store);
let registry = builder.build().expect("registry builds");
let result = registry
.dispatch("list", Value::Null)
.await
.expect("a config-locked row's commit failure must never fail an unrelated dispatch");
assert_eq!(
result,
serde_json::json!({ "pack": "alpha", "verb": "list" })
);
let metrics = registry
.audit_batch_metrics()
.expect("with_event_store configures the ADR-133 seam");
assert!(
metrics.degraded_rows >= 1,
"the config-locked row's failure must remain visible as degradation"
);
}
#[derive(Default)]
struct LegacyEventStore {
events: std::sync::Mutex<Vec<Event>>,
}
#[async_trait]
impl EventStore for LegacyEventStore {
async fn append_event(&self, event: Event) -> khive_storage::StorageResult<()> {
self.events.lock().unwrap().push(event);
Ok(())
}
async fn append_events(
&self,
events: Vec<Event>,
) -> khive_storage::StorageResult<BatchWriteSummary> {
let attempted = events.len() as u64;
self.events.lock().unwrap().extend(events);
Ok(BatchWriteSummary {
attempted,
affected: attempted,
failed: 0,
first_error: String::new(),
})
}
async fn get_event(&self, id: uuid::Uuid) -> khive_storage::StorageResult<Option<Event>> {
Ok(self
.events
.lock()
.unwrap()
.iter()
.find(|e| e.id == id)
.cloned())
}
async fn query_events(
&self,
_filter: EventFilter,
_page: PageRequest,
) -> khive_storage::StorageResult<Page<Event>> {
let items = self.events.lock().unwrap().clone();
let total = items.len() as u64;
Ok(Page {
items,
total: Some(total),
})
}
async fn count_events(&self, _filter: EventFilter) -> khive_storage::StorageResult<u64> {
Ok(self.events.lock().unwrap().len() as u64)
}
}
#[test]
fn build_rejects_a_configured_event_store_incompatible_with_the_audit_batch_seam() {
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_event_store(Arc::new(LegacyEventStore::default()));
let err = match builder.build() {
Ok(_) => {
panic!("a store that cannot implement the seam must not build a healthy registry")
}
Err(err) => err,
};
assert!(
matches!(&err, RuntimeError::IncompatibleEventStore(message)
if message.contains("supports_idempotent_audit_batch")),
"error names the missing capability so an operator can act on it: {err}"
);
}
#[tokio::test]
#[serial(config_ledger)]
#[serial(audit_append_failures)]
#[serial(audit_obligation_append_failures)]
async fn db_diagnostics_with_audit_metrics_reports_batch_failure_and_degradation() {
crate::config_ledger::record_config_locked(
"adr133_diag_test_key",
"adr133_diag_test_value",
);
let store = Arc::new(MemoryEventStore {
fail_appends: true,
..MemoryEventStore::default()
});
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_event_store(store);
let registry = builder.build().expect("registry builds");
let _ = registry.dispatch("list", Value::Null).await;
let metrics = registry
.audit_batch_metrics()
.expect("with_event_store configures the ADR-133 seam");
assert!(metrics.degraded, "the config-locked row must have degraded");
assert!(metrics.degraded_rows >= 1);
assert!(
metrics.flush_failures >= 1,
"the list dispatch's obligation row must count as a flush failure"
);
let rt = KhiveRuntime::memory().expect("memory runtime should create");
let report = rt
.db_diagnostics_with_audit_metrics(Some(metrics))
.await
.expect("diagnostics succeed");
assert_eq!(report.writer_contention.audit_degraded, Some(true));
assert!(report.writer_contention.audit_degraded_rows.unwrap_or(0) >= 1);
assert!(
report
.writer_contention
.audit_batch_flush_failures
.unwrap_or(0)
>= 1
);
assert!(report
.writer_contention
.audit_batch_flush_failures_unavailable_reason
.is_none());
assert!(report
.writer_contention
.audit_degraded_unavailable_reason
.is_none());
let bare_report = rt.db_diagnostics().await.expect("diagnostics succeed");
assert!(bare_report.writer_contention.audit_degraded.is_none());
assert!(bare_report
.writer_contention
.audit_degraded_unavailable_reason
.is_some());
assert!(bare_report
.writer_contention
.audit_admission_refused_obligations
.is_none());
assert!(bare_report
.writer_contention
.audit_admission_refused_obligations_unavailable_reason
.is_some());
assert!(bare_report
.writer_contention
.audit_admission_unresolved_obligations
.is_none());
assert!(bare_report
.writer_contention
.audit_admission_unresolved_obligations_unavailable_reason
.is_some());
}
#[tokio::test]
async fn audit_event_duration_us_reflects_measured_dispatch_time() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(SleepingPack);
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("slow_op", serde_json::json!({}))
.await
.unwrap();
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(page.items.len(), 1);
let ev = &page.items[0];
assert!(
ev.duration_us >= 10_000,
"duration_us must reflect the ~20ms measured dispatch time, got {}",
ev.duration_us
);
}
#[tokio::test]
async fn dispatch_unknown_verb_allowed_by_gate_still_persists_audit_row() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
let result = reg.dispatch("no_such_verb", serde_json::json!({})).await;
assert!(result.is_err(), "unknown verb must still return an error");
let count = store.count_events(EventFilter::default()).await.unwrap();
assert_eq!(
count, 1,
"an allowed-but-unknown verb must still persist one audit row"
);
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(page.items[0].duration_us, 0);
assert_eq!(page.items[0].outcome, EventOutcome::Error);
}
#[tokio::test]
async fn audit_event_persists_to_event_store_on_deny() {
#[derive(Debug)]
struct AlwaysDenyGate;
impl Gate for AlwaysDenyGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
Ok(GateDecision::deny("denied by test"))
}
}
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(Arc::new(AlwaysDenyGate));
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
let err = reg
.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
.await
.unwrap_err();
assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
let count = store.count_events(EventFilter::default()).await.unwrap();
assert_eq!(count, 1, "one audit event persisted to EventStore on deny");
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
let ev = &page.items[0];
assert_eq!(ev.verb, "list");
assert_eq!(ev.outcome, EventOutcome::Denied);
}
#[tokio::test]
async fn gate_error_returns_typed_refusal_without_invoking_pack() {
#[derive(Debug)]
struct FailingGate;
impl Gate for FailingGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, khive_gate::GateError> {
Err(khive_gate::GateError::Internal("gate broken".into()))
}
}
let store = Arc::new(MemoryEventStore::default());
let invoked = Arc::new(AtomicUsize::new(0));
let mut builder = VerbRegistryBuilder::new();
builder.register(GateErrorTrackingPack {
invoked: Arc::clone(&invoked),
});
builder.with_gate(Arc::new(FailingGate));
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
let err = reg
.dispatch("guarded", Value::Null)
.await
.expect_err("gate unavailability must refuse normal dispatch");
assert!(matches!(
err,
RuntimeError::GateUnavailable { ref verb, ref reason }
if verb == "guarded"
&& reason == "gate backend unavailable"
&& !reason.contains("gate broken")
));
assert_eq!(
invoked.load(Ordering::SeqCst),
0,
"pack handler must not run after a gate infrastructure error"
);
let count = store.count_events(EventFilter::default()).await.unwrap();
assert_eq!(count, 1, "gate infrastructure error must be audited");
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
let event = &page.items[0];
assert_eq!(event.verb, "guarded");
assert_eq!(event.outcome, EventOutcome::Error);
assert_eq!(event.payload["decision"], "gate_unavailable");
assert!(event.payload.get("deny_reason").is_none());
assert_eq!(event.payload["resource"]["work_class"], "interactive");
assert!(event.payload["resource"].get("cost_unit").is_none());
}
#[tokio::test]
#[serial(audit_append_failures)]
async fn gate_error_audit_failure_cannot_reopen_dispatch_or_replace_typed_error() {
#[derive(Debug)]
struct FailingGate;
impl Gate for FailingGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
Err(GateError::Internal("gate still broken".into()))
}
}
let before = audit_append_failure_count();
let invoked = Arc::new(AtomicUsize::new(0));
let store = Arc::new(MemoryEventStore {
fail_appends: true,
..MemoryEventStore::default()
});
let mut builder = VerbRegistryBuilder::new();
builder.register(GateErrorTrackingPack {
invoked: Arc::clone(&invoked),
});
builder.with_gate(Arc::new(FailingGate));
builder.with_event_store(store);
let registry = builder.build().expect("registry builds");
let error = registry
.dispatch("guarded", Value::Null)
.await
.expect_err("audit persistence failure must not reopen dispatch");
assert!(matches!(
error,
RuntimeError::GateUnavailable { ref verb, ref reason }
if verb == "guarded"
&& reason == "gate backend unavailable"
&& !reason.contains("gate still broken")
));
assert_eq!(invoked.load(Ordering::SeqCst), 0);
assert_eq!(
audit_append_failure_count(),
before + 1,
"best-effort audit failure remains diagnostic without changing the refusal"
);
}
#[tokio::test]
async fn gate_unavailable_reason_never_carries_backend_error_text() {
const CANARY: &str = "postgres://svc:not-a-real-secret@internal-host";
#[derive(Debug)]
struct FailingGate;
impl Gate for FailingGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
Err(GateError::Internal(CANARY.to_string()))
}
}
let mut builder = VerbRegistryBuilder::new();
builder.register(GateErrorTrackingPack {
invoked: Arc::new(AtomicUsize::new(0)),
});
builder.with_gate(Arc::new(FailingGate));
let registry = builder.build().expect("registry builds");
let err = registry
.dispatch("guarded", Value::Null)
.await
.expect_err("gate unavailability must refuse dispatch");
let RuntimeError::GateUnavailable { reason, .. } = &err else {
panic!("expected GateUnavailable, got {err:?}");
};
assert!(
!reason.contains(CANARY),
"caller-visible reason must not embed backend error text: {reason:?}"
);
assert!(
!reason.contains("svc") && !reason.contains("internal-host"),
"caller-visible reason must not embed backend error fragments: {reason:?}"
);
assert_eq!(reason, "gate backend unavailable");
let rendered = err.to_string();
assert!(
!rendered.contains(CANARY),
"top-level Display must not embed backend error text either: {rendered:?}"
);
}
#[tokio::test]
async fn gate_policy_error_classifies_distinctly_from_backend_unavailable() {
#[derive(Debug)]
struct PolicyBrokenGate;
impl Gate for PolicyBrokenGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
Err(GateError::Policy(
"rule set has no allow clause for this namespace".to_string(),
))
}
}
let mut builder = VerbRegistryBuilder::new();
builder.register(GateErrorTrackingPack {
invoked: Arc::new(AtomicUsize::new(0)),
});
builder.with_gate(Arc::new(PolicyBrokenGate));
let registry = builder.build().expect("registry builds");
let err = registry
.dispatch("guarded", Value::Null)
.await
.expect_err("gate unavailability must refuse dispatch");
assert!(matches!(
err,
RuntimeError::GateUnavailable { ref verb, ref reason }
if verb == "guarded"
&& reason == "gate policy evaluation failed"
&& !reason.contains("rule set has no allow clause")
));
}
#[tokio::test]
async fn no_event_store_configured_tracing_only() {
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
let reg = builder.build().expect("registry builds");
let res = reg.dispatch("list", Value::Null).await.unwrap();
assert_eq!(res["pack"], "alpha");
}
#[test]
#[serial]
fn dispatch_tracing_emits_gate_check_event_with_deny_payload() {
#[derive(Debug)]
struct TracingDenyGate;
impl Gate for TracingDenyGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
Ok(GateDecision::deny("denied by test gate"))
}
fn impl_name(&self) -> &'static str {
"TracingDenyGate"
}
}
let events = capture_dispatch_events(async {
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(Arc::new(TracingDenyGate));
let reg = builder.build().expect("registry builds");
let _ = reg.dispatch("create", serde_json::Value::Null).await;
});
let gate_events = gate_check_events_for(&events, "TracingDenyGate");
assert_eq!(
gate_events.len(),
1,
"exactly one gate.check tracing event per dispatch (deny); got {gate_events:?}"
);
let payload = gate_events[0]
.audit_event
.as_ref()
.expect("gate.check event must carry an audit_event field on Deny");
let audit: khive_gate::AuditEvent =
serde_json::from_str(payload).expect("audit_event payload must decode to AuditEvent");
assert_eq!(audit.decision, AuditDecision::Deny);
assert_eq!(audit.deny_reason.as_deref(), Some("denied by test gate"));
assert_eq!(audit.gate_impl, "TracingDenyGate");
let payload_json: serde_json::Value =
serde_json::from_str(payload).expect("payload must be valid JSON");
assert_eq!(
payload_json["obligations"],
serde_json::Value::Array(Vec::new()),
"obligations must be `[]` on Deny on the tracing payload, not omitted"
);
}
#[tokio::test]
async fn audit_envelope_round_trips_deny_reason_and_gate_impl_through_event_store() {
#[derive(Debug)]
struct DenyGateWithName;
impl Gate for DenyGateWithName {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
Ok(GateDecision::deny("policy: write forbidden for anon"))
}
fn impl_name(&self) -> &'static str {
"DenyGateWithName"
}
}
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(Arc::new(DenyGateWithName));
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
let err = reg
.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
.await
.unwrap_err();
assert!(
matches!(err, RuntimeError::PermissionDenied { .. }),
"expected PermissionDenied, got {err:?}"
);
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(
page.items.len(),
1,
"one audit event must be persisted on deny"
);
let ev = &page.items[0];
assert_eq!(ev.outcome, EventOutcome::Denied);
let data = &ev.payload;
let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
.expect("Event.payload must deserialize to AuditEvent");
assert_eq!(
audit.deny_reason.as_deref(),
Some("policy: write forbidden for anon"),
"deny_reason must be preserved through EventStore"
);
assert_eq!(
audit.gate_impl, "DenyGateWithName",
"gate_impl must be preserved through EventStore"
);
assert_eq!(
audit.decision,
khive_gate::AuditDecision::Deny,
"decision field must be preserved through EventStore"
);
}
#[tokio::test]
async fn audit_envelope_round_trips_obligations_through_event_store() {
use khive_gate::Obligation;
#[derive(Debug)]
struct ObligationGate;
impl Gate for ObligationGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
Ok(GateDecision::allow_with(vec![Obligation::Audit {
tag: "billing.meter".into(),
}]))
}
fn impl_name(&self) -> &'static str {
"ObligationGate"
}
}
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(Arc::new(ObligationGate));
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
.await
.unwrap();
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(page.items.len(), 1);
let ev = &page.items[0];
assert_eq!(ev.outcome, EventOutcome::Success);
let data = &ev.payload;
let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
.expect("Event.payload must deserialize to AuditEvent");
assert_eq!(audit.gate_impl, "ObligationGate");
assert_eq!(
audit.obligations.len(),
1,
"obligations must be preserved through EventStore"
);
match &audit.obligations[0] {
Obligation::Audit { tag } => assert_eq!(tag, "billing.meter"),
other => panic!("expected Audit obligation, got {other:?}"),
}
}
#[tokio::test]
async fn sql_backed_audit_envelope_round_trips_deny_reason_gate_impl_and_obligations() {
#[derive(Debug)]
struct SqlTestDenyGate;
impl Gate for SqlTestDenyGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
Ok(GateDecision::deny("sql-path: write denied"))
}
fn impl_name(&self) -> &'static str {
"SqlTestDenyGate"
}
}
let rt = KhiveRuntime::memory().expect("in-memory runtime");
let test_tok = NamespaceToken::for_namespace(Namespace::parse("test-ns").unwrap());
let sql_store = rt
.events(&test_tok)
.expect("events_for_namespace must succeed");
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(Arc::new(SqlTestDenyGate));
builder.with_event_store(sql_store.clone());
let reg = builder.build().expect("registry builds");
let err = reg
.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
.await
.unwrap_err();
assert!(
matches!(err, RuntimeError::PermissionDenied { .. }),
"expected PermissionDenied, got {err:?}"
);
let page = sql_store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(
page.items.len(),
1,
"one audit event must be persisted on deny through SqlEventStore"
);
let ev = &page.items[0];
assert_eq!(ev.outcome, EventOutcome::Denied);
let data = &ev.payload;
let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
.expect("Event.payload must deserialize to AuditEvent after SQL round-trip");
assert_eq!(
audit.deny_reason.as_deref(),
Some("sql-path: write denied"),
"deny_reason must survive the SQL text round-trip"
);
assert_eq!(
audit.gate_impl, "SqlTestDenyGate",
"gate_impl must survive the SQL text round-trip"
);
assert_eq!(
audit.decision,
khive_gate::AuditDecision::Deny,
"decision field must survive the SQL text round-trip"
);
assert!(
audit.obligations.is_empty(),
"obligations must be preserved as empty [] through SQL round-trip"
);
}
#[tokio::test]
async fn sql_backed_audit_envelope_round_trips_non_empty_obligations() {
use khive_gate::Obligation;
#[derive(Debug)]
struct SqlTestAllowWithObligationGate;
impl Gate for SqlTestAllowWithObligationGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
Ok(GateDecision::allow_with(vec![Obligation::Audit {
tag: "sql-path-billing.meter".into(),
}]))
}
fn impl_name(&self) -> &'static str {
"SqlTestAllowWithObligationGate"
}
}
let rt = KhiveRuntime::memory().expect("in-memory runtime");
let test_tok = NamespaceToken::for_namespace(Namespace::parse("test-ns").unwrap());
let sql_store = rt
.events(&test_tok)
.expect("events_for_namespace must succeed");
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(Arc::new(SqlTestAllowWithObligationGate));
builder.with_event_store(sql_store.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
.await
.expect("dispatch must succeed when gate allows");
let page = sql_store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(
page.items.len(),
1,
"one audit event must be persisted on allow through SqlEventStore"
);
let ev = &page.items[0];
assert_eq!(ev.outcome, EventOutcome::Success);
let data = &ev.payload;
let obligations_raw = data
.get("obligations")
.expect("Event.data JSON must contain 'obligations' key");
let obligations_arr = obligations_raw
.as_array()
.expect("'obligations' must be a JSON array");
assert!(
!obligations_arr.is_empty(),
"raw Event.data['obligations'] must be non-empty after SQL round-trip"
);
let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
.expect("Event.data must deserialize to AuditEvent after SQL round-trip");
assert_eq!(
audit.gate_impl, "SqlTestAllowWithObligationGate",
"gate_impl must survive the SQL text round-trip"
);
assert_eq!(
audit.decision,
khive_gate::AuditDecision::Allow,
"decision field must survive the SQL text round-trip"
);
assert_eq!(
audit.obligations.len(),
1,
"obligations must be non-empty after SQL round-trip (not silently defaulted to [])"
);
match &audit.obligations[0] {
Obligation::Audit { tag } => assert_eq!(
tag, "sql-path-billing.meter",
"Audit obligation tag must survive the SQL text round-trip"
),
other => panic!("expected Audit obligation, got {other:?}"),
}
}
#[tokio::test]
async fn audit_event_payload_shape_for_create_verb() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_event_store(store.clone());
builder.with_default_namespace("test-ns");
let reg = builder.build().expect("registry builds");
reg.dispatch("create", serde_json::json!({"namespace": "test-ns"}))
.await
.unwrap();
let count = store.count_events(EventFilter::default()).await.unwrap();
assert_eq!(count, 1, "exactly one audit event for one dispatch");
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
let ev = &page.items[0];
assert_eq!(ev.verb, "create", "ev.verb must be the dispatched verb");
assert_eq!(
ev.outcome,
EventOutcome::Success,
"ev.outcome must be Success on allow"
);
assert_eq!(
ev.namespace, "test-ns",
"ev.namespace must match the dispatch namespace"
);
let data = &ev.payload;
let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
.expect("ev.payload must deserialize to AuditEvent");
assert_eq!(
audit.decision,
khive_gate::AuditDecision::Allow,
"AuditEvent.decision must be Allow"
);
assert_eq!(audit.verb, "create", "AuditEvent.verb must be 'create'");
assert_eq!(
audit.namespace, "test-ns",
"AuditEvent.namespace must be preserved"
);
assert_eq!(
audit.gate_impl, "AllowAllGate",
"AuditEvent.gate_impl must name the gate implementation"
);
assert!(
audit.deny_reason.is_none(),
"AuditEvent.deny_reason must be None on Allow"
);
let payload_json: serde_json::Value =
serde_json::from_value(data.clone()).expect("data must be valid JSON");
assert_eq!(
payload_json["obligations"],
serde_json::Value::Array(Vec::new()),
"obligations must be [] on AllowAllGate"
);
}
struct EmbeddingAwarePack {
models: Vec<String>,
}
impl khive_types::Pack for EmbeddingAwarePack {
const NAME: &'static str = "embedding_aware";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &["widget"];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "create",
description: "create a widget (embedding-aware stub)",
visibility: Visibility::Verb,
category: VerbCategory::Commissive,
params: &[],
}];
}
#[async_trait]
impl PackRuntime for EmbeddingAwarePack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
fn registered_embedding_model_names(&self) -> Vec<String> {
self.models.clone()
}
async fn dispatch(
&self,
verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Ok(serde_json::json!({ "pack": "embedding_aware", "verb": verb }))
}
}
struct FailingProbePack;
impl khive_types::Pack for FailingProbePack {
const NAME: &'static str = "failing_probe";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "probe",
description: "always fails",
visibility: Visibility::Verb,
category: VerbCategory::Assertive,
params: &[],
}];
}
#[async_trait]
impl PackRuntime for FailingProbePack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
_verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::InvalidInput("boom".into()))
}
}
#[tokio::test]
async fn resource_cost_unit_present_on_non_embedding_successful_dispatch() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("list", serde_json::json!({})).await.unwrap();
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(page.items.len(), 1);
assert_eq!(
page.items[0].payload["resource"],
serde_json::json!({"work_class": "interactive", "cost_unit": 1}),
"non-embedding-bearing verb's resource.cost_unit must be base_weight(verb) alone"
);
}
#[tokio::test]
async fn resource_cost_unit_scales_with_registered_model_count_for_create() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(EmbeddingAwarePack {
models: vec!["all-minilm-l6-v2".into(), "paraphrase".into()],
});
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("create", serde_json::json!({"kind": "widget"}))
.await
.unwrap();
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(
page.items[0].payload["resource"],
serde_json::json!({"work_class": "interactive", "cost_unit": 3}),
);
}
#[tokio::test]
async fn resource_cost_unit_zero_registered_models_is_base_weight_only() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(EmbeddingAwarePack { models: vec![] });
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("create", serde_json::json!({"kind": "widget"}))
.await
.unwrap();
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(
page.items[0].payload["resource"]["cost_unit"], 1,
"zero registered embedding models must vanish the term, not error or omit"
);
}
#[tokio::test]
async fn resource_work_class_present_cost_unit_absent_when_dispatch_returns_error() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(FailingProbePack);
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
let err = reg
.dispatch("probe", serde_json::json!({}))
.await
.unwrap_err();
assert!(matches!(err, RuntimeError::InvalidInput(_)));
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(page.items.len(), 1);
assert_eq!(page.items[0].outcome, EventOutcome::Error);
assert_eq!(
page.items[0].payload["resource"],
serde_json::json!({"work_class": "interactive"}),
"resource must carry work_class with cost_unit OMITTED (never 0) on an \
errored dispatch: {:?}",
page.items[0].payload
);
}
#[tokio::test]
async fn resource_work_class_present_cost_unit_absent_when_no_pack_owns_the_verb() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
let _ = reg
.dispatch("no_such_verb_resource_test", serde_json::json!({}))
.await;
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(page.items.len(), 1);
assert_eq!(
page.items[0].payload["resource"],
serde_json::json!({"work_class": "interactive"})
);
}
#[tokio::test]
async fn resource_work_class_present_cost_unit_absent_on_denied_dispatch() {
#[derive(Debug)]
struct AlwaysDenyGate;
impl Gate for AlwaysDenyGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
Ok(GateDecision::deny("test: always deny"))
}
}
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(Arc::new(AlwaysDenyGate));
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
let _ = reg.dispatch("list", serde_json::json!({})).await;
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(page.items.len(), 1);
assert_eq!(page.items[0].outcome, EventOutcome::Denied);
assert_eq!(
page.items[0].payload["resource"],
serde_json::json!({"work_class": "interactive"})
);
}
#[tokio::test]
async fn resource_cost_unit_present_on_link_singleton_success() {
let store = Arc::new(MemoryEventStore::default());
let edge_id = uuid::Uuid::new_v4();
let source_id = uuid::Uuid::new_v4();
let target_id = uuid::Uuid::new_v4();
let edge_json = serde_json::json!({
"id": edge_id,
"namespace": "local",
"source_id": source_id,
"target_id": target_id,
"relation": "depends_on",
"weight": 1.0,
});
let mut builder = VerbRegistryBuilder::new();
builder.register(LinkResultPack::ok(edge_json));
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch(
"link",
serde_json::json!({
"source_id": source_id,
"target_id": target_id,
"relation": "depends_on",
}),
)
.await
.unwrap();
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(
page.items[0].payload["resource"],
serde_json::json!({"work_class": "interactive", "cost_unit": 1}),
"link has no embedding-bearing path -> base_weight(link) alone, even on the v2-enriched singleton path"
);
}
#[tokio::test]
async fn resource_work_class_present_cost_unit_absent_on_link_dispatch_failure() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(LinkResultPack::err("target endpoint not found"));
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
let _ = reg
.dispatch(
"link",
serde_json::json!({
"source_id": "note:alpha",
"target_id": "note:missing",
"relation": "depends_on",
}),
)
.await;
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(page.items.len(), 1);
assert_eq!(
page.items[0].payload["resource"],
serde_json::json!({"work_class": "interactive"})
);
}
#[tokio::test]
async fn audit_event_threads_target_id_from_dispatch_args() {
let store = Arc::new(MemoryEventStore::default());
let target = uuid::Uuid::new_v4();
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_event_store(store.clone());
builder.with_default_namespace("test-ns");
let reg = builder.build().expect("registry builds");
reg.dispatch(
"create",
serde_json::json!({"namespace": "test-ns", "target_id": target}),
)
.await
.unwrap();
let page = store
.query_events(
EventFilter::default(),
PageRequest {
offset: 0,
limit: 10,
},
)
.await
.unwrap();
assert_eq!(
page.items[0].target_id,
Some(target),
"#282: audit event must carry target_id from dispatch params"
);
}
struct LinkResultPack {
result: std::sync::Mutex<Option<Result<Value, RuntimeError>>>,
}
impl LinkResultPack {
fn ok(value: Value) -> Self {
Self {
result: std::sync::Mutex::new(Some(Ok(value))),
}
}
fn err(message: &str) -> Self {
Self {
result: std::sync::Mutex::new(Some(Err(RuntimeError::InvalidInput(
message.to_string(),
)))),
}
}
}
impl khive_types::Pack for LinkResultPack {
const NAME: &'static str = "kg";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "link",
description: "test link handler",
visibility: Visibility::Verb,
category: VerbCategory::Commissive,
params: &[],
}];
}
#[async_trait]
impl PackRuntime for LinkResultPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
_verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
self.result
.lock()
.unwrap()
.take()
.expect("LinkResultPack dispatch called more than once in a test")
}
}
#[tokio::test]
async fn link_audit_enriches_successful_singleton_with_edge_v2() {
let store = Arc::new(MemoryEventStore::default());
let edge_id = uuid::Uuid::new_v4();
let source_id = uuid::Uuid::new_v4();
let target_id = uuid::Uuid::new_v4();
let edge_json = serde_json::json!({
"id": edge_id,
"namespace": "local",
"source_id": source_id,
"target_id": target_id,
"relation": "depends_on",
"weight": 1.0,
});
let mut builder = VerbRegistryBuilder::new();
builder.register(LinkResultPack::ok(edge_json));
builder.with_event_store(store.clone());
builder.with_default_namespace("test-ns");
let reg = builder.build().expect("registry builds");
reg.dispatch(
"link",
serde_json::json!({
"source_id": source_id,
"target_id": target_id,
"relation": "depends_on",
}),
)
.await
.unwrap();
let count = store.count_events(EventFilter::default()).await.unwrap();
assert_eq!(
count, 1,
"exactly one deferred audit row must be persisted for a successful singleton link"
);
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
let ev = &page.items[0];
assert_eq!(ev.verb, "link");
assert_eq!(ev.outcome, EventOutcome::Success);
assert_eq!(
ev.payload_schema_version, 2,
"successful singleton link uses audit schema v2"
);
assert_eq!(
ev.target_id,
Some(edge_id),
"target_id must be the created/resolved edge id, not a raw caller arg"
);
assert_eq!(ev.payload["edge_id"], serde_json::json!(edge_id));
assert_eq!(ev.payload["source_id"], serde_json::json!(source_id));
assert_eq!(ev.payload["target_id"], serde_json::json!(target_id));
assert_eq!(ev.payload["relation"], "depends_on");
assert_eq!(ev.payload["weight"], 1.0);
assert_eq!(ev.payload["verb"], "link");
assert_eq!(ev.payload["decision"], "allow");
assert!(ev.payload.get("gate_impl").is_some());
}
#[tokio::test]
async fn link_audit_falls_back_to_v1_when_dispatch_fails() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(LinkResultPack::err("target endpoint not found"));
builder.with_event_store(store.clone());
builder.with_default_namespace("test-ns");
let reg = builder.build().expect("registry builds");
let err = reg
.dispatch(
"link",
serde_json::json!({
"source_id": "note:alpha",
"target_id": "note:missing",
"relation": "depends_on",
}),
)
.await
.unwrap_err();
assert!(
matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("not found")),
"the original dispatch error must be returned unchanged"
);
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(
page.items.len(),
1,
"a v1 fallback audit row must still be persisted on dispatch failure"
);
let ev = &page.items[0];
assert_eq!(
ev.payload_schema_version, 1,
"failed link keeps the v1 audit shape"
);
assert_eq!(
ev.outcome,
EventOutcome::Error,
"outcome reflects the dispatch result (Err), not the gate decision (Allow)"
);
assert!(
ev.duration_us >= 0,
"duration_us must still be populated (measured, not the Event::new \
default sentinel) on a failed dispatch"
);
assert!(
ev.target_id.is_none(),
"non-UUID caller-supplied ids do not spuriously populate target_id"
);
assert!(
ev.payload.get("edge_id").is_none(),
"v1 fallback must not carry edge enrichment fields"
);
let _: khive_gate::AuditEvent = serde_json::from_value(ev.payload.clone())
.expect("v1 fallback payload must deserialize as AuditEvent");
}
#[tokio::test]
async fn link_audit_falls_back_to_v1_when_result_missing_edge_fields() {
let store = Arc::new(MemoryEventStore::default());
let target_arg = uuid::Uuid::new_v4();
let mut builder = VerbRegistryBuilder::new();
builder.register(LinkResultPack::ok(serde_json::json!({"ok": true})));
builder.with_event_store(store.clone());
builder.with_default_namespace("test-ns");
let reg = builder.build().expect("registry builds");
reg.dispatch(
"link",
serde_json::json!({
"source_id": uuid::Uuid::new_v4(),
"target_id": target_arg,
"relation": "depends_on",
}),
)
.await
.unwrap();
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(page.items.len(), 1);
let ev = &page.items[0];
assert_eq!(
ev.payload_schema_version, 1,
"an unparsable success result falls back to v1 rather than dropping the audit row"
);
assert_eq!(ev.outcome, EventOutcome::Success);
assert_eq!(
ev.target_id,
Some(target_arg),
"v1 fallback still extracts target_id from the raw dispatch args"
);
assert!(ev.payload.get("edge_id").is_none());
}
#[tokio::test]
async fn link_audit_bulk_links_get_no_enrichment() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(LinkResultPack::ok(serde_json::json!({
"attempted": 2, "created": 2, "skipped": 0, "failed": 0
})));
builder.with_event_store(store.clone());
builder.with_default_namespace("test-ns");
let reg = builder.build().expect("registry builds");
reg.dispatch(
"link",
serde_json::json!({
"links": [
{"source_id": "a", "target_id": "b", "relation": "depends_on"},
{"source_id": "c", "target_id": "d", "relation": "depends_on"},
],
}),
)
.await
.unwrap();
let count = store.count_events(EventFilter::default()).await.unwrap();
assert_eq!(
count, 1,
"bulk `links` gets exactly one v1 audit row (deferred until dispatch \
resolves like every other Allow-outcome row since ADR-103 Stage 1, \
but never v2-enriched — enrichment is singleton-`link`-only)"
);
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
let ev = &page.items[0];
assert_eq!(
ev.payload_schema_version, 1,
"bulk link mode is out of scope for #676's events.target_id enrichment"
);
assert!(ev.target_id.is_none());
}
#[test]
fn link_audit_success_from_result_extracts_edge_fields() {
let gate_req = GateRequest::new(
ActorRef::anonymous(),
Namespace::local(),
"link",
serde_json::json!({}),
);
let decision = GateDecision::Allow {
obligations: vec![],
};
let audit = AuditEvent::from_check(&gate_req, &decision, "AllowAllGate");
let edge_id = uuid::Uuid::new_v4();
let source_id = uuid::Uuid::new_v4();
let target_id = uuid::Uuid::new_v4();
let result = serde_json::json!({
"id": edge_id,
"source_id": source_id,
"target_id": target_id,
"relation": "depends_on",
"weight": 0.5,
});
let (returned_id, payload) = link_audit_success_from_result(audit, &result)
.expect("well-formed edge JSON must produce an enriched payload");
assert_eq!(returned_id, edge_id);
assert_eq!(payload["edge_id"], serde_json::json!(edge_id));
assert_eq!(payload["relation"], "depends_on");
assert_eq!(payload["weight"], 0.5);
assert_eq!(
payload["verb"], "link",
"v1 AuditEvent fields must flatten into the v2 payload"
);
}
#[test]
fn link_audit_success_from_result_rejects_incomplete_or_malformed_result() {
let gate_req = GateRequest::new(
ActorRef::anonymous(),
Namespace::local(),
"link",
serde_json::json!({}),
);
let decision = GateDecision::Allow {
obligations: vec![],
};
let audit = AuditEvent::from_check(&gate_req, &decision, "AllowAllGate");
assert!(
link_audit_success_from_result(
audit.clone(),
&serde_json::json!({"id": uuid::Uuid::new_v4()}),
)
.is_none(),
"missing source_id/target_id/relation/weight must not enrich"
);
assert!(
link_audit_success_from_result(audit, &serde_json::json!({"id": "not-a-uuid"}))
.is_none(),
"a non-UUID id must not enrich"
);
}
async fn first_event(store: &Arc<MemoryEventStore>) -> Event {
let page = store
.query_events(
EventFilter::default(),
PageRequest {
limit: 10,
offset: 0,
},
)
.await
.unwrap();
assert_eq!(
page.items.len(),
1,
"expected exactly one persisted audit event"
);
page.items[0].clone()
}
#[tokio::test]
async fn dispatch_with_identity_stamps_request_id_on_success() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch_with_identity(
"list",
serde_json::json!({"namespace": "test-ns"}),
Some(RequestIdentity {
request_id: Some(101),
..Default::default()
}),
)
.await
.unwrap();
let ev = first_event(&store).await;
assert_eq!(ev.outcome, EventOutcome::Success);
assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(101));
}
#[tokio::test]
async fn dispatch_with_identity_stamps_request_id_on_dispatch_error() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(FailingProbePack);
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
let err = reg
.dispatch_with_identity(
"probe",
serde_json::json!({"namespace": "test-ns"}),
Some(RequestIdentity {
request_id: Some(102),
..Default::default()
}),
)
.await
.unwrap_err();
assert!(matches!(err, RuntimeError::InvalidInput(_)));
let ev = first_event(&store).await;
assert_eq!(ev.outcome, EventOutcome::Error);
assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(102));
}
#[tokio::test]
async fn dispatch_with_identity_stamps_request_id_on_denied() {
#[derive(Debug)]
struct AlwaysDenyGate;
impl Gate for AlwaysDenyGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
Ok(GateDecision::deny("denied by test"))
}
}
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_gate(Arc::new(AlwaysDenyGate));
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
let err = reg
.dispatch_with_identity(
"list",
serde_json::json!({"namespace": "test-ns"}),
Some(RequestIdentity {
request_id: Some(103),
..Default::default()
}),
)
.await
.unwrap_err();
assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
let ev = first_event(&store).await;
assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(103));
}
#[tokio::test]
async fn dispatch_with_identity_stamps_request_id_on_link_v2_success() {
let store = Arc::new(MemoryEventStore::default());
let edge_id = uuid::Uuid::new_v4();
let source_id = uuid::Uuid::new_v4();
let target_id = uuid::Uuid::new_v4();
let edge_json = serde_json::json!({
"id": edge_id,
"namespace": "local",
"source_id": source_id,
"target_id": target_id,
"relation": "depends_on",
"weight": 1.0,
});
let mut builder = VerbRegistryBuilder::new();
builder.register(LinkResultPack::ok(edge_json));
builder.with_event_store(store.clone());
builder.with_default_namespace("test-ns");
let reg = builder.build().expect("registry builds");
reg.dispatch_with_identity(
"link",
serde_json::json!({
"source_id": source_id,
"target_id": target_id,
"relation": "depends_on",
}),
Some(RequestIdentity {
namespace: "test-ns".to_string(),
request_id: Some(104),
..Default::default()
}),
)
.await
.unwrap();
let ev = first_event(&store).await;
assert_eq!(
ev.payload_schema_version, 2,
"successful singleton link uses audit schema v2"
);
assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(104));
}
#[tokio::test]
async fn dispatch_with_identity_stamps_request_id_on_link_v1_fallback() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(LinkResultPack::err("target endpoint not found"));
builder.with_event_store(store.clone());
builder.with_default_namespace("test-ns");
let reg = builder.build().expect("registry builds");
let err = reg
.dispatch_with_identity(
"link",
serde_json::json!({
"source_id": "note:alpha",
"target_id": "note:missing",
"relation": "depends_on",
}),
Some(RequestIdentity {
namespace: "test-ns".to_string(),
request_id: Some(105),
..Default::default()
}),
)
.await
.unwrap_err();
assert!(matches!(err, RuntimeError::InvalidInput(_)));
let ev = first_event(&store).await;
assert_eq!(
ev.payload_schema_version, 1,
"failed link keeps the v1 audit shape"
);
assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(105));
}
#[tokio::test]
async fn dispatch_with_identity_stamps_request_id_on_unknown_verb() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
let err = reg
.dispatch_with_identity(
"no_such_verb",
serde_json::json!({}),
Some(RequestIdentity {
namespace: Namespace::local().as_str().to_string(),
request_id: Some(106),
..Default::default()
}),
)
.await
.unwrap_err();
assert!(matches!(err, RuntimeError::UnknownVerb(_)));
let ev = first_event(&store).await;
assert_eq!(ev.outcome, EventOutcome::Error);
assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(106));
}
#[tokio::test]
async fn dispatch_with_identity_omits_request_id_key_when_absent() {
let store = Arc::new(MemoryEventStore::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(AlphaPack);
builder.with_event_store(store.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
.await
.unwrap();
let ev = first_event(&store).await;
let resource = ev.payload["resource"]
.as_object()
.expect("resource must be an object");
assert!(
!resource.contains_key("request_id"),
"request_id key must be entirely absent when no id is supplied, \
not present as null or 0: got {resource:?}"
);
}
}
#[cfg(test)]
mod dep_tests {
use super::*;
use async_trait::async_trait;
use khive_types::Pack;
use serde_json::Value;
struct KgDepPack;
struct MemoryDepPack;
struct ADepPack;
struct BDepPack;
impl Pack for KgDepPack {
const NAME: &'static str = "kg_dep";
const NOTE_KINDS: &'static [&'static str] = &["observation"];
const ENTITY_KINDS: &'static [&'static str] = &["concept"];
const HANDLERS: &'static [HandlerDef] = &[];
}
impl Pack for MemoryDepPack {
const NAME: &'static str = "memory_dep";
const NOTE_KINDS: &'static [&'static str] = &["memory"];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[];
const REQUIRES: &'static [&'static str] = &["kg_dep"];
}
impl Pack for ADepPack {
const NAME: &'static str = "pack_a";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[];
const REQUIRES: &'static [&'static str] = &["pack_b"];
}
impl Pack for BDepPack {
const NAME: &'static str = "pack_b";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[];
const REQUIRES: &'static [&'static str] = &["pack_a"];
}
#[async_trait]
impl PackRuntime for KgDepPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
verb: &str,
_: Value,
_: &VerbRegistry,
_: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::InvalidInput(format!(
"KgDepPack has no verbs: {verb}"
)))
}
}
#[async_trait]
impl PackRuntime for MemoryDepPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
fn requires(&self) -> &'static [&'static str] {
Self::REQUIRES
}
async fn dispatch(
&self,
verb: &str,
_: Value,
_: &VerbRegistry,
_: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::InvalidInput(format!(
"MemoryDepPack has no verbs: {verb}"
)))
}
}
#[async_trait]
impl PackRuntime for ADepPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
fn requires(&self) -> &'static [&'static str] {
Self::REQUIRES
}
async fn dispatch(
&self,
verb: &str,
_: Value,
_: &VerbRegistry,
_: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::InvalidInput(format!(
"ADepPack has no verbs: {verb}"
)))
}
}
#[async_trait]
impl PackRuntime for BDepPack {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
fn requires(&self) -> &'static [&'static str] {
Self::REQUIRES
}
async fn dispatch(
&self,
verb: &str,
_: Value,
_: &VerbRegistry,
_: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::InvalidInput(format!(
"BDepPack has no verbs: {verb}"
)))
}
}
#[test]
fn test_pack_deps_happy_path() {
let mut builder = VerbRegistryBuilder::new();
builder.register(MemoryDepPack);
builder.register(KgDepPack);
let reg = builder
.build()
.expect("kg_dep satisfies memory_dep dependency");
assert_eq!(reg.pack_requires("memory_dep").unwrap(), &["kg_dep"]);
let names = reg.pack_names();
let kg_pos = names.iter().position(|&n| n == "kg_dep").unwrap();
let mem_pos = names.iter().position(|&n| n == "memory_dep").unwrap();
assert!(
kg_pos < mem_pos,
"kg_dep must be loaded before memory_dep; order: {names:?}"
);
}
#[test]
fn test_pack_deps_missing() {
let mut builder = VerbRegistryBuilder::new();
builder.register(MemoryDepPack);
let err = match builder.build() {
Ok(_) => panic!("expected Err, got Ok"),
Err(e) => e,
};
assert!(
matches!(err, RuntimeError::MissingPackDependency(_)),
"expected MissingPackDependency, got {err:?}"
);
let msg = err.to_string();
assert!(
msg.contains("memory_dep"),
"error must name the dependent pack: {msg}"
);
assert!(
msg.contains("kg_dep"),
"error must name the missing dep: {msg}"
);
}
#[test]
fn test_pack_deps_circular() {
let mut builder = VerbRegistryBuilder::new();
builder.register(ADepPack);
builder.register(BDepPack);
let err = match builder.build() {
Ok(_) => panic!("expected Err, got Ok"),
Err(e) => e,
};
assert!(
matches!(err, RuntimeError::CircularPackDependency(_)),
"expected CircularPackDependency, got {err:?}"
);
let msg = err.to_string();
assert!(msg.contains("pack_a"), "error must name pack_a: {msg}");
assert!(msg.contains("pack_b"), "error must name pack_b: {msg}");
}
#[test]
fn test_pack_deps_no_deps() {
struct NoDepsA;
struct NoDepsB;
impl Pack for NoDepsA {
const NAME: &'static str = "no_deps_a";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[];
}
impl Pack for NoDepsB {
const NAME: &'static str = "no_deps_b";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[];
}
#[async_trait]
impl PackRuntime for NoDepsA {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
verb: &str,
_: Value,
_: &VerbRegistry,
_: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::InvalidInput(format!("NoDepsA: {verb}")))
}
}
#[async_trait]
impl PackRuntime for NoDepsB {
fn name(&self) -> &str {
Self::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
Self::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
Self::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
Self::HANDLERS
}
async fn dispatch(
&self,
verb: &str,
_: Value,
_: &VerbRegistry,
_: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Err(RuntimeError::InvalidInput(format!("NoDepsB: {verb}")))
}
}
let mut builder = VerbRegistryBuilder::new();
builder.register(NoDepsA);
builder.register(NoDepsB);
let reg = builder.build().expect("packs with REQUIRES=&[] build");
assert_eq!(reg.pack_requires("no_deps_a").unwrap(), &[] as &[&str]);
assert_eq!(reg.pack_requires("no_deps_b").unwrap(), &[] as &[&str]);
}
}
#[cfg(test)]
mod hook_tests {
use super::*;
use async_trait::async_trait;
use khive_types::Pack;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex as StdMutex;
struct SimplePack;
impl Pack for SimplePack {
const NAME: &'static str = "simple";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "ping",
description: "ping",
visibility: Visibility::Verb,
category: VerbCategory::Assertive,
params: &[],
}];
}
#[async_trait]
impl PackRuntime for SimplePack {
fn name(&self) -> &str {
SimplePack::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
SimplePack::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
SimplePack::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
SimplePack::HANDLERS
}
async fn dispatch(
&self,
verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Ok(serde_json::json!({ "verb": verb }))
}
}
struct RecallPack;
impl Pack for RecallPack {
const NAME: &'static str = "memory";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
name: "memory.recall",
description: "test recall",
visibility: Visibility::Verb,
category: VerbCategory::Assertive,
params: &[],
}];
}
#[async_trait]
impl PackRuntime for RecallPack {
fn name(&self) -> &str {
RecallPack::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
RecallPack::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
RecallPack::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
RecallPack::HANDLERS
}
async fn dispatch(
&self,
_verb: &str,
params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
let hit = serde_json::json!({
"id": uuid::Uuid::new_v4().to_string(),
"served_by_profile_id": "custom-recall-v1",
"serve_attribution": "profile",
});
if params.get("verbose").and_then(Value::as_bool) == Some(true) {
Ok(serde_json::json!({"results": [hit]}))
} else {
Ok(serde_json::json!([hit]))
}
}
}
#[derive(Default)]
struct EventCapturingHook {
event: StdMutex<Option<Event>>,
}
#[async_trait]
impl DispatchHook for EventCapturingHook {
async fn on_dispatch(&self, view: &EventView) {
*self.event.lock().unwrap() = Some(view.event.clone());
}
}
#[derive(Default)]
struct CountingHook {
calls: AtomicUsize,
last_verb: StdMutex<String>,
}
#[async_trait]
impl DispatchHook for CountingHook {
async fn on_dispatch(&self, view: &EventView) {
self.calls.fetch_add(1, Ordering::SeqCst);
*self.last_verb.lock().unwrap() = view.event.verb.clone();
}
}
#[tokio::test]
async fn dispatch_hook_fires_on_successful_dispatch() {
let hook = Arc::new(CountingHook::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(SimplePack);
builder.with_dispatch_hook(hook.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("ping", Value::Null).await.unwrap();
assert_eq!(
hook.calls.load(Ordering::SeqCst),
1,
"hook must fire once per successful dispatch"
);
assert_eq!(
hook.last_verb.lock().unwrap().as_str(),
"ping",
"hook event must carry the dispatched verb"
);
}
#[tokio::test]
async fn dispatch_hook_fires_multiple_times() {
let hook = Arc::new(CountingHook::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(SimplePack);
builder.with_dispatch_hook(hook.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("ping", Value::Null).await.unwrap();
reg.dispatch("ping", Value::Null).await.unwrap();
reg.dispatch("ping", Value::Null).await.unwrap();
assert_eq!(
hook.calls.load(Ordering::SeqCst),
3,
"hook must fire once per successful dispatch"
);
}
#[tokio::test]
async fn recall_hook_copies_serve_attribution_from_bare_and_verbose_results() {
let hook = Arc::new(EventCapturingHook::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(RecallPack);
builder.with_dispatch_hook(hook.clone());
let reg = builder.build().expect("registry builds");
for params in [serde_json::json!({}), serde_json::json!({"verbose": true})] {
reg.dispatch("memory.recall", params)
.await
.expect("recall dispatch");
let event = hook.event.lock().unwrap().clone().expect("hook event");
assert!(
event.target_id.is_some(),
"first recall id must become target"
);
assert_eq!(
event.payload["served_by_profile_id"],
serde_json::json!("custom-recall-v1")
);
assert_eq!(
event.payload["serve_attribution"],
serde_json::json!("profile")
);
}
}
#[tokio::test]
async fn dispatch_hook_does_not_fire_on_unknown_verb() {
let hook = Arc::new(CountingHook::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(SimplePack);
builder.with_dispatch_hook(hook.clone());
let reg = builder.build().expect("registry builds");
let _ = reg.dispatch("nonexistent", Value::Null).await;
assert_eq!(
hook.calls.load(Ordering::SeqCst),
0,
"hook must NOT fire for unknown verb (dispatch returns error)"
);
}
#[tokio::test]
async fn dispatch_hook_does_not_fire_on_gate_deny() {
use khive_gate::{Gate, GateDecision, GateError};
#[derive(Debug)]
struct AlwaysDenyGate;
impl Gate for AlwaysDenyGate {
fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
Ok(GateDecision::deny("test deny"))
}
}
let hook = Arc::new(CountingHook::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(SimplePack);
builder.with_gate(Arc::new(AlwaysDenyGate));
builder.with_dispatch_hook(hook.clone());
let reg = builder.build().expect("registry builds");
let err = reg.dispatch("ping", Value::Null).await.unwrap_err();
assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
assert_eq!(
hook.calls.load(Ordering::SeqCst),
0,
"hook must NOT fire when gate denies dispatch"
);
}
#[tokio::test]
async fn dispatch_hook_event_carries_namespace_from_params() {
let hook = Arc::new(CountingHook::default());
#[derive(Default)]
struct NsCapturingHook {
ns: StdMutex<String>,
}
#[async_trait]
impl DispatchHook for NsCapturingHook {
async fn on_dispatch(&self, view: &EventView) {
*self.ns.lock().unwrap() = view.event.namespace.clone();
}
}
let ns_hook = Arc::new(NsCapturingHook::default());
let mut builder = VerbRegistryBuilder::new();
builder.register(SimplePack);
builder.with_dispatch_hook(ns_hook.clone());
let reg = builder.build().expect("registry builds");
reg.dispatch("ping", serde_json::json!({"namespace": "tenant-abc"}))
.await
.unwrap();
assert_eq!(
ns_hook.ns.lock().unwrap().as_str(),
"tenant-abc",
"dispatch hook event must carry the resolved namespace"
);
drop(hook);
}
#[tokio::test]
async fn no_dispatch_hook_configured_dispatch_succeeds() {
let mut builder = VerbRegistryBuilder::new();
builder.register(SimplePack);
let reg = builder.build().expect("registry builds");
let res = reg.dispatch("ping", Value::Null).await.unwrap();
assert_eq!(res["verb"], "ping");
}
}
#[cfg(test)]
mod help_tests {
use super::*;
use async_trait::async_trait;
use khive_types::Pack;
use std::sync::{
atomic::{AtomicUsize, Ordering},
Arc,
};
static CREATE_PARAMS: [ParamDef; 2] = [
ParamDef {
name: "kind",
param_type: "string",
required: true,
description: "Granular kind (concept | document | ...).",
},
ParamDef {
name: "name",
param_type: "string",
required: false,
description: "Human-readable name.",
},
];
static RECALL_PARAMS: [ParamDef; 2] = [
ParamDef {
name: "query",
param_type: "string",
required: true,
description: "Semantic recall query.",
},
ParamDef {
name: "limit",
param_type: "integer",
required: false,
description: "Maximum memories to return.",
},
];
static EMBED_PARAMS: [ParamDef; 0] = [];
struct HelpPack {
invocations: Arc<AtomicUsize>,
}
impl Pack for HelpPack {
const NAME: &'static str = "helptest";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[
HandlerDef {
name: "create",
description: "Create an entity or note",
visibility: Visibility::Verb,
category: VerbCategory::Commissive,
params: &CREATE_PARAMS,
},
HandlerDef {
name: "recall",
description: "Recall memory notes with decay-aware hybrid ranking",
visibility: Visibility::Verb,
category: VerbCategory::Assertive,
params: &RECALL_PARAMS,
},
HandlerDef {
name: "recall.embed",
description: "Return the embedding vector used by memory recall",
visibility: Visibility::Subhandler,
category: VerbCategory::Assertive,
params: &EMBED_PARAMS,
},
HandlerDef {
name: "link",
description: "Create a typed directed edge",
visibility: Visibility::Verb,
category: VerbCategory::Commissive,
params: &[],
},
];
}
static HELP_EDGE_RULES: [EdgeEndpointRule; 2] = [
EdgeEndpointRule {
relation: khive_types::EdgeRelation::DependsOn,
source: EndpointKind::NoteOfKind("task"),
target: EndpointKind::NoteOfKind("task"),
},
EdgeEndpointRule {
relation: khive_types::EdgeRelation::Supersedes,
source: EndpointKind::NoteOfKind("task"),
target: EndpointKind::NoteOfKind("task"),
},
];
#[async_trait]
impl PackRuntime for HelpPack {
fn name(&self) -> &str {
HelpPack::NAME
}
fn note_kinds(&self) -> &'static [&'static str] {
HelpPack::NOTE_KINDS
}
fn entity_kinds(&self) -> &'static [&'static str] {
HelpPack::ENTITY_KINDS
}
fn handlers(&self) -> &'static [HandlerDef] {
HelpPack::HANDLERS
}
fn edge_rules(&self) -> &'static [EdgeEndpointRule] {
&HELP_EDGE_RULES
}
async fn dispatch(
&self,
verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
self.invocations.fetch_add(1, Ordering::SeqCst);
Ok(serde_json::json!({ "pack": "helptest", "verb": verb }))
}
}
fn build_help_registry(invocations: Arc<AtomicUsize>) -> VerbRegistry {
let mut builder = VerbRegistryBuilder::new();
builder.register(HelpPack { invocations });
builder.build().expect("help registry builds")
}
#[tokio::test]
async fn test_help_true_returns_schema_for_kg_create() {
let invocations = Arc::new(AtomicUsize::new(0));
let reg = build_help_registry(invocations.clone());
let result = reg
.dispatch("create", serde_json::json!({ "help": true }))
.await
.expect("help=true must succeed for a known verb");
assert_eq!(result["verb"], "create", "envelope must name the verb");
assert_eq!(
result["pack"], "helptest",
"envelope must name the owning pack"
);
assert!(
result["description"].as_str().is_some(),
"description must be a string"
);
let params = result["params"]
.as_array()
.expect("params must be a JSON array");
assert!(!params.is_empty(), "params array must not be empty");
let kind_param = params.iter().find(|p| p["name"] == "kind");
assert!(
kind_param.is_some(),
"params array must include the 'kind' parameter"
);
let kind_param = kind_param.unwrap();
assert_eq!(
kind_param["required"],
serde_json::json!(true),
"'kind' must be required"
);
assert_eq!(kind_param["type"], "string", "'kind' type must be 'string'");
let identifier_help = result["identifier_resolution"]
.as_object()
.expect("help=true must include the shared identifier contract");
assert!(identifier_help["full_uuid"]
.as_str()
.is_some_and(|text| text.contains("globally unique")));
assert!(identifier_help["short_prefix"]
.as_str()
.is_some_and(|text| text.contains("lookup scope belongs to the consuming parameter")));
assert!(identifier_help["parameter_rule"]
.as_str()
.is_some_and(|text| text.contains("submitted again")));
}
#[tokio::test]
async fn test_help_true_returns_schema_for_recall() {
let invocations = Arc::new(AtomicUsize::new(0));
let reg = build_help_registry(invocations.clone());
let result = reg
.dispatch("recall", serde_json::json!({ "help": true }))
.await
.expect("help=true must succeed for recall");
assert_eq!(result["verb"], "recall");
assert_eq!(result["pack"], "helptest");
let params = result["params"]
.as_array()
.expect("params must be a JSON array");
let query_param = params.iter().find(|p| p["name"] == "query");
assert!(query_param.is_some(), "params must include 'query'");
let query_param = query_param.unwrap();
assert_eq!(
query_param["required"],
serde_json::json!(true),
"'query' must be required"
);
let limit_param = params.iter().find(|p| p["name"] == "limit");
assert!(limit_param.is_some(), "params must include 'limit'");
let limit_param = limit_param.unwrap();
assert_eq!(
limit_param["required"],
serde_json::json!(false),
"'limit' must be optional"
);
}
#[tokio::test]
async fn test_link_help_true_exposes_endpoint_rules() {
let invocations = Arc::new(AtomicUsize::new(0));
let reg = build_help_registry(invocations.clone());
let result = reg
.dispatch("link", serde_json::json!({ "help": true }))
.await
.expect("help=true must succeed for link");
assert_eq!(result["verb"], "link");
let rules = result["endpoint_rules"]
.as_array()
.expect("link help must include an endpoint_rules array");
assert!(!rules.is_empty(), "endpoint_rules must not be empty");
assert!(
rules.iter().any(|r| r["relation"] == "contains"
&& r["source"] == "entity:concept"
&& r["target"] == "entity:concept"),
"endpoint_rules must include the base 'contains' entity rule; got {rules:#?}"
);
assert!(
rules.iter().any(|r| r["relation"] == "depends_on"
&& r["source"] == "note:task"
&& r["target"] == "note:task"),
"endpoint_rules must include the pack-declared depends_on rule; got {rules:#?}"
);
assert!(
rules
.iter()
.any(|r| r["relation"] == "annotates" && r["source"] == "note:*"),
"endpoint_rules must document the annotates note-to-any rule; got {rules:#?}"
);
assert_eq!(
invocations.load(Ordering::SeqCst),
0,
"link(help=true) must not invoke pack dispatch"
);
}
#[tokio::test]
async fn test_link_help_true_matches_special_relation_validator_set() {
let invocations = Arc::new(AtomicUsize::new(0));
let reg = build_help_registry(invocations.clone());
let result = reg
.dispatch("link", serde_json::json!({ "help": true }))
.await
.expect("help=true must succeed for link");
let rules = result["endpoint_rules"]
.as_array()
.expect("link help must include an endpoint_rules array");
for relation in ["supersedes", "supports", "refutes"] {
assert!(
rules.iter().any(|r| r["relation"] == relation
&& r["source"] == "note:*"
&& r["target"] == "note:*"),
"endpoint_rules must include the note:*->note:* row for '{relation}' \
(validator accepts any note->note pair unconditionally); got {rules:#?}"
);
assert!(
!rules.iter().any(|r| r["relation"] == relation
&& r["source"] == "note:task"
&& r["target"] == "note:task"),
"endpoint_rules must NOT advertise a pack EDGE_RULES row for special \
relation '{relation}' — validate_edge_relation_endpoints never consults \
pack_rule_allows for supersedes/supports/refutes; got {rules:#?}"
);
}
for (relation, kind) in [
("supersedes", "concept"),
("supports", "concept"),
("refutes", "concept"),
] {
assert!(
rules.iter().any(|r| r["relation"] == relation
&& r["source"] == format!("entity:{kind}")
&& r["target"] == "entity:concept"),
"endpoint_rules must include the base entity:{kind}->entity:concept row \
for '{relation}'; got {rules:#?}"
);
}
}
#[test]
fn special_relation_predicate_matches_the_dedicated_validator_set() {
for relation in khive_types::EdgeRelation::ALL {
assert_eq!(
is_special_relation(relation),
matches!(
relation,
khive_types::EdgeRelation::Supersedes
| khive_types::EdgeRelation::Supports
| khive_types::EdgeRelation::Refutes
),
"unexpected special-relation classification for {relation}"
);
}
}
#[tokio::test]
async fn test_help_true_does_not_execute_the_verb() {
let invocations = Arc::new(AtomicUsize::new(0));
let reg = build_help_registry(invocations.clone());
reg.dispatch("create", serde_json::json!({ "help": true }))
.await
.expect("help=true must succeed");
reg.dispatch("recall", serde_json::json!({ "help": true }))
.await
.expect("help=true must succeed");
assert_eq!(
invocations.load(Ordering::SeqCst),
0,
"pack dispatch MUST NOT be invoked when help=true; \
got {} invocation(s)",
invocations.load(Ordering::SeqCst)
);
reg.dispatch("create", serde_json::json!({}))
.await
.expect("normal dispatch must succeed");
assert_eq!(
invocations.load(Ordering::SeqCst),
1,
"pack dispatch must fire exactly once for a normal call"
);
}
#[tokio::test]
async fn help_true_on_subhandler_returns_callable_via_mcp_false() {
let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
let result = reg
.dispatch("recall.embed", serde_json::json!({ "help": true }))
.await
.expect("help=true on subhandler must succeed (no permission check on help path)");
assert_eq!(
result["callable_via_mcp"],
serde_json::json!(false),
"subhandler help must carry callable_via_mcp: false"
);
assert_eq!(
result["visibility"], "internal",
"subhandler help must carry visibility: internal"
);
assert_eq!(result["verb"], "recall.embed");
assert_eq!(result["pack"], "helptest");
}
#[tokio::test]
async fn help_true_on_public_verb_does_not_have_callable_via_mcp_false() {
let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
let result = reg
.dispatch("create", serde_json::json!({ "help": true }))
.await
.expect("help=true on public verb must succeed");
assert_ne!(
result.get("callable_via_mcp"),
Some(&serde_json::json!(false)),
"public verb help must NOT carry callable_via_mcp: false"
);
assert_ne!(
result.get("visibility"),
Some(&serde_json::json!("internal")),
"public verb help must NOT carry visibility: internal"
);
}
#[tokio::test]
async fn help_true_on_unknown_verb_returns_error() {
let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
let err = reg
.dispatch("nonexistent_verb", serde_json::json!({ "help": true }))
.await
.unwrap_err();
assert!(
matches!(err, RuntimeError::UnknownVerb(_)),
"help=true on unknown verb must return UnknownVerb, got {err:?}"
);
let msg = err.to_string();
assert!(
msg.contains("nonexistent_verb"),
"error must name the unknown verb: {msg}"
);
}
#[tokio::test]
async fn help_true_on_subhandler_includes_params_field() {
let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
let result = reg
.dispatch("recall.embed", serde_json::json!({ "help": true }))
.await
.expect("help=true on subhandler must succeed");
let params = result
.get("params")
.expect("subhandler help must include 'params' field");
assert!(
params.is_array(),
"subhandler help params must be a JSON array"
);
}
#[tokio::test]
async fn help_true_unknown_verb_available_list_excludes_subhandlers() {
let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
let err = reg
.dispatch("not_a_verb", serde_json::json!({ "help": true }))
.await
.unwrap_err();
let msg = err.to_string();
assert!(
!msg.contains("recall.embed"),
"unknown-verb help error must not advertise subhandler recall.embed: {msg}"
);
assert!(
msg.contains("create"),
"unknown-verb help error must still list public verb 'create': {msg}"
);
assert!(
msg.contains("recall"),
"unknown-verb help error must still list public verb 'recall': {msg}"
);
}
#[tokio::test]
async fn dispatch_unknown_verb_available_list_excludes_subhandlers() {
let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
let err = reg
.dispatch("not_a_verb", serde_json::json!({}))
.await
.unwrap_err();
let msg = err.to_string();
assert!(
!msg.contains("recall.embed"),
"dispatch unknown-verb error must not advertise subhandler recall.embed: {msg}"
);
assert!(
msg.contains("create"),
"dispatch unknown-verb error must still list public verb 'create': {msg}"
);
assert!(
msg.contains("recall"),
"dispatch unknown-verb error must still list public verb 'recall': {msg}"
);
}
struct SchemaPack {
pack_name: &'static str,
statements: &'static [&'static str],
}
impl Pack for SchemaPack {
const NAME: &'static str = "schema-pack";
const NOTE_KINDS: &'static [&'static str] = &[];
const ENTITY_KINDS: &'static [&'static str] = &[];
const HANDLERS: &'static [HandlerDef] = &[];
}
#[async_trait]
impl PackRuntime for SchemaPack {
fn name(&self) -> &str {
self.pack_name
}
fn note_kinds(&self) -> &'static [&'static str] {
&[]
}
fn entity_kinds(&self) -> &'static [&'static str] {
&[]
}
fn handlers(&self) -> &'static [HandlerDef] {
&[]
}
fn schema_plan(&self) -> SchemaPlan {
SchemaPlan {
pack: self.pack_name,
statements: self.statements,
}
}
async fn dispatch(
&self,
verb: &str,
_params: Value,
_registry: &VerbRegistry,
_token: &NamespaceToken,
) -> Result<Value, RuntimeError> {
Ok(serde_json::json!({ "pack": self.pack_name, "verb": verb }))
}
}
#[test]
fn all_schema_plans_named_returns_correct_pairs() {
let mut builder = VerbRegistryBuilder::new();
builder.register_boxed(Box::new(SchemaPack {
pack_name: "alpha",
statements: &["CREATE TABLE IF NOT EXISTS t_alpha (id INTEGER PRIMARY KEY)"],
}));
builder.register_boxed(Box::new(SchemaPack {
pack_name: "beta",
statements: &[],
}));
let reg = builder.build().expect("registry builds");
let named = reg.all_schema_plans_named();
assert_eq!(named.len(), 2);
let alpha_entry = named.iter().find(|(n, _)| *n == "alpha");
let beta_entry = named.iter().find(|(n, _)| *n == "beta");
assert!(alpha_entry.is_some(), "alpha must appear in named plans");
assert!(beta_entry.is_some(), "beta must appear in named plans");
let (_, alpha_plan) = alpha_entry.unwrap();
assert_eq!(alpha_plan.statements.len(), 1);
assert!(!alpha_plan.is_empty());
let (_, beta_plan) = beta_entry.unwrap();
assert!(beta_plan.is_empty());
}
#[tokio::test]
async fn apply_schema_plans_with_map_routes_to_correct_backend() {
use khive_storage::types::{SqlStatement, SqlValue};
let default_backend = khive_db::StorageBackend::memory().expect("default memory backend");
let pack_backend =
khive_db::StorageBackend::memory().expect("pack-specific memory backend");
let mut builder = VerbRegistryBuilder::new();
builder.register_boxed(Box::new(SchemaPack {
pack_name: "routed",
statements: &["CREATE TABLE IF NOT EXISTS t_routed (id INTEGER PRIMARY KEY)"],
}));
let reg = builder.build().expect("registry builds");
let mut backend_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
backend_map.insert("routed", &pack_backend);
reg.apply_schema_plans_with_map(&backend_map, &default_backend)
.expect("schema application must not collide");
let mut writer = pack_backend.sql().writer().await.expect("writer");
let result = writer
.execute(SqlStatement {
sql: "INSERT INTO t_routed (id) VALUES (?1)".into(),
params: vec![SqlValue::Integer(1)],
label: None,
})
.await;
assert!(
result.is_ok(),
"t_routed must exist on pack_backend after routing: {result:?}"
);
let mut default_writer = default_backend.sql().writer().await.expect("writer");
let default_result = default_writer
.execute(SqlStatement {
sql: "INSERT INTO t_routed (id) VALUES (?1)".into(),
params: vec![SqlValue::Integer(2)],
label: None,
})
.await;
assert!(
default_result.is_err(),
"t_routed must NOT exist on default_backend (table should not be there)"
);
}
#[tokio::test]
async fn apply_schema_plans_with_map_falls_back_to_default_for_unmapped_packs() {
use khive_storage::types::{SqlStatement, SqlValue};
let default_backend = khive_db::StorageBackend::memory().expect("default memory backend");
let mut builder = VerbRegistryBuilder::new();
builder.register_boxed(Box::new(SchemaPack {
pack_name: "unmapped",
statements: &["CREATE TABLE IF NOT EXISTS t_unmapped (id INTEGER PRIMARY KEY)"],
}));
let reg = builder.build().expect("registry builds");
let backend_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
reg.apply_schema_plans_with_map(&backend_map, &default_backend)
.expect("schema application must not collide");
let mut writer = default_backend.sql().writer().await.expect("writer");
let result = writer
.execute(SqlStatement {
sql: "INSERT INTO t_unmapped (id) VALUES (?1)".into(),
params: vec![SqlValue::Integer(1)],
label: None,
})
.await;
assert!(
result.is_ok(),
"t_unmapped must exist on default_backend for unmapped pack: {result:?}"
);
}
#[test]
fn apply_schema_plans_with_map_collision_is_an_error() {
let backend = khive_db::StorageBackend::memory().expect("memory backend");
let empty_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
let mut builder = VerbRegistryBuilder::new();
builder.register_boxed(Box::new(SchemaPack {
pack_name: "pack_alpha",
statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
}));
builder.register_boxed(Box::new(SchemaPack {
pack_name: "pack_beta",
statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
}));
let registry = builder.build().expect("registry builds");
let result = registry.apply_schema_plans_with_map(&empty_map, &backend);
assert!(
result.is_err(),
"two packs declaring the same table on the same backend must produce a collision error"
);
let err = result.unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("pack_alpha"),
"collision error must name first pack; got: {msg}"
);
assert!(
msg.contains("pack_beta"),
"collision error must name second pack; got: {msg}"
);
assert!(
msg.contains("collision_table"),
"collision error must name the table; got: {msg}"
);
}
#[test]
fn apply_schema_plans_with_map_read_only_collision_is_an_error_without_writes() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("read_only_schema_collision.db");
{
let writable = khive_db::StorageBackend::sqlite(&path).expect("writable backend");
writable.prepare_core_schema().expect("current schema");
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
for suffix in ["-wal", "-shm"] {
let mut name = path.file_name().expect("db file name").to_os_string();
name.push(suffix);
let sidecar = path.parent().expect("db parent dir").join(name);
if sidecar.exists() {
let mut permissions = std::fs::metadata(&sidecar)
.expect("sidecar metadata")
.permissions();
permissions.set_mode(0o444);
std::fs::set_permissions(&sidecar, permissions).expect("freeze sidecar");
}
}
}
let backend = khive_db::StorageBackend::sqlite_read_only(&path).expect("read-only backend");
let empty_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
let mut builder = VerbRegistryBuilder::new();
builder.register_boxed(Box::new(SchemaPack {
pack_name: "pack_alpha",
statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
}));
builder.register_boxed(Box::new(SchemaPack {
pack_name: "pack_beta",
statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
}));
let registry = builder.build().expect("registry builds");
let writes_before = backend.pool().writer_acquisition_snapshot();
let result = registry.apply_schema_plans_with_map(&empty_map, &backend);
let err = result.expect_err(
"read-only topology must reject the same cross-pack collision as writable topology",
);
let msg = err.to_string();
assert!(
msg.contains("pack_alpha"),
"collision error must name first pack; got: {msg}"
);
assert!(
msg.contains("pack_beta"),
"collision error must name second pack; got: {msg}"
);
assert!(
msg.contains("collision_table"),
"collision error must name the table; got: {msg}"
);
assert_eq!(
backend.pool().writer_acquisition_snapshot(),
writes_before,
"read-only collision validation must not acquire a writer"
);
}
}