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