Skip to main content

khive_runtime/pack/
builder.rs

1use std::collections::{HashMap, HashSet, VecDeque};
2use std::sync::Arc;
3
4#[cfg(doc)]
5use khive_gate::GateRequest;
6use khive_gate::{AllowAllGate, GateRef};
7use khive_storage::EventStore;
8#[cfg(doc)]
9use khive_storage::EventView;
10use khive_types::{Namespace, NotePropertyPolicySpec};
11use serde_json::Value;
12
13use crate::error::{
14    CircularPackDependency, MissingPackDependencies, MissingPackDependency, RuntimeError,
15};
16use crate::KhiveRuntime;
17
18use super::{
19    AuditSuccessRowsMode, DispatchHook, EdgeEndpointRule, EntityTypeDef, HandlerDef,
20    PackByIdResolver, PackRuntime, VerbCategory, VerbRegistry, Visibility, RESERVED_ENVELOPE_ARGS,
21};
22#[cfg(doc)]
23use super::{PackFactory, PackRegistry};
24
25#[cfg(any(test, feature = "test-internals"))]
26type RuntimeEventStoreTestWrapper =
27    Arc<dyn Fn(Arc<dyn EventStore>) -> Arc<dyn EventStore> + Send + Sync>;
28
29/// Builder for constructing a `VerbRegistry`.
30///
31/// Packs are registered here; once `.build()` is called the registry is
32/// immutable and cheaply cloneable.
33pub struct VerbRegistryBuilder {
34    packs: Vec<Box<dyn PackRuntime>>,
35    pub(super) pack_versions: HashMap<String, &'static str>,
36    /// Parallel to `packs`: whether the composition root vouches for the
37    /// pack at the same index, recorded by the registration method the
38    /// *caller* chose rather than anything the pack reports about itself.
39    /// [`Self::register`] (public, reachable from any pack crate) always
40    /// pushes `false`; `register_boxed` (crate-private, exercised only by
41    /// [`PackRegistry::register_packs`]'s `inventory`-discovered factories)
42    /// and the test-only `register_trusted` push `true`. A pack has no API
43    /// surface to set its own entry here — see
44    /// [`VerbRegistry::ADMISSION_DEGRADE_SAFE_VERBS`]'s doc for why
45    /// `pack.name()` alone cannot be trusted for this decision.
46    pack_trusted: Vec<bool>,
47    disabled_verbs: HashMap<String, Vec<String>>,
48    resolvers: Vec<(String, Box<dyn PackByIdResolver>)>,
49    pub(super) kg_read_resolver: Option<Arc<crate::kg_read::KgReadResolver>>,
50    gate: GateRef,
51    default_namespace: String,
52    /// Operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
53    ///
54    /// Threads into `VerbRegistry::visible_namespaces` and is consumed by the
55    /// default dispatch path to widen read scope to `['local'] ∪ visible_namespaces`.
56    /// Writes remain pinned to `'local'`. An explicit `namespace=` request param
57    /// is a precise escape and is not widened by this set. A cloud gate may also
58    /// consult the list as policy input at its own layer.
59    visible_namespaces: Vec<Namespace>,
60    /// Operator-declared namespaces the configured actor owns (`[actor]
61    /// owned_namespaces`, ADR-021 Delta 1).
62    ///
63    /// Threads into `VerbRegistry::owned_namespaces` and is stamped onto every
64    /// token the registry mints. It is read by the `memory.apply_batch` old-row
65    /// namespace check alone: it grants no write and widens no read.
66    owned_namespaces: Vec<Namespace>,
67    /// Configured actor identity label (ADR-057). When set, dispatch mints tokens
68    /// carrying this actor so that `comm.inbox` filters by `to_actor`.
69    actor_id: Option<String>,
70    /// Optional audit event sink.
71    ///
72    /// When set, every gate check writes a storage `Event` in addition to the
73    /// `tracing::info!` emission. Persistence is separate from the optional
74    /// runtime binding retained for config-lock ownership.
75    event_store: Option<Arc<dyn EventStore>>,
76    /// Retains runtime ownership and resolves its final namespace sink at build.
77    runtime_event_store: Option<KhiveRuntime>,
78    #[cfg(any(test, feature = "test-internals"))]
79    test_runtime_event_store_wrapper: Option<RuntimeEventStoreTestWrapper>,
80    /// The configured audit backend is intentionally read-only, so dispatch
81    /// omits the known-failing append and the transport surfaces an advisory.
82    audit_store_read_only: bool,
83    /// Optional post-dispatch hook.
84    ///
85    /// When set, every successful pack dispatch calls `hook.on_dispatch(view)`
86    /// with a synthetic `EventView` describing the outcome and carrying no
87    /// observations. Opt-in: when None, no overhead is incurred.
88    dispatch_hook: Option<Arc<dyn DispatchHook>>,
89    /// ADR-133 audit-batch config override, applied when `build()` lazily
90    /// constructs the batch seam from `event_store`. `None` uses
91    /// `AuditBatchConfig::default()`.
92    audit_batch_config: Option<crate::audit_batch::AuditBatchConfig>,
93    audit_success_rows_mode: Option<AuditSuccessRowsMode>,
94}
95
96impl VerbRegistryBuilder {
97    /// Create a builder with no packs, `AllowAllGate`, and the local namespace as default.
98    pub fn new() -> Self {
99        Self {
100            packs: Vec::new(),
101            pack_versions: HashMap::new(),
102            pack_trusted: Vec::new(),
103            disabled_verbs: HashMap::new(),
104            resolvers: Vec::new(),
105            kg_read_resolver: None,
106            gate: std::sync::Arc::new(AllowAllGate),
107            default_namespace: Namespace::local().as_str().to_string(),
108            visible_namespaces: vec![],
109            owned_namespaces: vec![],
110            actor_id: None,
111            event_store: None,
112            runtime_event_store: None,
113            #[cfg(any(test, feature = "test-internals"))]
114            test_runtime_event_store_wrapper: None,
115            audit_store_read_only: false,
116            dispatch_hook: None,
117            audit_batch_config: None,
118            audit_success_rows_mode: None,
119        }
120    }
121
122    /// Disable public handlers owned by a loaded pack; validated when the registry builds.
123    pub fn with_disabled_verbs(&mut self, pack: &str, verbs: &[String]) -> &mut Self {
124        self.disabled_verbs.insert(pack.to_owned(), verbs.to_vec());
125        self
126    }
127
128    /// Set the operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
129    ///
130    /// On the default (no explicit `namespace=` param) dispatch path, reads fan
131    /// out over `['local'] ∪ ns`. Writes remain pinned to `'local'`. An explicit
132    /// `namespace=` request parameter is a precise single-namespace escape and
133    /// is not widened by this set. A cloud gate may also consult the list as
134    /// policy input at its own layer.
135    pub fn with_visible_namespaces(&mut self, ns: Vec<Namespace>) -> &mut Self {
136        self.visible_namespaces = ns;
137        self
138    }
139
140    /// Set the namespaces the configured actor declared it owns (ADR-021 Delta 1).
141    ///
142    /// Every token the registry mints carries this list, and the
143    /// `memory.apply_batch` old-row namespace check admits an old row in a listed
144    /// namespace like one in the caller's own namespace. Ownership grants no
145    /// write into the namespace and widens no read; `visible_namespaces` stays a
146    /// read-only grant. A per-request identity overrides this baked list.
147    pub fn with_owned_namespaces(&mut self, ns: Vec<Namespace>) -> &mut Self {
148        self.owned_namespaces = ns;
149        self
150    }
151
152    /// Set the configured actor identity label (ADR-057).
153    ///
154    /// When set, the dispatch path mints tokens carrying this actor so that
155    /// `comm.inbox` applies the `to_actor` filter for directed delivery.
156    /// When `None` (default), tokens carry `ActorRef::anonymous()` and inbox
157    /// falls back to party-line behavior.
158    pub fn with_actor_id(&mut self, actor_id: Option<String>) -> &mut Self {
159        self.actor_id = actor_id;
160        self
161    }
162
163    /// Register a pack. The bound `P: Pack + PackRuntime` ensures the pack
164    /// declares vocabulary via `Pack` consts alongside runtime dispatch.
165    ///
166    /// This is the untrusted path: reachable from any external pack crate,
167    /// so the pack registered here is never eligible for admission-degrade
168    /// under `VerbRegistry::admission_degrade_safe`, regardless of what
169    /// `pack.name()`/handler category it reports. Use `register_boxed`
170    /// (composition root) or `register_trusted` (tests) for a pack the
171    /// caller actually vouches for.
172    pub fn register<P: khive_types::Pack + PackRuntime + 'static>(&mut self, pack: P) -> &mut Self {
173        self.packs.push(Box::new(pack));
174        self.pack_trusted.push(false);
175        self
176    }
177
178    /// Register a boxed pack directly, vouched for by the composition root.
179    ///
180    /// Crate-private: only [`PackRegistry::register_packs`]/
181    /// `register_packs_with_runtimes` should call this — both resolve the
182    /// pack from an `inventory`-discovered `&'static dyn PackFactory`
183    /// (collected at link time from `inventory::submit!` call sites, not
184    /// from request-time data), so the trust grant recorded here reflects a
185    /// decision the composition root made, never something the pack itself
186    /// supplied. External callers must use the typed [`Self::register`]
187    /// which enforces the `Pack + PackRuntime` dual-impl contract at the
188    /// call site but is never trusted. Here the `Pack + PackRuntime`
189    /// contract is satisfied upstream at the [`PackFactory::create`] site.
190    pub(crate) fn register_boxed(&mut self, pack: Box<dyn PackRuntime>) -> &mut Self {
191        self.packs.push(pack);
192        self.pack_trusted.push(true);
193        self
194    }
195
196    /// Register an owned mounted namespace without native-pack trust privileges.
197    pub fn register_mounted(
198        &mut self,
199        pack: Box<dyn PackRuntime>,
200    ) -> Result<&mut Self, RuntimeError> {
201        if pack.mounted_namespace() != Some(pack.name()) || !pack.handlers().is_empty() {
202            return Err(RuntimeError::InvalidInput(
203                "invalid mounted namespace registration".into(),
204            ));
205        }
206        self.packs.push(pack);
207        self.pack_trusted.push(false);
208        Ok(self)
209    }
210
211    /// Test-only trusted registration, mirroring `register_boxed`'s trust
212    /// grant for external test binaries (e.g.
213    /// `tests/read_verb_admission_exhaustion.rs`) that cannot reach a
214    /// crate-private method directly — the same reason
215    /// [`VerbRegistry::admission_degrade_safe_probe`] is `pub` rather than
216    /// `pub(crate)`. A test using this method is asserting that the pack it
217    /// registers stands in for a pack the real composition root would load,
218    /// not an untrusted/third-party one.
219    #[cfg(any(test, feature = "test-internals"))]
220    pub fn register_trusted<P: khive_types::Pack + PackRuntime + 'static>(
221        &mut self,
222        pack: P,
223    ) -> &mut Self {
224        self.packs.push(Box::new(pack));
225        self.pack_trusted.push(true);
226        self
227    }
228
229    /// Register a by-ID resolver for a pack that owns private SQL tables.
230    ///
231    /// Packs that implement `PackByIdResolver` call this during their boot path
232    /// so that `get(id)` and `delete(id)` can reach their records.
233    pub fn register_resolver(
234        &mut self,
235        name: impl Into<String>,
236        resolver: Box<dyn PackByIdResolver>,
237    ) -> &mut Self {
238        self.resolvers.push((name.into(), resolver));
239        self
240    }
241
242    /// Set the authorization gate consulted on every dispatch.
243    ///
244    /// Defaults to `AllowAllGate` if not set. `Deny` is authoritative — a deny
245    /// decision aborts dispatch with `RuntimeError::PermissionDenied`. Gate
246    /// infrastructure errors abort dispatch with `RuntimeError::GateUnavailable`.
247    pub fn with_gate(&mut self, gate: GateRef) -> &mut Self {
248        self.gate = gate;
249        self
250    }
251
252    /// Set the namespace surfaced to the gate when a verb does not carry an
253    /// explicit `namespace` argument. Transports should plumb the runtime's
254    /// `default_namespace` so the gate's `input.namespace` always reflects
255    /// the operation's true tenant.
256    pub fn with_default_namespace(&mut self, ns: impl Into<String>) -> &mut Self {
257        self.default_namespace = ns.into();
258        self
259    }
260
261    /// Set the `EventStore` used to persist audit events.
262    ///
263    /// When configured, every gate check appends one `Event` (substrate =
264    /// `Event`, outcome = `Success` on allow, `Denied` on deny, or `Error` on
265    /// gate unavailability) in addition to the `tracing::info!` emission.
266    ///
267    /// Callers that do not set this field continue to use tracing-only emission
268    /// (the v0.2 default), except `git.digest`: its successful response carries
269    /// a durable receipt and therefore fails safely when no store is configured.
270    pub fn with_event_store(&mut self, store: Arc<dyn EventStore>) -> &mut Self {
271        self.event_store = Some(store);
272        self.runtime_event_store = None;
273        self.audit_store_read_only = false;
274        self
275    }
276
277    /// Configure the registry's trusted audit sink from a runtime.
278    ///
279    /// Registry audit constructors stamp namespace and actor directly from
280    /// each resolved [`GateRequest`], including per-request daemon identity
281    /// overrides. This deliberately uses the runtime's undecorated sink: the
282    /// public token-scoped [`KhiveRuntime::events`] decorator would otherwise
283    /// replace every per-request stamp with the single actor that happened to
284    /// construct the registry.
285    ///
286    /// The sink is resolved during [`Self::build`] using the final default
287    /// namespace, so the order of namespace and sink configuration does not
288    /// change its read scope. Sink initialization errors are returned by build:
289    /// a serving registry never silently drops a configured runtime audit sink.
290    /// Metadata builds and explicit replacement sinks do not open this sink.
291    pub fn with_runtime_event_store(
292        &mut self,
293        runtime: &KhiveRuntime,
294    ) -> Result<&mut Self, RuntimeError> {
295        self.event_store = None;
296        self.runtime_event_store = Some(runtime.clone());
297        self.audit_store_read_only = false;
298        Ok(self)
299    }
300
301    /// Decorate the runtime-resolved audit sink for test fixtures.
302    ///
303    /// The runtime binding and namespace resolution are retained. Explicit,
304    /// read-only, metadata and unbound sinks do not invoke this wrapper.
305    #[cfg(any(test, feature = "test-internals"))]
306    #[doc(hidden)]
307    pub fn with_runtime_event_store_test_wrapper<F>(&mut self, wrapper: F) -> &mut Self
308    where
309        F: Fn(Arc<dyn EventStore>) -> Arc<dyn EventStore> + Send + Sync + 'static,
310    {
311        self.test_runtime_event_store_wrapper = Some(Arc::new(wrapper));
312        self
313    }
314
315    /// Override the ADR-133 audit-batch seam's tunables, applied when
316    /// `build()` lazily constructs the batch from `event_store`.
317    /// `None` (the default) uses `AuditBatchConfig::default()`. Exposed for
318    /// tests that need to force a small `max_pending_rows` or a short
319    /// `admission_deadline` to exercise admission-pressure paths
320    /// deterministically (#2117, #2147, #2208, #2217).
321    pub fn with_audit_batch_config(
322        &mut self,
323        config: crate::audit_batch::AuditBatchConfig,
324    ) -> &mut Self {
325        self.audit_batch_config = Some(config);
326        self
327    }
328
329    /// Override `KHIVE_AUDIT_SUCCESS_ROWS` for this registry (ADR-103 Amendment 7).
330    pub fn with_audit_success_rows_mode(&mut self, mode: AuditSuccessRowsMode) -> &mut Self {
331        self.audit_success_rows_mode = Some(mode);
332        self
333    }
334
335    /// Mark audit persistence unavailable because its backend is read-only.
336    ///
337    /// No `EventStore` is retained, so dispatch never attempts a write that is
338    /// known to fail. Successful request entries expose a machine-readable
339    /// advisory without changing their canonical verb result shape.
340    pub fn with_read_only_audit_store(&mut self) -> &mut Self {
341        self.event_store = None;
342        self.runtime_event_store = None;
343        self.audit_store_read_only = true;
344        self
345    }
346
347    /// Register a post-dispatch hook.
348    ///
349    /// When set, every successful pack dispatch calls `hook.on_dispatch(view)`
350    /// with a synthetic [`EventView`] describing the verb outcome. Its
351    /// `observations` vector is empty; callers that need persisted provenance
352    /// must load it explicitly. The hook is opt-in: registries without a hook
353    /// incur zero overhead on the dispatch hot path.
354    ///
355    /// Brain pack uses this as a best-effort in-memory update path. Errors from
356    /// `on_dispatch` are logged via `tracing::warn!` and never propagated.
357    pub fn with_dispatch_hook(&mut self, hook: Arc<dyn DispatchHook>) -> &mut Self {
358        self.dispatch_hook = Some(hook);
359        self
360    }
361
362    /// Consume the builder and produce an immutable, cloneable registry.
363    ///
364    /// Performs a topological sort of packs using Kahn's algorithm.
365    /// Returns an error if any declared dependency is missing from the loaded
366    /// pack set, or if a circular dependency is detected.
367    pub fn build(self) -> Result<VerbRegistry, RuntimeError> {
368        self.build_registry(true)
369    }
370
371    /// Inspect pack metadata without activating any registered pack.
372    /// The result exposes no dispatch, preparation hooks, or serving-registry conversion.
373    pub fn build_metadata(mut self) -> Result<PackMetadataRegistry, RuntimeError> {
374        self.event_store = None;
375        self.runtime_event_store = None;
376        self.dispatch_hook = None;
377        self.resolvers.clear();
378        self.build_registry(false)
379            .map(|registry| PackMetadataRegistry { registry })
380    }
381
382    fn build_registry(self, activate: bool) -> Result<VerbRegistry, RuntimeError> {
383        let packs = self.packs;
384        let mut name_to_idx: HashMap<&str, usize> = HashMap::with_capacity(packs.len());
385        for (idx, pack) in packs.iter().enumerate() {
386            if let Some(prev_idx) = name_to_idx.insert(pack.name(), idx) {
387                return Err(RuntimeError::PackRedeclared {
388                    name: pack.name().to_string(),
389                    first_idx: prev_idx,
390                    second_idx: idx,
391                });
392            }
393        }
394
395        for mounted in packs
396            .iter()
397            .filter(|pack| pack.mounted_namespace().is_some())
398        {
399            let prefix = format!("{}.", mounted.name());
400            if packs
401                .iter()
402                .flat_map(|pack| pack.handlers())
403                .any(|handler| handler.name.starts_with(&prefix))
404            {
405                return Err(RuntimeError::InvalidInput(
406                    "mounted namespace collides with a native verb".into(),
407                ));
408            }
409        }
410
411        // Apply this metadata invariant to every HandlerDef, including Subhandlers. Subhandlers
412        // are not top-level MCP-callable, but their describe/help contract still cannot truthfully
413        // advertise a name rejected by every typed request parser before visibility dispatch.
414        for pack in &packs {
415            for handler in pack.handlers() {
416                for parameter in handler.params {
417                    if RESERVED_ENVELOPE_ARGS.contains(&parameter.name) {
418                        return Err(RuntimeError::ReservedEnvelopeParam {
419                            pack: pack.name().to_string(),
420                            verb: handler.name.to_string(),
421                            param: parameter.name.to_string(),
422                        });
423                    }
424                }
425            }
426        }
427
428        let mut missing: Vec<MissingPackDependency> = Vec::new();
429        let mut indegree = vec![0usize; packs.len()];
430        let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); packs.len()];
431
432        for (idx, pack) in packs.iter().enumerate() {
433            for &requires in pack.requires() {
434                match name_to_idx.get(requires).copied() {
435                    Some(dep_idx) => {
436                        dependents[dep_idx].push(idx);
437                        indegree[idx] += 1;
438                    }
439                    None => missing.push(MissingPackDependency {
440                        from: pack.name().to_string(),
441                        requires: requires.to_string(),
442                    }),
443                }
444            }
445        }
446
447        if !missing.is_empty() {
448            return if missing.len() == 1 {
449                Err(RuntimeError::MissingPackDependency(missing.remove(0)))
450            } else {
451                Err(RuntimeError::MissingPackDependencies(
452                    MissingPackDependencies { missing },
453                ))
454            };
455        }
456
457        let mut ready: VecDeque<usize> = indegree
458            .iter()
459            .enumerate()
460            .filter_map(|(idx, degree)| (*degree == 0).then_some(idx))
461            .collect();
462        let mut ordered_indices = Vec::with_capacity(packs.len());
463
464        while let Some(idx) = ready.pop_front() {
465            ordered_indices.push(idx);
466            for &dep_idx in &dependents[idx] {
467                indegree[dep_idx] -= 1;
468                if indegree[dep_idx] == 0 {
469                    ready.push_back(dep_idx);
470                }
471            }
472        }
473
474        if ordered_indices.len() != packs.len() {
475            let cycle_nodes: HashSet<usize> = indegree
476                .iter()
477                .enumerate()
478                .filter_map(|(idx, degree)| (*degree > 0).then_some(idx))
479                .collect();
480            let cycle = find_pack_dependency_cycle(&packs, &name_to_idx, &cycle_nodes);
481            return Err(RuntimeError::CircularPackDependency(
482                CircularPackDependency { cycle },
483            ));
484        }
485
486        let mut pack_slots: Vec<Option<Box<dyn PackRuntime>>> =
487            packs.into_iter().map(Some).collect();
488        let mut trusted_slots: Vec<Option<bool>> =
489            self.pack_trusted.into_iter().map(Some).collect();
490        let mut ordered_packs: Vec<Box<dyn PackRuntime>> = Vec::with_capacity(pack_slots.len());
491        let mut ordered_trusted: Vec<bool> = Vec::with_capacity(trusted_slots.len());
492        for idx in ordered_indices {
493            ordered_packs.push(
494                pack_slots[idx]
495                    .take()
496                    .expect("topological index must exist"),
497            );
498            ordered_trusted.push(
499                trusted_slots[idx]
500                    .take()
501                    .expect("topological index must exist"),
502            );
503        }
504
505        validate_unique_note_kinds(&ordered_packs)?;
506        validate_unique_verb_names(&ordered_packs)?;
507        validate_unique_entity_types(&ordered_packs)?;
508        validate_entity_type_note_kind_collisions(&ordered_packs)?;
509        validate_brain_consumer_kinds(&ordered_packs)?;
510        super::declaration_validation::validate_declarations(&ordered_packs)?;
511        let mut disabled_verbs = HashSet::new();
512        let mut policies: Vec<_> = self.disabled_verbs.iter().collect();
513        policies.sort_by_key(|(pack, _)| *pack);
514        for (name, verbs) in policies {
515            if verbs.is_empty() {
516                continue;
517            }
518            let pack = ordered_packs
519                .iter()
520                .find(|pack| pack.name() == name.as_str())
521                .ok_or_else(|| {
522                    RuntimeError::InvalidInput(format!(
523                        "packs.{name}.verbs_disabled: pack is not loaded"
524                    ))
525                })?;
526            for verb in verbs {
527                let handler = pack
528                    .handlers()
529                    .iter()
530                    .find(|handler| {
531                        handler.name == verb.as_str()
532                            && matches!(handler.visibility, Visibility::Verb)
533                    })
534                    .ok_or_else(|| {
535                        RuntimeError::InvalidInput(format!(
536                    "packs.{name}.verbs_disabled: {verb:?} is not a public verb owned by this pack"
537                ))
538                    })?;
539                disabled_verbs.insert(handler.name);
540            }
541        }
542        let note_property_policies = collect_note_property_policies(&ordered_packs)?;
543        if activate {
544            for pack in &ordered_packs {
545                pack.validate_config()?;
546            }
547        }
548
549        let available_verbs: Vec<&'static str> = ordered_packs
550            .iter()
551            .flat_map(|p| p.handlers().iter())
552            .filter(|h| {
553                matches!(h.visibility, Visibility::Verb) && !disabled_verbs.contains(h.name)
554            })
555            .map(|h| h.name)
556            .collect();
557
558        // Keep the first declaration for duplicate subhandler names, matching
559        // the registry's existing pack-order metadata lookup behavior. Public
560        // verb names have already been checked for uniqueness above.
561        let mut handler_by_name: HashMap<&'static str, &'static HandlerDef> = HashMap::new();
562        for pack in &ordered_packs {
563            for handler in pack.handlers() {
564                handler_by_name.entry(handler.name).or_insert(handler);
565            }
566        }
567
568        let mut audit_success_row_omitted_verbs = HashSet::new();
569        let mut audit_success_row_sampled_verbs = HashMap::new();
570        let mut success_row_owners = HashSet::new();
571        for (pack, &trusted) in ordered_packs.iter().zip(ordered_trusted.iter()) {
572            for handler in pack.handlers() {
573                // An earlier untrusted subhandler still owns dispatch; a later
574                // trusted declaration must not lend that handler its privileges.
575                if !success_row_owners.insert(handler.name) {
576                    continue;
577                }
578                if trusted
579                    && VerbRegistry::AUDIT_SUCCESS_ROW_OMITTED_VERBS
580                        .contains(&(pack.name(), handler.name))
581                {
582                    audit_success_row_omitted_verbs.insert(handler.name);
583                }
584                if let Some(&(_, _, every, forcing)) = VerbRegistry::AUDIT_SUCCESS_ROW_SAMPLED_VERBS
585                    .iter()
586                    .find(|&&(owner, verb, _, _)| owner == pack.name() && verb == handler.name)
587                {
588                    if trusted {
589                        audit_success_row_sampled_verbs.insert(handler.name, (every, forcing));
590                    }
591                }
592            }
593        }
594        let audit_success_rows_mode = self
595            .audit_success_rows_mode
596            .unwrap_or_else(AuditSuccessRowsMode::from_env);
597
598        // Admission-degrade eligibility (#2147/#2217, khive-oss#2311): decided
599        // once here, from the trust bit the composition root recorded at
600        // registration time (never from `pack.name()`'s self-report) plus
601        // each handler's declared category and the `(pack, verb)` allowlist —
602        // see `VerbRegistry::admission_degrade_safe`'s doc. A verb is
603        // globally unique across `Visibility::Verb` handlers at this point
604        // (`validate_unique_verb_names` above already enforced that), so a
605        // flat `HashSet<&'static str>` is an unambiguous key: no dispatch
606        // call site needs to re-resolve which pack owns a verb to answer
607        // this question, and none does (`VerbRegistry::admission_degrade_safe`
608        // is a single hash-set lookup with no per-call pack/handler scan).
609        let mut degrade_safe_verbs: HashSet<&'static str> = HashSet::new();
610        let mut read_replay_safe_verbs = HashSet::new();
611        for (pack, &trusted) in ordered_packs.iter().zip(ordered_trusted.iter()) {
612            if !trusted {
613                continue;
614            }
615            let pack_name = pack.name();
616            for handler in pack.handlers() {
617                let canonical_owner = handler
618                    .name
619                    .split_once('.')
620                    .map_or("kg", |(owner, _)| owner);
621                if matches!(handler.visibility, Visibility::Verb)
622                    && pack_name == canonical_owner
623                    && crate::classify_operation(handler.name) == Some(crate::OperationAccess::Read)
624                    && !VerbRegistry::SIDE_EFFECTING_ASSERTIVE_VERBS.contains(&handler.name)
625                {
626                    read_replay_safe_verbs.insert(handler.name);
627                }
628                if !matches!(handler.visibility, Visibility::Verb)
629                    || handler.category != VerbCategory::Assertive
630                {
631                    continue;
632                }
633                let eligible = VerbRegistry::admission_degrade_safe_sorted()
634                    .binary_search_by(|&(p, v)| p.cmp(pack_name).then_with(|| v.cmp(handler.name)))
635                    .is_ok();
636                if eligible {
637                    degrade_safe_verbs.insert(handler.name);
638                }
639            }
640        }
641
642        // ADR-133: incidental audit writes route through one batch seam per
643        // configured `EventStore` instead of taking a writer-task
644        // acquisition per dispatch. No store configured (tracing-only or
645        // read-only-audit registries) means no seam to construct.
646        //
647        // A configured store that does not implement the seam's
648        // `preflight_event`/`append_events_idempotent` pair would otherwise
649        // build silently: every submitted row is rejected at preflight, the
650        // dispatch that produced it still reports success, and nothing here
651        // distinguishes that from a healthy registry. Reject it now, with an
652        // actionable message, instead of at the first audited dispatch.
653        let config_lock_runtime = self.runtime_event_store;
654        let event_store = match &config_lock_runtime {
655            Some(runtime) => Some(runtime.raw_events_for_namespace(&self.default_namespace)?),
656            None => self.event_store,
657        };
658        #[cfg(any(test, feature = "test-internals"))]
659        let event_store = match (
660            &config_lock_runtime,
661            &self.test_runtime_event_store_wrapper,
662            event_store,
663        ) {
664            (Some(_), Some(wrapper), Some(store)) => Some(wrapper(store)),
665            (_, _, store) => store,
666        };
667        if let Some(store) = &event_store {
668            if !store.supports_idempotent_audit_batch() {
669                return Err(RuntimeError::IncompatibleEventStore(
670                    "the configured EventStore does not implement ADR-133's \
671                     preflight_event/append_events_idempotent pair \
672                     (supports_idempotent_audit_batch() returned false); every \
673                     audited dispatch would silently lose its audit row while \
674                     still reporting success. Implement both methods and \
675                     override supports_idempotent_audit_batch() to opt in, or \
676                     do not call with_event_store() for this backend."
677                        .to_string(),
678                ));
679            }
680        }
681        let audit_batch = event_store.clone().map(|store| {
682            crate::audit_batch::AuditBatch::new(
683                store,
684                self.audit_batch_config.clone().unwrap_or_default(),
685            )
686        });
687
688        // Snapshot ownership before flattening rules for runtime installation.
689        // Keep declaration order and duplicate rules, including identical rules
690        // contributed by different packs.
691        let attributed_edge_rules = ordered_packs
692            .iter()
693            .flat_map(|pack| {
694                pack.edge_rules()
695                    .iter()
696                    .map(move |rule| (pack.name().to_owned(), *rule))
697            })
698            .collect();
699
700        Ok(VerbRegistry {
701            packs: Arc::new(ordered_packs),
702            attributed_edge_rules: Arc::new(attributed_edge_rules),
703            pack_versions: Arc::new(self.pack_versions),
704            note_property_policies: Arc::new(note_property_policies),
705            resolvers: Arc::new(self.resolvers),
706            kg_read_resolver: self.kg_read_resolver,
707            gate: self.gate,
708            default_namespace: self.default_namespace,
709            visible_namespaces: self.visible_namespaces,
710            owned_namespaces: self.owned_namespaces,
711            actor_id: self.actor_id,
712            event_store,
713            config_lock_runtime,
714            audit_store_read_only: self.audit_store_read_only,
715            dispatch_hook: self.dispatch_hook,
716            available_verbs: Arc::new(available_verbs),
717            disabled_verbs: Arc::new(disabled_verbs),
718            handler_by_name: Arc::new(handler_by_name),
719            degrade_safe_verbs: Arc::new(degrade_safe_verbs),
720            audit_success_rows_mode,
721            audit_success_row_omitted_verbs: Arc::new(audit_success_row_omitted_verbs),
722            audit_success_row_sampled_verbs: Arc::new(audit_success_row_sampled_verbs),
723            read_replay_safe_verbs: Arc::new(read_replay_safe_verbs),
724            reference_ring: Arc::new(crate::reference_ring::ReferenceRing::new()),
725            audit_batch,
726        })
727    }
728}
729
730/// Validate and capture property metadata in topological pack/declaration order.
731fn collect_note_property_policies(
732    packs: &[Box<dyn PackRuntime>],
733) -> Result<Vec<NotePropertyPolicySpec>, RuntimeError> {
734    let mut policies = Vec::new();
735    let mut seen = HashSet::new();
736    for pack in packs {
737        let owned_kinds = pack.note_kinds();
738        for spec in pack.note_property_policies() {
739            if !owned_kinds.contains(&spec.kind) {
740                return Err(RuntimeError::InvalidInput(format!(
741                    "pack {:?} declares property policy for unowned note kind {:?}, key {:?}",
742                    pack.name(),
743                    spec.kind,
744                    spec.key
745                )));
746            }
747            if !seen.insert((spec.kind, spec.key)) {
748                return Err(RuntimeError::InvalidInput(format!(
749                    "pack {:?} declares duplicate property policy for note kind {:?}, key {:?}",
750                    pack.name(),
751                    spec.kind,
752                    spec.key
753                )));
754            }
755            policies.push(*spec);
756        }
757    }
758    Ok(policies)
759}
760
761/// Validate that no two packs declare the same note kind.
762///
763/// Boot-time duplicate detection prevents pack configuration errors from
764/// silently corrupting note kind routing. Returns an error naming the
765/// duplicate kind and the two packs that claim it.
766fn validate_unique_note_kinds(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
767    let mut seen: HashMap<&str, &str> = HashMap::new();
768    for pack in packs {
769        for &kind in pack.note_kinds() {
770            if let Some(first_pack) = seen.insert(kind, pack.name()) {
771                return Err(RuntimeError::InvalidInput(format!(
772                    "duplicate note kind {kind:?}: claimed by both {first_pack:?} and {:?}",
773                    pack.name()
774                )));
775            }
776        }
777    }
778    Ok(())
779}
780
781/// Validate pack-declared brain consumer kinds at the composition boundary.
782///
783/// The wildcard belongs to the binding matcher rather than any consumer, and
784/// whitespace-bearing values can never equal the exact wire values callers
785/// request. Reject both at boot so a malformed declaration cannot make an
786/// otherwise unreachable binding appear valid.
787fn validate_brain_consumer_kinds(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
788    for pack in packs {
789        for &kind in pack.brain_consumer_kinds() {
790            if kind == "*" || kind.trim().is_empty() || kind.trim() != kind {
791                return Err(RuntimeError::InvalidInput(format!(
792                    "pack {:?} declares invalid brain consumer kind {kind:?}; declarations must be non-empty exact wire values and must not use the registry-owned \"*\" wildcard",
793                    pack.name()
794                )));
795            }
796        }
797    }
798    Ok(())
799}
800
801/// Validate that no two packs declare the same `Visibility::Verb` handler name.
802///
803/// `Visibility::Subhandler` entries are pack-prefixed by convention and excluded
804/// from cross-pack collision detection. Two packs declaring the same subhandler
805/// name prefix (e.g. `recall.embed`) would be a pack-authoring error but does not
806/// produce a cross-pack routing conflict since only the owning pack dispatches them.
807fn validate_unique_verb_names(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
808    let mut seen: HashMap<&str, &str> = HashMap::new();
809    for pack in packs {
810        for handler in pack.handlers() {
811            if !matches!(handler.visibility, Visibility::Verb) {
812                continue;
813            }
814            if let Some(first_pack) = seen.insert(handler.name, pack.name()) {
815                return Err(RuntimeError::VerbCollision {
816                    verb: handler.name.to_string(),
817                    first_pack: first_pack.to_string(),
818                    second_pack: pack.name().to_string(),
819                });
820            }
821        }
822    }
823    Ok(())
824}
825
826/// Validate that no two owners (the built-in table or a loaded pack) declare
827/// a colliding `entity_type` canonical name or alias.
828///
829/// Boot-time duplicate detection prevents pack configuration errors from
830/// silently applying insertion-order semantics to entity-type resolution
831/// (ADR-001's registry-ownership collision rule: same `(base_kind,
832/// canonical_name)` from two different packs, or an alias collision, is a
833/// boot error). Returns an error naming the colliding key and both
834/// contributing owners.
835fn validate_unique_entity_types(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
836    let owned_defs = packs
837        .iter()
838        .flat_map(|p| p.entity_types().iter().map(move |def| (p.name(), def)));
839    khive_types::EntityTypeRegistry::check_extra_collisions(owned_defs)
840        .map_err(RuntimeError::InvalidInput)
841}
842
843/// A granular kind token must identify only one substrate after pack composition.
844/// Check aliases too: both subtype and note-kind spellings are normalized at
845/// the request boundary, so a cosmetic spelling difference is still a clash.
846fn validate_entity_type_note_kind_collisions(
847    packs: &[Box<dyn PackRuntime>],
848) -> Result<(), RuntimeError> {
849    let mut note_kinds = HashMap::new();
850    for pack in packs {
851        for &kind in pack.note_kinds() {
852            note_kinds
853                .entry(khive_types::to_snake_case(kind))
854                .or_insert(pack.name());
855        }
856    }
857
858    let check_definition = |definition: &EntityTypeDef, owner: &str| {
859        for name in std::iter::once(definition.type_name).chain(definition.aliases.iter().copied())
860        {
861            let normalized = khive_types::to_snake_case(name);
862            if let Some(note_owner) = note_kinds.get(&normalized) {
863                return Err(RuntimeError::InvalidInput(format!(
864                    "entity subtype {name:?} from {owner:?} collides with note kind {normalized:?} from pack {note_owner:?}"
865                )));
866            }
867        }
868        Ok(())
869    };
870
871    let builtin = khive_types::EntityTypeRegistry::builtin();
872    for definition in builtin.definitions() {
873        check_definition(definition, "builtin")?;
874    }
875    for pack in packs {
876        for definition in pack.entity_types() {
877            check_definition(definition, pack.name())?;
878        }
879    }
880    Ok(())
881}
882
883fn find_pack_dependency_cycle(
884    packs: &[Box<dyn PackRuntime>],
885    name_to_idx: &HashMap<&str, usize>,
886    cycle_nodes: &HashSet<usize>,
887) -> Vec<String> {
888    fn visit(
889        idx: usize,
890        packs: &[Box<dyn PackRuntime>],
891        name_to_idx: &HashMap<&str, usize>,
892        cycle_nodes: &HashSet<usize>,
893        visiting: &mut Vec<usize>,
894        visited: &mut HashSet<usize>,
895    ) -> Option<Vec<String>> {
896        if let Some(pos) = visiting.iter().position(|&seen| seen == idx) {
897            let mut cycle: Vec<String> = visiting[pos..]
898                .iter()
899                .map(|&i| packs[i].name().to_string())
900                .collect();
901            cycle.push(packs[idx].name().to_string());
902            return Some(cycle);
903        }
904        if !visited.insert(idx) {
905            return None;
906        }
907        visiting.push(idx);
908        for &req in packs[idx].requires() {
909            let Some(&dep_idx) = name_to_idx.get(req) else {
910                continue;
911            };
912            if cycle_nodes.contains(&dep_idx) {
913                if let Some(cycle) =
914                    visit(dep_idx, packs, name_to_idx, cycle_nodes, visiting, visited)
915                {
916                    return Some(cycle);
917                }
918            }
919        }
920        visiting.pop();
921        None
922    }
923
924    let mut visited = HashSet::new();
925    for &idx in cycle_nodes {
926        let mut visiting = Vec::new();
927        if let Some(cycle) = visit(
928            idx,
929            packs,
930            name_to_idx,
931            cycle_nodes,
932            &mut visiting,
933            &mut visited,
934        ) {
935            return cycle;
936        }
937    }
938    cycle_nodes
939        .iter()
940        .map(|&idx| packs[idx].name().to_string())
941        .collect()
942}
943
944impl Default for VerbRegistryBuilder {
945    fn default() -> Self {
946        Self::new()
947    }
948}
949
950/// Pack metadata with no executable registry capability.
951///
952/// ```compile_fail
953/// fn dispatch(metadata: &khive_runtime::PackMetadataRegistry) {
954///     metadata.dispatch("telemetry.emit", serde_json::json!({}));
955/// }
956/// ```
957pub struct PackMetadataRegistry {
958    pub(super) registry: VerbRegistry,
959}
960
961impl PackMetadataRegistry {
962    pub fn has_verb(&self, verb: &str) -> bool {
963        self.registry.has_verb(verb)
964    }
965
966    pub fn describe_verb(&self, verb: &str) -> Result<Value, RuntimeError> {
967        self.registry.describe_verb(verb)
968    }
969
970    pub fn all_handlers_with_names(&self) -> Vec<(&str, &'static HandlerDef)> {
971        self.registry.all_handlers_with_names()
972    }
973
974    pub fn all_verbs(&self) -> Vec<&'static HandlerDef> {
975        self.registry.all_verbs()
976    }
977
978    pub fn pack_names(&self) -> Vec<&str> {
979        self.registry.pack_names()
980    }
981
982    /// Factory-reported version, if this pack was registered through a factory.
983    pub fn pack_version(&self, name: &str) -> Option<&'static str> {
984        self.registry.pack_version(name)
985    }
986
987    pub fn pack_requires(&self, name: &str) -> Option<&'static [&'static str]> {
988        self.registry.pack_requires(name)
989    }
990
991    pub fn pack_note_kinds(&self, name: &str) -> Option<&'static [&'static str]> {
992        self.registry.pack_note_kinds(name)
993    }
994
995    pub fn pack_entity_kinds(&self, name: &str) -> Option<&'static [&'static str]> {
996        self.registry.pack_entity_kinds(name)
997    }
998
999    pub fn pack_verbs(&self, name: &str) -> Option<&'static [HandlerDef]> {
1000        self.registry.pack_verbs(name)
1001    }
1002
1003    pub fn all_entity_kinds(&self) -> Vec<&'static str> {
1004        self.registry.all_entity_kinds()
1005    }
1006
1007    pub fn all_note_kinds(&self) -> Vec<&'static str> {
1008        self.registry.all_note_kinds()
1009    }
1010
1011    pub fn all_edge_rules(&self) -> Vec<EdgeEndpointRule> {
1012        self.registry.all_edge_rules()
1013    }
1014
1015    /// Pack ownership for every declared endpoint rule, in installation order.
1016    pub fn all_edge_rules_with_packs(&self) -> Vec<(&str, EdgeEndpointRule)> {
1017        self.registry.all_edge_rules_with_packs()
1018    }
1019}