Skip to main content

khive_runtime/
pack.rs

1// FILE SIZE JUSTIFICATION: pack.rs is the load-bearing dispatch core — VerbRegistry,
2// VerbRegistryBuilder, PackRuntime, DispatchHook, and their test scaffolding all
3// share internal state (packs Vec, gate, event_store) that cannot be cleanly split
4// without exposing private fields or duplicating the scaffolding. Inline tests cover
5// collision detection and dispatch path that require direct access to VerbRegistry
6// internals. Split plan: when the verb surface reaches a stable v1 API, extract
7// VerbRegistryBuilder into `pack/builder.rs` and gate/event logic into `pack/dispatch.rs`.
8//! Pack runtime trait and verb registry.
9//!
10//! `PackRuntime` mirrors `Pack`'s const associated items as methods for object safety.
11//! Build a [`VerbRegistry`] via `VerbRegistryBuilder::build()`; registration is builder-only.
12
13use std::collections::{HashMap, HashSet, VecDeque};
14use std::sync::Arc;
15use std::time::Instant;
16
17use crate::operations::{LinkSpec, Resolved};
18use crate::runtime::NamespaceToken;
19use async_trait::async_trait;
20use khive_gate::{AllowAllGate, AuditEvent, GateDecision, GateRef, GateRequest};
21use khive_storage::{Event, EventStore, EventView, SubstrateKind};
22use khive_types::{EventKind, EventOutcome, Namespace};
23use serde_json::Value;
24
25pub use khive_types::{
26    EdgeEndpointRule, EndpointKind, EntityTypeDef, HandlerDef, NoteKindSpec, NoteLifecycleSpec,
27    PackSchemaPlan, ParamDef, VerbCategory, VerbPresentationPolicy, Visibility,
28};
29// Backward-compat re-export.
30#[allow(deprecated)]
31pub use khive_types::VerbDef;
32
33use crate::validation::ValidationRule;
34
35/// Pack-auxiliary schema plan.
36///
37/// Declares `CREATE TABLE IF NOT EXISTS` statements for pack-owned tables that
38/// are NOT part of the core substrate schema (entities, notes, edges, events).
39/// Applied at boot via `StorageBackend::apply_schema` / `apply_pack_schema_plan`.
40///
41/// Core substrate tables evolve through versioned migrations. Pack schema is
42/// strictly for pack-auxiliary tables (e.g. GTD lifecycle audit, memory index).
43/// v1 pack schemas are non-versioned.
44#[derive(Debug, Default, Clone)]
45pub struct SchemaPlan {
46    /// Owning pack name.
47    pub pack: &'static str,
48    /// DDL statements applied idempotently at boot.
49    /// Each entry must be a self-contained `CREATE TABLE IF NOT EXISTS` or
50    /// similar idempotent statement.
51    pub statements: &'static [&'static str],
52}
53
54impl SchemaPlan {
55    /// Construct a `SchemaPlan` with no statements.
56    ///
57    /// Packs whose state lives entirely in the core substrate tables (entities,
58    /// notes, edges) use this as their `schema_plan()` return value.
59    pub const fn empty() -> Self {
60        Self {
61            pack: "",
62            statements: &[],
63        }
64    }
65
66    /// Returns `true` when the plan contains no DDL statements.
67    pub fn is_empty(&self) -> bool {
68        self.statements.is_empty()
69    }
70}
71
72/// Best-effort hook called after every successful verb dispatch.
73///
74/// The runtime supplies a synthetic [`EventView`] whose `event` describes the
75/// dispatch outcome and whose `observations` vector is currently empty. Loading
76/// persisted provenance observations belongs to an explicit caller or the
77/// deferred event-consumer contract; this hook does not provide it.
78#[async_trait]
79pub trait DispatchHook: Send + Sync {
80    /// Called with the dispatch-outcome event view after a successful pack dispatch.
81    ///
82    /// Errors are logged via `tracing::warn!` and never propagated to the
83    /// caller; the dispatch has already succeeded.
84    async fn on_dispatch(&self, view: &EventView);
85}
86
87use crate::error::{
88    CircularPackDependency, MissingPackDependencies, MissingPackDependency, RuntimeError,
89};
90use crate::KhiveRuntime;
91
92/// Async dispatch trait for packs.
93///
94/// This is the object-safe behavioral counterpart to `khive_types::Pack`.
95/// `Pack` uses const associated items (not object-safe in Rust); this trait
96/// mirrors that metadata as methods and adds async dispatch.
97///
98/// Registration requires `P: Pack + PackRuntime` — the compiler enforces
99/// that every runtime pack also declares its vocabulary via `Pack`.
100#[async_trait]
101pub trait PackRuntime: Send + Sync {
102    /// Pack name — must equal `<Self as Pack>::NAME`.
103    fn name(&self) -> &str;
104
105    /// Note kinds this pack owns — must equal `<Self as Pack>::NOTE_KINDS`.
106    fn note_kinds(&self) -> &'static [&'static str];
107
108    /// Entity kinds this pack owns — must equal `<Self as Pack>::ENTITY_KINDS`.
109    fn entity_kinds(&self) -> &'static [&'static str];
110
111    /// Brain profile consumer kinds this pack requests — must equal
112    /// `<Self as Pack>::BRAIN_CONSUMER_KINDS`.
113    fn brain_consumer_kinds(&self) -> &'static [&'static str] {
114        &[]
115    }
116
117    /// Handlers this pack registers — must equal `<Self as Pack>::HANDLERS`.
118    fn handlers(&self) -> &'static [HandlerDef];
119
120    /// Pack-extensible edge endpoint rules — must equal `<Self as Pack>::EDGE_RULES`.
121    /// Defaults to empty so existing packs that don't extend the edge contract
122    /// can ignore it.
123    fn edge_rules(&self) -> &'static [EdgeEndpointRule] {
124        &[]
125    }
126
127    /// Pack-extensible entity-type subtypes — must equal `<Self as Pack>::ENTITY_TYPES`.
128    /// Defaults to empty so existing packs that don't extend the entity_type
129    /// registry can ignore it.
130    fn entity_types(&self) -> &'static [EntityTypeDef] {
131        &[]
132    }
133
134    /// Pack names whose vocabulary this pack references.
135    /// Defaults to empty so existing packs compile without changes.
136    fn requires(&self) -> &'static [&'static str] {
137        &[]
138    }
139
140    /// NoteKindSpec declarations for note kinds this pack owns.
141    ///
142    /// Packs that introduce note kinds with explicit lifecycle semantics
143    /// declare the spec here.  The runtime collects these for introspection
144    /// and future enforcement.  Defaults to empty so existing packs compile
145    /// without changes.
146    fn note_kind_specs(&self) -> &'static [NoteKindSpec] {
147        &[]
148    }
149
150    /// Optional per-kind hook for shared CRUD specialization.
151    ///
152    /// When a kind is owned by this pack (declared in `note_kinds()` or
153    /// `entity_kinds()`), returning `Some(hook)` opts that kind into
154    /// pack-specific behavior — defaults, derived properties, side-effect
155    /// edges — through the shared `create` path. Returning `None` keeps
156    /// the kind as plain storage with no specialization.
157    fn kind_hook(&self, _kind: &str) -> Option<Arc<dyn KindHook>> {
158        None
159    }
160
161    /// Pack-auxiliary schema.
162    ///
163    /// Returns DDL statements for pack-owned tables that are NOT part of the
164    /// core substrate schema. Statements are idempotent (`CREATE TABLE IF NOT
165    /// EXISTS`) so callers can apply them safely on every registration. Core
166    /// substrate tables evolve through versioned migrations; pack schema is
167    /// strictly pack-auxiliary.
168    ///
169    /// Defaults to an empty plan — packs that store everything in the core
170    /// substrate tables (entities, notes, edges, events) return this default.
171    ///
172    /// Plans are aggregated via [`VerbRegistry::all_schema_plans`] and applied
173    /// at startup via `KhiveMcpServer::with_packs`. Packs that need their
174    /// schema present (e.g. GTD) also self-bootstrap lazily on first call for
175    /// robustness in test contexts that create fresh in-memory databases.
176    fn schema_plan(&self) -> SchemaPlan {
177        SchemaPlan::empty()
178    }
179
180    /// Domain-specific validation rules contributed by this pack.
181    ///
182    /// Rule IDs MUST follow the `<pack>/<rule-id>` namespace convention.
183    /// Built-in rules (no pack prefix) are reserved for the `khive-runtime`
184    /// validation infrastructure.
185    ///
186    /// Defaults to empty — packs with no domain-specific rules return `&[]`.
187    fn validation_rules(&self) -> &'static [ValidationRule] {
188        &[]
189    }
190
191    /// Register custom embedding providers with the runtime. Called during pack
192    /// initialisation, before the first verb dispatch, so `KhiveRuntime::embedder(name)`
193    /// resolves provider names declared here. Default no-op — packs that only use
194    /// built-in lattice models do not need to override this.
195    /// See `docs/api/pack.md#register_embedders` for a usage example.
196    fn register_embedders(&self, _runtime: &KhiveRuntime) {}
197
198    /// Install a pack-owned entity-type validator on the runtime, called during pack
199    /// initialisation (after the registry is built, before the first dispatch) so
200    /// `create_many`/`create_entity` reject unregistered `entity_type` values at the
201    /// runtime layer. Default no-op leaves the validator absent (skip-when-None).
202    /// See `docs/api/pack.md#register_entity_type_validator` for the two-hook compatibility contract.
203    fn register_entity_type_validator(&self, _runtime: &KhiveRuntime) {}
204
205    /// Install a pack-owned entity-type validator that also receives the boot-time
206    /// composed set of every loaded pack's `ENTITY_TYPES` ([`VerbRegistry::all_entity_types`]).
207    /// Defaults to calling [`register_entity_type_validator`](Self::register_entity_type_validator)
208    /// with just the runtime. `call_register_entity_type_validators` calls this hook, not
209    /// the simpler one — override this to receive the composed vocabulary.
210    /// See `docs/api/pack.md#register_entity_type_validator` for the two-hook compatibility contract.
211    fn register_entity_type_validator_with_types(
212        &self,
213        runtime: &KhiveRuntime,
214        _pack_entity_types: &[EntityTypeDef],
215    ) {
216        self.register_entity_type_validator(runtime);
217    }
218
219    /// Install a pack-owned note-mutation hook on the runtime, called during pack
220    /// initialisation with the same timing as `register_entity_type_validator`. Packs
221    /// that cache derived state keyed by note content (e.g. `khive-pack-memory`'s warm
222    /// ANN index) override this to install a hook via
223    /// `KhiveRuntime::install_note_mutation_hook`. Default no-op leaves the hook absent.
224    /// See `docs/api/pack.md#register_note_mutation_hook` for cross-pack notification rationale.
225    fn register_note_mutation_hook(&self, _runtime: &KhiveRuntime) {}
226
227    /// Warm up any in-memory state from persisted snapshots (optional). Called after
228    /// all packs are registered but before serving the first request. Must be
229    /// idempotent and infallible — errors are logged internally, never propagated.
230    async fn warm(&self) {}
231
232    /// Names of all embedding models registered on this pack's underlying runtime
233    /// handle. Defaults to empty — only packs that own embedding-bearing verbs
234    /// (kg, memory) need to override this.
235    /// See `docs/api/pack.md#registered_embedding_model_names` for the ADR-103 consumer.
236    fn registered_embedding_model_names(&self) -> Vec<String> {
237        Vec::new()
238    }
239
240    /// Dispatch a verb call. Returns serialized JSON response.
241    ///
242    /// The `registry` parameter gives the handler access to the merged
243    /// vocabulary and kind hooks across all loaded packs.
244    /// The `token` is an authorized namespace token minted by the dispatch
245    /// boundary after gate authorization — handlers must use it directly.
246    async fn dispatch(
247        &self,
248        verb: &str,
249        params: Value,
250        registry: &VerbRegistry,
251        token: &NamespaceToken,
252    ) -> Result<Value, RuntimeError>;
253}
254
255/// Per-kind specialization for shared CRUD.
256///
257/// Packs implement `KindHook` for kinds they own that need:
258/// - **Defaults** filled into create args (e.g. `status="inbox"` for tasks)
259/// - **Derived properties** computed from args (e.g. salience from priority)
260/// - **Side-effect writes** after the storage commit (e.g. `depends_on` edges)
261/// - **Cross-pack validation** before shared CRUD mutates an owned kind
262///
263/// Hooks are stateless from the framework's perspective — they receive the
264/// runtime and the current mutation inputs as method parameters. The pack
265/// registers them via [`PackRuntime::kind_hook`].
266///
267/// Lifecycle verbs (e.g. gtd's `complete`, `transition`) remain pack-owned
268/// verbs. Shared `create`, note `update`, and `link` calls flow through this
269/// trait when an endpoint kind has an owning pack hook.
270#[async_trait]
271pub trait KindHook: Send + Sync + std::fmt::Debug {
272    /// Mutate args before the storage write. Fill defaults, normalize values,
273    /// rearrange user-facing fields into the storage shape expected by the
274    /// shared CRUD handler.
275    ///
276    /// Returning an error aborts the create call (no storage write happens).
277    async fn prepare_create(
278        &self,
279        runtime: &KhiveRuntime,
280        args: &mut Value,
281    ) -> Result<(), RuntimeError>;
282
283    /// Fire side effects after a successful storage write — graph edges,
284    /// derived observations, etc. The newly created record's UUID is passed
285    /// so the hook can attach metadata referencing it.
286    ///
287    /// Errors here are **logged but not propagated** — the storage write has
288    /// already succeeded; failing the call would mislead the caller.
289    /// Implementations should `tracing::warn!` and return `Ok(())` for
290    /// best-effort side effects.
291    async fn after_create(
292        &self,
293        runtime: &KhiveRuntime,
294        id: uuid::Uuid,
295        args: &Value,
296    ) -> Result<(), RuntimeError>;
297
298    /// Validate a shared note-property update before storage is mutated.
299    ///
300    /// The default accepts the update. Kind-owning packs override this when a
301    /// property has invariants that generic CRUD cannot know about (for
302    /// example, GTD task dependency acyclicity).
303    async fn validate_note_update(
304        &self,
305        _runtime: &KhiveRuntime,
306        _token: &NamespaceToken,
307        _note: &khive_storage::Note,
308        _properties: Option<&Value>,
309    ) -> Result<(), RuntimeError> {
310        Ok(())
311    }
312
313    /// Validate one or more shared graph links before any edge is written.
314    ///
315    /// A batch is supplied as a unit so a hook can reject a cycle formed only
316    /// by the proposed edges. The default accepts every link.
317    async fn validate_links(
318        &self,
319        _runtime: &KhiveRuntime,
320        _token: &NamespaceToken,
321        _links: &[crate::LinkSpec],
322    ) -> Result<(), RuntimeError> {
323        Ok(())
324    }
325}
326
327/// Optional sub-trait for packs that own private SQL tables and issue UUIDs
328/// that must be reachable through the generic `get(id)` and `delete(id)` verbs.
329///
330/// Implementing both methods is required — the sub-trait bundles them atomically
331/// so partial implementation is a compile-time error, not a runtime surprise.
332/// Packs whose records live in the shared entity/note substrate (gtd, memory)
333/// do not implement this sub-trait.
334#[async_trait]
335pub trait PackByIdResolver: Send + Sync {
336    /// Attempt to resolve a live (non-deleted) UUID owned by this pack's private tables.
337    ///
338    /// Returns `Some(Resolved::PackRecord { ... })` if this pack owns the UUID,
339    /// `None` if it does not (the caller continues to the next resolver),
340    /// or `Err(...)` on a storage error.
341    ///
342    /// Must query domain-authoritative tables before mirror tables.
343    /// Must NOT filter by namespace. UUID v4 is globally unique; by-ID
344    /// resolution is namespace-blind per ADR-007.
345    async fn resolve_by_id(
346        &self,
347        id: uuid::Uuid,
348    ) -> Result<Option<crate::Resolved>, crate::RuntimeError>;
349
350    /// Attempt to resolve a UUID including already-soft-deleted records.
351    ///
352    /// Used by the hard-delete path. Default delegates to `resolve_by_id`;
353    /// packs with `deleted_at` columns override this to query without the filter.
354    async fn resolve_by_id_including_deleted(
355        &self,
356        id: uuid::Uuid,
357    ) -> Result<Option<crate::Resolved>, crate::RuntimeError> {
358        self.resolve_by_id(id).await
359    }
360
361    /// Delete a record owned by this pack's private tables.
362    ///
363    /// `hard` mirrors the `delete` verb's `hard?` argument.
364    /// Default behavior for packs with a `deleted_at` column MUST be soft-delete;
365    /// `hard=true` performs permanent removal.
366    ///
367    /// Returns `Ok(Value)` with a `{ deleted: true, id, kind, hard }` body on success.
368    /// Returns `Err(RuntimeError::NotFound(...))` if the record does not exist.
369    async fn delete_by_id(
370        &self,
371        id: uuid::Uuid,
372        hard: bool,
373    ) -> Result<serde_json::Value, crate::RuntimeError>;
374}
375
376/// Builder for constructing a `VerbRegistry`.
377///
378/// Packs are registered here; once `.build()` is called the registry is
379/// immutable and cheaply cloneable.
380pub struct VerbRegistryBuilder {
381    packs: Vec<Box<dyn PackRuntime>>,
382    resolvers: Vec<(String, Box<dyn PackByIdResolver>)>,
383    gate: GateRef,
384    default_namespace: String,
385    /// Operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
386    ///
387    /// Threads into `VerbRegistry::visible_namespaces` and is consumed by the
388    /// default dispatch path to widen read scope to `['local'] ∪ visible_namespaces`.
389    /// Writes remain pinned to `'local'`. An explicit `namespace=` request param
390    /// is a precise escape and is not widened by this set. A cloud gate may also
391    /// consult the list as policy input at its own layer.
392    visible_namespaces: Vec<Namespace>,
393    /// Configured actor identity label (ADR-057). When set, dispatch mints tokens
394    /// carrying this actor so that `comm.inbox` filters by `to_actor`.
395    actor_id: Option<String>,
396    /// Optional audit event sink.
397    ///
398    /// When set, every gate check writes a storage `Event` in addition to the
399    /// `tracing::info!` emission. The store is `Arc<dyn EventStore>` so the
400    /// registry does not depend on the full `KhiveRuntime` surface — only the
401    /// audit-persistence capability is needed here.
402    event_store: Option<Arc<dyn EventStore>>,
403    /// Optional post-dispatch hook.
404    ///
405    /// When set, every successful pack dispatch calls `hook.on_dispatch(view)`
406    /// with a synthetic `EventView` describing the outcome and carrying no
407    /// observations. Opt-in: when None, no overhead is incurred.
408    dispatch_hook: Option<Arc<dyn DispatchHook>>,
409}
410
411impl VerbRegistryBuilder {
412    /// Create a builder with no packs, `AllowAllGate`, and the local namespace as default.
413    pub fn new() -> Self {
414        Self {
415            packs: Vec::new(),
416            resolvers: Vec::new(),
417            gate: std::sync::Arc::new(AllowAllGate),
418            default_namespace: Namespace::local().as_str().to_string(),
419            visible_namespaces: vec![],
420            actor_id: None,
421            event_store: None,
422            dispatch_hook: None,
423        }
424    }
425
426    /// Set the operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
427    ///
428    /// On the default (no explicit `namespace=` param) dispatch path, reads fan
429    /// out over `['local'] ∪ ns`. Writes remain pinned to `'local'`. An explicit
430    /// `namespace=` request parameter is a precise single-namespace escape and
431    /// is not widened by this set. A cloud gate may also consult the list as
432    /// policy input at its own layer.
433    pub fn with_visible_namespaces(&mut self, ns: Vec<Namespace>) -> &mut Self {
434        self.visible_namespaces = ns;
435        self
436    }
437
438    /// Set the configured actor identity label (ADR-057).
439    ///
440    /// When set, the dispatch path mints tokens carrying this actor so that
441    /// `comm.inbox` applies the `to_actor` filter for directed delivery.
442    /// When `None` (default), tokens carry `ActorRef::anonymous()` and inbox
443    /// falls back to party-line behavior.
444    pub fn with_actor_id(&mut self, actor_id: Option<String>) -> &mut Self {
445        self.actor_id = actor_id;
446        self
447    }
448
449    /// Register a pack. The bound `P: Pack + PackRuntime` ensures the pack
450    /// declares vocabulary via `Pack` consts alongside runtime dispatch.
451    pub fn register<P: khive_types::Pack + PackRuntime + 'static>(&mut self, pack: P) -> &mut Self {
452        self.packs.push(Box::new(pack));
453        self
454    }
455
456    /// Register a boxed pack directly.
457    ///
458    /// Crate-private: only [`PackRegistry::register_packs`] should call this.
459    /// External callers must use the typed [`Self::register`] which enforces the
460    /// `Pack + PackRuntime` dual-impl contract at the call site.  Here the
461    /// contract is satisfied upstream at the [`PackFactory::create`] site.
462    pub(crate) fn register_boxed(&mut self, pack: Box<dyn PackRuntime>) -> &mut Self {
463        self.packs.push(pack);
464        self
465    }
466
467    /// Register a by-ID resolver for a pack that owns private SQL tables.
468    ///
469    /// Packs that implement `PackByIdResolver` call this during their boot path
470    /// so that `get(id)` and `delete(id)` can reach their records.
471    pub fn register_resolver(
472        &mut self,
473        name: impl Into<String>,
474        resolver: Box<dyn PackByIdResolver>,
475    ) -> &mut Self {
476        self.resolvers.push((name.into(), resolver));
477        self
478    }
479
480    /// Set the authorization gate consulted on every dispatch.
481    ///
482    /// Defaults to `AllowAllGate` if not set. `Deny` is authoritative — a deny
483    /// decision aborts dispatch with `RuntimeError::PermissionDenied`. Gate
484    /// infrastructure errors fail open (logged via `tracing::warn!`, dispatch
485    /// proceeds).
486    pub fn with_gate(&mut self, gate: GateRef) -> &mut Self {
487        self.gate = gate;
488        self
489    }
490
491    /// Set the namespace surfaced to the gate when a verb does not carry an
492    /// explicit `namespace` argument. Transports should plumb the runtime's
493    /// `default_namespace` so the gate's `input.namespace` always reflects
494    /// the operation's true tenant.
495    pub fn with_default_namespace(&mut self, ns: impl Into<String>) -> &mut Self {
496        self.default_namespace = ns.into();
497        self
498    }
499
500    /// Set the `EventStore` used to persist audit events.
501    ///
502    /// When configured, every gate check appends one `Event` (substrate =
503    /// `Event`, outcome = `Success` on allow, `Denied` on deny) in addition to
504    /// the `tracing::info!` emission that was already present in v0.2.
505    ///
506    /// Callers that do not set this field continue to use tracing-only emission
507    /// (the v0.2 default). There is no behavior change for them.
508    pub fn with_event_store(&mut self, store: Arc<dyn EventStore>) -> &mut Self {
509        self.event_store = Some(store);
510        self
511    }
512
513    /// Register a post-dispatch hook.
514    ///
515    /// When set, every successful pack dispatch calls `hook.on_dispatch(view)`
516    /// with a synthetic [`EventView`] describing the verb outcome. Its
517    /// `observations` vector is empty; callers that need persisted provenance
518    /// must load it explicitly. The hook is opt-in: registries without a hook
519    /// incur zero overhead on the dispatch hot path.
520    ///
521    /// Brain pack uses this as a best-effort in-memory update path. Errors from
522    /// `on_dispatch` are logged via `tracing::warn!` and never propagated.
523    pub fn with_dispatch_hook(&mut self, hook: Arc<dyn DispatchHook>) -> &mut Self {
524        self.dispatch_hook = Some(hook);
525        self
526    }
527
528    /// Consume the builder and produce an immutable, cloneable registry.
529    ///
530    /// Performs a topological sort of packs using Kahn's algorithm.
531    /// Returns an error if any declared dependency is missing from the loaded
532    /// pack set, or if a circular dependency is detected.
533    pub fn build(self) -> Result<VerbRegistry, RuntimeError> {
534        let packs = self.packs;
535        let mut name_to_idx: HashMap<&str, usize> = HashMap::with_capacity(packs.len());
536        for (idx, pack) in packs.iter().enumerate() {
537            if let Some(prev_idx) = name_to_idx.insert(pack.name(), idx) {
538                return Err(RuntimeError::PackRedeclared {
539                    name: pack.name().to_string(),
540                    first_idx: prev_idx,
541                    second_idx: idx,
542                });
543            }
544        }
545
546        let mut missing: Vec<MissingPackDependency> = Vec::new();
547        let mut indegree = vec![0usize; packs.len()];
548        let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); packs.len()];
549
550        for (idx, pack) in packs.iter().enumerate() {
551            for &requires in pack.requires() {
552                match name_to_idx.get(requires).copied() {
553                    Some(dep_idx) => {
554                        dependents[dep_idx].push(idx);
555                        indegree[idx] += 1;
556                    }
557                    None => missing.push(MissingPackDependency {
558                        from: pack.name().to_string(),
559                        requires: requires.to_string(),
560                    }),
561                }
562            }
563        }
564
565        if !missing.is_empty() {
566            return if missing.len() == 1 {
567                Err(RuntimeError::MissingPackDependency(missing.remove(0)))
568            } else {
569                Err(RuntimeError::MissingPackDependencies(
570                    MissingPackDependencies { missing },
571                ))
572            };
573        }
574
575        let mut ready: VecDeque<usize> = indegree
576            .iter()
577            .enumerate()
578            .filter_map(|(idx, degree)| (*degree == 0).then_some(idx))
579            .collect();
580        let mut ordered_indices = Vec::with_capacity(packs.len());
581
582        while let Some(idx) = ready.pop_front() {
583            ordered_indices.push(idx);
584            for &dep_idx in &dependents[idx] {
585                indegree[dep_idx] -= 1;
586                if indegree[dep_idx] == 0 {
587                    ready.push_back(dep_idx);
588                }
589            }
590        }
591
592        if ordered_indices.len() != packs.len() {
593            let cycle_nodes: HashSet<usize> = indegree
594                .iter()
595                .enumerate()
596                .filter_map(|(idx, degree)| (*degree > 0).then_some(idx))
597                .collect();
598            let cycle = find_pack_dependency_cycle(&packs, &name_to_idx, &cycle_nodes);
599            return Err(RuntimeError::CircularPackDependency(
600                CircularPackDependency { cycle },
601            ));
602        }
603
604        let mut slots: Vec<Option<Box<dyn PackRuntime>>> = packs.into_iter().map(Some).collect();
605        let ordered_packs: Vec<Box<dyn PackRuntime>> = ordered_indices
606            .into_iter()
607            .map(|idx| slots[idx].take().expect("topological index must exist"))
608            .collect();
609
610        validate_unique_note_kinds(&ordered_packs)?;
611        validate_unique_verb_names(&ordered_packs)?;
612        validate_unique_entity_types(&ordered_packs)?;
613        validate_brain_consumer_kinds(&ordered_packs)?;
614
615        let available_verbs: Vec<&'static str> = ordered_packs
616            .iter()
617            .flat_map(|p| p.handlers().iter())
618            .filter(|h| matches!(h.visibility, Visibility::Verb))
619            .map(|h| h.name)
620            .collect();
621
622        Ok(VerbRegistry {
623            packs: Arc::new(ordered_packs),
624            resolvers: Arc::new(self.resolvers),
625            gate: self.gate,
626            default_namespace: self.default_namespace,
627            visible_namespaces: self.visible_namespaces,
628            actor_id: self.actor_id,
629            event_store: self.event_store,
630            dispatch_hook: self.dispatch_hook,
631            available_verbs: Arc::new(available_verbs),
632            reference_ring: Arc::new(crate::reference_ring::ReferenceRing::new()),
633        })
634    }
635}
636
637/// Validate that no two packs declare the same note kind.
638///
639/// Boot-time duplicate detection prevents pack configuration errors from
640/// silently corrupting note kind routing. Returns an error naming the
641/// duplicate kind and the two packs that claim it.
642fn validate_unique_note_kinds(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
643    let mut seen: HashMap<&str, &str> = HashMap::new();
644    for pack in packs {
645        for &kind in pack.note_kinds() {
646            if let Some(first_pack) = seen.insert(kind, pack.name()) {
647                return Err(RuntimeError::InvalidInput(format!(
648                    "duplicate note kind {kind:?}: claimed by both {first_pack:?} and {:?}",
649                    pack.name()
650                )));
651            }
652        }
653    }
654    Ok(())
655}
656
657/// Validate pack-declared brain consumer kinds at the composition boundary.
658///
659/// The wildcard belongs to the binding matcher rather than any consumer, and
660/// whitespace-bearing values can never equal the exact wire values callers
661/// request. Reject both at boot so a malformed declaration cannot make an
662/// otherwise unreachable binding appear valid.
663fn validate_brain_consumer_kinds(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
664    for pack in packs {
665        for &kind in pack.brain_consumer_kinds() {
666            if kind == "*" || kind.trim().is_empty() || kind.trim() != kind {
667                return Err(RuntimeError::InvalidInput(format!(
668                    "pack {:?} declares invalid brain consumer kind {kind:?}; declarations must be non-empty exact wire values and must not use the registry-owned \"*\" wildcard",
669                    pack.name()
670                )));
671            }
672        }
673    }
674    Ok(())
675}
676
677/// Validate that no two packs declare the same `Visibility::Verb` handler name.
678///
679/// `Visibility::Subhandler` entries are pack-prefixed by convention and excluded
680/// from cross-pack collision detection. Two packs declaring the same subhandler
681/// name prefix (e.g. `recall.embed`) would be a pack-authoring error but does not
682/// produce a cross-pack routing conflict since only the owning pack dispatches them.
683fn validate_unique_verb_names(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
684    let mut seen: HashMap<&str, &str> = HashMap::new();
685    for pack in packs {
686        for handler in pack.handlers() {
687            if !matches!(handler.visibility, Visibility::Verb) {
688                continue;
689            }
690            if let Some(first_pack) = seen.insert(handler.name, pack.name()) {
691                return Err(RuntimeError::VerbCollision {
692                    verb: handler.name.to_string(),
693                    first_pack: first_pack.to_string(),
694                    second_pack: pack.name().to_string(),
695                });
696            }
697        }
698    }
699    Ok(())
700}
701
702/// Validate that no two owners (the built-in table or a loaded pack) declare
703/// a colliding `entity_type` canonical name or alias.
704///
705/// Boot-time duplicate detection prevents pack configuration errors from
706/// silently applying insertion-order semantics to entity-type resolution
707/// (ADR-001's registry-ownership collision rule: same `(base_kind,
708/// canonical_name)` from two different packs, or an alias collision, is a
709/// boot error). Returns an error naming the colliding key and both
710/// contributing owners.
711fn validate_unique_entity_types(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
712    let owned_defs = packs
713        .iter()
714        .flat_map(|p| p.entity_types().iter().map(move |def| (p.name(), def)));
715    khive_types::EntityTypeRegistry::check_extra_collisions(owned_defs)
716        .map_err(RuntimeError::InvalidInput)
717}
718
719fn find_pack_dependency_cycle(
720    packs: &[Box<dyn PackRuntime>],
721    name_to_idx: &HashMap<&str, usize>,
722    cycle_nodes: &HashSet<usize>,
723) -> Vec<String> {
724    fn visit(
725        idx: usize,
726        packs: &[Box<dyn PackRuntime>],
727        name_to_idx: &HashMap<&str, usize>,
728        cycle_nodes: &HashSet<usize>,
729        visiting: &mut Vec<usize>,
730        visited: &mut HashSet<usize>,
731    ) -> Option<Vec<String>> {
732        if let Some(pos) = visiting.iter().position(|&seen| seen == idx) {
733            let mut cycle: Vec<String> = visiting[pos..]
734                .iter()
735                .map(|&i| packs[i].name().to_string())
736                .collect();
737            cycle.push(packs[idx].name().to_string());
738            return Some(cycle);
739        }
740        if !visited.insert(idx) {
741            return None;
742        }
743        visiting.push(idx);
744        for &req in packs[idx].requires() {
745            let Some(&dep_idx) = name_to_idx.get(req) else {
746                continue;
747            };
748            if cycle_nodes.contains(&dep_idx) {
749                if let Some(cycle) =
750                    visit(dep_idx, packs, name_to_idx, cycle_nodes, visiting, visited)
751                {
752                    return Some(cycle);
753                }
754            }
755        }
756        visiting.pop();
757        None
758    }
759
760    let mut visited = HashSet::new();
761    for &idx in cycle_nodes {
762        let mut visiting = Vec::new();
763        if let Some(cycle) = visit(
764            idx,
765            packs,
766            name_to_idx,
767            cycle_nodes,
768            &mut visiting,
769            &mut visited,
770        ) {
771            return cycle;
772        }
773    }
774    cycle_nodes
775        .iter()
776        .map(|&idx| packs[idx].name().to_string())
777        .collect()
778}
779
780impl Default for VerbRegistryBuilder {
781    fn default() -> Self {
782        Self::new()
783    }
784}
785
786/// Immutable registry that dispatches verb calls to registered packs.
787///
788/// Clone is cheap (Arc-wrapped). Constructed via `VerbRegistryBuilder`.
789#[derive(Clone)]
790pub struct VerbRegistry {
791    packs: std::sync::Arc<Vec<Box<dyn PackRuntime>>>,
792    /// Pack-level by-ID resolvers, in registration order.
793    resolvers: std::sync::Arc<Vec<(String, Box<dyn PackByIdResolver>)>>,
794    gate: GateRef,
795    default_namespace: String,
796    /// Operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
797    ///
798    /// On the default (no explicit `namespace=` param) dispatch path, reads fan
799    /// out over `['local'] ∪ visible_namespaces`. Writes are unaffected — they
800    /// still pin to `'local'`. An explicit `namespace=` request param is a
801    /// precise single-namespace escape and is not widened by this set.
802    visible_namespaces: Vec<Namespace>,
803    /// Configured actor identity label (ADR-057). When `Some`, dispatch mints
804    /// tokens carrying this actor so that `comm.inbox` applies the `to_actor`
805    /// filter. When `None`, tokens carry `ActorRef::anonymous()` (party-line).
806    actor_id: Option<String>,
807    /// Audit event sink — `None` means tracing-only (v0.2 default).
808    event_store: Option<Arc<dyn EventStore>>,
809    /// Post-dispatch hook: `None` means no real-time observation.
810    dispatch_hook: Option<Arc<dyn DispatchHook>>,
811    /// Names of all `Visibility::Verb` handlers across all packs, precomputed
812    /// once at `build()` time. Used only to render the unknown-verb error
813    /// message — the pack set is fixed after construction, so there is no
814    /// need to re-scan every pack's handlers on every miss.
815    available_verbs: Arc<Vec<&'static str>>,
816    /// Recently-referenced ring (unified-verb draft ADR, Slice 1). Daemon-warm,
817    /// actor-scoped, never persisted — see `crate::reference_ring`. Shared
818    /// across every clone of this registry via the `Arc`, so admissions made
819    /// by one dispatch are visible to the next on the same warm daemon.
820    reference_ring: Arc<crate::reference_ring::ReferenceRing>,
821}
822
823/// Per-request identity context that overrides a [`VerbRegistry`]'s
824/// construction-baked `default_namespace` / `actor_id` / `visible_namespaces`
825/// for exactly one [`VerbRegistry::dispatch_with_identity`] call (ADR-096
826/// Fork 1 — warm-daemon per-request identity).
827///
828/// A single warm registry is built once with a baked identity, but must be
829/// able to serve requests whose caller resolved a *different* attribution
830/// identity (e.g. a different project-local `[actor]`) without a cold
831/// fallback and without mis-stamping writes under the registry's own baked
832/// actor. Supplying `Some(RequestIdentity { .. })` threads the caller's
833/// identity through token minting for that one call; the registry's fields
834/// (and every other in-flight call) are untouched. `None` is exactly
835/// [`VerbRegistry::dispatch`] — the baked scalars apply, unchanged from
836/// before this type existed.
837#[derive(Debug, Clone, Default)]
838pub struct RequestIdentity {
839    /// Storage/gate default namespace for this request (used when the verb's
840    /// own params carry no explicit `namespace` field). Overrides
841    /// `VerbRegistry::default_namespace`.
842    pub namespace: String,
843    /// Write-stamp / gate actor label for this request (ADR-057). Overrides
844    /// `VerbRegistry::actor_id`. `None` mints `ActorRef::anonymous()`, same
845    /// as an unconfigured baked `actor_id`.
846    pub actor_id: Option<String>,
847    /// Extra read-visibility namespaces for this request (ADR-007 Rev 4 Rule
848    /// 3b). Overrides `VerbRegistry::visible_namespaces`. Entries that fail
849    /// `Namespace::parse` are skipped with a `tracing::warn!` rather than
850    /// failing the whole request — a single malformed visibility entry from a
851    /// caller-supplied frame must not block dispatch.
852    pub visible_namespaces: Vec<String>,
853    /// Opaque process provenance resolved by the originating request process.
854    /// `None` means the origin did not set one; a warm daemon must not replace
855    /// it with its own process environment. This field is attribution-only and
856    /// never participates in the gate or token authority.
857    pub process_ref: Option<String>,
858    /// Caller-supplied correlation id for this request (khive#948), carried
859    /// unchanged from the daemon frame's `request_id` field. Stamped into the
860    /// audit event's `resource.request_id` on every outcome (success, error,
861    /// and denied) so a client can join its own pre-send sample to the
862    /// server-side audit row for the same request. `None` means the caller
863    /// supplied no id (a pre-#948 client, or an internal/non-benchmark
864    /// caller) — the audit row then carries no `request_id` key at all.
865    pub request_id: Option<u64>,
866}
867
868impl RequestIdentity {
869    /// Reconstruct the effective principal and namespace scope carried by an
870    /// already-authorized token for a nested registry dispatch.
871    ///
872    /// Cross-pack calls must still pass through the registry Gate, but using
873    /// the registry's construction-baked identity would silently replace a
874    /// warm daemon request's actor and visibility (ADR-096). This projection
875    /// preserves the token's exact primary namespace, actor, and read-visible
876    /// namespaces, and the origin's process provenance rider. A
877    /// `NamespaceToken` does not carry the ingress correlation id, so nested
878    /// calls intentionally use `request_id: None`; `process_ref` IS carried by
879    /// the token (ADR-096: an absent value stays absent, a present origin
880    /// rider survives nested dispatch without reading the daemon
881    /// environment).
882    pub fn from_token(token: &NamespaceToken) -> Self {
883        Self {
884            namespace: token.namespace().as_str().to_string(),
885            actor_id: token.actor().binding_id().map(str::to_string),
886            visible_namespaces: token
887                .visible_namespaces()
888                .iter()
889                .map(|namespace| namespace.as_str().to_string())
890                .collect(),
891            process_ref: token.process_ref().map(str::to_owned),
892            request_id: None,
893        }
894    }
895}
896
897/// A non-blank, out-of-band authenticated principal for [`VerbRegistry::dispatch_as`].
898///
899/// Embedding hosts authenticate a principal through their own channel (not the
900/// request DSL) and then need that principal to become the effective actor
901/// for one dispatch. The constructor rejects an empty or whitespace-only
902/// identifier so an authentication-integration failure (an empty subject)
903/// fails closed at construction time instead of silently resolving to the
904/// anonymous/local actor at dispatch time — see [`crate::actor_identity::resolve_actor`].
905#[derive(Debug, Clone, PartialEq, Eq)]
906pub struct VerifiedActor(String);
907
908impl VerifiedActor {
909    /// Validate and wrap a verified principal identifier.
910    ///
911    /// Returns `RuntimeError::InvalidInput` when `id` is empty or contains
912    /// only whitespace.
913    pub fn new(id: impl Into<String>) -> Result<Self, RuntimeError> {
914        let id = id.into();
915        if id.trim().is_empty() {
916            return Err(RuntimeError::InvalidInput(
917                "VerifiedActor: identifier must not be empty or whitespace-only".to_string(),
918            ));
919        }
920        Ok(Self(id))
921    }
922
923    /// Borrow the validated identifier.
924    pub fn as_str(&self) -> &str {
925        &self.0
926    }
927
928    fn into_inner(self) -> String {
929        self.0
930    }
931}
932
933/// Error returned by [`VerbRegistry::apply_schema_plans_with_map`] when two
934/// packs on the same backend declare the same auxiliary table (ADR-028 §7).
935#[derive(Debug)]
936pub struct PackSchemaCollisionError {
937    /// First pack to declare the table.
938    pub pack_a: &'static str,
939    /// Second pack that collides with `pack_a`.
940    pub pack_b: &'static str,
941    /// Table name or DDL error description.
942    pub table: String,
943}
944
945impl std::fmt::Display for PackSchemaCollisionError {
946    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
947        if self.pack_a == self.pack_b {
948            write!(
949                f,
950                "pack schema boot failure for pack {:?}: {}",
951                self.pack_a, self.table
952            )
953        } else {
954            write!(
955                f,
956                "pack schema collision: packs {:?} and {:?} both declare table {:?} \
957                 on the same backend — move one pack to a separate backend or rename the table",
958                self.pack_a, self.pack_b, self.table
959            )
960        }
961    }
962}
963
964impl std::error::Error for PackSchemaCollisionError {}
965
966/// Extract table names from a single DDL statement.
967///
968/// Handles `CREATE TABLE IF NOT EXISTS`, `CREATE TABLE`, and
969/// `CREATE VIRTUAL TABLE IF NOT EXISTS`, `CREATE VIRTUAL TABLE`.
970/// Returns an empty Vec when no table name is found (e.g. index DDL).
971fn extract_table_names(stmt: &str) -> Vec<String> {
972    let normalized = stmt.split_whitespace().collect::<Vec<_>>().join(" ");
973    let upper = normalized.to_ascii_uppercase();
974    let table_name = if let Some(rest) = upper.strip_prefix("CREATE VIRTUAL TABLE IF NOT EXISTS ") {
975        rest.split_whitespace().next()
976    } else if let Some(rest) = upper.strip_prefix("CREATE VIRTUAL TABLE ") {
977        rest.split_whitespace().next()
978    } else if let Some(rest) = upper.strip_prefix("CREATE TABLE IF NOT EXISTS ") {
979        rest.split_whitespace().next()
980    } else if let Some(rest) = upper.strip_prefix("CREATE TABLE ") {
981        rest.split_whitespace().next()
982    } else {
983        None
984    };
985    match table_name {
986        Some(name) => {
987            let clean = name.trim_matches(|c: char| c == '(' || c == ';');
988            if clean.is_empty() {
989                vec![]
990            } else {
991                vec![clean.to_ascii_lowercase()]
992            }
993        }
994        None => vec![],
995    }
996}
997
998/// Render an [`EndpointKind`] as the `"<substrate>:<kind>"` label used in
999/// `link(help=true)`'s `endpoint_rules` table.
1000fn endpoint_kind_label(kind: &EndpointKind) -> String {
1001    match kind {
1002        EndpointKind::EntityOfKind(k) => format!("entity:{k}"),
1003        EndpointKind::NoteOfKind(k) => format!("note:{k}"),
1004        EndpointKind::EntityOfType { kind, entity_type } => {
1005            format!("entity:{kind}({entity_type})")
1006        }
1007    }
1008}
1009
1010/// Relations `validate_edge_relation_endpoints`
1011/// (`crates/khive-runtime/src/operations.rs`) resolves in its own dedicated
1012/// branch — before the generic pack-rule branch (`pack_rule_allows`) is ever
1013/// reached. For these three relations the validator additionally accepts
1014/// any `note -> note` pair unconditionally, regardless of note kind
1015/// (ADR-002 §"Versioning" and §"Epistemic"), and never consults pack
1016/// `EDGE_RULES` at all, on either substrate.
1017pub(crate) const SPECIAL_RELATIONS: &[khive_types::EdgeRelation] = &[
1018    khive_types::EdgeRelation::Supersedes,
1019    khive_types::EdgeRelation::Supports,
1020    khive_types::EdgeRelation::Refutes,
1021];
1022
1023pub(crate) fn is_special_relation(relation: khive_types::EdgeRelation) -> bool {
1024    SPECIAL_RELATIONS.contains(&relation)
1025}
1026
1027/// Compose the full per-relation endpoint allowlist surfaced by
1028/// `link(help=true)` (issue #964).
1029///
1030/// Combines the base entity-to-entity endpoint contract
1031/// (`operations::base_entity_endpoint_rules`) with every loaded pack's
1032/// additive `EDGE_RULES`, the unconditional `note -> note` allowance for the
1033/// three special relations (`supersedes` / `supports` / `refutes` —
1034/// `operations.rs`'s dedicated special-relation branch), and the
1035/// `annotates` note-to-any special case — the exact same sources
1036/// `valid_relations_for_entity_pair` (`khive-pack-kg`) consults when
1037/// enriching a rejected `link` call, so a caller reading this table cannot
1038/// diverge from what the validator itself accepts.
1039///
1040/// Pack `EDGE_RULES` for a special relation are deliberately excluded: the
1041/// validator's special-relation branch returns before `pack_rule_allows` is
1042/// ever reached (`operations.rs`), so advertising such a rule here would
1043/// claim enforcement that never actually happens.
1044fn edge_endpoint_table(packs: &[Box<dyn PackRuntime>]) -> Vec<Value> {
1045    let mut rows: Vec<Value> = crate::operations::base_entity_endpoint_rules()
1046        .iter()
1047        .map(|(src, rel, tgt)| {
1048            serde_json::json!({
1049                "relation": rel.as_str(),
1050                "source": format!("entity:{src}"),
1051                "target": format!("entity:{tgt}"),
1052            })
1053        })
1054        .collect();
1055
1056    for rel in SPECIAL_RELATIONS {
1057        rows.push(serde_json::json!({
1058            "relation": rel.as_str(),
1059            "source": "note:*",
1060            "target": "note:*",
1061        }));
1062    }
1063
1064    for pack in packs.iter() {
1065        for rule in pack.edge_rules().iter() {
1066            if is_special_relation(rule.relation) {
1067                continue;
1068            }
1069            rows.push(serde_json::json!({
1070                "relation": rule.relation.as_str(),
1071                "source": endpoint_kind_label(&rule.source),
1072                "target": endpoint_kind_label(&rule.target),
1073            }));
1074        }
1075    }
1076
1077    rows.push(serde_json::json!({
1078        "relation": "annotates",
1079        "source": "note:*",
1080        "target": "any (entity, note, edge, or event)",
1081    }));
1082
1083    rows
1084}
1085
1086impl VerbRegistry {
1087    /// This registry's construction-baked default namespace.
1088    ///
1089    /// Used as the fallback when a request carries no [`RequestIdentity`]
1090    /// override (ADR-096 Fork 1) and by transports that need to advertise
1091    /// their own resolved identity when forwarding to a warm daemon.
1092    pub fn default_namespace(&self) -> &str {
1093        &self.default_namespace
1094    }
1095
1096    /// This registry's construction-baked actor identity label, if configured
1097    /// (ADR-057). `None` means dispatch mints `ActorRef::anonymous()` absent a
1098    /// per-request [`RequestIdentity`] override (ADR-096 Fork 1).
1099    pub fn actor_id(&self) -> Option<&str> {
1100        self.actor_id.as_deref()
1101    }
1102
1103    /// This registry's construction-baked extra read-visibility namespaces
1104    /// (ADR-007 Rev 4 Rule 3b), used absent a per-request [`RequestIdentity`]
1105    /// override (ADR-096 Fork 1).
1106    pub fn visible_namespaces(&self) -> &[Namespace] {
1107        &self.visible_namespaces
1108    }
1109
1110    /// This registry's configured audit `EventStore`, if any (ADR-094).
1111    ///
1112    /// Lets background tasks that hold a `VerbRegistry` but do not go through
1113    /// `dispatch` (e.g. the email channel poll loop) append best-effort
1114    /// lifecycle events to the same sink gate-check audit rows use, without
1115    /// threading a second `Option<Arc<dyn EventStore>>` field through every
1116    /// caller. `None` means tracing-only, matching the registry's own
1117    /// audit-persistence default.
1118    pub fn event_store(&self) -> Option<Arc<dyn EventStore>> {
1119        self.event_store.clone()
1120    }
1121
1122    /// Return the help schema envelope for a verb.
1123    ///
1124    /// Walks registered packs for the first matching `HandlerDef` and returns a
1125    /// structured JSON envelope. Subhandlers carry `callable_via_mcp: false`.
1126    /// `link`'s envelope additionally carries `endpoint_rules` — the composed
1127    /// per-relation source/target allowlist (issue #964) — so batch callers can
1128    /// defer to the kernel's own table instead of re-implementing it locally.
1129    /// Unknown verbs return `RuntimeError::InvalidInput`. Full shape documented
1130    /// in `docs/protocol.md` §Request Schema.
1131    pub fn describe_verb(&self, verb: &str) -> Result<Value, RuntimeError> {
1132        for pack in self.packs.iter() {
1133            for handler in pack.handlers().iter() {
1134                if handler.name == verb {
1135                    let category = format!("{:?}", handler.category);
1136                    let params_arr: Vec<Value> = handler
1137                        .params
1138                        .iter()
1139                        .map(|p| {
1140                            serde_json::json!({
1141                                "name": p.name,
1142                                "type": p.param_type,
1143                                "required": p.required,
1144                                "description": p.description,
1145                            })
1146                        })
1147                        .collect();
1148                    // Subhandlers are not callable via the MCP request surface;
1149                    // the help payload must match the behaviour the dispatch
1150                    // path enforces so callers reading `help=true` before
1151                    // probing see accurate availability.
1152                    if matches!(handler.visibility, Visibility::Subhandler) {
1153                        return Ok(serde_json::json!({
1154                            "verb": verb,
1155                            "pack": pack.name(),
1156                            "description": handler.description,
1157                            "category": category,
1158                            "params": params_arr,
1159                            "visibility": "internal",
1160                            "callable_via_mcp": false,
1161                            "note": "This is an internal subhandler. Calling it via the MCP \
1162                                     request surface returns permission denied. It can only be \
1163                                     invoked by internal runtime callers.",
1164                        }));
1165                    }
1166                    let mut envelope = serde_json::json!({
1167                        "verb": verb,
1168                        "pack": pack.name(),
1169                        "description": handler.description,
1170                        "category": category,
1171                        "params": params_arr,
1172                    });
1173                    if verb == "link" {
1174                        envelope["endpoint_rules"] = Value::Array(edge_endpoint_table(&self.packs));
1175                    }
1176                    return Ok(envelope);
1177                }
1178            }
1179        }
1180        // Verb-visibility handler names, precomputed at build() time (internal
1181        // subhandlers are excluded so they are not advertised in the
1182        // unknown-verb error).
1183        Err(RuntimeError::InvalidInput(format!(
1184            "unknown verb {verb:?}; available: {}",
1185            self.available_verbs.join(", ")
1186        )))
1187    }
1188
1189    /// Check whether the gate permits writes into `ns`.
1190    ///
1191    /// Performs a gate evaluation with verb `"authorize"` before any background
1192    /// loop is spawned (ADR-056 §6).  Returns `Ok(())` when the gate allows the
1193    /// namespace, or `Err(RuntimeError::PermissionDenied{..})` when denied.
1194    /// Gate errors (implementation failures) are surfaced as
1195    /// `RuntimeError::Internal`.
1196    pub fn authorize_namespace(&self, ns: Namespace) -> Result<(), RuntimeError> {
1197        let actor = crate::actor_identity::resolve_actor(self.actor_id.as_deref());
1198        let req = GateRequest::new(actor, ns, "authorize", serde_json::Value::Null);
1199        match self.gate.check(&req) {
1200            Ok(decision) if decision.is_allow() => Ok(()),
1201            Ok(GateDecision::Deny { reason }) => Err(RuntimeError::PermissionDenied {
1202                verb: "authorize".to_string(),
1203                reason,
1204            }),
1205            Ok(_) => Err(RuntimeError::PermissionDenied {
1206                verb: "authorize".to_string(),
1207                reason: "gate denied".to_string(),
1208            }),
1209            Err(e) => Err(RuntimeError::Internal(format!("gate error: {e}"))),
1210        }
1211    }
1212
1213    /// Gate and execute an operation handled outside normal pack dispatch.
1214    ///
1215    /// Multi-backend transports use this to route an operation through a
1216    /// coordinator while retaining [`Self::dispatch_with_identity`]'s gate and
1217    /// audit lifecycle. Deny is authoritative, gate errors fail open, and an
1218    /// allowed audit is persisted after the intercepted operation resolves so
1219    /// its outcome and duration reflect the operation result.
1220    pub async fn dispatch_intercepted_with_identity<F, Fut>(
1221        &self,
1222        verb: &str,
1223        params: &Value,
1224        identity: Option<&RequestIdentity>,
1225        dispatch: F,
1226    ) -> Result<Value, RuntimeError>
1227    where
1228        F: FnOnce(Namespace) -> Fut,
1229        Fut: std::future::Future<Output = Result<Value, RuntimeError>>,
1230    {
1231        let request_id = identity.and_then(|id| id.request_id);
1232        let gate_req = self.gate_request_with_identity(verb, params, identity)?;
1233        let deferred_audit = match self.gate.check(&gate_req) {
1234            Ok(decision) => {
1235                let audit = AuditEvent::from_check(&gate_req, &decision, self.gate.impl_name());
1236                tracing::info!(
1237                    audit_event = %serde_json::to_string(&audit)
1238                        .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
1239                    "gate.check"
1240                );
1241                if let GateDecision::Deny { reason } = decision {
1242                    if let Some(store) = &self.event_store {
1243                        let event = build_audit_storage_event(
1244                            &gate_req,
1245                            &audit,
1246                            EventOutcome::Denied,
1247                            Some(crate::cost_unit::base_resource_payload(request_id)),
1248                        );
1249                        append_audit_event_best_effort(store, event, verb).await;
1250                    }
1251                    return Err(RuntimeError::PermissionDenied {
1252                        verb: verb.to_string(),
1253                        reason,
1254                    });
1255                }
1256                Some(audit)
1257            }
1258            Err(err) => {
1259                tracing::warn!(verb, error = %err, "gate check failed (fail-open)");
1260                None
1261            }
1262        };
1263
1264        let started = Instant::now();
1265        let result = dispatch(gate_req.namespace.clone()).await;
1266        let duration_us = started.elapsed().as_micros() as i64;
1267        if let Some(audit) = deferred_audit {
1268            self.persist_intercepted_audit(
1269                verb,
1270                &gate_req,
1271                audit,
1272                &result,
1273                duration_us,
1274                request_id,
1275            )
1276            .await;
1277        }
1278        result
1279    }
1280
1281    async fn persist_intercepted_audit(
1282        &self,
1283        verb: &str,
1284        gate_req: &GateRequest,
1285        audit: AuditEvent,
1286        result: &Result<Value, RuntimeError>,
1287        duration_us: i64,
1288        request_id: Option<u64>,
1289    ) {
1290        let Some(store) = &self.event_store else {
1291            return;
1292        };
1293        let event = match result {
1294            Ok(value) if verb == "link" && gate_req.args.get("links").is_none() => {
1295                let resource = crate::cost_unit::resource_payload(
1296                    verb,
1297                    &gate_req.args,
1298                    value,
1299                    || 0,
1300                    request_id,
1301                );
1302                match link_audit_success_from_result(audit.clone(), value) {
1303                    Some((edge_id, mut payload)) => {
1304                        if let Value::Object(ref mut map) = payload {
1305                            map.insert("resource".to_string(), resource);
1306                        }
1307                        Event::new(
1308                            gate_req.namespace.as_str(),
1309                            gate_req.verb.as_str(),
1310                            EventKind::Audit,
1311                            SubstrateKind::Event,
1312                            format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
1313                        )
1314                        .with_outcome(EventOutcome::Success)
1315                        .with_target(edge_id)
1316                        .with_payload(payload)
1317                        .with_payload_schema_version(2)
1318                        .with_duration_us(duration_us)
1319                    }
1320                    None => build_audit_storage_event(
1321                        gate_req,
1322                        &audit,
1323                        EventOutcome::Success,
1324                        Some(resource),
1325                    )
1326                    .with_duration_us(duration_us),
1327                }
1328            }
1329            Ok(value) => build_audit_storage_event(
1330                gate_req,
1331                &audit,
1332                EventOutcome::Success,
1333                Some(crate::cost_unit::resource_payload(
1334                    verb,
1335                    &gate_req.args,
1336                    value,
1337                    || 0,
1338                    request_id,
1339                )),
1340            )
1341            .with_duration_us(duration_us),
1342            Err(_) => build_audit_storage_event(
1343                gate_req,
1344                &audit,
1345                EventOutcome::Error,
1346                Some(crate::cost_unit::base_resource_payload(request_id)),
1347            )
1348            .with_duration_us(duration_us),
1349        };
1350        append_audit_event_best_effort(store, event, verb).await;
1351    }
1352
1353    fn gate_request_with_identity(
1354        &self,
1355        verb: &str,
1356        params: &Value,
1357        identity: Option<&RequestIdentity>,
1358    ) -> Result<GateRequest, RuntimeError> {
1359        let default_namespace = identity
1360            .map(|id| id.namespace.as_str())
1361            .unwrap_or(self.default_namespace.as_str());
1362        let namespace = resolve_explicit_namespace(params, default_namespace)?;
1363        let actor_id = identity
1364            .map(|id| id.actor_id.as_deref())
1365            .unwrap_or(self.actor_id.as_deref());
1366        let actor = crate::actor_identity::resolve_actor(actor_id);
1367        Ok(GateRequest::new(actor, namespace, verb, params.clone()))
1368    }
1369
1370    /// Dispatch a verb to the first pack that handles it.
1371    ///
1372    /// Routes through the gate, then invokes the matching pack handler. When
1373    /// `params["help"] == true`, short-circuits to `describe_verb` with no side effects.
1374    /// Gate errors are fail-open. Full dispatch flow documented in `docs/protocol.md`.
1375    ///
1376    /// Equivalent to `self.dispatch_with_identity(verb, params, None)` — uses
1377    /// this registry's construction-baked `default_namespace` / `actor_id` /
1378    /// `visible_namespaces`.
1379    pub async fn dispatch(&self, verb: &str, params: Value) -> Result<Value, RuntimeError> {
1380        self.dispatch_with_identity(verb, params, None).await
1381    }
1382
1383    /// Dispatch a verb, optionally overriding this registry's baked identity
1384    /// scalars for exactly this call (ADR-096 Fork 1).
1385    ///
1386    /// `identity = None` behaves exactly like [`Self::dispatch`]. `identity =
1387    /// Some(id)` uses `id.namespace` / `id.actor_id` / `id.visible_namespaces`
1388    /// in place of `self.default_namespace` / `self.actor_id` /
1389    /// `self.visible_namespaces` for this call's namespace resolution, gate
1390    /// request, and token minting. The registry's own fields are never mutated,
1391    /// so concurrent calls with different (or no) identity are independent.
1392    /// See `docs/api/pack.md#dispatch_with_identity` for why this enables one warm
1393    /// registry to serve many attribution identities over a shared backend.
1394    pub async fn dispatch_with_identity(
1395        &self,
1396        verb: &str,
1397        params: Value,
1398        identity: Option<RequestIdentity>,
1399    ) -> Result<Value, RuntimeError> {
1400        // help=true interception: short-circuit before gate/pack.
1401        if params.get("help").and_then(Value::as_bool) == Some(true) {
1402            return self.describe_verb(verb);
1403        }
1404        // Resolve namespace before `params` is moved into pack.dispatch, so the
1405        // post-dispatch hook can reference it.
1406        //
1407        // Absent `namespace` and a present-but-malformed `namespace` are
1408        // different cases. A present non-string value (null, number, bool,
1409        // array, object) is explicit caller input that failed to parse and
1410        // must fail closed, not silently coerce to the default namespace.
1411        // Only a genuinely absent key defaults. Shared with the multi-backend
1412        // coordinator intercept via `resolve_explicit_namespace` so every MCP
1413        // ingress path applies the same fail-closed rule.
1414        let explicit_namespace = params.get("namespace").is_some_and(Value::is_string);
1415        // The caller-supplied correlation id (khive#948), if any. Read once
1416        // here so it is in scope for every audit-append site below,
1417        // including the ones that run before pack dispatch is attempted.
1418        let request_id: Option<u64> = identity.as_ref().and_then(|id| id.request_id);
1419        // Thread the configured actor identity into the gate request so the
1420        // gate can distinguish human vs agent callers at the dispatch seam.
1421        // Resolved once via the shared actor-identity policy and reused for
1422        // token minting below, so the gate's notion of "who is the caller"
1423        // and the storage token's notion can never drift apart.
1424        let gate_req = self.gate_request_with_identity(verb, &params, identity.as_ref())?;
1425        let ns = gate_req.namespace.clone();
1426        let resolved_actor = gate_req.actor.clone();
1427
1428        // Consult the gate.
1429        //
1430        // - Ok(Allow) → proceed to pack dispatch (tracing + optional EventStore).
1431        // - Ok(Deny) → emit audit, persist if store configured, return PermissionDenied.
1432        // - Err(_) → warn via tracing, fail-open (no audit persisted).
1433        let (gate_blocked, mut deferred_audit) = match self.gate.check(&gate_req) {
1434            Ok(decision) => {
1435                let is_deny = matches!(decision, GateDecision::Deny { .. });
1436
1437                // Emit audit event via tracing.
1438                let audit = AuditEvent::from_check(&gate_req, &decision, self.gate.impl_name());
1439                tracing::info!(
1440                    audit_event = %serde_json::to_string(&audit)
1441                        .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
1442                    "gate.check"
1443                );
1444
1445                // Drain any process-lifetime `OnceLock` config locks queued
1446                // since the last dispatch and persist them as `ConfigLocked`
1447                // events, riding this same audit-persistence gate. The
1448                // namespace/actor stamped on these rows are whichever
1449                // dispatch happens to observe the queue non-empty first:
1450                // an accepted provenance quirk, preferred over threading an
1451                // `EventStore` handle into every synchronous
1452                // `OnceLock::get_or_init` call site.
1453                if let Some(store) = &self.event_store {
1454                    if crate::config_ledger::PENDING
1455                        .swap(false, std::sync::atomic::Ordering::AcqRel)
1456                    {
1457                        for (key, value) in crate::config_ledger::drain_config_locked() {
1458                            let payload = serde_json::json!({ "key": key, "value": value });
1459                            let storage_event = Event::new(
1460                                gate_req.namespace.as_str(),
1461                                verb,
1462                                EventKind::ConfigLocked,
1463                                SubstrateKind::Event,
1464                                format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
1465                            )
1466                            .with_payload(payload);
1467                            append_audit_event_best_effort(store, storage_event, verb).await;
1468                        }
1469                    }
1470                }
1471
1472                // Every Allow-outcome audit row defers its append until pack
1473                // dispatch returns, so the row can carry the measured
1474                // dispatch time in `duration_us` (persisting before dispatch
1475                // ran always recorded the `Event::new` default of 0). A
1476                // singleton `link` call (no `links` bulk array) additionally
1477                // enriches the deferred row with the created/resolved edge
1478                // fields (schema v2) once dispatch resolves. Denied calls
1479                // have no dispatch to wait for and keep the immediate v1
1480                // append below.
1481                //
1482                // Accepted trade-off: a crash between this Allow decision and
1483                // the deferred append below (post-dispatch, further down this
1484                // function) loses that dispatch's audit row entirely: a
1485                // deliberate choice, not an oversight.
1486                let defer_audit = !is_deny;
1487
1488                // Persist to EventStore immediately only for denied calls.
1489                if !defer_audit {
1490                    if let Some(store) = &self.event_store {
1491                        // ADR-103 Decision (a): the closed `work_class` enum
1492                        // is stamped on every event, denial included -- only
1493                        // `resource.cost_unit` is scoped to a successful
1494                        // dispatch by Amendment 1. `base_resource_payload()`
1495                        // carries `work_class` alone, no `cost_unit` key.
1496                        let storage_event = build_audit_storage_event(
1497                            &gate_req,
1498                            &audit,
1499                            EventOutcome::Denied,
1500                            Some(crate::cost_unit::base_resource_payload(request_id)),
1501                        );
1502                        append_audit_event_best_effort(store, storage_event, verb).await;
1503                    }
1504                }
1505
1506                let reason = if is_deny {
1507                    let reason = match decision {
1508                        GateDecision::Deny { reason } => reason,
1509                        _ => String::new(),
1510                    };
1511                    Some(reason)
1512                } else {
1513                    None
1514                };
1515                let deferred = if defer_audit { Some(audit) } else { None };
1516                (reason, deferred)
1517            }
1518            Err(err) => {
1519                // Gate infrastructure failure — fail-open.
1520                // No decision was produced; no audit event is persisted.
1521                tracing::warn!(verb, error = %err, "gate check failed (fail-open)");
1522                (None, None)
1523            }
1524        };
1525
1526        // Hard enforcement: Deny is authoritative.
1527        if let Some(reason) = gate_blocked {
1528            return Err(RuntimeError::PermissionDenied {
1529                verb: verb.to_string(),
1530                reason,
1531            });
1532        }
1533
1534        // Mint the authorized storage token at the dispatch boundary.
1535        //
1536        // Writes pin to `local` by default. Actor identity and config
1537        // `[actor] id` are attribution and gate-context inputs only: they
1538        // never route storage. The explicit `namespace=` request param is a
1539        // precise single-namespace escape: the caller deliberately
1540        // reads/writes exactly that one set; it is NOT widened by `visible_namespaces`.
1541        //
1542        // When actor_id is configured, mint a token carrying that actor
1543        // label so that comm.inbox applies the to_actor filter for directed delivery.
1544        // Otherwise, use ActorRef::anonymous() and inbox falls back to party-line.
1545        // `actor_id_str` already reflects the per-request identity override
1546        // when supplied (resolved above into `resolved_actor`, mirrored into
1547        // the gate request). Reusing the same value here guarantees the
1548        // gate's actor and the storage token's actor can never diverge.
1549        //
1550        // On the default (no explicit `namespace=`) path, the read scope
1551        // widens to `['local'] ∪ visible_namespaces` (baked, or the
1552        // per-request override). `'local'` is always included
1553        // (mint_with_visibility deduplicates). Writes remain pinned to
1554        // `'local'`. Per-actor distinctions use view-layer tag filters
1555        // (assignee, actor_id, from/to), not namespace partitions. `ns`/
1556        // `explicit_namespace` were already validated above: reuse them
1557        // instead of re-reading `params["namespace"]` with `as_str()`, which
1558        // would silently drop malformed non-string values again.
1559        let token = if explicit_namespace {
1560            // Explicit escape: precise single-namespace scope, read+write. NOT widened.
1561            NamespaceToken::mint_with_visibility(ns.clone(), vec![], resolved_actor)
1562        } else {
1563            // Default path: write namespace = local; read scope = ['local'] ∪ visible_namespaces.
1564            let primary = Namespace::local();
1565            let mut extra_visible: Vec<Namespace> = match identity.as_ref() {
1566                Some(id) => id
1567                    .visible_namespaces
1568                    .iter()
1569                    .filter_map(|s| match Namespace::parse(s) {
1570                        Ok(parsed) => Some(parsed),
1571                        Err(e) => {
1572                            tracing::warn!(
1573                                namespace = %s,
1574                                error = %e,
1575                                "dispatch_with_identity: skipping invalid visible_namespace \
1576                                 entry from per-request identity"
1577                            );
1578                            None
1579                        }
1580                    })
1581                    .collect(),
1582                None => self.visible_namespaces.clone(),
1583            };
1584            extra_visible.push(Namespace::local()); // 'local' always readable; mint dedups
1585            NamespaceToken::mint_with_visibility(primary, extra_visible, resolved_actor)
1586        }
1587        .with_process_ref(match identity.as_ref() {
1588            Some(id) => id.process_ref.clone(),
1589            None => crate::config::process_ref_from_env(),
1590        });
1591
1592        for pack in self.packs.iter() {
1593            if let Some(handler_def) = pack.handlers().iter().find(|v| v.name == verb) {
1594                // Strip `namespace` from params before forwarding to packs.
1595                // The registry has already consumed it to mint the NamespaceToken.
1596                //
1597                // Exception: if the handler's own `params` schema declares
1598                // `"namespace"` as a valid field (e.g. brain.bind, brain.unbind,
1599                // brain.bindings, brain.resolve), the field is a *business* argument
1600                // — not a transport routing key — and must be passed through
1601                // unchanged. Stripping it would silently default the binding to the
1602                // "*" wildcard, broadening profile scope across namespaces.
1603                let handler_accepts_namespace =
1604                    handler_def.params.iter().any(|p| p.name == "namespace");
1605                let params = if !handler_accepts_namespace {
1606                    if let Value::Object(mut map) = params {
1607                        map.remove("namespace");
1608                        Value::Object(map)
1609                    } else {
1610                        params
1611                    }
1612                } else {
1613                    params
1614                };
1615                let dispatch_start = Instant::now();
1616                let result = pack.dispatch(verb, params, self, &token).await;
1617                let dispatch_us = dispatch_start.elapsed().as_micros() as i64;
1618
1619                // Append the deferred Allow-outcome audit row now that
1620                // dispatch has resolved, so `duration_us` carries the
1621                // measured `dispatch_us` instead of the `Event::new` default
1622                // of 0. A successful singleton `link` call enriches the row
1623                // with the created/resolved edge (schema v2); anything that
1624                // cannot be enriched, or is not a singleton `link` call,
1625                // falls back to the generic v1 audit shape so no audit row
1626                // is ever dropped for the deferred path.
1627                if let Some(audit) = deferred_audit.take() {
1628                    if let Some(store) = &self.event_store {
1629                        let is_link_singleton =
1630                            verb == "link" && gate_req.args.get("links").is_none();
1631                        match &result {
1632                            Ok(ok_val) if is_link_singleton => {
1633                                // ADR-103 Amendment 1: `link` (singleton or
1634                                // bulk) has no embedding-bearing path — edges
1635                                // carry no embedded body — so cost_unit is
1636                                // always base_weight("link") alone. The
1637                                // registered-model closure is never invoked
1638                                // (per_item_weight("link", ..) short-circuits
1639                                // to 0 before `model_count` reads it).
1640                                let resource = crate::cost_unit::resource_payload(
1641                                    verb,
1642                                    &gate_req.args,
1643                                    ok_val,
1644                                    || pack.registered_embedding_model_names().len() as i64,
1645                                    request_id,
1646                                );
1647                                match link_audit_success_from_result(audit.clone(), ok_val) {
1648                                    Some((edge_id, mut payload)) => {
1649                                        if let Value::Object(ref mut map) = payload {
1650                                            map.insert("resource".to_string(), resource);
1651                                        }
1652                                        let storage_event = Event::new(
1653                                            gate_req.namespace.as_str(),
1654                                            gate_req.verb.as_str(),
1655                                            EventKind::Audit,
1656                                            SubstrateKind::Event,
1657                                            format!(
1658                                                "{}:{}",
1659                                                gate_req.actor.kind, gate_req.actor.id
1660                                            ),
1661                                        )
1662                                        .with_outcome(EventOutcome::Success)
1663                                        .with_target(edge_id)
1664                                        .with_payload(payload)
1665                                        .with_payload_schema_version(2)
1666                                        .with_duration_us(dispatch_us);
1667                                        append_audit_event_best_effort(store, storage_event, verb)
1668                                            .await;
1669                                    }
1670                                    None => {
1671                                        tracing::warn!(
1672                                            verb,
1673                                            "link audit v2 enrichment parse failed; \
1674                                             falling back to v1 audit shape"
1675                                        );
1676                                        let storage_event = build_audit_storage_event(
1677                                            &gate_req,
1678                                            &audit,
1679                                            EventOutcome::Success,
1680                                            Some(resource),
1681                                        )
1682                                        .with_duration_us(dispatch_us);
1683                                        append_audit_event_best_effort(store, storage_event, verb)
1684                                            .await;
1685                                    }
1686                                }
1687                            }
1688                            _ => {
1689                                // The persisted audit outcome must reflect
1690                                // the dispatch result, not be hardcoded to
1691                                // Success — otherwise a failed dispatch is
1692                                // recorded as successful work and disappears
1693                                // from `outcome=error` queries.
1694                                //
1695                                // ADR-103 Amendment 1: `resource.cost_unit` is
1696                                // computed ONLY on a successful dispatch —
1697                                // there is no handler `Value` to read
1698                                // `item_count` from on an error, and the
1699                                // amendment's "absence has exactly two
1700                                // meanings" rule requires the field be
1701                                // omitted, never defaulted to 0, on an
1702                                // errored dispatch. `work_class` itself is
1703                                // NOT one of those two omission cases
1704                                // (ADR-103 Decision (a) stamps it on every
1705                                // event), so an errored dispatch still gets
1706                                // `resource: {"work_class": "interactive"}`,
1707                                // just with no `cost_unit` key.
1708                                let (outcome, resource) = match &result {
1709                                    Ok(ok_val) => (
1710                                        EventOutcome::Success,
1711                                        Some(crate::cost_unit::resource_payload(
1712                                            verb,
1713                                            &gate_req.args,
1714                                            ok_val,
1715                                            || pack.registered_embedding_model_names().len() as i64,
1716                                            request_id,
1717                                        )),
1718                                    ),
1719                                    Err(_) => (
1720                                        EventOutcome::Error,
1721                                        Some(crate::cost_unit::base_resource_payload(request_id)),
1722                                    ),
1723                                };
1724                                let storage_event =
1725                                    build_audit_storage_event(&gate_req, &audit, outcome, resource)
1726                                        .with_duration_us(dispatch_us);
1727                                append_audit_event_best_effort(store, storage_event, verb).await;
1728                            }
1729                        }
1730                    }
1731                }
1732
1733                // Post-dispatch hook: fires on success, opt-in.
1734                if let (Ok(ref ok_val), Some(hook)) = (&result, &self.dispatch_hook) {
1735                    let mut dispatch_event = Event::new(
1736                        ns.as_str(),
1737                        verb,
1738                        EventKind::Audit,
1739                        SubstrateKind::Event,
1740                        pack.name(),
1741                    )
1742                    .with_outcome(EventOutcome::Success)
1743                    .with_duration_us(dispatch_us);
1744
1745                    // For recall verbs: extract the first result's id as
1746                    // target_id so the brain temporal posterior can observe
1747                    // real hit/miss and latency. Copy the serve-attribution
1748                    // fields from that same hit so the hook credits the profile
1749                    // that actually served instead of always crediting default.
1750                    if verb == "memory.recall" {
1751                        let first_result =
1752                            ok_val.as_array().and_then(|arr| arr.first()).or_else(|| {
1753                                ok_val
1754                                    .get("results")
1755                                    .and_then(Value::as_array)
1756                                    .and_then(|arr| arr.first())
1757                            });
1758                        let first_note_id = first_result
1759                            .and_then(|v| v.get("id"))
1760                            .and_then(|v| v.as_str())
1761                            .and_then(|s| s.parse::<uuid::Uuid>().ok());
1762                        if let Some(note_id) = first_note_id {
1763                            dispatch_event = dispatch_event.with_target(note_id);
1764                        }
1765                        let mut payload = serde_json::Map::new();
1766                        if let Some(profile_id) = first_result
1767                            .and_then(|v| v.get("served_by_profile_id"))
1768                            .and_then(Value::as_str)
1769                        {
1770                            payload.insert(
1771                                "served_by_profile_id".to_string(),
1772                                Value::String(profile_id.to_string()),
1773                            );
1774                        }
1775                        if let Some(attribution) = first_result
1776                            .and_then(|v| v.get("serve_attribution"))
1777                            .and_then(Value::as_str)
1778                        {
1779                            payload.insert(
1780                                "serve_attribution".to_string(),
1781                                Value::String(attribution.to_string()),
1782                            );
1783                        }
1784                        dispatch_event = dispatch_event.with_payload(Value::Object(payload));
1785                        // No first result → target_id stays None (RecallMiss
1786                        // in brain's event interpreter).
1787                    }
1788
1789                    let dispatch_view = EventView {
1790                        event: dispatch_event,
1791                        observations: Vec::new(),
1792                    };
1793                    let hook = Arc::clone(hook);
1794                    hook.on_dispatch(&dispatch_view).await;
1795                }
1796
1797                // Recently-referenced ring admission: only by-id touches admit
1798                // an id. Runs unconditionally (not gated on `dispatch_hook`,
1799                // which is opt-in) because the ring is a core
1800                // dispatch-boundary capability, not an observer.
1801                //
1802                // Keyed on `token.namespace()`, NOT `ns`: `ns` is the
1803                // gate-resolved namespace, which on the default
1804                // (non-explicit) dispatch path can be a non-local
1805                // `default_namespace` (e.g. "foreign") while the storage
1806                // token that actually created/touched the record is pinned
1807                // to `local`. The ring must be keyed on the namespace the
1808                // record actually lives in: the same namespace
1809                // `resolve_reference`'s ring lookup uses: or admission and
1810                // lookup silently diverge on any non-local `default_namespace`
1811                // config.
1812                if let Ok(ref ok_val) = result {
1813                    let admissions = crate::reference_ring::ring_admissions_for(verb, ok_val);
1814                    if !admissions.is_empty() {
1815                        let actor_key = format!("{}:{}", gate_req.actor.kind, gate_req.actor.id);
1816                        for (id, name) in admissions {
1817                            self.reference_ring.admit(
1818                                token.namespace().as_str(),
1819                                &actor_key,
1820                                id,
1821                                name,
1822                            );
1823                        }
1824                    }
1825                }
1826
1827                return result;
1828            }
1829        }
1830
1831        // No pack owns this verb: the gate allowed it, but no dispatch runs.
1832        // Persist the deferred audit row now (duration stays at the
1833        // `Event::new` default of 0 — no dispatch occurred to measure) so an
1834        // allowed-but-unknown verb is never silently dropped from the audit
1835        // trail (matches the "no audit row is ever dropped" contract above).
1836        if let Some(audit) = deferred_audit.take() {
1837            if let Some(store) = &self.event_store {
1838                // Dispatch is about to return `InvalidInput` below (no pack
1839                // owns this verb), so the persisted outcome must be `Error`,
1840                // not `Success`. `work_class` is still stamped (ADR-103
1841                // Decision (a)); `resource.cost_unit` is omitted, matching
1842                // every other errored-dispatch row.
1843                let storage_event = build_audit_storage_event(
1844                    &gate_req,
1845                    &audit,
1846                    EventOutcome::Error,
1847                    Some(crate::cost_unit::base_resource_payload(request_id)),
1848                );
1849                append_audit_event_best_effort(store, storage_event, verb).await;
1850            }
1851        }
1852
1853        // Verb-visibility handler names, precomputed at build() time (internal
1854        // subhandlers are excluded so they are not advertised in the
1855        // unknown-verb error).
1856        Err(RuntimeError::InvalidInput(format!(
1857            "unknown verb {verb:?}; available: {}",
1858            self.available_verbs.join(", ")
1859        )))
1860    }
1861
1862    /// Dispatch a verb under an out-of-band verified actor identity.
1863    ///
1864    /// `verified_actor` is a typed [`VerifiedActor`] (constructor rejects blank
1865    /// identifiers) — only code holding a `VerbRegistry` handle can supply it.
1866    /// `dispatch_as` never reads `params["actor"]` to derive the effective actor;
1867    /// individual verbs may still accept an `actor` field for their own documented
1868    /// business semantics, unrelated to the acting principal. Every pack handler
1869    /// that reads "who is calling" resolves it from the `NamespaceToken` the
1870    /// dispatch boundary mints, so `verified_actor` becomes exactly the principal
1871    /// those handlers observe.
1872    ///
1873    /// Equivalent to `dispatch_with_identity(verb, params, Some(identity))` with
1874    /// `identity.actor_id = Some(verified_actor)` and every other identity scalar
1875    /// (namespace, visible namespaces) left at this registry's construction-baked
1876    /// value. [`Self::dispatch`] and [`Self::dispatch_with_identity`] are unaffected.
1877    /// See `docs/api/pack.md#dispatch_as` for the embedding-host use case and the
1878    /// blank-identifier safety rationale.
1879    pub async fn dispatch_as(
1880        &self,
1881        verb: &str,
1882        params: Value,
1883        verified_actor: VerifiedActor,
1884    ) -> Result<Value, RuntimeError> {
1885        let identity = RequestIdentity {
1886            namespace: self.default_namespace.clone(),
1887            actor_id: Some(verified_actor.into_inner()),
1888            visible_namespaces: self
1889                .visible_namespaces
1890                .iter()
1891                .map(|ns| ns.as_str().to_string())
1892                .collect(),
1893            process_ref: crate::config::process_ref_from_env(),
1894            request_id: None,
1895        };
1896        self.dispatch_with_identity(verb, params, Some(identity))
1897            .await
1898    }
1899
1900    /// Registered pack-level by-ID resolvers, in registration order.
1901    ///
1902    /// Each element is `(pack_name, resolver)`. The kg `get` and `delete` handlers
1903    /// iterate this slice to probe pack-private tables when the standard KG
1904    /// substrates (entity/note/edge/event) return `None` for a given UUID.
1905    pub fn resolvers(&self) -> &[(String, Box<dyn PackByIdResolver>)] {
1906        &self.resolvers
1907    }
1908
1909    /// The daemon-warm recently-referenced ring (unified-verb draft ADR,
1910    /// Slice 1). Consumed by `resolve_reference` (Layer 0 stage 2) and by the
1911    /// `resolve` verb handler; admitted-to by every successful by-id
1912    /// dispatch (see the admission block in `dispatch_with_identity`).
1913    pub fn reference_ring(&self) -> &Arc<crate::reference_ring::ReferenceRing> {
1914        &self.reference_ring
1915    }
1916
1917    /// Find a kind hook among the registered packs.
1918    ///
1919    /// Walks packs in registration order; the first pack that both owns the
1920    /// kind (declares it in `note_kinds()` or `entity_kinds()`) and returns
1921    /// a hook from `kind_hook(kind)` wins. Returns `None` if the kind is
1922    /// unknown to all packs or no owning pack registered a hook.
1923    pub fn find_kind_hook(&self, kind: &str) -> Option<Arc<dyn KindHook>> {
1924        for pack in self.packs.iter() {
1925            let owns = pack.note_kinds().contains(&kind) || pack.entity_kinds().contains(&kind);
1926            if owns {
1927                if let Some(hook) = pack.kind_hook(kind) {
1928                    return Some(hook);
1929                }
1930            }
1931        }
1932        None
1933    }
1934
1935    /// Run the owning kind's shared-note-update validator, if it declares one.
1936    ///
1937    /// Both canonical KG dispatch and user-facing atomic preparation call this
1938    /// seam so pack-specific property invariants cannot drift between them.
1939    pub async fn validate_note_update_hook(
1940        &self,
1941        runtime: &KhiveRuntime,
1942        token: &NamespaceToken,
1943        note: &khive_storage::Note,
1944        properties: Option<&Value>,
1945    ) -> Result<(), RuntimeError> {
1946        if let Some(hook) = self.find_kind_hook(&note.kind) {
1947            hook.validate_note_update(runtime, token, note, properties)
1948                .await?;
1949        }
1950        Ok(())
1951    }
1952
1953    /// Run shared-link validators grouped by the owning source-note kind.
1954    ///
1955    /// Supplying the whole proposed batch lets a kind hook reject an invariant
1956    /// violation formed only by multiple entries in that batch. Sources that
1957    /// are not live notes, or whose kind has no hook, remain the canonical
1958    /// endpoint validator's responsibility.
1959    pub async fn validate_link_hooks(
1960        &self,
1961        runtime: &KhiveRuntime,
1962        token: &NamespaceToken,
1963        specs: &[LinkSpec],
1964    ) -> Result<(), RuntimeError> {
1965        let mut specs_by_kind: HashMap<String, Vec<LinkSpec>> = HashMap::new();
1966        for spec in specs {
1967            let Some(Resolved::Note(source)) = runtime.resolve_by_id(token, spec.source_id).await?
1968            else {
1969                continue;
1970            };
1971            specs_by_kind
1972                .entry(source.kind)
1973                .or_default()
1974                .push(spec.clone());
1975        }
1976        for (kind, kind_specs) in specs_by_kind {
1977            if let Some(hook) = self.find_kind_hook(&kind) {
1978                hook.validate_links(runtime, token, &kind_specs).await?;
1979            }
1980        }
1981        Ok(())
1982    }
1983
1984    /// Whether any registered pack declares a handler with this verb name.
1985    ///
1986    /// A non-dispatch capability check: callers that would otherwise pay a
1987    /// guaranteed-failed `dispatch` (and its audit write) when an optional
1988    /// pack is absent can probe first and skip the call entirely.
1989    pub fn has_verb(&self, verb: &str) -> bool {
1990        self.packs
1991            .iter()
1992            .flat_map(|p| p.handlers().iter())
1993            .any(|h| h.name == verb)
1994    }
1995
1996    /// All MCP-exposed handlers across all registered packs (`Visibility::Verb` only).
1997    ///
1998    /// Subhandlers (`Visibility::Subhandler`) are excluded — they are internal
1999    /// pipeline steps not surfaced on the MCP wire. Returned with `'static`
2000    /// lifetime since pack handlers are `&'static [HandlerDef]` constants.
2001    pub fn all_verbs(&self) -> Vec<&'static HandlerDef> {
2002        self.packs
2003            .iter()
2004            .flat_map(|p| p.handlers().iter())
2005            .filter(|h| matches!(h.visibility, Visibility::Verb))
2006            .collect()
2007    }
2008
2009    /// All MCP-exposed handlers paired with the name of the pack that owns them
2010    /// (`Visibility::Verb` only).
2011    ///
2012    /// Subhandlers (`Visibility::Subhandler`) are excluded from the MCP catalog
2013    /// Use `all_handlers_with_names` when internal handlers must
2014    /// also be enumerated (e.g. runtime introspection).
2015    pub fn all_verbs_with_names(&self) -> Vec<(&str, &'static HandlerDef)> {
2016        self.packs
2017            .iter()
2018            .flat_map(|p| p.handlers().iter().map(move |v| (p.name(), v)))
2019            .filter(|(_, h)| matches!(h.visibility, Visibility::Verb))
2020            .collect()
2021    }
2022
2023    /// All handler definitions across all registered packs, including subhandlers.
2024    ///
2025    /// Unlike `all_verbs`, this includes `Visibility::Subhandler` entries. Useful
2026    /// for runtime introspection (e.g. `list_handlers`) and tooling that needs
2027    /// the complete handler surface.
2028    pub fn all_handlers_with_names(&self) -> Vec<(&str, &'static HandlerDef)> {
2029        self.packs
2030            .iter()
2031            .flat_map(|p| p.handlers().iter().map(move |v| (p.name(), v)))
2032            .collect()
2033    }
2034
2035    /// Merged set of note kinds across all registered packs (deduplicated,
2036    /// first-seen order preserved).
2037    pub fn all_note_kinds(&self) -> Vec<&'static str> {
2038        let mut seen = std::collections::HashSet::new();
2039        self.packs
2040            .iter()
2041            .flat_map(|p| p.note_kinds().iter().copied())
2042            .filter(|k| seen.insert(*k))
2043            .collect()
2044    }
2045
2046    /// Merged set of entity kinds across all registered packs (deduplicated,
2047    /// first-seen order preserved).
2048    pub fn all_entity_kinds(&self) -> Vec<&'static str> {
2049        let mut seen = std::collections::HashSet::new();
2050        self.packs
2051            .iter()
2052            .flat_map(|p| p.entity_kinds().iter().copied())
2053            .filter(|k| seen.insert(*k))
2054            .collect()
2055    }
2056
2057    /// Merged set of brain profile consumer kinds requested by registered
2058    /// packs (deduplicated, first-seen order preserved).
2059    pub fn all_brain_consumer_kinds(&self) -> Vec<&'static str> {
2060        let mut seen = std::collections::HashSet::new();
2061        self.packs
2062            .iter()
2063            .flat_map(|p| p.brain_consumer_kinds().iter().copied())
2064            .filter(|kind| seen.insert(*kind))
2065            .collect()
2066    }
2067
2068    /// Names of packs in topological load order.
2069    pub fn pack_names(&self) -> Vec<&str> {
2070        self.packs.iter().map(|p| p.name()).collect()
2071    }
2072
2073    /// Declared dependencies for a registered pack.
2074    pub fn pack_requires(&self, name: &str) -> Option<&'static [&'static str]> {
2075        self.packs
2076            .iter()
2077            .find(|p| p.name() == name)
2078            .map(|p| p.requires())
2079    }
2080
2081    /// Note kinds owned by a specific registered pack.
2082    ///
2083    /// Returns `None` if no pack with `name` is registered. The slice is
2084    /// the pack's `NOTE_KINDS` constant — `'static` lifetime, no allocation.
2085    pub fn pack_note_kinds(&self, name: &str) -> Option<&'static [&'static str]> {
2086        self.packs
2087            .iter()
2088            .find(|p| p.name() == name)
2089            .map(|p| p.note_kinds())
2090    }
2091
2092    /// Entity kinds owned by a specific registered pack.
2093    ///
2094    /// Returns `None` if no pack with `name` is registered. The slice is
2095    /// the pack's `ENTITY_KINDS` constant — `'static` lifetime, no allocation.
2096    pub fn pack_entity_kinds(&self, name: &str) -> Option<&'static [&'static str]> {
2097        self.packs
2098            .iter()
2099            .find(|p| p.name() == name)
2100            .map(|p| p.entity_kinds())
2101    }
2102
2103    /// Handlers declared by a specific registered pack.
2104    ///
2105    /// Returns `None` if no pack with `name` is registered. Each `HandlerDef`
2106    /// carries name + description + visibility — sufficient for introspection clients.
2107    pub fn pack_verbs(&self, name: &str) -> Option<&'static [HandlerDef]> {
2108        self.packs
2109            .iter()
2110            .find(|p| p.name() == name)
2111            .map(|p| p.handlers())
2112    }
2113
2114    /// All pack-declared edge endpoint rules across registered packs.
2115    ///
2116    /// Order follows topological pack registration; duplicates are *not* deduplicated —
2117    /// validation only checks membership, and an exact-duplicate rule is a
2118    /// harmless restatement.
2119    pub fn all_edge_rules(&self) -> Vec<EdgeEndpointRule> {
2120        self.packs
2121            .iter()
2122            .flat_map(|p| p.edge_rules().iter().copied())
2123            .collect()
2124    }
2125
2126    /// All pack-declared entity-type subtypes across registered packs.
2127    ///
2128    /// Order follows topological pack registration; duplicates are *not*
2129    /// deduplicated here — same posture as [`all_edge_rules`](Self::all_edge_rules).
2130    /// Consumers compose this with `EntityTypeRegistry::builtin()` via
2131    /// `EntityTypeRegistry::with_extra` to get the boot-time composed registry.
2132    pub fn all_entity_types(&self) -> Vec<EntityTypeDef> {
2133        self.packs
2134            .iter()
2135            .flat_map(|p| p.entity_types().iter().cloned())
2136            .collect()
2137    }
2138
2139    /// Collect all `NoteKindSpec` declarations from every loaded pack.
2140    ///
2141    /// Used by the runtime for lifecycle introspection and future enforcement.
2142    pub fn all_note_kind_specs(&self) -> Vec<&'static NoteKindSpec> {
2143        self.packs
2144            .iter()
2145            .flat_map(|p| p.note_kind_specs().iter())
2146            .collect()
2147    }
2148
2149    /// All pack-contributed validation rules across registered packs.
2150    ///
2151    /// Returns references into the pack-owned `'static` slices — no allocation
2152    /// beyond the outer `Vec`. Rule IDs are namespaced by pack; callers can
2153    /// group by `rule.id.split_once('/')` to attribute rules to their packs.
2154    pub fn all_validation_rules(&self) -> Vec<&'static ValidationRule> {
2155        self.packs
2156            .iter()
2157            .flat_map(|p| p.validation_rules().iter())
2158            .collect()
2159    }
2160
2161    /// Pack-auxiliary schema plans for all registered packs.
2162    ///
2163    /// Returns one `SchemaPlan` per pack. Callers (typically the runtime
2164    /// bootstrap) apply each plan to the pack's assigned backend. Empty plans
2165    /// are included so the caller can iterate uniformly; callers that want to
2166    /// skip empty plans should check `plan.is_empty()`.
2167    pub fn all_schema_plans(&self) -> Vec<SchemaPlan> {
2168        self.packs.iter().map(|p| p.schema_plan()).collect()
2169    }
2170
2171    /// Invoke `PackRuntime::register_embedders` on every registered pack.
2172    ///
2173    /// Called by the transport during startup, after the registry is built and
2174    /// before the first verb dispatch, so that custom embedding providers
2175    /// contributed by packs are reachable via `KhiveRuntime::embedder(name)`.
2176    ///
2177    /// Packs whose `register_embedders` is the default no-op pay no overhead.
2178    /// The method is idempotent when the underlying registry uses last-wins
2179    /// semantics for duplicate provider names.
2180    pub fn call_register_embedders(&self, runtime: &KhiveRuntime) {
2181        for pack in self.packs.iter() {
2182            pack.register_embedders(runtime);
2183        }
2184    }
2185
2186    /// Invoke `PackRuntime::register_entity_type_validator` on every registered pack.
2187    ///
2188    /// Called by the transport during startup, after the registry is built and
2189    /// before the first verb dispatch, so that entity-type validation at the
2190    /// runtime layer is active for all write paths including direct `create_many`
2191    /// callers that bypass the handler layer.
2192    ///
2193    /// Packs whose `register_entity_type_validator` is the default no-op pay
2194    /// no overhead.
2195    ///
2196    /// Composes [`all_entity_types`](Self::all_entity_types) once and passes
2197    /// the same aggregate to every pack, mirroring how `install_edge_rules`
2198    /// installs one `all_edge_rules()` aggregate for the whole registry.
2199    pub fn call_register_entity_type_validators(&self, runtime: &KhiveRuntime) {
2200        let entity_types = self.all_entity_types();
2201        for pack in self.packs.iter() {
2202            pack.register_entity_type_validator_with_types(runtime, &entity_types);
2203        }
2204    }
2205
2206    /// Invoke `PackRuntime::register_note_mutation_hook` on every registered pack.
2207    ///
2208    /// Called by the transport during startup, after the registry is built and
2209    /// before the first verb dispatch, so that note-mutation notifications at
2210    /// the runtime layer are active for all write paths — including KG's
2211    /// `update`/`delete` verbs reaching a `kind="memory"` note, which have no
2212    /// crate-level dependency on `khive-pack-memory`.
2213    ///
2214    /// Packs whose `register_note_mutation_hook` is the default no-op pay no
2215    /// overhead.
2216    pub fn call_register_note_mutation_hooks(&self, runtime: &KhiveRuntime) {
2217        for pack in self.packs.iter() {
2218            pack.register_note_mutation_hook(runtime);
2219        }
2220    }
2221
2222    /// Invoke `PackRuntime::warm` on every registered pack.
2223    /// Called by the daemon at boot (in a background task) so expensive in-memory
2224    /// state (ANN indexes) is pre-loaded without blocking request serving.
2225    pub async fn call_warm_all(&self) {
2226        for pack in self.packs.iter() {
2227            pack.warm().await;
2228        }
2229    }
2230
2231    /// Resolve the presentation policy for a verb name.
2232    ///
2233    /// Walks all registered handlers (including subhandlers) for the first
2234    /// matching name and returns its declared [`VerbPresentationPolicy`].
2235    /// Returns `Standard` for unknown verbs — unknown verbs will fail at
2236    /// dispatch anyway, so the fallback here is safe.
2237    pub fn presentation_policy_for(&self, verb: &str) -> khive_types::VerbPresentationPolicy {
2238        for pack in self.packs.iter() {
2239            if let Some(handler) = pack.handlers().iter().find(|h| h.name == verb) {
2240                return handler.presentation_policy();
2241            }
2242        }
2243        khive_types::VerbPresentationPolicy::Standard
2244    }
2245
2246    /// Returns `true` if the named verb exists and is tagged
2247    /// `Visibility::Subhandler` (internal / operator-only).
2248    ///
2249    /// Used by the MCP server to gate subhandler invocation at the wire
2250    /// boundary without blocking internal callers that invoke the same verbs
2251    /// through the runtime directly.
2252    pub fn is_subhandler_verb(&self, verb: &str) -> bool {
2253        for pack in self.packs.iter() {
2254            if let Some(handler) = pack.handlers().iter().find(|h| h.name == verb) {
2255                return matches!(handler.visibility, Visibility::Subhandler);
2256            }
2257        }
2258        false
2259    }
2260
2261    /// Apply all non-empty pack-auxiliary schema plans to the given backend.
2262    ///
2263    /// This is the centralized startup hook that replaced the previous lazy
2264    /// per-pack self-bootstrap pattern. Each pack's `SchemaPlan` carries
2265    /// idempotent `CREATE TABLE IF NOT EXISTS` DDL; calling this more than once
2266    /// is safe. Empty plans are skipped.
2267    ///
2268    /// Errors from individual plans are logged via `tracing::warn!` and not
2269    /// propagated so that a single pack's schema failure does not prevent the
2270    /// rest from loading. Callers that need hard-failure semantics should call
2271    /// `all_schema_plans()` and apply each plan individually.
2272    pub fn apply_schema_plans(&self, backend: &khive_db::StorageBackend) {
2273        for plan in self.all_schema_plans() {
2274            if plan.is_empty() {
2275                continue;
2276            }
2277            if let Err(e) = backend.apply_pack_ddl_statements(plan.statements) {
2278                tracing::warn!(
2279                    pack = plan.pack,
2280                    error = %e,
2281                    "failed to apply pack schema plan at startup (non-fatal)"
2282                );
2283            }
2284        }
2285    }
2286
2287    /// Pack-auxiliary schema plans with their owning pack names.
2288    ///
2289    /// Returns `(pack_name, SchemaPlan)` pairs for every registered pack.
2290    /// Used by the multi-backend boot path to apply each plan to the pack's
2291    /// assigned backend rather than a single shared backend.
2292    pub fn all_schema_plans_named(&self) -> Vec<(&'static str, SchemaPlan)> {
2293        self.packs
2294            .iter()
2295            .map(|p| {
2296                let plan = p.schema_plan();
2297                (plan.pack, plan)
2298            })
2299            .collect()
2300    }
2301
2302    /// Apply pack-auxiliary schema plans using a per-pack backend map.
2303    ///
2304    /// For each `(pack_name, plan)` returned by `all_schema_plans_named()`,
2305    /// applies the plan to `backend_for_pack[pack_name]` when present,
2306    /// falling back to `default_backend` for any pack not in the map.
2307    ///
2308    /// Returns an error when two packs on the same backend declare the same
2309    /// auxiliary table (ADR-028 §7 collision policy: boot failure naming both
2310    /// packs and the conflicting table).
2311    ///
2312    /// This is the multi-backend boot path (ADR-028). Single-backend callers
2313    /// should continue using [`Self::apply_schema_plans`].
2314    pub fn apply_schema_plans_with_map(
2315        &self,
2316        backend_for_pack: &HashMap<&str, &khive_db::StorageBackend>,
2317        default_backend: &khive_db::StorageBackend,
2318    ) -> Result<(), crate::PackSchemaCollisionError> {
2319        // Track which pack first claimed each table on each backend.
2320        // Backend identity is the raw pointer of the underlying connection pool Arc.
2321        let mut claimed: HashMap<(*const (), String), &'static str> = HashMap::new();
2322
2323        for (pack_name, plan) in self.all_schema_plans_named() {
2324            if plan.is_empty() {
2325                continue;
2326            }
2327            let backend = backend_for_pack
2328                .get(pack_name)
2329                .copied()
2330                .unwrap_or(default_backend);
2331            let backend_ptr = std::sync::Arc::as_ptr(&backend.pool_arc()) as *const ();
2332
2333            // Pre-scan DDL for table names and detect collisions before applying.
2334            for stmt in plan.statements {
2335                for table_name in extract_table_names(stmt) {
2336                    let key = (backend_ptr, table_name.clone());
2337                    match claimed.entry(key) {
2338                        std::collections::hash_map::Entry::Vacant(e) => {
2339                            e.insert(pack_name);
2340                        }
2341                        std::collections::hash_map::Entry::Occupied(e) => {
2342                            let prior_pack = *e.get();
2343                            return Err(crate::PackSchemaCollisionError {
2344                                pack_a: prior_pack,
2345                                pack_b: pack_name,
2346                                table: table_name,
2347                            });
2348                        }
2349                    }
2350                }
2351            }
2352
2353            backend
2354                .apply_pack_ddl_statements(plan.statements)
2355                .map_err(|e| crate::PackSchemaCollisionError {
2356                    pack_a: pack_name,
2357                    pack_b: pack_name,
2358                    table: format!("DDL error: {e}"),
2359                })?;
2360        }
2361        Ok(())
2362    }
2363}
2364
2365// ── Inventory-based dynamic pack loading ────────────────────────────────────
2366
2367/// Output of [`PackFactory::create_install`] — bundles the pack runtime with
2368/// its optional by-ID resolver and dispatch hook so a factory can hand back
2369/// all three built from one shared instance (see `BrainPackFactory` for why
2370/// this matters: the dispatch hook must observe the same state the runtime
2371/// mutates, not a second unrelated instance).
2372pub struct PackInstall {
2373    /// The pack runtime, registered into the builder's pack list.
2374    pub runtime: Box<dyn PackRuntime>,
2375    /// Optional by-ID resolver, registered when present.
2376    pub resolver: Option<Box<dyn PackByIdResolver>>,
2377    /// Optional post-dispatch observer, wired via `VerbRegistryBuilder::with_dispatch_hook`.
2378    pub dispatch_hook: Option<Arc<dyn DispatchHook>>,
2379}
2380
2381/// Factory for creating pack instances registered via `inventory` at link time.
2382/// Each pack crate submits a `&'static dyn PackFactory` wrapped in a
2383/// [`PackRegistration`]; the binary's linker collects them all into a single
2384/// slice iterable at runtime.
2385///
2386/// Implementors must be `Send + Sync + 'static` because the registry is built
2387/// once and shared across async tasks.
2388pub trait PackFactory: Send + Sync + 'static {
2389    /// Canonical lowercase name for this pack (e.g. `"kg"`, `"gtd"`).
2390    fn name(&self) -> &'static str;
2391
2392    /// Names of packs that must be loaded before this one.
2393    ///
2394    /// Defaults to empty so pack crates that have no dependencies compile
2395    /// without changes. [`PackRegistry::register_packs`] validates that every
2396    /// name listed here is present in the caller's explicit pack list — absent
2397    /// dependencies are a boot error, not silently auto-added.
2398    fn requires(&self) -> &'static [&'static str] {
2399        &[]
2400    }
2401
2402    /// Create a new pack instance for the given runtime.
2403    fn create(&self, runtime: KhiveRuntime) -> Box<dyn PackRuntime>;
2404
2405    /// Build the full installation bundle for this pack: runtime, optional
2406    /// resolver, optional dispatch hook.
2407    ///
2408    /// Defaults to composing `create` and `create_resolver` with no dispatch
2409    /// hook, so existing factories compile unchanged. Packs whose dispatch
2410    /// hook must observe the same instance as the runtime (e.g. `brain`)
2411    /// override this method instead of `create`, since the default would
2412    /// otherwise require two independent instances to share state.
2413    fn create_install(&self, runtime: KhiveRuntime) -> PackInstall {
2414        let resolver = self.create_resolver(runtime.clone());
2415        PackInstall {
2416            runtime: self.create(runtime),
2417            resolver,
2418            dispatch_hook: None,
2419        }
2420    }
2421
2422    /// Optionally create a `PackByIdResolver` for this pack.
2423    ///
2424    /// Packs that own private SQL tables implement this to hook into
2425    /// `get(id)` and `delete(id)`. Defaults to `None` so existing packs
2426    /// compile without changes.
2427    fn create_resolver(&self, _runtime: KhiveRuntime) -> Option<Box<dyn PackByIdResolver>> {
2428        None
2429    }
2430}
2431
2432/// Newtype wrapper collected by `inventory` so pack crates can submit
2433/// `&'static dyn PackFactory` references without the type-ascription syntax
2434/// that `inventory::submit!` does not support for bare trait-object references.
2435pub struct PackRegistration(pub &'static dyn PackFactory);
2436
2437inventory::collect!(PackRegistration);
2438
2439/// Error returned by [`PackRegistry::register_packs`] when boot validation fails.
2440#[derive(Debug)]
2441pub enum PackLoadError {
2442    /// The requested pack name was not found in the inventory.
2443    UnknownPack(String),
2444    /// A pack was requested but a declared dependency is absent from the list.
2445    MissingDependency {
2446        /// The pack that declared the dependency.
2447        pack: String,
2448        /// The dependency that is missing from the requested pack list.
2449        dep: String,
2450    },
2451}
2452
2453impl std::fmt::Display for PackLoadError {
2454    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2455        match self {
2456            PackLoadError::UnknownPack(name) => write!(f, "unknown pack {name:?}"),
2457            PackLoadError::MissingDependency { pack, dep } => write!(
2458                f,
2459                "pack {pack:?} requires {dep:?}, which is not in the requested pack list; \
2460                 add --pack {dep} before --pack {pack}"
2461            ),
2462        }
2463    }
2464}
2465
2466impl std::error::Error for PackLoadError {}
2467
2468/// Registry of pack factories discovered via `inventory` at link time.
2469///
2470/// No instance is needed — all methods are associated functions that walk the
2471/// globally-collected [`PackRegistration`] slice.
2472pub struct PackRegistry;
2473
2474impl PackRegistry {
2475    /// Names of all pack factories discovered via `inventory`.
2476    pub fn discovered_names() -> Vec<&'static str> {
2477        inventory::iter::<PackRegistration>
2478            .into_iter()
2479            .map(|r| r.0.name())
2480            .collect()
2481    }
2482
2483    /// Register the named packs into `builder` using the supplied `runtime`.
2484    ///
2485    /// Validates the explicit pack list against `PackFactory::requires()` —
2486    /// if any requested pack declares a dependency that is absent from `names`,
2487    /// registration fails (missing dependency is a boot error, not silently
2488    /// auto-added). Callers must include all required packs explicitly.
2489    ///
2490    /// The [`VerbRegistryBuilder::build`] topo-sort enforces correct load order.
2491    ///
2492    /// Returns `Ok(())` when all names are recognised and all declared
2493    /// dependencies are satisfied; returns `Err(PackLoadError)` with a
2494    /// distinct variant for unknown pack vs missing dependency.
2495    pub fn register_packs(
2496        names: &[String],
2497        runtime: KhiveRuntime,
2498        builder: &mut VerbRegistryBuilder,
2499    ) -> Result<(), PackLoadError> {
2500        // Build a name→factory index once.
2501        let all: Vec<&'static dyn PackFactory> = inventory::iter::<PackRegistration>
2502            .into_iter()
2503            .map(|r| r.0)
2504            .collect();
2505        let factory_for = |name: &str| -> Option<&'static dyn PackFactory> {
2506            all.iter().copied().find(|f| f.name() == name)
2507        };
2508
2509        // Validate that every requested name is a known factory.
2510        let requested: std::collections::HashSet<&str> = names.iter().map(String::as_str).collect();
2511        for name in names {
2512            factory_for(name.as_str()).ok_or_else(|| PackLoadError::UnknownPack(name.clone()))?;
2513        }
2514
2515        // Validate that all requires() dependencies are explicitly present in
2516        // the requested set. Missing dep → boot error, not auto-add.
2517        for name in names {
2518            let factory = factory_for(name.as_str()).unwrap(); // validated above
2519            for &dep in factory.requires() {
2520                if !requested.contains(dep) {
2521                    return Err(PackLoadError::MissingDependency {
2522                        pack: name.clone(),
2523                        dep: dep.to_string(),
2524                    });
2525                }
2526            }
2527        }
2528
2529        // Register every requested pack; VerbRegistryBuilder::build()
2530        // performs the topo-sort, so insertion order here does not matter.
2531        for name in names {
2532            let factory = factory_for(name.as_str()).unwrap(); // validated above
2533            let install = factory.create_install(runtime.clone());
2534            builder.register_boxed(install.runtime);
2535            if let Some(resolver) = install.resolver {
2536                builder.register_resolver(name.clone(), resolver);
2537            }
2538            if let Some(hook) = install.dispatch_hook {
2539                builder.with_dispatch_hook(hook);
2540            }
2541        }
2542
2543        Ok(())
2544    }
2545
2546    /// Register the named packs into `builder`, routing each pack to its own runtime.
2547    ///
2548    /// `runtimes` maps pack name → `KhiveRuntime` (one per backend assignment).
2549    /// `default_runtime` is used for any pack whose name is not in `runtimes`.
2550    /// The validation logic (unknown pack, missing dependency) is identical to
2551    /// [`PackRegistry::register_packs`].
2552    ///
2553    /// This is the multi-backend boot path (ADR-028). Single-backend callers
2554    /// should continue using [`PackRegistry::register_packs`].
2555    pub fn register_packs_with_runtimes(
2556        names: &[String],
2557        runtimes: &HashMap<String, KhiveRuntime>,
2558        default_runtime: &KhiveRuntime,
2559        builder: &mut VerbRegistryBuilder,
2560    ) -> Result<(), PackLoadError> {
2561        let all: Vec<&'static dyn PackFactory> = inventory::iter::<PackRegistration>
2562            .into_iter()
2563            .map(|r| r.0)
2564            .collect();
2565        let factory_for = |name: &str| -> Option<&'static dyn PackFactory> {
2566            all.iter().copied().find(|f| f.name() == name)
2567        };
2568
2569        let requested: std::collections::HashSet<&str> = names.iter().map(String::as_str).collect();
2570        for name in names {
2571            factory_for(name.as_str()).ok_or_else(|| PackLoadError::UnknownPack(name.clone()))?;
2572        }
2573
2574        for name in names {
2575            let factory = factory_for(name.as_str()).unwrap();
2576            for &dep in factory.requires() {
2577                if !requested.contains(dep) {
2578                    return Err(PackLoadError::MissingDependency {
2579                        pack: name.clone(),
2580                        dep: dep.to_string(),
2581                    });
2582                }
2583            }
2584        }
2585
2586        for name in names {
2587            let factory = factory_for(name.as_str()).unwrap();
2588            let runtime = runtimes
2589                .get(name.as_str())
2590                .cloned()
2591                .unwrap_or_else(|| default_runtime.clone());
2592            let install = factory.create_install(runtime);
2593            builder.register_boxed(install.runtime);
2594            if let Some(resolver) = install.resolver {
2595                builder.register_resolver(name.clone(), resolver);
2596            }
2597            if let Some(hook) = install.dispatch_hook {
2598                builder.with_dispatch_hook(hook);
2599            }
2600        }
2601
2602        Ok(())
2603    }
2604}
2605
2606fn target_id_from_args(args: &serde_json::Value) -> Option<uuid::Uuid> {
2607    args.get("target_id")
2608        .and_then(serde_json::Value::as_str)
2609        .and_then(|s| s.parse::<uuid::Uuid>().ok())
2610}
2611
2612/// Build a v1-shape audit storage event from a gate check outcome.
2613/// See `docs/api/pack.md#build_audit_storage_event` for the `resource` payload contract.
2614fn build_audit_storage_event(
2615    gate_req: &GateRequest,
2616    audit: &AuditEvent,
2617    outcome: EventOutcome,
2618    resource: Option<Value>,
2619) -> Event {
2620    let mut audit_data = serde_json::to_value(audit).unwrap_or_else(|e| {
2621        tracing::warn!(error = %e, "failed to serialize AuditEvent for EventStore");
2622        serde_json::Value::Null
2623    });
2624    if let Some(resource) = resource {
2625        if let Value::Object(ref mut map) = audit_data {
2626            map.insert("resource".to_string(), resource);
2627        }
2628    }
2629    let mut storage_event = Event::new(
2630        gate_req.namespace.as_str(),
2631        gate_req.verb.as_str(),
2632        EventKind::Audit,
2633        SubstrateKind::Event,
2634        format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
2635    )
2636    .with_outcome(outcome)
2637    .with_payload(audit_data);
2638    if let Some(target_id) = target_id_from_args(&gate_req.args) {
2639        storage_event = storage_event.with_target(target_id);
2640    }
2641    storage_event
2642}
2643
2644/// Append an audit event, logging and swallowing store failures.
2645///
2646/// Audit persistence is best-effort everywhere in the dispatch path: a store
2647/// write failure must never fail the verb call it is auditing.
2648async fn append_audit_event_best_effort(store: &Arc<dyn EventStore>, event: Event, verb: &str) {
2649    if let Err(store_err) = store.append_event(event).await {
2650        tracing::warn!(
2651            verb,
2652            error = %store_err,
2653            "audit event store write failed (non-fatal)"
2654        );
2655    }
2656}
2657
2658/// Schema v2 audit payload for a successful singleton `link` call — additive
2659/// over v1 via `#[serde(flatten)]`. See `docs/api/pack.md#linkauditsuccessv2`.
2660#[derive(Debug, Clone, serde::Serialize)]
2661struct LinkAuditSuccessV2 {
2662    #[serde(flatten)]
2663    audit: AuditEvent,
2664    edge_id: uuid::Uuid,
2665    source_id: uuid::Uuid,
2666    target_id: uuid::Uuid,
2667    relation: String,
2668    weight: f64,
2669}
2670
2671/// Extract edge fields to enrich a successful singleton `link` audit row.
2672/// Returns `None` on any missing/malformed field (falls back to v1 shape).
2673/// See `docs/api/pack.md#link_audit_success_from_result`.
2674fn link_audit_success_from_result(
2675    audit: AuditEvent,
2676    result: &serde_json::Value,
2677) -> Option<(uuid::Uuid, serde_json::Value)> {
2678    let edge_id = result.get("id")?.as_str()?.parse::<uuid::Uuid>().ok()?;
2679    let source_id = result
2680        .get("source_id")?
2681        .as_str()?
2682        .parse::<uuid::Uuid>()
2683        .ok()?;
2684    let target_id = result
2685        .get("target_id")?
2686        .as_str()?
2687        .parse::<uuid::Uuid>()
2688        .ok()?;
2689    let relation = result.get("relation")?.as_str()?.to_string();
2690    let weight = result.get("weight")?.as_f64()?;
2691    let enriched = LinkAuditSuccessV2 {
2692        audit,
2693        edge_id,
2694        source_id,
2695        target_id,
2696        relation,
2697        weight,
2698    };
2699    let payload = serde_json::to_value(&enriched).ok()?;
2700    Some((edge_id, payload))
2701}
2702
2703/// Resolve and validate a caller-supplied `namespace` argument the same way
2704/// on every MCP ingress path.
2705///
2706/// - Absent `namespace` key → parse `default_namespace`.
2707/// - Present `namespace: "<string>"` → parse the caller's value.
2708/// - Present non-string `namespace` (null, number, bool, array, object) →
2709///   fail closed with `RuntimeError::InvalidInput`. ADR-018 requires this:
2710///   a malformed explicit value must never be silently coerced to the
2711///   default namespace.
2712///
2713/// Single chokepoint for both `VerbRegistry::dispatch` and the multi-backend
2714/// coordinator intercept — see `docs/api/pack.md#resolve_explicit_namespace`.
2715pub fn resolve_explicit_namespace(
2716    params: &Value,
2717    default_namespace: &str,
2718) -> Result<Namespace, RuntimeError> {
2719    match params.get("namespace") {
2720        None => Namespace::parse(default_namespace)
2721            .map_err(|e| RuntimeError::InvalidInput(format!("invalid namespace: {e}"))),
2722        Some(Value::String(ns_str)) => Namespace::parse(ns_str)
2723            .map_err(|e| RuntimeError::InvalidInput(format!("invalid namespace {ns_str:?}: {e}"))),
2724        Some(other) => Err(RuntimeError::InvalidInput(format!(
2725            "invalid namespace: expected string when present, got {}",
2726            json_type_name(other),
2727        ))),
2728    }
2729}
2730
2731/// JSON type name for error messages: describes a present-but-malformed
2732/// `namespace` value without echoing its contents.
2733pub fn json_type_name(v: &Value) -> &'static str {
2734    match v {
2735        Value::Null => "null",
2736        Value::Bool(_) => "boolean",
2737        Value::Number(_) => "number",
2738        Value::String(_) => "string",
2739        Value::Array(_) => "array",
2740        Value::Object(_) => "object",
2741    }
2742}
2743
2744// INLINE TEST JUSTIFICATION: tests here exercise VerbRegistry collision detection,
2745// gate enforcement, and dispatch ordering that depend on direct access to the
2746// registry's private `packs` Vec and gate field. Moving them to tests/ would
2747// require pub-exporting registry internals. Broad behavioral dispatch tests
2748// live in tests/integration.rs.
2749#[cfg(test)]
2750mod tests {
2751    use super::*;
2752    use crate::ActorRef;
2753    use khive_types::Pack;
2754
2755    #[test]
2756    fn from_token_preserves_process_ref() {
2757        let with_ref = NamespaceToken::mint_authorized(
2758            Namespace::local(),
2759            ActorRef::new("agent", "provenance-carrier"),
2760        )
2761        .with_process_ref(Some("proc:origin-abc123".to_string()));
2762        let identity = RequestIdentity::from_token(&with_ref);
2763        assert_eq!(identity.process_ref.as_deref(), Some("proc:origin-abc123"));
2764
2765        let without_ref = NamespaceToken::mint_authorized(
2766            Namespace::local(),
2767            ActorRef::new("agent", "provenance-absent"),
2768        );
2769        let identity = RequestIdentity::from_token(&without_ref);
2770        assert_eq!(identity.process_ref, None);
2771    }
2772
2773    struct AlphaPack;
2774
2775    impl Pack for AlphaPack {
2776        const NAME: &'static str = "alpha";
2777        const NOTE_KINDS: &'static [&'static str] = &["memo", "log"];
2778        const ENTITY_KINDS: &'static [&'static str] = &["widget"];
2779        const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["recall", "search"];
2780        const HANDLERS: &'static [HandlerDef] = &[
2781            HandlerDef {
2782                name: "create",
2783                description: "create a widget",
2784                visibility: Visibility::Verb,
2785                category: VerbCategory::Commissive,
2786                params: &[],
2787            },
2788            HandlerDef {
2789                name: "list",
2790                description: "list widgets",
2791                visibility: Visibility::Verb,
2792                category: VerbCategory::Assertive,
2793                params: &[],
2794            },
2795        ];
2796    }
2797
2798    #[async_trait]
2799    impl PackRuntime for AlphaPack {
2800        fn name(&self) -> &str {
2801            AlphaPack::NAME
2802        }
2803        fn note_kinds(&self) -> &'static [&'static str] {
2804            AlphaPack::NOTE_KINDS
2805        }
2806        fn entity_kinds(&self) -> &'static [&'static str] {
2807            AlphaPack::ENTITY_KINDS
2808        }
2809        fn brain_consumer_kinds(&self) -> &'static [&'static str] {
2810            AlphaPack::BRAIN_CONSUMER_KINDS
2811        }
2812        fn handlers(&self) -> &'static [HandlerDef] {
2813            AlphaPack::HANDLERS
2814        }
2815        async fn dispatch(
2816            &self,
2817            verb: &str,
2818            _params: Value,
2819            _registry: &VerbRegistry,
2820            _token: &NamespaceToken,
2821        ) -> Result<Value, RuntimeError> {
2822            Ok(serde_json::json!({ "pack": "alpha", "verb": verb }))
2823        }
2824    }
2825
2826    /// A pack whose `dispatch` sleeps for a fixed, generous duration so
2827    /// `duration_us` regression tests (ADR-103 Stage 1) have a reliably
2828    /// nonzero, non-flaky measured dispatch time to assert against.
2829    struct SleepingPack;
2830
2831    impl Pack for SleepingPack {
2832        const NAME: &'static str = "sleeping";
2833        const NOTE_KINDS: &'static [&'static str] = &[];
2834        const ENTITY_KINDS: &'static [&'static str] = &[];
2835        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
2836            name: "slow_op",
2837            description: "sleeps before returning",
2838            visibility: Visibility::Verb,
2839            category: VerbCategory::Assertive,
2840            params: &[],
2841        }];
2842    }
2843
2844    #[async_trait]
2845    impl PackRuntime for SleepingPack {
2846        fn name(&self) -> &str {
2847            SleepingPack::NAME
2848        }
2849        fn note_kinds(&self) -> &'static [&'static str] {
2850            SleepingPack::NOTE_KINDS
2851        }
2852        fn entity_kinds(&self) -> &'static [&'static str] {
2853            SleepingPack::ENTITY_KINDS
2854        }
2855        fn handlers(&self) -> &'static [HandlerDef] {
2856            SleepingPack::HANDLERS
2857        }
2858        async fn dispatch(
2859            &self,
2860            verb: &str,
2861            _params: Value,
2862            _registry: &VerbRegistry,
2863            _token: &NamespaceToken,
2864        ) -> Result<Value, RuntimeError> {
2865            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
2866            Ok(serde_json::json!({ "pack": "sleeping", "verb": verb }))
2867        }
2868    }
2869
2870    struct BetaPack;
2871
2872    impl Pack for BetaPack {
2873        const NAME: &'static str = "beta";
2874        const NOTE_KINDS: &'static [&'static str] = &["alert"];
2875        const ENTITY_KINDS: &'static [&'static str] = &["widget", "gadget"];
2876        const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["search", "knowledge_compose"];
2877        const HANDLERS: &'static [HandlerDef] = &[
2878            HandlerDef {
2879                name: "notify",
2880                description: "send alert",
2881                visibility: Visibility::Verb,
2882                category: VerbCategory::Commissive,
2883                params: &[],
2884            },
2885            // "create" is Subhandler so it does NOT collide with AlphaPack's
2886            // Verb-visibility "create" — subhandlers are pack-internal and
2887            // excluded from cross-pack collision detection.
2888            HandlerDef {
2889                name: "create",
2890                description: "beta internal create (subhandler)",
2891                visibility: Visibility::Subhandler,
2892                category: VerbCategory::Commissive,
2893                params: &[],
2894            },
2895        ];
2896    }
2897
2898    /// Build a registry with AlphaPack + BetaPack.
2899    ///
2900    /// BetaPack's `create` is Subhandler so there is no Verb-visibility
2901    /// collision with AlphaPack's `create` Verb. Tests that need a collision
2902    /// use `build_colliding_registry()` instead.
2903    fn build_registry() -> VerbRegistry {
2904        let mut builder = VerbRegistryBuilder::new();
2905        builder.register(AlphaPack);
2906        builder.register(BetaPack);
2907        builder.build().expect("registry builds without collision")
2908    }
2909
2910    /// Build a registry with two packs that declare the same Verb-visibility
2911    /// handler — used to test that `VerbCollision` is raised at build time.
2912    struct CollidingPack;
2913
2914    impl Pack for CollidingPack {
2915        const NAME: &'static str = "colliding";
2916        const NOTE_KINDS: &'static [&'static str] = &[];
2917        const ENTITY_KINDS: &'static [&'static str] = &[];
2918        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
2919            name: "create",
2920            description: "duplicate Verb-visibility create",
2921            visibility: Visibility::Verb,
2922            category: VerbCategory::Commissive,
2923            params: &[],
2924        }];
2925    }
2926
2927    #[async_trait]
2928    impl PackRuntime for CollidingPack {
2929        fn name(&self) -> &str {
2930            Self::NAME
2931        }
2932        fn note_kinds(&self) -> &'static [&'static str] {
2933            Self::NOTE_KINDS
2934        }
2935        fn entity_kinds(&self) -> &'static [&'static str] {
2936            Self::ENTITY_KINDS
2937        }
2938        fn handlers(&self) -> &'static [HandlerDef] {
2939            Self::HANDLERS
2940        }
2941        async fn dispatch(
2942            &self,
2943            verb: &str,
2944            _params: Value,
2945            _registry: &VerbRegistry,
2946            _token: &NamespaceToken,
2947        ) -> Result<Value, RuntimeError> {
2948            Ok(serde_json::json!({ "pack": "colliding", "verb": verb }))
2949        }
2950    }
2951
2952    #[async_trait]
2953    impl PackRuntime for BetaPack {
2954        fn name(&self) -> &str {
2955            BetaPack::NAME
2956        }
2957        fn note_kinds(&self) -> &'static [&'static str] {
2958            BetaPack::NOTE_KINDS
2959        }
2960        fn entity_kinds(&self) -> &'static [&'static str] {
2961            BetaPack::ENTITY_KINDS
2962        }
2963        fn brain_consumer_kinds(&self) -> &'static [&'static str] {
2964            BetaPack::BRAIN_CONSUMER_KINDS
2965        }
2966        fn handlers(&self) -> &'static [HandlerDef] {
2967            BetaPack::HANDLERS
2968        }
2969        async fn dispatch(
2970            &self,
2971            verb: &str,
2972            _params: Value,
2973            _registry: &VerbRegistry,
2974            _token: &NamespaceToken,
2975        ) -> Result<Value, RuntimeError> {
2976            Ok(serde_json::json!({ "pack": "beta", "verb": verb }))
2977        }
2978    }
2979
2980    #[tokio::test]
2981    async fn dispatch_routes_to_correct_pack() {
2982        let reg = build_registry();
2983
2984        let res = reg.dispatch("list", Value::Null).await.unwrap();
2985        assert_eq!(res["pack"], "alpha");
2986
2987        let res = reg.dispatch("notify", Value::Null).await.unwrap();
2988        assert_eq!(res["pack"], "beta");
2989    }
2990
2991    /// Two packs declaring the same `Visibility::Verb` handler must be
2992    /// rejected at build time — the old "first registered wins" behaviour is
2993    /// replaced by a boot error.
2994    #[test]
2995    fn verb_collision_is_boot_time_error() {
2996        let mut builder = VerbRegistryBuilder::new();
2997        builder.register(AlphaPack);
2998        builder.register(CollidingPack);
2999        let err = builder
3000            .build()
3001            .err()
3002            .expect("duplicate Verb-visibility handler must be rejected at build time");
3003        assert!(
3004            matches!(err, RuntimeError::VerbCollision { ref verb, .. } if verb == "create"),
3005            "expected VerbCollision for 'create', got {err:?}"
3006        );
3007        let msg = err.to_string();
3008        assert!(
3009            msg.contains("create"),
3010            "error must name the colliding verb: {msg}"
3011        );
3012        assert!(
3013            msg.contains("alpha") || msg.contains("colliding"),
3014            "error must name one of the conflicting packs: {msg}"
3015        );
3016    }
3017
3018    /// Subhandler-visibility handlers with the same name across packs are NOT
3019    /// a collision — they are pack-internal and excluded from cross-pack
3020    /// collision detection.
3021    #[test]
3022    fn subhandler_same_name_across_packs_is_not_a_collision() {
3023        struct SubhandlerPack;
3024        impl Pack for SubhandlerPack {
3025            const NAME: &'static str = "subhandler_pack";
3026            const NOTE_KINDS: &'static [&'static str] = &[];
3027            const ENTITY_KINDS: &'static [&'static str] = &[];
3028            const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
3029                name: "create",
3030                description: "internal create",
3031                visibility: Visibility::Subhandler,
3032                category: VerbCategory::Commissive,
3033                params: &[],
3034            }];
3035        }
3036        #[async_trait]
3037        impl PackRuntime for SubhandlerPack {
3038            fn name(&self) -> &str {
3039                Self::NAME
3040            }
3041            fn note_kinds(&self) -> &'static [&'static str] {
3042                Self::NOTE_KINDS
3043            }
3044            fn entity_kinds(&self) -> &'static [&'static str] {
3045                Self::ENTITY_KINDS
3046            }
3047            fn handlers(&self) -> &'static [HandlerDef] {
3048                Self::HANDLERS
3049            }
3050            async fn dispatch(
3051                &self,
3052                verb: &str,
3053                _: Value,
3054                _: &VerbRegistry,
3055                _: &NamespaceToken,
3056            ) -> Result<Value, RuntimeError> {
3057                Ok(serde_json::json!({"pack": "subhandler_pack", "verb": verb}))
3058            }
3059        }
3060        let mut builder = VerbRegistryBuilder::new();
3061        builder.register(AlphaPack); // AlphaPack has Verb "create"
3062        builder.register(SubhandlerPack); // SubhandlerPack has Subhandler "create" — no collision
3063        builder
3064            .build()
3065            .expect("subhandler same name must NOT be a collision");
3066    }
3067
3068    #[tokio::test]
3069    async fn dispatch_unknown_verb_returns_error() {
3070        let reg = build_registry();
3071
3072        let err = reg.dispatch("explode", Value::Null).await.unwrap_err();
3073        let msg = err.to_string();
3074        assert!(msg.contains("explode"));
3075        assert!(msg.contains("create"));
3076    }
3077
3078    /// `all_verbs` returns only `Visibility::Verb` entries.
3079    ///
3080    /// BetaPack's `create` is `Visibility::Subhandler` — it must NOT appear
3081    /// in `all_verbs()` even though it has the same name as a Verb in AlphaPack.
3082    #[test]
3083    fn all_verbs_aggregates_across_packs_excludes_subhandlers() {
3084        let reg = build_registry();
3085        let verbs: Vec<&str> = reg.all_verbs().iter().map(|v| v.name).collect();
3086        // BetaPack's "create" (Subhandler) is absent; only Verb-visibility entries appear.
3087        assert_eq!(verbs, vec!["create", "list", "notify"]);
3088    }
3089
3090    #[test]
3091    fn all_verbs_with_names_pairs_pack_name_excludes_subhandlers() {
3092        let reg = build_registry();
3093        let pairs: Vec<(&str, &str)> = reg
3094            .all_verbs_with_names()
3095            .iter()
3096            .map(|(pack, v)| (*pack, v.name))
3097            .collect();
3098        // BetaPack's "create" is Subhandler and must NOT appear here.
3099        assert_eq!(
3100            pairs,
3101            vec![("alpha", "create"), ("alpha", "list"), ("beta", "notify"),]
3102        );
3103    }
3104
3105    #[test]
3106    fn all_handlers_with_names_includes_subhandlers() {
3107        let reg = build_registry();
3108        let pairs: Vec<(&str, &str)> = reg
3109            .all_handlers_with_names()
3110            .iter()
3111            .map(|(pack, v)| (*pack, v.name))
3112            .collect();
3113        // BetaPack's Subhandler "create" IS present in the full handler list.
3114        assert_eq!(
3115            pairs,
3116            vec![
3117                ("alpha", "create"),
3118                ("alpha", "list"),
3119                ("beta", "notify"),
3120                ("beta", "create"),
3121            ]
3122        );
3123    }
3124
3125    #[test]
3126    fn note_kinds_are_ordered() {
3127        let reg = build_registry();
3128        let kinds = reg.all_note_kinds();
3129        assert_eq!(kinds, vec!["memo", "log", "alert"]);
3130    }
3131
3132    #[test]
3133    fn brain_consumer_kinds_are_ordered_and_deduplicated() {
3134        let reg = build_registry();
3135        assert_eq!(
3136            reg.all_brain_consumer_kinds(),
3137            vec!["recall", "search", "knowledge_compose"]
3138        );
3139    }
3140
3141    #[test]
3142    fn brain_consumer_kind_wildcard_is_rejected_at_build_time() {
3143        struct WildcardConsumerPack;
3144
3145        impl khive_types::Pack for WildcardConsumerPack {
3146            const NAME: &'static str = "wildcard-consumer";
3147            const NOTE_KINDS: &'static [&'static str] = &[];
3148            const ENTITY_KINDS: &'static [&'static str] = &[];
3149            const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["*"];
3150            const HANDLERS: &'static [HandlerDef] = &[];
3151        }
3152
3153        #[async_trait]
3154        impl PackRuntime for WildcardConsumerPack {
3155            fn name(&self) -> &str {
3156                Self::NAME
3157            }
3158            fn note_kinds(&self) -> &'static [&'static str] {
3159                Self::NOTE_KINDS
3160            }
3161            fn entity_kinds(&self) -> &'static [&'static str] {
3162                Self::ENTITY_KINDS
3163            }
3164            fn brain_consumer_kinds(&self) -> &'static [&'static str] {
3165                Self::BRAIN_CONSUMER_KINDS
3166            }
3167            fn handlers(&self) -> &'static [HandlerDef] {
3168                Self::HANDLERS
3169            }
3170            async fn dispatch(
3171                &self,
3172                _verb: &str,
3173                _params: Value,
3174                _registry: &VerbRegistry,
3175                _token: &NamespaceToken,
3176            ) -> Result<Value, RuntimeError> {
3177                Ok(Value::Null)
3178            }
3179        }
3180
3181        let mut builder = VerbRegistryBuilder::new();
3182        builder.register(WildcardConsumerPack);
3183        let Err(RuntimeError::InvalidInput(message)) = builder.build() else {
3184            panic!("registry must reject a pack-declared brain wildcard");
3185        };
3186        assert!(message.contains("wildcard-consumer"), "{message}");
3187        assert!(message.contains("registry-owned"), "{message}");
3188    }
3189
3190    #[test]
3191    fn note_kind_duplicate_rejected_at_build_time() {
3192        struct DupPack;
3193
3194        impl khive_types::Pack for DupPack {
3195            const NAME: &'static str = "dup";
3196            // "memo" is already declared by AlphaPack — must be rejected at build.
3197            const NOTE_KINDS: &'static [&'static str] = &["memo"];
3198            const ENTITY_KINDS: &'static [&'static str] = &[];
3199            const HANDLERS: &'static [HandlerDef] = &[];
3200        }
3201
3202        #[async_trait]
3203        impl PackRuntime for DupPack {
3204            fn name(&self) -> &str {
3205                Self::NAME
3206            }
3207            fn note_kinds(&self) -> &'static [&'static str] {
3208                Self::NOTE_KINDS
3209            }
3210            fn entity_kinds(&self) -> &'static [&'static str] {
3211                Self::ENTITY_KINDS
3212            }
3213            fn handlers(&self) -> &'static [HandlerDef] {
3214                Self::HANDLERS
3215            }
3216            async fn dispatch(
3217                &self,
3218                _verb: &str,
3219                _params: Value,
3220                _registry: &VerbRegistry,
3221                _token: &NamespaceToken,
3222            ) -> Result<Value, RuntimeError> {
3223                Ok(Value::Null)
3224            }
3225        }
3226
3227        let mut builder = VerbRegistryBuilder::new();
3228        builder.register(AlphaPack);
3229        builder.register(DupPack);
3230        let err = builder
3231            .build()
3232            .err()
3233            .expect("duplicate note kind must be rejected");
3234        let msg = err.to_string();
3235        assert!(
3236            msg.contains("memo"),
3237            "error must name the duplicate kind: {msg}"
3238        );
3239        assert!(
3240            msg.contains("alpha") || msg.contains("dup"),
3241            "error must name one of the conflicting packs: {msg}"
3242        );
3243    }
3244
3245    #[test]
3246    fn entity_kinds_are_deduplicated() {
3247        let reg = build_registry();
3248        let kinds = reg.all_entity_kinds();
3249        assert_eq!(kinds, vec!["widget", "gadget"]);
3250    }
3251
3252    // ---- ENTITY_TYPES composition (pack-declared entity-type subtypes) ----
3253
3254    struct GammaPack;
3255
3256    impl Pack for GammaPack {
3257        const NAME: &'static str = "gamma";
3258        const NOTE_KINDS: &'static [&'static str] = &[];
3259        const ENTITY_KINDS: &'static [&'static str] = &[];
3260        const HANDLERS: &'static [HandlerDef] = &[];
3261        const ENTITY_TYPES: &'static [EntityTypeDef] = &[EntityTypeDef {
3262            kind: khive_types::EntityKind::Document,
3263            type_name: "gamma_report",
3264            aliases: &["gamma_rep"],
3265        }];
3266    }
3267
3268    #[async_trait]
3269    impl PackRuntime for GammaPack {
3270        fn name(&self) -> &str {
3271            Self::NAME
3272        }
3273        fn note_kinds(&self) -> &'static [&'static str] {
3274            Self::NOTE_KINDS
3275        }
3276        fn entity_kinds(&self) -> &'static [&'static str] {
3277            Self::ENTITY_KINDS
3278        }
3279        fn handlers(&self) -> &'static [HandlerDef] {
3280            Self::HANDLERS
3281        }
3282        fn entity_types(&self) -> &'static [EntityTypeDef] {
3283            Self::ENTITY_TYPES
3284        }
3285        async fn dispatch(
3286            &self,
3287            verb: &str,
3288            _params: Value,
3289            _registry: &VerbRegistry,
3290            _token: &NamespaceToken,
3291        ) -> Result<Value, RuntimeError> {
3292            Ok(serde_json::json!({ "pack": "gamma", "verb": verb }))
3293        }
3294    }
3295
3296    /// Builtin-only behavior is unchanged when no pack declares extras:
3297    /// `all_entity_types()` is empty, and composing it with the builtin
3298    /// registry resolves exactly like `EntityTypeRegistry::builtin()`.
3299    #[test]
3300    fn all_entity_types_empty_when_no_pack_declares_extras() {
3301        let reg = build_registry(); // AlphaPack + BetaPack — neither declares ENTITY_TYPES.
3302        assert!(reg.all_entity_types().is_empty());
3303        let composed = khive_types::EntityTypeRegistry::with_extra(reg.all_entity_types());
3304        let resolved = composed
3305            .resolve(khive_types::EntityKind::Document, Some("paper"))
3306            .expect("builtin paper subtype must still resolve");
3307        assert_eq!(resolved.entity_type.as_deref(), Some("paper"));
3308    }
3309
3310    /// A pack-declared entity type validates through the composed registry,
3311    /// and builtin subtypes remain resolvable alongside it.
3312    #[test]
3313    fn pack_declared_entity_type_validates_through_composed_registry() {
3314        let mut builder = VerbRegistryBuilder::new();
3315        builder.register(AlphaPack);
3316        builder.register(GammaPack);
3317        let reg = builder.build().expect("registry builds");
3318
3319        let extras = reg.all_entity_types();
3320        assert_eq!(extras.len(), 1);
3321
3322        let composed = khive_types::EntityTypeRegistry::with_extra(extras);
3323        let resolved = composed
3324            .resolve(khive_types::EntityKind::Document, Some("gamma_rep"))
3325            .expect("pack-declared alias must resolve through the composed registry");
3326        assert_eq!(resolved.entity_type.as_deref(), Some("gamma_report"));
3327
3328        let builtin_resolved = composed
3329            .resolve(khive_types::EntityKind::Document, Some("paper"))
3330            .expect("builtin subtype must remain resolvable when a pack adds extras");
3331        assert_eq!(builtin_resolved.entity_type.as_deref(), Some("paper"));
3332
3333        composed
3334            .resolve(khive_types::EntityKind::Document, Some("nonexistent_type"))
3335            .expect_err("undeclared entity_type must still be rejected");
3336    }
3337
3338    /// Two packs declaring the exact same `(kind, type_name)` subtype are
3339    /// rejected at `build()` — ADR-001's registry-ownership collision rule
3340    /// ("same `(base_kind, canonical_name)` from two different packs = boot
3341    /// error") — instead of silently resolving via registration order the
3342    /// way `EntityTypeRegistry::with_extra`'s hard-`insert` semantics would.
3343    #[test]
3344    fn overlapping_pack_declared_entity_types_reject_at_boot() {
3345        struct DeltaPack;
3346        impl Pack for DeltaPack {
3347            const NAME: &'static str = "delta";
3348            const NOTE_KINDS: &'static [&'static str] = &[];
3349            const ENTITY_KINDS: &'static [&'static str] = &[];
3350            const HANDLERS: &'static [HandlerDef] = &[];
3351            const ENTITY_TYPES: &'static [EntityTypeDef] = &[EntityTypeDef {
3352                kind: khive_types::EntityKind::Document,
3353                type_name: "gamma_report",
3354                aliases: &["gamma_rep"],
3355            }];
3356        }
3357        #[async_trait]
3358        impl PackRuntime for DeltaPack {
3359            fn name(&self) -> &str {
3360                Self::NAME
3361            }
3362            fn note_kinds(&self) -> &'static [&'static str] {
3363                Self::NOTE_KINDS
3364            }
3365            fn entity_kinds(&self) -> &'static [&'static str] {
3366                Self::ENTITY_KINDS
3367            }
3368            fn handlers(&self) -> &'static [HandlerDef] {
3369                Self::HANDLERS
3370            }
3371            fn entity_types(&self) -> &'static [EntityTypeDef] {
3372                Self::ENTITY_TYPES
3373            }
3374            async fn dispatch(
3375                &self,
3376                verb: &str,
3377                _params: Value,
3378                _registry: &VerbRegistry,
3379                _token: &NamespaceToken,
3380            ) -> Result<Value, RuntimeError> {
3381                Ok(serde_json::json!({ "pack": "delta", "verb": verb }))
3382            }
3383        }
3384
3385        let mut builder = VerbRegistryBuilder::new();
3386        builder.register(GammaPack);
3387        builder.register(DeltaPack);
3388        let err = builder.build().err().expect(
3389            "overlapping ENTITY_TYPES declarations must fail at build, not silently compose",
3390        );
3391
3392        let msg = err.to_string();
3393        assert!(
3394            msg.contains("gamma") && msg.contains("delta"),
3395            "collision error must name both contributing packs: {msg}"
3396        );
3397        assert!(
3398            msg.contains("gamma_report"),
3399            "collision error must name the colliding entity_type key: {msg}"
3400        );
3401    }
3402
3403    // ---- Gate wiring ----
3404
3405    use khive_gate::{Gate, GateError};
3406    use std::sync::atomic::{AtomicUsize, Ordering};
3407    use std::sync::Arc;
3408
3409    #[derive(Default, Debug)]
3410    struct CountingGate {
3411        calls: AtomicUsize,
3412        deny_verb: Option<&'static str>,
3413    }
3414
3415    impl Gate for CountingGate {
3416        fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
3417            self.calls.fetch_add(1, Ordering::SeqCst);
3418            if Some(req.verb.as_str()) == self.deny_verb {
3419                Ok(GateDecision::deny(format!("test deny for {}", req.verb)))
3420            } else {
3421                Ok(GateDecision::allow())
3422            }
3423        }
3424    }
3425
3426    #[tokio::test]
3427    async fn dispatch_consults_the_gate() {
3428        let gate = Arc::new(CountingGate::default());
3429        let mut builder = VerbRegistryBuilder::new();
3430        builder.register(AlphaPack);
3431        builder.with_gate(gate.clone());
3432        let reg = builder.build().expect("registry builds");
3433
3434        reg.dispatch("list", Value::Null).await.unwrap();
3435        reg.dispatch("create", Value::Null).await.unwrap();
3436        assert_eq!(
3437            gate.calls.load(Ordering::SeqCst),
3438            2,
3439            "gate should be consulted once per dispatch"
3440        );
3441    }
3442
3443    #[tokio::test]
3444    async fn dispatch_returns_permission_denied_on_deny_v03() {
3445        let gate = Arc::new(CountingGate {
3446            calls: AtomicUsize::new(0),
3447            deny_verb: Some("create"),
3448        });
3449        let mut builder = VerbRegistryBuilder::new();
3450        builder.register(AlphaPack);
3451        builder.with_gate(gate.clone());
3452        let reg = builder.build().expect("registry builds");
3453
3454        // Gate denies — dispatch now returns PermissionDenied (hard enforcement).
3455        let err = reg.dispatch("create", Value::Null).await.unwrap_err();
3456        assert!(
3457            matches!(err, RuntimeError::PermissionDenied { ref verb, .. } if verb == "create"),
3458            "expected PermissionDenied, got {err:?}"
3459        );
3460        let msg = err.to_string();
3461        assert!(
3462            msg.contains("create"),
3463            "error message must name the verb: {msg}"
3464        );
3465        assert!(
3466            msg.contains("test deny for create"),
3467            "error message must carry the deny reason: {msg}"
3468        );
3469        assert_eq!(gate.calls.load(Ordering::SeqCst), 1);
3470    }
3471
3472    #[tokio::test]
3473    async fn dispatch_allow_verb_succeeds_even_with_deny_gate_for_other_verb() {
3474        // Deny only "create" — "list" must still work.
3475        let gate = Arc::new(CountingGate {
3476            calls: AtomicUsize::new(0),
3477            deny_verb: Some("create"),
3478        });
3479        let mut builder = VerbRegistryBuilder::new();
3480        builder.register(AlphaPack);
3481        builder.with_gate(gate.clone());
3482        let reg = builder.build().expect("registry builds");
3483
3484        let res = reg.dispatch("list", Value::Null).await.unwrap();
3485        assert_eq!(res["pack"], "alpha");
3486    }
3487
3488    #[tokio::test]
3489    async fn dispatch_uses_allow_all_gate_by_default() {
3490        // No `with_gate` call — builder should use `AllowAllGate` so dispatch works.
3491        let reg = build_registry();
3492        let res = reg.dispatch("list", Value::Null).await.unwrap();
3493        assert_eq!(res["pack"], "alpha");
3494    }
3495
3496    // Captures the namespace each call sees so we can assert what the gate
3497    // actually receives, rather than assuming a hard-wired `default_ns()`.
3498    #[derive(Default, Debug)]
3499    struct NamespaceCapturingGate {
3500        seen: std::sync::Mutex<Vec<String>>,
3501    }
3502
3503    impl Gate for NamespaceCapturingGate {
3504        fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
3505            self.seen
3506                .lock()
3507                .unwrap()
3508                .push(req.namespace.as_str().to_string());
3509            Ok(GateDecision::allow())
3510        }
3511    }
3512
3513    #[tokio::test]
3514    async fn dispatch_propagates_params_namespace_to_gate() {
3515        let gate = Arc::new(NamespaceCapturingGate::default());
3516        let mut builder = VerbRegistryBuilder::new();
3517        builder.register(AlphaPack);
3518        builder.with_gate(gate.clone());
3519        builder.with_default_namespace("tenant-x");
3520        let reg = builder.build().expect("registry builds");
3521
3522        // Explicit namespace in params wins.
3523        reg.dispatch("list", serde_json::json!({"namespace": "tenant-y"}))
3524            .await
3525            .unwrap();
3526        // Missing namespace → registry default.
3527        reg.dispatch("list", Value::Null).await.unwrap();
3528        // Empty string is rejected: Namespace::parse("") fails → InvalidInput error.
3529        let err = reg
3530            .dispatch("list", serde_json::json!({"namespace": ""}))
3531            .await
3532            .unwrap_err();
3533        assert!(
3534            matches!(err, RuntimeError::InvalidInput(_)),
3535            "empty namespace must return InvalidInput, got {err:?}"
3536        );
3537
3538        let seen = gate.seen.lock().unwrap().clone();
3539        assert_eq!(seen, vec!["tenant-y", "tenant-x"]);
3540    }
3541
3542    #[tokio::test]
3543    async fn dispatch_falls_back_to_local_when_no_default_set() {
3544        // Builder default mirrors `Namespace::default_ns()`.
3545        let gate = Arc::new(NamespaceCapturingGate::default());
3546        let mut builder = VerbRegistryBuilder::new();
3547        builder.register(AlphaPack);
3548        builder.with_gate(gate.clone());
3549        let reg = builder.build().expect("registry builds");
3550
3551        reg.dispatch("list", Value::Null).await.unwrap();
3552        let seen = gate.seen.lock().unwrap().clone();
3553        assert_eq!(seen, vec!["local"]);
3554    }
3555
3556    /// A present-but-malformed `namespace` value must never reach the gate as
3557    /// the default namespace. Table-driven over every
3558    /// non-string JSON type; the gate-spy proves no call is ever recorded (the
3559    /// dispatch must short-circuit with `InvalidInput` before `GateRequest` is
3560    /// built), so the default namespace can never appear as a coerced stand-in.
3561    #[tokio::test]
3562    async fn namespace_null_rejected_not_coerced() {
3563        let cases: Vec<(&str, Value)> = vec![
3564            ("null", Value::Null),
3565            ("number", serde_json::json!(42)),
3566            ("boolean", serde_json::json!(true)),
3567            ("array", serde_json::json!(["local"])),
3568            ("object", serde_json::json!({"ns": "local"})),
3569        ];
3570
3571        for (label, ns_value) in cases {
3572            let gate = Arc::new(NamespaceCapturingGate::default());
3573            let mut builder = VerbRegistryBuilder::new();
3574            builder.register(AlphaPack);
3575            builder.with_gate(gate.clone());
3576            builder.with_default_namespace("tenant-x");
3577            let reg = builder.build().expect("registry builds");
3578
3579            let err = reg
3580                .dispatch("list", serde_json::json!({"namespace": ns_value}))
3581                .await
3582                .unwrap_err();
3583            assert!(
3584                matches!(err, RuntimeError::InvalidInput(_)),
3585                "case {label}: expected InvalidInput, got {err:?}"
3586            );
3587
3588            // The gate must never have been consulted for this malformed input —
3589            // proves no Allow decision (and therefore no default-namespace write)
3590            // can ever be reached for it.
3591            let seen = gate.seen.lock().unwrap().clone();
3592            assert!(
3593                seen.is_empty(),
3594                "case {label}: gate must not be consulted for malformed namespace, saw {seen:?}"
3595            );
3596        }
3597    }
3598
3599    // ---- Audit event emission ----
3600
3601    use khive_gate::{AuditDecision, AuditEvent, Obligation};
3602
3603    /// A gate that records every audit event emitted via from_check.
3604    #[derive(Default, Debug)]
3605    struct AuditCapturingGate {
3606        events: std::sync::Mutex<Vec<AuditEvent>>,
3607        deny_verb: Option<&'static str>,
3608    }
3609
3610    impl Gate for AuditCapturingGate {
3611        fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
3612            let decision = if Some(req.verb.as_str()) == self.deny_verb {
3613                GateDecision::deny("test deny")
3614            } else {
3615                GateDecision::allow_with(vec![Obligation::Audit {
3616                    tag: format!("{}.check", req.verb),
3617                }])
3618            };
3619            // Capture what dispatch will also emit.
3620            let ev = AuditEvent::from_check(req, &decision, self.impl_name());
3621            self.events.lock().unwrap().push(ev);
3622            Ok(decision)
3623        }
3624
3625        fn impl_name(&self) -> &'static str {
3626            "AuditCapturingGate"
3627        }
3628    }
3629
3630    #[tokio::test]
3631    async fn dispatch_emits_one_audit_event_per_call() {
3632        let gate = Arc::new(AuditCapturingGate::default());
3633        let mut builder = VerbRegistryBuilder::new();
3634        builder.register(AlphaPack);
3635        builder.with_gate(gate.clone());
3636        let reg = builder.build().expect("registry builds");
3637
3638        reg.dispatch("list", Value::Null).await.unwrap();
3639        reg.dispatch("create", Value::Null).await.unwrap();
3640
3641        let evs = gate.events.lock().unwrap();
3642        assert_eq!(evs.len(), 2, "exactly one audit event per dispatch call");
3643    }
3644
3645    #[tokio::test]
3646    async fn dispatch_audit_event_allow_carries_obligations() {
3647        let gate = Arc::new(AuditCapturingGate::default());
3648        let mut builder = VerbRegistryBuilder::new();
3649        builder.register(AlphaPack);
3650        builder.with_gate(gate.clone());
3651        let reg = builder.build().expect("registry builds");
3652
3653        reg.dispatch("list", Value::Null).await.unwrap();
3654
3655        let evs = gate.events.lock().unwrap();
3656        let ev = &evs[0];
3657        assert_eq!(ev.verb, "list");
3658        assert_eq!(ev.decision, AuditDecision::Allow);
3659        assert!(ev.deny_reason.is_none());
3660        assert_eq!(ev.obligations.len(), 1);
3661        assert_eq!(ev.gate_impl, "AuditCapturingGate");
3662    }
3663
3664    #[tokio::test]
3665    async fn dispatch_audit_event_deny_carries_reason() {
3666        let gate = Arc::new(AuditCapturingGate {
3667            events: Default::default(),
3668            deny_verb: Some("create"),
3669        });
3670        let mut builder = VerbRegistryBuilder::new();
3671        builder.register(AlphaPack);
3672        builder.with_gate(gate.clone());
3673        let reg = builder.build().expect("registry builds");
3674
3675        // Gate denies — dispatch returns PermissionDenied (hard enforcement).
3676        // The audit event is still recorded (captured inside the gate impl).
3677        let err = reg.dispatch("create", Value::Null).await.unwrap_err();
3678        assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
3679
3680        let evs = gate.events.lock().unwrap();
3681        let ev = &evs[0];
3682        assert_eq!(ev.verb, "create");
3683        assert_eq!(ev.decision, AuditDecision::Deny);
3684        assert_eq!(ev.deny_reason.as_deref(), Some("test deny"));
3685        assert!(ev.obligations.is_empty());
3686    }
3687
3688    #[tokio::test]
3689    async fn dispatch_audit_event_fields_match_gate_request() {
3690        let gate = Arc::new(AuditCapturingGate::default());
3691        let mut builder = VerbRegistryBuilder::new();
3692        builder.register(AlphaPack);
3693        builder.with_gate(gate.clone());
3694        builder.with_default_namespace("tenant-z");
3695        let reg = builder.build().expect("registry builds");
3696
3697        reg.dispatch("list", serde_json::json!({"namespace": "tenant-q"}))
3698            .await
3699            .unwrap();
3700
3701        let evs = gate.events.lock().unwrap();
3702        let ev = &evs[0];
3703        // Namespace from params wins.
3704        assert_eq!(ev.namespace, "tenant-q");
3705        assert_eq!(ev.verb, "list");
3706        assert_eq!(ev.actor.kind, "anonymous");
3707    }
3708
3709    // ---- Actor attribution threading into gate request (ADR-057) ----
3710
3711    /// A gate spy that captures the raw `GateRequest` it receives.
3712    #[derive(Default, Debug)]
3713    struct ActorCapturingGate {
3714        requests: std::sync::Mutex<Vec<GateRequest>>,
3715    }
3716
3717    impl Gate for ActorCapturingGate {
3718        fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
3719            self.requests.lock().unwrap().push(req.clone());
3720            Ok(GateDecision::allow())
3721        }
3722    }
3723
3724    /// When `actor_id` is configured, the gate request carries that actor, not
3725    /// anonymous. This exercises the ADR-057 attribution fix: the gate can
3726    /// distinguish an agent caller from an unauthenticated caller.
3727    #[tokio::test]
3728    async fn gate_request_carries_configured_actor_when_actor_id_is_set() {
3729        let gate = Arc::new(ActorCapturingGate::default());
3730        let mut builder = VerbRegistryBuilder::new();
3731        builder.register(AlphaPack);
3732        builder.with_gate(gate.clone());
3733        builder.with_actor_id(Some("team-abc:implementer".to_string()));
3734        let reg = builder.build().expect("registry builds");
3735
3736        reg.dispatch("list", Value::Null).await.unwrap();
3737
3738        let reqs = gate.requests.lock().unwrap();
3739        assert_eq!(reqs.len(), 1);
3740        let req = &reqs[0];
3741        assert_eq!(
3742            req.actor.kind, "actor",
3743            "gate request must carry kind='actor' when actor_id is configured"
3744        );
3745        assert_eq!(
3746            req.actor.id, "team-abc:implementer",
3747            "gate request must carry the configured actor id"
3748        );
3749    }
3750
3751    /// When no `actor_id` is configured, the gate request still receives the
3752    /// anonymous actor (no regression to the party-line default).
3753    #[tokio::test]
3754    async fn gate_request_carries_anonymous_when_no_actor_id_configured() {
3755        let gate = Arc::new(ActorCapturingGate::default());
3756        let mut builder = VerbRegistryBuilder::new();
3757        builder.register(AlphaPack);
3758        builder.with_gate(gate.clone());
3759        // actor_id left at default (None).
3760        let reg = builder.build().expect("registry builds");
3761
3762        reg.dispatch("list", Value::Null).await.unwrap();
3763
3764        let reqs = gate.requests.lock().unwrap();
3765        assert_eq!(reqs.len(), 1);
3766        let req = &reqs[0];
3767        assert_eq!(
3768            req.actor.kind, "anonymous",
3769            "gate request must carry anonymous actor when no actor_id is configured"
3770        );
3771        assert_eq!(req.actor.id, "local");
3772    }
3773
3774    /// A pack that records the `ActorRef` carried by the `NamespaceToken` it
3775    /// is dispatched with, so tests can compare it against the gate's actor.
3776    struct TokenCapturingPack {
3777        actors: Arc<std::sync::Mutex<Vec<khive_gate::ActorRef>>>,
3778    }
3779
3780    impl Pack for TokenCapturingPack {
3781        const NAME: &'static str = "alpha";
3782        const NOTE_KINDS: &'static [&'static str] = &[];
3783        const ENTITY_KINDS: &'static [&'static str] = &[];
3784        const HANDLERS: &'static [HandlerDef] = AlphaPack::HANDLERS;
3785    }
3786
3787    #[async_trait]
3788    impl PackRuntime for TokenCapturingPack {
3789        fn name(&self) -> &str {
3790            Self::NAME
3791        }
3792        fn note_kinds(&self) -> &'static [&'static str] {
3793            Self::NOTE_KINDS
3794        }
3795        fn entity_kinds(&self) -> &'static [&'static str] {
3796            Self::ENTITY_KINDS
3797        }
3798        fn handlers(&self) -> &'static [HandlerDef] {
3799            Self::HANDLERS
3800        }
3801        async fn dispatch(
3802            &self,
3803            verb: &str,
3804            _params: Value,
3805            _registry: &VerbRegistry,
3806            token: &NamespaceToken,
3807        ) -> Result<Value, RuntimeError> {
3808            self.actors.lock().unwrap().push(token.actor().clone());
3809            Ok(serde_json::json!({ "pack": "alpha", "verb": verb }))
3810        }
3811    }
3812
3813    /// The gate's actor and the storage token's actor must be the exact same
3814    /// resolved value: both come from one `resolve_actor` call
3815    /// (`resolved_actor`) instead of two independently hand-synchronized
3816    /// `match` expressions, so a future edit to one copy but not the other
3817    /// cannot silently desynchronize "who the gate thinks the caller is" from
3818    /// "who the storage layer thinks the caller is". Reintroducing a second
3819    /// independent actor-resolution copy for the token would regress this and
3820    /// this test would catch it.
3821    #[tokio::test]
3822    async fn gate_actor_and_token_actor_are_identical_when_actor_id_is_set() {
3823        let gate = Arc::new(ActorCapturingGate::default());
3824        let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
3825        let pack = TokenCapturingPack {
3826            actors: actors.clone(),
3827        };
3828        let mut builder = VerbRegistryBuilder::new();
3829        builder.register(pack);
3830        builder.with_gate(gate.clone());
3831        builder.with_actor_id(Some("actor-alpha".to_string()));
3832        let reg = builder.build().expect("registry builds");
3833
3834        reg.dispatch("list", Value::Null).await.unwrap();
3835
3836        let reqs = gate.requests.lock().unwrap();
3837        let gate_actor = reqs[0].actor.clone();
3838        drop(reqs);
3839
3840        let captured = actors.lock().unwrap();
3841        let token_actor = captured[0].clone();
3842
3843        assert_eq!(
3844            gate_actor.kind, token_actor.kind,
3845            "gate request actor and storage token actor must carry the same kind"
3846        );
3847        assert_eq!(
3848            gate_actor.id, token_actor.id,
3849            "gate request actor and storage token actor must carry the same id"
3850        );
3851        assert_eq!(gate_actor.id, "actor-alpha");
3852    }
3853
3854    /// Same identity check with no configured `actor_id`: both the gate and
3855    /// the storage token must independently land on `ActorRef::anonymous()`.
3856    #[tokio::test]
3857    async fn gate_actor_and_token_actor_are_identical_when_anonymous() {
3858        let gate = Arc::new(ActorCapturingGate::default());
3859        let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
3860        let pack = TokenCapturingPack {
3861            actors: actors.clone(),
3862        };
3863        let mut builder = VerbRegistryBuilder::new();
3864        builder.register(pack);
3865        builder.with_gate(gate.clone());
3866        let reg = builder.build().expect("registry builds");
3867
3868        reg.dispatch("list", Value::Null).await.unwrap();
3869
3870        let reqs = gate.requests.lock().unwrap();
3871        let gate_actor = reqs[0].actor.clone();
3872        drop(reqs);
3873
3874        let captured = actors.lock().unwrap();
3875        let token_actor = captured[0].clone();
3876
3877        assert_eq!(gate_actor.kind, token_actor.kind);
3878        assert_eq!(gate_actor.id, token_actor.id);
3879        assert_eq!(gate_actor.id, "local");
3880    }
3881
3882    // ---- dispatch_as: verified-actor dispatch for embedding hosts ----
3883
3884    /// `dispatch_as` must thread the caller-supplied verified actor through
3885    /// to the pack handler's `NamespaceToken`, exactly as `dispatch_with_identity`
3886    /// does with a `RequestIdentity.actor_id` — this is the observable
3887    /// contract embedding hosts rely on.
3888    #[tokio::test]
3889    async fn dispatch_as_threads_verified_actor_into_token() {
3890        let gate = Arc::new(ActorCapturingGate::default());
3891        let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
3892        let pack = TokenCapturingPack {
3893            actors: actors.clone(),
3894        };
3895        let mut builder = VerbRegistryBuilder::new();
3896        builder.register(pack);
3897        builder.with_gate(gate.clone());
3898        let reg = builder.build().expect("registry builds");
3899
3900        reg.dispatch_as(
3901            "list",
3902            Value::Null,
3903            VerifiedActor::new("gateway:principal-42").unwrap(),
3904        )
3905        .await
3906        .unwrap();
3907
3908        let reqs = gate.requests.lock().unwrap();
3909        assert_eq!(reqs[0].actor.kind, "actor");
3910        assert_eq!(reqs[0].actor.id, "gateway:principal-42");
3911        drop(reqs);
3912
3913        let captured = actors.lock().unwrap();
3914        assert_eq!(captured[0].kind, "actor");
3915        assert_eq!(
3916            captured[0].id, "gateway:principal-42",
3917            "the storage token actor must be the verified_actor supplied to dispatch_as, \
3918             matching exactly what pack handlers read as the acting principal"
3919        );
3920    }
3921
3922    /// `dispatch_as` is purely additive: a registry with a baked `actor_id`
3923    /// must still serve plain `dispatch()` calls under its own baked actor,
3924    /// unaffected by any `dispatch_as` call made on the same (cheaply
3925    /// cloneable) registry. No shared mutable state links the two calls.
3926    #[tokio::test]
3927    async fn dispatch_as_does_not_change_plain_dispatch_behavior() {
3928        let gate = Arc::new(ActorCapturingGate::default());
3929        let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
3930        let pack = TokenCapturingPack {
3931            actors: actors.clone(),
3932        };
3933        let mut builder = VerbRegistryBuilder::new();
3934        builder.register(pack);
3935        builder.with_gate(gate.clone());
3936        builder.with_actor_id(Some("baked-actor".to_string()));
3937        let reg = builder.build().expect("registry builds");
3938
3939        reg.dispatch_as(
3940            "list",
3941            Value::Null,
3942            VerifiedActor::new("verified-actor").unwrap(),
3943        )
3944        .await
3945        .unwrap();
3946        reg.dispatch("list", Value::Null).await.unwrap();
3947
3948        let captured = actors.lock().unwrap();
3949        assert_eq!(captured.len(), 2);
3950        assert_eq!(captured[0].id, "verified-actor", "dispatch_as call");
3951        assert_eq!(
3952            captured[1].id, "baked-actor",
3953            "a later plain dispatch() call must still use the registry's baked \
3954             actor_id, unaffected by the prior dispatch_as call"
3955        );
3956    }
3957
3958    /// A request `params` payload cannot inject or override the actor:
3959    /// `dispatch_as` resolves the acting principal solely from its Rust-side
3960    /// `verified_actor` argument, never from `params`. An `actor` key placed
3961    /// in `params` passes through untouched to the pack handler like any
3962    /// other unrecognized field — the dispatch boundary itself never reads
3963    /// `params["actor"]`.
3964    #[tokio::test]
3965    async fn dispatch_as_ignores_actor_key_in_params() {
3966        let gate = Arc::new(ActorCapturingGate::default());
3967        let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
3968        let pack = TokenCapturingPack {
3969            actors: actors.clone(),
3970        };
3971        let mut builder = VerbRegistryBuilder::new();
3972        builder.register(pack);
3973        builder.with_gate(gate.clone());
3974        let reg = builder.build().expect("registry builds");
3975
3976        reg.dispatch_as(
3977            "list",
3978            serde_json::json!({"actor": "spoofed-actor"}),
3979            VerifiedActor::new("verified-actor").unwrap(),
3980        )
3981        .await
3982        .unwrap();
3983
3984        let captured = actors.lock().unwrap();
3985        assert_eq!(
3986            captured[0].id, "verified-actor",
3987            "an 'actor' key inside params must never override the verified_actor \
3988             argument threaded through dispatch_as"
3989        );
3990    }
3991
3992    /// `VerifiedActor::new` must reject an empty identifier rather than
3993    /// letting it reach dispatch and silently resolve to the anonymous actor.
3994    #[test]
3995    fn verified_actor_rejects_empty_identifier() {
3996        let err = VerifiedActor::new("").unwrap_err();
3997        assert!(
3998            matches!(err, RuntimeError::InvalidInput(_)),
3999            "expected InvalidInput, got {err:?}"
4000        );
4001    }
4002
4003    /// `VerifiedActor::new` must reject a whitespace-only identifier for the
4004    /// same reason: it must never launder into `ActorRef::anonymous()`.
4005    #[test]
4006    fn verified_actor_rejects_whitespace_only_identifier() {
4007        let err = VerifiedActor::new("   ").unwrap_err();
4008        assert!(
4009            matches!(err, RuntimeError::InvalidInput(_)),
4010            "expected InvalidInput, got {err:?}"
4011        );
4012    }
4013
4014    // ---- Rego gate: fail-closed end-to-end ----
4015
4016    /// A `RegoGate` whose policy lacks the named entrypoint rule must cause
4017    /// `VerbRegistry::dispatch` to return `RuntimeError::PermissionDenied` —
4018    /// never to proceed to the pack handler.
4019    ///
4020    /// This is the runtime-level assertion that a gate evaluation failure
4021    /// fails closed rather than opening a security hole.
4022    /// `RegoGate::check` converts all evaluation failures (missing rule,
4023    /// undefined result, serialization error, poisoned engine) to
4024    /// `Ok(GateDecision::Deny)`, so dispatch is blocked. The runtime's
4025    /// fail-open `Err(_)` branch remains for non-evaluation gate errors
4026    /// (e.g. infrastructure faults from other `Gate` implementations).
4027    #[tokio::test]
4028    async fn rego_gate_missing_entrypoint_returns_permission_denied() {
4029        use khive_gate_rego::RegoGate;
4030
4031        // Policy defines `verdict` but NOT `data.khive.gate.decision` (the
4032        // default entrypoint).  Construction succeeds — from_policy_str does
4033        // not validate the default entrypoint.  check() must convert the
4034        // missing-rule evaluation error to Ok(Deny) so the runtime denies
4035        // the request rather than treating the Err as a fail-open signal.
4036        let policy = r#"
4037            package khive.gate
4038            import rego.v1
4039            verdict := "allow"
4040        "#;
4041        let gate = Arc::new(RegoGate::from_policy_str(policy).expect("policy compiles"));
4042
4043        let mut builder = VerbRegistryBuilder::new();
4044        builder.register(AlphaPack);
4045        builder.with_gate(gate);
4046        let reg = builder.build().expect("registry builds");
4047
4048        let err = reg.dispatch("create", Value::Null).await.unwrap_err();
4049        assert!(
4050            matches!(err, RuntimeError::PermissionDenied { ref verb, .. } if verb == "create"),
4051            "expected PermissionDenied for missing rego entrypoint, got {err:?}"
4052        );
4053    }
4054
4055    // ---- Audit tracing emission ----
4056    //
4057    // The AuditCapturingGate tests above prove that AuditEvent::from_check is
4058    // called with the right inputs, but they observe the event *inside* the
4059    // gate impl — they would still pass if dispatch's
4060    // `tracing::info!(audit_event = ..., "gate.check")` were deleted or
4061    // renamed. The tests below install a capture Layer and assert on the
4062    // actual tracing event surfaced from dispatch. This locks the public
4063    // observability contract: one `gate.check` info event per dispatch,
4064    // carrying an `audit_event` field that round-trips back to an `AuditEvent`.
4065
4066    use std::sync::{Mutex as StdMutex, Once, OnceLock};
4067
4068    use serial_test::serial;
4069    use tracing::field::{Field, Visit};
4070
4071    #[derive(Clone, Debug, Default)]
4072    struct CapturedEvent {
4073        message: Option<String>,
4074        audit_event: Option<String>,
4075    }
4076
4077    #[derive(Default)]
4078    struct CapturedEventVisitor(CapturedEvent);
4079
4080    impl Visit for CapturedEventVisitor {
4081        fn record_str(&mut self, field: &Field, value: &str) {
4082            match field.name() {
4083                "message" => self.0.message = Some(value.to_string()),
4084                "audit_event" => self.0.audit_event = Some(value.to_string()),
4085                _ => {}
4086            }
4087        }
4088
4089        fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
4090            // `tracing::info!(audit_event = %expr, "msg")` records via the
4091            // Display-wrapped Debug path, so we receive the JSON string here.
4092            // `"msg"` literal records as a `message` field via `record_debug`
4093            // with a quoted Debug representation; strip the surrounding quotes
4094            // so the captured message matches the source.
4095            let formatted = format!("{value:?}");
4096            let cleaned = formatted
4097                .trim_start_matches('"')
4098                .trim_end_matches('"')
4099                .to_string();
4100            match field.name() {
4101                "message" => self.0.message = Some(cleaned),
4102                "audit_event" => self.0.audit_event = Some(cleaned),
4103                _ => {}
4104            }
4105        }
4106    }
4107
4108    /// Minimal `tracing::Subscriber` that captures events into a shared vec.
4109    ///
4110    /// Implemented directly (without `tracing_subscriber::registry()` layering)
4111    /// to avoid the layer machinery that can cause thread-local dispatch to be
4112    /// bypassed when the registry's internal global state is initialised by
4113    /// another subscriber in the same test binary.
4114    ///
4115    /// Isolation across concurrent tests is handled at the dispatcher level by
4116    /// `tracing::dispatcher::with_default`, which installs this subscriber
4117    /// as the thread-local default for the duration of the test closure.
4118    /// Other threads (e.g. `#[tokio::test]` pool workers) emit through their
4119    /// own (typically NoSubscriber) dispatchers and never reach this instance.
4120    struct CaptureSubscriber {
4121        events: Arc<StdMutex<Vec<CapturedEvent>>>,
4122    }
4123
4124    impl CaptureSubscriber {
4125        fn new(events: Arc<StdMutex<Vec<CapturedEvent>>>) -> Self {
4126            Self { events }
4127        }
4128    }
4129
4130    impl tracing::Subscriber for CaptureSubscriber {
4131        fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
4132            true
4133        }
4134        fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
4135            tracing::span::Id::from_u64(1)
4136        }
4137        fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
4138        fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
4139        fn event(&self, event: &tracing::Event<'_>) {
4140            let mut visitor = CapturedEventVisitor::default();
4141            event.record(&mut visitor);
4142            self.events.lock().unwrap().push(visitor.0);
4143        }
4144        fn enter(&self, _: &tracing::span::Id) {}
4145        fn exit(&self, _: &tracing::span::Id) {}
4146    }
4147
4148    /// Global capture buffer for the tracing tests.
4149    ///
4150    /// The subscriber is installed exactly once via `set_global_default`
4151    /// (thread-local dispatchers via `with_default` proved unreliable when
4152    /// other tests in the binary configure their own dispatchers in parallel —
4153    /// the global state interacted unpredictably and events were lost).
4154    ///
4155    /// Each test that uses this buffer is `#[serial]`, so only one
4156    /// runs at a time. The buffer is cleared at the start of each capture call.
4157    static GLOBAL_CAPTURE: OnceLock<Arc<StdMutex<Vec<CapturedEvent>>>> = OnceLock::new();
4158    static GLOBAL_INIT: Once = Once::new();
4159
4160    fn global_capture() -> Arc<StdMutex<Vec<CapturedEvent>>> {
4161        GLOBAL_INIT.call_once(|| {
4162            let buffer = Arc::new(StdMutex::new(Vec::new()));
4163            let subscriber = CaptureSubscriber::new(Arc::clone(&buffer));
4164            // Ignore error: if another subscriber is already set globally, our
4165            // subscriber installation fails, but the buffer will simply stay
4166            // empty and tests will fail with a clear "got 0 events" message
4167            // rather than a silent corruption.
4168            let _ = tracing::subscriber::set_global_default(subscriber);
4169            let _ = GLOBAL_CAPTURE.set(buffer);
4170        });
4171        Arc::clone(GLOBAL_CAPTURE.get().expect("global capture initialized"))
4172    }
4173
4174    /// Run an async block under the global capture subscriber and return
4175    /// the events emitted during the run. Clears the buffer at the start.
4176    ///
4177    /// Callers MUST be `#[serial]` to prevent concurrent buffer pollution.
4178    fn capture_dispatch_events<Fut>(future: Fut) -> Vec<CapturedEvent>
4179    where
4180        Fut: std::future::Future<Output = ()>,
4181    {
4182        let buffer = global_capture();
4183        buffer.lock().unwrap().clear();
4184
4185        let rt = tokio::runtime::Builder::new_current_thread()
4186            .enable_all()
4187            .build()
4188            .expect("build current-thread tokio runtime");
4189        rt.block_on(future);
4190
4191        let result = buffer.lock().unwrap().clone();
4192        result
4193    }
4194
4195    /// Pull every captured event whose `message` matches `"gate.check"` AND
4196    /// whose audit_event JSON declares the expected `gate_impl` name.
4197    ///
4198    /// Filtering by `gate_impl` lets concurrent tests in the same binary
4199    /// emit their own gate.check events into the global capture buffer
4200    /// without polluting each others' counts.
4201    fn gate_check_events_for(events: &[CapturedEvent], gate_impl: &str) -> Vec<CapturedEvent> {
4202        events
4203            .iter()
4204            .filter(|e| e.message.as_deref() == Some("gate.check"))
4205            .filter(|e| {
4206                e.audit_event
4207                    .as_deref()
4208                    .and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok())
4209                    .and_then(|v| {
4210                        v.get("gate_impl")
4211                            .and_then(|g| g.as_str().map(|s| s.to_string()))
4212                    })
4213                    .as_deref()
4214                    == Some(gate_impl)
4215            })
4216            .cloned()
4217            .collect()
4218    }
4219
4220    #[test]
4221    #[serial]
4222    fn dispatch_tracing_emits_one_gate_check_event_on_allow() {
4223        #[derive(Debug)]
4224        struct TracingAllowGate;
4225        impl Gate for TracingAllowGate {
4226            fn check(&self, _: &GateRequest) -> Result<GateDecision, GateError> {
4227                Ok(GateDecision::allow())
4228            }
4229            fn impl_name(&self) -> &'static str {
4230                "TracingAllowGate"
4231            }
4232        }
4233
4234        let events = capture_dispatch_events(async {
4235            let mut builder = VerbRegistryBuilder::new();
4236            builder.register(AlphaPack);
4237            builder.with_gate(Arc::new(TracingAllowGate));
4238            builder.with_default_namespace("tenant-default");
4239            let reg = builder.build().expect("registry builds");
4240            reg.dispatch("list", serde_json::json!({"namespace": "tenant-q"}))
4241                .await
4242                .unwrap();
4243        });
4244
4245        let gate_events = gate_check_events_for(&events, "TracingAllowGate");
4246        assert_eq!(
4247            gate_events.len(),
4248            1,
4249            "exactly one gate.check tracing event per dispatch (allow); got {gate_events:?}"
4250        );
4251        let payload = gate_events[0]
4252            .audit_event
4253            .as_ref()
4254            .expect("gate.check event must carry an audit_event field");
4255        let audit: khive_gate::AuditEvent =
4256            serde_json::from_str(payload).expect("audit_event payload must decode to AuditEvent");
4257        assert_eq!(audit.decision, AuditDecision::Allow);
4258        assert_eq!(audit.verb, "list");
4259        assert_eq!(audit.namespace, "tenant-q");
4260        assert_eq!(audit.gate_impl, "TracingAllowGate");
4261        assert!(
4262            audit.deny_reason.is_none(),
4263            "deny_reason must be None on Allow"
4264        );
4265    }
4266
4267    // ---- Hard enforcement + EventStore persistence ----
4268
4269    use crate::runtime::NamespaceToken;
4270    use async_trait::async_trait;
4271    use khive_storage::{
4272        BatchWriteSummary, Event, EventFilter, EventStore, Page, PageRequest, SubstrateKind,
4273    };
4274    use khive_types::EventOutcome;
4275
4276    /// In-memory EventStore for unit tests — avoids file-backed SQLite.
4277    #[derive(Default, Debug)]
4278    struct MemoryEventStore {
4279        events: std::sync::Mutex<Vec<Event>>,
4280    }
4281
4282    #[async_trait]
4283    impl EventStore for MemoryEventStore {
4284        async fn append_event(&self, event: Event) -> khive_storage::StorageResult<()> {
4285            self.events.lock().unwrap().push(event);
4286            Ok(())
4287        }
4288        async fn append_events(
4289            &self,
4290            events: Vec<Event>,
4291        ) -> khive_storage::StorageResult<BatchWriteSummary> {
4292            let attempted = events.len() as u64;
4293            let affected = attempted;
4294            self.events.lock().unwrap().extend(events);
4295            Ok(BatchWriteSummary {
4296                attempted,
4297                affected,
4298                failed: 0,
4299                first_error: String::new(),
4300            })
4301        }
4302        async fn get_event(&self, id: uuid::Uuid) -> khive_storage::StorageResult<Option<Event>> {
4303            Ok(self
4304                .events
4305                .lock()
4306                .unwrap()
4307                .iter()
4308                .find(|e| e.id == id)
4309                .cloned())
4310        }
4311        async fn query_events(
4312            &self,
4313            _filter: EventFilter,
4314            _page: PageRequest,
4315        ) -> khive_storage::StorageResult<Page<Event>> {
4316            let items = self.events.lock().unwrap().clone();
4317            let total = items.len() as u64;
4318            Ok(Page {
4319                items,
4320                total: Some(total),
4321            })
4322        }
4323        async fn count_events(&self, _filter: EventFilter) -> khive_storage::StorageResult<u64> {
4324            Ok(self.events.lock().unwrap().len() as u64)
4325        }
4326    }
4327
4328    #[tokio::test]
4329    async fn allow_all_gate_default_remains_backward_compatible() {
4330        // No gate set — AllowAllGate is the default. Dispatch must succeed.
4331        let mut builder = VerbRegistryBuilder::new();
4332        builder.register(AlphaPack);
4333        let reg = builder.build().expect("registry builds");
4334
4335        let res = reg.dispatch("list", Value::Null).await.unwrap();
4336        assert_eq!(
4337            res["pack"], "alpha",
4338            "AllowAllGate must allow every verb — backward compat guarantee"
4339        );
4340        let res = reg.dispatch("create", Value::Null).await.unwrap();
4341        assert_eq!(res["pack"], "alpha");
4342    }
4343
4344    #[tokio::test]
4345    async fn deny_gate_returns_permission_denied_pack_never_invoked() {
4346        #[derive(Debug)]
4347        struct AlwaysDenyGate;
4348        impl Gate for AlwaysDenyGate {
4349            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
4350                Ok(GateDecision::deny("test: always deny"))
4351            }
4352        }
4353
4354        // Track whether dispatch was ever invoked on the pack.
4355        #[derive(Debug)]
4356        struct TrackedPack {
4357            invoked: Arc<AtomicUsize>,
4358        }
4359
4360        impl khive_types::Pack for TrackedPack {
4361            const NAME: &'static str = "tracked";
4362            const NOTE_KINDS: &'static [&'static str] = &[];
4363            const ENTITY_KINDS: &'static [&'static str] = &[];
4364            const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
4365                name: "guarded",
4366                description: "a guarded verb",
4367                visibility: Visibility::Verb,
4368                category: VerbCategory::Assertive,
4369                params: &[],
4370            }];
4371        }
4372
4373        #[async_trait]
4374        impl PackRuntime for TrackedPack {
4375            fn name(&self) -> &str {
4376                Self::NAME
4377            }
4378            fn note_kinds(&self) -> &'static [&'static str] {
4379                Self::NOTE_KINDS
4380            }
4381            fn entity_kinds(&self) -> &'static [&'static str] {
4382                Self::ENTITY_KINDS
4383            }
4384            fn handlers(&self) -> &'static [HandlerDef] {
4385                Self::HANDLERS
4386            }
4387            async fn dispatch(
4388                &self,
4389                _verb: &str,
4390                _params: Value,
4391                _registry: &VerbRegistry,
4392                _token: &NamespaceToken,
4393            ) -> Result<Value, RuntimeError> {
4394                self.invoked.fetch_add(1, Ordering::SeqCst);
4395                Ok(serde_json::json!({"invoked": true}))
4396            }
4397        }
4398
4399        let invoked = Arc::new(AtomicUsize::new(0));
4400        let mut builder = VerbRegistryBuilder::new();
4401        builder.register(TrackedPack {
4402            invoked: invoked.clone(),
4403        });
4404        builder.with_gate(Arc::new(AlwaysDenyGate));
4405        let reg = builder.build().expect("registry builds");
4406
4407        let err = reg.dispatch("guarded", Value::Null).await.unwrap_err();
4408        assert!(
4409            matches!(err, RuntimeError::PermissionDenied { ref verb, ref reason } if verb == "guarded" && reason.contains("always deny")),
4410            "expected PermissionDenied with verb=guarded and reason, got: {err:?}"
4411        );
4412        assert_eq!(
4413            invoked.load(Ordering::SeqCst),
4414            0,
4415            "pack dispatch MUST NOT be invoked when gate denies"
4416        );
4417    }
4418
4419    #[tokio::test]
4420    async fn audit_event_persists_to_event_store_on_allow() {
4421        let store = Arc::new(MemoryEventStore::default());
4422        let mut builder = VerbRegistryBuilder::new();
4423        builder.register(AlphaPack);
4424        builder.with_event_store(store.clone());
4425        let reg = builder.build().expect("registry builds");
4426
4427        reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
4428            .await
4429            .unwrap();
4430
4431        let count = store.count_events(EventFilter::default()).await.unwrap();
4432        assert_eq!(count, 1, "one audit event persisted to EventStore on allow");
4433
4434        let page = store
4435            .query_events(
4436                EventFilter::default(),
4437                PageRequest {
4438                    limit: 10,
4439                    offset: 0,
4440                },
4441            )
4442            .await
4443            .unwrap();
4444        let ev = &page.items[0];
4445        assert_eq!(ev.verb, "list");
4446        assert_eq!(ev.namespace, "test-ns");
4447        assert_eq!(ev.substrate, SubstrateKind::Event);
4448        assert_eq!(ev.outcome, EventOutcome::Success);
4449    }
4450
4451    #[tokio::test]
4452    async fn audit_event_duration_us_reflects_measured_dispatch_time() {
4453        // The persisted audit row's `duration_us` must carry the measured
4454        // pack-dispatch time, not the `Event::new` default of 0 (persisting
4455        // the row before dispatch ran always yielded 0). `SleepingPack`
4456        // sleeps 20ms so the assertion has a wide, non-flaky margin over
4457        // scheduling jitter.
4458        let store = Arc::new(MemoryEventStore::default());
4459        let mut builder = VerbRegistryBuilder::new();
4460        builder.register(SleepingPack);
4461        builder.with_event_store(store.clone());
4462        let reg = builder.build().expect("registry builds");
4463
4464        reg.dispatch("slow_op", serde_json::json!({}))
4465            .await
4466            .unwrap();
4467
4468        let page = store
4469            .query_events(
4470                EventFilter::default(),
4471                PageRequest {
4472                    limit: 10,
4473                    offset: 0,
4474                },
4475            )
4476            .await
4477            .unwrap();
4478        assert_eq!(page.items.len(), 1);
4479        let ev = &page.items[0];
4480        assert!(
4481            ev.duration_us >= 10_000,
4482            "duration_us must reflect the ~20ms measured dispatch time, got {}",
4483            ev.duration_us
4484        );
4485    }
4486
4487    #[tokio::test]
4488    async fn dispatch_unknown_verb_allowed_by_gate_still_persists_audit_row() {
4489        // Generalizing audit-row deferral to every Allow-outcome verb (not
4490        // just singleton `link`) must not silently drop the audit row for a
4491        // verb the gate allows but no pack owns. `duration_us` stays at the
4492        // `Event::new` default of 0 here since no dispatch ever ran to measure.
4493        let store = Arc::new(MemoryEventStore::default());
4494        let mut builder = VerbRegistryBuilder::new();
4495        builder.register(AlphaPack);
4496        builder.with_event_store(store.clone());
4497        let reg = builder.build().expect("registry builds");
4498
4499        let result = reg.dispatch("no_such_verb", serde_json::json!({})).await;
4500        assert!(result.is_err(), "unknown verb must still return an error");
4501
4502        let count = store.count_events(EventFilter::default()).await.unwrap();
4503        assert_eq!(
4504            count, 1,
4505            "an allowed-but-unknown verb must still persist one audit row"
4506        );
4507        let page = store
4508            .query_events(
4509                EventFilter::default(),
4510                PageRequest {
4511                    limit: 10,
4512                    offset: 0,
4513                },
4514            )
4515            .await
4516            .unwrap();
4517        assert_eq!(page.items[0].duration_us, 0);
4518        // Dispatch returns InvalidInput for an unknown verb, so the
4519        // persisted outcome must be Error, not the previously-hardcoded
4520        // Success.
4521        assert_eq!(page.items[0].outcome, EventOutcome::Error);
4522    }
4523
4524    #[tokio::test]
4525    async fn audit_event_persists_to_event_store_on_deny() {
4526        #[derive(Debug)]
4527        struct AlwaysDenyGate;
4528        impl Gate for AlwaysDenyGate {
4529            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
4530                Ok(GateDecision::deny("denied by test"))
4531            }
4532        }
4533
4534        let store = Arc::new(MemoryEventStore::default());
4535        let mut builder = VerbRegistryBuilder::new();
4536        builder.register(AlphaPack);
4537        builder.with_gate(Arc::new(AlwaysDenyGate));
4538        builder.with_event_store(store.clone());
4539        let reg = builder.build().expect("registry builds");
4540
4541        // Hard enforce → PermissionDenied returned.
4542        let err = reg
4543            .dispatch("list", serde_json::json!({"namespace": "test-ns"}))
4544            .await
4545            .unwrap_err();
4546        assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
4547
4548        let count = store.count_events(EventFilter::default()).await.unwrap();
4549        assert_eq!(count, 1, "one audit event persisted to EventStore on deny");
4550
4551        let page = store
4552            .query_events(
4553                EventFilter::default(),
4554                PageRequest {
4555                    limit: 10,
4556                    offset: 0,
4557                },
4558            )
4559            .await
4560            .unwrap();
4561        let ev = &page.items[0];
4562        assert_eq!(ev.verb, "list");
4563        assert_eq!(ev.outcome, EventOutcome::Denied);
4564    }
4565
4566    #[tokio::test]
4567    async fn gate_error_does_not_persist_to_event_store() {
4568        #[derive(Debug)]
4569        struct FailingGate;
4570        impl Gate for FailingGate {
4571            fn check(&self, _req: &GateRequest) -> Result<GateDecision, khive_gate::GateError> {
4572                Err(khive_gate::GateError::Internal("gate broken".into()))
4573            }
4574        }
4575
4576        let store = Arc::new(MemoryEventStore::default());
4577        let mut builder = VerbRegistryBuilder::new();
4578        builder.register(AlphaPack);
4579        builder.with_gate(Arc::new(FailingGate));
4580        builder.with_event_store(store.clone());
4581        let reg = builder.build().expect("registry builds");
4582
4583        // Gate Err → fail-open, dispatch proceeds.
4584        let res = reg.dispatch("list", Value::Null).await.unwrap();
4585        assert_eq!(
4586            res["pack"], "alpha",
4587            "gate error must fail-open, not block dispatch"
4588        );
4589
4590        let count = store.count_events(EventFilter::default()).await.unwrap();
4591        assert_eq!(
4592            count, 0,
4593            "gate infrastructure error must NOT produce an audit event in EventStore"
4594        );
4595    }
4596
4597    #[tokio::test]
4598    async fn no_event_store_configured_tracing_only() {
4599        // When no event_store is configured, dispatch must succeed without error.
4600        // (The tracing path is exercised in the tracing tests above; here we just
4601        // verify the absence of event_store does not break dispatch.)
4602        let mut builder = VerbRegistryBuilder::new();
4603        builder.register(AlphaPack);
4604        let reg = builder.build().expect("registry builds");
4605
4606        let res = reg.dispatch("list", Value::Null).await.unwrap();
4607        assert_eq!(res["pack"], "alpha");
4608    }
4609
4610    #[test]
4611    #[serial]
4612    fn dispatch_tracing_emits_gate_check_event_with_deny_payload() {
4613        #[derive(Debug)]
4614        struct TracingDenyGate;
4615        impl Gate for TracingDenyGate {
4616            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
4617                Ok(GateDecision::deny("denied by test gate"))
4618            }
4619            fn impl_name(&self) -> &'static str {
4620                "TracingDenyGate"
4621            }
4622        }
4623
4624        let events = capture_dispatch_events(async {
4625            let mut builder = VerbRegistryBuilder::new();
4626            builder.register(AlphaPack);
4627            builder.with_gate(Arc::new(TracingDenyGate));
4628            let reg = builder.build().expect("registry builds");
4629            // Hard enforcement — dispatch returns PermissionDenied on Deny.
4630            // The tracing audit event is still emitted before the error is returned.
4631            let _ = reg.dispatch("create", serde_json::Value::Null).await;
4632        });
4633
4634        let gate_events = gate_check_events_for(&events, "TracingDenyGate");
4635        assert_eq!(
4636            gate_events.len(),
4637            1,
4638            "exactly one gate.check tracing event per dispatch (deny); got {gate_events:?}"
4639        );
4640        let payload = gate_events[0]
4641            .audit_event
4642            .as_ref()
4643            .expect("gate.check event must carry an audit_event field on Deny");
4644        let audit: khive_gate::AuditEvent =
4645            serde_json::from_str(payload).expect("audit_event payload must decode to AuditEvent");
4646        assert_eq!(audit.decision, AuditDecision::Deny);
4647        assert_eq!(audit.deny_reason.as_deref(), Some("denied by test gate"));
4648        assert_eq!(audit.gate_impl, "TracingDenyGate");
4649        // Wire-shape rule: obligations is always serialized as an array, empty
4650        // on Deny. Round-trip back through serde_json::Value to confirm the
4651        // field exists on the wire and is `[]`, not missing.
4652        let payload_json: serde_json::Value =
4653            serde_json::from_str(payload).expect("payload must be valid JSON");
4654        assert_eq!(
4655            payload_json["obligations"],
4656            serde_json::Value::Array(Vec::new()),
4657            "obligations must be `[]` on Deny on the tracing payload, not omitted"
4658        );
4659    }
4660
4661    // ---- EventStore audit envelope round-trip ----
4662    //
4663    // EventStore must not persist a summary Event without the full
4664    // AuditEvent fields (deny_reason, gate_impl, obligations). This test
4665    // verifies the complete envelope survives append_event → query_events.
4666
4667    #[tokio::test]
4668    async fn audit_envelope_round_trips_deny_reason_and_gate_impl_through_event_store() {
4669        #[derive(Debug)]
4670        struct DenyGateWithName;
4671        impl Gate for DenyGateWithName {
4672            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
4673                Ok(GateDecision::deny("policy: write forbidden for anon"))
4674            }
4675            fn impl_name(&self) -> &'static str {
4676                "DenyGateWithName"
4677            }
4678        }
4679
4680        let store = Arc::new(MemoryEventStore::default());
4681        let mut builder = VerbRegistryBuilder::new();
4682        builder.register(AlphaPack);
4683        builder.with_gate(Arc::new(DenyGateWithName));
4684        builder.with_event_store(store.clone());
4685        let reg = builder.build().expect("registry builds");
4686
4687        // Dispatch is denied — PermissionDenied returned.
4688        let err = reg
4689            .dispatch("list", serde_json::json!({"namespace": "test-ns"}))
4690            .await
4691            .unwrap_err();
4692        assert!(
4693            matches!(err, RuntimeError::PermissionDenied { .. }),
4694            "expected PermissionDenied, got {err:?}"
4695        );
4696
4697        // Exactly one event in the store.
4698        let page = store
4699            .query_events(
4700                EventFilter::default(),
4701                PageRequest {
4702                    limit: 10,
4703                    offset: 0,
4704                },
4705            )
4706            .await
4707            .unwrap();
4708        assert_eq!(
4709            page.items.len(),
4710            1,
4711            "one audit event must be persisted on deny"
4712        );
4713
4714        let ev = &page.items[0];
4715        assert_eq!(ev.outcome, EventOutcome::Denied);
4716
4717        // The payload field must hold the full AuditEvent envelope.
4718        let data = &ev.payload;
4719
4720        let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
4721            .expect("Event.payload must deserialize to AuditEvent");
4722
4723        assert_eq!(
4724            audit.deny_reason.as_deref(),
4725            Some("policy: write forbidden for anon"),
4726            "deny_reason must be preserved through EventStore"
4727        );
4728        assert_eq!(
4729            audit.gate_impl, "DenyGateWithName",
4730            "gate_impl must be preserved through EventStore"
4731        );
4732        assert_eq!(
4733            audit.decision,
4734            khive_gate::AuditDecision::Deny,
4735            "decision field must be preserved through EventStore"
4736        );
4737    }
4738
4739    #[tokio::test]
4740    async fn audit_envelope_round_trips_obligations_through_event_store() {
4741        use khive_gate::Obligation;
4742
4743        #[derive(Debug)]
4744        struct ObligationGate;
4745        impl Gate for ObligationGate {
4746            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
4747                Ok(GateDecision::allow_with(vec![Obligation::Audit {
4748                    tag: "billing.meter".into(),
4749                }]))
4750            }
4751            fn impl_name(&self) -> &'static str {
4752                "ObligationGate"
4753            }
4754        }
4755
4756        let store = Arc::new(MemoryEventStore::default());
4757        let mut builder = VerbRegistryBuilder::new();
4758        builder.register(AlphaPack);
4759        builder.with_gate(Arc::new(ObligationGate));
4760        builder.with_event_store(store.clone());
4761        let reg = builder.build().expect("registry builds");
4762
4763        reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
4764            .await
4765            .unwrap();
4766
4767        let page = store
4768            .query_events(
4769                EventFilter::default(),
4770                PageRequest {
4771                    limit: 10,
4772                    offset: 0,
4773                },
4774            )
4775            .await
4776            .unwrap();
4777        assert_eq!(page.items.len(), 1);
4778
4779        let ev = &page.items[0];
4780        assert_eq!(ev.outcome, EventOutcome::Success);
4781
4782        let data = &ev.payload;
4783
4784        let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
4785            .expect("Event.payload must deserialize to AuditEvent");
4786
4787        assert_eq!(audit.gate_impl, "ObligationGate");
4788        assert_eq!(
4789            audit.obligations.len(),
4790            1,
4791            "obligations must be preserved through EventStore"
4792        );
4793        match &audit.obligations[0] {
4794            Obligation::Audit { tag } => assert_eq!(tag, "billing.meter"),
4795            other => panic!("expected Audit obligation, got {other:?}"),
4796        }
4797    }
4798
4799    // ---- SQL-backed audit envelope round-trip ----
4800    //
4801    // The two tests above use MemoryEventStore (no serialization). This test
4802    // wires the production SqlEventStore via KhiveRuntime::memory() to verify
4803    // that the full AuditEvent envelope survives the SQL text→parse round-trip
4804    // (Event.data is stored as TEXT and parsed back on read).
4805
4806    #[tokio::test]
4807    async fn sql_backed_audit_envelope_round_trips_deny_reason_gate_impl_and_obligations() {
4808        #[derive(Debug)]
4809        struct SqlTestDenyGate;
4810        impl Gate for SqlTestDenyGate {
4811            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
4812                Ok(GateDecision::deny("sql-path: write denied"))
4813            }
4814            fn impl_name(&self) -> &'static str {
4815                "SqlTestDenyGate"
4816            }
4817        }
4818
4819        // KhiveRuntime::memory() creates an in-memory SQLite pool (is_file_backed=false).
4820        // events_for_namespace ensures the events schema and returns a SqlEventStore
4821        // scoped to "test-ns". The pool is shared so reads and writes see the same data.
4822        let rt = KhiveRuntime::memory().expect("in-memory runtime");
4823        let test_tok = NamespaceToken::for_namespace(Namespace::parse("test-ns").unwrap());
4824        let sql_store = rt
4825            .events(&test_tok)
4826            .expect("events_for_namespace must succeed");
4827
4828        let mut builder = VerbRegistryBuilder::new();
4829        builder.register(AlphaPack);
4830        builder.with_gate(Arc::new(SqlTestDenyGate));
4831        builder.with_event_store(sql_store.clone());
4832        let reg = builder.build().expect("registry builds");
4833
4834        // Dispatch is denied — PermissionDenied returned.
4835        let err = reg
4836            .dispatch("list", serde_json::json!({"namespace": "test-ns"}))
4837            .await
4838            .unwrap_err();
4839        assert!(
4840            matches!(err, RuntimeError::PermissionDenied { .. }),
4841            "expected PermissionDenied, got {err:?}"
4842        );
4843
4844        // Query via the same SqlEventStore — this is the SQL read path.
4845        let page = sql_store
4846            .query_events(
4847                EventFilter::default(),
4848                PageRequest {
4849                    limit: 10,
4850                    offset: 0,
4851                },
4852            )
4853            .await
4854            .unwrap();
4855        assert_eq!(
4856            page.items.len(),
4857            1,
4858            "one audit event must be persisted on deny through SqlEventStore"
4859        );
4860
4861        let ev = &page.items[0];
4862        assert_eq!(ev.outcome, EventOutcome::Denied);
4863
4864        // Event.payload must hold the full AuditEvent serialized as JSON text and
4865        // parsed back. If the SQL path was lossy, this deserialization would fail
4866        // or the field assertions below would fail.
4867        let data = &ev.payload;
4868
4869        let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
4870            .expect("Event.payload must deserialize to AuditEvent after SQL round-trip");
4871
4872        assert_eq!(
4873            audit.deny_reason.as_deref(),
4874            Some("sql-path: write denied"),
4875            "deny_reason must survive the SQL text round-trip"
4876        );
4877        assert_eq!(
4878            audit.gate_impl, "SqlTestDenyGate",
4879            "gate_impl must survive the SQL text round-trip"
4880        );
4881        assert_eq!(
4882            audit.decision,
4883            khive_gate::AuditDecision::Deny,
4884            "decision field must survive the SQL text round-trip"
4885        );
4886        // obligations is [] on a Deny gate (no obligations returned).
4887        // Verify the field is present and empty after SQL round-trip.
4888        assert!(
4889            audit.obligations.is_empty(),
4890            "obligations must be preserved as empty [] through SQL round-trip"
4891        );
4892    }
4893
4894    // ---- SQL-backed audit envelope: non-empty obligations survive round-trip ----
4895    //
4896    // Blind spot: the deny-path SQL test above only
4897    // asserts obligations == [], which passes even if the SQL path drops the
4898    // field entirely (AuditEvent.obligations has #[serde(default)]).
4899    //
4900    // This test installs an allow-path gate that returns a non-empty obligations
4901    // vec. After dispatch, the same SqlEventStore is queried and both layers are
4902    // checked:
4903    //   1. Raw Event.data["obligations"] is a non-empty JSON array.
4904    //   2. Deserialized AuditEvent.obligations[0] matches the expected variant.
4905    #[tokio::test]
4906    async fn sql_backed_audit_envelope_round_trips_non_empty_obligations() {
4907        use khive_gate::Obligation;
4908
4909        #[derive(Debug)]
4910        struct SqlTestAllowWithObligationGate;
4911        impl Gate for SqlTestAllowWithObligationGate {
4912            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
4913                Ok(GateDecision::allow_with(vec![Obligation::Audit {
4914                    tag: "sql-path-billing.meter".into(),
4915                }]))
4916            }
4917            fn impl_name(&self) -> &'static str {
4918                "SqlTestAllowWithObligationGate"
4919            }
4920        }
4921
4922        let rt = KhiveRuntime::memory().expect("in-memory runtime");
4923        let test_tok = NamespaceToken::for_namespace(Namespace::parse("test-ns").unwrap());
4924        let sql_store = rt
4925            .events(&test_tok)
4926            .expect("events_for_namespace must succeed");
4927
4928        let mut builder = VerbRegistryBuilder::new();
4929        builder.register(AlphaPack);
4930        builder.with_gate(Arc::new(SqlTestAllowWithObligationGate));
4931        builder.with_event_store(sql_store.clone());
4932        let reg = builder.build().expect("registry builds");
4933
4934        // Dispatch succeeds — the gate allows with obligations.
4935        reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
4936            .await
4937            .expect("dispatch must succeed when gate allows");
4938
4939        // Query via the same SqlEventStore — this is the SQL read path.
4940        let page = sql_store
4941            .query_events(
4942                EventFilter::default(),
4943                PageRequest {
4944                    limit: 10,
4945                    offset: 0,
4946                },
4947            )
4948            .await
4949            .unwrap();
4950        assert_eq!(
4951            page.items.len(),
4952            1,
4953            "one audit event must be persisted on allow through SqlEventStore"
4954        );
4955
4956        let ev = &page.items[0];
4957        assert_eq!(ev.outcome, EventOutcome::Success);
4958
4959        let data = &ev.payload;
4960
4961        // Layer 1: raw JSON check — obligations must be a non-empty array in
4962        // the persisted TEXT. If the SQL path dropped the field, the default
4963        // #[serde(default)] would silently deserialize it to [], so we verify
4964        // the raw JSON before deserializing.
4965        let obligations_raw = data
4966            .get("obligations")
4967            .expect("Event.data JSON must contain 'obligations' key");
4968        let obligations_arr = obligations_raw
4969            .as_array()
4970            .expect("'obligations' must be a JSON array");
4971        assert!(
4972            !obligations_arr.is_empty(),
4973            "raw Event.data['obligations'] must be non-empty after SQL round-trip"
4974        );
4975
4976        // Layer 2: deserialized AuditEvent check — the obligation variant and
4977        // payload must survive the text round-trip faithfully.
4978        let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
4979            .expect("Event.data must deserialize to AuditEvent after SQL round-trip");
4980
4981        assert_eq!(
4982            audit.gate_impl, "SqlTestAllowWithObligationGate",
4983            "gate_impl must survive the SQL text round-trip"
4984        );
4985        assert_eq!(
4986            audit.decision,
4987            khive_gate::AuditDecision::Allow,
4988            "decision field must survive the SQL text round-trip"
4989        );
4990        assert_eq!(
4991            audit.obligations.len(),
4992            1,
4993            "obligations must be non-empty after SQL round-trip (not silently defaulted to [])"
4994        );
4995        match &audit.obligations[0] {
4996            Obligation::Audit { tag } => assert_eq!(
4997                tag, "sql-path-billing.meter",
4998                "Audit obligation tag must survive the SQL text round-trip"
4999            ),
5000            other => panic!("expected Audit obligation, got {other:?}"),
5001        }
5002    }
5003
5004    // ---- Audit payload shape for 'create' verb dispatch ----
5005    //
5006    // The previous audit tests verify the envelope shape for the 'list' verb.
5007    // This test dispatches 'create' (matching the create_note + annotates path)
5008    // and verifies that ev.verb, ev.outcome, and ev.data all round-trip correctly
5009    // through the EventStore. Ensures the wire shape is independent of which verb
5010    // triggers the gate check.
5011    #[tokio::test]
5012    async fn audit_event_payload_shape_for_create_verb() {
5013        let store = Arc::new(MemoryEventStore::default());
5014        let mut builder = VerbRegistryBuilder::new();
5015        builder.register(AlphaPack);
5016        builder.with_event_store(store.clone());
5017        builder.with_default_namespace("test-ns");
5018        let reg = builder.build().expect("registry builds");
5019
5020        // Dispatch 'create' — AlphaPack returns a stub value; what matters is
5021        // the EventStore entry emitted by the registry's gate-check path.
5022        reg.dispatch("create", serde_json::json!({"namespace": "test-ns"}))
5023            .await
5024            .unwrap();
5025
5026        let count = store.count_events(EventFilter::default()).await.unwrap();
5027        assert_eq!(count, 1, "exactly one audit event for one dispatch");
5028
5029        let page = store
5030            .query_events(
5031                EventFilter::default(),
5032                PageRequest {
5033                    limit: 10,
5034                    offset: 0,
5035                },
5036            )
5037            .await
5038            .unwrap();
5039        let ev = &page.items[0];
5040
5041        // Top-level Event fields.
5042        assert_eq!(ev.verb, "create", "ev.verb must be the dispatched verb");
5043        assert_eq!(
5044            ev.outcome,
5045            EventOutcome::Success,
5046            "ev.outcome must be Success on allow"
5047        );
5048        assert_eq!(
5049            ev.namespace, "test-ns",
5050            "ev.namespace must match the dispatch namespace"
5051        );
5052
5053        // ev.payload must hold the full AuditEvent envelope.
5054        let data = &ev.payload;
5055
5056        let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
5057            .expect("ev.payload must deserialize to AuditEvent");
5058
5059        assert_eq!(
5060            audit.decision,
5061            khive_gate::AuditDecision::Allow,
5062            "AuditEvent.decision must be Allow"
5063        );
5064        assert_eq!(audit.verb, "create", "AuditEvent.verb must be 'create'");
5065        assert_eq!(
5066            audit.namespace, "test-ns",
5067            "AuditEvent.namespace must be preserved"
5068        );
5069        assert_eq!(
5070            audit.gate_impl, "AllowAllGate",
5071            "AuditEvent.gate_impl must name the gate implementation"
5072        );
5073        assert!(
5074            audit.deny_reason.is_none(),
5075            "AuditEvent.deny_reason must be None on Allow"
5076        );
5077        // Wire-shape check: obligations serializes as [] on AllowAllGate.
5078        let payload_json: serde_json::Value =
5079            serde_json::from_value(data.clone()).expect("data must be valid JSON");
5080        assert_eq!(
5081            payload_json["obligations"],
5082            serde_json::Value::Array(Vec::new()),
5083            "obligations must be [] on AllowAllGate"
5084        );
5085    }
5086
5087    // ---- ADR-103 Amendment 1: resource.cost_unit emission ----
5088
5089    /// Test pack whose `create` handler is a stub (mirrors `AlphaPack`) but
5090    /// overrides `registered_embedding_model_names` to a configurable set,
5091    /// exercising ADR-103 Amendment 1's `model_count` computation for
5092    /// singleton `create` at the dispatch audit-row emission seam.
5093    struct EmbeddingAwarePack {
5094        models: Vec<String>,
5095    }
5096
5097    impl khive_types::Pack for EmbeddingAwarePack {
5098        const NAME: &'static str = "embedding_aware";
5099        const NOTE_KINDS: &'static [&'static str] = &[];
5100        const ENTITY_KINDS: &'static [&'static str] = &["widget"];
5101        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
5102            name: "create",
5103            description: "create a widget (embedding-aware stub)",
5104            visibility: Visibility::Verb,
5105            category: VerbCategory::Commissive,
5106            params: &[],
5107        }];
5108    }
5109
5110    #[async_trait]
5111    impl PackRuntime for EmbeddingAwarePack {
5112        fn name(&self) -> &str {
5113            Self::NAME
5114        }
5115        fn note_kinds(&self) -> &'static [&'static str] {
5116            Self::NOTE_KINDS
5117        }
5118        fn entity_kinds(&self) -> &'static [&'static str] {
5119            Self::ENTITY_KINDS
5120        }
5121        fn handlers(&self) -> &'static [HandlerDef] {
5122            Self::HANDLERS
5123        }
5124        fn registered_embedding_model_names(&self) -> Vec<String> {
5125            self.models.clone()
5126        }
5127        async fn dispatch(
5128            &self,
5129            verb: &str,
5130            _params: Value,
5131            _registry: &VerbRegistry,
5132            _token: &NamespaceToken,
5133        ) -> Result<Value, RuntimeError> {
5134            Ok(serde_json::json!({ "pack": "embedding_aware", "verb": verb }))
5135        }
5136    }
5137
5138    /// Test pack whose one verb, `probe`, always fails — used to drive the
5139    /// general (non-link) deferred-audit Err arm without a real backend.
5140    struct FailingProbePack;
5141
5142    impl khive_types::Pack for FailingProbePack {
5143        const NAME: &'static str = "failing_probe";
5144        const NOTE_KINDS: &'static [&'static str] = &[];
5145        const ENTITY_KINDS: &'static [&'static str] = &[];
5146        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
5147            name: "probe",
5148            description: "always fails",
5149            visibility: Visibility::Verb,
5150            category: VerbCategory::Assertive,
5151            params: &[],
5152        }];
5153    }
5154
5155    #[async_trait]
5156    impl PackRuntime for FailingProbePack {
5157        fn name(&self) -> &str {
5158            Self::NAME
5159        }
5160        fn note_kinds(&self) -> &'static [&'static str] {
5161            Self::NOTE_KINDS
5162        }
5163        fn entity_kinds(&self) -> &'static [&'static str] {
5164            Self::ENTITY_KINDS
5165        }
5166        fn handlers(&self) -> &'static [HandlerDef] {
5167            Self::HANDLERS
5168        }
5169        async fn dispatch(
5170            &self,
5171            _verb: &str,
5172            _params: Value,
5173            _registry: &VerbRegistry,
5174            _token: &NamespaceToken,
5175        ) -> Result<Value, RuntimeError> {
5176            Err(RuntimeError::InvalidInput("boom".into()))
5177        }
5178    }
5179
5180    #[tokio::test]
5181    async fn resource_cost_unit_present_on_non_embedding_successful_dispatch() {
5182        let store = Arc::new(MemoryEventStore::default());
5183        let mut builder = VerbRegistryBuilder::new();
5184        builder.register(AlphaPack);
5185        builder.with_event_store(store.clone());
5186        let reg = builder.build().expect("registry builds");
5187
5188        reg.dispatch("list", serde_json::json!({})).await.unwrap();
5189
5190        let page = store
5191            .query_events(
5192                EventFilter::default(),
5193                PageRequest {
5194                    limit: 10,
5195                    offset: 0,
5196                },
5197            )
5198            .await
5199            .unwrap();
5200        assert_eq!(page.items.len(), 1);
5201        assert_eq!(
5202            page.items[0].payload["resource"],
5203            serde_json::json!({"work_class": "interactive", "cost_unit": 1}),
5204            "non-embedding-bearing verb's resource.cost_unit must be base_weight(verb) alone"
5205        );
5206    }
5207
5208    #[tokio::test]
5209    async fn resource_cost_unit_scales_with_registered_model_count_for_create() {
5210        let store = Arc::new(MemoryEventStore::default());
5211        let mut builder = VerbRegistryBuilder::new();
5212        builder.register(EmbeddingAwarePack {
5213            models: vec!["all-minilm-l6-v2".into(), "paraphrase".into()],
5214        });
5215        builder.with_event_store(store.clone());
5216        let reg = builder.build().expect("registry builds");
5217
5218        reg.dispatch("create", serde_json::json!({"kind": "widget"}))
5219            .await
5220            .unwrap();
5221
5222        let page = store
5223            .query_events(
5224                EventFilter::default(),
5225                PageRequest {
5226                    limit: 10,
5227                    offset: 0,
5228                },
5229            )
5230            .await
5231            .unwrap();
5232        // base_weight(1) + per_item_weight(1) * item_count(1) * model_count(2)
5233        assert_eq!(
5234            page.items[0].payload["resource"],
5235            serde_json::json!({"work_class": "interactive", "cost_unit": 3}),
5236        );
5237    }
5238
5239    #[tokio::test]
5240    async fn resource_cost_unit_zero_registered_models_is_base_weight_only() {
5241        let store = Arc::new(MemoryEventStore::default());
5242        let mut builder = VerbRegistryBuilder::new();
5243        builder.register(EmbeddingAwarePack { models: vec![] });
5244        builder.with_event_store(store.clone());
5245        let reg = builder.build().expect("registry builds");
5246
5247        reg.dispatch("create", serde_json::json!({"kind": "widget"}))
5248            .await
5249            .unwrap();
5250
5251        let page = store
5252            .query_events(
5253                EventFilter::default(),
5254                PageRequest {
5255                    limit: 10,
5256                    offset: 0,
5257                },
5258            )
5259            .await
5260            .unwrap();
5261        assert_eq!(
5262            page.items[0].payload["resource"]["cost_unit"], 1,
5263            "zero registered embedding models must vanish the term, not error or omit"
5264        );
5265    }
5266
5267    #[tokio::test]
5268    async fn resource_work_class_present_cost_unit_absent_when_dispatch_returns_error() {
5269        let store = Arc::new(MemoryEventStore::default());
5270        let mut builder = VerbRegistryBuilder::new();
5271        builder.register(FailingProbePack);
5272        builder.with_event_store(store.clone());
5273        let reg = builder.build().expect("registry builds");
5274
5275        let err = reg
5276            .dispatch("probe", serde_json::json!({}))
5277            .await
5278            .unwrap_err();
5279        assert!(matches!(err, RuntimeError::InvalidInput(_)));
5280
5281        let page = store
5282            .query_events(
5283                EventFilter::default(),
5284                PageRequest {
5285                    limit: 10,
5286                    offset: 0,
5287                },
5288            )
5289            .await
5290            .unwrap();
5291        assert_eq!(page.items.len(), 1);
5292        assert_eq!(page.items[0].outcome, EventOutcome::Error);
5293        // ADR-103 Decision (a): work_class is stamped on EVERY event, denial
5294        // and error included -- only Amendment 1's cost_unit field is scoped
5295        // to a successful dispatch. An errored dispatch keeps
5296        // resource.work_class and omits only resource.cost_unit, never 0.
5297        assert_eq!(
5298            page.items[0].payload["resource"],
5299            serde_json::json!({"work_class": "interactive"}),
5300            "resource must carry work_class with cost_unit OMITTED (never 0) on an \
5301             errored dispatch: {:?}",
5302            page.items[0].payload
5303        );
5304    }
5305
5306    #[tokio::test]
5307    async fn resource_work_class_present_cost_unit_absent_when_no_pack_owns_the_verb() {
5308        let store = Arc::new(MemoryEventStore::default());
5309        let mut builder = VerbRegistryBuilder::new();
5310        builder.register(AlphaPack);
5311        builder.with_event_store(store.clone());
5312        let reg = builder.build().expect("registry builds");
5313
5314        let _ = reg
5315            .dispatch("no_such_verb_resource_test", serde_json::json!({}))
5316            .await;
5317
5318        let page = store
5319            .query_events(
5320                EventFilter::default(),
5321                PageRequest {
5322                    limit: 10,
5323                    offset: 0,
5324                },
5325            )
5326            .await
5327            .unwrap();
5328        assert_eq!(page.items.len(), 1);
5329        assert_eq!(
5330            page.items[0].payload["resource"],
5331            serde_json::json!({"work_class": "interactive"})
5332        );
5333    }
5334
5335    #[tokio::test]
5336    async fn resource_work_class_present_cost_unit_absent_on_denied_dispatch() {
5337        #[derive(Debug)]
5338        struct AlwaysDenyGate;
5339        impl Gate for AlwaysDenyGate {
5340            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
5341                Ok(GateDecision::deny("test: always deny"))
5342            }
5343        }
5344        let store = Arc::new(MemoryEventStore::default());
5345        let mut builder = VerbRegistryBuilder::new();
5346        builder.register(AlphaPack);
5347        builder.with_gate(Arc::new(AlwaysDenyGate));
5348        builder.with_event_store(store.clone());
5349        let reg = builder.build().expect("registry builds");
5350
5351        let _ = reg.dispatch("list", serde_json::json!({})).await;
5352
5353        let page = store
5354            .query_events(
5355                EventFilter::default(),
5356                PageRequest {
5357                    limit: 10,
5358                    offset: 0,
5359                },
5360            )
5361            .await
5362            .unwrap();
5363        assert_eq!(page.items.len(), 1);
5364        assert_eq!(page.items[0].outcome, EventOutcome::Denied);
5365        assert_eq!(
5366            page.items[0].payload["resource"],
5367            serde_json::json!({"work_class": "interactive"})
5368        );
5369    }
5370
5371    #[tokio::test]
5372    async fn resource_cost_unit_present_on_link_singleton_success() {
5373        let store = Arc::new(MemoryEventStore::default());
5374        let edge_id = uuid::Uuid::new_v4();
5375        let source_id = uuid::Uuid::new_v4();
5376        let target_id = uuid::Uuid::new_v4();
5377        let edge_json = serde_json::json!({
5378            "id": edge_id,
5379            "namespace": "local",
5380            "source_id": source_id,
5381            "target_id": target_id,
5382            "relation": "depends_on",
5383            "weight": 1.0,
5384        });
5385        let mut builder = VerbRegistryBuilder::new();
5386        builder.register(LinkResultPack::ok(edge_json));
5387        builder.with_event_store(store.clone());
5388        let reg = builder.build().expect("registry builds");
5389
5390        reg.dispatch(
5391            "link",
5392            serde_json::json!({
5393                "source_id": source_id,
5394                "target_id": target_id,
5395                "relation": "depends_on",
5396            }),
5397        )
5398        .await
5399        .unwrap();
5400
5401        let page = store
5402            .query_events(
5403                EventFilter::default(),
5404                PageRequest {
5405                    limit: 10,
5406                    offset: 0,
5407                },
5408            )
5409            .await
5410            .unwrap();
5411        assert_eq!(
5412            page.items[0].payload["resource"],
5413            serde_json::json!({"work_class": "interactive", "cost_unit": 1}),
5414            "link has no embedding-bearing path -> base_weight(link) alone, even on the v2-enriched singleton path"
5415        );
5416    }
5417
5418    #[tokio::test]
5419    async fn resource_work_class_present_cost_unit_absent_on_link_dispatch_failure() {
5420        let store = Arc::new(MemoryEventStore::default());
5421        let mut builder = VerbRegistryBuilder::new();
5422        builder.register(LinkResultPack::err("target endpoint not found"));
5423        builder.with_event_store(store.clone());
5424        let reg = builder.build().expect("registry builds");
5425
5426        let _ = reg
5427            .dispatch(
5428                "link",
5429                serde_json::json!({
5430                    "source_id": "note:alpha",
5431                    "target_id": "note:missing",
5432                    "relation": "depends_on",
5433                }),
5434            )
5435            .await;
5436
5437        let page = store
5438            .query_events(
5439                EventFilter::default(),
5440                PageRequest {
5441                    limit: 10,
5442                    offset: 0,
5443                },
5444            )
5445            .await
5446            .unwrap();
5447        assert_eq!(page.items.len(), 1);
5448        assert_eq!(
5449            page.items[0].payload["resource"],
5450            serde_json::json!({"work_class": "interactive"})
5451        );
5452    }
5453
5454    // Registry audit event must carry target_id when dispatch params include it.
5455    #[tokio::test]
5456    async fn audit_event_threads_target_id_from_dispatch_args() {
5457        let store = Arc::new(MemoryEventStore::default());
5458        let target = uuid::Uuid::new_v4();
5459        let mut builder = VerbRegistryBuilder::new();
5460        builder.register(AlphaPack);
5461        builder.with_event_store(store.clone());
5462        builder.with_default_namespace("test-ns");
5463        let reg = builder.build().expect("registry builds");
5464
5465        reg.dispatch(
5466            "create",
5467            serde_json::json!({"namespace": "test-ns", "target_id": target}),
5468        )
5469        .await
5470        .unwrap();
5471
5472        let page = store
5473            .query_events(
5474                EventFilter::default(),
5475                PageRequest {
5476                    offset: 0,
5477                    limit: 10,
5478                },
5479            )
5480            .await
5481            .unwrap();
5482        assert_eq!(
5483            page.items[0].target_id,
5484            Some(target),
5485            "#282: audit event must carry target_id from dispatch params"
5486        );
5487    }
5488
5489    // ---- Link-verb audit enrichment ----
5490
5491    /// Test pack exposing a single `link` verb whose one-shot result is
5492    /// configured up front — lets tests drive both the success and failure
5493    /// legs of the deferred link-audit path without a real KG backend.
5494    struct LinkResultPack {
5495        result: std::sync::Mutex<Option<Result<Value, RuntimeError>>>,
5496    }
5497
5498    impl LinkResultPack {
5499        fn ok(value: Value) -> Self {
5500            Self {
5501                result: std::sync::Mutex::new(Some(Ok(value))),
5502            }
5503        }
5504        fn err(message: &str) -> Self {
5505            Self {
5506                result: std::sync::Mutex::new(Some(Err(RuntimeError::InvalidInput(
5507                    message.to_string(),
5508                )))),
5509            }
5510        }
5511    }
5512
5513    impl khive_types::Pack for LinkResultPack {
5514        const NAME: &'static str = "kg";
5515        const NOTE_KINDS: &'static [&'static str] = &[];
5516        const ENTITY_KINDS: &'static [&'static str] = &[];
5517        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
5518            name: "link",
5519            description: "test link handler",
5520            visibility: Visibility::Verb,
5521            category: VerbCategory::Commissive,
5522            params: &[],
5523        }];
5524    }
5525
5526    #[async_trait]
5527    impl PackRuntime for LinkResultPack {
5528        fn name(&self) -> &str {
5529            Self::NAME
5530        }
5531        fn note_kinds(&self) -> &'static [&'static str] {
5532            Self::NOTE_KINDS
5533        }
5534        fn entity_kinds(&self) -> &'static [&'static str] {
5535            Self::ENTITY_KINDS
5536        }
5537        fn handlers(&self) -> &'static [HandlerDef] {
5538            Self::HANDLERS
5539        }
5540        async fn dispatch(
5541            &self,
5542            _verb: &str,
5543            _params: Value,
5544            _registry: &VerbRegistry,
5545            _token: &NamespaceToken,
5546        ) -> Result<Value, RuntimeError> {
5547            self.result
5548                .lock()
5549                .unwrap()
5550                .take()
5551                .expect("LinkResultPack dispatch called more than once in a test")
5552        }
5553    }
5554
5555    #[tokio::test]
5556    async fn link_audit_enriches_successful_singleton_with_edge_v2() {
5557        let store = Arc::new(MemoryEventStore::default());
5558        let edge_id = uuid::Uuid::new_v4();
5559        let source_id = uuid::Uuid::new_v4();
5560        let target_id = uuid::Uuid::new_v4();
5561        let edge_json = serde_json::json!({
5562            "id": edge_id,
5563            "namespace": "local",
5564            "source_id": source_id,
5565            "target_id": target_id,
5566            "relation": "depends_on",
5567            "weight": 1.0,
5568        });
5569        let mut builder = VerbRegistryBuilder::new();
5570        builder.register(LinkResultPack::ok(edge_json));
5571        builder.with_event_store(store.clone());
5572        builder.with_default_namespace("test-ns");
5573        let reg = builder.build().expect("registry builds");
5574
5575        reg.dispatch(
5576            "link",
5577            serde_json::json!({
5578                "source_id": source_id,
5579                "target_id": target_id,
5580                "relation": "depends_on",
5581            }),
5582        )
5583        .await
5584        .unwrap();
5585
5586        let count = store.count_events(EventFilter::default()).await.unwrap();
5587        assert_eq!(
5588            count, 1,
5589            "exactly one deferred audit row must be persisted for a successful singleton link"
5590        );
5591        let page = store
5592            .query_events(
5593                EventFilter::default(),
5594                PageRequest {
5595                    limit: 10,
5596                    offset: 0,
5597                },
5598            )
5599            .await
5600            .unwrap();
5601        let ev = &page.items[0];
5602        assert_eq!(ev.verb, "link");
5603        assert_eq!(ev.outcome, EventOutcome::Success);
5604        assert_eq!(
5605            ev.payload_schema_version, 2,
5606            "successful singleton link uses audit schema v2"
5607        );
5608        assert_eq!(
5609            ev.target_id,
5610            Some(edge_id),
5611            "target_id must be the created/resolved edge id, not a raw caller arg"
5612        );
5613        assert_eq!(ev.payload["edge_id"], serde_json::json!(edge_id));
5614        assert_eq!(ev.payload["source_id"], serde_json::json!(source_id));
5615        assert_eq!(ev.payload["target_id"], serde_json::json!(target_id));
5616        assert_eq!(ev.payload["relation"], "depends_on");
5617        assert_eq!(ev.payload["weight"], 1.0);
5618        // v1 AuditEvent fields remain present via #[serde(flatten)].
5619        assert_eq!(ev.payload["verb"], "link");
5620        assert_eq!(ev.payload["decision"], "allow");
5621        assert!(ev.payload.get("gate_impl").is_some());
5622    }
5623
5624    #[tokio::test]
5625    async fn link_audit_falls_back_to_v1_when_dispatch_fails() {
5626        let store = Arc::new(MemoryEventStore::default());
5627        let mut builder = VerbRegistryBuilder::new();
5628        builder.register(LinkResultPack::err("target endpoint not found"));
5629        builder.with_event_store(store.clone());
5630        builder.with_default_namespace("test-ns");
5631        let reg = builder.build().expect("registry builds");
5632
5633        let err = reg
5634            .dispatch(
5635                "link",
5636                serde_json::json!({
5637                    "source_id": "note:alpha",
5638                    "target_id": "note:missing",
5639                    "relation": "depends_on",
5640                }),
5641            )
5642            .await
5643            .unwrap_err();
5644        assert!(
5645            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("not found")),
5646            "the original dispatch error must be returned unchanged"
5647        );
5648
5649        let page = store
5650            .query_events(
5651                EventFilter::default(),
5652                PageRequest {
5653                    limit: 10,
5654                    offset: 0,
5655                },
5656            )
5657            .await
5658            .unwrap();
5659        assert_eq!(
5660            page.items.len(),
5661            1,
5662            "a v1 fallback audit row must still be persisted on dispatch failure"
5663        );
5664        let ev = &page.items[0];
5665        assert_eq!(
5666            ev.payload_schema_version, 1,
5667            "failed link keeps the v1 audit shape"
5668        );
5669        // The persisted outcome must reflect the dispatch result (Err →
5670        // Error), not be hardcoded to Success from the gate's Allow decision.
5671        assert_eq!(
5672            ev.outcome,
5673            EventOutcome::Error,
5674            "outcome reflects the dispatch result (Err), not the gate decision (Allow)"
5675        );
5676        assert!(
5677            ev.duration_us >= 0,
5678            "duration_us must still be populated (measured, not the Event::new \
5679             default sentinel) on a failed dispatch"
5680        );
5681        assert!(
5682            ev.target_id.is_none(),
5683            "non-UUID caller-supplied ids do not spuriously populate target_id"
5684        );
5685        assert!(
5686            ev.payload.get("edge_id").is_none(),
5687            "v1 fallback must not carry edge enrichment fields"
5688        );
5689        let _: khive_gate::AuditEvent = serde_json::from_value(ev.payload.clone())
5690            .expect("v1 fallback payload must deserialize as AuditEvent");
5691    }
5692
5693    #[tokio::test]
5694    async fn link_audit_falls_back_to_v1_when_result_missing_edge_fields() {
5695        let store = Arc::new(MemoryEventStore::default());
5696        let target_arg = uuid::Uuid::new_v4();
5697        let mut builder = VerbRegistryBuilder::new();
5698        builder.register(LinkResultPack::ok(serde_json::json!({"ok": true})));
5699        builder.with_event_store(store.clone());
5700        builder.with_default_namespace("test-ns");
5701        let reg = builder.build().expect("registry builds");
5702
5703        reg.dispatch(
5704            "link",
5705            serde_json::json!({
5706                "source_id": uuid::Uuid::new_v4(),
5707                "target_id": target_arg,
5708                "relation": "depends_on",
5709            }),
5710        )
5711        .await
5712        .unwrap();
5713
5714        let page = store
5715            .query_events(
5716                EventFilter::default(),
5717                PageRequest {
5718                    limit: 10,
5719                    offset: 0,
5720                },
5721            )
5722            .await
5723            .unwrap();
5724        assert_eq!(page.items.len(), 1);
5725        let ev = &page.items[0];
5726        assert_eq!(
5727            ev.payload_schema_version, 1,
5728            "an unparsable success result falls back to v1 rather than dropping the audit row"
5729        );
5730        assert_eq!(ev.outcome, EventOutcome::Success);
5731        assert_eq!(
5732            ev.target_id,
5733            Some(target_arg),
5734            "v1 fallback still extracts target_id from the raw dispatch args"
5735        );
5736        assert!(ev.payload.get("edge_id").is_none());
5737    }
5738
5739    #[tokio::test]
5740    async fn link_audit_bulk_links_get_no_enrichment() {
5741        let store = Arc::new(MemoryEventStore::default());
5742        let mut builder = VerbRegistryBuilder::new();
5743        builder.register(LinkResultPack::ok(serde_json::json!({
5744            "attempted": 2, "created": 2, "skipped": 0, "failed": 0
5745        })));
5746        builder.with_event_store(store.clone());
5747        builder.with_default_namespace("test-ns");
5748        let reg = builder.build().expect("registry builds");
5749
5750        reg.dispatch(
5751            "link",
5752            serde_json::json!({
5753                "links": [
5754                    {"source_id": "a", "target_id": "b", "relation": "depends_on"},
5755                    {"source_id": "c", "target_id": "d", "relation": "depends_on"},
5756                ],
5757            }),
5758        )
5759        .await
5760        .unwrap();
5761
5762        let count = store.count_events(EventFilter::default()).await.unwrap();
5763        assert_eq!(
5764            count, 1,
5765            "bulk `links` gets exactly one v1 audit row (deferred until dispatch \
5766             resolves like every other Allow-outcome row since ADR-103 Stage 1, \
5767             but never v2-enriched — enrichment is singleton-`link`-only)"
5768        );
5769        let page = store
5770            .query_events(
5771                EventFilter::default(),
5772                PageRequest {
5773                    limit: 10,
5774                    offset: 0,
5775                },
5776            )
5777            .await
5778            .unwrap();
5779        let ev = &page.items[0];
5780        assert_eq!(
5781            ev.payload_schema_version, 1,
5782            "bulk link mode is out of scope for #676's events.target_id enrichment"
5783        );
5784        assert!(ev.target_id.is_none());
5785    }
5786
5787    #[test]
5788    fn link_audit_success_from_result_extracts_edge_fields() {
5789        let gate_req = GateRequest::new(
5790            ActorRef::anonymous(),
5791            Namespace::local(),
5792            "link",
5793            serde_json::json!({}),
5794        );
5795        let decision = GateDecision::Allow {
5796            obligations: vec![],
5797        };
5798        let audit = AuditEvent::from_check(&gate_req, &decision, "AllowAllGate");
5799
5800        let edge_id = uuid::Uuid::new_v4();
5801        let source_id = uuid::Uuid::new_v4();
5802        let target_id = uuid::Uuid::new_v4();
5803        let result = serde_json::json!({
5804            "id": edge_id,
5805            "source_id": source_id,
5806            "target_id": target_id,
5807            "relation": "depends_on",
5808            "weight": 0.5,
5809        });
5810
5811        let (returned_id, payload) = link_audit_success_from_result(audit, &result)
5812            .expect("well-formed edge JSON must produce an enriched payload");
5813        assert_eq!(returned_id, edge_id);
5814        assert_eq!(payload["edge_id"], serde_json::json!(edge_id));
5815        assert_eq!(payload["relation"], "depends_on");
5816        assert_eq!(payload["weight"], 0.5);
5817        assert_eq!(
5818            payload["verb"], "link",
5819            "v1 AuditEvent fields must flatten into the v2 payload"
5820        );
5821    }
5822
5823    #[test]
5824    fn link_audit_success_from_result_rejects_incomplete_or_malformed_result() {
5825        let gate_req = GateRequest::new(
5826            ActorRef::anonymous(),
5827            Namespace::local(),
5828            "link",
5829            serde_json::json!({}),
5830        );
5831        let decision = GateDecision::Allow {
5832            obligations: vec![],
5833        };
5834        let audit = AuditEvent::from_check(&gate_req, &decision, "AllowAllGate");
5835
5836        assert!(
5837            link_audit_success_from_result(
5838                audit.clone(),
5839                &serde_json::json!({"id": uuid::Uuid::new_v4()}),
5840            )
5841            .is_none(),
5842            "missing source_id/target_id/relation/weight must not enrich"
5843        );
5844        assert!(
5845            link_audit_success_from_result(audit, &serde_json::json!({"id": "not-a-uuid"}))
5846                .is_none(),
5847            "a non-UUID id must not enrich"
5848        );
5849    }
5850
5851    // ---- khive#948: request_id survives to the persisted audit event ----
5852    //
5853    // The pure `resource_payload`/`base_resource_payload` helpers are unit
5854    // tested in `cost_unit.rs`; these tests prove the id actually reaches
5855    // `resource.request_id` on a persisted `Event` through every one of
5856    // `dispatch_with_identity`'s four audit-append sites (denied, ordinary
5857    // success/error, singleton-link v2 success and its v1 fallback, and the
5858    // unknown-verb error path), plus the "no id supplied" omission case.
5859
5860    async fn first_event(store: &Arc<MemoryEventStore>) -> Event {
5861        let page = store
5862            .query_events(
5863                EventFilter::default(),
5864                PageRequest {
5865                    limit: 10,
5866                    offset: 0,
5867                },
5868            )
5869            .await
5870            .unwrap();
5871        assert_eq!(
5872            page.items.len(),
5873            1,
5874            "expected exactly one persisted audit event"
5875        );
5876        page.items[0].clone()
5877    }
5878
5879    #[tokio::test]
5880    async fn dispatch_with_identity_stamps_request_id_on_success() {
5881        let store = Arc::new(MemoryEventStore::default());
5882        let mut builder = VerbRegistryBuilder::new();
5883        builder.register(AlphaPack);
5884        builder.with_event_store(store.clone());
5885        let reg = builder.build().expect("registry builds");
5886
5887        reg.dispatch_with_identity(
5888            "list",
5889            serde_json::json!({"namespace": "test-ns"}),
5890            Some(RequestIdentity {
5891                request_id: Some(101),
5892                ..Default::default()
5893            }),
5894        )
5895        .await
5896        .unwrap();
5897
5898        let ev = first_event(&store).await;
5899        assert_eq!(ev.outcome, EventOutcome::Success);
5900        assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(101));
5901    }
5902
5903    #[tokio::test]
5904    async fn dispatch_with_identity_stamps_request_id_on_dispatch_error() {
5905        let store = Arc::new(MemoryEventStore::default());
5906        let mut builder = VerbRegistryBuilder::new();
5907        builder.register(FailingProbePack);
5908        builder.with_event_store(store.clone());
5909        let reg = builder.build().expect("registry builds");
5910
5911        let err = reg
5912            .dispatch_with_identity(
5913                "probe",
5914                serde_json::json!({"namespace": "test-ns"}),
5915                Some(RequestIdentity {
5916                    request_id: Some(102),
5917                    ..Default::default()
5918                }),
5919            )
5920            .await
5921            .unwrap_err();
5922        assert!(matches!(err, RuntimeError::InvalidInput(_)));
5923
5924        let ev = first_event(&store).await;
5925        assert_eq!(ev.outcome, EventOutcome::Error);
5926        assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(102));
5927    }
5928
5929    #[tokio::test]
5930    async fn dispatch_with_identity_stamps_request_id_on_denied() {
5931        #[derive(Debug)]
5932        struct AlwaysDenyGate;
5933        impl Gate for AlwaysDenyGate {
5934            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
5935                Ok(GateDecision::deny("denied by test"))
5936            }
5937        }
5938
5939        let store = Arc::new(MemoryEventStore::default());
5940        let mut builder = VerbRegistryBuilder::new();
5941        builder.register(AlphaPack);
5942        builder.with_gate(Arc::new(AlwaysDenyGate));
5943        builder.with_event_store(store.clone());
5944        let reg = builder.build().expect("registry builds");
5945
5946        let err = reg
5947            .dispatch_with_identity(
5948                "list",
5949                serde_json::json!({"namespace": "test-ns"}),
5950                Some(RequestIdentity {
5951                    request_id: Some(103),
5952                    ..Default::default()
5953                }),
5954            )
5955            .await
5956            .unwrap_err();
5957        assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
5958
5959        let ev = first_event(&store).await;
5960        assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(103));
5961    }
5962
5963    #[tokio::test]
5964    async fn dispatch_with_identity_stamps_request_id_on_link_v2_success() {
5965        let store = Arc::new(MemoryEventStore::default());
5966        let edge_id = uuid::Uuid::new_v4();
5967        let source_id = uuid::Uuid::new_v4();
5968        let target_id = uuid::Uuid::new_v4();
5969        let edge_json = serde_json::json!({
5970            "id": edge_id,
5971            "namespace": "local",
5972            "source_id": source_id,
5973            "target_id": target_id,
5974            "relation": "depends_on",
5975            "weight": 1.0,
5976        });
5977        let mut builder = VerbRegistryBuilder::new();
5978        builder.register(LinkResultPack::ok(edge_json));
5979        builder.with_event_store(store.clone());
5980        builder.with_default_namespace("test-ns");
5981        let reg = builder.build().expect("registry builds");
5982
5983        reg.dispatch_with_identity(
5984            "link",
5985            serde_json::json!({
5986                "source_id": source_id,
5987                "target_id": target_id,
5988                "relation": "depends_on",
5989            }),
5990            Some(RequestIdentity {
5991                namespace: "test-ns".to_string(),
5992                request_id: Some(104),
5993                ..Default::default()
5994            }),
5995        )
5996        .await
5997        .unwrap();
5998
5999        let ev = first_event(&store).await;
6000        assert_eq!(
6001            ev.payload_schema_version, 2,
6002            "successful singleton link uses audit schema v2"
6003        );
6004        assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(104));
6005    }
6006
6007    #[tokio::test]
6008    async fn dispatch_with_identity_stamps_request_id_on_link_v1_fallback() {
6009        let store = Arc::new(MemoryEventStore::default());
6010        let mut builder = VerbRegistryBuilder::new();
6011        builder.register(LinkResultPack::err("target endpoint not found"));
6012        builder.with_event_store(store.clone());
6013        builder.with_default_namespace("test-ns");
6014        let reg = builder.build().expect("registry builds");
6015
6016        let err = reg
6017            .dispatch_with_identity(
6018                "link",
6019                serde_json::json!({
6020                    "source_id": "note:alpha",
6021                    "target_id": "note:missing",
6022                    "relation": "depends_on",
6023                }),
6024                Some(RequestIdentity {
6025                    namespace: "test-ns".to_string(),
6026                    request_id: Some(105),
6027                    ..Default::default()
6028                }),
6029            )
6030            .await
6031            .unwrap_err();
6032        assert!(matches!(err, RuntimeError::InvalidInput(_)));
6033
6034        let ev = first_event(&store).await;
6035        assert_eq!(
6036            ev.payload_schema_version, 1,
6037            "failed link keeps the v1 audit shape"
6038        );
6039        assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(105));
6040    }
6041
6042    #[tokio::test]
6043    async fn dispatch_with_identity_stamps_request_id_on_unknown_verb() {
6044        let store = Arc::new(MemoryEventStore::default());
6045        let mut builder = VerbRegistryBuilder::new();
6046        builder.register(AlphaPack);
6047        builder.with_event_store(store.clone());
6048        let reg = builder.build().expect("registry builds");
6049
6050        let err = reg
6051            .dispatch_with_identity(
6052                "no_such_verb",
6053                serde_json::json!({}),
6054                Some(RequestIdentity {
6055                    namespace: Namespace::local().as_str().to_string(),
6056                    request_id: Some(106),
6057                    ..Default::default()
6058                }),
6059            )
6060            .await
6061            .unwrap_err();
6062        assert!(matches!(err, RuntimeError::InvalidInput(_)));
6063
6064        let ev = first_event(&store).await;
6065        assert_eq!(ev.outcome, EventOutcome::Error);
6066        assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(106));
6067    }
6068
6069    #[tokio::test]
6070    async fn dispatch_with_identity_omits_request_id_key_when_absent() {
6071        let store = Arc::new(MemoryEventStore::default());
6072        let mut builder = VerbRegistryBuilder::new();
6073        builder.register(AlphaPack);
6074        builder.with_event_store(store.clone());
6075        let reg = builder.build().expect("registry builds");
6076
6077        // No identity at all — the pre-#948 call shape.
6078        reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
6079            .await
6080            .unwrap();
6081
6082        let ev = first_event(&store).await;
6083        let resource = ev.payload["resource"]
6084            .as_object()
6085            .expect("resource must be an object");
6086        assert!(
6087            !resource.contains_key("request_id"),
6088            "request_id key must be entirely absent when no id is supplied, \
6089             not present as null or 0: got {resource:?}"
6090        );
6091    }
6092}
6093
6094// ---- Inter-pack dependency checking ----
6095
6096#[cfg(test)]
6097mod dep_tests {
6098    use super::*;
6099    use async_trait::async_trait;
6100    use khive_types::Pack;
6101    use serde_json::Value;
6102
6103    struct KgDepPack;
6104    struct MemoryDepPack;
6105    struct ADepPack;
6106    struct BDepPack;
6107
6108    impl Pack for KgDepPack {
6109        const NAME: &'static str = "kg_dep";
6110        const NOTE_KINDS: &'static [&'static str] = &["observation"];
6111        const ENTITY_KINDS: &'static [&'static str] = &["concept"];
6112        const HANDLERS: &'static [HandlerDef] = &[];
6113    }
6114
6115    impl Pack for MemoryDepPack {
6116        const NAME: &'static str = "memory_dep";
6117        const NOTE_KINDS: &'static [&'static str] = &["memory"];
6118        const ENTITY_KINDS: &'static [&'static str] = &[];
6119        const HANDLERS: &'static [HandlerDef] = &[];
6120        const REQUIRES: &'static [&'static str] = &["kg_dep"];
6121    }
6122
6123    impl Pack for ADepPack {
6124        const NAME: &'static str = "pack_a";
6125        const NOTE_KINDS: &'static [&'static str] = &[];
6126        const ENTITY_KINDS: &'static [&'static str] = &[];
6127        const HANDLERS: &'static [HandlerDef] = &[];
6128        const REQUIRES: &'static [&'static str] = &["pack_b"];
6129    }
6130
6131    impl Pack for BDepPack {
6132        const NAME: &'static str = "pack_b";
6133        const NOTE_KINDS: &'static [&'static str] = &[];
6134        const ENTITY_KINDS: &'static [&'static str] = &[];
6135        const HANDLERS: &'static [HandlerDef] = &[];
6136        const REQUIRES: &'static [&'static str] = &["pack_a"];
6137    }
6138
6139    #[async_trait]
6140    impl PackRuntime for KgDepPack {
6141        fn name(&self) -> &str {
6142            Self::NAME
6143        }
6144        fn note_kinds(&self) -> &'static [&'static str] {
6145            Self::NOTE_KINDS
6146        }
6147        fn entity_kinds(&self) -> &'static [&'static str] {
6148            Self::ENTITY_KINDS
6149        }
6150        fn handlers(&self) -> &'static [HandlerDef] {
6151            Self::HANDLERS
6152        }
6153        async fn dispatch(
6154            &self,
6155            verb: &str,
6156            _: Value,
6157            _: &VerbRegistry,
6158            _: &NamespaceToken,
6159        ) -> Result<Value, RuntimeError> {
6160            Err(RuntimeError::InvalidInput(format!(
6161                "KgDepPack has no verbs: {verb}"
6162            )))
6163        }
6164    }
6165
6166    #[async_trait]
6167    impl PackRuntime for MemoryDepPack {
6168        fn name(&self) -> &str {
6169            Self::NAME
6170        }
6171        fn note_kinds(&self) -> &'static [&'static str] {
6172            Self::NOTE_KINDS
6173        }
6174        fn entity_kinds(&self) -> &'static [&'static str] {
6175            Self::ENTITY_KINDS
6176        }
6177        fn handlers(&self) -> &'static [HandlerDef] {
6178            Self::HANDLERS
6179        }
6180        fn requires(&self) -> &'static [&'static str] {
6181            Self::REQUIRES
6182        }
6183        async fn dispatch(
6184            &self,
6185            verb: &str,
6186            _: Value,
6187            _: &VerbRegistry,
6188            _: &NamespaceToken,
6189        ) -> Result<Value, RuntimeError> {
6190            Err(RuntimeError::InvalidInput(format!(
6191                "MemoryDepPack has no verbs: {verb}"
6192            )))
6193        }
6194    }
6195
6196    #[async_trait]
6197    impl PackRuntime for ADepPack {
6198        fn name(&self) -> &str {
6199            Self::NAME
6200        }
6201        fn note_kinds(&self) -> &'static [&'static str] {
6202            Self::NOTE_KINDS
6203        }
6204        fn entity_kinds(&self) -> &'static [&'static str] {
6205            Self::ENTITY_KINDS
6206        }
6207        fn handlers(&self) -> &'static [HandlerDef] {
6208            Self::HANDLERS
6209        }
6210        fn requires(&self) -> &'static [&'static str] {
6211            Self::REQUIRES
6212        }
6213        async fn dispatch(
6214            &self,
6215            verb: &str,
6216            _: Value,
6217            _: &VerbRegistry,
6218            _: &NamespaceToken,
6219        ) -> Result<Value, RuntimeError> {
6220            Err(RuntimeError::InvalidInput(format!(
6221                "ADepPack has no verbs: {verb}"
6222            )))
6223        }
6224    }
6225
6226    #[async_trait]
6227    impl PackRuntime for BDepPack {
6228        fn name(&self) -> &str {
6229            Self::NAME
6230        }
6231        fn note_kinds(&self) -> &'static [&'static str] {
6232            Self::NOTE_KINDS
6233        }
6234        fn entity_kinds(&self) -> &'static [&'static str] {
6235            Self::ENTITY_KINDS
6236        }
6237        fn handlers(&self) -> &'static [HandlerDef] {
6238            Self::HANDLERS
6239        }
6240        fn requires(&self) -> &'static [&'static str] {
6241            Self::REQUIRES
6242        }
6243        async fn dispatch(
6244            &self,
6245            verb: &str,
6246            _: Value,
6247            _: &VerbRegistry,
6248            _: &NamespaceToken,
6249        ) -> Result<Value, RuntimeError> {
6250            Err(RuntimeError::InvalidInput(format!(
6251                "BDepPack has no verbs: {verb}"
6252            )))
6253        }
6254    }
6255
6256    #[test]
6257    fn test_pack_deps_happy_path() {
6258        let mut builder = VerbRegistryBuilder::new();
6259        builder.register(MemoryDepPack);
6260        builder.register(KgDepPack);
6261        let reg = builder
6262            .build()
6263            .expect("kg_dep satisfies memory_dep dependency");
6264        assert_eq!(reg.pack_requires("memory_dep").unwrap(), &["kg_dep"]);
6265        let names = reg.pack_names();
6266        let kg_pos = names.iter().position(|&n| n == "kg_dep").unwrap();
6267        let mem_pos = names.iter().position(|&n| n == "memory_dep").unwrap();
6268        assert!(
6269            kg_pos < mem_pos,
6270            "kg_dep must be loaded before memory_dep; order: {names:?}"
6271        );
6272    }
6273
6274    #[test]
6275    fn test_pack_deps_missing() {
6276        let mut builder = VerbRegistryBuilder::new();
6277        builder.register(MemoryDepPack);
6278        let err = match builder.build() {
6279            Ok(_) => panic!("expected Err, got Ok"),
6280            Err(e) => e,
6281        };
6282        assert!(
6283            matches!(err, RuntimeError::MissingPackDependency(_)),
6284            "expected MissingPackDependency, got {err:?}"
6285        );
6286        let msg = err.to_string();
6287        assert!(
6288            msg.contains("memory_dep"),
6289            "error must name the dependent pack: {msg}"
6290        );
6291        assert!(
6292            msg.contains("kg_dep"),
6293            "error must name the missing dep: {msg}"
6294        );
6295    }
6296
6297    #[test]
6298    fn test_pack_deps_circular() {
6299        let mut builder = VerbRegistryBuilder::new();
6300        builder.register(ADepPack);
6301        builder.register(BDepPack);
6302        let err = match builder.build() {
6303            Ok(_) => panic!("expected Err, got Ok"),
6304            Err(e) => e,
6305        };
6306        assert!(
6307            matches!(err, RuntimeError::CircularPackDependency(_)),
6308            "expected CircularPackDependency, got {err:?}"
6309        );
6310        let msg = err.to_string();
6311        assert!(msg.contains("pack_a"), "error must name pack_a: {msg}");
6312        assert!(msg.contains("pack_b"), "error must name pack_b: {msg}");
6313    }
6314
6315    #[test]
6316    fn test_pack_deps_no_deps() {
6317        struct NoDepsA;
6318        struct NoDepsB;
6319
6320        impl Pack for NoDepsA {
6321            const NAME: &'static str = "no_deps_a";
6322            const NOTE_KINDS: &'static [&'static str] = &[];
6323            const ENTITY_KINDS: &'static [&'static str] = &[];
6324            const HANDLERS: &'static [HandlerDef] = &[];
6325        }
6326
6327        impl Pack for NoDepsB {
6328            const NAME: &'static str = "no_deps_b";
6329            const NOTE_KINDS: &'static [&'static str] = &[];
6330            const ENTITY_KINDS: &'static [&'static str] = &[];
6331            const HANDLERS: &'static [HandlerDef] = &[];
6332        }
6333
6334        #[async_trait]
6335        impl PackRuntime for NoDepsA {
6336            fn name(&self) -> &str {
6337                Self::NAME
6338            }
6339            fn note_kinds(&self) -> &'static [&'static str] {
6340                Self::NOTE_KINDS
6341            }
6342            fn entity_kinds(&self) -> &'static [&'static str] {
6343                Self::ENTITY_KINDS
6344            }
6345            fn handlers(&self) -> &'static [HandlerDef] {
6346                Self::HANDLERS
6347            }
6348            async fn dispatch(
6349                &self,
6350                verb: &str,
6351                _: Value,
6352                _: &VerbRegistry,
6353                _: &NamespaceToken,
6354            ) -> Result<Value, RuntimeError> {
6355                Err(RuntimeError::InvalidInput(format!("NoDepsA: {verb}")))
6356            }
6357        }
6358
6359        #[async_trait]
6360        impl PackRuntime for NoDepsB {
6361            fn name(&self) -> &str {
6362                Self::NAME
6363            }
6364            fn note_kinds(&self) -> &'static [&'static str] {
6365                Self::NOTE_KINDS
6366            }
6367            fn entity_kinds(&self) -> &'static [&'static str] {
6368                Self::ENTITY_KINDS
6369            }
6370            fn handlers(&self) -> &'static [HandlerDef] {
6371                Self::HANDLERS
6372            }
6373            async fn dispatch(
6374                &self,
6375                verb: &str,
6376                _: Value,
6377                _: &VerbRegistry,
6378                _: &NamespaceToken,
6379            ) -> Result<Value, RuntimeError> {
6380                Err(RuntimeError::InvalidInput(format!("NoDepsB: {verb}")))
6381            }
6382        }
6383
6384        let mut builder = VerbRegistryBuilder::new();
6385        builder.register(NoDepsA);
6386        builder.register(NoDepsB);
6387        let reg = builder.build().expect("packs with REQUIRES=&[] build");
6388        assert_eq!(reg.pack_requires("no_deps_a").unwrap(), &[] as &[&str]);
6389        assert_eq!(reg.pack_requires("no_deps_b").unwrap(), &[] as &[&str]);
6390    }
6391}
6392
6393// ── Dispatch hook tests ─────────────────────────────────────────
6394
6395#[cfg(test)]
6396mod hook_tests {
6397    use super::*;
6398    use async_trait::async_trait;
6399    use khive_types::Pack;
6400    use std::sync::atomic::{AtomicUsize, Ordering};
6401    use std::sync::Mutex as StdMutex;
6402
6403    struct SimplePack;
6404
6405    impl Pack for SimplePack {
6406        const NAME: &'static str = "simple";
6407        const NOTE_KINDS: &'static [&'static str] = &[];
6408        const ENTITY_KINDS: &'static [&'static str] = &[];
6409        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
6410            name: "ping",
6411            description: "ping",
6412            visibility: Visibility::Verb,
6413            category: VerbCategory::Assertive,
6414            params: &[],
6415        }];
6416    }
6417
6418    #[async_trait]
6419    impl PackRuntime for SimplePack {
6420        fn name(&self) -> &str {
6421            SimplePack::NAME
6422        }
6423        fn note_kinds(&self) -> &'static [&'static str] {
6424            SimplePack::NOTE_KINDS
6425        }
6426        fn entity_kinds(&self) -> &'static [&'static str] {
6427            SimplePack::ENTITY_KINDS
6428        }
6429        fn handlers(&self) -> &'static [HandlerDef] {
6430            SimplePack::HANDLERS
6431        }
6432        async fn dispatch(
6433            &self,
6434            verb: &str,
6435            _params: Value,
6436            _registry: &VerbRegistry,
6437            _token: &NamespaceToken,
6438        ) -> Result<Value, RuntimeError> {
6439            Ok(serde_json::json!({ "verb": verb }))
6440        }
6441    }
6442
6443    struct RecallPack;
6444
6445    impl Pack for RecallPack {
6446        const NAME: &'static str = "memory";
6447        const NOTE_KINDS: &'static [&'static str] = &[];
6448        const ENTITY_KINDS: &'static [&'static str] = &[];
6449        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
6450            name: "memory.recall",
6451            description: "test recall",
6452            visibility: Visibility::Verb,
6453            category: VerbCategory::Assertive,
6454            params: &[],
6455        }];
6456    }
6457
6458    #[async_trait]
6459    impl PackRuntime for RecallPack {
6460        fn name(&self) -> &str {
6461            RecallPack::NAME
6462        }
6463        fn note_kinds(&self) -> &'static [&'static str] {
6464            RecallPack::NOTE_KINDS
6465        }
6466        fn entity_kinds(&self) -> &'static [&'static str] {
6467            RecallPack::ENTITY_KINDS
6468        }
6469        fn handlers(&self) -> &'static [HandlerDef] {
6470            RecallPack::HANDLERS
6471        }
6472        async fn dispatch(
6473            &self,
6474            _verb: &str,
6475            params: Value,
6476            _registry: &VerbRegistry,
6477            _token: &NamespaceToken,
6478        ) -> Result<Value, RuntimeError> {
6479            let hit = serde_json::json!({
6480                "id": uuid::Uuid::new_v4().to_string(),
6481                "served_by_profile_id": "custom-recall-v1",
6482                "serve_attribution": "profile",
6483            });
6484            if params.get("verbose").and_then(Value::as_bool) == Some(true) {
6485                Ok(serde_json::json!({"results": [hit]}))
6486            } else {
6487                Ok(serde_json::json!([hit]))
6488            }
6489        }
6490    }
6491
6492    #[derive(Default)]
6493    struct EventCapturingHook {
6494        event: StdMutex<Option<Event>>,
6495    }
6496
6497    #[async_trait]
6498    impl DispatchHook for EventCapturingHook {
6499        async fn on_dispatch(&self, view: &EventView) {
6500            *self.event.lock().unwrap() = Some(view.event.clone());
6501        }
6502    }
6503
6504    /// Hook that counts calls and records the last verb seen.
6505    #[derive(Default)]
6506    struct CountingHook {
6507        calls: AtomicUsize,
6508        last_verb: StdMutex<String>,
6509    }
6510
6511    #[async_trait]
6512    impl DispatchHook for CountingHook {
6513        async fn on_dispatch(&self, view: &EventView) {
6514            self.calls.fetch_add(1, Ordering::SeqCst);
6515            *self.last_verb.lock().unwrap() = view.event.verb.clone();
6516        }
6517    }
6518
6519    #[tokio::test]
6520    async fn dispatch_hook_fires_on_successful_dispatch() {
6521        let hook = Arc::new(CountingHook::default());
6522        let mut builder = VerbRegistryBuilder::new();
6523        builder.register(SimplePack);
6524        builder.with_dispatch_hook(hook.clone());
6525        let reg = builder.build().expect("registry builds");
6526
6527        reg.dispatch("ping", Value::Null).await.unwrap();
6528
6529        assert_eq!(
6530            hook.calls.load(Ordering::SeqCst),
6531            1,
6532            "hook must fire once per successful dispatch"
6533        );
6534        assert_eq!(
6535            hook.last_verb.lock().unwrap().as_str(),
6536            "ping",
6537            "hook event must carry the dispatched verb"
6538        );
6539    }
6540
6541    #[tokio::test]
6542    async fn dispatch_hook_fires_multiple_times() {
6543        let hook = Arc::new(CountingHook::default());
6544        let mut builder = VerbRegistryBuilder::new();
6545        builder.register(SimplePack);
6546        builder.with_dispatch_hook(hook.clone());
6547        let reg = builder.build().expect("registry builds");
6548
6549        reg.dispatch("ping", Value::Null).await.unwrap();
6550        reg.dispatch("ping", Value::Null).await.unwrap();
6551        reg.dispatch("ping", Value::Null).await.unwrap();
6552
6553        assert_eq!(
6554            hook.calls.load(Ordering::SeqCst),
6555            3,
6556            "hook must fire once per successful dispatch"
6557        );
6558    }
6559
6560    #[tokio::test]
6561    async fn recall_hook_copies_serve_attribution_from_bare_and_verbose_results() {
6562        let hook = Arc::new(EventCapturingHook::default());
6563        let mut builder = VerbRegistryBuilder::new();
6564        builder.register(RecallPack);
6565        builder.with_dispatch_hook(hook.clone());
6566        let reg = builder.build().expect("registry builds");
6567
6568        for params in [serde_json::json!({}), serde_json::json!({"verbose": true})] {
6569            reg.dispatch("memory.recall", params)
6570                .await
6571                .expect("recall dispatch");
6572            let event = hook.event.lock().unwrap().clone().expect("hook event");
6573            assert!(
6574                event.target_id.is_some(),
6575                "first recall id must become target"
6576            );
6577            assert_eq!(
6578                event.payload["served_by_profile_id"],
6579                serde_json::json!("custom-recall-v1")
6580            );
6581            assert_eq!(
6582                event.payload["serve_attribution"],
6583                serde_json::json!("profile")
6584            );
6585        }
6586    }
6587
6588    #[tokio::test]
6589    async fn dispatch_hook_does_not_fire_on_unknown_verb() {
6590        let hook = Arc::new(CountingHook::default());
6591        let mut builder = VerbRegistryBuilder::new();
6592        builder.register(SimplePack);
6593        builder.with_dispatch_hook(hook.clone());
6594        let reg = builder.build().expect("registry builds");
6595
6596        let _ = reg.dispatch("nonexistent", Value::Null).await;
6597
6598        assert_eq!(
6599            hook.calls.load(Ordering::SeqCst),
6600            0,
6601            "hook must NOT fire for unknown verb (dispatch returns error)"
6602        );
6603    }
6604
6605    #[tokio::test]
6606    async fn dispatch_hook_does_not_fire_on_gate_deny() {
6607        use khive_gate::{Gate, GateDecision, GateError};
6608
6609        #[derive(Debug)]
6610        struct AlwaysDenyGate;
6611        impl Gate for AlwaysDenyGate {
6612            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
6613                Ok(GateDecision::deny("test deny"))
6614            }
6615        }
6616
6617        let hook = Arc::new(CountingHook::default());
6618        let mut builder = VerbRegistryBuilder::new();
6619        builder.register(SimplePack);
6620        builder.with_gate(Arc::new(AlwaysDenyGate));
6621        builder.with_dispatch_hook(hook.clone());
6622        let reg = builder.build().expect("registry builds");
6623
6624        let err = reg.dispatch("ping", Value::Null).await.unwrap_err();
6625        assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
6626
6627        assert_eq!(
6628            hook.calls.load(Ordering::SeqCst),
6629            0,
6630            "hook must NOT fire when gate denies dispatch"
6631        );
6632    }
6633
6634    #[tokio::test]
6635    async fn dispatch_hook_event_carries_namespace_from_params() {
6636        let hook = Arc::new(CountingHook::default());
6637
6638        #[derive(Default)]
6639        struct NsCapturingHook {
6640            ns: StdMutex<String>,
6641        }
6642
6643        #[async_trait]
6644        impl DispatchHook for NsCapturingHook {
6645            async fn on_dispatch(&self, view: &EventView) {
6646                *self.ns.lock().unwrap() = view.event.namespace.clone();
6647            }
6648        }
6649
6650        let ns_hook = Arc::new(NsCapturingHook::default());
6651        let mut builder = VerbRegistryBuilder::new();
6652        builder.register(SimplePack);
6653        builder.with_dispatch_hook(ns_hook.clone());
6654        let reg = builder.build().expect("registry builds");
6655
6656        reg.dispatch("ping", serde_json::json!({"namespace": "tenant-abc"}))
6657            .await
6658            .unwrap();
6659
6660        assert_eq!(
6661            ns_hook.ns.lock().unwrap().as_str(),
6662            "tenant-abc",
6663            "dispatch hook event must carry the resolved namespace"
6664        );
6665
6666        // Suppress unused-variable warning from the outer hook.
6667        drop(hook);
6668    }
6669
6670    #[tokio::test]
6671    async fn no_dispatch_hook_configured_dispatch_succeeds() {
6672        // Regression: registries without a hook must still work.
6673        let mut builder = VerbRegistryBuilder::new();
6674        builder.register(SimplePack);
6675        // No with_dispatch_hook call.
6676        let reg = builder.build().expect("registry builds");
6677
6678        let res = reg.dispatch("ping", Value::Null).await.unwrap();
6679        assert_eq!(res["verb"], "ping");
6680    }
6681}
6682
6683// ── help=true tests ──────────────────────────────────────────────
6684
6685#[cfg(test)]
6686mod help_tests {
6687    use super::*;
6688    use async_trait::async_trait;
6689    use khive_types::Pack;
6690    use std::sync::{
6691        atomic::{AtomicUsize, Ordering},
6692        Arc,
6693    };
6694
6695    // ── HelpPack: a minimal pack with one handler that records invocation count.
6696    //
6697    // Used to verify that help=true never reaches the pack's dispatch method.
6698
6699    static CREATE_PARAMS: [ParamDef; 2] = [
6700        ParamDef {
6701            name: "kind",
6702            param_type: "string",
6703            required: true,
6704            description: "Granular kind (concept | document | ...).",
6705        },
6706        ParamDef {
6707            name: "name",
6708            param_type: "string",
6709            required: false,
6710            description: "Human-readable name.",
6711        },
6712    ];
6713
6714    static RECALL_PARAMS: [ParamDef; 2] = [
6715        ParamDef {
6716            name: "query",
6717            param_type: "string",
6718            required: true,
6719            description: "Semantic recall query.",
6720        },
6721        ParamDef {
6722            name: "limit",
6723            param_type: "integer",
6724            required: false,
6725            description: "Maximum memories to return.",
6726        },
6727    ];
6728
6729    // A subhandler with no params — mirrors recall.embed / brain.emit / etc.
6730    // Used to test that help=true on a Subhandler returns callable_via_mcp: false.
6731    static EMBED_PARAMS: [ParamDef; 0] = [];
6732
6733    struct HelpPack {
6734        invocations: Arc<AtomicUsize>,
6735    }
6736
6737    impl Pack for HelpPack {
6738        const NAME: &'static str = "helptest";
6739        const NOTE_KINDS: &'static [&'static str] = &[];
6740        const ENTITY_KINDS: &'static [&'static str] = &[];
6741        const HANDLERS: &'static [HandlerDef] = &[
6742            HandlerDef {
6743                name: "create",
6744                description: "Create an entity or note",
6745                visibility: Visibility::Verb,
6746                category: VerbCategory::Commissive,
6747                params: &CREATE_PARAMS,
6748            },
6749            HandlerDef {
6750                name: "recall",
6751                description: "Recall memory notes with decay-aware hybrid ranking",
6752                visibility: Visibility::Verb,
6753                category: VerbCategory::Assertive,
6754                params: &RECALL_PARAMS,
6755            },
6756            // A Subhandler used to test that help=true returns
6757            // callable_via_mcp: false for internal verbs.
6758            HandlerDef {
6759                name: "recall.embed",
6760                description: "Return the embedding vector used by memory recall",
6761                visibility: Visibility::Subhandler,
6762                category: VerbCategory::Assertive,
6763                params: &EMBED_PARAMS,
6764            },
6765            HandlerDef {
6766                name: "link",
6767                description: "Create a typed directed edge",
6768                visibility: Visibility::Verb,
6769                category: VerbCategory::Commissive,
6770                params: &[],
6771            },
6772        ];
6773    }
6774
6775    // A pack-declared additive edge rule (mirrors the GTD pack's real
6776    // task-to-task `depends_on` rule), used to verify `link(help=true)`
6777    // surfaces pack-composed rules alongside the base entity table. The
6778    // second entry declares a rule for a special relation
6779    // (`supersedes`) that the validator's dedicated special-relation
6780    // branch never consults `pack_rule_allows` for — it must NOT be
6781    // advertised (see `test_link_help_true_matches_special_relation_validator_set`).
6782    static HELP_EDGE_RULES: [EdgeEndpointRule; 2] = [
6783        EdgeEndpointRule {
6784            relation: khive_types::EdgeRelation::DependsOn,
6785            source: EndpointKind::NoteOfKind("task"),
6786            target: EndpointKind::NoteOfKind("task"),
6787        },
6788        EdgeEndpointRule {
6789            relation: khive_types::EdgeRelation::Supersedes,
6790            source: EndpointKind::NoteOfKind("task"),
6791            target: EndpointKind::NoteOfKind("task"),
6792        },
6793    ];
6794
6795    #[async_trait]
6796    impl PackRuntime for HelpPack {
6797        fn name(&self) -> &str {
6798            HelpPack::NAME
6799        }
6800        fn note_kinds(&self) -> &'static [&'static str] {
6801            HelpPack::NOTE_KINDS
6802        }
6803        fn entity_kinds(&self) -> &'static [&'static str] {
6804            HelpPack::ENTITY_KINDS
6805        }
6806        fn handlers(&self) -> &'static [HandlerDef] {
6807            HelpPack::HANDLERS
6808        }
6809        fn edge_rules(&self) -> &'static [EdgeEndpointRule] {
6810            &HELP_EDGE_RULES
6811        }
6812        async fn dispatch(
6813            &self,
6814            verb: &str,
6815            _params: Value,
6816            _registry: &VerbRegistry,
6817            _token: &NamespaceToken,
6818        ) -> Result<Value, RuntimeError> {
6819            self.invocations.fetch_add(1, Ordering::SeqCst);
6820            Ok(serde_json::json!({ "pack": "helptest", "verb": verb }))
6821        }
6822    }
6823
6824    fn build_help_registry(invocations: Arc<AtomicUsize>) -> VerbRegistry {
6825        let mut builder = VerbRegistryBuilder::new();
6826        builder.register(HelpPack { invocations });
6827        builder.build().expect("help registry builds")
6828    }
6829
6830    /// help=true on `create` returns a schema envelope with the correct verb name,
6831    /// pack name, description, and at least the required `kind` parameter.
6832    #[tokio::test]
6833    async fn test_help_true_returns_schema_for_kg_create() {
6834        let invocations = Arc::new(AtomicUsize::new(0));
6835        let reg = build_help_registry(invocations.clone());
6836
6837        let result = reg
6838            .dispatch("create", serde_json::json!({ "help": true }))
6839            .await
6840            .expect("help=true must succeed for a known verb");
6841
6842        // Shape checks.
6843        assert_eq!(result["verb"], "create", "envelope must name the verb");
6844        assert_eq!(
6845            result["pack"], "helptest",
6846            "envelope must name the owning pack"
6847        );
6848        assert!(
6849            result["description"].as_str().is_some(),
6850            "description must be a string"
6851        );
6852
6853        // Params array must be present and non-empty.
6854        let params = result["params"]
6855            .as_array()
6856            .expect("params must be a JSON array");
6857        assert!(!params.is_empty(), "params array must not be empty");
6858
6859        // The required `kind` param must appear.
6860        let kind_param = params.iter().find(|p| p["name"] == "kind");
6861        assert!(
6862            kind_param.is_some(),
6863            "params array must include the 'kind' parameter"
6864        );
6865        let kind_param = kind_param.unwrap();
6866        assert_eq!(
6867            kind_param["required"],
6868            serde_json::json!(true),
6869            "'kind' must be required"
6870        );
6871        assert_eq!(kind_param["type"], "string", "'kind' type must be 'string'");
6872    }
6873
6874    /// help=true on `recall` returns a schema envelope including the `query` param.
6875    #[tokio::test]
6876    async fn test_help_true_returns_schema_for_recall() {
6877        let invocations = Arc::new(AtomicUsize::new(0));
6878        let reg = build_help_registry(invocations.clone());
6879
6880        let result = reg
6881            .dispatch("recall", serde_json::json!({ "help": true }))
6882            .await
6883            .expect("help=true must succeed for recall");
6884
6885        assert_eq!(result["verb"], "recall");
6886        assert_eq!(result["pack"], "helptest");
6887
6888        let params = result["params"]
6889            .as_array()
6890            .expect("params must be a JSON array");
6891
6892        // `query` must be present and required.
6893        let query_param = params.iter().find(|p| p["name"] == "query");
6894        assert!(query_param.is_some(), "params must include 'query'");
6895        let query_param = query_param.unwrap();
6896        assert_eq!(
6897            query_param["required"],
6898            serde_json::json!(true),
6899            "'query' must be required"
6900        );
6901
6902        // `limit` must be present and optional.
6903        let limit_param = params.iter().find(|p| p["name"] == "limit");
6904        assert!(limit_param.is_some(), "params must include 'limit'");
6905        let limit_param = limit_param.unwrap();
6906        assert_eq!(
6907            limit_param["required"],
6908            serde_json::json!(false),
6909            "'limit' must be optional"
6910        );
6911    }
6912
6913    /// `link(help=true)` (issue #964) surfaces the composed per-relation
6914    /// endpoint allowlist: the base entity-to-entity table, every loaded
6915    /// pack's additive `EDGE_RULES`, and the `annotates` note-to-any rule —
6916    /// so a batch caller can defer to the kernel's own table instead of
6917    /// re-implementing it.
6918    #[tokio::test]
6919    async fn test_link_help_true_exposes_endpoint_rules() {
6920        let invocations = Arc::new(AtomicUsize::new(0));
6921        let reg = build_help_registry(invocations.clone());
6922
6923        let result = reg
6924            .dispatch("link", serde_json::json!({ "help": true }))
6925            .await
6926            .expect("help=true must succeed for link");
6927
6928        assert_eq!(result["verb"], "link");
6929        let rules = result["endpoint_rules"]
6930            .as_array()
6931            .expect("link help must include an endpoint_rules array");
6932        assert!(!rules.is_empty(), "endpoint_rules must not be empty");
6933
6934        // A base entity-to-entity rule (khive-runtime's own table) must appear.
6935        assert!(
6936            rules.iter().any(|r| r["relation"] == "contains"
6937                && r["source"] == "entity:concept"
6938                && r["target"] == "entity:concept"),
6939            "endpoint_rules must include the base 'contains' entity rule; got {rules:#?}"
6940        );
6941
6942        // The pack-declared additive rule (HelpPack's task->task depends_on) must appear.
6943        assert!(
6944            rules.iter().any(|r| r["relation"] == "depends_on"
6945                && r["source"] == "note:task"
6946                && r["target"] == "note:task"),
6947            "endpoint_rules must include the pack-declared depends_on rule; got {rules:#?}"
6948        );
6949
6950        // The annotates note-to-any special case must appear.
6951        assert!(
6952            rules
6953                .iter()
6954                .any(|r| r["relation"] == "annotates" && r["source"] == "note:*"),
6955            "endpoint_rules must document the annotates note-to-any rule; got {rules:#?}"
6956        );
6957
6958        // help=true must remain side-effect-free.
6959        assert_eq!(
6960            invocations.load(Ordering::SeqCst),
6961            0,
6962            "link(help=true) must not invoke pack dispatch"
6963        );
6964    }
6965
6966    /// `link(help=true)`'s `endpoint_rules` must match, set-for-set, every
6967    /// endpoint pair `validate_edge_relation_endpoints`
6968    /// (`crates/khive-runtime/src/operations.rs`) actually accepts for the
6969    /// three special relations (`supersedes` / `supports` / `refutes`):
6970    ///
6971    /// - a `note -> note` row for each of the three relations (the
6972    ///   validator's dedicated special-relation branch accepts any
6973    ///   `Resolved::Note(_), Resolved::Note(_)` pair unconditionally,
6974    ///   `operations.rs:1338` / `:1527` — before `pack_rule_allows` is ever
6975    ///   reached);
6976    /// - the base entity->entity rows for the three relations
6977    ///   (`base_entity_endpoint_rules`, e.g. `concept -[supersedes]-> concept`);
6978    /// - and, critically, NOT a row for `HelpPack`'s pack-declared
6979    ///   `supersedes` rule on `note:task -> note:task`
6980    ///   (`HELP_EDGE_RULES[1]`) — because the validator's special-relation
6981    ///   branch returns before `pack_rule_allows` is consulted, that pack
6982    ///   rule is never actually enforced, so advertising it would be a false
6983    ///   promise (the exact defect this test guards against, issue #991).
6984    #[tokio::test]
6985    async fn test_link_help_true_matches_special_relation_validator_set() {
6986        let invocations = Arc::new(AtomicUsize::new(0));
6987        let reg = build_help_registry(invocations.clone());
6988
6989        let result = reg
6990            .dispatch("link", serde_json::json!({ "help": true }))
6991            .await
6992            .expect("help=true must succeed for link");
6993
6994        let rules = result["endpoint_rules"]
6995            .as_array()
6996            .expect("link help must include an endpoint_rules array");
6997
6998        for relation in ["supersedes", "supports", "refutes"] {
6999            // The unconditional note -> note row must appear.
7000            assert!(
7001                rules.iter().any(|r| r["relation"] == relation
7002                    && r["source"] == "note:*"
7003                    && r["target"] == "note:*"),
7004                "endpoint_rules must include the note:*->note:* row for '{relation}' \
7005                 (validator accepts any note->note pair unconditionally); got {rules:#?}"
7006            );
7007
7008            // HelpPack's pack-declared rule for this relation on note:task->note:task
7009            // (only Supersedes is declared in HELP_EDGE_RULES) must NOT be advertised
7010            // as a distinct entity — the validator never reaches pack_rule_allows for
7011            // special relations, so no note:task->note:task row should exist for it.
7012            assert!(
7013                !rules.iter().any(|r| r["relation"] == relation
7014                    && r["source"] == "note:task"
7015                    && r["target"] == "note:task"),
7016                "endpoint_rules must NOT advertise a pack EDGE_RULES row for special \
7017                 relation '{relation}' — validate_edge_relation_endpoints never consults \
7018                 pack_rule_allows for supersedes/supports/refutes; got {rules:#?}"
7019            );
7020        }
7021
7022        // Base entity->entity rows for the three relations (from
7023        // base_entity_endpoint_rules) must still appear alongside the note rows.
7024        for (relation, kind) in [
7025            ("supersedes", "concept"),
7026            ("supports", "concept"),
7027            ("refutes", "concept"),
7028        ] {
7029            assert!(
7030                rules.iter().any(|r| r["relation"] == relation
7031                    && r["source"] == format!("entity:{kind}")
7032                    && r["target"] == "entity:concept"),
7033                "endpoint_rules must include the base entity:{kind}->entity:concept row \
7034                 for '{relation}'; got {rules:#?}"
7035            );
7036        }
7037    }
7038
7039    #[test]
7040    fn special_relation_predicate_matches_the_dedicated_validator_set() {
7041        for relation in khive_types::EdgeRelation::ALL {
7042            assert_eq!(
7043                is_special_relation(relation),
7044                matches!(
7045                    relation,
7046                    khive_types::EdgeRelation::Supersedes
7047                        | khive_types::EdgeRelation::Supports
7048                        | khive_types::EdgeRelation::Refutes
7049                ),
7050                "unexpected special-relation classification for {relation}"
7051            );
7052        }
7053    }
7054
7055    /// help=true is intercepted before pack dispatch — the pack's dispatch method
7056    /// must never be invoked when help=true is in the params.
7057    #[tokio::test]
7058    async fn test_help_true_does_not_execute_the_verb() {
7059        let invocations = Arc::new(AtomicUsize::new(0));
7060        let reg = build_help_registry(invocations.clone());
7061
7062        // Call both verbs with help=true.
7063        reg.dispatch("create", serde_json::json!({ "help": true }))
7064            .await
7065            .expect("help=true must succeed");
7066        reg.dispatch("recall", serde_json::json!({ "help": true }))
7067            .await
7068            .expect("help=true must succeed");
7069
7070        assert_eq!(
7071            invocations.load(Ordering::SeqCst),
7072            0,
7073            "pack dispatch MUST NOT be invoked when help=true; \
7074             got {} invocation(s)",
7075            invocations.load(Ordering::SeqCst)
7076        );
7077
7078        // Confirm that a normal call (without help=true) DOES invoke dispatch.
7079        reg.dispatch("create", serde_json::json!({}))
7080            .await
7081            .expect("normal dispatch must succeed");
7082        assert_eq!(
7083            invocations.load(Ordering::SeqCst),
7084            1,
7085            "pack dispatch must fire exactly once for a normal call"
7086        );
7087    }
7088
7089    // ── Subhandler help-schema regressions ─────────────────────────────────
7090    //
7091    // Subhandler verbs must return `callable_via_mcp: false` in their help
7092    // schema so agents who read help=true before probing see accurate
7093    // availability — not a "looks callable" schema followed by permission denied.
7094
7095    /// help=true on a `Visibility::Subhandler` verb returns `callable_via_mcp: false`
7096    /// and `visibility: "internal"` rather than a plain callable-looking envelope.
7097    #[tokio::test]
7098    async fn help_true_on_subhandler_returns_callable_via_mcp_false() {
7099        let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
7100
7101        let result = reg
7102            .dispatch("recall.embed", serde_json::json!({ "help": true }))
7103            .await
7104            .expect("help=true on subhandler must succeed (no permission check on help path)");
7105
7106        assert_eq!(
7107            result["callable_via_mcp"],
7108            serde_json::json!(false),
7109            "subhandler help must carry callable_via_mcp: false"
7110        );
7111        assert_eq!(
7112            result["visibility"], "internal",
7113            "subhandler help must carry visibility: internal"
7114        );
7115        // The verb and pack fields must still be present so the caller knows
7116        // what the schema belongs to.
7117        assert_eq!(result["verb"], "recall.embed");
7118        assert_eq!(result["pack"], "helptest");
7119    }
7120
7121    /// Public Verb-visibility handlers must NOT have `callable_via_mcp: false`.
7122    #[tokio::test]
7123    async fn help_true_on_public_verb_does_not_have_callable_via_mcp_false() {
7124        let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
7125
7126        let result = reg
7127            .dispatch("create", serde_json::json!({ "help": true }))
7128            .await
7129            .expect("help=true on public verb must succeed");
7130
7131        // callable_via_mcp must be absent or true for public verbs.
7132        assert_ne!(
7133            result.get("callable_via_mcp"),
7134            Some(&serde_json::json!(false)),
7135            "public verb help must NOT carry callable_via_mcp: false"
7136        );
7137        // visibility must be absent or 'public' (never 'internal') for public verbs.
7138        assert_ne!(
7139            result.get("visibility"),
7140            Some(&serde_json::json!("internal")),
7141            "public verb help must NOT carry visibility: internal"
7142        );
7143    }
7144
7145    /// help=true on an unknown verb returns an error (same behavior as normal dispatch).
7146    #[tokio::test]
7147    async fn help_true_on_unknown_verb_returns_error() {
7148        let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
7149
7150        let err = reg
7151            .dispatch("nonexistent_verb", serde_json::json!({ "help": true }))
7152            .await
7153            .unwrap_err();
7154
7155        assert!(
7156            matches!(err, RuntimeError::InvalidInput(_)),
7157            "help=true on unknown verb must return InvalidInput, got {err:?}"
7158        );
7159        let msg = err.to_string();
7160        assert!(
7161            msg.contains("nonexistent_verb"),
7162            "error must name the unknown verb: {msg}"
7163        );
7164    }
7165
7166    /// Subhandler help must include params: [] even when the verb has no params.
7167    #[tokio::test]
7168    async fn help_true_on_subhandler_includes_params_field() {
7169        let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
7170
7171        let result = reg
7172            .dispatch("recall.embed", serde_json::json!({ "help": true }))
7173            .await
7174            .expect("help=true on subhandler must succeed");
7175
7176        // params must always be present (consistent shape).
7177        let params = result
7178            .get("params")
7179            .expect("subhandler help must include 'params' field");
7180        assert!(
7181            params.is_array(),
7182            "subhandler help params must be a JSON array"
7183        );
7184    }
7185
7186    // ── Unknown-verb error must not leak subhandler names ─────────
7187
7188    /// `describe_verb` on an unknown verb must list only Verb-visibility names
7189    /// in the "available" list: never subhandler names like `recall.embed`.
7190    #[tokio::test]
7191    async fn help_true_unknown_verb_available_list_excludes_subhandlers() {
7192        let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
7193
7194        let err = reg
7195            .dispatch("not_a_verb", serde_json::json!({ "help": true }))
7196            .await
7197            .unwrap_err();
7198
7199        let msg = err.to_string();
7200        // `recall.embed` is a Subhandler in HelpPack — must NOT appear in the
7201        // "available" list of an unknown-verb error.
7202        assert!(
7203            !msg.contains("recall.embed"),
7204            "unknown-verb help error must not advertise subhandler recall.embed: {msg}"
7205        );
7206        // Public verbs must still appear so the agent knows what to call.
7207        assert!(
7208            msg.contains("create"),
7209            "unknown-verb help error must still list public verb 'create': {msg}"
7210        );
7211        assert!(
7212            msg.contains("recall"),
7213            "unknown-verb help error must still list public verb 'recall': {msg}"
7214        );
7215    }
7216
7217    /// Normal dispatch on an unknown verb must also not leak subhandler names.
7218    #[tokio::test]
7219    async fn dispatch_unknown_verb_available_list_excludes_subhandlers() {
7220        let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
7221
7222        let err = reg
7223            .dispatch("not_a_verb", serde_json::json!({}))
7224            .await
7225            .unwrap_err();
7226
7227        let msg = err.to_string();
7228        // `recall.embed` is a Subhandler in HelpPack — must NOT appear in the
7229        // "available" list of an unknown-verb dispatch error.
7230        assert!(
7231            !msg.contains("recall.embed"),
7232            "dispatch unknown-verb error must not advertise subhandler recall.embed: {msg}"
7233        );
7234        // Public verbs must still appear so the agent knows what to call.
7235        assert!(
7236            msg.contains("create"),
7237            "dispatch unknown-verb error must still list public verb 'create': {msg}"
7238        );
7239        assert!(
7240            msg.contains("recall"),
7241            "dispatch unknown-verb error must still list public verb 'recall': {msg}"
7242        );
7243    }
7244
7245    // ── ADR-028 multi-backend schema routing tests ───────────────────────────
7246
7247    /// A test pack that returns a real SchemaPlan so we can assert routing.
7248    struct SchemaPack {
7249        pack_name: &'static str,
7250        statements: &'static [&'static str],
7251    }
7252
7253    impl Pack for SchemaPack {
7254        const NAME: &'static str = "schema-pack";
7255        const NOTE_KINDS: &'static [&'static str] = &[];
7256        const ENTITY_KINDS: &'static [&'static str] = &[];
7257        const HANDLERS: &'static [HandlerDef] = &[];
7258    }
7259
7260    #[async_trait]
7261    impl PackRuntime for SchemaPack {
7262        fn name(&self) -> &str {
7263            self.pack_name
7264        }
7265        fn note_kinds(&self) -> &'static [&'static str] {
7266            &[]
7267        }
7268        fn entity_kinds(&self) -> &'static [&'static str] {
7269            &[]
7270        }
7271        fn handlers(&self) -> &'static [HandlerDef] {
7272            &[]
7273        }
7274        fn schema_plan(&self) -> SchemaPlan {
7275            SchemaPlan {
7276                pack: self.pack_name,
7277                statements: self.statements,
7278            }
7279        }
7280        async fn dispatch(
7281            &self,
7282            verb: &str,
7283            _params: Value,
7284            _registry: &VerbRegistry,
7285            _token: &NamespaceToken,
7286        ) -> Result<Value, RuntimeError> {
7287            Ok(serde_json::json!({ "pack": self.pack_name, "verb": verb }))
7288        }
7289    }
7290
7291    // ADR-028: all_schema_plans_named returns (pack_name, SchemaPlan) pairs
7292    // where pack_name comes from SchemaPlan::pack (always &'static str).
7293    #[test]
7294    fn all_schema_plans_named_returns_correct_pairs() {
7295        let mut builder = VerbRegistryBuilder::new();
7296        builder.register_boxed(Box::new(SchemaPack {
7297            pack_name: "alpha",
7298            statements: &["CREATE TABLE IF NOT EXISTS t_alpha (id INTEGER PRIMARY KEY)"],
7299        }));
7300        builder.register_boxed(Box::new(SchemaPack {
7301            pack_name: "beta",
7302            statements: &[],
7303        }));
7304        let reg = builder.build().expect("registry builds");
7305
7306        let named = reg.all_schema_plans_named();
7307        assert_eq!(named.len(), 2);
7308
7309        let alpha_entry = named.iter().find(|(n, _)| *n == "alpha");
7310        let beta_entry = named.iter().find(|(n, _)| *n == "beta");
7311
7312        assert!(alpha_entry.is_some(), "alpha must appear in named plans");
7313        assert!(beta_entry.is_some(), "beta must appear in named plans");
7314
7315        let (_, alpha_plan) = alpha_entry.unwrap();
7316        assert_eq!(alpha_plan.statements.len(), 1);
7317        assert!(!alpha_plan.is_empty());
7318
7319        let (_, beta_plan) = beta_entry.unwrap();
7320        assert!(beta_plan.is_empty());
7321    }
7322
7323    // ADR-028: apply_schema_plans_with_map routes non-empty plans to the
7324    // correct per-pack backend instead of the default.
7325    //
7326    // Verification: apply DDL to routed backend, then confirm the table is
7327    // present on pack_backend and absent on default_backend by attempting to
7328    // apply the same DDL again — if the table already exists on pack_backend
7329    // the idempotent CREATE IF NOT EXISTS succeeds; applying to default_backend
7330    // would only matter if the table were routed there.  We verify isolation
7331    // by applying the plan and then running a targeted DDL on each backend
7332    // that would fail if the table did not already exist (CREATE without
7333    // IF NOT EXISTS on a duplicate raises an error), combined with a no-error
7334    // path on the correct backend.
7335    //
7336    // Simpler approach: confirm the plan applies without error (routing is
7337    // correct) and that the opposite backend returns an error when we try to
7338    // INSERT into the routed table (table-not-found = SQLITE_ERROR).
7339    #[tokio::test]
7340    async fn apply_schema_plans_with_map_routes_to_correct_backend() {
7341        use khive_storage::types::{SqlStatement, SqlValue};
7342
7343        let default_backend = khive_db::StorageBackend::memory().expect("default memory backend");
7344        let pack_backend =
7345            khive_db::StorageBackend::memory().expect("pack-specific memory backend");
7346
7347        let mut builder = VerbRegistryBuilder::new();
7348        builder.register_boxed(Box::new(SchemaPack {
7349            pack_name: "routed",
7350            statements: &["CREATE TABLE IF NOT EXISTS t_routed (id INTEGER PRIMARY KEY)"],
7351        }));
7352        let reg = builder.build().expect("registry builds");
7353
7354        let mut backend_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
7355        backend_map.insert("routed", &pack_backend);
7356
7357        reg.apply_schema_plans_with_map(&backend_map, &default_backend)
7358            .expect("schema application must not collide");
7359
7360        // On pack_backend: INSERT must succeed (table exists).
7361        let mut writer = pack_backend.sql().writer().await.expect("writer");
7362        let result = writer
7363            .execute(SqlStatement {
7364                sql: "INSERT INTO t_routed (id) VALUES (?1)".into(),
7365                params: vec![SqlValue::Integer(1)],
7366                label: None,
7367            })
7368            .await;
7369        assert!(
7370            result.is_ok(),
7371            "t_routed must exist on pack_backend after routing: {result:?}"
7372        );
7373
7374        // On default_backend: INSERT must fail (table not there).
7375        let mut default_writer = default_backend.sql().writer().await.expect("writer");
7376        let default_result = default_writer
7377            .execute(SqlStatement {
7378                sql: "INSERT INTO t_routed (id) VALUES (?1)".into(),
7379                params: vec![SqlValue::Integer(2)],
7380                label: None,
7381            })
7382            .await;
7383        assert!(
7384            default_result.is_err(),
7385            "t_routed must NOT exist on default_backend (table should not be there)"
7386        );
7387    }
7388
7389    // ADR-028: apply_schema_plans_with_map uses default backend for packs
7390    // absent from the map.
7391    #[tokio::test]
7392    async fn apply_schema_plans_with_map_falls_back_to_default_for_unmapped_packs() {
7393        use khive_storage::types::{SqlStatement, SqlValue};
7394
7395        let default_backend = khive_db::StorageBackend::memory().expect("default memory backend");
7396
7397        let mut builder = VerbRegistryBuilder::new();
7398        builder.register_boxed(Box::new(SchemaPack {
7399            pack_name: "unmapped",
7400            statements: &["CREATE TABLE IF NOT EXISTS t_unmapped (id INTEGER PRIMARY KEY)"],
7401        }));
7402        let reg = builder.build().expect("registry builds");
7403
7404        let backend_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
7405        reg.apply_schema_plans_with_map(&backend_map, &default_backend)
7406            .expect("schema application must not collide");
7407
7408        // On default_backend: INSERT must succeed (table fell back here).
7409        let mut writer = default_backend.sql().writer().await.expect("writer");
7410        let result = writer
7411            .execute(SqlStatement {
7412                sql: "INSERT INTO t_unmapped (id) VALUES (?1)".into(),
7413                params: vec![SqlValue::Integer(1)],
7414                label: None,
7415            })
7416            .await;
7417        assert!(
7418            result.is_ok(),
7419            "t_unmapped must exist on default_backend for unmapped pack: {result:?}"
7420        );
7421    }
7422
7423    // ADR-028: two packs declaring the same auxiliary table on the same
7424    // backend must cause apply_schema_plans_with_map to return an error that
7425    // names both packs and the table: it is a boot-time failure, not a
7426    // silent DDL race.
7427    #[test]
7428    fn apply_schema_plans_with_map_collision_is_an_error() {
7429        let backend = khive_db::StorageBackend::memory().expect("memory backend");
7430        let empty_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
7431
7432        let mut builder = VerbRegistryBuilder::new();
7433        builder.register_boxed(Box::new(SchemaPack {
7434            pack_name: "pack_alpha",
7435            statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
7436        }));
7437        builder.register_boxed(Box::new(SchemaPack {
7438            pack_name: "pack_beta",
7439            statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
7440        }));
7441        let registry = builder.build().expect("registry builds");
7442
7443        let result = registry.apply_schema_plans_with_map(&empty_map, &backend);
7444        assert!(
7445            result.is_err(),
7446            "two packs declaring the same table on the same backend must produce a collision error"
7447        );
7448        let err = result.unwrap_err();
7449        let msg = err.to_string();
7450        assert!(
7451            msg.contains("pack_alpha"),
7452            "collision error must name first pack; got: {msg}"
7453        );
7454        assert!(
7455            msg.contains("pack_beta"),
7456            "collision error must name second pack; got: {msg}"
7457        );
7458        assert!(
7459            msg.contains("collision_table"),
7460            "collision error must name the table; got: {msg}"
7461        );
7462    }
7463}