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