Skip to main content

khive_runtime/
pack.rs

1// FILE SIZE JUSTIFICATION: pack.rs is the load-bearing dispatch core — VerbRegistry,
2// VerbRegistryBuilder, PackRuntime, DispatchHook, and their test scaffolding all
3// share internal state (packs Vec, gate, event_store) that cannot be cleanly split
4// without exposing private fields or duplicating the scaffolding. Inline tests cover
5// collision detection and dispatch path that require direct access to VerbRegistry
6// internals. Split plan: when the verb surface reaches a stable v1 API, extract
7// VerbRegistryBuilder into `pack/builder.rs` and gate/event logic into `pack/dispatch.rs`.
8//! Pack runtime trait and verb registry.
9//!
10//! `PackRuntime` mirrors `Pack`'s const associated items as methods for object safety.
11//! Build a [`VerbRegistry`] via `VerbRegistryBuilder::build()`; registration is builder-only.
12
13use std::collections::{HashMap, HashSet, VecDeque};
14use std::sync::Arc;
15use std::time::Instant;
16
17use crate::operations::{LinkSpec, Resolved};
18use crate::runtime::NamespaceToken;
19use async_trait::async_trait;
20use khive_gate::{AllowAllGate, AuditEvent, GateDecision, GateRef, GateRequest};
21use khive_storage::{Event, EventStore, EventView, SubstrateKind};
22use khive_types::{EventKind, EventOutcome, Namespace};
23use serde_json::Value;
24
25pub use khive_types::{
26    EdgeEndpointRule, EndpointKind, EntityTypeDef, HandlerDef, NoteKindSpec, NoteLifecycleSpec,
27    PackSchemaPlan, ParamDef, VerbCategory, VerbPresentationPolicy, Visibility,
28    RESERVED_ENVELOPE_ARGS,
29};
30// Backward-compat re-export.
31#[allow(deprecated)]
32pub use khive_types::VerbDef;
33
34use crate::validation::ValidationRule;
35
36/// Name of the pack providing the shared CRUD verbs and the general-purpose
37/// note kinds those verbs exist to serve.
38///
39/// Its note kinds are the ones any caller may author freely through `create`
40/// and `update`; every other pack's note kinds are records maintained by that
41/// pack's own verbs. Used by
42/// [`VerbRegistry::pack_owned_note_kinds`].
43pub const GENERIC_CRUD_PACK: &str = "kg";
44
45/// Stable advisory code emitted when a successful inspection cannot persist
46/// its dispatch audit because the configured audit backend is read-only.
47pub const AUDIT_PERSISTENCE_SKIPPED_READ_ONLY: &str = "audit_persistence_skipped_read_only";
48
49const FULL_UUID_IDENTIFIER_HELP: &str = "A complete UUID spelling accepted by the consuming \
50    parameter directly names one globally unique record; direct UUID lookup is not a namespace \
51    search. Strict identifier responses use canonical lowercase dashed UUIDs.";
52const SHORT_PREFIX_IDENTIFIER_HELP: &str = "A short UUID prefix is at least 8 hexadecimal \
53    characters without dashes that do not parse as a complete UUID. It is a resolution, not a \
54    direct identifier; a 32-character compact UUID is complete input instead. Its lookup scope belongs to the consuming parameter: \
55    operations governed by ADR-007's by-ID contract resolve without a namespace filter, while \
56    other resolvers may search only the caller's primary namespace. A prefix can be missing or \
57    ambiguous.";
58const IDENTIFIER_PARAMETER_HELP: &str = "A parameter that requires a full UUID rejects prefixes \
59    and explains the resolution consequence. Its corresponding response field remains a \
60    canonical full UUID so the value can be submitted again.";
61
62fn identifier_resolution_help() -> Value {
63    serde_json::json!({
64        "full_uuid": FULL_UUID_IDENTIFIER_HELP,
65        "short_prefix": SHORT_PREFIX_IDENTIFIER_HELP,
66        "parameter_rule": IDENTIFIER_PARAMETER_HELP,
67    })
68}
69
70/// Pack-auxiliary schema plan.
71///
72/// Declares `CREATE TABLE IF NOT EXISTS` statements for pack-owned tables that
73/// are NOT part of the core substrate schema (entities, notes, edges, events).
74/// Applied at boot via `StorageBackend::apply_schema` / `apply_pack_schema_plan`.
75///
76/// Core substrate tables evolve through versioned migrations. Pack schema is
77/// strictly for pack-auxiliary tables (e.g. GTD lifecycle audit, memory index).
78/// v1 pack schemas are non-versioned.
79#[derive(Debug, Default, Clone)]
80pub struct SchemaPlan {
81    /// Owning pack name.
82    pub pack: &'static str,
83    /// DDL statements applied idempotently at boot.
84    /// Each entry must be a self-contained `CREATE TABLE IF NOT EXISTS` or
85    /// similar idempotent statement.
86    pub statements: &'static [&'static str],
87}
88
89impl SchemaPlan {
90    /// Construct a `SchemaPlan` with no statements.
91    ///
92    /// Packs whose state lives entirely in the core substrate tables (entities,
93    /// notes, edges) use this as their `schema_plan()` return value.
94    pub const fn empty() -> Self {
95        Self {
96            pack: "",
97            statements: &[],
98        }
99    }
100
101    /// Returns `true` when the plan contains no DDL statements.
102    pub fn is_empty(&self) -> bool {
103        self.statements.is_empty()
104    }
105}
106
107/// Best-effort hook called after every successful verb dispatch.
108///
109/// The runtime supplies a synthetic [`EventView`] whose `event` describes the
110/// dispatch outcome and whose `observations` vector is currently empty. Loading
111/// persisted provenance observations belongs to an explicit caller or the
112/// deferred event-consumer contract; this hook does not provide it.
113#[async_trait]
114pub trait DispatchHook: Send + Sync {
115    /// Called with the dispatch-outcome event view after a successful pack dispatch.
116    ///
117    /// Errors are logged via `tracing::warn!` and never propagated to the
118    /// caller; the dispatch has already succeeded.
119    async fn on_dispatch(&self, view: &EventView);
120}
121
122use crate::error::{
123    CircularPackDependency, MissingPackDependencies, MissingPackDependency, RuntimeError,
124};
125use crate::KhiveRuntime;
126
127/// Async dispatch trait for packs.
128///
129/// This is the object-safe behavioral counterpart to `khive_types::Pack`.
130/// `Pack` uses const associated items (not object-safe in Rust); this trait
131/// mirrors that metadata as methods and adds async dispatch.
132///
133/// Registration requires `P: Pack + PackRuntime` — the compiler enforces
134/// that every runtime pack also declares its vocabulary via `Pack`.
135#[async_trait]
136pub trait PackRuntime: Send + Sync {
137    /// Pack name — must equal `<Self as Pack>::NAME`.
138    fn name(&self) -> &str;
139
140    /// Note kinds this pack owns — must equal `<Self as Pack>::NOTE_KINDS`.
141    fn note_kinds(&self) -> &'static [&'static str];
142
143    /// Entity kinds this pack owns — must equal `<Self as Pack>::ENTITY_KINDS`.
144    fn entity_kinds(&self) -> &'static [&'static str];
145
146    /// Brain profile consumer kinds this pack requests — must equal
147    /// `<Self as Pack>::BRAIN_CONSUMER_KINDS`.
148    fn brain_consumer_kinds(&self) -> &'static [&'static str] {
149        &[]
150    }
151
152    /// Handlers this pack registers — must equal `<Self as Pack>::HANDLERS`.
153    fn handlers(&self) -> &'static [HandlerDef];
154
155    /// Pack-extensible edge endpoint rules — must equal `<Self as Pack>::EDGE_RULES`.
156    /// Defaults to empty so existing packs that don't extend the edge contract
157    /// can ignore it.
158    fn edge_rules(&self) -> &'static [EdgeEndpointRule] {
159        &[]
160    }
161
162    /// Pack-extensible entity-type subtypes — must equal `<Self as Pack>::ENTITY_TYPES`.
163    /// Defaults to empty so existing packs that don't extend the entity_type
164    /// registry can ignore it.
165    fn entity_types(&self) -> &'static [EntityTypeDef] {
166        &[]
167    }
168
169    /// Pack names whose vocabulary this pack references.
170    /// Defaults to empty so existing packs compile without changes.
171    fn requires(&self) -> &'static [&'static str] {
172        &[]
173    }
174
175    /// NoteKindSpec declarations for note kinds this pack owns.
176    ///
177    /// Packs that introduce note kinds with explicit lifecycle semantics
178    /// declare the spec here.  The runtime collects these for introspection
179    /// and future enforcement.  Defaults to empty so existing packs compile
180    /// without changes.
181    fn note_kind_specs(&self) -> &'static [NoteKindSpec] {
182        &[]
183    }
184
185    /// Optional per-kind hook for shared CRUD specialization.
186    ///
187    /// When a kind is owned by this pack (declared in `note_kinds()` or
188    /// `entity_kinds()`), returning `Some(hook)` opts that kind into
189    /// pack-specific behavior — defaults, derived properties, side-effect
190    /// edges — through the shared `create` path. Returning `None` keeps
191    /// the kind as plain storage with no specialization.
192    fn kind_hook(&self, _kind: &str) -> Option<Arc<dyn KindHook>> {
193        None
194    }
195
196    /// Accept the trusted channel-ingest capability grant for this specific
197    /// pack instance.
198    ///
199    /// Called at most once per instance, immediately after this instance is
200    /// constructed via [`PackFactory::create_install`], and only for packs
201    /// whose name appears in `CHANNEL_INGEST_CAPABLE_PACKS`. Storing the
202    /// grant on `self` (rather than on the `&'static dyn PackFactory`, which
203    /// is a single process-wide singleton shared by every instance the
204    /// factory ever creates) makes the grant instance-bound: a `CommPack`
205    /// built outside [`PackRegistry::register_packs`] holds no capability
206    /// unless something calls this on that specific instance. Defaults to a
207    /// no-op so packs outside the allowlist compile without changes.
208    fn accept_channel_ingest_capability(&self, _capability: ChannelIngestCapability) {}
209
210    /// Pack-auxiliary schema.
211    ///
212    /// Returns DDL statements for pack-owned tables that are NOT part of the
213    /// core substrate schema. Statements are idempotent (`CREATE TABLE IF NOT
214    /// EXISTS`) so callers can apply them safely on every registration. Core
215    /// substrate tables evolve through versioned migrations; pack schema is
216    /// strictly pack-auxiliary.
217    ///
218    /// Defaults to an empty plan — packs that store everything in the core
219    /// substrate tables (entities, notes, edges, events) return this default.
220    ///
221    /// Plans are aggregated via [`VerbRegistry::all_schema_plans`] and applied
222    /// at startup via `KhiveMcpServer::with_packs`. Packs that need their
223    /// schema present (e.g. GTD) also self-bootstrap lazily on first call for
224    /// robustness in test contexts that create fresh in-memory databases.
225    fn schema_plan(&self) -> SchemaPlan {
226        SchemaPlan::empty()
227    }
228
229    /// Domain-specific validation rules contributed by this pack.
230    ///
231    /// Rule IDs MUST follow the `<pack>/<rule-id>` namespace convention.
232    /// Built-in rules (no pack prefix) are reserved for the `khive-runtime`
233    /// validation infrastructure.
234    ///
235    /// Defaults to empty — packs with no domain-specific rules return `&[]`.
236    fn validation_rules(&self) -> &'static [ValidationRule] {
237        &[]
238    }
239
240    /// Register custom embedding providers with the runtime. Called during pack
241    /// initialisation, before the first verb dispatch, so `KhiveRuntime::embedder(name)`
242    /// resolves provider names declared here. Default no-op — packs that only use
243    /// built-in lattice models do not need to override this.
244    /// See `docs/api/pack.md#register_embedders` for a usage example.
245    fn register_embedders(&self, _runtime: &KhiveRuntime) {}
246
247    /// Install a pack-owned entity-type validator on the runtime, called during pack
248    /// initialisation (after the registry is built, before the first dispatch) so
249    /// `create_many`/`create_entity` reject unregistered `entity_type` values at the
250    /// runtime layer. Default no-op leaves the validator absent (skip-when-None).
251    /// See `docs/api/pack.md#register_entity_type_validator` for the two-hook compatibility contract.
252    fn register_entity_type_validator(&self, _runtime: &KhiveRuntime) {}
253
254    /// Install a pack-owned entity-type validator that also receives the boot-time
255    /// composed set of every loaded pack's `ENTITY_TYPES` ([`VerbRegistry::all_entity_types`]).
256    /// Defaults to calling [`register_entity_type_validator`](Self::register_entity_type_validator)
257    /// with just the runtime. `call_register_entity_type_validators` calls this hook, not
258    /// the simpler one — override this to receive the composed vocabulary.
259    /// See `docs/api/pack.md#register_entity_type_validator` for the two-hook compatibility contract.
260    fn register_entity_type_validator_with_types(
261        &self,
262        runtime: &KhiveRuntime,
263        _pack_entity_types: &[EntityTypeDef],
264    ) {
265        self.register_entity_type_validator(runtime);
266    }
267
268    /// Install a pack-owned note-mutation hook on the runtime, called during pack
269    /// initialisation with the same timing as `register_entity_type_validator`. Packs
270    /// that cache derived state keyed by note content (e.g. `khive-pack-memory`'s warm
271    /// ANN index) override this to install a hook via
272    /// `KhiveRuntime::install_note_mutation_hook`. Default no-op leaves the hook absent.
273    /// See `docs/api/pack.md#register_note_mutation_hook` for cross-pack notification rationale.
274    fn register_note_mutation_hook(&self, _runtime: &KhiveRuntime) {}
275
276    /// Install a note-write validator on the runtime, called at pack
277    /// initialisation with the same timing as `register_note_mutation_hook`.
278    ///
279    /// A pack owning a note kind whose properties carry identity that the
280    /// runtime can derive from the authorization token implements this and
281    /// calls `KhiveRuntime::install_note_write_validator`, so the identity is
282    /// derived at every note-write site rather than trusted from caller input
283    /// on the write paths that reach no pack verb. Default no-op leaves the
284    /// slot absent. The slot holds one validator, so an implementation must
285    /// return properties for kinds it does not own unchanged.
286    fn register_note_write_validator(&self, _runtime: &KhiveRuntime) {}
287
288    /// Warm up any in-memory state from persisted snapshots (optional). Called after
289    /// all packs are registered but before serving the first request. Must be
290    /// idempotent and infallible — errors are logged internally, never propagated.
291    async fn warm(&self) {}
292
293    /// Names of all embedding models registered on this pack's underlying runtime
294    /// handle. Defaults to empty — only packs that own embedding-bearing verbs
295    /// (kg, memory) need to override this.
296    /// See `docs/api/pack.md#registered_embedding_model_names` for the ADR-103 consumer.
297    fn registered_embedding_model_names(&self) -> Vec<String> {
298        Vec::new()
299    }
300
301    /// Dispatch a verb call. Returns serialized JSON response.
302    ///
303    /// The `registry` parameter gives the handler access to the merged
304    /// vocabulary and kind hooks across all loaded packs.
305    /// The `token` is an authorized namespace token minted by the dispatch
306    /// boundary after gate authorization — handlers must use it directly.
307    async fn dispatch(
308        &self,
309        verb: &str,
310        params: Value,
311        registry: &VerbRegistry,
312        token: &NamespaceToken,
313    ) -> Result<Value, RuntimeError>;
314}
315
316/// Per-kind specialization for shared CRUD.
317///
318/// Packs implement `KindHook` for kinds they own that need:
319/// - **Defaults** filled into create args (e.g. `status="inbox"` for tasks)
320/// - **Derived properties** computed from args (e.g. salience from priority)
321/// - **Side-effect writes** after the storage commit (e.g. `depends_on` edges)
322/// - **Cross-pack validation** before shared CRUD mutates an owned kind
323///
324/// Hooks are stateless from the framework's perspective — they receive the
325/// runtime and the current mutation inputs as method parameters. The pack
326/// registers them via [`PackRuntime::kind_hook`].
327///
328/// Lifecycle verbs (e.g. gtd's `complete`, `transition`) remain pack-owned
329/// verbs. Shared `create`, note `update`, and `link` calls flow through this
330/// trait when an endpoint kind has an owning pack hook.
331#[async_trait]
332pub trait KindHook: Send + Sync + std::fmt::Debug {
333    /// Mutate args before the storage write. Fill defaults, normalize values,
334    /// rearrange user-facing fields into the storage shape expected by the
335    /// shared CRUD handler.
336    ///
337    /// Returning an error aborts the create call (no storage write happens).
338    async fn prepare_create(
339        &self,
340        runtime: &KhiveRuntime,
341        args: &mut Value,
342    ) -> Result<(), RuntimeError>;
343
344    /// Fire side effects after a successful storage write — graph edges,
345    /// derived observations, etc. The newly created record's UUID is passed
346    /// so the hook can attach metadata referencing it.
347    ///
348    /// Errors here are **logged but not propagated** — the storage write has
349    /// already succeeded; failing the call would mislead the caller.
350    /// Implementations should `tracing::warn!` and return `Ok(())` for
351    /// best-effort side effects.
352    async fn after_create(
353        &self,
354        runtime: &KhiveRuntime,
355        id: uuid::Uuid,
356        args: &Value,
357    ) -> Result<(), RuntimeError>;
358
359    /// Normalize a shared note update before storage is mutated.
360    ///
361    /// The default preserves the original property-validation contract. A
362    /// kind-owning pack overrides this when caller-facing note fields mirror
363    /// owned properties and must be changed together (for example, a task's
364    /// searchable `content` and `properties.description`).
365    async fn prepare_note_update(
366        &self,
367        runtime: &KhiveRuntime,
368        token: &NamespaceToken,
369        note: &khive_storage::Note,
370        args: &mut Value,
371    ) -> Result<(), RuntimeError> {
372        let properties = args.get("properties").filter(|value| !value.is_null());
373        self.validate_note_update(runtime, token, note, properties)
374            .await
375    }
376
377    /// Validate a shared note-property update before storage is mutated.
378    ///
379    /// The default accepts the update. Kind-owning packs override this when a
380    /// property has invariants that generic CRUD cannot know about (for
381    /// example, GTD task dependency acyclicity).
382    async fn validate_note_update(
383        &self,
384        _runtime: &KhiveRuntime,
385        _token: &NamespaceToken,
386        _note: &khive_storage::Note,
387        _properties: Option<&Value>,
388    ) -> Result<(), RuntimeError> {
389        Ok(())
390    }
391
392    /// Validate one or more shared graph links before any edge is written.
393    ///
394    /// A batch is supplied as a unit so a hook can reject a cycle formed only
395    /// by the proposed edges. The default accepts every link.
396    async fn validate_links(
397        &self,
398        _runtime: &KhiveRuntime,
399        _token: &NamespaceToken,
400        _links: &[crate::LinkSpec],
401    ) -> Result<(), RuntimeError> {
402        Ok(())
403    }
404}
405
406/// Optional sub-trait for packs that own private SQL tables and issue UUIDs
407/// that must be reachable through the generic `get(id)` and `delete(id)` verbs.
408///
409/// Implementing both methods is required — the sub-trait bundles them atomically
410/// so partial implementation is a compile-time error, not a runtime surprise.
411/// Packs whose records live in the shared entity/note substrate (gtd, memory)
412/// do not implement this sub-trait.
413#[async_trait]
414pub trait PackByIdResolver: Send + Sync {
415    /// Attempt to resolve a live (non-deleted) UUID owned by this pack's private tables.
416    ///
417    /// Returns `Some(Resolved::PackRecord { ... })` if this pack owns the UUID,
418    /// `None` if it does not (the caller continues to the next resolver),
419    /// or `Err(...)` on a storage error.
420    ///
421    /// Must query domain-authoritative tables before mirror tables.
422    /// Must NOT filter by namespace. UUID v4 is globally unique; by-ID
423    /// resolution is namespace-blind per ADR-007.
424    async fn resolve_by_id(
425        &self,
426        id: uuid::Uuid,
427    ) -> Result<Option<crate::Resolved>, crate::RuntimeError>;
428
429    /// Attempt to resolve a UUID including already-soft-deleted records.
430    ///
431    /// Used by the hard-delete path. Default delegates to `resolve_by_id`;
432    /// packs with `deleted_at` columns override this to query without the filter.
433    async fn resolve_by_id_including_deleted(
434        &self,
435        id: uuid::Uuid,
436    ) -> Result<Option<crate::Resolved>, crate::RuntimeError> {
437        self.resolve_by_id(id).await
438    }
439
440    /// Delete a record owned by this pack's private tables.
441    ///
442    /// `hard` mirrors the `delete` verb's `hard?` argument.
443    /// Default behavior for packs with a `deleted_at` column MUST be soft-delete;
444    /// `hard=true` performs permanent removal.
445    ///
446    /// Returns `Ok(Value)` with a `{ deleted: true, id, kind, hard }` body on success.
447    /// Returns `Err(RuntimeError::NotFound(...))` if the record does not exist.
448    async fn delete_by_id(
449        &self,
450        id: uuid::Uuid,
451        hard: bool,
452    ) -> Result<serde_json::Value, crate::RuntimeError>;
453}
454
455/// Builder for constructing a `VerbRegistry`.
456///
457/// Packs are registered here; once `.build()` is called the registry is
458/// immutable and cheaply cloneable.
459pub struct VerbRegistryBuilder {
460    packs: Vec<Box<dyn PackRuntime>>,
461    resolvers: Vec<(String, Box<dyn PackByIdResolver>)>,
462    gate: GateRef,
463    default_namespace: String,
464    /// Operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
465    ///
466    /// Threads into `VerbRegistry::visible_namespaces` and is consumed by the
467    /// default dispatch path to widen read scope to `['local'] ∪ visible_namespaces`.
468    /// Writes remain pinned to `'local'`. An explicit `namespace=` request param
469    /// is a precise escape and is not widened by this set. A cloud gate may also
470    /// consult the list as policy input at its own layer.
471    visible_namespaces: Vec<Namespace>,
472    /// Configured actor identity label (ADR-057). When set, dispatch mints tokens
473    /// carrying this actor so that `comm.inbox` filters by `to_actor`.
474    actor_id: Option<String>,
475    /// Optional audit event sink.
476    ///
477    /// When set, every gate check writes a storage `Event` in addition to the
478    /// `tracing::info!` emission. The store is `Arc<dyn EventStore>` so the
479    /// registry does not depend on the full `KhiveRuntime` surface — only the
480    /// audit-persistence capability is needed here.
481    event_store: Option<Arc<dyn EventStore>>,
482    /// The configured audit backend is intentionally read-only, so dispatch
483    /// omits the known-failing append and the transport surfaces an advisory.
484    audit_store_read_only: bool,
485    /// Optional post-dispatch hook.
486    ///
487    /// When set, every successful pack dispatch calls `hook.on_dispatch(view)`
488    /// with a synthetic `EventView` describing the outcome and carrying no
489    /// observations. Opt-in: when None, no overhead is incurred.
490    dispatch_hook: Option<Arc<dyn DispatchHook>>,
491    /// ADR-133 audit-batch config override, applied when `build()` lazily
492    /// constructs the batch seam from `event_store`. `None` uses
493    /// `AuditBatchConfig::default()`.
494    audit_batch_config: Option<crate::audit_batch::AuditBatchConfig>,
495}
496
497impl VerbRegistryBuilder {
498    /// Create a builder with no packs, `AllowAllGate`, and the local namespace as default.
499    pub fn new() -> Self {
500        Self {
501            packs: Vec::new(),
502            resolvers: Vec::new(),
503            gate: std::sync::Arc::new(AllowAllGate),
504            default_namespace: Namespace::local().as_str().to_string(),
505            visible_namespaces: vec![],
506            actor_id: None,
507            event_store: None,
508            audit_store_read_only: false,
509            dispatch_hook: None,
510            audit_batch_config: None,
511        }
512    }
513
514    /// Set the operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
515    ///
516    /// On the default (no explicit `namespace=` param) dispatch path, reads fan
517    /// out over `['local'] ∪ ns`. Writes remain pinned to `'local'`. An explicit
518    /// `namespace=` request parameter is a precise single-namespace escape and
519    /// is not widened by this set. A cloud gate may also consult the list as
520    /// policy input at its own layer.
521    pub fn with_visible_namespaces(&mut self, ns: Vec<Namespace>) -> &mut Self {
522        self.visible_namespaces = ns;
523        self
524    }
525
526    /// Set the configured actor identity label (ADR-057).
527    ///
528    /// When set, the dispatch path mints tokens carrying this actor so that
529    /// `comm.inbox` applies the `to_actor` filter for directed delivery.
530    /// When `None` (default), tokens carry `ActorRef::anonymous()` and inbox
531    /// falls back to party-line behavior.
532    pub fn with_actor_id(&mut self, actor_id: Option<String>) -> &mut Self {
533        self.actor_id = actor_id;
534        self
535    }
536
537    /// Register a pack. The bound `P: Pack + PackRuntime` ensures the pack
538    /// declares vocabulary via `Pack` consts alongside runtime dispatch.
539    pub fn register<P: khive_types::Pack + PackRuntime + 'static>(&mut self, pack: P) -> &mut Self {
540        self.packs.push(Box::new(pack));
541        self
542    }
543
544    /// Register a boxed pack directly.
545    ///
546    /// Crate-private: only [`PackRegistry::register_packs`] should call this.
547    /// External callers must use the typed [`Self::register`] which enforces the
548    /// `Pack + PackRuntime` dual-impl contract at the call site.  Here the
549    /// contract is satisfied upstream at the [`PackFactory::create`] site.
550    pub(crate) fn register_boxed(&mut self, pack: Box<dyn PackRuntime>) -> &mut Self {
551        self.packs.push(pack);
552        self
553    }
554
555    /// Register a by-ID resolver for a pack that owns private SQL tables.
556    ///
557    /// Packs that implement `PackByIdResolver` call this during their boot path
558    /// so that `get(id)` and `delete(id)` can reach their records.
559    pub fn register_resolver(
560        &mut self,
561        name: impl Into<String>,
562        resolver: Box<dyn PackByIdResolver>,
563    ) -> &mut Self {
564        self.resolvers.push((name.into(), resolver));
565        self
566    }
567
568    /// Set the authorization gate consulted on every dispatch.
569    ///
570    /// Defaults to `AllowAllGate` if not set. `Deny` is authoritative — a deny
571    /// decision aborts dispatch with `RuntimeError::PermissionDenied`. Gate
572    /// infrastructure errors abort dispatch with `RuntimeError::GateUnavailable`.
573    pub fn with_gate(&mut self, gate: GateRef) -> &mut Self {
574        self.gate = gate;
575        self
576    }
577
578    /// Set the namespace surfaced to the gate when a verb does not carry an
579    /// explicit `namespace` argument. Transports should plumb the runtime's
580    /// `default_namespace` so the gate's `input.namespace` always reflects
581    /// the operation's true tenant.
582    pub fn with_default_namespace(&mut self, ns: impl Into<String>) -> &mut Self {
583        self.default_namespace = ns.into();
584        self
585    }
586
587    /// Set the `EventStore` used to persist audit events.
588    ///
589    /// When configured, every gate check appends one `Event` (substrate =
590    /// `Event`, outcome = `Success` on allow, `Denied` on deny, or `Error` on
591    /// gate unavailability) in addition to the `tracing::info!` emission.
592    ///
593    /// Callers that do not set this field continue to use tracing-only emission
594    /// (the v0.2 default), except `git.digest`: its successful response carries
595    /// a durable receipt and therefore fails safely when no store is configured.
596    pub fn with_event_store(&mut self, store: Arc<dyn EventStore>) -> &mut Self {
597        self.event_store = Some(store);
598        self.audit_store_read_only = false;
599        self
600    }
601
602    /// Override the ADR-133 audit-batch seam's tunables, applied when
603    /// `build()` lazily constructs the batch from `event_store`.
604    /// `None` (the default) uses `AuditBatchConfig::default()`. Exposed for
605    /// tests that need to force a small `max_pending_rows` or a short
606    /// `admission_deadline` to exercise admission-pressure paths
607    /// deterministically (khive#2117, khive#2147, khive#2208, khive#2217).
608    pub fn with_audit_batch_config(
609        &mut self,
610        config: crate::audit_batch::AuditBatchConfig,
611    ) -> &mut Self {
612        self.audit_batch_config = Some(config);
613        self
614    }
615
616    /// Mark audit persistence unavailable because its backend is read-only.
617    ///
618    /// No `EventStore` is retained, so dispatch never attempts a write that is
619    /// known to fail. Successful request entries expose a machine-readable
620    /// advisory without changing their canonical verb result shape.
621    pub fn with_read_only_audit_store(&mut self) -> &mut Self {
622        self.event_store = None;
623        self.audit_store_read_only = true;
624        self
625    }
626
627    /// Register a post-dispatch hook.
628    ///
629    /// When set, every successful pack dispatch calls `hook.on_dispatch(view)`
630    /// with a synthetic [`EventView`] describing the verb outcome. Its
631    /// `observations` vector is empty; callers that need persisted provenance
632    /// must load it explicitly. The hook is opt-in: registries without a hook
633    /// incur zero overhead on the dispatch hot path.
634    ///
635    /// Brain pack uses this as a best-effort in-memory update path. Errors from
636    /// `on_dispatch` are logged via `tracing::warn!` and never propagated.
637    pub fn with_dispatch_hook(&mut self, hook: Arc<dyn DispatchHook>) -> &mut Self {
638        self.dispatch_hook = Some(hook);
639        self
640    }
641
642    /// Consume the builder and produce an immutable, cloneable registry.
643    ///
644    /// Performs a topological sort of packs using Kahn's algorithm.
645    /// Returns an error if any declared dependency is missing from the loaded
646    /// pack set, or if a circular dependency is detected.
647    pub fn build(self) -> Result<VerbRegistry, RuntimeError> {
648        let packs = self.packs;
649        let mut name_to_idx: HashMap<&str, usize> = HashMap::with_capacity(packs.len());
650        for (idx, pack) in packs.iter().enumerate() {
651            if let Some(prev_idx) = name_to_idx.insert(pack.name(), idx) {
652                return Err(RuntimeError::PackRedeclared {
653                    name: pack.name().to_string(),
654                    first_idx: prev_idx,
655                    second_idx: idx,
656                });
657            }
658        }
659
660        // Apply this metadata invariant to every HandlerDef, including Subhandlers. Subhandlers
661        // are not top-level MCP-callable, but their describe/help contract still cannot truthfully
662        // advertise a name rejected by every typed request parser before visibility dispatch.
663        for pack in &packs {
664            for handler in pack.handlers() {
665                for parameter in handler.params {
666                    if RESERVED_ENVELOPE_ARGS.contains(&parameter.name) {
667                        return Err(RuntimeError::ReservedEnvelopeParam {
668                            pack: pack.name().to_string(),
669                            verb: handler.name.to_string(),
670                            param: parameter.name.to_string(),
671                        });
672                    }
673                }
674            }
675        }
676
677        let mut missing: Vec<MissingPackDependency> = Vec::new();
678        let mut indegree = vec![0usize; packs.len()];
679        let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); packs.len()];
680
681        for (idx, pack) in packs.iter().enumerate() {
682            for &requires in pack.requires() {
683                match name_to_idx.get(requires).copied() {
684                    Some(dep_idx) => {
685                        dependents[dep_idx].push(idx);
686                        indegree[idx] += 1;
687                    }
688                    None => missing.push(MissingPackDependency {
689                        from: pack.name().to_string(),
690                        requires: requires.to_string(),
691                    }),
692                }
693            }
694        }
695
696        if !missing.is_empty() {
697            return if missing.len() == 1 {
698                Err(RuntimeError::MissingPackDependency(missing.remove(0)))
699            } else {
700                Err(RuntimeError::MissingPackDependencies(
701                    MissingPackDependencies { missing },
702                ))
703            };
704        }
705
706        let mut ready: VecDeque<usize> = indegree
707            .iter()
708            .enumerate()
709            .filter_map(|(idx, degree)| (*degree == 0).then_some(idx))
710            .collect();
711        let mut ordered_indices = Vec::with_capacity(packs.len());
712
713        while let Some(idx) = ready.pop_front() {
714            ordered_indices.push(idx);
715            for &dep_idx in &dependents[idx] {
716                indegree[dep_idx] -= 1;
717                if indegree[dep_idx] == 0 {
718                    ready.push_back(dep_idx);
719                }
720            }
721        }
722
723        if ordered_indices.len() != packs.len() {
724            let cycle_nodes: HashSet<usize> = indegree
725                .iter()
726                .enumerate()
727                .filter_map(|(idx, degree)| (*degree > 0).then_some(idx))
728                .collect();
729            let cycle = find_pack_dependency_cycle(&packs, &name_to_idx, &cycle_nodes);
730            return Err(RuntimeError::CircularPackDependency(
731                CircularPackDependency { cycle },
732            ));
733        }
734
735        let mut slots: Vec<Option<Box<dyn PackRuntime>>> = packs.into_iter().map(Some).collect();
736        let ordered_packs: Vec<Box<dyn PackRuntime>> = ordered_indices
737            .into_iter()
738            .map(|idx| slots[idx].take().expect("topological index must exist"))
739            .collect();
740
741        validate_unique_note_kinds(&ordered_packs)?;
742        validate_unique_verb_names(&ordered_packs)?;
743        validate_unique_entity_types(&ordered_packs)?;
744        validate_brain_consumer_kinds(&ordered_packs)?;
745
746        let available_verbs: Vec<&'static str> = ordered_packs
747            .iter()
748            .flat_map(|p| p.handlers().iter())
749            .filter(|h| matches!(h.visibility, Visibility::Verb))
750            .map(|h| h.name)
751            .collect();
752
753        // ADR-133: incidental audit writes route through one batch seam per
754        // configured `EventStore` instead of taking a writer-task
755        // acquisition per dispatch. No store configured (tracing-only or
756        // read-only-audit registries) means no seam to construct.
757        //
758        // A configured store that does not implement the seam's
759        // `preflight_event`/`append_events_idempotent` pair would otherwise
760        // build silently: every submitted row is rejected at preflight, the
761        // dispatch that produced it still reports success, and nothing here
762        // distinguishes that from a healthy registry. Reject it now, with an
763        // actionable message, instead of at the first audited dispatch.
764        if let Some(store) = &self.event_store {
765            if !store.supports_idempotent_audit_batch() {
766                return Err(RuntimeError::IncompatibleEventStore(
767                    "the configured EventStore does not implement ADR-133's \
768                     preflight_event/append_events_idempotent pair \
769                     (supports_idempotent_audit_batch() returned false); every \
770                     audited dispatch would silently lose its audit row while \
771                     still reporting success. Implement both methods and \
772                     override supports_idempotent_audit_batch() to opt in, or \
773                     do not call with_event_store() for this backend."
774                        .to_string(),
775                ));
776            }
777        }
778        let audit_batch = self.event_store.clone().map(|store| {
779            crate::audit_batch::AuditBatch::new(
780                store,
781                self.audit_batch_config.clone().unwrap_or_default(),
782            )
783        });
784
785        Ok(VerbRegistry {
786            packs: Arc::new(ordered_packs),
787            resolvers: Arc::new(self.resolvers),
788            gate: self.gate,
789            default_namespace: self.default_namespace,
790            visible_namespaces: self.visible_namespaces,
791            actor_id: self.actor_id,
792            event_store: self.event_store,
793            audit_store_read_only: self.audit_store_read_only,
794            dispatch_hook: self.dispatch_hook,
795            available_verbs: Arc::new(available_verbs),
796            reference_ring: Arc::new(crate::reference_ring::ReferenceRing::new()),
797            audit_batch,
798        })
799    }
800}
801
802/// Validate that no two packs declare the same note kind.
803///
804/// Boot-time duplicate detection prevents pack configuration errors from
805/// silently corrupting note kind routing. Returns an error naming the
806/// duplicate kind and the two packs that claim it.
807fn validate_unique_note_kinds(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
808    let mut seen: HashMap<&str, &str> = HashMap::new();
809    for pack in packs {
810        for &kind in pack.note_kinds() {
811            if let Some(first_pack) = seen.insert(kind, pack.name()) {
812                return Err(RuntimeError::InvalidInput(format!(
813                    "duplicate note kind {kind:?}: claimed by both {first_pack:?} and {:?}",
814                    pack.name()
815                )));
816            }
817        }
818    }
819    Ok(())
820}
821
822/// Validate pack-declared brain consumer kinds at the composition boundary.
823///
824/// The wildcard belongs to the binding matcher rather than any consumer, and
825/// whitespace-bearing values can never equal the exact wire values callers
826/// request. Reject both at boot so a malformed declaration cannot make an
827/// otherwise unreachable binding appear valid.
828fn validate_brain_consumer_kinds(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
829    for pack in packs {
830        for &kind in pack.brain_consumer_kinds() {
831            if kind == "*" || kind.trim().is_empty() || kind.trim() != kind {
832                return Err(RuntimeError::InvalidInput(format!(
833                    "pack {:?} declares invalid brain consumer kind {kind:?}; declarations must be non-empty exact wire values and must not use the registry-owned \"*\" wildcard",
834                    pack.name()
835                )));
836            }
837        }
838    }
839    Ok(())
840}
841
842/// Validate that no two packs declare the same `Visibility::Verb` handler name.
843///
844/// `Visibility::Subhandler` entries are pack-prefixed by convention and excluded
845/// from cross-pack collision detection. Two packs declaring the same subhandler
846/// name prefix (e.g. `recall.embed`) would be a pack-authoring error but does not
847/// produce a cross-pack routing conflict since only the owning pack dispatches them.
848fn validate_unique_verb_names(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
849    let mut seen: HashMap<&str, &str> = HashMap::new();
850    for pack in packs {
851        for handler in pack.handlers() {
852            if !matches!(handler.visibility, Visibility::Verb) {
853                continue;
854            }
855            if let Some(first_pack) = seen.insert(handler.name, pack.name()) {
856                return Err(RuntimeError::VerbCollision {
857                    verb: handler.name.to_string(),
858                    first_pack: first_pack.to_string(),
859                    second_pack: pack.name().to_string(),
860                });
861            }
862        }
863    }
864    Ok(())
865}
866
867/// Validate that no two owners (the built-in table or a loaded pack) declare
868/// a colliding `entity_type` canonical name or alias.
869///
870/// Boot-time duplicate detection prevents pack configuration errors from
871/// silently applying insertion-order semantics to entity-type resolution
872/// (ADR-001's registry-ownership collision rule: same `(base_kind,
873/// canonical_name)` from two different packs, or an alias collision, is a
874/// boot error). Returns an error naming the colliding key and both
875/// contributing owners.
876fn validate_unique_entity_types(packs: &[Box<dyn PackRuntime>]) -> Result<(), RuntimeError> {
877    let owned_defs = packs
878        .iter()
879        .flat_map(|p| p.entity_types().iter().map(move |def| (p.name(), def)));
880    khive_types::EntityTypeRegistry::check_extra_collisions(owned_defs)
881        .map_err(RuntimeError::InvalidInput)
882}
883
884fn find_pack_dependency_cycle(
885    packs: &[Box<dyn PackRuntime>],
886    name_to_idx: &HashMap<&str, usize>,
887    cycle_nodes: &HashSet<usize>,
888) -> Vec<String> {
889    fn visit(
890        idx: usize,
891        packs: &[Box<dyn PackRuntime>],
892        name_to_idx: &HashMap<&str, usize>,
893        cycle_nodes: &HashSet<usize>,
894        visiting: &mut Vec<usize>,
895        visited: &mut HashSet<usize>,
896    ) -> Option<Vec<String>> {
897        if let Some(pos) = visiting.iter().position(|&seen| seen == idx) {
898            let mut cycle: Vec<String> = visiting[pos..]
899                .iter()
900                .map(|&i| packs[i].name().to_string())
901                .collect();
902            cycle.push(packs[idx].name().to_string());
903            return Some(cycle);
904        }
905        if !visited.insert(idx) {
906            return None;
907        }
908        visiting.push(idx);
909        for &req in packs[idx].requires() {
910            let Some(&dep_idx) = name_to_idx.get(req) else {
911                continue;
912            };
913            if cycle_nodes.contains(&dep_idx) {
914                if let Some(cycle) =
915                    visit(dep_idx, packs, name_to_idx, cycle_nodes, visiting, visited)
916                {
917                    return Some(cycle);
918                }
919            }
920        }
921        visiting.pop();
922        None
923    }
924
925    let mut visited = HashSet::new();
926    for &idx in cycle_nodes {
927        let mut visiting = Vec::new();
928        if let Some(cycle) = visit(
929            idx,
930            packs,
931            name_to_idx,
932            cycle_nodes,
933            &mut visiting,
934            &mut visited,
935        ) {
936            return cycle;
937        }
938    }
939    cycle_nodes
940        .iter()
941        .map(|&idx| packs[idx].name().to_string())
942        .collect()
943}
944
945impl Default for VerbRegistryBuilder {
946    fn default() -> Self {
947        Self::new()
948    }
949}
950
951/// Immutable registry that dispatches verb calls to registered packs.
952///
953/// Clone is cheap (Arc-wrapped). Constructed via `VerbRegistryBuilder`.
954#[derive(Clone)]
955pub struct VerbRegistry {
956    packs: std::sync::Arc<Vec<Box<dyn PackRuntime>>>,
957    /// Pack-level by-ID resolvers, in registration order.
958    resolvers: std::sync::Arc<Vec<(String, Box<dyn PackByIdResolver>)>>,
959    gate: GateRef,
960    default_namespace: String,
961    /// Operator-configured read-visibility set (ADR-007 Rev 4 Rule 3b).
962    ///
963    /// On the default (no explicit `namespace=` param) dispatch path, reads fan
964    /// out over `['local'] ∪ visible_namespaces`. Writes are unaffected — they
965    /// still pin to `'local'`. An explicit `namespace=` request param is a
966    /// precise single-namespace escape and is not widened by this set.
967    visible_namespaces: Vec<Namespace>,
968    /// Configured actor identity label (ADR-057). When `Some`, dispatch mints
969    /// tokens carrying this actor so that `comm.inbox` applies the `to_actor`
970    /// filter. When `None`, tokens carry `ActorRef::anonymous()` (party-line).
971    actor_id: Option<String>,
972    /// Audit event sink — `None` means tracing-only (v0.2 default).
973    event_store: Option<Arc<dyn EventStore>>,
974    /// Distinguishes ordinary tracing-only construction from a sink omitted
975    /// deliberately because its configured backend is read-only.
976    audit_store_read_only: bool,
977    /// Post-dispatch hook: `None` means no real-time observation.
978    dispatch_hook: Option<Arc<dyn DispatchHook>>,
979    /// Names of all `Visibility::Verb` handlers across all packs, precomputed
980    /// once at `build()` time. Used only to render the unknown-verb error
981    /// message — the pack set is fixed after construction, so there is no
982    /// need to re-scan every pack's handlers on every miss.
983    available_verbs: Arc<Vec<&'static str>>,
984    /// Recently-referenced ring (unified-verb draft ADR, Slice 1). Daemon-warm,
985    /// actor-scoped, never persisted — see `crate::reference_ring`. Shared
986    /// across every clone of this registry via the `Arc`, so admissions made
987    /// by one dispatch are visible to the next on the same warm daemon.
988    reference_ring: Arc<crate::reference_ring::ReferenceRing>,
989    /// ADR-133 audit-batch seam. `None` exactly when `event_store` is
990    /// `None` — no store configured means no seam to construct, and every
991    /// audit call site falls back to its pre-ADR-133 tracing-only/no-op
992    /// path.
993    audit_batch: Option<Arc<crate::audit_batch::AuditBatch>>,
994}
995
996/// Result of an operation handled outside normal pack dispatch, paired with
997/// typed transport metadata that must survive the gate/audit boundary.
998///
999/// The canonical `result` remains the value used for audit accounting. The
1000/// metadata is returned to the intercepting transport without being smuggled
1001/// through a mutex side channel or folded into the verb's public result shape.
1002#[derive(Debug, Clone, PartialEq)]
1003pub struct InterceptedDispatchResult<M> {
1004    /// Canonical verb result used for audit and resource accounting.
1005    pub result: Value,
1006    /// Transport-owned metadata that must accompany the canonical result.
1007    pub metadata: M,
1008}
1009
1010impl<M> InterceptedDispatchResult<M> {
1011    /// Pair a canonical result with its typed transport metadata.
1012    pub fn new(result: Value, metadata: M) -> Self {
1013        Self { result, metadata }
1014    }
1015}
1016
1017/// Per-request identity context that overrides a [`VerbRegistry`]'s
1018/// construction-baked `default_namespace` / `actor_id` / `visible_namespaces`
1019/// for exactly one [`VerbRegistry::dispatch_with_identity`] call (ADR-096
1020/// Fork 1 — warm-daemon per-request identity).
1021///
1022/// A single warm registry is built once with a baked identity, but must be
1023/// able to serve requests whose caller resolved a *different* attribution
1024/// identity (e.g. a different project-local `[actor]`) without a cold
1025/// fallback and without mis-stamping writes under the registry's own baked
1026/// actor. Supplying `Some(RequestIdentity { .. })` threads the caller's
1027/// identity through token minting for that one call; the registry's fields
1028/// (and every other in-flight call) are untouched. `None` is exactly
1029/// [`VerbRegistry::dispatch`] — the baked scalars apply, unchanged from
1030/// before this type existed.
1031#[derive(Debug, Clone, Default)]
1032pub struct RequestIdentity {
1033    /// Storage/gate default namespace for this request (used when the verb's
1034    /// own params carry no explicit `namespace` field). Overrides
1035    /// `VerbRegistry::default_namespace`.
1036    pub namespace: String,
1037    /// Write-stamp / gate actor label for this request (ADR-057). Overrides
1038    /// `VerbRegistry::actor_id`. `None` mints `ActorRef::anonymous()`, same
1039    /// as an unconfigured baked `actor_id`.
1040    pub actor_id: Option<String>,
1041    /// Extra read-visibility namespaces for this request (ADR-007 Rev 4 Rule
1042    /// 3b). Overrides `VerbRegistry::visible_namespaces`. Entries that fail
1043    /// `Namespace::parse` are skipped with a `tracing::warn!` rather than
1044    /// failing the whole request — a single malformed visibility entry from a
1045    /// caller-supplied frame must not block dispatch.
1046    pub visible_namespaces: Vec<String>,
1047    /// Opaque process provenance resolved by the originating request process.
1048    /// `None` means the origin did not set one; a warm daemon must not replace
1049    /// it with its own process environment. This field is attribution-only and
1050    /// never participates in the gate or token authority.
1051    pub process_ref: Option<String>,
1052    /// Caller-supplied correlation id for this request (khive#948), carried
1053    /// unchanged from the daemon frame's `request_id` field. Every operation
1054    /// in one batch or chain receives the same value: it is a request-group
1055    /// selector, never an operation-unique id. Stamped into the audit event's
1056    /// `resource.request_id` on every outcome (success, error, and denied) so
1057    /// a client can join its own pre-send sample to all server-side audit rows
1058    /// for that request. `None` means the caller
1059    /// supplied no id (a pre-#948 client, or an internal/non-benchmark
1060    /// caller) — the audit row then carries no `request_id` key at all.
1061    pub request_id: Option<u64>,
1062}
1063
1064impl RequestIdentity {
1065    /// Reconstruct the effective principal and namespace scope carried by an
1066    /// already-authorized token for a nested registry dispatch.
1067    ///
1068    /// Cross-pack calls must still pass through the registry Gate, but using
1069    /// the registry's construction-baked identity would silently replace a
1070    /// warm daemon request's actor and visibility (ADR-096). This projection
1071    /// preserves the token's exact primary namespace, actor, and read-visible
1072    /// namespaces, and the origin's process provenance rider. A
1073    /// `NamespaceToken` does not carry the ingress correlation id, so nested
1074    /// calls intentionally use `request_id: None`; `process_ref` IS carried by
1075    /// the token (ADR-096: an absent value stays absent, a present origin
1076    /// rider survives nested dispatch without reading the daemon
1077    /// environment).
1078    pub fn from_token(token: &NamespaceToken) -> Self {
1079        Self {
1080            namespace: token.namespace().as_str().to_string(),
1081            actor_id: token.actor().binding_id().map(str::to_string),
1082            visible_namespaces: token
1083                .visible_namespaces()
1084                .iter()
1085                .map(|namespace| namespace.as_str().to_string())
1086                .collect(),
1087            process_ref: token.process_ref().map(str::to_owned),
1088            request_id: None,
1089        }
1090    }
1091}
1092
1093/// A non-blank, out-of-band authenticated principal for [`VerbRegistry::dispatch_as`].
1094///
1095/// Embedding hosts authenticate a principal through their own channel (not the
1096/// request DSL) and then need that principal to become the effective actor
1097/// for one dispatch. The constructor rejects an empty or whitespace-only
1098/// identifier so an authentication-integration failure (an empty subject)
1099/// fails closed at construction time instead of silently resolving to the
1100/// anonymous/local actor at dispatch time — see [`crate::actor_identity::resolve_actor`].
1101#[derive(Debug, Clone, PartialEq, Eq)]
1102pub struct VerifiedActor(String);
1103
1104impl VerifiedActor {
1105    /// Validate and wrap a verified principal identifier.
1106    ///
1107    /// Returns `RuntimeError::InvalidInput` when `id` is empty or contains
1108    /// only whitespace.
1109    pub fn new(id: impl Into<String>) -> Result<Self, RuntimeError> {
1110        let id = id.into();
1111        if id.trim().is_empty() {
1112            return Err(RuntimeError::InvalidInput(
1113                "VerifiedActor: identifier must not be empty or whitespace-only".to_string(),
1114            ));
1115        }
1116        Ok(Self(id))
1117    }
1118
1119    /// Borrow the validated identifier.
1120    pub fn as_str(&self) -> &str {
1121        &self.0
1122    }
1123
1124    fn into_inner(self) -> String {
1125        self.0
1126    }
1127}
1128
1129/// Error returned by [`VerbRegistry::apply_schema_plans_with_map`] when two
1130/// packs on the same backend declare the same auxiliary table (ADR-028 §7).
1131#[derive(Debug)]
1132pub struct PackSchemaCollisionError {
1133    /// First pack to declare the table.
1134    pub pack_a: &'static str,
1135    /// Second pack that collides with `pack_a`.
1136    pub pack_b: &'static str,
1137    /// Table name or DDL error description.
1138    pub table: String,
1139}
1140
1141impl std::fmt::Display for PackSchemaCollisionError {
1142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1143        if self.pack_a == self.pack_b {
1144            write!(
1145                f,
1146                "pack schema boot failure for pack {:?}: {}",
1147                self.pack_a, self.table
1148            )
1149        } else {
1150            write!(
1151                f,
1152                "pack schema collision: packs {:?} and {:?} both declare table {:?} \
1153                 on the same backend — move one pack to a separate backend or rename the table",
1154                self.pack_a, self.pack_b, self.table
1155            )
1156        }
1157    }
1158}
1159
1160impl std::error::Error for PackSchemaCollisionError {}
1161
1162/// Extract table names from a single DDL statement.
1163///
1164/// Handles `CREATE TABLE IF NOT EXISTS`, `CREATE TABLE`, and
1165/// `CREATE VIRTUAL TABLE IF NOT EXISTS`, `CREATE VIRTUAL TABLE`.
1166/// Returns an empty Vec when no table name is found (e.g. index DDL).
1167fn extract_table_names(stmt: &str) -> Vec<String> {
1168    let normalized = stmt.split_whitespace().collect::<Vec<_>>().join(" ");
1169    let upper = normalized.to_ascii_uppercase();
1170    let table_name = if let Some(rest) = upper.strip_prefix("CREATE VIRTUAL TABLE IF NOT EXISTS ") {
1171        rest.split_whitespace().next()
1172    } else if let Some(rest) = upper.strip_prefix("CREATE VIRTUAL TABLE ") {
1173        rest.split_whitespace().next()
1174    } else if let Some(rest) = upper.strip_prefix("CREATE TABLE IF NOT EXISTS ") {
1175        rest.split_whitespace().next()
1176    } else if let Some(rest) = upper.strip_prefix("CREATE TABLE ") {
1177        rest.split_whitespace().next()
1178    } else {
1179        None
1180    };
1181    match table_name {
1182        Some(name) => {
1183            let clean = name.trim_matches(|c: char| c == '(' || c == ';');
1184            if clean.is_empty() {
1185                vec![]
1186            } else {
1187                vec![clean.to_ascii_lowercase()]
1188            }
1189        }
1190        None => vec![],
1191    }
1192}
1193
1194/// Render an [`EndpointKind`] as the `"<substrate>:<kind>"` label used in
1195/// `link(help=true)`'s `endpoint_rules` table.
1196fn endpoint_kind_label(kind: &EndpointKind) -> String {
1197    match kind {
1198        EndpointKind::EntityOfKind(k) => format!("entity:{k}"),
1199        EndpointKind::NoteOfKind(k) => format!("note:{k}"),
1200        EndpointKind::EntityOfType { kind, entity_type } => {
1201            format!("entity:{kind}({entity_type})")
1202        }
1203    }
1204}
1205
1206/// Relations `validate_edge_relation_endpoints`
1207/// (`crates/khive-runtime/src/operations.rs`) resolves in its own dedicated
1208/// branch — before the generic pack-rule branch (`pack_rule_allows`) is ever
1209/// reached. For these three relations the validator additionally accepts
1210/// any `note -> note` pair unconditionally, regardless of note kind
1211/// (ADR-002 §"Versioning" and §"Epistemic"), and never consults pack
1212/// `EDGE_RULES` at all, on either substrate.
1213pub(crate) const SPECIAL_RELATIONS: &[khive_types::EdgeRelation] = &[
1214    khive_types::EdgeRelation::Supersedes,
1215    khive_types::EdgeRelation::Supports,
1216    khive_types::EdgeRelation::Refutes,
1217];
1218
1219pub(crate) fn is_special_relation(relation: khive_types::EdgeRelation) -> bool {
1220    SPECIAL_RELATIONS.contains(&relation)
1221}
1222
1223/// Compose the full per-relation endpoint allowlist surfaced by
1224/// `link(help=true)` (issue #964).
1225///
1226/// Combines the base entity-to-entity endpoint contract
1227/// (`operations::base_entity_endpoint_rules`) with every loaded pack's
1228/// additive `EDGE_RULES`, the unconditional `note -> note` allowance for the
1229/// three special relations (`supersedes` / `supports` / `refutes` —
1230/// `operations.rs`'s dedicated special-relation branch), and the
1231/// `annotates` note-to-any special case — the exact same sources
1232/// `valid_relations_for_entity_pair` (`khive-pack-kg`) consults when
1233/// enriching a rejected `link` call, so a caller reading this table cannot
1234/// diverge from what the validator itself accepts.
1235///
1236/// Pack `EDGE_RULES` for a special relation are deliberately excluded: the
1237/// validator's special-relation branch returns before `pack_rule_allows` is
1238/// ever reached (`operations.rs`), so advertising such a rule here would
1239/// claim enforcement that never actually happens.
1240fn edge_endpoint_table(packs: &[Box<dyn PackRuntime>]) -> Vec<Value> {
1241    let mut rows: Vec<Value> = crate::operations::base_entity_endpoint_rules()
1242        .iter()
1243        .map(|(src, rel, tgt)| {
1244            serde_json::json!({
1245                "relation": rel.as_str(),
1246                "source": format!("entity:{src}"),
1247                "target": format!("entity:{tgt}"),
1248            })
1249        })
1250        .collect();
1251
1252    for rel in SPECIAL_RELATIONS {
1253        rows.push(serde_json::json!({
1254            "relation": rel.as_str(),
1255            "source": "note:*",
1256            "target": "note:*",
1257        }));
1258    }
1259
1260    for pack in packs.iter() {
1261        for rule in pack.edge_rules().iter() {
1262            if is_special_relation(rule.relation) {
1263                continue;
1264            }
1265            rows.push(serde_json::json!({
1266                "relation": rule.relation.as_str(),
1267                "source": endpoint_kind_label(&rule.source),
1268                "target": endpoint_kind_label(&rule.target),
1269            }));
1270        }
1271    }
1272
1273    rows.push(serde_json::json!({
1274        "relation": "annotates",
1275        "source": "note:*",
1276        "target": "any (entity, note, edge, or event)",
1277    }));
1278
1279    rows
1280}
1281
1282impl VerbRegistry {
1283    /// This registry's construction-baked default namespace.
1284    ///
1285    /// Used as the fallback when a request carries no [`RequestIdentity`]
1286    /// override (ADR-096 Fork 1) and by transports that need to advertise
1287    /// their own resolved identity when forwarding to a warm daemon.
1288    pub fn default_namespace(&self) -> &str {
1289        &self.default_namespace
1290    }
1291
1292    /// This registry's construction-baked actor identity label, if configured
1293    /// (ADR-057). `None` means dispatch mints `ActorRef::anonymous()` absent a
1294    /// per-request [`RequestIdentity`] override (ADR-096 Fork 1).
1295    pub fn actor_id(&self) -> Option<&str> {
1296        self.actor_id.as_deref()
1297    }
1298
1299    /// This registry's construction-baked extra read-visibility namespaces
1300    /// (ADR-007 Rev 4 Rule 3b), used absent a per-request [`RequestIdentity`]
1301    /// override (ADR-096 Fork 1).
1302    pub fn visible_namespaces(&self) -> &[Namespace] {
1303        &self.visible_namespaces
1304    }
1305
1306    /// This registry's configured audit `EventStore`, if any (ADR-094).
1307    ///
1308    /// Lets background tasks that hold a `VerbRegistry` but do not go through
1309    /// `dispatch` (e.g. the email channel poll loop) append best-effort
1310    /// lifecycle events to the same sink gate-check audit rows use, without
1311    /// threading a second `Option<Arc<dyn EventStore>>` field through every
1312    /// caller. `None` means either the historical tracing-only default or an
1313    /// intentionally read-only audit backend; callers that need to distinguish
1314    /// those cases use [`Self::audit_persistence_advisory`].
1315    pub fn event_store(&self) -> Option<Arc<dyn EventStore>> {
1316        self.event_store.clone()
1317    }
1318
1319    /// Process-lifetime audit-batch health counters for this registry's
1320    /// ADR-133 seam, if one is configured. `None` exactly when
1321    /// [`Self::event_store`] is `None` — the same condition under which no
1322    /// batch exists to report on. The `db_diagnostics` verb feeds this into
1323    /// `KhiveRuntime::db_diagnostics_with_audit_metrics` so an operator can
1324    /// see flush failures and pure-observability degradation instead of the
1325    /// permanently-unavailable placeholder a bare `KhiveRuntime` reports.
1326    ///
1327    /// `admission_refused_obligations` and `admission_unresolved_obligations`
1328    /// are sourced separately from [`audit_admission_refused_obligation_count`]
1329    /// and [`audit_admission_unresolved_obligation_count`] rather than from
1330    /// `batch.health_metrics()`: they count a decision made in
1331    /// `append_audit_event_best_effort` (ADR-103 Amendment 3 / ADR-133
1332    /// Amendment 1), not a property of the batch itself, so they are
1333    /// process-wide like the rest of this struct's fields rather than
1334    /// per-`AuditBatch`.
1335    pub fn audit_batch_metrics(&self) -> Option<khive_db::diagnostics::RuntimeAuditBatchMetrics> {
1336        self.audit_batch.as_ref().map(|batch| {
1337            let m = batch.health_metrics();
1338            khive_db::diagnostics::RuntimeAuditBatchMetrics {
1339                flush_failures: m.flush_failures,
1340                degraded_rows: m.degraded_rows,
1341                degraded: m.degraded,
1342                admission_refused_obligations: audit_admission_refused_obligation_count(),
1343                admission_unresolved_obligations: audit_admission_unresolved_obligation_count(),
1344            }
1345        })
1346    }
1347
1348    /// Test/diagnostic-only accessor for the underlying ADR-133 audit-batch
1349    /// seam. `None` when no `EventStore` was configured (the batch is lazily
1350    /// constructed from one). Exposed so admission-pressure mechanism tests
1351    /// can saturate and drain the SAME instance a real dispatch uses
1352    /// (khive#2117, khive#2147, khive#2208, khive#2217) instead of testing a
1353    /// look-alike.
1354    pub fn audit_batch_handle(&self) -> Option<Arc<crate::audit_batch::AuditBatch>> {
1355        self.audit_batch.clone()
1356    }
1357
1358    /// Stop admitting new audit rows and wait for every already-accepted row
1359    /// to reach a terminal state (ADR-133).
1360    ///
1361    /// A no-op returning `Ok(())` when no `EventStore` — and therefore no
1362    /// audit-batch seam — is configured. Callers that own this registry's
1363    /// shutdown sequence should call this before tearing down the writer or
1364    /// database so no accepted audit row is silently dropped mid-flight.
1365    pub async fn shutdown_audit_batch(
1366        &self,
1367    ) -> Result<(), crate::audit_batch::AuditTerminalReason> {
1368        use crate::audit_batch::AuditBatchControl;
1369        match &self.audit_batch {
1370            Some(audit_batch) => audit_batch.close_and_drain().await,
1371            None => Ok(()),
1372        }
1373    }
1374
1375    /// Advisory for a dispatch whose configured audit sink is read-only.
1376    ///
1377    /// The MCP transport places this beside successful per-operation results;
1378    /// `None` means audit persistence is configured normally or was never
1379    /// configured at all.
1380    pub fn audit_persistence_advisory(&self) -> Option<Value> {
1381        self.audit_store_read_only.then(|| {
1382            serde_json::json!({
1383                "code": AUDIT_PERSISTENCE_SKIPPED_READ_ONLY,
1384                "severity": "warning",
1385                "component": "audit_event_store",
1386                "reason": "read_only_backend",
1387                "message": "operation completed, but its dispatch audit event was not persisted because the audit backend is read-only",
1388            })
1389        })
1390    }
1391
1392    /// Explicit, fail-closed opt-in for admission-pressure audit degradation
1393    /// (khive#2147/khive#2217). `VerbCategory::Assertive` alone is NOT a
1394    /// sound proxy for "safe to drop this dispatch's own audit row under
1395    /// audit-lane admission pressure": several Assertive handlers have
1396    /// their own accounting-bearing side effects. Two known examples,
1397    /// deliberately excluded here:
1398    /// - `memory.recall` dispatches `brain.record_serve` as a background
1399    ///   write; degrading `memory.recall`'s row raises the risk that a
1400    ///   serve goes unaccounted for if the ledger dispatch itself later
1401    ///   also races admission pressure.
1402    /// - `db_diagnostics` may backfill WAL frames via a PASSIVE checkpoint
1403    ///   probe — physical I/O, not a pure in-memory read.
1404    ///
1405    /// What membership here means, precisely: the verb performs no domain
1406    /// mutation, so its OWN per-dispatch audit/accounting row may be dropped
1407    /// under transient admission pressure without the caller losing a
1408    /// meaningful result (ADR-103 Amendment 3, ADR-133 Amendment 1). It does
1409    /// NOT mean the handler is free of every event-plane write: `search`
1410    /// still fires its own best-effort `SearchExecuted` telemetry, and
1411    /// `context` still records a one-time `ConfigLocked` event, both on
1412    /// independent code paths this mechanism never touches — those events
1413    /// commit or fail on their own terms, unaffected by whether this
1414    /// dispatch's own audit row degrades.
1415    ///
1416    /// Every entry here MUST be declared `VerbCategory::Assertive` in
1417    /// `khive-pack-kg/src/handler_defs.rs` — enforced by the
1418    /// `admission_degrade_safe_verbs_are_registered_assertive` census test
1419    /// below, which re-derives the classification from that file's live
1420    /// source rather than trusting this list's own claim. Adding a verb
1421    /// from a different pack requires extending that test's source scan,
1422    /// not just this list.
1423    const ADMISSION_DEGRADE_SAFE_VERBS: &'static [&'static str] = &[
1424        "get",
1425        "list",
1426        "stats",
1427        "search",
1428        "neighbors",
1429        "traverse",
1430        "context",
1431        "query",
1432        "resolve",
1433        "whoami",
1434        "verbs",
1435    ];
1436
1437    /// Whether `verb` is both declared [`VerbCategory::Assertive`] (the
1438    /// speech-act tag for handlers that "retrieve and present facts" rather
1439    /// than committing a domain change) AND explicitly opted in to
1440    /// admission-pressure audit degradation via
1441    /// [`Self::ADMISSION_DEGRADE_SAFE_VERBS`]. Unknown or non-opted-in verbs
1442    /// are conservatively `false` — fail-closed, so a new Assertive handler
1443    /// hard-fails its audit obligation like any write until someone
1444    /// deliberately reviews it and adds it to the allowlist.
1445    ///
1446    /// Used only to decide whether a dispatch's own audit-obligation row may
1447    /// degrade to best-effort on transient audit-lane admission pressure
1448    /// (`append_audit_event_best_effort`) — a read that performed no domain
1449    /// write must not fail the caller just because the audit lane is
1450    /// momentarily saturated. Never used for permission checking, transport
1451    /// routing, or return-shape selection.
1452    fn admission_degrade_safe(&self, verb: &str) -> bool {
1453        if !Self::ADMISSION_DEGRADE_SAFE_VERBS.contains(&verb) {
1454            return false;
1455        }
1456        self.packs
1457            .iter()
1458            .find_map(|pack| pack.handlers().iter().find(|h| h.name == verb))
1459            .is_some_and(|handler| handler.category == VerbCategory::Assertive)
1460    }
1461
1462    /// Return the help schema envelope for a verb.
1463    ///
1464    /// Walks registered packs for the first matching `HandlerDef` and returns a
1465    /// structured JSON envelope. Subhandlers carry `callable_via_mcp: false`.
1466    /// Every envelope carries the shared `identifier_resolution` contract.
1467    /// `link`'s envelope additionally carries `endpoint_rules` — the composed
1468    /// per-relation source/target allowlist (issue #964) — so batch callers can
1469    /// defer to the kernel's own table instead of re-implementing it locally.
1470    /// Unknown verbs return `RuntimeError::InvalidInput`. Full shape documented
1471    /// in `docs/protocol.md` §Request Schema.
1472    pub fn describe_verb(&self, verb: &str) -> Result<Value, RuntimeError> {
1473        for pack in self.packs.iter() {
1474            for handler in pack.handlers().iter() {
1475                if handler.name == verb {
1476                    let category = format!("{:?}", handler.category);
1477                    let params_arr: Vec<Value> = handler
1478                        .params
1479                        .iter()
1480                        .map(|p| {
1481                            serde_json::json!({
1482                                "name": p.name,
1483                                "type": p.param_type,
1484                                "required": p.required,
1485                                "description": p.description,
1486                            })
1487                        })
1488                        .collect();
1489                    // Subhandlers are not callable via the MCP request surface;
1490                    // the help payload must match the behaviour the dispatch
1491                    // path enforces so callers reading `help=true` before
1492                    // probing see accurate availability.
1493                    if matches!(handler.visibility, Visibility::Subhandler) {
1494                        return Ok(serde_json::json!({
1495                            "verb": verb,
1496                            "pack": pack.name(),
1497                            "description": handler.description,
1498                            "category": category,
1499                            "params": params_arr,
1500                            "identifier_resolution": identifier_resolution_help(),
1501                            "visibility": "internal",
1502                            "callable_via_mcp": false,
1503                            "note": "This is an internal subhandler. Calling it via the MCP \
1504                                     request surface returns permission denied. It can only be \
1505                                     invoked by internal runtime callers.",
1506                        }));
1507                    }
1508                    let mut envelope = serde_json::json!({
1509                        "verb": verb,
1510                        "pack": pack.name(),
1511                        "description": handler.description,
1512                        "category": category,
1513                        "params": params_arr,
1514                        "identifier_resolution": identifier_resolution_help(),
1515                    });
1516                    if verb == "link" {
1517                        envelope["endpoint_rules"] = Value::Array(edge_endpoint_table(&self.packs));
1518                    }
1519                    return Ok(envelope);
1520                }
1521            }
1522        }
1523        // Verb-visibility handler names, precomputed at build() time (internal
1524        // subhandlers are excluded so they are not advertised in the
1525        // unknown-verb error).
1526        Err(RuntimeError::UnknownVerb(format!(
1527            "unknown verb {verb:?}; available: {}",
1528            self.available_verbs.join(", ")
1529        )))
1530    }
1531
1532    /// Check whether the gate permits writes into `ns`.
1533    ///
1534    /// Performs a gate evaluation with verb `"authorize"` before any background
1535    /// loop is spawned (ADR-056 §6).  Returns `Ok(())` when the gate allows the
1536    /// namespace, or `Err(RuntimeError::PermissionDenied{..})` when denied.
1537    /// Gate errors (implementation failures) are surfaced as
1538    /// `RuntimeError::Internal` carrying the stable classified reason; the
1539    /// bounded, masked backend detail goes to the server-side log here, since
1540    /// callers log the returned error.
1541    pub fn authorize_namespace(&self, ns: Namespace) -> Result<(), RuntimeError> {
1542        let actor = crate::actor_identity::resolve_actor(self.actor_id.as_deref());
1543        let req = GateRequest::new(actor, ns, "authorize", serde_json::Value::Null);
1544        match self.gate.check(&req) {
1545            Ok(decision) if decision.is_allow() => Ok(()),
1546            Ok(GateDecision::Deny { reason }) => Err(RuntimeError::PermissionDenied {
1547                verb: "authorize".to_string(),
1548                reason,
1549            }),
1550            Ok(_) => Err(RuntimeError::PermissionDenied {
1551                verb: "authorize".to_string(),
1552                reason: "gate denied".to_string(),
1553            }),
1554            Err(e) => {
1555                tracing::warn!(
1556                    error = %crate::secret_gate::bounded_masked_log_text(&e.to_string()),
1557                    "authorize_namespace: gate check failed (fail-closed)"
1558                );
1559                Err(RuntimeError::Internal(format!(
1560                    "gate error: {}",
1561                    e.wire_reason()
1562                )))
1563            }
1564        }
1565    }
1566
1567    /// Gate and execute an operation handled outside normal pack dispatch.
1568    ///
1569    /// Multi-backend transports use this to route an operation through a
1570    /// coordinator while retaining [`Self::dispatch_with_identity`]'s gate and
1571    /// audit lifecycle. Deny is authoritative, gate errors fail closed, and an
1572    /// allowed audit is persisted after the intercepted operation resolves so
1573    /// its outcome and duration reflect the operation result. Successful
1574    /// `git.digest` interception uses the same strict durable-receipt exception
1575    /// as normal pack dispatch.
1576    pub async fn dispatch_intercepted_with_identity<F, Fut>(
1577        &self,
1578        verb: &str,
1579        params: &Value,
1580        identity: Option<&RequestIdentity>,
1581        dispatch: F,
1582    ) -> Result<Value, RuntimeError>
1583    where
1584        F: FnOnce(Namespace) -> Fut,
1585        Fut: std::future::Future<Output = Result<Value, RuntimeError>>,
1586    {
1587        self.dispatch_intercepted_with_metadata_with_identity(
1588            verb,
1589            params,
1590            identity,
1591            |namespace| async move {
1592                dispatch(namespace)
1593                    .await
1594                    .map(|result| InterceptedDispatchResult::new(result, ()))
1595            },
1596        )
1597        .await
1598        .map(|outcome| outcome.result)
1599    }
1600
1601    /// Gate and execute an intercepted operation whose transport needs typed
1602    /// metadata in addition to the canonical verb result.
1603    ///
1604    /// Audit accounting always receives `outcome.result`; `outcome.metadata`
1605    /// crosses the dispatch seam unchanged for the transport to place beside
1606    /// that result in its own envelope.
1607    pub async fn dispatch_intercepted_with_metadata_with_identity<M, F, Fut>(
1608        &self,
1609        verb: &str,
1610        params: &Value,
1611        identity: Option<&RequestIdentity>,
1612        dispatch: F,
1613    ) -> Result<InterceptedDispatchResult<M>, RuntimeError>
1614    where
1615        F: FnOnce(Namespace) -> Fut,
1616        Fut: std::future::Future<Output = Result<InterceptedDispatchResult<M>, RuntimeError>>,
1617    {
1618        let request_id = identity.and_then(|id| id.request_id);
1619        let gate_req = self.gate_request_with_identity(verb, params, identity)?;
1620        let mut deferred_audit = match self.gate.check(&gate_req) {
1621            Ok(decision) => {
1622                let audit = AuditEvent::from_check(&gate_req, &decision, self.gate.impl_name());
1623                tracing::info!(
1624                    audit_event = %serde_json::to_string(&audit)
1625                        .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
1626                    "gate.check"
1627                );
1628                if let GateDecision::Deny { reason } = decision {
1629                    if let Some(store) = &self.event_store {
1630                        let event = build_audit_storage_event(
1631                            &gate_req,
1632                            &audit,
1633                            EventOutcome::Denied,
1634                            Some(crate::cost_unit::base_resource_payload(request_id)),
1635                        );
1636                        // The dispatch already returns `PermissionDenied`
1637                        // below regardless of whether this row commits — a
1638                        // deny never reports success — so a persistent
1639                        // commit failure here has no caller-visible outcome
1640                        // to fold into; it is still logged and counted by
1641                        // the helper.
1642                        let _ = append_audit_event_best_effort(
1643                            self.audit_batch.as_ref(),
1644                            store,
1645                            event,
1646                            verb,
1647                            crate::audit_batch::AuditProducer::GateDenied,
1648                            false,
1649                        )
1650                        .await;
1651                    }
1652                    return Err(RuntimeError::PermissionDenied {
1653                        verb: verb.to_string(),
1654                        reason,
1655                    });
1656                }
1657                Some(audit)
1658            }
1659            Err(err) => {
1660                return Err(self
1661                    .gate_unavailable_error(&gate_req, &err, request_id)
1662                    .await);
1663            }
1664        };
1665
1666        let started = Instant::now();
1667        let mut result = dispatch(gate_req.namespace.clone()).await;
1668        let duration_us = started.elapsed().as_micros() as i64;
1669        let receipt_outcome = if verb == "git.digest" && result.is_ok() {
1670            let resource = result.as_ref().ok().map(|outcome| {
1671                crate::cost_unit::resource_payload(
1672                    verb,
1673                    &gate_req.args,
1674                    &outcome.result,
1675                    || 0,
1676                    request_id,
1677                )
1678            });
1679            // The receipt helper operates on the canonical verb result. Move
1680            // that value out temporarily so it can turn receipt failures into
1681            // the outer dispatch error without discarding successful typed
1682            // transport metadata.
1683            let mut receipt_result: Result<Value, RuntimeError> = match result.as_mut() {
1684                Ok(outcome) => Ok(std::mem::take(&mut outcome.result)),
1685                Err(_) => unreachable!("git.digest receipt path is guarded by result.is_ok()"),
1686            };
1687            let outcome = persist_git_digest_receipt(
1688                self.event_store.as_ref(),
1689                self.audit_batch.as_ref(),
1690                &gate_req,
1691                deferred_audit.as_ref(),
1692                &mut receipt_result,
1693                duration_us,
1694                resource,
1695            )
1696            .await;
1697            match receipt_result {
1698                Ok(receipted_result) => {
1699                    if let Ok(intercepted) = &mut result {
1700                        intercepted.result = receipted_result;
1701                    }
1702                }
1703                Err(error) => result = Err(error),
1704            }
1705            Some(outcome)
1706        } else {
1707            None
1708        };
1709        if receipt_outcome.is_none()
1710            || receipt_outcome == Some(GitDigestReceiptOutcome::BuildRejected)
1711        {
1712            if let Some(audit) = deferred_audit.take() {
1713                let audit_outcome = self
1714                    .persist_intercepted_audit(
1715                        verb,
1716                        &gate_req,
1717                        audit,
1718                        result.as_ref().map(|outcome| &outcome.result),
1719                        duration_us,
1720                        request_id,
1721                    )
1722                    .await;
1723                result = fold_audit_obligation(result, audit_outcome);
1724            }
1725        }
1726        result
1727    }
1728
1729    async fn persist_intercepted_audit(
1730        &self,
1731        verb: &str,
1732        gate_req: &GateRequest,
1733        audit: AuditEvent,
1734        result: Result<&Value, &RuntimeError>,
1735        duration_us: i64,
1736        request_id: Option<u64>,
1737    ) -> Result<(), RuntimeError> {
1738        let Some(store) = &self.event_store else {
1739            return Ok(());
1740        };
1741        let event = match result {
1742            Ok(value) if verb == "link" && gate_req.args.get("links").is_none() => {
1743                let resource = crate::cost_unit::resource_payload(
1744                    verb,
1745                    &gate_req.args,
1746                    value,
1747                    || 0,
1748                    request_id,
1749                );
1750                match link_audit_success_from_result(audit.clone(), value) {
1751                    Some((edge_id, mut payload)) => {
1752                        if let Value::Object(ref mut map) = payload {
1753                            map.insert("resource".to_string(), resource);
1754                        }
1755                        Event::new(
1756                            gate_req.namespace.as_str(),
1757                            gate_req.verb.as_str(),
1758                            EventKind::Audit,
1759                            SubstrateKind::Event,
1760                            format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
1761                        )
1762                        .with_outcome(EventOutcome::Success)
1763                        .with_target(edge_id)
1764                        .with_payload(payload)
1765                        .with_payload_schema_version(2)
1766                        .with_duration_us(duration_us)
1767                    }
1768                    None => build_audit_storage_event(
1769                        gate_req,
1770                        &audit,
1771                        EventOutcome::Success,
1772                        Some(resource),
1773                    )
1774                    .with_duration_us(duration_us),
1775                }
1776            }
1777            Ok(value) => build_audit_storage_event(
1778                gate_req,
1779                &audit,
1780                EventOutcome::Success,
1781                Some(crate::cost_unit::resource_payload(
1782                    verb,
1783                    &gate_req.args,
1784                    value,
1785                    || 0,
1786                    request_id,
1787                )),
1788            )
1789            .with_duration_us(duration_us),
1790            Err(_) => build_audit_storage_event(
1791                gate_req,
1792                &audit,
1793                EventOutcome::Error,
1794                Some(crate::cost_unit::base_resource_payload(request_id)),
1795            )
1796            .with_duration_us(duration_us),
1797        };
1798        let producer = if result.is_ok() {
1799            crate::audit_batch::AuditProducer::DispatchSucceeded
1800        } else {
1801            crate::audit_batch::AuditProducer::DispatchFailed
1802        };
1803        append_audit_event_best_effort(
1804            self.audit_batch.as_ref(),
1805            store,
1806            event,
1807            verb,
1808            producer,
1809            self.admission_degrade_safe(verb),
1810        )
1811        .await
1812    }
1813
1814    fn gate_request_with_identity(
1815        &self,
1816        verb: &str,
1817        params: &Value,
1818        identity: Option<&RequestIdentity>,
1819    ) -> Result<GateRequest, RuntimeError> {
1820        let default_namespace = identity
1821            .map(|id| id.namespace.as_str())
1822            .unwrap_or(self.default_namespace.as_str());
1823        let namespace = resolve_explicit_namespace(params, default_namespace)?;
1824        let actor_id = identity
1825            .map(|id| id.actor_id.as_deref())
1826            .unwrap_or(self.actor_id.as_deref());
1827        let actor = crate::actor_identity::resolve_actor(actor_id);
1828        Ok(GateRequest::new(actor, namespace, verb, params.clone()))
1829    }
1830
1831    async fn gate_unavailable_error(
1832        &self,
1833        gate_req: &GateRequest,
1834        error: &khive_gate::GateError,
1835        request_id: Option<u64>,
1836    ) -> RuntimeError {
1837        let audit = AuditEvent::gate_unavailable(gate_req, self.gate.impl_name());
1838        tracing::info!(
1839            audit_event = %serde_json::to_string(&audit)
1840                .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
1841            "gate.check"
1842        );
1843        tracing::warn!(
1844            verb = %gate_req.verb,
1845            error = %crate::secret_gate::bounded_masked_log_text(&error.to_string()),
1846            "gate check failed (fail-closed)"
1847        );
1848        if let Some(store) = &self.event_store {
1849            let event = build_audit_storage_event(
1850                gate_req,
1851                &audit,
1852                EventOutcome::Error,
1853                Some(crate::cost_unit::base_resource_payload(request_id)),
1854            );
1855            let _ = append_audit_event_best_effort(
1856                self.audit_batch.as_ref(),
1857                store,
1858                event,
1859                gate_req.verb.as_str(),
1860                crate::audit_batch::AuditProducer::GateUnavailable,
1861                false,
1862            )
1863            .await;
1864        }
1865        RuntimeError::GateUnavailable {
1866            verb: gate_req.verb.clone(),
1867            // Caller-visible: a stable, classified reason derived from the
1868            // `GateError` variant only. `error`'s `Display` text is logged
1869            // above (server-side, via `tracing::warn!`) and must never be
1870            // interpolated here — a gate backend's error message can embed
1871            // connection details, addresses, or credentials.
1872            reason: error.wire_reason().to_string(),
1873        }
1874    }
1875
1876    /// Dispatch a verb to the first pack that handles it.
1877    ///
1878    /// Routes through the gate, then invokes the matching pack handler. When
1879    /// `params["help"] == true`, short-circuits to `describe_verb` with no side effects.
1880    /// Gate errors fail closed. Full dispatch flow documented in `docs/protocol.md`.
1881    ///
1882    /// Equivalent to `self.dispatch_with_identity(verb, params, None)` — uses
1883    /// this registry's construction-baked `default_namespace` / `actor_id` /
1884    /// `visible_namespaces`.
1885    pub async fn dispatch(&self, verb: &str, params: Value) -> Result<Value, RuntimeError> {
1886        self.dispatch_with_identity(verb, params, None).await
1887    }
1888
1889    /// Dispatch a verb, optionally overriding this registry's baked identity
1890    /// scalars for exactly this call (ADR-096 Fork 1).
1891    ///
1892    /// `identity = None` behaves exactly like [`Self::dispatch`]. `identity =
1893    /// Some(id)` uses `id.namespace` / `id.actor_id` / `id.visible_namespaces`
1894    /// in place of `self.default_namespace` / `self.actor_id` /
1895    /// `self.visible_namespaces` for this call's namespace resolution, gate
1896    /// request, and token minting. The registry's own fields are never mutated,
1897    /// so concurrent calls with different (or no) identity are independent.
1898    /// See `docs/api/pack.md#dispatch_with_identity` for why this enables one warm
1899    /// registry to serve many attribution identities over a shared backend.
1900    pub async fn dispatch_with_identity(
1901        &self,
1902        verb: &str,
1903        params: Value,
1904        identity: Option<RequestIdentity>,
1905    ) -> Result<Value, RuntimeError> {
1906        // help=true interception: short-circuit before gate/pack.
1907        if params.get("help").and_then(Value::as_bool) == Some(true) {
1908            return self.describe_verb(verb);
1909        }
1910        // Resolve namespace before `params` is moved into pack.dispatch, so the
1911        // post-dispatch hook can reference it.
1912        //
1913        // Absent `namespace` and a present-but-malformed `namespace` are
1914        // different cases. A present non-string value (null, number, bool,
1915        // array, object) is explicit caller input that failed to parse and
1916        // must fail closed, not silently coerce to the default namespace.
1917        // Only a genuinely absent key defaults. Shared with the multi-backend
1918        // coordinator intercept via `resolve_explicit_namespace` so every MCP
1919        // ingress path applies the same fail-closed rule.
1920        let explicit_namespace = params.get("namespace").is_some_and(Value::is_string);
1921        // The caller-supplied correlation id (khive#948), if any. Read once
1922        // here so it is in scope for every audit-append site below,
1923        // including the ones that run before pack dispatch is attempted.
1924        let request_id: Option<u64> = identity.as_ref().and_then(|id| id.request_id);
1925        // Thread the configured actor identity into the gate request so the
1926        // gate can distinguish human vs agent callers at the dispatch seam.
1927        // Resolved once via the shared actor-identity policy and reused for
1928        // token minting below, so the gate's notion of "who is the caller"
1929        // and the storage token's notion can never drift apart.
1930        let gate_req = self.gate_request_with_identity(verb, &params, identity.as_ref())?;
1931        let ns = gate_req.namespace.clone();
1932        let resolved_actor = gate_req.actor.clone();
1933
1934        // Consult the gate.
1935        //
1936        // - Ok(Allow) → proceed to pack dispatch (tracing + optional EventStore).
1937        // - Ok(Deny) → emit audit, persist if store configured, return PermissionDenied.
1938        // - Err(_) → emit an outage audit and return GateUnavailable.
1939        let (gate_blocked, mut deferred_audit) = match self.gate.check(&gate_req) {
1940            Ok(decision) => {
1941                let is_deny = matches!(decision, GateDecision::Deny { .. });
1942
1943                // Emit audit event via tracing.
1944                let audit = AuditEvent::from_check(&gate_req, &decision, self.gate.impl_name());
1945                tracing::info!(
1946                    audit_event = %serde_json::to_string(&audit)
1947                        .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
1948                    "gate.check"
1949                );
1950
1951                // Drain any process-lifetime `OnceLock` config locks queued
1952                // since the last dispatch and persist them as `ConfigLocked`
1953                // events, riding this same audit-persistence gate. The
1954                // namespace/actor stamped on these rows are whichever
1955                // dispatch happens to observe the queue non-empty first:
1956                // an accepted provenance quirk, preferred over threading an
1957                // `EventStore` handle into every synchronous
1958                // `OnceLock::get_or_init` call site. The verb column is NOT
1959                // inherited from that bystander dispatch: a config-lock row
1960                // wearing an operation verb pollutes verb-filtered queries
1961                // (e.g. per-verb receipt counts), so these rows carry their
1962                // own `config.lock` pseudo-verb and remain discoverable by
1963                // `EventKind::ConfigLocked`.
1964                if let Some(store) = &self.event_store {
1965                    if crate::config_ledger::PENDING
1966                        .swap(false, std::sync::atomic::Ordering::AcqRel)
1967                    {
1968                        for (key, value) in crate::config_ledger::drain_config_locked() {
1969                            let payload = serde_json::json!({ "key": key, "value": value });
1970                            let storage_event = Event::new(
1971                                gate_req.namespace.as_str(),
1972                                "config.lock",
1973                                EventKind::ConfigLocked,
1974                                SubstrateKind::Event,
1975                                format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
1976                            )
1977                            .with_payload(payload);
1978                            // ConfigLocked is pure observability: the helper
1979                            // never returns `Err` for it, so there is
1980                            // nothing to fold.
1981                            let _ = append_audit_event_best_effort(
1982                                self.audit_batch.as_ref(),
1983                                store,
1984                                storage_event,
1985                                "config.lock",
1986                                crate::audit_batch::AuditProducer::ConfigLocked,
1987                                false,
1988                            )
1989                            .await;
1990                        }
1991                    }
1992                }
1993
1994                // Every Allow-outcome audit row defers its append until pack
1995                // dispatch returns, so the row can carry the measured
1996                // dispatch time in `duration_us` (persisting before dispatch
1997                // ran always recorded the `Event::new` default of 0). A
1998                // singleton `link` call (no `links` bulk array) additionally
1999                // enriches the deferred row with the created/resolved edge
2000                // fields (schema v2) once dispatch resolves. Denied calls
2001                // have no dispatch to wait for and keep the immediate v1
2002                // append below.
2003                //
2004                // Accepted trade-off for ordinary verbs: a crash between this
2005                // Allow decision and the deferred append loses the audit row.
2006                // `git.digest` narrows the caller-visible contract below: it
2007                // never returns success until the deferred receipt append is
2008                // confirmed, though a process crash can still leave committed
2009                // ingest writes with no response and no completed receipt.
2010                let defer_audit = !is_deny;
2011
2012                // Persist to EventStore immediately only for denied calls.
2013                if !defer_audit {
2014                    if let Some(store) = &self.event_store {
2015                        // ADR-103 Decision (a): the closed `work_class` enum
2016                        // is stamped on every event, denial included -- only
2017                        // `resource.cost_unit` is scoped to a successful
2018                        // dispatch by Amendment 1. `base_resource_payload()`
2019                        // carries `work_class` alone, no `cost_unit` key.
2020                        let storage_event = build_audit_storage_event(
2021                            &gate_req,
2022                            &audit,
2023                            EventOutcome::Denied,
2024                            Some(crate::cost_unit::base_resource_payload(request_id)),
2025                        );
2026                        // As above (line ~1513): this path always returns
2027                        // `PermissionDenied` below regardless, so there is no
2028                        // success outcome to fold a commit failure into.
2029                        let _ = append_audit_event_best_effort(
2030                            self.audit_batch.as_ref(),
2031                            store,
2032                            storage_event,
2033                            verb,
2034                            crate::audit_batch::AuditProducer::GateDenied,
2035                            false,
2036                        )
2037                        .await;
2038                    }
2039                }
2040
2041                let reason = if is_deny {
2042                    let reason = match decision {
2043                        GateDecision::Deny { reason } => reason,
2044                        _ => String::new(),
2045                    };
2046                    Some(reason)
2047                } else {
2048                    None
2049                };
2050                let deferred = if defer_audit { Some(audit) } else { None };
2051                (reason, deferred)
2052            }
2053            Err(err) => {
2054                return Err(self
2055                    .gate_unavailable_error(&gate_req, &err, request_id)
2056                    .await);
2057            }
2058        };
2059
2060        // Hard enforcement: Deny is authoritative.
2061        if let Some(reason) = gate_blocked {
2062            return Err(RuntimeError::PermissionDenied {
2063                verb: verb.to_string(),
2064                reason,
2065            });
2066        }
2067
2068        // Mint the authorized storage token at the dispatch boundary.
2069        //
2070        // Writes pin to `local` by default. Actor identity and config
2071        // `[actor] id` are attribution and gate-context inputs only: they
2072        // never route storage. The explicit `namespace=` request param is a
2073        // precise single-namespace escape: the caller deliberately
2074        // reads/writes exactly that one set; it is NOT widened by `visible_namespaces`.
2075        //
2076        // When actor_id is configured, mint a token carrying that actor
2077        // label so that comm.inbox applies the to_actor filter for directed delivery.
2078        // Otherwise, use ActorRef::anonymous() and inbox falls back to party-line.
2079        // `actor_id_str` already reflects the per-request identity override
2080        // when supplied (resolved above into `resolved_actor`, mirrored into
2081        // the gate request). Reusing the same value here guarantees the
2082        // gate's actor and the storage token's actor can never diverge.
2083        //
2084        // On the default (no explicit `namespace=`) path, the read scope
2085        // widens to `['local'] ∪ visible_namespaces` (baked, or the
2086        // per-request override). `'local'` is always included
2087        // (mint_with_visibility deduplicates). Writes remain pinned to
2088        // `'local'`. Per-actor distinctions use view-layer tag filters
2089        // (assignee, actor_id, from/to), not namespace partitions. `ns`/
2090        // `explicit_namespace` were already validated above: reuse them
2091        // instead of re-reading `params["namespace"]` with `as_str()`, which
2092        // would silently drop malformed non-string values again.
2093        let token = if explicit_namespace {
2094            // Explicit escape: precise single-namespace scope, read+write. NOT widened.
2095            NamespaceToken::mint_with_visibility(ns.clone(), vec![], resolved_actor)
2096        } else {
2097            // Default path: write namespace = local; read scope = ['local'] ∪ visible_namespaces.
2098            let primary = Namespace::local();
2099            let mut extra_visible: Vec<Namespace> = match identity.as_ref() {
2100                Some(id) => id
2101                    .visible_namespaces
2102                    .iter()
2103                    .filter_map(|s| match Namespace::parse(s) {
2104                        Ok(parsed) => Some(parsed),
2105                        Err(e) => {
2106                            tracing::warn!(
2107                                namespace = %s,
2108                                error = %e,
2109                                "dispatch_with_identity: skipping invalid visible_namespace \
2110                                 entry from per-request identity"
2111                            );
2112                            None
2113                        }
2114                    })
2115                    .collect(),
2116                None => self.visible_namespaces.clone(),
2117            };
2118            extra_visible.push(Namespace::local()); // 'local' always readable; mint dedups
2119            NamespaceToken::mint_with_visibility(primary, extra_visible, resolved_actor)
2120        }
2121        .with_process_ref(match identity.as_ref() {
2122            Some(id) => id.process_ref.clone(),
2123            None => crate::config::process_ref_from_env(),
2124        });
2125
2126        for pack in self.packs.iter() {
2127            if let Some(handler_def) = pack.handlers().iter().find(|v| v.name == verb) {
2128                // Strip `namespace` from params before forwarding to packs.
2129                // The registry has already consumed it to mint the NamespaceToken.
2130                //
2131                // Exception: if the handler's own `params` schema declares
2132                // `"namespace"` as a valid field (e.g. brain.bind, brain.unbind,
2133                // brain.bindings, brain.resolve), the field is a *business* argument
2134                // — not a transport routing key — and must be passed through
2135                // unchanged. Stripping it would silently default the binding to the
2136                // "*" wildcard, broadening profile scope across namespaces.
2137                let handler_accepts_namespace =
2138                    handler_def.params.iter().any(|p| p.name == "namespace");
2139                let params = if !handler_accepts_namespace {
2140                    if let Value::Object(mut map) = params {
2141                        map.remove("namespace");
2142                        Value::Object(map)
2143                    } else {
2144                        params
2145                    }
2146                } else {
2147                    params
2148                };
2149                let dispatch_start = Instant::now();
2150                let mut result = pack.dispatch(verb, params, self, &token).await;
2151                let dispatch_us = dispatch_start.elapsed().as_micros() as i64;
2152
2153                // Unlike ordinary audit rows, a successful `git.digest`
2154                // response is returned only after its complete report has
2155                // been durably persisted as a schema-v2 audit receipt. The
2156                // receipt helper borrows the deferred audit row so malformed
2157                // handler output can still fall back to one generic Error
2158                // audit. Handler errors use that same ordinary path below.
2159                let git_digest_receipt_outcome = if verb == "git.digest" && result.is_ok() {
2160                    let resource = result.as_ref().ok().map(|value| {
2161                        crate::cost_unit::resource_payload(
2162                            verb,
2163                            &gate_req.args,
2164                            value,
2165                            || pack.registered_embedding_model_names().len() as i64,
2166                            request_id,
2167                        )
2168                    });
2169                    Some(
2170                        persist_git_digest_receipt(
2171                            self.event_store.as_ref(),
2172                            self.audit_batch.as_ref(),
2173                            &gate_req,
2174                            deferred_audit.as_ref(),
2175                            &mut result,
2176                            dispatch_us,
2177                            resource,
2178                        )
2179                        .await,
2180                    )
2181                } else {
2182                    None
2183                };
2184
2185                // Append the deferred Allow-outcome audit row now that
2186                // dispatch has resolved, so `duration_us` carries the
2187                // measured `dispatch_us` instead of the `Event::new` default
2188                // of 0. A successful singleton `link` call enriches the row
2189                // with the created/resolved edge (schema v2); anything that
2190                // cannot be enriched, or is not a singleton `link` call,
2191                // falls back to the generic v1 audit shape so no audit row
2192                // is ever dropped for the deferred path.
2193                let needs_generic_audit = git_digest_receipt_outcome.is_none()
2194                    || git_digest_receipt_outcome == Some(GitDigestReceiptOutcome::BuildRejected);
2195                if let (true, Some(audit)) = (needs_generic_audit, deferred_audit.take()) {
2196                    if let Some(store) = &self.event_store {
2197                        let is_link_singleton =
2198                            verb == "link" && gate_req.args.get("links").is_none();
2199                        // Read-only pass over `result` first: every arm below
2200                        // only needs `audit_outcome` afterward, and folding a
2201                        // failure into `result` requires a mutable borrow
2202                        // that cannot coexist with the `&result` match below.
2203                        let audit_outcome: Result<(), RuntimeError> = match &result {
2204                            Ok(ok_val) if is_link_singleton => {
2205                                // ADR-103 Amendment 1: `link` (singleton or
2206                                // bulk) has no embedding-bearing path — edges
2207                                // carry no embedded body — so cost_unit is
2208                                // always base_weight("link") alone. The
2209                                // registered-model closure is never invoked
2210                                // (per_item_weight("link", ..) short-circuits
2211                                // to 0 before `model_count` reads it).
2212                                let resource = crate::cost_unit::resource_payload(
2213                                    verb,
2214                                    &gate_req.args,
2215                                    ok_val,
2216                                    || pack.registered_embedding_model_names().len() as i64,
2217                                    request_id,
2218                                );
2219                                match link_audit_success_from_result(audit.clone(), ok_val) {
2220                                    Some((edge_id, mut payload)) => {
2221                                        if let Value::Object(ref mut map) = payload {
2222                                            map.insert("resource".to_string(), resource);
2223                                        }
2224                                        let storage_event = Event::new(
2225                                            gate_req.namespace.as_str(),
2226                                            gate_req.verb.as_str(),
2227                                            EventKind::Audit,
2228                                            SubstrateKind::Event,
2229                                            format!(
2230                                                "{}:{}",
2231                                                gate_req.actor.kind, gate_req.actor.id
2232                                            ),
2233                                        )
2234                                        .with_outcome(EventOutcome::Success)
2235                                        .with_target(edge_id)
2236                                        .with_payload(payload)
2237                                        .with_payload_schema_version(2)
2238                                        .with_duration_us(dispatch_us);
2239                                        append_audit_event_best_effort(
2240                                            self.audit_batch.as_ref(),
2241                                            store,
2242                                            storage_event,
2243                                            verb,
2244                                            crate::audit_batch::AuditProducer::DispatchSucceeded,
2245                                            self.admission_degrade_safe(verb),
2246                                        )
2247                                        .await
2248                                    }
2249                                    None => {
2250                                        tracing::warn!(
2251                                            verb,
2252                                            "link audit v2 enrichment parse failed; \
2253                                             falling back to v1 audit shape"
2254                                        );
2255                                        let storage_event = build_audit_storage_event(
2256                                            &gate_req,
2257                                            &audit,
2258                                            EventOutcome::Success,
2259                                            Some(resource),
2260                                        )
2261                                        .with_duration_us(dispatch_us);
2262                                        append_audit_event_best_effort(
2263                                            self.audit_batch.as_ref(),
2264                                            store,
2265                                            storage_event,
2266                                            verb,
2267                                            crate::audit_batch::AuditProducer::DispatchSucceeded,
2268                                            self.admission_degrade_safe(verb),
2269                                        )
2270                                        .await
2271                                    }
2272                                }
2273                            }
2274                            _ => {
2275                                // The persisted audit outcome must reflect
2276                                // the dispatch result, not be hardcoded to
2277                                // Success — otherwise a failed dispatch is
2278                                // recorded as successful work and disappears
2279                                // from `outcome=error` queries.
2280                                //
2281                                // ADR-103 Amendment 1: `resource.cost_unit` is
2282                                // computed ONLY on a successful dispatch —
2283                                // there is no handler `Value` to read
2284                                // `item_count` from on an error, and the
2285                                // amendment's "absence has exactly two
2286                                // meanings" rule requires the field be
2287                                // omitted, never defaulted to 0, on an
2288                                // errored dispatch. `work_class` itself is
2289                                // NOT one of those two omission cases
2290                                // (ADR-103 Decision (a) stamps it on every
2291                                // event), so an errored dispatch still gets
2292                                // `resource: {"work_class": "interactive"}`,
2293                                // just with no `cost_unit` key.
2294                                let (outcome, resource) = match &result {
2295                                    Ok(ok_val) => (
2296                                        EventOutcome::Success,
2297                                        Some(crate::cost_unit::resource_payload(
2298                                            verb,
2299                                            &gate_req.args,
2300                                            ok_val,
2301                                            || pack.registered_embedding_model_names().len() as i64,
2302                                            request_id,
2303                                        )),
2304                                    ),
2305                                    Err(_) => (
2306                                        EventOutcome::Error,
2307                                        Some(crate::cost_unit::base_resource_payload(request_id)),
2308                                    ),
2309                                };
2310                                let producer = if result.is_ok() {
2311                                    crate::audit_batch::AuditProducer::DispatchSucceeded
2312                                } else {
2313                                    crate::audit_batch::AuditProducer::DispatchFailed
2314                                };
2315                                let storage_event =
2316                                    build_audit_storage_event(&gate_req, &audit, outcome, resource)
2317                                        .with_duration_us(dispatch_us);
2318                                append_audit_event_best_effort(
2319                                    self.audit_batch.as_ref(),
2320                                    store,
2321                                    storage_event,
2322                                    verb,
2323                                    producer,
2324                                    self.admission_degrade_safe(verb),
2325                                )
2326                                .await
2327                            }
2328                        };
2329                        // Only a would-be-success dispatch can be flipped by
2330                        // an obligation failure (ADR-133 D2/D3/D4): an
2331                        // already-erroring dispatch (DispatchFailed producer)
2332                        // keeps its original error, matching
2333                        // `fold_audit_obligation`'s contract.
2334                        result = fold_audit_obligation(result, audit_outcome);
2335                    }
2336                }
2337
2338                // Post-dispatch hook: fires on success, opt-in.
2339                if let (Ok(ref ok_val), Some(hook)) = (&result, &self.dispatch_hook) {
2340                    let mut dispatch_event = Event::new(
2341                        ns.as_str(),
2342                        verb,
2343                        EventKind::Audit,
2344                        SubstrateKind::Event,
2345                        pack.name(),
2346                    )
2347                    .with_outcome(EventOutcome::Success)
2348                    .with_duration_us(dispatch_us);
2349
2350                    // For recall verbs: extract the first result's id as
2351                    // target_id so the brain temporal posterior can observe
2352                    // real hit/miss and latency. Copy the serve-attribution
2353                    // fields from that same hit so the hook credits the profile
2354                    // that actually served instead of always crediting default.
2355                    if verb == "memory.recall" {
2356                        let first_result =
2357                            ok_val.as_array().and_then(|arr| arr.first()).or_else(|| {
2358                                ok_val
2359                                    .get("results")
2360                                    .and_then(Value::as_array)
2361                                    .and_then(|arr| arr.first())
2362                            });
2363                        let first_note_id = first_result
2364                            .and_then(|v| v.get("id"))
2365                            .and_then(|v| v.as_str())
2366                            .and_then(|s| s.parse::<uuid::Uuid>().ok());
2367                        if let Some(note_id) = first_note_id {
2368                            dispatch_event = dispatch_event.with_target(note_id);
2369                        }
2370                        let mut payload = serde_json::Map::new();
2371                        if let Some(profile_id) = first_result
2372                            .and_then(|v| v.get("served_by_profile_id"))
2373                            .and_then(Value::as_str)
2374                        {
2375                            payload.insert(
2376                                "served_by_profile_id".to_string(),
2377                                Value::String(profile_id.to_string()),
2378                            );
2379                        }
2380                        if let Some(attribution) = first_result
2381                            .and_then(|v| v.get("serve_attribution"))
2382                            .and_then(Value::as_str)
2383                        {
2384                            payload.insert(
2385                                "serve_attribution".to_string(),
2386                                Value::String(attribution.to_string()),
2387                            );
2388                        }
2389                        dispatch_event = dispatch_event.with_payload(Value::Object(payload));
2390                        // No first result → target_id stays None (RecallMiss
2391                        // in brain's event interpreter).
2392                    }
2393
2394                    let dispatch_view = EventView {
2395                        event: dispatch_event,
2396                        observations: Vec::new(),
2397                    };
2398                    let hook = Arc::clone(hook);
2399                    hook.on_dispatch(&dispatch_view).await;
2400                }
2401
2402                // Recently-referenced ring admission: only by-id touches admit
2403                // an id. Runs unconditionally (not gated on `dispatch_hook`,
2404                // which is opt-in) because the ring is a core
2405                // dispatch-boundary capability, not an observer.
2406                //
2407                // Keyed on `token.namespace()`, NOT `ns`: `ns` is the
2408                // gate-resolved namespace, which on the default
2409                // (non-explicit) dispatch path can be a non-local
2410                // `default_namespace` (e.g. "foreign") while the storage
2411                // token that actually created/touched the record is pinned
2412                // to `local`. The ring must be keyed on the namespace the
2413                // record actually lives in: the same namespace
2414                // `resolve_reference`'s ring lookup uses: or admission and
2415                // lookup silently diverge on any non-local `default_namespace`
2416                // config.
2417                if let Ok(ref ok_val) = result {
2418                    let admissions = crate::reference_ring::ring_admissions_for(verb, ok_val);
2419                    if !admissions.is_empty() {
2420                        let actor_key = format!("{}:{}", gate_req.actor.kind, gate_req.actor.id);
2421                        for (id, name) in admissions {
2422                            self.reference_ring.admit(
2423                                token.namespace().as_str(),
2424                                &actor_key,
2425                                id,
2426                                name,
2427                            );
2428                        }
2429                    }
2430                }
2431
2432                return result;
2433            }
2434        }
2435
2436        // No pack owns this verb: the gate allowed it, but no dispatch runs.
2437        // Persist the deferred audit row now (duration stays at the
2438        // `Event::new` default of 0 — no dispatch occurred to measure) so an
2439        // allowed-but-unknown verb is never silently dropped from the audit
2440        // trail (matches the "no audit row is ever dropped" contract above).
2441        if let Some(audit) = deferred_audit.take() {
2442            if let Some(store) = &self.event_store {
2443                // Dispatch is about to return `UnknownVerb` below (no pack
2444                // owns this verb), so the persisted outcome must be `Error`,
2445                // not `Success`. `work_class` is still stamped (ADR-103
2446                // Decision (a)); `resource.cost_unit` is omitted, matching
2447                // every other errored-dispatch row.
2448                let storage_event = build_audit_storage_event(
2449                    &gate_req,
2450                    &audit,
2451                    EventOutcome::Error,
2452                    Some(crate::cost_unit::base_resource_payload(request_id)),
2453                );
2454                // Dispatch already returns `UnknownVerb` below regardless, so
2455                // — as with the deny paths above — there is no success
2456                // outcome to fold a commit failure into.
2457                let _ = append_audit_event_best_effort(
2458                    self.audit_batch.as_ref(),
2459                    store,
2460                    storage_event,
2461                    verb,
2462                    crate::audit_batch::AuditProducer::UnknownVerb,
2463                    false,
2464                )
2465                .await;
2466            }
2467        }
2468
2469        // Verb-visibility handler names, precomputed at build() time (internal
2470        // subhandlers are excluded so they are not advertised in the
2471        // unknown-verb error).
2472        Err(RuntimeError::UnknownVerb(format!(
2473            "unknown verb {verb:?}; available: {}",
2474            self.available_verbs.join(", ")
2475        )))
2476    }
2477
2478    /// Dispatch a verb under an out-of-band verified actor identity.
2479    ///
2480    /// `verified_actor` is a typed [`VerifiedActor`] (constructor rejects blank
2481    /// identifiers) — only code holding a `VerbRegistry` handle can supply it.
2482    /// `dispatch_as` never reads `params["actor"]` to derive the effective actor;
2483    /// individual verbs may still accept an `actor` field for their own documented
2484    /// business semantics, unrelated to the acting principal. Every pack handler
2485    /// that reads "who is calling" resolves it from the `NamespaceToken` the
2486    /// dispatch boundary mints, so `verified_actor` becomes exactly the principal
2487    /// those handlers observe.
2488    ///
2489    /// Equivalent to `dispatch_with_identity(verb, params, Some(identity))` with
2490    /// `identity.actor_id = Some(verified_actor)` and every other identity scalar
2491    /// (namespace, visible namespaces) left at this registry's construction-baked
2492    /// value. [`Self::dispatch`] and [`Self::dispatch_with_identity`] are unaffected.
2493    /// See `docs/api/pack.md#dispatch_as` for the embedding-host use case and the
2494    /// blank-identifier safety rationale.
2495    pub async fn dispatch_as(
2496        &self,
2497        verb: &str,
2498        params: Value,
2499        verified_actor: VerifiedActor,
2500    ) -> Result<Value, RuntimeError> {
2501        let identity = RequestIdentity {
2502            namespace: self.default_namespace.clone(),
2503            actor_id: Some(verified_actor.into_inner()),
2504            visible_namespaces: self
2505                .visible_namespaces
2506                .iter()
2507                .map(|ns| ns.as_str().to_string())
2508                .collect(),
2509            process_ref: crate::config::process_ref_from_env(),
2510            request_id: None,
2511        };
2512        self.dispatch_with_identity(verb, params, Some(identity))
2513            .await
2514    }
2515
2516    /// Registered pack-level by-ID resolvers, in registration order.
2517    ///
2518    /// Each element is `(pack_name, resolver)`. The kg `get` and `delete` handlers
2519    /// iterate this slice to probe pack-private tables when the standard KG
2520    /// substrates (entity/note/edge/event) return `None` for a given UUID.
2521    pub fn resolvers(&self) -> &[(String, Box<dyn PackByIdResolver>)] {
2522        &self.resolvers
2523    }
2524
2525    /// The daemon-warm recently-referenced ring (unified-verb draft ADR,
2526    /// Slice 1). Consumed by `resolve_reference` (Layer 0 stage 2) and by the
2527    /// `resolve` verb handler; admitted-to by every successful by-id
2528    /// dispatch (see the admission block in `dispatch_with_identity`).
2529    pub fn reference_ring(&self) -> &Arc<crate::reference_ring::ReferenceRing> {
2530        &self.reference_ring
2531    }
2532
2533    /// Find a kind hook among the registered packs.
2534    ///
2535    /// Walks packs in registration order; the first pack that both owns the
2536    /// kind (declares it in `note_kinds()` or `entity_kinds()`) and returns
2537    /// a hook from `kind_hook(kind)` wins. Returns `None` if the kind is
2538    /// unknown to all packs or no owning pack registered a hook.
2539    pub fn find_kind_hook(&self, kind: &str) -> Option<Arc<dyn KindHook>> {
2540        for pack in self.packs.iter() {
2541            let owns = pack.note_kinds().contains(&kind) || pack.entity_kinds().contains(&kind);
2542            if owns {
2543                if let Some(hook) = pack.kind_hook(kind) {
2544                    return Some(hook);
2545                }
2546            }
2547        }
2548        None
2549    }
2550
2551    /// Run the owning kind's shared-note-update normalizer/validator, if it declares one.
2552    ///
2553    /// Both canonical KG dispatch and user-facing atomic preparation call this
2554    /// seam so pack-specific property invariants cannot drift between them.
2555    pub async fn prepare_note_update_hook(
2556        &self,
2557        runtime: &KhiveRuntime,
2558        token: &NamespaceToken,
2559        note: &khive_storage::Note,
2560        args: &mut Value,
2561    ) -> Result<(), RuntimeError> {
2562        if let Some(hook) = self.find_kind_hook(&note.kind) {
2563            hook.prepare_note_update(runtime, token, note, args).await?;
2564        }
2565        Ok(())
2566    }
2567
2568    /// Run the owning kind's shared-note-update property validator, if it
2569    /// declares one.
2570    ///
2571    /// Kept as the validation-only compatibility seam for callers that do not
2572    /// own a mutable request object. Canonical and atomic CRUD use
2573    /// [`Self::prepare_note_update_hook`] so a hook can also normalize coupled
2574    /// fields before its validation runs.
2575    pub async fn validate_note_update_hook(
2576        &self,
2577        runtime: &KhiveRuntime,
2578        token: &NamespaceToken,
2579        note: &khive_storage::Note,
2580        properties: Option<&Value>,
2581    ) -> Result<(), RuntimeError> {
2582        if let Some(hook) = self.find_kind_hook(&note.kind) {
2583            hook.validate_note_update(runtime, token, note, properties)
2584                .await?;
2585        }
2586        Ok(())
2587    }
2588
2589    /// Run shared-link validators grouped by the owning source-note kind.
2590    ///
2591    /// Supplying the whole proposed batch lets a kind hook reject an invariant
2592    /// violation formed only by multiple entries in that batch. Sources that
2593    /// are not live notes, or whose kind has no hook, remain the canonical
2594    /// endpoint validator's responsibility.
2595    pub async fn validate_link_hooks(
2596        &self,
2597        runtime: &KhiveRuntime,
2598        token: &NamespaceToken,
2599        specs: &[LinkSpec],
2600    ) -> Result<(), RuntimeError> {
2601        let mut specs_by_kind: HashMap<String, Vec<LinkSpec>> = HashMap::new();
2602        for spec in specs {
2603            let Some(Resolved::Note(source)) = runtime.resolve_by_id(token, spec.source_id).await?
2604            else {
2605                continue;
2606            };
2607            specs_by_kind
2608                .entry(source.kind)
2609                .or_default()
2610                .push(spec.clone());
2611        }
2612        for (kind, kind_specs) in specs_by_kind {
2613            if let Some(hook) = self.find_kind_hook(&kind) {
2614                hook.validate_links(runtime, token, &kind_specs).await?;
2615            }
2616        }
2617        Ok(())
2618    }
2619
2620    /// Whether any registered pack declares a handler with this verb name.
2621    ///
2622    /// A non-dispatch capability check: callers that would otherwise pay a
2623    /// guaranteed-failed `dispatch` (and its audit write) when an optional
2624    /// pack is absent can probe first and skip the call entirely.
2625    pub fn has_verb(&self, verb: &str) -> bool {
2626        self.packs
2627            .iter()
2628            .flat_map(|p| p.handlers().iter())
2629            .any(|h| h.name == verb)
2630    }
2631
2632    /// All MCP-exposed handlers across all registered packs (`Visibility::Verb` only).
2633    ///
2634    /// Subhandlers (`Visibility::Subhandler`) are excluded — they are internal
2635    /// pipeline steps not surfaced on the MCP wire. Returned with `'static`
2636    /// lifetime since pack handlers are `&'static [HandlerDef]` constants.
2637    pub fn all_verbs(&self) -> Vec<&'static HandlerDef> {
2638        self.packs
2639            .iter()
2640            .flat_map(|p| p.handlers().iter())
2641            .filter(|h| matches!(h.visibility, Visibility::Verb))
2642            .collect()
2643    }
2644
2645    /// All MCP-exposed handlers paired with the name of the pack that owns them
2646    /// (`Visibility::Verb` only).
2647    ///
2648    /// Subhandlers (`Visibility::Subhandler`) are excluded from the MCP catalog
2649    /// Use `all_handlers_with_names` when internal handlers must
2650    /// also be enumerated (e.g. runtime introspection).
2651    pub fn all_verbs_with_names(&self) -> Vec<(&str, &'static HandlerDef)> {
2652        self.packs
2653            .iter()
2654            .flat_map(|p| p.handlers().iter().map(move |v| (p.name(), v)))
2655            .filter(|(_, h)| matches!(h.visibility, Visibility::Verb))
2656            .collect()
2657    }
2658
2659    /// All handler definitions across all registered packs, including subhandlers.
2660    ///
2661    /// Unlike `all_verbs`, this includes `Visibility::Subhandler` entries. Useful
2662    /// for runtime introspection (e.g. `list_handlers`) and tooling that needs
2663    /// the complete handler surface.
2664    pub fn all_handlers_with_names(&self) -> Vec<(&str, &'static HandlerDef)> {
2665        self.packs
2666            .iter()
2667            .flat_map(|p| p.handlers().iter().map(move |v| (p.name(), v)))
2668            .collect()
2669    }
2670
2671    /// Merged set of note kinds across all registered packs (deduplicated,
2672    /// first-seen order preserved).
2673    pub fn all_note_kinds(&self) -> Vec<&'static str> {
2674        let mut seen = std::collections::HashSet::new();
2675        self.packs
2676            .iter()
2677            .flat_map(|p| p.note_kinds().iter().copied())
2678            .filter(|k| seen.insert(*k))
2679            .collect()
2680    }
2681
2682    /// Note kinds owned by a pack, i.e. every kind in [`all_note_kinds`] that
2683    /// is not one of the generic-CRUD pack's own kinds.
2684    ///
2685    /// [`GENERIC_CRUD_PACK`] declares the general-purpose note kinds the shared
2686    /// CRUD verbs exist to serve (`observation`, `insight`, …); every other
2687    /// pack's kinds are records that pack's own verbs create and maintain.
2688    /// Derived from the packs' `NOTE_KINDS` constants, so a pack that adds or
2689    /// drops a kind moves this set with it — nothing is hardcoded here but the
2690    /// name of the generic pack itself.
2691    ///
2692    /// [`all_note_kinds`]: Self::all_note_kinds
2693    pub fn pack_owned_note_kinds(&self) -> Vec<&'static str> {
2694        let generic: std::collections::HashSet<&'static str> = self
2695            .packs
2696            .iter()
2697            .filter(|p| p.name() == GENERIC_CRUD_PACK)
2698            .flat_map(|p| p.note_kinds().iter().copied())
2699            .collect();
2700        let mut seen = std::collections::HashSet::new();
2701        self.packs
2702            .iter()
2703            .filter(|p| p.name() != GENERIC_CRUD_PACK)
2704            .flat_map(|p| p.note_kinds().iter().copied())
2705            .filter(|k| !generic.contains(k) && seen.insert(*k))
2706            .collect()
2707    }
2708
2709    /// Merged set of entity kinds across all registered packs (deduplicated,
2710    /// first-seen order preserved).
2711    pub fn all_entity_kinds(&self) -> Vec<&'static str> {
2712        let mut seen = std::collections::HashSet::new();
2713        self.packs
2714            .iter()
2715            .flat_map(|p| p.entity_kinds().iter().copied())
2716            .filter(|k| seen.insert(*k))
2717            .collect()
2718    }
2719
2720    /// Merged set of brain profile consumer kinds requested by registered
2721    /// packs (deduplicated, first-seen order preserved).
2722    pub fn all_brain_consumer_kinds(&self) -> Vec<&'static str> {
2723        let mut seen = std::collections::HashSet::new();
2724        self.packs
2725            .iter()
2726            .flat_map(|p| p.brain_consumer_kinds().iter().copied())
2727            .filter(|kind| seen.insert(*kind))
2728            .collect()
2729    }
2730
2731    /// Names of packs in topological load order.
2732    pub fn pack_names(&self) -> Vec<&str> {
2733        self.packs.iter().map(|p| p.name()).collect()
2734    }
2735
2736    /// Declared dependencies for a registered pack.
2737    pub fn pack_requires(&self, name: &str) -> Option<&'static [&'static str]> {
2738        self.packs
2739            .iter()
2740            .find(|p| p.name() == name)
2741            .map(|p| p.requires())
2742    }
2743
2744    /// Note kinds owned by a specific registered pack.
2745    ///
2746    /// Returns `None` if no pack with `name` is registered. The slice is
2747    /// the pack's `NOTE_KINDS` constant — `'static` lifetime, no allocation.
2748    pub fn pack_note_kinds(&self, name: &str) -> Option<&'static [&'static str]> {
2749        self.packs
2750            .iter()
2751            .find(|p| p.name() == name)
2752            .map(|p| p.note_kinds())
2753    }
2754
2755    /// Entity kinds owned by a specific registered pack.
2756    ///
2757    /// Returns `None` if no pack with `name` is registered. The slice is
2758    /// the pack's `ENTITY_KINDS` constant — `'static` lifetime, no allocation.
2759    pub fn pack_entity_kinds(&self, name: &str) -> Option<&'static [&'static str]> {
2760        self.packs
2761            .iter()
2762            .find(|p| p.name() == name)
2763            .map(|p| p.entity_kinds())
2764    }
2765
2766    /// Handlers declared by a specific registered pack.
2767    ///
2768    /// Returns `None` if no pack with `name` is registered. Each `HandlerDef`
2769    /// carries name + description + visibility — sufficient for introspection clients.
2770    pub fn pack_verbs(&self, name: &str) -> Option<&'static [HandlerDef]> {
2771        self.packs
2772            .iter()
2773            .find(|p| p.name() == name)
2774            .map(|p| p.handlers())
2775    }
2776
2777    /// All pack-declared edge endpoint rules across registered packs.
2778    ///
2779    /// Order follows topological pack registration; duplicates are *not* deduplicated —
2780    /// validation only checks membership, and an exact-duplicate rule is a
2781    /// harmless restatement.
2782    pub fn all_edge_rules(&self) -> Vec<EdgeEndpointRule> {
2783        self.packs
2784            .iter()
2785            .flat_map(|p| p.edge_rules().iter().copied())
2786            .collect()
2787    }
2788
2789    /// All pack-declared entity-type subtypes across registered packs.
2790    ///
2791    /// Order follows topological pack registration; duplicates are *not*
2792    /// deduplicated here — same posture as [`all_edge_rules`](Self::all_edge_rules).
2793    /// Consumers compose this with `EntityTypeRegistry::builtin()` via
2794    /// `EntityTypeRegistry::with_extra` to get the boot-time composed registry.
2795    pub fn all_entity_types(&self) -> Vec<EntityTypeDef> {
2796        self.packs
2797            .iter()
2798            .flat_map(|p| p.entity_types().iter().cloned())
2799            .collect()
2800    }
2801
2802    /// Collect all `NoteKindSpec` declarations from every loaded pack.
2803    ///
2804    /// Used by the runtime for lifecycle introspection and future enforcement.
2805    pub fn all_note_kind_specs(&self) -> Vec<&'static NoteKindSpec> {
2806        self.packs
2807            .iter()
2808            .flat_map(|p| p.note_kind_specs().iter())
2809            .collect()
2810    }
2811
2812    /// All pack-contributed validation rules across registered packs.
2813    ///
2814    /// Returns references into the pack-owned `'static` slices — no allocation
2815    /// beyond the outer `Vec`. Rule IDs are namespaced by pack; callers can
2816    /// group by `rule.id.split_once('/')` to attribute rules to their packs.
2817    pub fn all_validation_rules(&self) -> Vec<&'static ValidationRule> {
2818        self.packs
2819            .iter()
2820            .flat_map(|p| p.validation_rules().iter())
2821            .collect()
2822    }
2823
2824    /// Pack-auxiliary schema plans for all registered packs.
2825    ///
2826    /// Returns one `SchemaPlan` per pack. Callers (typically the runtime
2827    /// bootstrap) apply each plan to the pack's assigned backend. Empty plans
2828    /// are included so the caller can iterate uniformly; callers that want to
2829    /// skip empty plans should check `plan.is_empty()`.
2830    pub fn all_schema_plans(&self) -> Vec<SchemaPlan> {
2831        self.packs.iter().map(|p| p.schema_plan()).collect()
2832    }
2833
2834    /// Invoke `PackRuntime::register_embedders` on every registered pack.
2835    ///
2836    /// Called by the transport during startup, after the registry is built and
2837    /// before the first verb dispatch, so that custom embedding providers
2838    /// contributed by packs are reachable via `KhiveRuntime::embedder(name)`.
2839    ///
2840    /// Packs whose `register_embedders` is the default no-op pay no overhead.
2841    /// The method is idempotent when the underlying registry uses last-wins
2842    /// semantics for duplicate provider names.
2843    pub fn call_register_embedders(&self, runtime: &KhiveRuntime) {
2844        for pack in self.packs.iter() {
2845            pack.register_embedders(runtime);
2846        }
2847    }
2848
2849    /// Invoke `PackRuntime::register_entity_type_validator` on every registered pack.
2850    ///
2851    /// Called by the transport during startup, after the registry is built and
2852    /// before the first verb dispatch, so that entity-type validation at the
2853    /// runtime layer is active for all write paths including direct `create_many`
2854    /// callers that bypass the handler layer.
2855    ///
2856    /// Packs whose `register_entity_type_validator` is the default no-op pay
2857    /// no overhead.
2858    ///
2859    /// Composes [`all_entity_types`](Self::all_entity_types) once and passes
2860    /// the same aggregate to every pack, mirroring how `install_edge_rules`
2861    /// installs one `all_edge_rules()` aggregate for the whole registry.
2862    pub fn call_register_entity_type_validators(&self, runtime: &KhiveRuntime) {
2863        let entity_types = self.all_entity_types();
2864        for pack in self.packs.iter() {
2865            pack.register_entity_type_validator_with_types(runtime, &entity_types);
2866        }
2867    }
2868
2869    /// Invoke `PackRuntime::register_note_mutation_hook` on every registered pack.
2870    ///
2871    /// Called by the transport during startup, after the registry is built and
2872    /// before the first verb dispatch, so that note-mutation notifications at
2873    /// the runtime layer are active for all write paths — including KG's
2874    /// `update`/`delete` verbs reaching a `kind="memory"` note, which have no
2875    /// crate-level dependency on `khive-pack-memory`.
2876    ///
2877    /// Packs whose `register_note_mutation_hook` is the default no-op pay no
2878    /// overhead.
2879    pub fn call_register_note_mutation_hooks(&self, runtime: &KhiveRuntime) {
2880        for pack in self.packs.iter() {
2881            pack.register_note_mutation_hook(runtime);
2882        }
2883    }
2884
2885    /// Invoke `PackRuntime::register_note_write_validator` on every registered pack.
2886    ///
2887    /// Called by the transport during startup with the same timing as
2888    /// `call_register_note_mutation_hooks`, so note-write validation is active
2889    /// at the runtime layer for every write path — the generic `create` verb,
2890    /// direct Rust callers, and proposal apply, none of which dispatch a pack
2891    /// hook of their own on the note-write.
2892    pub fn call_register_note_write_validators(&self, runtime: &KhiveRuntime) {
2893        for pack in self.packs.iter() {
2894            pack.register_note_write_validator(runtime);
2895        }
2896    }
2897
2898    /// Invoke `PackRuntime::warm` on every registered pack.
2899    /// Called by the daemon at boot (in a background task) so expensive in-memory
2900    /// state (ANN indexes) is pre-loaded without blocking request serving.
2901    pub async fn call_warm_all(&self) {
2902        for pack in self.packs.iter() {
2903            pack.warm().await;
2904        }
2905    }
2906
2907    /// Resolve the presentation policy for a verb name.
2908    ///
2909    /// Walks all registered handlers (including subhandlers) for the first
2910    /// matching name and returns its declared [`VerbPresentationPolicy`].
2911    /// Returns `Standard` for unknown verbs — unknown verbs will fail at
2912    /// dispatch anyway, so the fallback here is safe.
2913    pub fn presentation_policy_for(&self, verb: &str) -> khive_types::VerbPresentationPolicy {
2914        for pack in self.packs.iter() {
2915            if let Some(handler) = pack.handlers().iter().find(|h| h.name == verb) {
2916                return handler.presentation_policy();
2917            }
2918        }
2919        khive_types::VerbPresentationPolicy::Standard
2920    }
2921
2922    /// Returns `true` if the named verb exists and is tagged
2923    /// `Visibility::Subhandler` (internal / operator-only).
2924    ///
2925    /// Used by the MCP server to gate subhandler invocation at the wire
2926    /// boundary without blocking internal callers that invoke the same verbs
2927    /// through the runtime directly.
2928    pub fn is_subhandler_verb(&self, verb: &str) -> bool {
2929        for pack in self.packs.iter() {
2930            if let Some(handler) = pack.handlers().iter().find(|h| h.name == verb) {
2931                return matches!(handler.visibility, Visibility::Subhandler);
2932            }
2933        }
2934        false
2935    }
2936
2937    /// Apply all non-empty pack-auxiliary schema plans to the given backend.
2938    ///
2939    /// This is the centralized startup hook that replaced the previous lazy
2940    /// per-pack self-bootstrap pattern. Each pack's `SchemaPlan` carries
2941    /// idempotent `CREATE TABLE IF NOT EXISTS` DDL; calling this more than once
2942    /// is safe. Empty plans are skipped.
2943    ///
2944    /// Errors from individual plans are logged via `tracing::warn!` and not
2945    /// propagated so that a single pack's schema failure does not prevent the
2946    /// rest from loading. Callers that need hard-failure semantics should call
2947    /// `all_schema_plans()` and apply each plan individually.
2948    pub fn apply_schema_plans(&self, backend: &khive_db::StorageBackend) {
2949        if backend.is_read_only() {
2950            tracing::info!(
2951                "skipping pack schema plans because the backend is read-only; snapshot schema is used as-is"
2952            );
2953            return;
2954        }
2955        for plan in self.all_schema_plans() {
2956            if plan.is_empty() {
2957                continue;
2958            }
2959            if let Err(e) = backend.apply_pack_ddl_statements(plan.statements) {
2960                tracing::warn!(
2961                    pack = plan.pack,
2962                    error = %e,
2963                    "failed to apply pack schema plan at startup (non-fatal)"
2964                );
2965            }
2966        }
2967    }
2968
2969    /// Pack-auxiliary schema plans with their owning pack names.
2970    ///
2971    /// Returns `(pack_name, SchemaPlan)` pairs for every registered pack.
2972    /// Used by the multi-backend boot path to apply each plan to the pack's
2973    /// assigned backend rather than a single shared backend.
2974    pub fn all_schema_plans_named(&self) -> Vec<(&'static str, SchemaPlan)> {
2975        self.packs
2976            .iter()
2977            .map(|p| {
2978                let plan = p.schema_plan();
2979                (plan.pack, plan)
2980            })
2981            .collect()
2982    }
2983
2984    /// Apply pack-auxiliary schema plans using a per-pack backend map.
2985    ///
2986    /// For each `(pack_name, plan)` returned by `all_schema_plans_named()`,
2987    /// applies the plan to `backend_for_pack[pack_name]` when present,
2988    /// falling back to `default_backend` for any pack not in the map.
2989    ///
2990    /// Returns an error when two packs on the same backend declare the same
2991    /// auxiliary table (ADR-028 §7 collision policy: boot failure naming both
2992    /// packs and the conflicting table).
2993    ///
2994    /// This is the multi-backend boot path (ADR-028). Single-backend callers
2995    /// should continue using [`Self::apply_schema_plans`].
2996    pub fn apply_schema_plans_with_map(
2997        &self,
2998        backend_for_pack: &HashMap<&str, &khive_db::StorageBackend>,
2999        default_backend: &khive_db::StorageBackend,
3000    ) -> Result<(), crate::PackSchemaCollisionError> {
3001        // Track which pack first claimed each table on each backend.
3002        // Backend identity is the raw pointer of the underlying connection pool Arc.
3003        let mut claimed: HashMap<(*const (), String), &'static str> = HashMap::new();
3004
3005        for (pack_name, plan) in self.all_schema_plans_named() {
3006            if plan.is_empty() {
3007                continue;
3008            }
3009            let backend = backend_for_pack
3010                .get(pack_name)
3011                .copied()
3012                .unwrap_or(default_backend);
3013            let backend_ptr = std::sync::Arc::as_ptr(&backend.pool_arc()) as *const ();
3014
3015            // Pre-scan DDL for table names and detect collisions before applying.
3016            for stmt in plan.statements {
3017                for table_name in extract_table_names(stmt) {
3018                    let key = (backend_ptr, table_name.clone());
3019                    match claimed.entry(key) {
3020                        std::collections::hash_map::Entry::Vacant(e) => {
3021                            e.insert(pack_name);
3022                        }
3023                        std::collections::hash_map::Entry::Occupied(e) => {
3024                            let prior_pack = *e.get();
3025                            return Err(crate::PackSchemaCollisionError {
3026                                pack_a: prior_pack,
3027                                pack_b: pack_name,
3028                                table: table_name,
3029                            });
3030                        }
3031                    }
3032                }
3033            }
3034
3035            if backend.is_read_only() {
3036                tracing::info!(
3037                    pack = pack_name,
3038                    "skipping pack schema plan because its assigned backend is read-only"
3039                );
3040                continue;
3041            }
3042
3043            backend
3044                .apply_pack_ddl_statements(plan.statements)
3045                .map_err(|e| crate::PackSchemaCollisionError {
3046                    pack_a: pack_name,
3047                    pack_b: pack_name,
3048                    table: format!("DDL error: {e}"),
3049                })?;
3050        }
3051        Ok(())
3052    }
3053}
3054
3055// ── Inventory-based dynamic pack loading ────────────────────────────────────
3056
3057/// Output of [`PackFactory::create_install`] — bundles the pack runtime with
3058/// its optional by-ID resolver and dispatch hook so a factory can hand back
3059/// all three built from one shared instance (see `BrainPackFactory` for why
3060/// this matters: the dispatch hook must observe the same state the runtime
3061/// mutates, not a second unrelated instance).
3062pub struct PackInstall {
3063    /// The pack runtime, registered into the builder's pack list.
3064    pub runtime: Box<dyn PackRuntime>,
3065    /// Optional by-ID resolver, registered when present.
3066    pub resolver: Option<Box<dyn PackByIdResolver>>,
3067    /// Optional post-dispatch observer, wired via `VerbRegistryBuilder::with_dispatch_hook`.
3068    pub dispatch_hook: Option<Arc<dyn DispatchHook>>,
3069}
3070
3071/// Factory for creating pack instances registered via `inventory` at link time.
3072/// Each pack crate submits a `&'static dyn PackFactory` wrapped in a
3073/// [`PackRegistration`]; the binary's linker collects them all into a single
3074/// slice iterable at runtime.
3075///
3076/// Implementors must be `Send + Sync + 'static` because the registry is built
3077/// once and shared across async tasks.
3078/// Possession-bounded capability for the trusted channel-ingest note path.
3079///
3080/// Constructible only inside `khive-runtime` (the field is private), and
3081/// granted during pack registration exclusively to factories named in
3082/// `CHANNEL_INGEST_CAPABLE_PACKS`. Every call to
3083/// [`crate::KhiveRuntime::try_create_note_as_trusted_ingest`] must present a
3084/// reference to one, so the set of callers able to establish transport-owned
3085/// message properties is bounded by possession at the composition root, not
3086/// by a documentation prohibition. Two ways to obtain one: registering
3087/// through [`PackRegistry::register_packs`]/`register_packs_with_runtimes`
3088/// under the `comm` name (the allowlisted, automatic path), or a composition
3089/// root that builds packs directly calling
3090/// [`ChannelIngestCapability::grant_for_direct_composition`] and passing the
3091/// result to [`crate::PackRuntime::accept_channel_ingest_capability`] (or a
3092/// pack's constructor variant that does so) itself. The residual trust
3093/// assumption is unchanged either way: whoever assembles the
3094/// `VerbRegistryBuilder` already decides which packs are wired in and already
3095/// holds a `KhiveRuntime`, so minting the grant explicitly carries no more
3096/// privilege than that composition already had by choosing to register `comm`
3097/// at all.
3098pub struct ChannelIngestCapability {
3099    pub(crate) _sealed: (),
3100}
3101
3102impl ChannelIngestCapability {
3103    /// Mint a capability for a composition root that constructs
3104    /// channel-transport packs directly, bypassing
3105    /// [`PackRegistry::register_packs`] (which grants this automatically).
3106    ///
3107    /// See the type-level doc for the trust argument: this carries no more
3108    /// privilege than the caller already has by virtue of holding a
3109    /// `KhiveRuntime` and choosing to wire the pack in.
3110    pub fn grant_for_direct_composition() -> Self {
3111        Self { _sealed: () }
3112    }
3113}
3114
3115/// Pack names entitled to a [`ChannelIngestCapability`] grant at registration.
3116pub(crate) const CHANNEL_INGEST_CAPABLE_PACKS: &[&str] = &["comm"];
3117
3118pub trait PackFactory: Send + Sync + 'static {
3119    /// Canonical lowercase name for this pack (e.g. `"kg"`, `"gtd"`).
3120    fn name(&self) -> &'static str;
3121
3122    /// Names of packs that must be loaded before this one.
3123    ///
3124    /// Defaults to empty so pack crates that have no dependencies compile
3125    /// without changes. [`PackRegistry::register_packs`] validates that every
3126    /// name listed here is present in the caller's explicit pack list — absent
3127    /// dependencies are a boot error, not silently auto-added.
3128    fn requires(&self) -> &'static [&'static str] {
3129        &[]
3130    }
3131
3132    /// Create a new pack instance for the given runtime.
3133    fn create(&self, runtime: KhiveRuntime) -> Box<dyn PackRuntime>;
3134
3135    /// Build the full installation bundle for this pack: runtime, optional
3136    /// resolver, optional dispatch hook.
3137    ///
3138    /// Defaults to composing `create` and `create_resolver` with no dispatch
3139    /// hook, so existing factories compile unchanged. Packs whose dispatch
3140    /// hook must observe the same instance as the runtime (e.g. `brain`)
3141    /// override this method instead of `create`, since the default would
3142    /// otherwise require two independent instances to share state.
3143    fn create_install(&self, runtime: KhiveRuntime) -> PackInstall {
3144        let resolver = self.create_resolver(runtime.clone());
3145        PackInstall {
3146            runtime: self.create(runtime),
3147            resolver,
3148            dispatch_hook: None,
3149        }
3150    }
3151
3152    /// Optionally create a `PackByIdResolver` for this pack.
3153    ///
3154    /// Packs that own private SQL tables implement this to hook into
3155    /// `get(id)` and `delete(id)`. Defaults to `None` so existing packs
3156    /// compile without changes.
3157    fn create_resolver(&self, _runtime: KhiveRuntime) -> Option<Box<dyn PackByIdResolver>> {
3158        None
3159    }
3160}
3161
3162/// Newtype wrapper collected by `inventory` so pack crates can submit
3163/// `&'static dyn PackFactory` references without the type-ascription syntax
3164/// that `inventory::submit!` does not support for bare trait-object references.
3165pub struct PackRegistration(pub &'static dyn PackFactory);
3166
3167inventory::collect!(PackRegistration);
3168
3169/// Error returned by [`PackRegistry::register_packs`] when boot validation fails.
3170#[derive(Debug)]
3171pub enum PackLoadError {
3172    /// The requested pack name was not found in the inventory.
3173    UnknownPack(String),
3174    /// A pack was requested but a declared dependency is absent from the list.
3175    MissingDependency {
3176        /// The pack that declared the dependency.
3177        pack: String,
3178        /// The dependency that is missing from the requested pack list.
3179        dep: String,
3180    },
3181}
3182
3183impl std::fmt::Display for PackLoadError {
3184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3185        match self {
3186            PackLoadError::UnknownPack(name) => write!(f, "unknown pack {name:?}"),
3187            PackLoadError::MissingDependency { pack, dep } => write!(
3188                f,
3189                "pack {pack:?} requires {dep:?}, which is not in the requested pack list; \
3190                 add --pack {dep} before --pack {pack}"
3191            ),
3192        }
3193    }
3194}
3195
3196impl std::error::Error for PackLoadError {}
3197
3198/// Registry of pack factories discovered via `inventory` at link time.
3199///
3200/// No instance is needed — all methods are associated functions that walk the
3201/// globally-collected [`PackRegistration`] slice.
3202pub struct PackRegistry;
3203
3204impl PackRegistry {
3205    /// Names of all pack factories discovered via `inventory`.
3206    pub fn discovered_names() -> Vec<&'static str> {
3207        inventory::iter::<PackRegistration>
3208            .into_iter()
3209            .map(|r| r.0.name())
3210            .collect()
3211    }
3212
3213    /// Register the named packs into `builder` using the supplied `runtime`.
3214    ///
3215    /// Validates the explicit pack list against `PackFactory::requires()` —
3216    /// if any requested pack declares a dependency that is absent from `names`,
3217    /// registration fails (missing dependency is a boot error, not silently
3218    /// auto-added). Callers must include all required packs explicitly.
3219    ///
3220    /// The [`VerbRegistryBuilder::build`] topo-sort enforces correct load order.
3221    ///
3222    /// Returns `Ok(())` when all names are recognised and all declared
3223    /// dependencies are satisfied; returns `Err(PackLoadError)` with a
3224    /// distinct variant for unknown pack vs missing dependency.
3225    pub fn register_packs(
3226        names: &[String],
3227        runtime: KhiveRuntime,
3228        builder: &mut VerbRegistryBuilder,
3229    ) -> Result<(), PackLoadError> {
3230        // Build a name→factory index once.
3231        let all: Vec<&'static dyn PackFactory> = inventory::iter::<PackRegistration>
3232            .into_iter()
3233            .map(|r| r.0)
3234            .collect();
3235        let factory_for = |name: &str| -> Option<&'static dyn PackFactory> {
3236            all.iter().copied().find(|f| f.name() == name)
3237        };
3238
3239        // Validate that every requested name is a known factory.
3240        let requested: std::collections::HashSet<&str> = names.iter().map(String::as_str).collect();
3241        for name in names {
3242            factory_for(name.as_str()).ok_or_else(|| PackLoadError::UnknownPack(name.clone()))?;
3243        }
3244
3245        // Validate that all requires() dependencies are explicitly present in
3246        // the requested set. Missing dep → boot error, not auto-add.
3247        for name in names {
3248            let factory = factory_for(name.as_str()).unwrap(); // validated above
3249            for &dep in factory.requires() {
3250                if !requested.contains(dep) {
3251                    return Err(PackLoadError::MissingDependency {
3252                        pack: name.clone(),
3253                        dep: dep.to_string(),
3254                    });
3255                }
3256            }
3257        }
3258
3259        // Register every requested pack; VerbRegistryBuilder::build()
3260        // performs the topo-sort, so insertion order here does not matter.
3261        for name in names {
3262            let factory = factory_for(name.as_str()).unwrap(); // validated above
3263            let install = factory.create_install(runtime.clone());
3264            if CHANNEL_INGEST_CAPABLE_PACKS.contains(&name.as_str()) {
3265                install
3266                    .runtime
3267                    .accept_channel_ingest_capability(ChannelIngestCapability { _sealed: () });
3268            }
3269            builder.register_boxed(install.runtime);
3270            if let Some(resolver) = install.resolver {
3271                builder.register_resolver(name.clone(), resolver);
3272            }
3273            if let Some(hook) = install.dispatch_hook {
3274                builder.with_dispatch_hook(hook);
3275            }
3276        }
3277
3278        Ok(())
3279    }
3280
3281    /// Register the named packs into `builder`, routing each pack to its own runtime.
3282    ///
3283    /// `runtimes` maps pack name → `KhiveRuntime` (one per backend assignment).
3284    /// `default_runtime` is used for any pack whose name is not in `runtimes`.
3285    /// The validation logic (unknown pack, missing dependency) is identical to
3286    /// [`PackRegistry::register_packs`].
3287    ///
3288    /// This is the multi-backend boot path (ADR-028). Single-backend callers
3289    /// should continue using [`PackRegistry::register_packs`].
3290    pub fn register_packs_with_runtimes(
3291        names: &[String],
3292        runtimes: &HashMap<String, KhiveRuntime>,
3293        default_runtime: &KhiveRuntime,
3294        builder: &mut VerbRegistryBuilder,
3295    ) -> Result<(), PackLoadError> {
3296        let all: Vec<&'static dyn PackFactory> = inventory::iter::<PackRegistration>
3297            .into_iter()
3298            .map(|r| r.0)
3299            .collect();
3300        let factory_for = |name: &str| -> Option<&'static dyn PackFactory> {
3301            all.iter().copied().find(|f| f.name() == name)
3302        };
3303
3304        let requested: std::collections::HashSet<&str> = names.iter().map(String::as_str).collect();
3305        for name in names {
3306            factory_for(name.as_str()).ok_or_else(|| PackLoadError::UnknownPack(name.clone()))?;
3307        }
3308
3309        for name in names {
3310            let factory = factory_for(name.as_str()).unwrap();
3311            for &dep in factory.requires() {
3312                if !requested.contains(dep) {
3313                    return Err(PackLoadError::MissingDependency {
3314                        pack: name.clone(),
3315                        dep: dep.to_string(),
3316                    });
3317                }
3318            }
3319        }
3320
3321        for name in names {
3322            let factory = factory_for(name.as_str()).unwrap();
3323            let runtime = runtimes
3324                .get(name.as_str())
3325                .cloned()
3326                .unwrap_or_else(|| default_runtime.clone());
3327            let install = factory.create_install(runtime);
3328            if CHANNEL_INGEST_CAPABLE_PACKS.contains(&name.as_str()) {
3329                install
3330                    .runtime
3331                    .accept_channel_ingest_capability(ChannelIngestCapability { _sealed: () });
3332            }
3333            builder.register_boxed(install.runtime);
3334            if let Some(resolver) = install.resolver {
3335                builder.register_resolver(name.clone(), resolver);
3336            }
3337            if let Some(hook) = install.dispatch_hook {
3338                builder.with_dispatch_hook(hook);
3339            }
3340        }
3341
3342        Ok(())
3343    }
3344}
3345
3346fn target_id_from_args(args: &serde_json::Value) -> Option<uuid::Uuid> {
3347    args.get("target_id")
3348        .and_then(serde_json::Value::as_str)
3349        .and_then(|s| s.parse::<uuid::Uuid>().ok())
3350}
3351
3352/// Build a v1-shape audit storage event from a gate check outcome.
3353/// See `docs/api/pack.md#build_audit_storage_event` for the `resource` payload contract.
3354fn build_audit_storage_event(
3355    gate_req: &GateRequest,
3356    audit: &AuditEvent,
3357    outcome: EventOutcome,
3358    resource: Option<Value>,
3359) -> Event {
3360    let mut audit_data = serde_json::to_value(audit).unwrap_or_else(|e| {
3361        tracing::warn!(error = %e, "failed to serialize AuditEvent for EventStore");
3362        serde_json::Value::Null
3363    });
3364    if let Some(resource) = resource {
3365        if let Value::Object(ref mut map) = audit_data {
3366            map.insert("resource".to_string(), resource);
3367        }
3368    }
3369    let mut storage_event = Event::new(
3370        gate_req.namespace.as_str(),
3371        gate_req.verb.as_str(),
3372        EventKind::Audit,
3373        SubstrateKind::Event,
3374        format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
3375    )
3376    .with_outcome(outcome)
3377    .with_payload(audit_data);
3378    if let Some(target_id) = target_id_from_args(&gate_req.args) {
3379        storage_event = storage_event.with_target(target_id);
3380    }
3381    storage_event
3382}
3383
3384/// Process-wide pure-observability audit appends whose errors were logged
3385/// and swallowed — never an obligation-bearing row, which fails its dispatch
3386/// instead and is counted separately by
3387/// [`AUDIT_OBLIGATION_APPEND_FAILURES`]/[`audit_obligation_append_failure_count`].
3388/// Keeping this counter obligation-free preserves its documented contract
3389/// (`docs/guide/api-reference.md`, `khive-db`'s `WriterContentionDiagnostics::audit_append_failures`
3390/// doc comment): every unit counted here was swallowed, none was propagated.
3391static AUDIT_APPEND_FAILURES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3392
3393pub(crate) fn audit_append_failure_count() -> u64 {
3394    AUDIT_APPEND_FAILURES.load(std::sync::atomic::Ordering::Relaxed)
3395}
3396
3397/// Process-wide commit failures for obligation-bearing audit rows (ADR-133
3398/// D2/D3/D4): gate denials, dispatch outcomes, unknown-verb rows, and
3399/// `git.digest` success receipts. Most call sites fold this failure into the
3400/// dispatch's own error (a would-be success becomes an error, per
3401/// [`fold_audit_obligation`]); a denial's own audit row is the one
3402/// exception — its dispatch already returns `PermissionDenied` independent
3403/// of whether this row commits, so the failure is logged and counted here
3404/// but not separately propagated. Disjoint from [`AUDIT_APPEND_FAILURES`] —
3405/// each failing row is classified by [`crate::audit_batch::classify`] into
3406/// exactly one of the two classes and increments exactly one of these two
3407/// counters, never both.
3408static AUDIT_OBLIGATION_APPEND_FAILURES: std::sync::atomic::AtomicU64 =
3409    std::sync::atomic::AtomicU64::new(0);
3410
3411/// Test-only reader: no production caller needs this counter today (unlike
3412/// [`audit_append_failure_count`], which `KhiveRuntime::db_diagnostics`
3413/// surfaces), but the mechanism tests need to observe it directly to prove
3414/// obligation and swallowed failures land on disjoint counters.
3415#[cfg(test)]
3416pub(crate) fn audit_obligation_append_failure_count() -> u64 {
3417    AUDIT_OBLIGATION_APPEND_FAILURES.load(std::sync::atomic::Ordering::Relaxed)
3418}
3419
3420/// Process-wide count of `DispatchObligation` rows **refused before they
3421/// could be enqueued** (`AuditTerminalReason::QueueAdmissionExhausted`) for an
3422/// [`VerbRegistry::admission_degrade_safe`] verb (khive#2147/khive#2217).
3423/// This is a confirmed, terminal accounting loss: the row never shared a
3424/// generation with anyone and will never commit. Disjoint from both
3425/// [`AUDIT_APPEND_FAILURES`] and [`AUDIT_OBLIGATION_APPEND_FAILURES`]: this
3426/// case is neither. It is not [`AUDIT_APPEND_FAILURES`] — that counter's own
3427/// contract (`khive-db`'s `WriterContentionDiagnostics::audit_append_failures`
3428/// doc) says an obligation-bearing row's commit failure "either fail[s] the
3429/// dispatch... or [is] tracked by the runtime's own separate
3430/// obligation-failure counter instead", and this dispatch does neither: it
3431/// reports the caller's already-computed success with no error. It is not
3432/// [`AUDIT_OBLIGATION_APPEND_FAILURES`] either — that counter's contract is
3433/// "most call sites fold this failure into the dispatch's own error", which
3434/// is exactly the propagation this admission-degrade path exists to avoid.
3435/// Also disjoint from [`AUDIT_ADMISSION_UNRESOLVED_OBLIGATIONS`] — that
3436/// counter's row was enqueued and may still commit; this one's was not.
3437/// Read in production by [`VerbRegistry::audit_batch_metrics`], which feeds
3438/// it into `khive_db::diagnostics::RuntimeAuditBatchMetrics::admission_refused_obligations`
3439/// and from there into the `db_diagnostics` verb's
3440/// `writer_contention.audit_admission_refused_obligations` field (ADR-103
3441/// Amendment 3) — an operator can read this counter without a test-only
3442/// feature gate. The mechanism tests also read it directly, including the
3443/// admission-pressure regression tests in `tests/read_verb_admission_exhaustion.rs`,
3444/// which (like `khive-runtime/src/audit_batch.rs`'s own `test_internals`
3445/// module) need it as `pub`, not `pub(crate)`, since they compile as a
3446/// separate external binary outside this crate.
3447static AUDIT_ADMISSION_REFUSED_OBLIGATIONS: std::sync::atomic::AtomicU64 =
3448    std::sync::atomic::AtomicU64::new(0);
3449
3450pub fn audit_admission_refused_obligation_count() -> u64 {
3451    AUDIT_ADMISSION_REFUSED_OBLIGATIONS.load(std::sync::atomic::Ordering::Relaxed)
3452}
3453
3454/// Process-wide count of `DispatchObligation` rows that were **already
3455/// enqueued but had not resolved by the time the caller's admission wait
3456/// deadline elapsed** (`AuditTerminalReason::AdmissionDeadlineExpired`) for an
3457/// [`VerbRegistry::admission_degrade_safe`] verb (khive#2147/khive#2217).
3458/// Unlike [`AUDIT_ADMISSION_REFUSED_OBLIGATIONS`], a row counted here is not
3459/// a confirmed loss: per `AuditTerminalReason::AdmissionDeadlineExpired`'s own
3460/// doc, the row may still be committed (or terminally failed) by the
3461/// generation driver independently of the caller's timeout, so this counter
3462/// is an upper bound on the eventual undercount, not the undercount itself.
3463/// Read in production by [`VerbRegistry::audit_batch_metrics`], which feeds
3464/// it into `khive_db::diagnostics::RuntimeAuditBatchMetrics::admission_unresolved_obligations`
3465/// and from there into the `db_diagnostics` verb's
3466/// `writer_contention.audit_admission_unresolved_obligations` field (ADR-103
3467/// Amendment 3).
3468static AUDIT_ADMISSION_UNRESOLVED_OBLIGATIONS: std::sync::atomic::AtomicU64 =
3469    std::sync::atomic::AtomicU64::new(0);
3470
3471pub fn audit_admission_unresolved_obligation_count() -> u64 {
3472    AUDIT_ADMISSION_UNRESOLVED_OBLIGATIONS.load(std::sync::atomic::Ordering::Relaxed)
3473}
3474
3475const GIT_DIGEST_RECEIPT_FAILURE: &str =
3476    "git_digest_receipt_persist_failed: git.digest writes may have committed, but no durable \
3477     success receipt was confirmed; inspect ingest state before retrying";
3478
3479/// Tells the dispatch seam whether it should consume the deferred audit or
3480/// reuse it for the ordinary generic Error row.
3481#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3482enum GitDigestReceiptOutcome {
3483    /// The schema-v2 receipt landed; no second audit row may be appended.
3484    Persisted,
3485    /// The handler's nominal success could not be shaped into a receipt. The
3486    /// helper has converted it to an error, and the original audit remains
3487    /// available for one generic Error row.
3488    BuildRejected,
3489    /// Persistence could not be attempted or its append failed. A second
3490    /// best-effort append would either be impossible or duplicate the same
3491    /// known store failure, so the caller must not retry it here.
3492    PersistenceUnavailable,
3493}
3494
3495/// Persist the complete successful `git.digest` report as a schema-v2 audit
3496/// event and add that event's UUID to the returned report as `receipt_id`.
3497///
3498/// This is intentionally strict while every other dispatch audit remains
3499/// best-effort: a caller must never receive an unqualified digest success if
3500/// response loss would leave it unable to recover the exact per-pass report.
3501/// Missing audit/store configuration, an invalid handler report, or an append
3502/// failure therefore replaces the handler success with a stable safe error.
3503/// The error does not expose storage paths, source URLs, or command stderr and
3504/// explicitly warns that ingest writes may already have committed.
3505async fn persist_git_digest_receipt(
3506    store: Option<&Arc<dyn EventStore>>,
3507    audit_batch: Option<&Arc<crate::audit_batch::AuditBatch>>,
3508    gate_req: &GateRequest,
3509    audit: Option<&AuditEvent>,
3510    result: &mut Result<Value, RuntimeError>,
3511    duration_us: i64,
3512    resource: Option<Value>,
3513) -> GitDigestReceiptOutcome {
3514    let Ok(report) = result else {
3515        return GitDigestReceiptOutcome::PersistenceUnavailable;
3516    };
3517    let Some(store) = store else {
3518        tracing::error!(
3519            verb = "git.digest",
3520            "durable receipt store is not configured"
3521        );
3522        *result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
3523        return GitDigestReceiptOutcome::PersistenceUnavailable;
3524    };
3525    let Some(audit) = audit else {
3526        tracing::error!(
3527            verb = "git.digest",
3528            "durable receipt cannot be built because the gate produced no audit decision"
3529        );
3530        *result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
3531        return GitDigestReceiptOutcome::PersistenceUnavailable;
3532    };
3533
3534    let Some(report_object) = report.as_object_mut() else {
3535        tracing::error!(
3536            verb = "git.digest",
3537            "digest handler returned a non-object report"
3538        );
3539        *result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
3540        return GitDigestReceiptOutcome::BuildRejected;
3541    };
3542    let Some(project_id) = report_object
3543        .get("project_id")
3544        .and_then(Value::as_str)
3545        .and_then(|raw| raw.parse::<uuid::Uuid>().ok())
3546    else {
3547        tracing::error!(
3548            verb = "git.digest",
3549            "digest handler report omitted a valid project_id"
3550        );
3551        *result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
3552        return GitDigestReceiptOutcome::BuildRejected;
3553    };
3554
3555    // Allocate the event first so the exact durable key can be embedded in
3556    // both the caller-visible report and the report snapshot stored in it.
3557    let mut event = Event::new(
3558        gate_req.namespace.as_str(),
3559        gate_req.verb.as_str(),
3560        EventKind::Audit,
3561        SubstrateKind::Event,
3562        format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
3563    )
3564    .with_outcome(EventOutcome::Success)
3565    .with_target(project_id)
3566    .with_payload_schema_version(2)
3567    .with_duration_us(duration_us);
3568    let receipt_id = event.id;
3569    report_object.insert(
3570        "receipt_id".to_string(),
3571        Value::String(receipt_id.to_string()),
3572    );
3573
3574    let mut payload = serde_json::to_value(audit).unwrap_or_else(|serialize_err| {
3575        tracing::error!(
3576            verb = "git.digest",
3577            error = %serialize_err,
3578            "failed to serialize gate audit for durable digest receipt"
3579        );
3580        Value::Null
3581    });
3582    let Value::Object(payload_object) = &mut payload else {
3583        tracing::error!(
3584            verb = "git.digest",
3585            "gate audit serialization did not produce an object"
3586        );
3587        *result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
3588        return GitDigestReceiptOutcome::BuildRejected;
3589    };
3590    if let Some(resource) = resource {
3591        payload_object.insert("resource".to_string(), resource);
3592    }
3593    payload_object.insert("result".to_string(), report.clone());
3594    event.payload = payload;
3595
3596    // Strict path (ADR-133): a git.digest success receipt must still commit
3597    // exactly once before the caller can see success, so this row waits on
3598    // its generation's commit through the batch seam rather than
3599    // best-effort — the batching only changes whether it shares a writer
3600    // acquisition with concurrent rows, never whether it is durable before
3601    // the caller observes success.
3602    let submit_result = if let Some(audit_batch) = audit_batch {
3603        use crate::audit_batch::AuditBatchControl;
3604        audit_batch
3605            .submit(crate::audit_batch::PreparedAuditRow {
3606                event,
3607                producer: crate::audit_batch::AuditProducer::GitDigestReceipt,
3608            })
3609            .await
3610            .map(|_outcome| ())
3611            .map_err(|reason| format!("{reason:?}"))
3612    } else {
3613        store.append_event(event).await.map_err(|e| e.to_string())
3614    };
3615    if let Err(store_err) = submit_result {
3616        // `GitDigestReceipt` is always `DispatchObligation` (see
3617        // `crate::audit_batch::classify`) and this failure always
3618        // propagates below, so it belongs on the obligation counter, not
3619        // the swallowed-failures one.
3620        AUDIT_OBLIGATION_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3621        tracing::error!(
3622            verb = "git.digest",
3623            error = %store_err,
3624            receipt_id = %receipt_id,
3625            "durable digest receipt append failed"
3626        );
3627        *result = Err(RuntimeError::Internal(GIT_DIGEST_RECEIPT_FAILURE.into()));
3628        return GitDigestReceiptOutcome::PersistenceUnavailable;
3629    }
3630    GitDigestReceiptOutcome::Persisted
3631}
3632
3633/// Append an audit event, propagating a persistent failure for
3634/// obligation-bearing producers and swallowing it for pure-observability
3635/// producers.
3636///
3637/// ADR-133 D2/D3/D4: a dispatch must not report success when the row that
3638/// accounts for, authorizes, or audits it did not commit. Producers
3639/// classified [`crate::audit_batch::AuditProductionClass::DispatchObligation`]
3640/// (gate denials, dispatch outcomes, unknown-verb, git.digest receipts)
3641/// therefore return `Err` here on a persistent commit failure; the caller is
3642/// responsible for folding that into the dispatch result on the
3643/// success path — see [`fold_audit_obligation`]. Producers classified
3644/// [`crate::audit_batch::AuditProductionClass::PureObservability`]
3645/// (config-lock rows, `memory.recall` execution) degrade gracefully: the
3646/// failure is logged and counted but never returned, matching the pre-ADR-133
3647/// best-effort contract.
3648///
3649/// Every failure — obligation or observability — increments one of the
3650/// process-wide diagnostics counters above; the one exception is the
3651/// admission-degrade case below, which increments one of its own dedicated
3652/// [`AUDIT_ADMISSION_REFUSED_OBLIGATIONS`] /
3653/// [`AUDIT_ADMISSION_UNRESOLVED_OBLIGATIONS`] counters instead — it is
3654/// neither a swallowed observability failure nor a propagated obligation
3655/// failure.
3656///
3657/// `degrade_allowlisted` (khive#2147/khive#2217) narrows that obligation for
3658/// one specific case: a *successful* dispatch (`AuditProducer::DispatchSucceeded`)
3659/// for a verb that [`VerbRegistry::admission_degrade_safe`] has explicitly
3660/// opted in (Assertive alone is not a sufficient signal — see that method's
3661/// doc) performs no domain write, so this row's own admission being
3662/// transiently refused or timed out (`AuditTerminalReason::QueueAdmissionExhausted`
3663/// / `AdmissionDeadlineExpired`) degrades to best-effort instead of failing
3664/// the dispatch — the caller-visible read result is preserved. This function
3665/// derives eligibility from `producer` itself rather than trusting the
3666/// caller's `degrade_allowlisted` answer in isolation, so a `DispatchFailed`
3667/// row can never take the degrade path no matter what a caller passes: every
3668/// failed dispatch, every write verb, every gate-denial/unknown-verb/git.digest
3669/// row stays strictly obligation-bearing.
3670///
3671/// When the registry has an audit-batch seam configured (it is whenever
3672/// `store` is), the row routes through
3673/// [`crate::audit_batch::AuditBatchControl::submit`] instead of taking its
3674/// own writer-task acquisition — concurrent producers collapse onto one
3675/// commit per generation. `audit_batch: None` (a `VerbRegistry` predating
3676/// the seam, or constructed without going through the builder) falls back to
3677/// the pre-ADR-133 direct append, classified the same way.
3678async fn append_audit_event_best_effort(
3679    audit_batch: Option<&Arc<crate::audit_batch::AuditBatch>>,
3680    store: &Arc<dyn EventStore>,
3681    event: Event,
3682    verb: &str,
3683    producer: crate::audit_batch::AuditProducer,
3684    degrade_allowlisted: bool,
3685) -> Result<(), RuntimeError> {
3686    use crate::audit_batch::{
3687        classify, AuditBatchControl, AuditProducer, AuditProductionClass, AuditTerminalReason,
3688    };
3689
3690    let is_obligation = classify(producer) == AuditProductionClass::DispatchObligation;
3691    let admission_degrade_eligible =
3692        degrade_allowlisted && producer == AuditProducer::DispatchSucceeded;
3693
3694    if let Some(audit_batch) = audit_batch {
3695        if let Err(reason) = audit_batch
3696            .submit(crate::audit_batch::PreparedAuditRow { event, producer })
3697            .await
3698        {
3699            if is_obligation {
3700                // khive#2147/khive#2217: a read verb performs no domain write, so
3701                // when the audit-lane's OWN admission is merely under transient
3702                // pressure (the row was refused before enqueue, or the caller's
3703                // wait deadline elapsed on a row that is still likely to commit),
3704                // failing the read discards a valid result to protect an
3705                // obligation the read never needed as strictly as a write does.
3706                // Any other reason (a definite store/durability failure) still
3707                // fails the dispatch for reads exactly as it does for writes.
3708                //
3709                // The two admission-pressure reasons are not the same fact and
3710                // are counted on separate counters: `QueueAdmissionExhausted`
3711                // never enqueued, so it is a confirmed terminal loss, while
3712                // `AdmissionDeadlineExpired` was already enqueued and may still
3713                // commit later — see `AuditTerminalReason::AdmissionDeadlineExpired`'s
3714                // own doc.
3715                if admission_degrade_eligible {
3716                    match reason {
3717                        AuditTerminalReason::QueueAdmissionExhausted => {
3718                            AUDIT_ADMISSION_REFUSED_OBLIGATIONS
3719                                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3720                            tracing::warn!(
3721                                verb,
3722                                reason = ?reason,
3723                                "read verb's audit obligation row was refused before \
3724                                 enqueue under audit-lane admission pressure; dispatch \
3725                                 still reports its own result (non-fatal)"
3726                            );
3727                            return Ok(());
3728                        }
3729                        AuditTerminalReason::AdmissionDeadlineExpired => {
3730                            AUDIT_ADMISSION_UNRESOLVED_OBLIGATIONS
3731                                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3732                            tracing::warn!(
3733                                verb,
3734                                reason = ?reason,
3735                                "read verb's audit obligation row was still enqueued and \
3736                                 unresolved when the caller's admission wait deadline \
3737                                 elapsed; it may still commit. Dispatch still reports its \
3738                                 own result (non-fatal)"
3739                            );
3740                            return Ok(());
3741                        }
3742                        _ => {}
3743                    }
3744                }
3745                AUDIT_OBLIGATION_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3746                tracing::error!(
3747                    verb,
3748                    reason = ?reason,
3749                    "audit obligation batch submission failed; failing dispatch"
3750                );
3751                return Err(RuntimeError::Internal(format!(
3752                    "audit obligation commit failed for verb {verb:?}: {reason:?}"
3753                )));
3754            }
3755            AUDIT_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3756            tracing::warn!(
3757                verb,
3758                reason = ?reason,
3759                "audit event batch submission failed (non-fatal)"
3760            );
3761        }
3762        return Ok(());
3763    }
3764
3765    if let Err(store_err) = store.append_event(event).await {
3766        if is_obligation {
3767            AUDIT_OBLIGATION_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3768            tracing::error!(
3769                verb,
3770                error = %store_err,
3771                "audit obligation store write failed; failing dispatch"
3772            );
3773            return Err(RuntimeError::Internal(format!(
3774                "audit obligation commit failed for verb {verb:?}: {store_err}"
3775            )));
3776        }
3777        AUDIT_APPEND_FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3778        tracing::warn!(
3779            verb,
3780            error = %store_err,
3781            "audit event store write failed (non-fatal)"
3782        );
3783    }
3784    Ok(())
3785}
3786
3787/// Fold an audit-obligation outcome into a dispatch result.
3788///
3789/// A dispatch that would otherwise report success cannot claim it once the
3790/// row accounting for it fails to commit (ADR-133 D2/D3/D4), so `Ok` becomes
3791/// the audit's `Err`. A dispatch that already reports failure keeps its
3792/// original error — the obligation is on never reporting a false success,
3793/// not on replacing one error with another.
3794fn fold_audit_obligation<T>(
3795    result: Result<T, RuntimeError>,
3796    audit_outcome: Result<(), RuntimeError>,
3797) -> Result<T, RuntimeError> {
3798    match (result, audit_outcome) {
3799        (Ok(value), Ok(())) => Ok(value),
3800        (Ok(_), Err(audit_err)) => Err(audit_err),
3801        (Err(err), _) => Err(err),
3802    }
3803}
3804
3805/// Schema v2 audit payload for a successful singleton `link` call — additive
3806/// over v1 via `#[serde(flatten)]`. See `docs/api/pack.md#linkauditsuccessv2`.
3807#[derive(Debug, Clone, serde::Serialize)]
3808struct LinkAuditSuccessV2 {
3809    #[serde(flatten)]
3810    audit: AuditEvent,
3811    edge_id: uuid::Uuid,
3812    source_id: uuid::Uuid,
3813    target_id: uuid::Uuid,
3814    relation: String,
3815    weight: f64,
3816}
3817
3818/// Extract edge fields to enrich a successful singleton `link` audit row.
3819/// Returns `None` on any missing/malformed field (falls back to v1 shape).
3820/// See `docs/api/pack.md#link_audit_success_from_result`.
3821fn link_audit_success_from_result(
3822    audit: AuditEvent,
3823    result: &serde_json::Value,
3824) -> Option<(uuid::Uuid, serde_json::Value)> {
3825    let edge_id = result.get("id")?.as_str()?.parse::<uuid::Uuid>().ok()?;
3826    let source_id = result
3827        .get("source_id")?
3828        .as_str()?
3829        .parse::<uuid::Uuid>()
3830        .ok()?;
3831    let target_id = result
3832        .get("target_id")?
3833        .as_str()?
3834        .parse::<uuid::Uuid>()
3835        .ok()?;
3836    let relation = result.get("relation")?.as_str()?.to_string();
3837    let weight = result.get("weight")?.as_f64()?;
3838    let enriched = LinkAuditSuccessV2 {
3839        audit,
3840        edge_id,
3841        source_id,
3842        target_id,
3843        relation,
3844        weight,
3845    };
3846    let payload = serde_json::to_value(&enriched).ok()?;
3847    Some((edge_id, payload))
3848}
3849
3850/// Resolve and validate a caller-supplied `namespace` argument the same way
3851/// on every MCP ingress path.
3852///
3853/// - Absent `namespace` key → parse `default_namespace`.
3854/// - Present `namespace: "<string>"` → parse the caller's value.
3855/// - Present non-string `namespace` (null, number, bool, array, object) →
3856///   fail closed with `RuntimeError::InvalidInput`. ADR-018 requires this:
3857///   a malformed explicit value must never be silently coerced to the
3858///   default namespace.
3859///
3860/// Single chokepoint for both `VerbRegistry::dispatch` and the multi-backend
3861/// coordinator intercept — see `docs/api/pack.md#resolve_explicit_namespace`.
3862pub fn resolve_explicit_namespace(
3863    params: &Value,
3864    default_namespace: &str,
3865) -> Result<Namespace, RuntimeError> {
3866    match params.get("namespace") {
3867        None => Namespace::parse(default_namespace)
3868            .map_err(|e| RuntimeError::InvalidInput(format!("invalid namespace: {e}"))),
3869        Some(Value::String(ns_str)) => Namespace::parse(ns_str)
3870            .map_err(|e| RuntimeError::InvalidInput(format!("invalid namespace {ns_str:?}: {e}"))),
3871        Some(other) => Err(RuntimeError::InvalidInput(format!(
3872            "invalid namespace: expected string when present, got {}",
3873            json_type_name(other),
3874        ))),
3875    }
3876}
3877
3878/// JSON type name for error messages: describes a present-but-malformed
3879/// `namespace` value without echoing its contents.
3880pub fn json_type_name(v: &Value) -> &'static str {
3881    match v {
3882        Value::Null => "null",
3883        Value::Bool(_) => "boolean",
3884        Value::Number(_) => "number",
3885        Value::String(_) => "string",
3886        Value::Array(_) => "array",
3887        Value::Object(_) => "object",
3888    }
3889}
3890
3891// INLINE TEST JUSTIFICATION: tests here exercise VerbRegistry collision detection,
3892// gate enforcement, and dispatch ordering that depend on direct access to the
3893// registry's private `packs` Vec and gate field. Moving them to tests/ would
3894// require pub-exporting registry internals. Broad behavioral dispatch tests
3895// live in tests/integration.rs.
3896#[cfg(test)]
3897pub(crate) mod tests {
3898    use super::*;
3899    use crate::ActorRef;
3900    use khive_types::Pack;
3901
3902    /// Verbs known, by prior review (khive#2147/khive#2217 round 1), to have
3903    /// their own accounting-bearing side effect despite being declared
3904    /// `VerbCategory::Assertive` — see [`VerbRegistry::ADMISSION_DEGRADE_SAFE_VERBS`]'s
3905    /// doc for why each is excluded. `VerbCategory::Assertive` alone cannot
3906    /// distinguish these from a genuinely side-effect-free read (that is the
3907    /// whole reason the allowlist exists instead of a bare category check),
3908    /// so this denylist is the mechanizable guard against silently
3909    /// reintroducing one of them: a category-only census would stay green if
3910    /// either name were re-added to the allowlist.
3911    const KNOWN_INCIDENTAL_WRITE_VERBS: &[&str] = &["memory.recall", "db_diagnostics"];
3912
3913    /// khive-runtime links no real pack crates in its own test binary (see
3914    /// the comment on `CommProbeFactory` below), so
3915    /// [`VerbRegistry::ADMISSION_DEGRADE_SAFE_VERBS`] cannot be checked
3916    /// against a live registered `HandlerDef` here. Instead this
3917    /// re-derives each opted-in verb's classification from
3918    /// `khive-pack-kg/src/handler_defs.rs`'s live source — the same
3919    /// fail-closed pattern as `adr133_writer_census.rs`'s
3920    /// `reclassify_from_live_source`. Every entry in the allowlist is
3921    /// currently declared in that one file; a verb from a different pack
3922    /// would need this scan extended to that pack's source first.
3923    ///
3924    /// This test proves category membership (`VerbCategory::Assertive`) and
3925    /// non-membership in [`KNOWN_INCIDENTAL_WRITE_VERBS`]. It does NOT prove
3926    /// general effect-purity: an Assertive handler may still emit its own
3927    /// observability/config events on an independent, best-effort background
3928    /// path (`search`'s `SearchExecuted` telemetry, `context`'s one-time
3929    /// `ConfigLocked` event) that this test does not inspect and that this
3930    /// PR's admission-degrade mechanism does not touch — those events commit
3931    /// or fail on their own path regardless of what happens to this
3932    /// dispatch's own audit row. Proving general effect-purity would require
3933    /// an explicit per-handler effect/accounting capability tag, which is
3934    /// out of scope here (see ADR-103 Amendment 3's "why this is accepted"
3935    /// section); this census instead locks down the two properties that are
3936    /// mechanizable today: declared category, and the one known-bad-name
3937    /// regression class.
3938    #[test]
3939    fn admission_degrade_safe_verbs_are_registered_assertive() {
3940        let path = concat!(
3941            env!("CARGO_MANIFEST_DIR"),
3942            "/../khive-pack-kg/src/handler_defs.rs"
3943        );
3944        let source =
3945            std::fs::read_to_string(path).unwrap_or_else(|e| panic!("failed to read {path}: {e}"));
3946
3947        for verb in VerbRegistry::ADMISSION_DEGRADE_SAFE_VERBS {
3948            assert!(
3949                !KNOWN_INCIDENTAL_WRITE_VERBS.contains(verb),
3950                "admission-degrade-safe verb {verb:?} is a known incidental-write verb \
3951                 (khive#2147/khive#2217 round 1); it must not be re-added to \
3952                 ADMISSION_DEGRADE_SAFE_VERBS even though it is VerbCategory::Assertive"
3953            );
3954            // Anchored to exactly 8 leading spaces: that is the indentation
3955            // `HandlerDef { name: ... }` top-level fields use in this file,
3956            // versus 16 for a nested `ParamDef { name: ... }` — several
3957            // handlers (e.g. `search`) declare a `query`/`kind`/... param
3958            // whose own `name:` field would otherwise collide with a verb
3959            // of the same name declared later in the file.
3960            let needle = format!("\n        name: \"{verb}\",");
3961            let name_pos = source.find(&needle).unwrap_or_else(|| {
3962                panic!(
3963                    "admission-degrade-safe verb {verb:?} has no top-level `HandlerDef` in \
3964                     khive-pack-kg/src/handler_defs.rs; update the allowlist or this \
3965                     census's source path"
3966                )
3967            });
3968            // Each `HandlerDef` literal in this file declares `category:`
3969            // shortly after `name:`, well before the next handler's own
3970            // `name:` field — bound the scan to the text up to the next
3971            // `HandlerDef {` (or EOF) so a later handler's category can
3972            // never be misattributed to this one.
3973            let block_end = source[name_pos..]
3974                .find("HandlerDef {")
3975                .map(|offset| name_pos + offset)
3976                .unwrap_or(source.len());
3977            let block = &source[name_pos..block_end];
3978            assert!(
3979                block.contains("VerbCategory::Assertive"),
3980                "admission-degrade-safe verb {verb:?} is declared in \
3981                 khive-pack-kg/src/handler_defs.rs but is not VerbCategory::Assertive; \
3982                 admission degradation must not silently apply to a write-capable verb"
3983            );
3984        }
3985    }
3986
3987    static COMM_PROBE_GRANTED: std::sync::atomic::AtomicBool =
3988        std::sync::atomic::AtomicBool::new(false);
3989    static OTHER_PROBE_GRANTED: std::sync::atomic::AtomicBool =
3990        std::sync::atomic::AtomicBool::new(false);
3991
3992    /// Probe factories proving the channel-ingest grant is name-bounded.
3993    /// khive-runtime's own test binary links no real pack crates, so the
3994    /// `comm` name is free for the probe here.
3995    struct CommProbeFactory;
3996    struct OtherProbeFactory;
3997
3998    fn probe_pack(
3999        _runtime: KhiveRuntime,
4000        grant_flag: &'static std::sync::atomic::AtomicBool,
4001    ) -> Box<dyn PackRuntime> {
4002        struct ProbePack {
4003            grant_flag: &'static std::sync::atomic::AtomicBool,
4004        }
4005        #[async_trait::async_trait]
4006        impl PackRuntime for ProbePack {
4007            fn name(&self) -> &str {
4008                "probe"
4009            }
4010            fn note_kinds(&self) -> &'static [&'static str] {
4011                &[]
4012            }
4013            fn entity_kinds(&self) -> &'static [&'static str] {
4014                &[]
4015            }
4016            fn handlers(&self) -> &'static [HandlerDef] {
4017                &[]
4018            }
4019            fn accept_channel_ingest_capability(&self, _capability: ChannelIngestCapability) {
4020                self.grant_flag
4021                    .store(true, std::sync::atomic::Ordering::SeqCst);
4022            }
4023            async fn dispatch(
4024                &self,
4025                _verb: &str,
4026                _params: serde_json::Value,
4027                _registry: &VerbRegistry,
4028                _token: &NamespaceToken,
4029            ) -> Result<serde_json::Value, crate::RuntimeError> {
4030                Err(crate::RuntimeError::InvalidInput("probe".into()))
4031            }
4032        }
4033        Box::new(ProbePack { grant_flag })
4034    }
4035
4036    impl PackFactory for CommProbeFactory {
4037        fn name(&self) -> &'static str {
4038            "comm"
4039        }
4040        fn create(&self, runtime: KhiveRuntime) -> Box<dyn PackRuntime> {
4041            probe_pack(runtime, &COMM_PROBE_GRANTED)
4042        }
4043    }
4044
4045    impl PackFactory for OtherProbeFactory {
4046        fn name(&self) -> &'static str {
4047            "grant-probe-other"
4048        }
4049        fn create(&self, runtime: KhiveRuntime) -> Box<dyn PackRuntime> {
4050            probe_pack(runtime, &OTHER_PROBE_GRANTED)
4051        }
4052    }
4053
4054    inventory::submit! { PackRegistration(&CommProbeFactory) }
4055    inventory::submit! { PackRegistration(&OtherProbeFactory) }
4056
4057    #[test]
4058    fn channel_ingest_grant_reaches_only_allowlisted_pack_names() {
4059        let runtime = KhiveRuntime::memory().unwrap();
4060        let mut builder = VerbRegistryBuilder::new();
4061        PackRegistry::register_packs(
4062            &["comm".to_string(), "grant-probe-other".to_string()],
4063            runtime,
4064            &mut builder,
4065        )
4066        .expect("probe registration succeeds");
4067        assert!(
4068            COMM_PROBE_GRANTED.load(std::sync::atomic::Ordering::SeqCst),
4069            "the comm-named factory must receive the channel-ingest grant"
4070        );
4071        assert!(
4072            !OTHER_PROBE_GRANTED.load(std::sync::atomic::Ordering::SeqCst),
4073            "a factory outside CHANNEL_INGEST_CAPABLE_PACKS must never be granted"
4074        );
4075    }
4076
4077    #[test]
4078    fn from_token_preserves_process_ref() {
4079        let with_ref = NamespaceToken::mint_authorized(
4080            Namespace::local(),
4081            ActorRef::new("agent", "provenance-carrier"),
4082        )
4083        .with_process_ref(Some("proc:origin-abc123".to_string()));
4084        let identity = RequestIdentity::from_token(&with_ref);
4085        assert_eq!(identity.process_ref.as_deref(), Some("proc:origin-abc123"));
4086
4087        let without_ref = NamespaceToken::mint_authorized(
4088            Namespace::local(),
4089            ActorRef::new("agent", "provenance-absent"),
4090        );
4091        let identity = RequestIdentity::from_token(&without_ref);
4092        assert_eq!(identity.process_ref, None);
4093    }
4094
4095    struct AlphaPack;
4096
4097    impl Pack for AlphaPack {
4098        const NAME: &'static str = "alpha";
4099        const NOTE_KINDS: &'static [&'static str] = &["memo", "log"];
4100        const ENTITY_KINDS: &'static [&'static str] = &["widget"];
4101        const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["recall", "search"];
4102        const HANDLERS: &'static [HandlerDef] = &[
4103            HandlerDef {
4104                name: "create",
4105                description: "create a widget",
4106                visibility: Visibility::Verb,
4107                category: VerbCategory::Commissive,
4108                params: &[],
4109            },
4110            HandlerDef {
4111                name: "list",
4112                description: "list widgets",
4113                visibility: Visibility::Verb,
4114                category: VerbCategory::Assertive,
4115                params: &[],
4116            },
4117        ];
4118    }
4119
4120    #[async_trait]
4121    impl PackRuntime for AlphaPack {
4122        fn name(&self) -> &str {
4123            AlphaPack::NAME
4124        }
4125        fn note_kinds(&self) -> &'static [&'static str] {
4126            AlphaPack::NOTE_KINDS
4127        }
4128        fn entity_kinds(&self) -> &'static [&'static str] {
4129            AlphaPack::ENTITY_KINDS
4130        }
4131        fn brain_consumer_kinds(&self) -> &'static [&'static str] {
4132            AlphaPack::BRAIN_CONSUMER_KINDS
4133        }
4134        fn handlers(&self) -> &'static [HandlerDef] {
4135            AlphaPack::HANDLERS
4136        }
4137        async fn dispatch(
4138            &self,
4139            verb: &str,
4140            _params: Value,
4141            _registry: &VerbRegistry,
4142            _token: &NamespaceToken,
4143        ) -> Result<Value, RuntimeError> {
4144            Ok(serde_json::json!({ "pack": "alpha", "verb": verb }))
4145        }
4146    }
4147
4148    #[derive(Debug)]
4149    struct GateErrorTrackingPack {
4150        invoked: Arc<AtomicUsize>,
4151    }
4152
4153    impl Pack for GateErrorTrackingPack {
4154        const NAME: &'static str = "gate_error_tracking";
4155        const NOTE_KINDS: &'static [&'static str] = &[];
4156        const ENTITY_KINDS: &'static [&'static str] = &[];
4157        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
4158            name: "guarded",
4159            description: "track whether gate-error dispatch reaches the handler",
4160            visibility: Visibility::Verb,
4161            category: VerbCategory::Assertive,
4162            params: &[],
4163        }];
4164    }
4165
4166    #[async_trait]
4167    impl PackRuntime for GateErrorTrackingPack {
4168        fn name(&self) -> &str {
4169            Self::NAME
4170        }
4171
4172        fn note_kinds(&self) -> &'static [&'static str] {
4173            Self::NOTE_KINDS
4174        }
4175
4176        fn entity_kinds(&self) -> &'static [&'static str] {
4177            Self::ENTITY_KINDS
4178        }
4179
4180        fn handlers(&self) -> &'static [HandlerDef] {
4181            Self::HANDLERS
4182        }
4183
4184        async fn dispatch(
4185            &self,
4186            _verb: &str,
4187            _params: Value,
4188            _registry: &VerbRegistry,
4189            _token: &NamespaceToken,
4190        ) -> Result<Value, RuntimeError> {
4191            self.invoked.fetch_add(1, Ordering::SeqCst);
4192            Ok(serde_json::json!({"invoked": true}))
4193        }
4194    }
4195
4196    /// A pack whose `dispatch` sleeps for a fixed, generous duration so
4197    /// `duration_us` regression tests (ADR-103 Stage 1) have a reliably
4198    /// nonzero, non-flaky measured dispatch time to assert against.
4199    struct SleepingPack;
4200
4201    impl Pack for SleepingPack {
4202        const NAME: &'static str = "sleeping";
4203        const NOTE_KINDS: &'static [&'static str] = &[];
4204        const ENTITY_KINDS: &'static [&'static str] = &[];
4205        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
4206            name: "slow_op",
4207            description: "sleeps before returning",
4208            visibility: Visibility::Verb,
4209            category: VerbCategory::Assertive,
4210            params: &[],
4211        }];
4212    }
4213
4214    #[async_trait]
4215    impl PackRuntime for SleepingPack {
4216        fn name(&self) -> &str {
4217            SleepingPack::NAME
4218        }
4219        fn note_kinds(&self) -> &'static [&'static str] {
4220            SleepingPack::NOTE_KINDS
4221        }
4222        fn entity_kinds(&self) -> &'static [&'static str] {
4223            SleepingPack::ENTITY_KINDS
4224        }
4225        fn handlers(&self) -> &'static [HandlerDef] {
4226            SleepingPack::HANDLERS
4227        }
4228        async fn dispatch(
4229            &self,
4230            verb: &str,
4231            _params: Value,
4232            _registry: &VerbRegistry,
4233            _token: &NamespaceToken,
4234        ) -> Result<Value, RuntimeError> {
4235            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
4236            Ok(serde_json::json!({ "pack": "sleeping", "verb": verb }))
4237        }
4238    }
4239
4240    struct BetaPack;
4241
4242    impl Pack for BetaPack {
4243        const NAME: &'static str = "beta";
4244        const NOTE_KINDS: &'static [&'static str] = &["alert"];
4245        const ENTITY_KINDS: &'static [&'static str] = &["widget", "gadget"];
4246        const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["search", "knowledge_compose"];
4247        const HANDLERS: &'static [HandlerDef] = &[
4248            HandlerDef {
4249                name: "notify",
4250                description: "send alert",
4251                visibility: Visibility::Verb,
4252                category: VerbCategory::Commissive,
4253                params: &[],
4254            },
4255            // "create" is Subhandler so it does NOT collide with AlphaPack's
4256            // Verb-visibility "create" — subhandlers are pack-internal and
4257            // excluded from cross-pack collision detection.
4258            HandlerDef {
4259                name: "create",
4260                description: "beta internal create (subhandler)",
4261                visibility: Visibility::Subhandler,
4262                category: VerbCategory::Commissive,
4263                params: &[],
4264            },
4265        ];
4266    }
4267
4268    /// Build a registry with AlphaPack + BetaPack.
4269    ///
4270    /// BetaPack's `create` is Subhandler so there is no Verb-visibility
4271    /// collision with AlphaPack's `create` Verb. Tests that need a collision
4272    /// use `build_colliding_registry()` instead.
4273    fn build_registry() -> VerbRegistry {
4274        let mut builder = VerbRegistryBuilder::new();
4275        builder.register(AlphaPack);
4276        builder.register(BetaPack);
4277        builder.build().expect("registry builds without collision")
4278    }
4279
4280    /// Build a registry with two packs that declare the same Verb-visibility
4281    /// handler — used to test that `VerbCollision` is raised at build time.
4282    struct CollidingPack;
4283
4284    impl Pack for CollidingPack {
4285        const NAME: &'static str = "colliding";
4286        const NOTE_KINDS: &'static [&'static str] = &[];
4287        const ENTITY_KINDS: &'static [&'static str] = &[];
4288        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
4289            name: "create",
4290            description: "duplicate Verb-visibility create",
4291            visibility: Visibility::Verb,
4292            category: VerbCategory::Commissive,
4293            params: &[],
4294        }];
4295    }
4296
4297    #[async_trait]
4298    impl PackRuntime for CollidingPack {
4299        fn name(&self) -> &str {
4300            Self::NAME
4301        }
4302        fn note_kinds(&self) -> &'static [&'static str] {
4303            Self::NOTE_KINDS
4304        }
4305        fn entity_kinds(&self) -> &'static [&'static str] {
4306            Self::ENTITY_KINDS
4307        }
4308        fn handlers(&self) -> &'static [HandlerDef] {
4309            Self::HANDLERS
4310        }
4311        async fn dispatch(
4312            &self,
4313            verb: &str,
4314            _params: Value,
4315            _registry: &VerbRegistry,
4316            _token: &NamespaceToken,
4317        ) -> Result<Value, RuntimeError> {
4318            Ok(serde_json::json!({ "pack": "colliding", "verb": verb }))
4319        }
4320    }
4321
4322    struct ReservedEnvelopeParamPack;
4323
4324    impl Pack for ReservedEnvelopeParamPack {
4325        const NAME: &'static str = "reserved-envelope-param";
4326        const NOTE_KINDS: &'static [&'static str] = &[];
4327        const ENTITY_KINDS: &'static [&'static str] = &[];
4328        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
4329            name: "broken.serve",
4330            description: "declares a transport-owned argument",
4331            visibility: Visibility::Verb,
4332            category: VerbCategory::Commissive,
4333            params: &[ParamDef {
4334                name: "presentation",
4335                param_type: "object",
4336                required: false,
4337                description: "invalid collision with the request envelope",
4338            }],
4339        }];
4340    }
4341
4342    #[async_trait]
4343    impl PackRuntime for ReservedEnvelopeParamPack {
4344        fn name(&self) -> &str {
4345            Self::NAME
4346        }
4347        fn note_kinds(&self) -> &'static [&'static str] {
4348            Self::NOTE_KINDS
4349        }
4350        fn entity_kinds(&self) -> &'static [&'static str] {
4351            Self::ENTITY_KINDS
4352        }
4353        fn handlers(&self) -> &'static [HandlerDef] {
4354            Self::HANDLERS
4355        }
4356        async fn dispatch(
4357            &self,
4358            _verb: &str,
4359            _params: Value,
4360            _registry: &VerbRegistry,
4361            _token: &NamespaceToken,
4362        ) -> Result<Value, RuntimeError> {
4363            unreachable!("invalid handler metadata must fail before dispatch")
4364        }
4365    }
4366
4367    #[async_trait]
4368    impl PackRuntime for BetaPack {
4369        fn name(&self) -> &str {
4370            BetaPack::NAME
4371        }
4372        fn note_kinds(&self) -> &'static [&'static str] {
4373            BetaPack::NOTE_KINDS
4374        }
4375        fn entity_kinds(&self) -> &'static [&'static str] {
4376            BetaPack::ENTITY_KINDS
4377        }
4378        fn brain_consumer_kinds(&self) -> &'static [&'static str] {
4379            BetaPack::BRAIN_CONSUMER_KINDS
4380        }
4381        fn handlers(&self) -> &'static [HandlerDef] {
4382            BetaPack::HANDLERS
4383        }
4384        async fn dispatch(
4385            &self,
4386            verb: &str,
4387            _params: Value,
4388            _registry: &VerbRegistry,
4389            _token: &NamespaceToken,
4390        ) -> Result<Value, RuntimeError> {
4391            Ok(serde_json::json!({ "pack": "beta", "verb": verb }))
4392        }
4393    }
4394
4395    #[tokio::test]
4396    async fn dispatch_routes_to_correct_pack() {
4397        let reg = build_registry();
4398
4399        let res = reg.dispatch("list", Value::Null).await.unwrap();
4400        assert_eq!(res["pack"], "alpha");
4401
4402        let res = reg.dispatch("notify", Value::Null).await.unwrap();
4403        assert_eq!(res["pack"], "beta");
4404    }
4405
4406    /// Two packs declaring the same `Visibility::Verb` handler must be
4407    /// rejected at build time — the old "first registered wins" behaviour is
4408    /// replaced by a boot error.
4409    #[test]
4410    fn verb_collision_is_boot_time_error() {
4411        let mut builder = VerbRegistryBuilder::new();
4412        builder.register(AlphaPack);
4413        builder.register(CollidingPack);
4414        let err = builder
4415            .build()
4416            .err()
4417            .expect("duplicate Verb-visibility handler must be rejected at build time");
4418        assert!(
4419            matches!(err, RuntimeError::VerbCollision { ref verb, .. } if verb == "create"),
4420            "expected VerbCollision for 'create', got {err:?}"
4421        );
4422        let msg = err.to_string();
4423        assert!(
4424            msg.contains("create"),
4425            "error must name the colliding verb: {msg}"
4426        );
4427        assert!(
4428            msg.contains("alpha") || msg.contains("colliding"),
4429            "error must name one of the conflicting packs: {msg}"
4430        );
4431    }
4432
4433    #[test]
4434    fn reserved_request_envelope_param_is_boot_time_error() {
4435        let mut builder = VerbRegistryBuilder::new();
4436        builder.register(ReservedEnvelopeParamPack);
4437        let error = builder
4438            .build()
4439            .err()
4440            .expect("transport-owned parameter names must fail registry construction");
4441        assert!(
4442            matches!(
4443                error,
4444                RuntimeError::ReservedEnvelopeParam {
4445                    ref pack,
4446                    ref verb,
4447                    ref param,
4448                } if pack == "reserved-envelope-param"
4449                    && verb == "broken.serve"
4450                    && param == "presentation"
4451            ),
4452            "unexpected error: {error:?}"
4453        );
4454    }
4455
4456    #[test]
4457    fn reserved_request_envelope_param_is_boot_time_error_for_subhandler() {
4458        struct ReservedEnvelopeSubhandlerParamPack;
4459
4460        impl Pack for ReservedEnvelopeSubhandlerParamPack {
4461            const NAME: &'static str = "reserved-envelope-subhandler-param";
4462            const NOTE_KINDS: &'static [&'static str] = &[];
4463            const ENTITY_KINDS: &'static [&'static str] = &[];
4464            const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
4465                name: "broken.internal",
4466                description: "declares a transport-owned argument on an internal handler",
4467                visibility: Visibility::Subhandler,
4468                category: VerbCategory::Assertive,
4469                params: &[ParamDef {
4470                    name: "presentation_per_op",
4471                    param_type: "string",
4472                    required: false,
4473                    description: "invalid collision with the request envelope",
4474                }],
4475            }];
4476        }
4477
4478        #[async_trait]
4479        impl PackRuntime for ReservedEnvelopeSubhandlerParamPack {
4480            fn name(&self) -> &str {
4481                Self::NAME
4482            }
4483            fn note_kinds(&self) -> &'static [&'static str] {
4484                Self::NOTE_KINDS
4485            }
4486            fn entity_kinds(&self) -> &'static [&'static str] {
4487                Self::ENTITY_KINDS
4488            }
4489            fn handlers(&self) -> &'static [HandlerDef] {
4490                Self::HANDLERS
4491            }
4492            async fn dispatch(
4493                &self,
4494                _verb: &str,
4495                _params: Value,
4496                _registry: &VerbRegistry,
4497                _token: &NamespaceToken,
4498            ) -> Result<Value, RuntimeError> {
4499                unreachable!("invalid handler metadata must fail before dispatch")
4500            }
4501        }
4502
4503        let mut builder = VerbRegistryBuilder::new();
4504        builder.register(ReservedEnvelopeSubhandlerParamPack);
4505        let error = builder
4506            .build()
4507            .err()
4508            .expect("transport-owned parameter names must fail registry construction");
4509        assert!(
4510            matches!(
4511                error,
4512                RuntimeError::ReservedEnvelopeParam {
4513                    ref pack,
4514                    ref verb,
4515                    ref param,
4516                } if pack == "reserved-envelope-subhandler-param"
4517                    && verb == "broken.internal"
4518                    && param == "presentation_per_op"
4519            ),
4520            "unexpected error: {error:?}"
4521        );
4522    }
4523
4524    /// Subhandler-visibility handlers with the same name across packs are NOT
4525    /// a collision — they are pack-internal and excluded from cross-pack
4526    /// collision detection.
4527    #[test]
4528    fn subhandler_same_name_across_packs_is_not_a_collision() {
4529        struct SubhandlerPack;
4530        impl Pack for SubhandlerPack {
4531            const NAME: &'static str = "subhandler_pack";
4532            const NOTE_KINDS: &'static [&'static str] = &[];
4533            const ENTITY_KINDS: &'static [&'static str] = &[];
4534            const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
4535                name: "create",
4536                description: "internal create",
4537                visibility: Visibility::Subhandler,
4538                category: VerbCategory::Commissive,
4539                params: &[],
4540            }];
4541        }
4542        #[async_trait]
4543        impl PackRuntime for SubhandlerPack {
4544            fn name(&self) -> &str {
4545                Self::NAME
4546            }
4547            fn note_kinds(&self) -> &'static [&'static str] {
4548                Self::NOTE_KINDS
4549            }
4550            fn entity_kinds(&self) -> &'static [&'static str] {
4551                Self::ENTITY_KINDS
4552            }
4553            fn handlers(&self) -> &'static [HandlerDef] {
4554                Self::HANDLERS
4555            }
4556            async fn dispatch(
4557                &self,
4558                verb: &str,
4559                _: Value,
4560                _: &VerbRegistry,
4561                _: &NamespaceToken,
4562            ) -> Result<Value, RuntimeError> {
4563                Ok(serde_json::json!({"pack": "subhandler_pack", "verb": verb}))
4564            }
4565        }
4566        let mut builder = VerbRegistryBuilder::new();
4567        builder.register(AlphaPack); // AlphaPack has Verb "create"
4568        builder.register(SubhandlerPack); // SubhandlerPack has Subhandler "create" — no collision
4569        builder
4570            .build()
4571            .expect("subhandler same name must NOT be a collision");
4572    }
4573
4574    #[tokio::test]
4575    async fn dispatch_unknown_verb_returns_error() {
4576        let reg = build_registry();
4577
4578        let err = reg.dispatch("explode", Value::Null).await.unwrap_err();
4579        let msg = err.to_string();
4580        assert!(msg.contains("explode"));
4581        assert!(msg.contains("create"));
4582    }
4583
4584    /// `all_verbs` returns only `Visibility::Verb` entries.
4585    ///
4586    /// BetaPack's `create` is `Visibility::Subhandler` — it must NOT appear
4587    /// in `all_verbs()` even though it has the same name as a Verb in AlphaPack.
4588    #[test]
4589    fn all_verbs_aggregates_across_packs_excludes_subhandlers() {
4590        let reg = build_registry();
4591        let verbs: Vec<&str> = reg.all_verbs().iter().map(|v| v.name).collect();
4592        // BetaPack's "create" (Subhandler) is absent; only Verb-visibility entries appear.
4593        assert_eq!(verbs, vec!["create", "list", "notify"]);
4594    }
4595
4596    #[test]
4597    fn all_verbs_with_names_pairs_pack_name_excludes_subhandlers() {
4598        let reg = build_registry();
4599        let pairs: Vec<(&str, &str)> = reg
4600            .all_verbs_with_names()
4601            .iter()
4602            .map(|(pack, v)| (*pack, v.name))
4603            .collect();
4604        // BetaPack's "create" is Subhandler and must NOT appear here.
4605        assert_eq!(
4606            pairs,
4607            vec![("alpha", "create"), ("alpha", "list"), ("beta", "notify"),]
4608        );
4609    }
4610
4611    #[test]
4612    fn all_handlers_with_names_includes_subhandlers() {
4613        let reg = build_registry();
4614        let pairs: Vec<(&str, &str)> = reg
4615            .all_handlers_with_names()
4616            .iter()
4617            .map(|(pack, v)| (*pack, v.name))
4618            .collect();
4619        // BetaPack's Subhandler "create" IS present in the full handler list.
4620        assert_eq!(
4621            pairs,
4622            vec![
4623                ("alpha", "create"),
4624                ("alpha", "list"),
4625                ("beta", "notify"),
4626                ("beta", "create"),
4627            ]
4628        );
4629    }
4630
4631    #[test]
4632    fn note_kinds_are_ordered() {
4633        let reg = build_registry();
4634        let kinds = reg.all_note_kinds();
4635        assert_eq!(kinds, vec!["memo", "log", "alert"]);
4636    }
4637
4638    #[test]
4639    fn brain_consumer_kinds_are_ordered_and_deduplicated() {
4640        let reg = build_registry();
4641        assert_eq!(
4642            reg.all_brain_consumer_kinds(),
4643            vec!["recall", "search", "knowledge_compose"]
4644        );
4645    }
4646
4647    #[test]
4648    fn brain_consumer_kind_wildcard_is_rejected_at_build_time() {
4649        struct WildcardConsumerPack;
4650
4651        impl khive_types::Pack for WildcardConsumerPack {
4652            const NAME: &'static str = "wildcard-consumer";
4653            const NOTE_KINDS: &'static [&'static str] = &[];
4654            const ENTITY_KINDS: &'static [&'static str] = &[];
4655            const BRAIN_CONSUMER_KINDS: &'static [&'static str] = &["*"];
4656            const HANDLERS: &'static [HandlerDef] = &[];
4657        }
4658
4659        #[async_trait]
4660        impl PackRuntime for WildcardConsumerPack {
4661            fn name(&self) -> &str {
4662                Self::NAME
4663            }
4664            fn note_kinds(&self) -> &'static [&'static str] {
4665                Self::NOTE_KINDS
4666            }
4667            fn entity_kinds(&self) -> &'static [&'static str] {
4668                Self::ENTITY_KINDS
4669            }
4670            fn brain_consumer_kinds(&self) -> &'static [&'static str] {
4671                Self::BRAIN_CONSUMER_KINDS
4672            }
4673            fn handlers(&self) -> &'static [HandlerDef] {
4674                Self::HANDLERS
4675            }
4676            async fn dispatch(
4677                &self,
4678                _verb: &str,
4679                _params: Value,
4680                _registry: &VerbRegistry,
4681                _token: &NamespaceToken,
4682            ) -> Result<Value, RuntimeError> {
4683                Ok(Value::Null)
4684            }
4685        }
4686
4687        let mut builder = VerbRegistryBuilder::new();
4688        builder.register(WildcardConsumerPack);
4689        let Err(RuntimeError::InvalidInput(message)) = builder.build() else {
4690            panic!("registry must reject a pack-declared brain wildcard");
4691        };
4692        assert!(message.contains("wildcard-consumer"), "{message}");
4693        assert!(message.contains("registry-owned"), "{message}");
4694    }
4695
4696    #[test]
4697    fn note_kind_duplicate_rejected_at_build_time() {
4698        struct DupPack;
4699
4700        impl khive_types::Pack for DupPack {
4701            const NAME: &'static str = "dup";
4702            // "memo" is already declared by AlphaPack — must be rejected at build.
4703            const NOTE_KINDS: &'static [&'static str] = &["memo"];
4704            const ENTITY_KINDS: &'static [&'static str] = &[];
4705            const HANDLERS: &'static [HandlerDef] = &[];
4706        }
4707
4708        #[async_trait]
4709        impl PackRuntime for DupPack {
4710            fn name(&self) -> &str {
4711                Self::NAME
4712            }
4713            fn note_kinds(&self) -> &'static [&'static str] {
4714                Self::NOTE_KINDS
4715            }
4716            fn entity_kinds(&self) -> &'static [&'static str] {
4717                Self::ENTITY_KINDS
4718            }
4719            fn handlers(&self) -> &'static [HandlerDef] {
4720                Self::HANDLERS
4721            }
4722            async fn dispatch(
4723                &self,
4724                _verb: &str,
4725                _params: Value,
4726                _registry: &VerbRegistry,
4727                _token: &NamespaceToken,
4728            ) -> Result<Value, RuntimeError> {
4729                Ok(Value::Null)
4730            }
4731        }
4732
4733        let mut builder = VerbRegistryBuilder::new();
4734        builder.register(AlphaPack);
4735        builder.register(DupPack);
4736        let err = builder
4737            .build()
4738            .err()
4739            .expect("duplicate note kind must be rejected");
4740        let msg = err.to_string();
4741        assert!(
4742            msg.contains("memo"),
4743            "error must name the duplicate kind: {msg}"
4744        );
4745        assert!(
4746            msg.contains("alpha") || msg.contains("dup"),
4747            "error must name one of the conflicting packs: {msg}"
4748        );
4749    }
4750
4751    #[test]
4752    fn entity_kinds_are_deduplicated() {
4753        let reg = build_registry();
4754        let kinds = reg.all_entity_kinds();
4755        assert_eq!(kinds, vec!["widget", "gadget"]);
4756    }
4757
4758    // ---- ENTITY_TYPES composition (pack-declared entity-type subtypes) ----
4759
4760    struct GammaPack;
4761
4762    impl Pack for GammaPack {
4763        const NAME: &'static str = "gamma";
4764        const NOTE_KINDS: &'static [&'static str] = &[];
4765        const ENTITY_KINDS: &'static [&'static str] = &[];
4766        const HANDLERS: &'static [HandlerDef] = &[];
4767        const ENTITY_TYPES: &'static [EntityTypeDef] = &[EntityTypeDef {
4768            kind: khive_types::EntityKind::Document,
4769            type_name: "gamma_report",
4770            aliases: &["gamma_rep"],
4771        }];
4772    }
4773
4774    #[async_trait]
4775    impl PackRuntime for GammaPack {
4776        fn name(&self) -> &str {
4777            Self::NAME
4778        }
4779        fn note_kinds(&self) -> &'static [&'static str] {
4780            Self::NOTE_KINDS
4781        }
4782        fn entity_kinds(&self) -> &'static [&'static str] {
4783            Self::ENTITY_KINDS
4784        }
4785        fn handlers(&self) -> &'static [HandlerDef] {
4786            Self::HANDLERS
4787        }
4788        fn entity_types(&self) -> &'static [EntityTypeDef] {
4789            Self::ENTITY_TYPES
4790        }
4791        async fn dispatch(
4792            &self,
4793            verb: &str,
4794            _params: Value,
4795            _registry: &VerbRegistry,
4796            _token: &NamespaceToken,
4797        ) -> Result<Value, RuntimeError> {
4798            Ok(serde_json::json!({ "pack": "gamma", "verb": verb }))
4799        }
4800    }
4801
4802    /// Builtin-only behavior is unchanged when no pack declares extras:
4803    /// `all_entity_types()` is empty, and composing it with the builtin
4804    /// registry resolves exactly like `EntityTypeRegistry::builtin()`.
4805    #[test]
4806    fn all_entity_types_empty_when_no_pack_declares_extras() {
4807        let reg = build_registry(); // AlphaPack + BetaPack — neither declares ENTITY_TYPES.
4808        assert!(reg.all_entity_types().is_empty());
4809        let composed = khive_types::EntityTypeRegistry::with_extra(reg.all_entity_types());
4810        let resolved = composed
4811            .resolve(khive_types::EntityKind::Document, Some("paper"))
4812            .expect("builtin paper subtype must still resolve");
4813        assert_eq!(resolved.entity_type.as_deref(), Some("paper"));
4814    }
4815
4816    /// A pack-declared entity type validates through the composed registry,
4817    /// and builtin subtypes remain resolvable alongside it.
4818    #[test]
4819    fn pack_declared_entity_type_validates_through_composed_registry() {
4820        let mut builder = VerbRegistryBuilder::new();
4821        builder.register(AlphaPack);
4822        builder.register(GammaPack);
4823        let reg = builder.build().expect("registry builds");
4824
4825        let extras = reg.all_entity_types();
4826        assert_eq!(extras.len(), 1);
4827
4828        let composed = khive_types::EntityTypeRegistry::with_extra(extras);
4829        let resolved = composed
4830            .resolve(khive_types::EntityKind::Document, Some("gamma_rep"))
4831            .expect("pack-declared alias must resolve through the composed registry");
4832        assert_eq!(resolved.entity_type.as_deref(), Some("gamma_report"));
4833
4834        let builtin_resolved = composed
4835            .resolve(khive_types::EntityKind::Document, Some("paper"))
4836            .expect("builtin subtype must remain resolvable when a pack adds extras");
4837        assert_eq!(builtin_resolved.entity_type.as_deref(), Some("paper"));
4838
4839        composed
4840            .resolve(khive_types::EntityKind::Document, Some("nonexistent_type"))
4841            .expect_err("undeclared entity_type must still be rejected");
4842    }
4843
4844    /// Two packs declaring the exact same `(kind, type_name)` subtype are
4845    /// rejected at `build()` — ADR-001's registry-ownership collision rule
4846    /// ("same `(base_kind, canonical_name)` from two different packs = boot
4847    /// error") — instead of silently resolving via registration order the
4848    /// way `EntityTypeRegistry::with_extra`'s hard-`insert` semantics would.
4849    #[test]
4850    fn overlapping_pack_declared_entity_types_reject_at_boot() {
4851        struct DeltaPack;
4852        impl Pack for DeltaPack {
4853            const NAME: &'static str = "delta";
4854            const NOTE_KINDS: &'static [&'static str] = &[];
4855            const ENTITY_KINDS: &'static [&'static str] = &[];
4856            const HANDLERS: &'static [HandlerDef] = &[];
4857            const ENTITY_TYPES: &'static [EntityTypeDef] = &[EntityTypeDef {
4858                kind: khive_types::EntityKind::Document,
4859                type_name: "gamma_report",
4860                aliases: &["gamma_rep"],
4861            }];
4862        }
4863        #[async_trait]
4864        impl PackRuntime for DeltaPack {
4865            fn name(&self) -> &str {
4866                Self::NAME
4867            }
4868            fn note_kinds(&self) -> &'static [&'static str] {
4869                Self::NOTE_KINDS
4870            }
4871            fn entity_kinds(&self) -> &'static [&'static str] {
4872                Self::ENTITY_KINDS
4873            }
4874            fn handlers(&self) -> &'static [HandlerDef] {
4875                Self::HANDLERS
4876            }
4877            fn entity_types(&self) -> &'static [EntityTypeDef] {
4878                Self::ENTITY_TYPES
4879            }
4880            async fn dispatch(
4881                &self,
4882                verb: &str,
4883                _params: Value,
4884                _registry: &VerbRegistry,
4885                _token: &NamespaceToken,
4886            ) -> Result<Value, RuntimeError> {
4887                Ok(serde_json::json!({ "pack": "delta", "verb": verb }))
4888            }
4889        }
4890
4891        let mut builder = VerbRegistryBuilder::new();
4892        builder.register(GammaPack);
4893        builder.register(DeltaPack);
4894        let err = builder.build().err().expect(
4895            "overlapping ENTITY_TYPES declarations must fail at build, not silently compose",
4896        );
4897
4898        let msg = err.to_string();
4899        assert!(
4900            msg.contains("gamma") && msg.contains("delta"),
4901            "collision error must name both contributing packs: {msg}"
4902        );
4903        assert!(
4904            msg.contains("gamma_report"),
4905            "collision error must name the colliding entity_type key: {msg}"
4906        );
4907    }
4908
4909    // ---- Gate wiring ----
4910
4911    use khive_gate::{Gate, GateError};
4912    use std::sync::atomic::{AtomicUsize, Ordering};
4913    use std::sync::Arc;
4914
4915    #[derive(Default, Debug)]
4916    struct CountingGate {
4917        calls: AtomicUsize,
4918        deny_verb: Option<&'static str>,
4919    }
4920
4921    impl Gate for CountingGate {
4922        fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
4923            self.calls.fetch_add(1, Ordering::SeqCst);
4924            if Some(req.verb.as_str()) == self.deny_verb {
4925                Ok(GateDecision::deny(format!("test deny for {}", req.verb)))
4926            } else {
4927                Ok(GateDecision::allow())
4928            }
4929        }
4930    }
4931
4932    #[tokio::test]
4933    async fn dispatch_consults_the_gate() {
4934        let gate = Arc::new(CountingGate::default());
4935        let mut builder = VerbRegistryBuilder::new();
4936        builder.register(AlphaPack);
4937        builder.with_gate(gate.clone());
4938        let reg = builder.build().expect("registry builds");
4939
4940        reg.dispatch("list", Value::Null).await.unwrap();
4941        reg.dispatch("create", Value::Null).await.unwrap();
4942        assert_eq!(
4943            gate.calls.load(Ordering::SeqCst),
4944            2,
4945            "gate should be consulted once per dispatch"
4946        );
4947    }
4948
4949    #[tokio::test]
4950    async fn dispatch_returns_permission_denied_on_deny_v03() {
4951        let gate = Arc::new(CountingGate {
4952            calls: AtomicUsize::new(0),
4953            deny_verb: Some("create"),
4954        });
4955        let mut builder = VerbRegistryBuilder::new();
4956        builder.register(AlphaPack);
4957        builder.with_gate(gate.clone());
4958        let reg = builder.build().expect("registry builds");
4959
4960        // Gate denies — dispatch now returns PermissionDenied (hard enforcement).
4961        let err = reg.dispatch("create", Value::Null).await.unwrap_err();
4962        assert!(
4963            matches!(err, RuntimeError::PermissionDenied { ref verb, .. } if verb == "create"),
4964            "expected PermissionDenied, got {err:?}"
4965        );
4966        let msg = err.to_string();
4967        assert!(
4968            msg.contains("create"),
4969            "error message must name the verb: {msg}"
4970        );
4971        assert!(
4972            msg.contains("test deny for create"),
4973            "error message must carry the deny reason: {msg}"
4974        );
4975        assert_eq!(gate.calls.load(Ordering::SeqCst), 1);
4976    }
4977
4978    #[tokio::test]
4979    async fn dispatch_allow_verb_succeeds_even_with_deny_gate_for_other_verb() {
4980        // Deny only "create" — "list" must still work.
4981        let gate = Arc::new(CountingGate {
4982            calls: AtomicUsize::new(0),
4983            deny_verb: Some("create"),
4984        });
4985        let mut builder = VerbRegistryBuilder::new();
4986        builder.register(AlphaPack);
4987        builder.with_gate(gate.clone());
4988        let reg = builder.build().expect("registry builds");
4989
4990        let res = reg.dispatch("list", Value::Null).await.unwrap();
4991        assert_eq!(res["pack"], "alpha");
4992    }
4993
4994    #[tokio::test]
4995    async fn dispatch_uses_allow_all_gate_by_default() {
4996        // No `with_gate` call — builder should use `AllowAllGate` so dispatch works.
4997        let reg = build_registry();
4998        let res = reg.dispatch("list", Value::Null).await.unwrap();
4999        assert_eq!(res["pack"], "alpha");
5000    }
5001
5002    // Captures the namespace each call sees so we can assert what the gate
5003    // actually receives, rather than assuming a hard-wired `default_ns()`.
5004    #[derive(Default, Debug)]
5005    struct NamespaceCapturingGate {
5006        seen: std::sync::Mutex<Vec<String>>,
5007    }
5008
5009    impl Gate for NamespaceCapturingGate {
5010        fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
5011            self.seen
5012                .lock()
5013                .unwrap()
5014                .push(req.namespace.as_str().to_string());
5015            Ok(GateDecision::allow())
5016        }
5017    }
5018
5019    #[tokio::test]
5020    async fn dispatch_propagates_params_namespace_to_gate() {
5021        let gate = Arc::new(NamespaceCapturingGate::default());
5022        let mut builder = VerbRegistryBuilder::new();
5023        builder.register(AlphaPack);
5024        builder.with_gate(gate.clone());
5025        builder.with_default_namespace("tenant-x");
5026        let reg = builder.build().expect("registry builds");
5027
5028        // Explicit namespace in params wins.
5029        reg.dispatch("list", serde_json::json!({"namespace": "tenant-y"}))
5030            .await
5031            .unwrap();
5032        // Missing namespace → registry default.
5033        reg.dispatch("list", Value::Null).await.unwrap();
5034        // Empty string is rejected: Namespace::parse("") fails → InvalidInput error.
5035        let err = reg
5036            .dispatch("list", serde_json::json!({"namespace": ""}))
5037            .await
5038            .unwrap_err();
5039        assert!(
5040            matches!(err, RuntimeError::InvalidInput(_)),
5041            "empty namespace must return InvalidInput, got {err:?}"
5042        );
5043
5044        let seen = gate.seen.lock().unwrap().clone();
5045        assert_eq!(seen, vec!["tenant-y", "tenant-x"]);
5046    }
5047
5048    #[tokio::test]
5049    async fn dispatch_falls_back_to_local_when_no_default_set() {
5050        // Builder default mirrors `Namespace::default_ns()`.
5051        let gate = Arc::new(NamespaceCapturingGate::default());
5052        let mut builder = VerbRegistryBuilder::new();
5053        builder.register(AlphaPack);
5054        builder.with_gate(gate.clone());
5055        let reg = builder.build().expect("registry builds");
5056
5057        reg.dispatch("list", Value::Null).await.unwrap();
5058        let seen = gate.seen.lock().unwrap().clone();
5059        assert_eq!(seen, vec!["local"]);
5060    }
5061
5062    /// A present-but-malformed `namespace` value must never reach the gate as
5063    /// the default namespace. Table-driven over every
5064    /// non-string JSON type; the gate-spy proves no call is ever recorded (the
5065    /// dispatch must short-circuit with `InvalidInput` before `GateRequest` is
5066    /// built), so the default namespace can never appear as a coerced stand-in.
5067    #[tokio::test]
5068    async fn namespace_null_rejected_not_coerced() {
5069        let cases: Vec<(&str, Value)> = vec![
5070            ("null", Value::Null),
5071            ("number", serde_json::json!(42)),
5072            ("boolean", serde_json::json!(true)),
5073            ("array", serde_json::json!(["local"])),
5074            ("object", serde_json::json!({"ns": "local"})),
5075        ];
5076
5077        for (label, ns_value) in cases {
5078            let gate = Arc::new(NamespaceCapturingGate::default());
5079            let mut builder = VerbRegistryBuilder::new();
5080            builder.register(AlphaPack);
5081            builder.with_gate(gate.clone());
5082            builder.with_default_namespace("tenant-x");
5083            let reg = builder.build().expect("registry builds");
5084
5085            let err = reg
5086                .dispatch("list", serde_json::json!({"namespace": ns_value}))
5087                .await
5088                .unwrap_err();
5089            assert!(
5090                matches!(err, RuntimeError::InvalidInput(_)),
5091                "case {label}: expected InvalidInput, got {err:?}"
5092            );
5093
5094            // The gate must never have been consulted for this malformed input —
5095            // proves no Allow decision (and therefore no default-namespace write)
5096            // can ever be reached for it.
5097            let seen = gate.seen.lock().unwrap().clone();
5098            assert!(
5099                seen.is_empty(),
5100                "case {label}: gate must not be consulted for malformed namespace, saw {seen:?}"
5101            );
5102        }
5103    }
5104
5105    // ---- Audit event emission ----
5106
5107    use khive_gate::{AuditDecision, AuditEvent, Obligation};
5108
5109    /// A gate that records every audit event emitted via from_check.
5110    #[derive(Default, Debug)]
5111    struct AuditCapturingGate {
5112        events: std::sync::Mutex<Vec<AuditEvent>>,
5113        deny_verb: Option<&'static str>,
5114    }
5115
5116    impl Gate for AuditCapturingGate {
5117        fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
5118            let decision = if Some(req.verb.as_str()) == self.deny_verb {
5119                GateDecision::deny("test deny")
5120            } else {
5121                GateDecision::allow_with(vec![Obligation::Audit {
5122                    tag: format!("{}.check", req.verb),
5123                }])
5124            };
5125            // Capture what dispatch will also emit.
5126            let ev = AuditEvent::from_check(req, &decision, self.impl_name());
5127            self.events.lock().unwrap().push(ev);
5128            Ok(decision)
5129        }
5130
5131        fn impl_name(&self) -> &'static str {
5132            "AuditCapturingGate"
5133        }
5134    }
5135
5136    #[tokio::test]
5137    async fn dispatch_emits_one_audit_event_per_call() {
5138        let gate = Arc::new(AuditCapturingGate::default());
5139        let mut builder = VerbRegistryBuilder::new();
5140        builder.register(AlphaPack);
5141        builder.with_gate(gate.clone());
5142        let reg = builder.build().expect("registry builds");
5143
5144        reg.dispatch("list", Value::Null).await.unwrap();
5145        reg.dispatch("create", Value::Null).await.unwrap();
5146
5147        let evs = gate.events.lock().unwrap();
5148        assert_eq!(evs.len(), 2, "exactly one audit event per dispatch call");
5149    }
5150
5151    #[tokio::test]
5152    async fn dispatch_audit_event_allow_carries_obligations() {
5153        let gate = Arc::new(AuditCapturingGate::default());
5154        let mut builder = VerbRegistryBuilder::new();
5155        builder.register(AlphaPack);
5156        builder.with_gate(gate.clone());
5157        let reg = builder.build().expect("registry builds");
5158
5159        reg.dispatch("list", Value::Null).await.unwrap();
5160
5161        let evs = gate.events.lock().unwrap();
5162        let ev = &evs[0];
5163        assert_eq!(ev.verb, "list");
5164        assert_eq!(ev.decision, AuditDecision::Allow);
5165        assert!(ev.deny_reason.is_none());
5166        assert_eq!(ev.obligations.len(), 1);
5167        assert_eq!(ev.gate_impl, "AuditCapturingGate");
5168    }
5169
5170    #[tokio::test]
5171    async fn dispatch_audit_event_deny_carries_reason() {
5172        let gate = Arc::new(AuditCapturingGate {
5173            events: Default::default(),
5174            deny_verb: Some("create"),
5175        });
5176        let mut builder = VerbRegistryBuilder::new();
5177        builder.register(AlphaPack);
5178        builder.with_gate(gate.clone());
5179        let reg = builder.build().expect("registry builds");
5180
5181        // Gate denies — dispatch returns PermissionDenied (hard enforcement).
5182        // The audit event is still recorded (captured inside the gate impl).
5183        let err = reg.dispatch("create", Value::Null).await.unwrap_err();
5184        assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
5185
5186        let evs = gate.events.lock().unwrap();
5187        let ev = &evs[0];
5188        assert_eq!(ev.verb, "create");
5189        assert_eq!(ev.decision, AuditDecision::Deny);
5190        assert_eq!(ev.deny_reason.as_deref(), Some("test deny"));
5191        assert!(ev.obligations.is_empty());
5192    }
5193
5194    #[tokio::test]
5195    async fn dispatch_audit_event_fields_match_gate_request() {
5196        let gate = Arc::new(AuditCapturingGate::default());
5197        let mut builder = VerbRegistryBuilder::new();
5198        builder.register(AlphaPack);
5199        builder.with_gate(gate.clone());
5200        builder.with_default_namespace("tenant-z");
5201        let reg = builder.build().expect("registry builds");
5202
5203        reg.dispatch("list", serde_json::json!({"namespace": "tenant-q"}))
5204            .await
5205            .unwrap();
5206
5207        let evs = gate.events.lock().unwrap();
5208        let ev = &evs[0];
5209        // Namespace from params wins.
5210        assert_eq!(ev.namespace, "tenant-q");
5211        assert_eq!(ev.verb, "list");
5212        assert_eq!(ev.actor.kind, "anonymous");
5213    }
5214
5215    // ---- Actor attribution threading into gate request (ADR-057) ----
5216
5217    /// A gate spy that captures the raw `GateRequest` it receives.
5218    #[derive(Default, Debug)]
5219    struct ActorCapturingGate {
5220        requests: std::sync::Mutex<Vec<GateRequest>>,
5221    }
5222
5223    impl Gate for ActorCapturingGate {
5224        fn check(&self, req: &GateRequest) -> Result<GateDecision, GateError> {
5225            self.requests.lock().unwrap().push(req.clone());
5226            Ok(GateDecision::allow())
5227        }
5228    }
5229
5230    /// When `actor_id` is configured, the gate request carries that actor, not
5231    /// anonymous. This exercises the ADR-057 attribution fix: the gate can
5232    /// distinguish an agent caller from an unauthenticated caller.
5233    #[tokio::test]
5234    async fn gate_request_carries_configured_actor_when_actor_id_is_set() {
5235        let gate = Arc::new(ActorCapturingGate::default());
5236        let mut builder = VerbRegistryBuilder::new();
5237        builder.register(AlphaPack);
5238        builder.with_gate(gate.clone());
5239        builder.with_actor_id(Some("team-abc:implementer".to_string()));
5240        let reg = builder.build().expect("registry builds");
5241
5242        reg.dispatch("list", Value::Null).await.unwrap();
5243
5244        let reqs = gate.requests.lock().unwrap();
5245        assert_eq!(reqs.len(), 1);
5246        let req = &reqs[0];
5247        assert_eq!(
5248            req.actor.kind, "actor",
5249            "gate request must carry kind='actor' when actor_id is configured"
5250        );
5251        assert_eq!(
5252            req.actor.id, "team-abc:implementer",
5253            "gate request must carry the configured actor id"
5254        );
5255    }
5256
5257    /// When no `actor_id` is configured, the gate request still receives the
5258    /// anonymous actor (no regression to the party-line default).
5259    #[tokio::test]
5260    async fn gate_request_carries_anonymous_when_no_actor_id_configured() {
5261        let gate = Arc::new(ActorCapturingGate::default());
5262        let mut builder = VerbRegistryBuilder::new();
5263        builder.register(AlphaPack);
5264        builder.with_gate(gate.clone());
5265        // actor_id left at default (None).
5266        let reg = builder.build().expect("registry builds");
5267
5268        reg.dispatch("list", Value::Null).await.unwrap();
5269
5270        let reqs = gate.requests.lock().unwrap();
5271        assert_eq!(reqs.len(), 1);
5272        let req = &reqs[0];
5273        assert_eq!(
5274            req.actor.kind, "anonymous",
5275            "gate request must carry anonymous actor when no actor_id is configured"
5276        );
5277        assert_eq!(req.actor.id, "local");
5278    }
5279
5280    /// A pack that records the `ActorRef` carried by the `NamespaceToken` it
5281    /// is dispatched with, so tests can compare it against the gate's actor.
5282    struct TokenCapturingPack {
5283        actors: Arc<std::sync::Mutex<Vec<khive_gate::ActorRef>>>,
5284    }
5285
5286    impl Pack for TokenCapturingPack {
5287        const NAME: &'static str = "alpha";
5288        const NOTE_KINDS: &'static [&'static str] = &[];
5289        const ENTITY_KINDS: &'static [&'static str] = &[];
5290        const HANDLERS: &'static [HandlerDef] = AlphaPack::HANDLERS;
5291    }
5292
5293    #[async_trait]
5294    impl PackRuntime for TokenCapturingPack {
5295        fn name(&self) -> &str {
5296            Self::NAME
5297        }
5298        fn note_kinds(&self) -> &'static [&'static str] {
5299            Self::NOTE_KINDS
5300        }
5301        fn entity_kinds(&self) -> &'static [&'static str] {
5302            Self::ENTITY_KINDS
5303        }
5304        fn handlers(&self) -> &'static [HandlerDef] {
5305            Self::HANDLERS
5306        }
5307        async fn dispatch(
5308            &self,
5309            verb: &str,
5310            _params: Value,
5311            _registry: &VerbRegistry,
5312            token: &NamespaceToken,
5313        ) -> Result<Value, RuntimeError> {
5314            self.actors.lock().unwrap().push(token.actor().clone());
5315            Ok(serde_json::json!({ "pack": "alpha", "verb": verb }))
5316        }
5317    }
5318
5319    /// The gate's actor and the storage token's actor must be the exact same
5320    /// resolved value: both come from one `resolve_actor` call
5321    /// (`resolved_actor`) instead of two independently hand-synchronized
5322    /// `match` expressions, so a future edit to one copy but not the other
5323    /// cannot silently desynchronize "who the gate thinks the caller is" from
5324    /// "who the storage layer thinks the caller is". Reintroducing a second
5325    /// independent actor-resolution copy for the token would regress this and
5326    /// this test would catch it.
5327    #[tokio::test]
5328    async fn gate_actor_and_token_actor_are_identical_when_actor_id_is_set() {
5329        let gate = Arc::new(ActorCapturingGate::default());
5330        let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
5331        let pack = TokenCapturingPack {
5332            actors: actors.clone(),
5333        };
5334        let mut builder = VerbRegistryBuilder::new();
5335        builder.register(pack);
5336        builder.with_gate(gate.clone());
5337        builder.with_actor_id(Some("actor-alpha".to_string()));
5338        let reg = builder.build().expect("registry builds");
5339
5340        reg.dispatch("list", Value::Null).await.unwrap();
5341
5342        let reqs = gate.requests.lock().unwrap();
5343        let gate_actor = reqs[0].actor.clone();
5344        drop(reqs);
5345
5346        let captured = actors.lock().unwrap();
5347        let token_actor = captured[0].clone();
5348
5349        assert_eq!(
5350            gate_actor.kind, token_actor.kind,
5351            "gate request actor and storage token actor must carry the same kind"
5352        );
5353        assert_eq!(
5354            gate_actor.id, token_actor.id,
5355            "gate request actor and storage token actor must carry the same id"
5356        );
5357        assert_eq!(gate_actor.id, "actor-alpha");
5358    }
5359
5360    /// Same identity check with no configured `actor_id`: both the gate and
5361    /// the storage token must independently land on `ActorRef::anonymous()`.
5362    #[tokio::test]
5363    async fn gate_actor_and_token_actor_are_identical_when_anonymous() {
5364        let gate = Arc::new(ActorCapturingGate::default());
5365        let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
5366        let pack = TokenCapturingPack {
5367            actors: actors.clone(),
5368        };
5369        let mut builder = VerbRegistryBuilder::new();
5370        builder.register(pack);
5371        builder.with_gate(gate.clone());
5372        let reg = builder.build().expect("registry builds");
5373
5374        reg.dispatch("list", Value::Null).await.unwrap();
5375
5376        let reqs = gate.requests.lock().unwrap();
5377        let gate_actor = reqs[0].actor.clone();
5378        drop(reqs);
5379
5380        let captured = actors.lock().unwrap();
5381        let token_actor = captured[0].clone();
5382
5383        assert_eq!(gate_actor.kind, token_actor.kind);
5384        assert_eq!(gate_actor.id, token_actor.id);
5385        assert_eq!(gate_actor.id, "local");
5386    }
5387
5388    // ---- dispatch_as: verified-actor dispatch for embedding hosts ----
5389
5390    /// `dispatch_as` must thread the caller-supplied verified actor through
5391    /// to the pack handler's `NamespaceToken`, exactly as `dispatch_with_identity`
5392    /// does with a `RequestIdentity.actor_id` — this is the observable
5393    /// contract embedding hosts rely on.
5394    #[tokio::test]
5395    async fn dispatch_as_threads_verified_actor_into_token() {
5396        let gate = Arc::new(ActorCapturingGate::default());
5397        let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
5398        let pack = TokenCapturingPack {
5399            actors: actors.clone(),
5400        };
5401        let mut builder = VerbRegistryBuilder::new();
5402        builder.register(pack);
5403        builder.with_gate(gate.clone());
5404        let reg = builder.build().expect("registry builds");
5405
5406        reg.dispatch_as(
5407            "list",
5408            Value::Null,
5409            VerifiedActor::new("gateway:principal-42").unwrap(),
5410        )
5411        .await
5412        .unwrap();
5413
5414        let reqs = gate.requests.lock().unwrap();
5415        assert_eq!(reqs[0].actor.kind, "actor");
5416        assert_eq!(reqs[0].actor.id, "gateway:principal-42");
5417        drop(reqs);
5418
5419        let captured = actors.lock().unwrap();
5420        assert_eq!(captured[0].kind, "actor");
5421        assert_eq!(
5422            captured[0].id, "gateway:principal-42",
5423            "the storage token actor must be the verified_actor supplied to dispatch_as, \
5424             matching exactly what pack handlers read as the acting principal"
5425        );
5426    }
5427
5428    /// `dispatch_as` is purely additive: a registry with a baked `actor_id`
5429    /// must still serve plain `dispatch()` calls under its own baked actor,
5430    /// unaffected by any `dispatch_as` call made on the same (cheaply
5431    /// cloneable) registry. No shared mutable state links the two calls.
5432    #[tokio::test]
5433    async fn dispatch_as_does_not_change_plain_dispatch_behavior() {
5434        let gate = Arc::new(ActorCapturingGate::default());
5435        let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
5436        let pack = TokenCapturingPack {
5437            actors: actors.clone(),
5438        };
5439        let mut builder = VerbRegistryBuilder::new();
5440        builder.register(pack);
5441        builder.with_gate(gate.clone());
5442        builder.with_actor_id(Some("baked-actor".to_string()));
5443        let reg = builder.build().expect("registry builds");
5444
5445        reg.dispatch_as(
5446            "list",
5447            Value::Null,
5448            VerifiedActor::new("verified-actor").unwrap(),
5449        )
5450        .await
5451        .unwrap();
5452        reg.dispatch("list", Value::Null).await.unwrap();
5453
5454        let captured = actors.lock().unwrap();
5455        assert_eq!(captured.len(), 2);
5456        assert_eq!(captured[0].id, "verified-actor", "dispatch_as call");
5457        assert_eq!(
5458            captured[1].id, "baked-actor",
5459            "a later plain dispatch() call must still use the registry's baked \
5460             actor_id, unaffected by the prior dispatch_as call"
5461        );
5462    }
5463
5464    /// A request `params` payload cannot inject or override the actor:
5465    /// `dispatch_as` resolves the acting principal solely from its Rust-side
5466    /// `verified_actor` argument, never from `params`. An `actor` key placed
5467    /// in `params` passes through untouched to the pack handler like any
5468    /// other unrecognized field — the dispatch boundary itself never reads
5469    /// `params["actor"]`.
5470    #[tokio::test]
5471    async fn dispatch_as_ignores_actor_key_in_params() {
5472        let gate = Arc::new(ActorCapturingGate::default());
5473        let actors = Arc::new(std::sync::Mutex::new(Vec::new()));
5474        let pack = TokenCapturingPack {
5475            actors: actors.clone(),
5476        };
5477        let mut builder = VerbRegistryBuilder::new();
5478        builder.register(pack);
5479        builder.with_gate(gate.clone());
5480        let reg = builder.build().expect("registry builds");
5481
5482        reg.dispatch_as(
5483            "list",
5484            serde_json::json!({"actor": "spoofed-actor"}),
5485            VerifiedActor::new("verified-actor").unwrap(),
5486        )
5487        .await
5488        .unwrap();
5489
5490        let captured = actors.lock().unwrap();
5491        assert_eq!(
5492            captured[0].id, "verified-actor",
5493            "an 'actor' key inside params must never override the verified_actor \
5494             argument threaded through dispatch_as"
5495        );
5496    }
5497
5498    /// `VerifiedActor::new` must reject an empty identifier rather than
5499    /// letting it reach dispatch and silently resolve to the anonymous actor.
5500    #[test]
5501    fn verified_actor_rejects_empty_identifier() {
5502        let err = VerifiedActor::new("").unwrap_err();
5503        assert!(
5504            matches!(err, RuntimeError::InvalidInput(_)),
5505            "expected InvalidInput, got {err:?}"
5506        );
5507    }
5508
5509    /// `VerifiedActor::new` must reject a whitespace-only identifier for the
5510    /// same reason: it must never launder into `ActorRef::anonymous()`.
5511    #[test]
5512    fn verified_actor_rejects_whitespace_only_identifier() {
5513        let err = VerifiedActor::new("   ").unwrap_err();
5514        assert!(
5515            matches!(err, RuntimeError::InvalidInput(_)),
5516            "expected InvalidInput, got {err:?}"
5517        );
5518    }
5519
5520    // ---- Rego gate: fail-closed end-to-end ----
5521
5522    /// A `RegoGate` whose policy lacks the named entrypoint rule must cause
5523    /// `VerbRegistry::dispatch` to return `RuntimeError::PermissionDenied` —
5524    /// never to proceed to the pack handler.
5525    ///
5526    /// This is the runtime-level assertion that a gate evaluation failure
5527    /// fails closed rather than opening a security hole. `RegoGate::check`
5528    /// converts all evaluation failures (missing rule, undefined result,
5529    /// serialization error, poisoned engine) to `Ok(GateDecision::Deny)` with
5530    /// a static classified reason, so dispatch is blocked as a policy
5531    /// refusal. Infrastructure faults from other `Gate` implementations
5532    /// remain distinguishable as `RuntimeError::GateUnavailable`.
5533    #[tokio::test]
5534    async fn rego_gate_missing_entrypoint_returns_permission_denied() {
5535        use khive_gate_rego::RegoGate;
5536
5537        // Policy defines `verdict` but NOT `data.khive.gate.decision` (the
5538        // default entrypoint).  Construction succeeds — from_policy_str does
5539        // not validate the default entrypoint.  check() must convert the
5540        // missing-rule evaluation error to Ok(Deny) with a static classified
5541        // reason so the runtime reports a policy refusal rather than a gate
5542        // infrastructure outage.
5543        let policy = r#"
5544            package khive.gate
5545            import rego.v1
5546            verdict := "allow"
5547        "#;
5548        let gate = Arc::new(RegoGate::from_policy_str(policy).expect("policy compiles"));
5549
5550        let mut builder = VerbRegistryBuilder::new();
5551        builder.register(AlphaPack);
5552        builder.with_gate(gate);
5553        let reg = builder.build().expect("registry builds");
5554
5555        let err = reg.dispatch("create", Value::Null).await.unwrap_err();
5556        assert!(
5557            matches!(err, RuntimeError::PermissionDenied { ref verb, ref reason }
5558                if verb == "create" && reason == "policy evaluation failed"),
5559            "expected PermissionDenied with the static classified reason for a missing rego entrypoint, got {err:?}"
5560        );
5561    }
5562
5563    // ---- Audit tracing emission ----
5564    //
5565    // The AuditCapturingGate tests above prove that AuditEvent::from_check is
5566    // called with the right inputs, but they observe the event *inside* the
5567    // gate impl — they would still pass if dispatch's
5568    // `tracing::info!(audit_event = ..., "gate.check")` were deleted or
5569    // renamed. The tests below install a capture Layer and assert on the
5570    // actual tracing event surfaced from dispatch. This locks the public
5571    // observability contract: one `gate.check` info event per dispatch,
5572    // carrying an `audit_event` field that round-trips back to an `AuditEvent`.
5573
5574    use std::sync::{Mutex as StdMutex, Once, OnceLock};
5575
5576    use serial_test::serial;
5577    use tracing::field::{Field, Visit};
5578
5579    #[derive(Clone, Debug, Default)]
5580    struct CapturedEvent {
5581        message: Option<String>,
5582        audit_event: Option<String>,
5583        into_id: Option<String>,
5584        budget_rows: Option<u64>,
5585    }
5586
5587    #[derive(Default)]
5588    struct CapturedEventVisitor(CapturedEvent);
5589
5590    impl Visit for CapturedEventVisitor {
5591        fn record_str(&mut self, field: &Field, value: &str) {
5592            match field.name() {
5593                "message" => self.0.message = Some(value.to_string()),
5594                "audit_event" => self.0.audit_event = Some(value.to_string()),
5595                _ => {}
5596            }
5597        }
5598
5599        fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
5600            // `tracing::info!(audit_event = %expr, "msg")` records via the
5601            // Display-wrapped Debug path, so we receive the JSON string here.
5602            // `"msg"` literal records as a `message` field via `record_debug`
5603            // with a quoted Debug representation; strip the surrounding quotes
5604            // so the captured message matches the source.
5605            let formatted = format!("{value:?}");
5606            let cleaned = formatted
5607                .trim_start_matches('"')
5608                .trim_end_matches('"')
5609                .to_string();
5610            match field.name() {
5611                "message" => self.0.message = Some(cleaned),
5612                "audit_event" => self.0.audit_event = Some(cleaned),
5613                "into_id" => self.0.into_id = Some(cleaned),
5614                _ => {}
5615            }
5616        }
5617
5618        fn record_u64(&mut self, field: &Field, value: u64) {
5619            if field.name() == "budget_rows" {
5620                self.0.budget_rows = Some(value);
5621            }
5622        }
5623    }
5624
5625    /// Minimal `tracing::Subscriber` that captures events into a shared vec.
5626    ///
5627    /// Implemented directly (without `tracing_subscriber::registry()` layering)
5628    /// to avoid the layer machinery that can cause thread-local dispatch to be
5629    /// bypassed when the registry's internal global state is initialised by
5630    /// another subscriber in the same test binary.
5631    ///
5632    /// Isolation across concurrent tests is handled at the dispatcher level by
5633    /// `tracing::dispatcher::with_default`, which installs this subscriber
5634    /// as the thread-local default for the duration of the test closure.
5635    /// Other threads (e.g. `#[tokio::test]` pool workers) emit through their
5636    /// own (typically NoSubscriber) dispatchers and never reach this instance.
5637    struct CaptureSubscriber {
5638        events: Arc<StdMutex<Vec<CapturedEvent>>>,
5639    }
5640
5641    impl CaptureSubscriber {
5642        fn new(events: Arc<StdMutex<Vec<CapturedEvent>>>) -> Self {
5643            Self { events }
5644        }
5645    }
5646
5647    impl tracing::Subscriber for CaptureSubscriber {
5648        fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
5649            true
5650        }
5651        fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
5652            tracing::span::Id::from_u64(1)
5653        }
5654        fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
5655        fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
5656        fn event(&self, event: &tracing::Event<'_>) {
5657            let mut visitor = CapturedEventVisitor::default();
5658            event.record(&mut visitor);
5659            let captured = visitor.0;
5660            // Tee the post-commit budget logs into their own append-only sink:
5661            // `capture_dispatch_events` clears the main buffer, so a reader of
5662            // budget events sharing that buffer would race the clear.
5663            if let (Some(message), Some(into_id)) = (&captured.message, &captured.into_id) {
5664                if message.ends_with("transaction materialization budget") {
5665                    budget_events_sink()
5666                        .lock()
5667                        .unwrap()
5668                        .push(CapturedBudgetLog {
5669                            message: message.clone(),
5670                            into_id: into_id.clone(),
5671                            budget_rows: captured.budget_rows.unwrap_or(0),
5672                        });
5673                }
5674            }
5675            self.events.lock().unwrap().push(captured);
5676        }
5677        fn enter(&self, _: &tracing::span::Id) {}
5678        fn exit(&self, _: &tracing::span::Id) {}
5679    }
5680
5681    /// Global capture buffer for the tracing tests.
5682    ///
5683    /// The subscriber is installed exactly once via `set_global_default`
5684    /// (thread-local dispatchers via `with_default` proved unreliable when
5685    /// other tests in the binary configure their own dispatchers in parallel —
5686    /// the global state interacted unpredictably and events were lost).
5687    ///
5688    /// Each test that uses this buffer is `#[serial]`, so only one
5689    /// runs at a time. The buffer is cleared at the start of each capture call.
5690    static GLOBAL_CAPTURE: OnceLock<Arc<StdMutex<Vec<CapturedEvent>>>> = OnceLock::new();
5691    static GLOBAL_INIT: Once = Once::new();
5692
5693    /// One captured post-commit budget log (curation merge tests).
5694    #[derive(Clone)]
5695    pub(crate) struct CapturedBudgetLog {
5696        pub(crate) message: String,
5697        pub(crate) into_id: String,
5698        pub(crate) budget_rows: u64,
5699    }
5700
5701    /// Append-only sink the subscriber tees budget logs into. Never cleared:
5702    /// curation tests select their own rows by `into_id`, so stale rows from
5703    /// other tests are inert rather than a pollution hazard.
5704    static BUDGET_EVENTS: OnceLock<Arc<StdMutex<Vec<CapturedBudgetLog>>>> = OnceLock::new();
5705
5706    fn budget_events_sink() -> Arc<StdMutex<Vec<CapturedBudgetLog>>> {
5707        Arc::clone(BUDGET_EVENTS.get_or_init(|| Arc::new(StdMutex::new(Vec::new()))))
5708    }
5709
5710    /// Entry point for the curation merge tests: installs the process-global
5711    /// capture subscriber (once for the whole test binary — a second
5712    /// `set_global_default` elsewhere would starve one of the captures) and
5713    /// returns the budget-log sink it tees into.
5714    pub(crate) fn budget_log_events() -> Arc<StdMutex<Vec<CapturedBudgetLog>>> {
5715        let _ = global_capture();
5716        budget_events_sink()
5717    }
5718
5719    fn global_capture() -> Arc<StdMutex<Vec<CapturedEvent>>> {
5720        GLOBAL_INIT.call_once(|| {
5721            let buffer = Arc::new(StdMutex::new(Vec::new()));
5722            let subscriber = CaptureSubscriber::new(Arc::clone(&buffer));
5723            // Ignore error: if another subscriber is already set globally, our
5724            // subscriber installation fails, but the buffer will simply stay
5725            // empty and tests will fail with a clear "got 0 events" message
5726            // rather than a silent corruption.
5727            let _ = tracing::subscriber::set_global_default(subscriber);
5728            let _ = GLOBAL_CAPTURE.set(buffer);
5729        });
5730        Arc::clone(GLOBAL_CAPTURE.get().expect("global capture initialized"))
5731    }
5732
5733    /// Run an async block under the global capture subscriber and return
5734    /// the events emitted during the run. Clears the buffer at the start.
5735    ///
5736    /// Callers MUST be `#[serial]` to prevent concurrent buffer pollution.
5737    fn capture_dispatch_events<Fut>(future: Fut) -> Vec<CapturedEvent>
5738    where
5739        Fut: std::future::Future<Output = ()>,
5740    {
5741        let buffer = global_capture();
5742        buffer.lock().unwrap().clear();
5743
5744        let rt = tokio::runtime::Builder::new_current_thread()
5745            .enable_all()
5746            .build()
5747            .expect("build current-thread tokio runtime");
5748        rt.block_on(future);
5749
5750        let result = buffer.lock().unwrap().clone();
5751        result
5752    }
5753
5754    /// Pull every captured event whose `message` matches `"gate.check"` AND
5755    /// whose audit_event JSON declares the expected `gate_impl` name.
5756    ///
5757    /// Filtering by `gate_impl` lets concurrent tests in the same binary
5758    /// emit their own gate.check events into the global capture buffer
5759    /// without polluting each others' counts.
5760    fn gate_check_events_for(events: &[CapturedEvent], gate_impl: &str) -> Vec<CapturedEvent> {
5761        events
5762            .iter()
5763            .filter(|e| e.message.as_deref() == Some("gate.check"))
5764            .filter(|e| {
5765                e.audit_event
5766                    .as_deref()
5767                    .and_then(|s| serde_json::from_str::<serde_json::Value>(s).ok())
5768                    .and_then(|v| {
5769                        v.get("gate_impl")
5770                            .and_then(|g| g.as_str().map(|s| s.to_string()))
5771                    })
5772                    .as_deref()
5773                    == Some(gate_impl)
5774            })
5775            .cloned()
5776            .collect()
5777    }
5778
5779    #[test]
5780    #[serial]
5781    fn dispatch_tracing_emits_one_gate_check_event_on_allow() {
5782        #[derive(Debug)]
5783        struct TracingAllowGate;
5784        impl Gate for TracingAllowGate {
5785            fn check(&self, _: &GateRequest) -> Result<GateDecision, GateError> {
5786                Ok(GateDecision::allow())
5787            }
5788            fn impl_name(&self) -> &'static str {
5789                "TracingAllowGate"
5790            }
5791        }
5792
5793        let events = capture_dispatch_events(async {
5794            let mut builder = VerbRegistryBuilder::new();
5795            builder.register(AlphaPack);
5796            builder.with_gate(Arc::new(TracingAllowGate));
5797            builder.with_default_namespace("tenant-default");
5798            let reg = builder.build().expect("registry builds");
5799            reg.dispatch("list", serde_json::json!({"namespace": "tenant-q"}))
5800                .await
5801                .unwrap();
5802        });
5803
5804        let gate_events = gate_check_events_for(&events, "TracingAllowGate");
5805        assert_eq!(
5806            gate_events.len(),
5807            1,
5808            "exactly one gate.check tracing event per dispatch (allow); got {gate_events:?}"
5809        );
5810        let payload = gate_events[0]
5811            .audit_event
5812            .as_ref()
5813            .expect("gate.check event must carry an audit_event field");
5814        let audit: khive_gate::AuditEvent =
5815            serde_json::from_str(payload).expect("audit_event payload must decode to AuditEvent");
5816        assert_eq!(audit.decision, AuditDecision::Allow);
5817        assert_eq!(audit.verb, "list");
5818        assert_eq!(audit.namespace, "tenant-q");
5819        assert_eq!(audit.gate_impl, "TracingAllowGate");
5820        assert!(
5821            audit.deny_reason.is_none(),
5822            "deny_reason must be None on Allow"
5823        );
5824    }
5825
5826    #[test]
5827    #[serial]
5828    fn dispatch_tracing_emits_one_gate_check_event_when_gate_is_unavailable() {
5829        #[derive(Debug)]
5830        struct TracingUnavailableGate;
5831        impl Gate for TracingUnavailableGate {
5832            fn check(&self, _: &GateRequest) -> Result<GateDecision, GateError> {
5833                Err(GateError::Internal("tracing gate broken".into()))
5834            }
5835
5836            fn impl_name(&self) -> &'static str {
5837                "TracingUnavailableGate"
5838            }
5839        }
5840
5841        let events = capture_dispatch_events(async {
5842            let mut builder = VerbRegistryBuilder::new();
5843            builder.register(AlphaPack);
5844            builder.with_gate(Arc::new(TracingUnavailableGate));
5845            let reg = builder.build().expect("registry builds");
5846            let error = reg
5847                .dispatch("list", Value::Null)
5848                .await
5849                .expect_err("gate outage must refuse dispatch");
5850            assert!(matches!(error, RuntimeError::GateUnavailable { .. }));
5851        });
5852
5853        let gate_events = gate_check_events_for(&events, "TracingUnavailableGate");
5854        assert_eq!(
5855            gate_events.len(),
5856            1,
5857            "exactly one gate.check tracing event per gate outage; got {gate_events:?}"
5858        );
5859        let payload = gate_events[0]
5860            .audit_event
5861            .as_ref()
5862            .expect("gate outage trace must carry an audit_event field");
5863        let audit: AuditEvent =
5864            serde_json::from_str(payload).expect("audit_event payload must decode");
5865        assert_eq!(audit.decision, AuditDecision::GateUnavailable);
5866        assert!(audit.deny_reason.is_none());
5867        assert!(audit.obligations.is_empty());
5868        assert_eq!(audit.gate_impl, "TracingUnavailableGate");
5869    }
5870
5871    // ---- Hard enforcement + EventStore persistence ----
5872
5873    use crate::runtime::NamespaceToken;
5874    use async_trait::async_trait;
5875    use khive_storage::{
5876        BatchWriteSummary, Event, EventFilter, EventStore, Page, PageRequest, SubstrateKind,
5877    };
5878    use khive_types::EventOutcome;
5879
5880    /// Minimal stand-in for the Git pack: the receipt contract belongs to the
5881    /// runtime dispatch seam, so these tests do not need a git repository or
5882    /// any Git-pack dependency.
5883    struct GitDigestResultPack {
5884        project_id: uuid::Uuid,
5885    }
5886
5887    impl Pack for GitDigestResultPack {
5888        const NAME: &'static str = "git";
5889        const NOTE_KINDS: &'static [&'static str] = &[];
5890        const ENTITY_KINDS: &'static [&'static str] = &[];
5891        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
5892            name: "git.digest",
5893            description: "return a deterministic digest report",
5894            visibility: Visibility::Verb,
5895            category: VerbCategory::Assertive,
5896            params: &[],
5897        }];
5898    }
5899
5900    #[async_trait]
5901    impl PackRuntime for GitDigestResultPack {
5902        fn name(&self) -> &str {
5903            Self::NAME
5904        }
5905        fn note_kinds(&self) -> &'static [&'static str] {
5906            Self::NOTE_KINDS
5907        }
5908        fn entity_kinds(&self) -> &'static [&'static str] {
5909            Self::ENTITY_KINDS
5910        }
5911        fn handlers(&self) -> &'static [HandlerDef] {
5912            Self::HANDLERS
5913        }
5914        async fn dispatch(
5915            &self,
5916            _verb: &str,
5917            _params: Value,
5918            _registry: &VerbRegistry,
5919            _token: &NamespaceToken,
5920        ) -> Result<Value, RuntimeError> {
5921            Ok(serde_json::json!({
5922                "project_id": self.project_id,
5923                "project_created": false,
5924                "commits_ingested": 2,
5925                "commits_skipped_existing": 1,
5926                "issues_ingested": 3,
5927                "issues_skipped_existing": 4,
5928                "prs_ingested": 5,
5929                "prs_skipped_existing": 6,
5930                "done": true,
5931                "history_exhausted": true,
5932                "sources": {
5933                    "commits": {"state": "completed"},
5934                    "issues": {"state": "completed"},
5935                    "pull_requests": {"state": "completed"}
5936                },
5937                "warnings": []
5938            }))
5939        }
5940    }
5941
5942    /// A nominally successful handler with an invalid receipt identity. The
5943    /// runtime must turn this into an error without consuming its generic
5944    /// audit fallback.
5945    struct MalformedGitDigestResultPack;
5946
5947    impl Pack for MalformedGitDigestResultPack {
5948        const NAME: &'static str = "malformed-git";
5949        const NOTE_KINDS: &'static [&'static str] = &[];
5950        const ENTITY_KINDS: &'static [&'static str] = &[];
5951        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
5952            name: "git.digest",
5953            description: "return a malformed digest report",
5954            visibility: Visibility::Verb,
5955            category: VerbCategory::Assertive,
5956            params: &[],
5957        }];
5958    }
5959
5960    #[async_trait]
5961    impl PackRuntime for MalformedGitDigestResultPack {
5962        fn name(&self) -> &str {
5963            Self::NAME
5964        }
5965        fn note_kinds(&self) -> &'static [&'static str] {
5966            Self::NOTE_KINDS
5967        }
5968        fn entity_kinds(&self) -> &'static [&'static str] {
5969            Self::ENTITY_KINDS
5970        }
5971        fn handlers(&self) -> &'static [HandlerDef] {
5972            Self::HANDLERS
5973        }
5974        async fn dispatch(
5975            &self,
5976            _verb: &str,
5977            _params: Value,
5978            _registry: &VerbRegistry,
5979            _token: &NamespaceToken,
5980        ) -> Result<Value, RuntimeError> {
5981            Ok(serde_json::json!({
5982                "project_id": "not-a-uuid",
5983                "done": true,
5984            }))
5985        }
5986    }
5987
5988    /// One entry in the interleaved submission trace. Typed so assertions
5989    /// match on fields instead of parsing a formatted string; both sides of
5990    /// the ordering land on ONE vector so their relative order is observable
5991    /// rather than assumed.
5992    #[derive(Debug, Clone, PartialEq)]
5993    enum TraceEntry {
5994        /// A handler effect that has committed (nothing downstream undoes it).
5995        Effect { name: String },
5996        /// An audit row submitted to the event store, carrying exactly the
5997        /// fields the obligation test discriminates on.
5998        Audit {
5999            kind: EventKind,
6000            outcome: EventOutcome,
6001            verb: String,
6002            /// The row's `resource.cost_unit`, `None` when the payload omits
6003            /// it (the error path's `base_resource_payload` does).
6004            cost_unit: Option<Value>,
6005        },
6006    }
6007
6008    /// In-memory EventStore for unit tests — avoids file-backed SQLite.
6009    #[derive(Default, Debug)]
6010    struct MemoryEventStore {
6011        events: std::sync::Mutex<Vec<Event>>,
6012        fail_appends: bool,
6013        /// Fail only a generation whose batch contains an event of this
6014        /// kind, leaving every other generation (e.g. the deferred
6015        /// obligation row committed after dispatch resolves) to commit
6016        /// normally. Lets a test fail a pure-observability row without
6017        /// also failing the obligation row that shares the same store.
6018        fail_kind: Option<EventKind>,
6019        /// Append-ordered record of what was SUBMITTED to this store,
6020        /// written before the injected-failure check so a submission this
6021        /// store then rejects is still visible.
6022        ///
6023        /// `events` alone cannot show that: a rejected append returns before
6024        /// the store records anything, so a test reading `events` cannot
6025        /// tell a row that failed to commit from a row that was never built.
6026        /// Those are different production behaviours and only one of them is
6027        /// the audit contract. A test that hands the same vector to its
6028        /// handler also gets the ordering between the handler's effect and
6029        /// the audit submission, which is the only way to observe that the
6030        /// audit row is written after the handler rather than before it.
6031        trace: Option<Arc<std::sync::Mutex<Vec<TraceEntry>>>>,
6032    }
6033
6034    impl MemoryEventStore {
6035        /// Record a submission attempt. Call before any failure check.
6036        ///
6037        /// The projection carries the verb and the row's `resource.cost_unit`
6038        /// value, not just kind and outcome, and not merely whether the key is
6039        /// present.
6040        ///
6041        /// Presence alone is too weak to pin what it looks like it pins.
6042        /// `cost_unit::resource_payload` inserts the key unconditionally, and
6043        /// for most verbs `item_count` returns a constant `1` regardless of the
6044        /// handler's return value, so a submission built from a static or null
6045        /// `ok_val` still carries the key. Presence separates `resource_payload`
6046        /// from the error path's `base_resource_payload`, which is a real
6047        /// property but a different one.
6048        ///
6049        /// The value is what sources the return value, and only for a verb whose
6050        /// `item_count` reads it. `knowledge.index` is that verb: `item_count`
6051        /// takes `result["total"]`, so `cost_unit` is `total + 1` and moves with
6052        /// what the handler returned. The fixture below uses that verb for
6053        /// exactly this reason.
6054        fn trace_submission(&self, events: &[Event]) {
6055            if let Some(trace) = &self.trace {
6056                let mut trace = trace.lock().expect("trace lock");
6057                for event in events {
6058                    let cost_unit = event
6059                        .payload
6060                        .get("resource")
6061                        .and_then(|resource| resource.get("cost_unit"))
6062                        .cloned();
6063                    trace.push(TraceEntry::Audit {
6064                        kind: event.kind,
6065                        outcome: event.outcome,
6066                        verb: event.verb.clone(),
6067                        cost_unit,
6068                    });
6069                }
6070            }
6071        }
6072    }
6073
6074    #[async_trait]
6075    impl EventStore for MemoryEventStore {
6076        async fn append_event(&self, event: Event) -> khive_storage::StorageResult<()> {
6077            self.trace_submission(std::slice::from_ref(&event));
6078            if self.fail_appends || self.fail_kind == Some(event.kind) {
6079                return Err(khive_storage::StorageError::Internal(
6080                    "injected audit append failure".to_string(),
6081                ));
6082            }
6083            self.events.lock().unwrap().push(event);
6084            Ok(())
6085        }
6086        async fn append_events(
6087            &self,
6088            events: Vec<Event>,
6089        ) -> khive_storage::StorageResult<BatchWriteSummary> {
6090            self.trace_submission(&events);
6091            let attempted = events.len() as u64;
6092            let affected = attempted;
6093            self.events.lock().unwrap().extend(events);
6094            Ok(BatchWriteSummary {
6095                attempted,
6096                affected,
6097                failed: 0,
6098                first_error: String::new(),
6099            })
6100        }
6101        async fn get_event(&self, id: uuid::Uuid) -> khive_storage::StorageResult<Option<Event>> {
6102            Ok(self
6103                .events
6104                .lock()
6105                .unwrap()
6106                .iter()
6107                .find(|e| e.id == id)
6108                .cloned())
6109        }
6110        async fn query_events(
6111            &self,
6112            _filter: EventFilter,
6113            _page: PageRequest,
6114        ) -> khive_storage::StorageResult<Page<Event>> {
6115            let items = self.events.lock().unwrap().clone();
6116            let total = items.len() as u64;
6117            Ok(Page {
6118                items,
6119                total: Some(total),
6120            })
6121        }
6122        async fn count_events(&self, _filter: EventFilter) -> khive_storage::StorageResult<u64> {
6123            Ok(self.events.lock().unwrap().len() as u64)
6124        }
6125
6126        fn preflight_event(&self, _event: &Event) -> khive_storage::StorageResult<()> {
6127            Ok(())
6128        }
6129
6130        async fn append_events_idempotent(
6131            &self,
6132            events: Vec<Event>,
6133        ) -> khive_storage::StorageResult<khive_storage::event::IdempotentEventBatchResult>
6134        {
6135            self.trace_submission(&events);
6136            if self.fail_appends
6137                || self
6138                    .fail_kind
6139                    .is_some_and(|kind| events.iter().any(|e| e.kind == kind))
6140            {
6141                return Err(khive_storage::StorageError::Internal(
6142                    "injected audit append failure".to_string(),
6143                ));
6144            }
6145            let mut store = self.events.lock().unwrap();
6146            let mut rows = Vec::with_capacity(events.len());
6147            for event in events {
6148                if let Some(existing) = store.iter().find(|e| e.id == event.id) {
6149                    if *existing == event {
6150                        rows.push(
6151                            khive_storage::event::EventAppendDisposition::AlreadyPresentIdentical,
6152                        );
6153                    } else {
6154                        rows.push(khive_storage::event::EventAppendDisposition::IdentityConflict);
6155                    }
6156                } else {
6157                    store.push(event);
6158                    rows.push(khive_storage::event::EventAppendDisposition::Inserted);
6159                }
6160            }
6161            Ok(khive_storage::event::IdempotentEventBatchResult { rows })
6162        }
6163
6164        fn supports_idempotent_audit_batch(&self) -> bool {
6165            true
6166        }
6167    }
6168
6169    fn only_git_digest_event(store: &MemoryEventStore) -> Event {
6170        let events: Vec<Event> = store
6171            .events
6172            .lock()
6173            .unwrap()
6174            .iter()
6175            .filter(|event| event.verb == "git.digest")
6176            .cloned()
6177            .collect();
6178        assert_eq!(
6179            events.len(),
6180            1,
6181            "expected exactly one git.digest receipt event"
6182        );
6183        events[0].clone()
6184    }
6185
6186    #[tokio::test]
6187    async fn git_digest_success_returns_complete_durable_receipt() {
6188        let project_id = uuid::Uuid::new_v4();
6189        let store = Arc::new(MemoryEventStore::default());
6190        let mut builder = VerbRegistryBuilder::new();
6191        builder.register(GitDigestResultPack { project_id });
6192        builder.with_event_store(store.clone());
6193        let registry = builder.build().expect("registry builds");
6194
6195        let result = registry
6196            .dispatch_with_identity(
6197                "git.digest",
6198                serde_json::json!({
6199                    "source": "https://user:SECRET@example.invalid/org/repo",
6200                }),
6201                Some(RequestIdentity {
6202                    namespace: Namespace::local().as_str().to_string(),
6203                    request_id: Some(1_510),
6204                    ..Default::default()
6205                }),
6206            )
6207            .await
6208            .expect("durably receipted digest succeeds");
6209        let receipt_id = result["receipt_id"]
6210            .as_str()
6211            .and_then(|raw| raw.parse::<uuid::Uuid>().ok())
6212            .expect("response has UUID receipt_id");
6213
6214        let event = only_git_digest_event(&store);
6215        assert_eq!(event.id, receipt_id);
6216        assert_eq!(event.target_id, Some(project_id));
6217        assert_eq!(event.verb, "git.digest");
6218        assert_eq!(event.outcome, EventOutcome::Success);
6219        assert_eq!(event.payload_schema_version, 2);
6220        assert_eq!(event.payload["result"], result);
6221        assert_eq!(event.payload["resource"]["request_id"], 1_510);
6222        assert_eq!(event.payload["result"]["commits_ingested"], 2);
6223        assert_eq!(event.payload["result"]["issues_ingested"], 3);
6224        assert_eq!(event.payload["result"]["prs_ingested"], 5);
6225        assert!(
6226            !event.payload.to_string().contains("SECRET"),
6227            "receipt must not persist the caller's source URL or credentials"
6228        );
6229    }
6230
6231    #[tokio::test]
6232    async fn malformed_git_digest_report_appends_one_generic_error_audit() {
6233        let store = Arc::new(MemoryEventStore::default());
6234        let mut builder = VerbRegistryBuilder::new();
6235        builder.register(MalformedGitDigestResultPack);
6236        builder.with_event_store(store.clone());
6237        let registry = builder.build().expect("registry builds");
6238
6239        let err = registry
6240            .dispatch("git.digest", serde_json::json!({}))
6241            .await
6242            .expect_err("malformed receipt identity must fail the response");
6243        assert!(matches!(
6244            err,
6245            RuntimeError::Internal(ref message)
6246                if message.starts_with("git_digest_receipt_persist_failed:")
6247        ));
6248
6249        let event = only_git_digest_event(&store);
6250        assert_eq!(event.outcome, EventOutcome::Error);
6251        assert_eq!(event.payload_schema_version, 1);
6252        assert!(
6253            event.payload.get("result").is_none(),
6254            "a generic Error audit must not masquerade as a success receipt"
6255        );
6256        let audit: AuditEvent =
6257            serde_json::from_value(event.payload).expect("generic payload remains an AuditEvent");
6258        assert_eq!(audit.verb, "git.digest");
6259        assert_eq!(audit.decision, AuditDecision::Allow);
6260    }
6261
6262    #[tokio::test]
6263    #[serial(audit_append_failures)]
6264    #[serial(audit_obligation_append_failures)]
6265    async fn git_digest_receipt_append_failure_never_returns_unqualified_success() {
6266        let before = audit_append_failure_count();
6267        let before_obligation = audit_obligation_append_failure_count();
6268        let store = Arc::new(MemoryEventStore {
6269            fail_appends: true,
6270            ..MemoryEventStore::default()
6271        });
6272        let mut builder = VerbRegistryBuilder::new();
6273        builder.register(GitDigestResultPack {
6274            project_id: uuid::Uuid::new_v4(),
6275        });
6276        builder.with_event_store(store);
6277        let registry = builder.build().expect("registry builds");
6278
6279        let err = registry
6280            .dispatch("git.digest", serde_json::json!({}))
6281            .await
6282            .expect_err("receipt persistence failure must fail the response");
6283        assert!(
6284            matches!(&err, RuntimeError::Internal(message)
6285                if message.starts_with("git_digest_receipt_persist_failed:")
6286                    && message.contains("writes may have committed")),
6287            "error is stable, safe, and retry-aware: {err}"
6288        );
6289        // The git.digest receipt is obligation-bearing (`GitDigestReceipt`
6290        // classifies as `DispatchObligation`) and this failure propagated
6291        // into the dispatch's own error above, so it counts on the
6292        // obligation counter, not the swallowed-failures one.
6293        assert_eq!(audit_append_failure_count(), before);
6294        assert_eq!(
6295            audit_obligation_append_failure_count(),
6296            before_obligation + 1
6297        );
6298    }
6299
6300    #[tokio::test]
6301    async fn git_digest_without_event_store_fails_safe_after_handler_success() {
6302        let mut builder = VerbRegistryBuilder::new();
6303        builder.register(GitDigestResultPack {
6304            project_id: uuid::Uuid::new_v4(),
6305        });
6306        let registry = builder.build().expect("registry builds");
6307
6308        let err = registry
6309            .dispatch("git.digest", serde_json::json!({}))
6310            .await
6311            .expect_err("a successful digest needs a durable store");
6312        assert!(matches!(
6313            err,
6314            RuntimeError::Internal(ref message)
6315                if message.starts_with("git_digest_receipt_persist_failed:")
6316        ));
6317    }
6318
6319    #[tokio::test]
6320    async fn git_digest_gate_unavailable_precedes_the_receipt_contract() {
6321        #[derive(Debug)]
6322        struct FailingGate;
6323        impl Gate for FailingGate {
6324            fn check(&self, _req: &GateRequest) -> Result<GateDecision, khive_gate::GateError> {
6325                Err(khive_gate::GateError::Internal(
6326                    "injected gate failure".into(),
6327                ))
6328            }
6329        }
6330
6331        let store = Arc::new(MemoryEventStore::default());
6332        let mut builder = VerbRegistryBuilder::new();
6333        builder.register(GitDigestResultPack {
6334            project_id: uuid::Uuid::new_v4(),
6335        });
6336        builder.with_gate(Arc::new(FailingGate));
6337        builder.with_event_store(store.clone());
6338        let registry = builder.build().expect("registry builds");
6339
6340        let err = registry
6341            .dispatch("git.digest", serde_json::json!({}))
6342            .await
6343            .expect_err("gate unavailability must refuse before the handler or receipt path");
6344        assert!(matches!(
6345            err,
6346            RuntimeError::GateUnavailable { ref verb, ref reason }
6347                if verb == "git.digest"
6348                    && reason == "gate backend unavailable"
6349                    && !reason.contains("injected gate failure")
6350        ));
6351        let event = only_git_digest_event(&store);
6352        assert_eq!(event.outcome, EventOutcome::Error);
6353        assert_eq!(event.payload["decision"], "gate_unavailable");
6354        assert!(event.payload.get("result").is_none());
6355    }
6356
6357    #[tokio::test]
6358    async fn intercepted_gate_error_returns_typed_refusal_without_invoking_operation() {
6359        #[derive(Debug)]
6360        struct FailingGate;
6361        impl Gate for FailingGate {
6362            fn check(&self, _req: &GateRequest) -> Result<GateDecision, khive_gate::GateError> {
6363                Err(khive_gate::GateError::Internal(
6364                    "intercepted gate broken".into(),
6365                ))
6366            }
6367        }
6368
6369        let invoked = Arc::new(AtomicUsize::new(0));
6370        let invoked_by_operation = Arc::clone(&invoked);
6371        let store = Arc::new(MemoryEventStore::default());
6372        let mut builder = VerbRegistryBuilder::new();
6373        builder.with_gate(Arc::new(FailingGate));
6374        builder.with_event_store(store.clone());
6375        let registry = builder.build().expect("registry builds");
6376        let identity = RequestIdentity {
6377            namespace: "identity-default".to_string(),
6378            request_id: Some(1_600),
6379            ..Default::default()
6380        };
6381
6382        let err = registry
6383            .dispatch_intercepted_with_identity(
6384                "list",
6385                &serde_json::json!({"namespace": "test-ns"}),
6386                Some(&identity),
6387                move |_namespace| {
6388                    invoked_by_operation.fetch_add(1, Ordering::SeqCst);
6389                    async move { Ok(serde_json::json!({"invoked": true})) }
6390                },
6391            )
6392            .await
6393            .expect_err("gate unavailability must refuse intercepted dispatch");
6394
6395        assert!(matches!(
6396            err,
6397            RuntimeError::GateUnavailable { ref verb, ref reason }
6398                if verb == "list"
6399                    && reason == "gate backend unavailable"
6400                    && !reason.contains("intercepted gate broken")
6401        ));
6402        assert_eq!(
6403            invoked.load(Ordering::SeqCst),
6404            0,
6405            "intercepted operation must not run after a gate infrastructure error"
6406        );
6407
6408        let events = store.events.lock().unwrap();
6409        assert_eq!(events.len(), 1);
6410        assert_eq!(events[0].verb, "list");
6411        assert_eq!(events[0].namespace, "test-ns");
6412        assert_eq!(events[0].outcome, EventOutcome::Error);
6413        assert_eq!(events[0].payload["decision"], "gate_unavailable");
6414        assert!(events[0].payload.get("deny_reason").is_none());
6415        assert_eq!(events[0].payload["resource"]["work_class"], "interactive");
6416        assert_eq!(events[0].payload["resource"]["request_id"], 1_600);
6417        assert!(events[0].payload["resource"].get("cost_unit").is_none());
6418    }
6419
6420    #[tokio::test]
6421    async fn intercepted_deny_remains_distinct_and_does_not_invoke_operation() {
6422        #[derive(Debug)]
6423        struct DenyingGate;
6424        impl Gate for DenyingGate {
6425            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
6426                Ok(GateDecision::deny("intercepted policy denied"))
6427            }
6428        }
6429
6430        let invoked = Arc::new(AtomicUsize::new(0));
6431        let invoked_by_operation = Arc::clone(&invoked);
6432        let store = Arc::new(MemoryEventStore::default());
6433        let mut builder = VerbRegistryBuilder::new();
6434        builder.with_gate(Arc::new(DenyingGate));
6435        builder.with_event_store(store.clone());
6436        let registry = builder.build().expect("registry builds");
6437
6438        let err = registry
6439            .dispatch_intercepted_with_identity("list", &Value::Null, None, move |_namespace| {
6440                invoked_by_operation.fetch_add(1, Ordering::SeqCst);
6441                async move { Ok(serde_json::json!({"invoked": true})) }
6442            })
6443            .await
6444            .expect_err("explicit gate denial must refuse intercepted dispatch");
6445
6446        assert!(matches!(
6447            err,
6448            RuntimeError::PermissionDenied { ref verb, ref reason }
6449                if verb == "list" && reason == "intercepted policy denied"
6450        ));
6451        assert_eq!(invoked.load(Ordering::SeqCst), 0);
6452
6453        let events = store.events.lock().unwrap();
6454        assert_eq!(events.len(), 1);
6455        assert_eq!(events[0].outcome, EventOutcome::Denied);
6456        assert_eq!(events[0].payload["decision"], "deny");
6457        assert_eq!(
6458            events[0].payload["deny_reason"],
6459            "intercepted policy denied"
6460        );
6461    }
6462
6463    #[tokio::test]
6464    async fn intercepted_git_digest_uses_the_same_receipt_contract() {
6465        let project_id = uuid::Uuid::new_v4();
6466        let store = Arc::new(MemoryEventStore::default());
6467        let mut builder = VerbRegistryBuilder::new();
6468        builder.with_event_store(store.clone());
6469        let registry = builder.build().expect("registry builds");
6470
6471        let result = registry
6472            .dispatch_intercepted_with_identity(
6473                "git.digest",
6474                &serde_json::json!({}),
6475                Some(&RequestIdentity {
6476                    namespace: Namespace::local().as_str().to_string(),
6477                    request_id: Some(1_647),
6478                    ..Default::default()
6479                }),
6480                |_namespace| async move {
6481                    Ok(serde_json::json!({
6482                        "project_id": project_id,
6483                        "commits_ingested": 7,
6484                        "done": true,
6485                    }))
6486                },
6487            )
6488            .await
6489            .expect("intercepted digest is durably receipted");
6490
6491        let event = only_git_digest_event(&store);
6492        assert_eq!(result["receipt_id"], serde_json::json!(event.id));
6493        assert_eq!(event.payload["result"], result);
6494        assert_eq!(event.payload["resource"]["request_id"], 1_647);
6495    }
6496
6497    #[tokio::test]
6498    async fn intercepted_git_digest_receipt_preserves_typed_metadata() {
6499        let project_id = uuid::Uuid::new_v4();
6500        let store = Arc::new(MemoryEventStore::default());
6501        let mut builder = VerbRegistryBuilder::new();
6502        builder.with_event_store(store.clone());
6503        let registry = builder.build().expect("registry builds");
6504
6505        let outcome = registry
6506            .dispatch_intercepted_with_metadata_with_identity(
6507                "git.digest",
6508                &serde_json::json!({}),
6509                None,
6510                |_namespace| async move {
6511                    Ok(InterceptedDispatchResult::new(
6512                        serde_json::json!({
6513                            "project_id": project_id,
6514                            "commits_ingested": 3,
6515                            "done": true,
6516                        }),
6517                        vec!["backend-a".to_string(), "backend-b".to_string()],
6518                    ))
6519                },
6520            )
6521            .await
6522            .expect("metadata-bearing digest is durably receipted");
6523
6524        let event = only_git_digest_event(&store);
6525        assert_eq!(outcome.result["receipt_id"], serde_json::json!(event.id));
6526        assert_eq!(event.payload["result"], outcome.result);
6527        assert_eq!(outcome.metadata, ["backend-a", "backend-b"]);
6528    }
6529
6530    #[tokio::test]
6531    async fn intercepted_malformed_git_digest_appends_one_generic_error_audit() {
6532        let store = Arc::new(MemoryEventStore::default());
6533        let mut builder = VerbRegistryBuilder::new();
6534        builder.with_event_store(store.clone());
6535        let registry = builder.build().expect("registry builds");
6536
6537        let err = registry
6538            .dispatch_intercepted_with_identity(
6539                "git.digest",
6540                &serde_json::json!({}),
6541                None,
6542                |_namespace| async {
6543                    Ok(serde_json::json!({
6544                        "project_id": "not-a-uuid",
6545                        "done": true,
6546                    }))
6547                },
6548            )
6549            .await
6550            .expect_err("malformed intercepted receipt must fail the response");
6551        assert!(matches!(
6552            err,
6553            RuntimeError::Internal(ref message)
6554                if message.starts_with("git_digest_receipt_persist_failed:")
6555        ));
6556
6557        let event = only_git_digest_event(&store);
6558        assert_eq!(event.outcome, EventOutcome::Error);
6559        assert_eq!(event.payload_schema_version, 1);
6560        assert!(event.payload.get("result").is_none());
6561        let audit: AuditEvent =
6562            serde_json::from_value(event.payload).expect("generic payload remains an AuditEvent");
6563        assert_eq!(audit.verb, "git.digest");
6564        assert_eq!(audit.decision, AuditDecision::Allow);
6565    }
6566
6567    #[tokio::test]
6568    async fn allow_all_gate_default_remains_backward_compatible() {
6569        // No gate set — AllowAllGate is the default. Dispatch must succeed.
6570        let mut builder = VerbRegistryBuilder::new();
6571        builder.register(AlphaPack);
6572        let reg = builder.build().expect("registry builds");
6573
6574        let res = reg.dispatch("list", Value::Null).await.unwrap();
6575        assert_eq!(
6576            res["pack"], "alpha",
6577            "AllowAllGate must allow every verb — backward compat guarantee"
6578        );
6579        let res = reg.dispatch("create", Value::Null).await.unwrap();
6580        assert_eq!(res["pack"], "alpha");
6581    }
6582
6583    #[tokio::test]
6584    async fn deny_gate_returns_permission_denied_pack_never_invoked() {
6585        #[derive(Debug)]
6586        struct AlwaysDenyGate;
6587        impl Gate for AlwaysDenyGate {
6588            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
6589                Ok(GateDecision::deny("test: always deny"))
6590            }
6591        }
6592
6593        // Track whether dispatch was ever invoked on the pack.
6594        #[derive(Debug)]
6595        struct TrackedPack {
6596            invoked: Arc<AtomicUsize>,
6597        }
6598
6599        impl khive_types::Pack for TrackedPack {
6600            const NAME: &'static str = "tracked";
6601            const NOTE_KINDS: &'static [&'static str] = &[];
6602            const ENTITY_KINDS: &'static [&'static str] = &[];
6603            const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
6604                name: "guarded",
6605                description: "a guarded verb",
6606                visibility: Visibility::Verb,
6607                category: VerbCategory::Assertive,
6608                params: &[],
6609            }];
6610        }
6611
6612        #[async_trait]
6613        impl PackRuntime for TrackedPack {
6614            fn name(&self) -> &str {
6615                Self::NAME
6616            }
6617            fn note_kinds(&self) -> &'static [&'static str] {
6618                Self::NOTE_KINDS
6619            }
6620            fn entity_kinds(&self) -> &'static [&'static str] {
6621                Self::ENTITY_KINDS
6622            }
6623            fn handlers(&self) -> &'static [HandlerDef] {
6624                Self::HANDLERS
6625            }
6626            async fn dispatch(
6627                &self,
6628                _verb: &str,
6629                _params: Value,
6630                _registry: &VerbRegistry,
6631                _token: &NamespaceToken,
6632            ) -> Result<Value, RuntimeError> {
6633                self.invoked.fetch_add(1, Ordering::SeqCst);
6634                Ok(serde_json::json!({"invoked": true}))
6635            }
6636        }
6637
6638        let invoked = Arc::new(AtomicUsize::new(0));
6639        let mut builder = VerbRegistryBuilder::new();
6640        builder.register(TrackedPack {
6641            invoked: invoked.clone(),
6642        });
6643        builder.with_gate(Arc::new(AlwaysDenyGate));
6644        let reg = builder.build().expect("registry builds");
6645
6646        let err = reg.dispatch("guarded", Value::Null).await.unwrap_err();
6647        assert!(
6648            matches!(err, RuntimeError::PermissionDenied { ref verb, ref reason } if verb == "guarded" && reason.contains("always deny")),
6649            "expected PermissionDenied with verb=guarded and reason, got: {err:?}"
6650        );
6651        assert_eq!(
6652            invoked.load(Ordering::SeqCst),
6653            0,
6654            "pack dispatch MUST NOT be invoked when gate denies"
6655        );
6656    }
6657
6658    #[tokio::test]
6659    async fn update_denial_precedes_id_existence_resolution() {
6660        #[derive(Debug)]
6661        struct AlwaysDenyUpdateGate {
6662            checked: Arc<AtomicUsize>,
6663        }
6664        impl Gate for AlwaysDenyUpdateGate {
6665            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
6666                self.checked.fetch_add(1, Ordering::SeqCst);
6667                Ok(GateDecision::deny("caller has no update capability"))
6668            }
6669        }
6670
6671        #[derive(Debug)]
6672        struct ExistenceOracleUpdatePack {
6673            existing_id: String,
6674            invoked: Arc<AtomicUsize>,
6675        }
6676
6677        impl khive_types::Pack for ExistenceOracleUpdatePack {
6678            const NAME: &'static str = "existence_oracle";
6679            const NOTE_KINDS: &'static [&'static str] = &[];
6680            const ENTITY_KINDS: &'static [&'static str] = &[];
6681            const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
6682                name: "update",
6683                description: "distinguish a present id from an absent id",
6684                visibility: Visibility::Verb,
6685                category: VerbCategory::Declaration,
6686                params: &[],
6687            }];
6688        }
6689
6690        #[async_trait]
6691        impl PackRuntime for ExistenceOracleUpdatePack {
6692            fn name(&self) -> &str {
6693                Self::NAME
6694            }
6695            fn note_kinds(&self) -> &'static [&'static str] {
6696                Self::NOTE_KINDS
6697            }
6698            fn entity_kinds(&self) -> &'static [&'static str] {
6699                Self::ENTITY_KINDS
6700            }
6701            fn handlers(&self) -> &'static [HandlerDef] {
6702                Self::HANDLERS
6703            }
6704            async fn dispatch(
6705                &self,
6706                _verb: &str,
6707                params: Value,
6708                _registry: &VerbRegistry,
6709                _token: &NamespaceToken,
6710            ) -> Result<Value, RuntimeError> {
6711                self.invoked.fetch_add(1, Ordering::SeqCst);
6712                match params.get("id").and_then(Value::as_str) {
6713                    Some(id) if id == self.existing_id => Ok(serde_json::json!({"updated": id})),
6714                    _ => Err(RuntimeError::NotFound("record".to_string())),
6715                }
6716            }
6717        }
6718
6719        let existing_id = uuid::Uuid::new_v4().to_string();
6720        let absent_id = uuid::Uuid::new_v4().to_string();
6721        let invoked = Arc::new(AtomicUsize::new(0));
6722        let checked = Arc::new(AtomicUsize::new(0));
6723
6724        let pack = || ExistenceOracleUpdatePack {
6725            existing_id: existing_id.clone(),
6726            invoked: Arc::clone(&invoked),
6727        };
6728
6729        let mut control_builder = VerbRegistryBuilder::new();
6730        control_builder.register(pack());
6731        let control = control_builder.build().expect("control registry builds");
6732        control
6733            .dispatch("update", serde_json::json!({"id": existing_id.clone()}))
6734            .await
6735            .expect("positive control resolves the present id");
6736        assert!(matches!(
6737            control
6738                .dispatch("update", serde_json::json!({"id": absent_id.clone()}))
6739                .await,
6740            Err(RuntimeError::NotFound(_))
6741        ));
6742        assert_eq!(invoked.load(Ordering::SeqCst), 2);
6743
6744        let mut denied_builder = VerbRegistryBuilder::new();
6745        denied_builder.register(pack());
6746        denied_builder.with_gate(Arc::new(AlwaysDenyUpdateGate {
6747            checked: Arc::clone(&checked),
6748        }));
6749        let denied = denied_builder.build().expect("denied registry builds");
6750
6751        let present_error = denied
6752            .dispatch("update", serde_json::json!({"id": existing_id.clone()}))
6753            .await
6754            .expect_err("denied present-id update must not resolve the id");
6755        let absent_error = denied
6756            .dispatch("update", serde_json::json!({"id": absent_id.clone()}))
6757            .await
6758            .expect_err("denied absent-id update must not resolve the id");
6759
6760        let denial = |error: RuntimeError| match error {
6761            RuntimeError::PermissionDenied { verb, reason } => (verb, reason),
6762            other => panic!("expected gate refusal, got {other:?}"),
6763        };
6764        let present_denial = denial(present_error);
6765        let absent_denial = denial(absent_error);
6766        assert_eq!(present_denial.0, "update");
6767        assert_eq!(present_denial.1, "caller has no update capability");
6768        assert_eq!(present_denial, absent_denial);
6769        assert_eq!(
6770            checked.load(Ordering::SeqCst),
6771            2,
6772            "both denied requests must consult the configured gate"
6773        );
6774        assert_eq!(
6775            invoked.load(Ordering::SeqCst),
6776            2,
6777            "neither denied request may reach the existence oracle"
6778        );
6779    }
6780
6781    #[tokio::test]
6782    async fn audit_event_persists_to_event_store_on_allow() {
6783        let store = Arc::new(MemoryEventStore::default());
6784        let mut builder = VerbRegistryBuilder::new();
6785        builder.register(AlphaPack);
6786        builder.with_event_store(store.clone());
6787        let reg = builder.build().expect("registry builds");
6788
6789        reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
6790            .await
6791            .unwrap();
6792
6793        let count = store.count_events(EventFilter::default()).await.unwrap();
6794        assert_eq!(count, 1, "one audit event persisted to EventStore on allow");
6795
6796        let page = store
6797            .query_events(
6798                EventFilter::default(),
6799                PageRequest {
6800                    limit: 10,
6801                    offset: 0,
6802                },
6803            )
6804            .await
6805            .unwrap();
6806        let ev = &page.items[0];
6807        assert_eq!(ev.verb, "list");
6808        assert_eq!(ev.namespace, "test-ns");
6809        assert_eq!(ev.substrate, SubstrateKind::Event);
6810        assert_eq!(ev.outcome, EventOutcome::Success);
6811    }
6812
6813    #[tokio::test]
6814    #[serial(audit_append_failures)]
6815    #[serial(audit_obligation_append_failures)]
6816    async fn audit_append_failure_fails_an_obligation_bearing_dispatch() {
6817        let before = audit_append_failure_count();
6818        let before_obligation = audit_obligation_append_failure_count();
6819
6820        let successful_store = Arc::new(MemoryEventStore::default());
6821        let mut successful_builder = VerbRegistryBuilder::new();
6822        successful_builder.register(AlphaPack);
6823        successful_builder.with_event_store(successful_store);
6824        let successful_registry = successful_builder.build().expect("registry builds");
6825        successful_registry
6826            .dispatch("list", Value::Null)
6827            .await
6828            .expect("successful audit append must not affect dispatch");
6829        assert_eq!(
6830            audit_append_failure_count(),
6831            before,
6832            "successful audit appends must not increment the swallowed-failure counter"
6833        );
6834        assert_eq!(
6835            audit_obligation_append_failure_count(),
6836            before_obligation,
6837            "successful audit appends must not increment the obligation-failure counter"
6838        );
6839
6840        // ADR-133 D2/D3/D4: `list`'s deferred audit row is a
6841        // `DispatchSucceeded` obligation. A dispatch must not report success
6842        // when the row that accounts for it did not commit, so a persistent
6843        // commit failure here must fail the dispatch that would otherwise
6844        // have reported success.
6845        let failing_store = Arc::new(MemoryEventStore {
6846            fail_appends: true,
6847            ..MemoryEventStore::default()
6848        });
6849        let mut failing_builder = VerbRegistryBuilder::new();
6850        failing_builder.register(AlphaPack);
6851        failing_builder.with_event_store(failing_store);
6852        let failing_registry = failing_builder.build().expect("registry builds");
6853        let err = failing_registry
6854            .dispatch("list", Value::Null)
6855            .await
6856            .expect_err(
6857                "a persistent obligation-bearing audit commit failure must fail the dispatch",
6858            );
6859        assert!(
6860            matches!(&err, RuntimeError::Internal(message)
6861                if message.contains("audit obligation commit failed")),
6862            "error names the obligation failure so it is distinguishable from a handler error: {err}"
6863        );
6864
6865        // `list`'s deferred audit row is `DispatchSucceeded`, an obligation
6866        // producer, so this propagated failure belongs on the obligation
6867        // counter — the swallowed-failure counter must not move for it.
6868        assert_eq!(
6869            audit_append_failure_count(),
6870            before,
6871            "an obligation failure must never inflate the swallowed-failure counter"
6872        );
6873        assert_eq!(
6874            audit_obligation_append_failure_count(),
6875            before_obligation + 1,
6876            "the failed obligation append must remain visible to diagnostics"
6877        );
6878    }
6879
6880    /// An obligation-bearing audit row is written AFTER the handler returns and FROM the
6881    /// handler's own return value. So when that row fails to commit,
6882    /// `fold_audit_obligation` turns a would-be success into an error for a dispatch whose
6883    /// effect has ALREADY happened and cannot be rolled back by it.
6884    ///
6885    /// The existing obligation test above proves the flip using `list`, a read, where the
6886    /// distinction does not matter. This one pins the part that decides caller behaviour:
6887    /// the write landed, and the caller was told it failed. A caller that treats this error
6888    /// as "it did not run" and retries therefore applies the effect twice, which is what the
6889    /// last assertion covers.
6890    ///
6891    /// The handler and the event store share one trace vector, so the ordering claim is
6892    /// observed rather than assumed. That matters more than it looks: asserting only the
6893    /// caller-visible error and the handler's effect would leave this test green against an
6894    /// implementation that submits no audit row at all, or that submits one built from the
6895    /// error path — both of which contradict the contract while producing exactly the same
6896    /// error string.
6897    ///
6898    /// The outcome alone does not separate those. A row can carry `Success` and still have
6899    /// been built without the handler's return value, which is a third implementation and
6900    /// also wrong. So the trace records whether the row's resource carries `cost_unit`:
6901    /// `resource_payload` derives that key from `ok_val`, and `base_resource_payload`
6902    /// documents that it omits it. Asserting the key is what pins result-sourcing; the
6903    /// verb is asserted alongside it so a fabricated row for some other verb cannot satisfy
6904    /// the same check.
6905    ///
6906    /// Not pinned here: that the row commits on a SEPARATE writer acquisition from the
6907    /// handler's. The store double has no writer to observe, so that half of the mechanism
6908    /// needs a different fixture than this one.
6909    #[tokio::test]
6910    #[serial(audit_append_failures)]
6911    #[serial(audit_obligation_append_failures)]
6912    // The config ledger is process-global and an event-store dispatch drains its
6913    // queue before invoking the pack, so a concurrent config_ledger test can land
6914    // a submission ahead of this handler's effect and break the first-entry
6915    // assertion below. That group is held for the position assertion, not for the
6916    // audit counters the two groups above cover.
6917    #[serial(config_ledger)]
6918    async fn obligation_failure_reports_a_write_that_already_committed() {
6919        /// `total` is what `cost_unit` is computed from, so this number is the
6920        /// test's handle on whether the audit row was built from the return
6921        /// value. 41 is arbitrary but distinctive: it makes the expected
6922        /// `cost_unit` 42 (`base_weight` 1 + `item_count` 41 * `model_count`
6923        /// 1), a value no default path produces.
6924        const RETURNED_TOTAL: u64 = 41;
6925
6926        #[derive(Debug)]
6927        struct RecordingWritePack {
6928            committed: Arc<std::sync::Mutex<Vec<TraceEntry>>>,
6929        }
6930
6931        impl Pack for RecordingWritePack {
6932            const NAME: &'static str = "recording_write";
6933            const NOTE_KINDS: &'static [&'static str] = &[];
6934            const ENTITY_KINDS: &'static [&'static str] = &[];
6935            // `knowledge.index` rather than `create`, and the choice is
6936            // load-bearing rather than incidental: it is the one verb whose
6937            // `cost_unit` reads the handler's return value (`item_count` takes
6938            // `result["total"]`). Under any other verb `item_count` is the
6939            // constant `1`, so the recorded `cost_unit` would be the same
6940            // whether the row was built from the result or from a static value,
6941            // and the assertion below could not tell those apart.
6942            const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
6943                name: "knowledge.index",
6944                description: "record one committed write",
6945                visibility: Visibility::Verb,
6946                category: VerbCategory::Commissive,
6947                params: &[],
6948            }];
6949        }
6950
6951        #[async_trait]
6952        impl PackRuntime for RecordingWritePack {
6953            fn name(&self) -> &str {
6954                Self::NAME
6955            }
6956            fn note_kinds(&self) -> &'static [&'static str] {
6957                Self::NOTE_KINDS
6958            }
6959            fn entity_kinds(&self) -> &'static [&'static str] {
6960                Self::ENTITY_KINDS
6961            }
6962            fn handlers(&self) -> &'static [HandlerDef] {
6963                Self::HANDLERS
6964            }
6965            async fn dispatch(
6966                &self,
6967                _verb: &str,
6968                params: Value,
6969                _registry: &VerbRegistry,
6970                _token: &NamespaceToken,
6971            ) -> Result<Value, RuntimeError> {
6972                // Stands in for a committed effect: by the time this returns, the write
6973                // is done and nothing downstream can undo it. Pushed onto the SAME
6974                // vector the event store traces into, so the relative order of the
6975                // effect and the audit submission is observable rather than assumed.
6976                let name = params
6977                    .get("name")
6978                    .and_then(Value::as_str)
6979                    .unwrap_or("unnamed")
6980                    .to_string();
6981                self.committed
6982                    .lock()
6983                    .expect("committed lock")
6984                    .push(TraceEntry::Effect { name: name.clone() });
6985                Ok(serde_json::json!({ "created": name, "total": RETURNED_TOTAL }))
6986            }
6987        }
6988
6989        let committed = Arc::new(std::sync::Mutex::new(Vec::new()));
6990        let failing_store = Arc::new(MemoryEventStore {
6991            fail_appends: true,
6992            trace: Some(Arc::clone(&committed)),
6993            ..MemoryEventStore::default()
6994        });
6995        let mut builder = VerbRegistryBuilder::new();
6996        builder.register(RecordingWritePack {
6997            committed: Arc::clone(&committed),
6998        });
6999        builder.with_event_store(failing_store);
7000        let registry = builder.build().expect("registry builds");
7001
7002        let err = registry
7003            .dispatch("knowledge.index", serde_json::json!({"name": "first"}))
7004            .await
7005            .expect_err("an obligation commit failure must fail the dispatch");
7006        assert!(
7007            matches!(&err, RuntimeError::Internal(message)
7008                if message.contains("audit obligation commit failed")),
7009            "the error must name the obligation failure, since that string is what tells a \
7010             caller the effect landed: {err}"
7011        );
7012
7013        // The trace carries both sides, so each of the three claims above is an
7014        // assertion rather than a comment. Read as a sequence it says: the handler's
7015        // effect committed, and only THEN was an audit row submitted -- a row built
7016        // from the successful result, which is what makes it the obligation row and
7017        // not an error row.
7018        let first_pass = committed.lock().expect("committed lock").clone();
7019        let first_effect = TraceEntry::Effect {
7020            name: "first".to_string(),
7021        };
7022        assert_eq!(
7023            first_pass.first(),
7024            Some(&first_effect),
7025            "the handler's effect must land FIRST: an implementation that submitted the \
7026             audit row before dispatching would satisfy every other assertion here"
7027        );
7028        let audit_rows: Vec<&TraceEntry> = first_pass
7029            .iter()
7030            .filter(|entry| matches!(entry, TraceEntry::Audit { .. }))
7031            .collect();
7032        assert!(
7033            !audit_rows.is_empty(),
7034            "an audit row must actually be SUBMITTED; without this assertion the test \
7035             passes against an implementation that returns the same error and never \
7036             builds a row at all, which is a different defect wearing the same error \
7037             string. Trace was {first_pass:?}"
7038        );
7039        let expected_cost_unit = serde_json::json!(RETURNED_TOTAL + 1);
7040        assert!(
7041            audit_rows.iter().any(|entry| matches!(
7042                entry,
7043                TraceEntry::Audit {
7044                    outcome: EventOutcome::Success,
7045                    verb,
7046                    cost_unit: Some(cost_unit),
7047                    ..
7048                } if verb.as_str() == "knowledge.index" && *cost_unit == expected_cost_unit
7049            )),
7050            "the submitted row must be the SUCCESS row for THIS verb, carrying a resource \
7051             computed FROM the handler's return value. The outcome alone is not enough: an \
7052             implementation that stamps Success on a row built without `ok_val` would \
7053             satisfy an outcome-only assertion while breaking the contract this test \
7054             exists for. The exact value is the discriminator, not the key's presence: \
7055             `resource_payload` inserts `cost_unit` unconditionally, so presence survives a \
7056             static `ok_val`, while {expected_cost_unit} is reachable only from the \
7057             returned `total` of {RETURNED_TOTAL} (`base_weight` 1 + `item_count` \
7058             {RETURNED_TOTAL} * `model_count` 1). Substituting a null or static result \
7059             collapses it to 1, and the error path's `base_resource_payload` omits the key \
7060             entirely (`cost_unit: None` here), so all three implementations are \
7061             distinguishable. Trace was {first_pass:?}"
7062        );
7063        assert_eq!(
7064            first_pass
7065                .iter()
7066                .filter(|entry| **entry == first_effect)
7067                .count(),
7068            1,
7069            "exactly one effect on the first pass"
7070        );
7071
7072        // What a caller does on a failure it believes means "did not run".
7073        let _ = registry
7074            .dispatch("knowledge.index", serde_json::json!({"name": "first"}))
7075            .await
7076            .expect_err("the retry fails the same way");
7077        assert_eq!(
7078            committed
7079                .lock()
7080                .expect("committed lock")
7081                .iter()
7082                .filter(|entry| **entry == first_effect)
7083                .count(),
7084            2,
7085            "retrying this error double-writes; a caller must re-derive state instead of \
7086             resubmitting"
7087        );
7088    }
7089
7090    #[tokio::test]
7091    #[serial(config_ledger)]
7092    #[serial(audit_append_failures)]
7093    #[serial(audit_obligation_append_failures)]
7094    async fn config_locked_row_degrades_without_failing_the_dispatch_that_observed_it() {
7095        // Deny-gate a dispatch so the only append this call makes is the
7096        // immediate `ConfigLocked` drain in the gate-check block: the
7097        // `GateDenied` row and the eventual `PermissionDenied` return are
7098        // unaffected by the store either way (see the two `let _ =` sites
7099        // above), so any failure this test observes is isolated to the
7100        // pure-observability `ConfigLocked` row. The `fail_appends: true`
7101        // store also fails the fire-and-forget `GateDenied` append, which
7102        // now counts on the obligation counter (`#[serial(...)]` above
7103        // keeps that from racing this file's exact-delta assertions on it).
7104        #[derive(Debug)]
7105        struct DenyGate;
7106        impl Gate for DenyGate {
7107            fn check(&self, _req: &GateRequest) -> Result<GateDecision, khive_gate::GateError> {
7108                Ok(GateDecision::Deny {
7109                    reason: "denied for test".to_string(),
7110                })
7111            }
7112        }
7113
7114        crate::config_ledger::record_config_locked("adr133_test_key", "adr133_test_value");
7115
7116        let store = Arc::new(MemoryEventStore {
7117            fail_appends: true,
7118            ..MemoryEventStore::default()
7119        });
7120        let mut builder = VerbRegistryBuilder::new();
7121        builder.register(AlphaPack);
7122        builder.with_gate(Arc::new(DenyGate));
7123        builder.with_event_store(store);
7124        let registry = builder.build().expect("registry builds");
7125
7126        let err = registry
7127            .dispatch("list", Value::Null)
7128            .await
7129            .expect_err("the gate denies every request");
7130        assert!(
7131            matches!(err, RuntimeError::PermissionDenied { .. }),
7132            "a pure-observability row's failure must never surface as the dispatch error: {err}"
7133        );
7134
7135        let metrics = registry
7136            .audit_batch_metrics()
7137            .expect("with_event_store configures the ADR-133 seam");
7138        assert!(
7139            metrics.degraded,
7140            "the config-locked row's commit failure must be visible as degradation"
7141        );
7142        assert!(metrics.degraded_rows >= 1);
7143    }
7144
7145    #[tokio::test]
7146    #[serial(config_ledger)]
7147    #[serial(audit_append_failures)]
7148    async fn config_locked_row_failure_never_fails_a_dispatch_that_would_otherwise_succeed() {
7149        // ADR-133 criterion 4's success half: a pure-observability row's
7150        // commit failure must degrade gracefully without touching the
7151        // caller-visible outcome of a dispatch that has nothing to do with
7152        // it. Only the `ConfigLocked` generation fails here — the gate
7153        // allows the call, so `list`'s own `DispatchSucceeded` obligation
7154        // row commits in a later, unaffected generation.
7155        crate::config_ledger::record_config_locked(
7156            "adr133_success_path_key",
7157            "adr133_success_path_value",
7158        );
7159
7160        let store = Arc::new(MemoryEventStore {
7161            fail_kind: Some(EventKind::ConfigLocked),
7162            ..MemoryEventStore::default()
7163        });
7164        let mut builder = VerbRegistryBuilder::new();
7165        builder.register(AlphaPack);
7166        builder.with_event_store(store);
7167        let registry = builder.build().expect("registry builds");
7168
7169        let result = registry
7170            .dispatch("list", Value::Null)
7171            .await
7172            .expect("a config-locked row's commit failure must never fail an unrelated dispatch");
7173        assert_eq!(
7174            result,
7175            serde_json::json!({ "pack": "alpha", "verb": "list" })
7176        );
7177
7178        let metrics = registry
7179            .audit_batch_metrics()
7180            .expect("with_event_store configures the ADR-133 seam");
7181        assert!(
7182            metrics.degraded_rows >= 1,
7183            "the config-locked row's failure must remain visible as degradation"
7184        );
7185    }
7186
7187    /// An `EventStore` that only implements the base trait — the
7188    /// unmodified pre-ADR-133 shape. `preflight_event`/
7189    /// `append_events_idempotent`/`supports_idempotent_audit_batch` are all
7190    /// inherited defaults.
7191    #[derive(Default)]
7192    struct LegacyEventStore {
7193        events: std::sync::Mutex<Vec<Event>>,
7194    }
7195
7196    #[async_trait]
7197    impl EventStore for LegacyEventStore {
7198        async fn append_event(&self, event: Event) -> khive_storage::StorageResult<()> {
7199            self.events.lock().unwrap().push(event);
7200            Ok(())
7201        }
7202        async fn append_events(
7203            &self,
7204            events: Vec<Event>,
7205        ) -> khive_storage::StorageResult<BatchWriteSummary> {
7206            let attempted = events.len() as u64;
7207            self.events.lock().unwrap().extend(events);
7208            Ok(BatchWriteSummary {
7209                attempted,
7210                affected: attempted,
7211                failed: 0,
7212                first_error: String::new(),
7213            })
7214        }
7215        async fn get_event(&self, id: uuid::Uuid) -> khive_storage::StorageResult<Option<Event>> {
7216            Ok(self
7217                .events
7218                .lock()
7219                .unwrap()
7220                .iter()
7221                .find(|e| e.id == id)
7222                .cloned())
7223        }
7224        async fn query_events(
7225            &self,
7226            _filter: EventFilter,
7227            _page: PageRequest,
7228        ) -> khive_storage::StorageResult<Page<Event>> {
7229            let items = self.events.lock().unwrap().clone();
7230            let total = items.len() as u64;
7231            Ok(Page {
7232                items,
7233                total: Some(total),
7234            })
7235        }
7236        async fn count_events(&self, _filter: EventFilter) -> khive_storage::StorageResult<u64> {
7237            Ok(self.events.lock().unwrap().len() as u64)
7238        }
7239    }
7240
7241    #[test]
7242    fn build_rejects_a_configured_event_store_incompatible_with_the_audit_batch_seam() {
7243        let mut builder = VerbRegistryBuilder::new();
7244        builder.register(AlphaPack);
7245        builder.with_event_store(Arc::new(LegacyEventStore::default()));
7246        let err = match builder.build() {
7247            Ok(_) => {
7248                panic!("a store that cannot implement the seam must not build a healthy registry")
7249            }
7250            Err(err) => err,
7251        };
7252        assert!(
7253            matches!(&err, RuntimeError::IncompatibleEventStore(message)
7254                if message.contains("supports_idempotent_audit_batch")),
7255            "error names the missing capability so an operator can act on it: {err}"
7256        );
7257    }
7258
7259    #[tokio::test]
7260    #[serial(config_ledger)]
7261    #[serial(audit_append_failures)]
7262    #[serial(audit_obligation_append_failures)]
7263    async fn db_diagnostics_with_audit_metrics_reports_batch_failure_and_degradation() {
7264        // One dispatch call exercises both halves of the classifier through
7265        // the registry it actually owns the seam on: the queued
7266        // `ConfigLocked` (pure-observability) row drains during the gate
7267        // check regardless of allow/deny, and `list`'s deferred
7268        // `DispatchSucceeded` (obligation) row is appended once dispatch
7269        // resolves — both against the same persistently failing store.
7270        crate::config_ledger::record_config_locked(
7271            "adr133_diag_test_key",
7272            "adr133_diag_test_value",
7273        );
7274        let store = Arc::new(MemoryEventStore {
7275            fail_appends: true,
7276            ..MemoryEventStore::default()
7277        });
7278        let mut builder = VerbRegistryBuilder::new();
7279        builder.register(AlphaPack);
7280        builder.with_event_store(store);
7281        let registry = builder.build().expect("registry builds");
7282        let _ = registry.dispatch("list", Value::Null).await;
7283
7284        let metrics = registry
7285            .audit_batch_metrics()
7286            .expect("with_event_store configures the ADR-133 seam");
7287        assert!(metrics.degraded, "the config-locked row must have degraded");
7288        assert!(metrics.degraded_rows >= 1);
7289        assert!(
7290            metrics.flush_failures >= 1,
7291            "the list dispatch's obligation row must count as a flush failure"
7292        );
7293
7294        let rt = KhiveRuntime::memory().expect("memory runtime should create");
7295        let report = rt
7296            .db_diagnostics_with_audit_metrics(Some(metrics))
7297            .await
7298            .expect("diagnostics succeed");
7299        assert_eq!(report.writer_contention.audit_degraded, Some(true));
7300        assert!(report.writer_contention.audit_degraded_rows.unwrap_or(0) >= 1);
7301        assert!(
7302            report
7303                .writer_contention
7304                .audit_batch_flush_failures
7305                .unwrap_or(0)
7306                >= 1
7307        );
7308        assert!(report
7309            .writer_contention
7310            .audit_batch_flush_failures_unavailable_reason
7311            .is_none());
7312        assert!(report
7313            .writer_contention
7314            .audit_degraded_unavailable_reason
7315            .is_none());
7316
7317        // The no-metrics path (a bare `KhiveRuntime::db_diagnostics`, or the
7318        // `db_diagnostics_with_audit_metrics(None)` it delegates to) must
7319        // still report the batch-health fields as explicitly unavailable
7320        // rather than silently zero, so an operator cannot mistake "no
7321        // registry wired in" for "no failures occurred".
7322        let bare_report = rt.db_diagnostics().await.expect("diagnostics succeed");
7323        assert!(bare_report.writer_contention.audit_degraded.is_none());
7324        assert!(bare_report
7325            .writer_contention
7326            .audit_degraded_unavailable_reason
7327            .is_some());
7328        assert!(bare_report
7329            .writer_contention
7330            .audit_admission_refused_obligations
7331            .is_none());
7332        assert!(bare_report
7333            .writer_contention
7334            .audit_admission_refused_obligations_unavailable_reason
7335            .is_some());
7336        assert!(bare_report
7337            .writer_contention
7338            .audit_admission_unresolved_obligations
7339            .is_none());
7340        assert!(bare_report
7341            .writer_contention
7342            .audit_admission_unresolved_obligations_unavailable_reason
7343            .is_some());
7344    }
7345
7346    #[tokio::test]
7347    async fn audit_event_duration_us_reflects_measured_dispatch_time() {
7348        // The persisted audit row's `duration_us` must carry the measured
7349        // pack-dispatch time, not the `Event::new` default of 0 (persisting
7350        // the row before dispatch ran always yielded 0). `SleepingPack`
7351        // sleeps 20ms so the assertion has a wide, non-flaky margin over
7352        // scheduling jitter.
7353        let store = Arc::new(MemoryEventStore::default());
7354        let mut builder = VerbRegistryBuilder::new();
7355        builder.register(SleepingPack);
7356        builder.with_event_store(store.clone());
7357        let reg = builder.build().expect("registry builds");
7358
7359        reg.dispatch("slow_op", serde_json::json!({}))
7360            .await
7361            .unwrap();
7362
7363        let page = store
7364            .query_events(
7365                EventFilter::default(),
7366                PageRequest {
7367                    limit: 10,
7368                    offset: 0,
7369                },
7370            )
7371            .await
7372            .unwrap();
7373        assert_eq!(page.items.len(), 1);
7374        let ev = &page.items[0];
7375        assert!(
7376            ev.duration_us >= 10_000,
7377            "duration_us must reflect the ~20ms measured dispatch time, got {}",
7378            ev.duration_us
7379        );
7380    }
7381
7382    #[tokio::test]
7383    async fn dispatch_unknown_verb_allowed_by_gate_still_persists_audit_row() {
7384        // Generalizing audit-row deferral to every Allow-outcome verb (not
7385        // just singleton `link`) must not silently drop the audit row for a
7386        // verb the gate allows but no pack owns. `duration_us` stays at the
7387        // `Event::new` default of 0 here since no dispatch ever ran to measure.
7388        let store = Arc::new(MemoryEventStore::default());
7389        let mut builder = VerbRegistryBuilder::new();
7390        builder.register(AlphaPack);
7391        builder.with_event_store(store.clone());
7392        let reg = builder.build().expect("registry builds");
7393
7394        let result = reg.dispatch("no_such_verb", serde_json::json!({})).await;
7395        assert!(result.is_err(), "unknown verb must still return an error");
7396
7397        let count = store.count_events(EventFilter::default()).await.unwrap();
7398        assert_eq!(
7399            count, 1,
7400            "an allowed-but-unknown verb must still persist one audit row"
7401        );
7402        let page = store
7403            .query_events(
7404                EventFilter::default(),
7405                PageRequest {
7406                    limit: 10,
7407                    offset: 0,
7408                },
7409            )
7410            .await
7411            .unwrap();
7412        assert_eq!(page.items[0].duration_us, 0);
7413        // Dispatch returns UnknownVerb for an unknown verb, so the
7414        // persisted outcome must be Error, not the previously-hardcoded
7415        // Success.
7416        assert_eq!(page.items[0].outcome, EventOutcome::Error);
7417    }
7418
7419    #[tokio::test]
7420    async fn audit_event_persists_to_event_store_on_deny() {
7421        #[derive(Debug)]
7422        struct AlwaysDenyGate;
7423        impl Gate for AlwaysDenyGate {
7424            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7425                Ok(GateDecision::deny("denied by test"))
7426            }
7427        }
7428
7429        let store = Arc::new(MemoryEventStore::default());
7430        let mut builder = VerbRegistryBuilder::new();
7431        builder.register(AlphaPack);
7432        builder.with_gate(Arc::new(AlwaysDenyGate));
7433        builder.with_event_store(store.clone());
7434        let reg = builder.build().expect("registry builds");
7435
7436        // Hard enforce → PermissionDenied returned.
7437        let err = reg
7438            .dispatch("list", serde_json::json!({"namespace": "test-ns"}))
7439            .await
7440            .unwrap_err();
7441        assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
7442
7443        let count = store.count_events(EventFilter::default()).await.unwrap();
7444        assert_eq!(count, 1, "one audit event persisted to EventStore on deny");
7445
7446        let page = store
7447            .query_events(
7448                EventFilter::default(),
7449                PageRequest {
7450                    limit: 10,
7451                    offset: 0,
7452                },
7453            )
7454            .await
7455            .unwrap();
7456        let ev = &page.items[0];
7457        assert_eq!(ev.verb, "list");
7458        assert_eq!(ev.outcome, EventOutcome::Denied);
7459    }
7460
7461    #[tokio::test]
7462    async fn gate_error_returns_typed_refusal_without_invoking_pack() {
7463        #[derive(Debug)]
7464        struct FailingGate;
7465        impl Gate for FailingGate {
7466            fn check(&self, _req: &GateRequest) -> Result<GateDecision, khive_gate::GateError> {
7467                Err(khive_gate::GateError::Internal("gate broken".into()))
7468            }
7469        }
7470
7471        let store = Arc::new(MemoryEventStore::default());
7472        let invoked = Arc::new(AtomicUsize::new(0));
7473        let mut builder = VerbRegistryBuilder::new();
7474        builder.register(GateErrorTrackingPack {
7475            invoked: Arc::clone(&invoked),
7476        });
7477        builder.with_gate(Arc::new(FailingGate));
7478        builder.with_event_store(store.clone());
7479        let reg = builder.build().expect("registry builds");
7480
7481        let err = reg
7482            .dispatch("guarded", Value::Null)
7483            .await
7484            .expect_err("gate unavailability must refuse normal dispatch");
7485        assert!(matches!(
7486            err,
7487            RuntimeError::GateUnavailable { ref verb, ref reason }
7488                if verb == "guarded"
7489                    && reason == "gate backend unavailable"
7490                    && !reason.contains("gate broken")
7491        ));
7492        assert_eq!(
7493            invoked.load(Ordering::SeqCst),
7494            0,
7495            "pack handler must not run after a gate infrastructure error"
7496        );
7497
7498        let count = store.count_events(EventFilter::default()).await.unwrap();
7499        assert_eq!(count, 1, "gate infrastructure error must be audited");
7500        let page = store
7501            .query_events(
7502                EventFilter::default(),
7503                PageRequest {
7504                    limit: 10,
7505                    offset: 0,
7506                },
7507            )
7508            .await
7509            .unwrap();
7510        let event = &page.items[0];
7511        assert_eq!(event.verb, "guarded");
7512        assert_eq!(event.outcome, EventOutcome::Error);
7513        assert_eq!(event.payload["decision"], "gate_unavailable");
7514        assert!(event.payload.get("deny_reason").is_none());
7515        assert_eq!(event.payload["resource"]["work_class"], "interactive");
7516        assert!(event.payload["resource"].get("cost_unit").is_none());
7517    }
7518
7519    #[tokio::test]
7520    #[serial(audit_append_failures)]
7521    async fn gate_error_audit_failure_cannot_reopen_dispatch_or_replace_typed_error() {
7522        #[derive(Debug)]
7523        struct FailingGate;
7524        impl Gate for FailingGate {
7525            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7526                Err(GateError::Internal("gate still broken".into()))
7527            }
7528        }
7529
7530        let before = audit_append_failure_count();
7531        let invoked = Arc::new(AtomicUsize::new(0));
7532        let store = Arc::new(MemoryEventStore {
7533            fail_appends: true,
7534            ..MemoryEventStore::default()
7535        });
7536        let mut builder = VerbRegistryBuilder::new();
7537        builder.register(GateErrorTrackingPack {
7538            invoked: Arc::clone(&invoked),
7539        });
7540        builder.with_gate(Arc::new(FailingGate));
7541        builder.with_event_store(store);
7542        let registry = builder.build().expect("registry builds");
7543
7544        let error = registry
7545            .dispatch("guarded", Value::Null)
7546            .await
7547            .expect_err("audit persistence failure must not reopen dispatch");
7548
7549        assert!(matches!(
7550            error,
7551            RuntimeError::GateUnavailable { ref verb, ref reason }
7552                if verb == "guarded"
7553                    && reason == "gate backend unavailable"
7554                    && !reason.contains("gate still broken")
7555        ));
7556        assert_eq!(invoked.load(Ordering::SeqCst), 0);
7557        assert_eq!(
7558            audit_append_failure_count(),
7559            before + 1,
7560            "best-effort audit failure remains diagnostic without changing the refusal"
7561        );
7562    }
7563
7564    /// Regression for a credential-disclosure path: a gate backend's error
7565    /// `Display` text can embed connection details (URLs, addresses, auth
7566    /// material). That text must never reach `RuntimeError::GateUnavailable`
7567    /// as observed by a dispatch caller — only the stable classified
7568    /// `wire_reason()` may cross that boundary. A bounded, masked rendering
7569    /// of the error is logged server-side via `tracing::warn!` in
7570    /// `gate_unavailable_error`.
7571    #[tokio::test]
7572    async fn gate_unavailable_reason_never_carries_backend_error_text() {
7573        const CANARY: &str = "postgres://svc:not-a-real-secret@internal-host";
7574
7575        #[derive(Debug)]
7576        struct FailingGate;
7577        impl Gate for FailingGate {
7578            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7579                Err(GateError::Internal(CANARY.to_string()))
7580            }
7581        }
7582
7583        let mut builder = VerbRegistryBuilder::new();
7584        builder.register(GateErrorTrackingPack {
7585            invoked: Arc::new(AtomicUsize::new(0)),
7586        });
7587        builder.with_gate(Arc::new(FailingGate));
7588        let registry = builder.build().expect("registry builds");
7589
7590        let err = registry
7591            .dispatch("guarded", Value::Null)
7592            .await
7593            .expect_err("gate unavailability must refuse dispatch");
7594
7595        let RuntimeError::GateUnavailable { reason, .. } = &err else {
7596            panic!("expected GateUnavailable, got {err:?}");
7597        };
7598        assert!(
7599            !reason.contains(CANARY),
7600            "caller-visible reason must not embed backend error text: {reason:?}"
7601        );
7602        assert!(
7603            !reason.contains("svc") && !reason.contains("internal-host"),
7604            "caller-visible reason must not embed backend error fragments: {reason:?}"
7605        );
7606        assert_eq!(reason, "gate backend unavailable");
7607
7608        // The full error, canary included, still reaches the server-side log.
7609        let rendered = err.to_string();
7610        assert!(
7611            !rendered.contains(CANARY),
7612            "top-level Display must not embed backend error text either: {rendered:?}"
7613        );
7614    }
7615
7616    /// Task 2 (ADR-129 gate-error classification): a `GateError::Policy`
7617    /// failure — the gate backend is reachable but its configured policy
7618    /// could not be evaluated — is a distinct, non-transient class from a
7619    /// `GateError::Internal` backend-availability failure, and gets its own
7620    /// stable reason text at the dispatch boundary.
7621    #[tokio::test]
7622    async fn gate_policy_error_classifies_distinctly_from_backend_unavailable() {
7623        #[derive(Debug)]
7624        struct PolicyBrokenGate;
7625        impl Gate for PolicyBrokenGate {
7626            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7627                Err(GateError::Policy(
7628                    "rule set has no allow clause for this namespace".to_string(),
7629                ))
7630            }
7631        }
7632
7633        let mut builder = VerbRegistryBuilder::new();
7634        builder.register(GateErrorTrackingPack {
7635            invoked: Arc::new(AtomicUsize::new(0)),
7636        });
7637        builder.with_gate(Arc::new(PolicyBrokenGate));
7638        let registry = builder.build().expect("registry builds");
7639
7640        let err = registry
7641            .dispatch("guarded", Value::Null)
7642            .await
7643            .expect_err("gate unavailability must refuse dispatch");
7644
7645        assert!(matches!(
7646            err,
7647            RuntimeError::GateUnavailable { ref verb, ref reason }
7648                if verb == "guarded"
7649                    && reason == "gate policy evaluation failed"
7650                    && !reason.contains("rule set has no allow clause")
7651        ));
7652    }
7653
7654    #[tokio::test]
7655    async fn no_event_store_configured_tracing_only() {
7656        // Ordinary verbs remain tracing-only without an event store. The
7657        // strict git.digest receipt exception is covered separately above.
7658        let mut builder = VerbRegistryBuilder::new();
7659        builder.register(AlphaPack);
7660        let reg = builder.build().expect("registry builds");
7661
7662        let res = reg.dispatch("list", Value::Null).await.unwrap();
7663        assert_eq!(res["pack"], "alpha");
7664    }
7665
7666    #[test]
7667    #[serial]
7668    fn dispatch_tracing_emits_gate_check_event_with_deny_payload() {
7669        #[derive(Debug)]
7670        struct TracingDenyGate;
7671        impl Gate for TracingDenyGate {
7672            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7673                Ok(GateDecision::deny("denied by test gate"))
7674            }
7675            fn impl_name(&self) -> &'static str {
7676                "TracingDenyGate"
7677            }
7678        }
7679
7680        let events = capture_dispatch_events(async {
7681            let mut builder = VerbRegistryBuilder::new();
7682            builder.register(AlphaPack);
7683            builder.with_gate(Arc::new(TracingDenyGate));
7684            let reg = builder.build().expect("registry builds");
7685            // Hard enforcement — dispatch returns PermissionDenied on Deny.
7686            // The tracing audit event is still emitted before the error is returned.
7687            let _ = reg.dispatch("create", serde_json::Value::Null).await;
7688        });
7689
7690        let gate_events = gate_check_events_for(&events, "TracingDenyGate");
7691        assert_eq!(
7692            gate_events.len(),
7693            1,
7694            "exactly one gate.check tracing event per dispatch (deny); got {gate_events:?}"
7695        );
7696        let payload = gate_events[0]
7697            .audit_event
7698            .as_ref()
7699            .expect("gate.check event must carry an audit_event field on Deny");
7700        let audit: khive_gate::AuditEvent =
7701            serde_json::from_str(payload).expect("audit_event payload must decode to AuditEvent");
7702        assert_eq!(audit.decision, AuditDecision::Deny);
7703        assert_eq!(audit.deny_reason.as_deref(), Some("denied by test gate"));
7704        assert_eq!(audit.gate_impl, "TracingDenyGate");
7705        // Wire-shape rule: obligations is always serialized as an array, empty
7706        // on Deny. Round-trip back through serde_json::Value to confirm the
7707        // field exists on the wire and is `[]`, not missing.
7708        let payload_json: serde_json::Value =
7709            serde_json::from_str(payload).expect("payload must be valid JSON");
7710        assert_eq!(
7711            payload_json["obligations"],
7712            serde_json::Value::Array(Vec::new()),
7713            "obligations must be `[]` on Deny on the tracing payload, not omitted"
7714        );
7715    }
7716
7717    // ---- EventStore audit envelope round-trip ----
7718    //
7719    // EventStore must not persist a summary Event without the full
7720    // AuditEvent fields (deny_reason, gate_impl, obligations). This test
7721    // verifies the complete envelope survives append_event → query_events.
7722
7723    #[tokio::test]
7724    async fn audit_envelope_round_trips_deny_reason_and_gate_impl_through_event_store() {
7725        #[derive(Debug)]
7726        struct DenyGateWithName;
7727        impl Gate for DenyGateWithName {
7728            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7729                Ok(GateDecision::deny("policy: write forbidden for anon"))
7730            }
7731            fn impl_name(&self) -> &'static str {
7732                "DenyGateWithName"
7733            }
7734        }
7735
7736        let store = Arc::new(MemoryEventStore::default());
7737        let mut builder = VerbRegistryBuilder::new();
7738        builder.register(AlphaPack);
7739        builder.with_gate(Arc::new(DenyGateWithName));
7740        builder.with_event_store(store.clone());
7741        let reg = builder.build().expect("registry builds");
7742
7743        // Dispatch is denied — PermissionDenied returned.
7744        let err = reg
7745            .dispatch("list", serde_json::json!({"namespace": "test-ns"}))
7746            .await
7747            .unwrap_err();
7748        assert!(
7749            matches!(err, RuntimeError::PermissionDenied { .. }),
7750            "expected PermissionDenied, got {err:?}"
7751        );
7752
7753        // Exactly one event in the store.
7754        let page = store
7755            .query_events(
7756                EventFilter::default(),
7757                PageRequest {
7758                    limit: 10,
7759                    offset: 0,
7760                },
7761            )
7762            .await
7763            .unwrap();
7764        assert_eq!(
7765            page.items.len(),
7766            1,
7767            "one audit event must be persisted on deny"
7768        );
7769
7770        let ev = &page.items[0];
7771        assert_eq!(ev.outcome, EventOutcome::Denied);
7772
7773        // The payload field must hold the full AuditEvent envelope.
7774        let data = &ev.payload;
7775
7776        let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
7777            .expect("Event.payload must deserialize to AuditEvent");
7778
7779        assert_eq!(
7780            audit.deny_reason.as_deref(),
7781            Some("policy: write forbidden for anon"),
7782            "deny_reason must be preserved through EventStore"
7783        );
7784        assert_eq!(
7785            audit.gate_impl, "DenyGateWithName",
7786            "gate_impl must be preserved through EventStore"
7787        );
7788        assert_eq!(
7789            audit.decision,
7790            khive_gate::AuditDecision::Deny,
7791            "decision field must be preserved through EventStore"
7792        );
7793    }
7794
7795    #[tokio::test]
7796    async fn audit_envelope_round_trips_obligations_through_event_store() {
7797        use khive_gate::Obligation;
7798
7799        #[derive(Debug)]
7800        struct ObligationGate;
7801        impl Gate for ObligationGate {
7802            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7803                Ok(GateDecision::allow_with(vec![Obligation::Audit {
7804                    tag: "billing.meter".into(),
7805                }]))
7806            }
7807            fn impl_name(&self) -> &'static str {
7808                "ObligationGate"
7809            }
7810        }
7811
7812        let store = Arc::new(MemoryEventStore::default());
7813        let mut builder = VerbRegistryBuilder::new();
7814        builder.register(AlphaPack);
7815        builder.with_gate(Arc::new(ObligationGate));
7816        builder.with_event_store(store.clone());
7817        let reg = builder.build().expect("registry builds");
7818
7819        reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
7820            .await
7821            .unwrap();
7822
7823        let page = store
7824            .query_events(
7825                EventFilter::default(),
7826                PageRequest {
7827                    limit: 10,
7828                    offset: 0,
7829                },
7830            )
7831            .await
7832            .unwrap();
7833        assert_eq!(page.items.len(), 1);
7834
7835        let ev = &page.items[0];
7836        assert_eq!(ev.outcome, EventOutcome::Success);
7837
7838        let data = &ev.payload;
7839
7840        let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
7841            .expect("Event.payload must deserialize to AuditEvent");
7842
7843        assert_eq!(audit.gate_impl, "ObligationGate");
7844        assert_eq!(
7845            audit.obligations.len(),
7846            1,
7847            "obligations must be preserved through EventStore"
7848        );
7849        match &audit.obligations[0] {
7850            Obligation::Audit { tag } => assert_eq!(tag, "billing.meter"),
7851            other => panic!("expected Audit obligation, got {other:?}"),
7852        }
7853    }
7854
7855    // ---- SQL-backed audit envelope round-trip ----
7856    //
7857    // The two tests above use MemoryEventStore (no serialization). This test
7858    // wires the production SqlEventStore via KhiveRuntime::memory() to verify
7859    // that the full AuditEvent envelope survives the SQL text→parse round-trip
7860    // (Event.data is stored as TEXT and parsed back on read).
7861
7862    #[tokio::test]
7863    async fn sql_backed_audit_envelope_round_trips_deny_reason_gate_impl_and_obligations() {
7864        #[derive(Debug)]
7865        struct SqlTestDenyGate;
7866        impl Gate for SqlTestDenyGate {
7867            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7868                Ok(GateDecision::deny("sql-path: write denied"))
7869            }
7870            fn impl_name(&self) -> &'static str {
7871                "SqlTestDenyGate"
7872            }
7873        }
7874
7875        // KhiveRuntime::memory() creates an in-memory SQLite pool (is_file_backed=false).
7876        // events_for_namespace ensures the events schema and returns a SqlEventStore
7877        // scoped to "test-ns". The pool is shared so reads and writes see the same data.
7878        let rt = KhiveRuntime::memory().expect("in-memory runtime");
7879        let test_tok = NamespaceToken::for_namespace(Namespace::parse("test-ns").unwrap());
7880        let sql_store = rt
7881            .events(&test_tok)
7882            .expect("events_for_namespace must succeed");
7883
7884        let mut builder = VerbRegistryBuilder::new();
7885        builder.register(AlphaPack);
7886        builder.with_gate(Arc::new(SqlTestDenyGate));
7887        builder.with_event_store(sql_store.clone());
7888        let reg = builder.build().expect("registry builds");
7889
7890        // Dispatch is denied — PermissionDenied returned.
7891        let err = reg
7892            .dispatch("list", serde_json::json!({"namespace": "test-ns"}))
7893            .await
7894            .unwrap_err();
7895        assert!(
7896            matches!(err, RuntimeError::PermissionDenied { .. }),
7897            "expected PermissionDenied, got {err:?}"
7898        );
7899
7900        // Query via the same SqlEventStore — this is the SQL read path.
7901        let page = sql_store
7902            .query_events(
7903                EventFilter::default(),
7904                PageRequest {
7905                    limit: 10,
7906                    offset: 0,
7907                },
7908            )
7909            .await
7910            .unwrap();
7911        assert_eq!(
7912            page.items.len(),
7913            1,
7914            "one audit event must be persisted on deny through SqlEventStore"
7915        );
7916
7917        let ev = &page.items[0];
7918        assert_eq!(ev.outcome, EventOutcome::Denied);
7919
7920        // Event.payload must hold the full AuditEvent serialized as JSON text and
7921        // parsed back. If the SQL path was lossy, this deserialization would fail
7922        // or the field assertions below would fail.
7923        let data = &ev.payload;
7924
7925        let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
7926            .expect("Event.payload must deserialize to AuditEvent after SQL round-trip");
7927
7928        assert_eq!(
7929            audit.deny_reason.as_deref(),
7930            Some("sql-path: write denied"),
7931            "deny_reason must survive the SQL text round-trip"
7932        );
7933        assert_eq!(
7934            audit.gate_impl, "SqlTestDenyGate",
7935            "gate_impl must survive the SQL text round-trip"
7936        );
7937        assert_eq!(
7938            audit.decision,
7939            khive_gate::AuditDecision::Deny,
7940            "decision field must survive the SQL text round-trip"
7941        );
7942        // obligations is [] on a Deny gate (no obligations returned).
7943        // Verify the field is present and empty after SQL round-trip.
7944        assert!(
7945            audit.obligations.is_empty(),
7946            "obligations must be preserved as empty [] through SQL round-trip"
7947        );
7948    }
7949
7950    // ---- SQL-backed audit envelope: non-empty obligations survive round-trip ----
7951    //
7952    // Blind spot: the deny-path SQL test above only
7953    // asserts obligations == [], which passes even if the SQL path drops the
7954    // field entirely (AuditEvent.obligations has #[serde(default)]).
7955    //
7956    // This test installs an allow-path gate that returns a non-empty obligations
7957    // vec. After dispatch, the same SqlEventStore is queried and both layers are
7958    // checked:
7959    //   1. Raw Event.data["obligations"] is a non-empty JSON array.
7960    //   2. Deserialized AuditEvent.obligations[0] matches the expected variant.
7961    #[tokio::test]
7962    async fn sql_backed_audit_envelope_round_trips_non_empty_obligations() {
7963        use khive_gate::Obligation;
7964
7965        #[derive(Debug)]
7966        struct SqlTestAllowWithObligationGate;
7967        impl Gate for SqlTestAllowWithObligationGate {
7968            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
7969                Ok(GateDecision::allow_with(vec![Obligation::Audit {
7970                    tag: "sql-path-billing.meter".into(),
7971                }]))
7972            }
7973            fn impl_name(&self) -> &'static str {
7974                "SqlTestAllowWithObligationGate"
7975            }
7976        }
7977
7978        let rt = KhiveRuntime::memory().expect("in-memory runtime");
7979        let test_tok = NamespaceToken::for_namespace(Namespace::parse("test-ns").unwrap());
7980        let sql_store = rt
7981            .events(&test_tok)
7982            .expect("events_for_namespace must succeed");
7983
7984        let mut builder = VerbRegistryBuilder::new();
7985        builder.register(AlphaPack);
7986        builder.with_gate(Arc::new(SqlTestAllowWithObligationGate));
7987        builder.with_event_store(sql_store.clone());
7988        let reg = builder.build().expect("registry builds");
7989
7990        // Dispatch succeeds — the gate allows with obligations.
7991        reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
7992            .await
7993            .expect("dispatch must succeed when gate allows");
7994
7995        // Query via the same SqlEventStore — this is the SQL read path.
7996        let page = sql_store
7997            .query_events(
7998                EventFilter::default(),
7999                PageRequest {
8000                    limit: 10,
8001                    offset: 0,
8002                },
8003            )
8004            .await
8005            .unwrap();
8006        assert_eq!(
8007            page.items.len(),
8008            1,
8009            "one audit event must be persisted on allow through SqlEventStore"
8010        );
8011
8012        let ev = &page.items[0];
8013        assert_eq!(ev.outcome, EventOutcome::Success);
8014
8015        let data = &ev.payload;
8016
8017        // Layer 1: raw JSON check — obligations must be a non-empty array in
8018        // the persisted TEXT. If the SQL path dropped the field, the default
8019        // #[serde(default)] would silently deserialize it to [], so we verify
8020        // the raw JSON before deserializing.
8021        let obligations_raw = data
8022            .get("obligations")
8023            .expect("Event.data JSON must contain 'obligations' key");
8024        let obligations_arr = obligations_raw
8025            .as_array()
8026            .expect("'obligations' must be a JSON array");
8027        assert!(
8028            !obligations_arr.is_empty(),
8029            "raw Event.data['obligations'] must be non-empty after SQL round-trip"
8030        );
8031
8032        // Layer 2: deserialized AuditEvent check — the obligation variant and
8033        // payload must survive the text round-trip faithfully.
8034        let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
8035            .expect("Event.data must deserialize to AuditEvent after SQL round-trip");
8036
8037        assert_eq!(
8038            audit.gate_impl, "SqlTestAllowWithObligationGate",
8039            "gate_impl must survive the SQL text round-trip"
8040        );
8041        assert_eq!(
8042            audit.decision,
8043            khive_gate::AuditDecision::Allow,
8044            "decision field must survive the SQL text round-trip"
8045        );
8046        assert_eq!(
8047            audit.obligations.len(),
8048            1,
8049            "obligations must be non-empty after SQL round-trip (not silently defaulted to [])"
8050        );
8051        match &audit.obligations[0] {
8052            Obligation::Audit { tag } => assert_eq!(
8053                tag, "sql-path-billing.meter",
8054                "Audit obligation tag must survive the SQL text round-trip"
8055            ),
8056            other => panic!("expected Audit obligation, got {other:?}"),
8057        }
8058    }
8059
8060    // ---- Audit payload shape for 'create' verb dispatch ----
8061    //
8062    // The previous audit tests verify the envelope shape for the 'list' verb.
8063    // This test dispatches 'create' (matching the create_note + annotates path)
8064    // and verifies that ev.verb, ev.outcome, and ev.data all round-trip correctly
8065    // through the EventStore. Ensures the wire shape is independent of which verb
8066    // triggers the gate check.
8067    #[tokio::test]
8068    async fn audit_event_payload_shape_for_create_verb() {
8069        let store = Arc::new(MemoryEventStore::default());
8070        let mut builder = VerbRegistryBuilder::new();
8071        builder.register(AlphaPack);
8072        builder.with_event_store(store.clone());
8073        builder.with_default_namespace("test-ns");
8074        let reg = builder.build().expect("registry builds");
8075
8076        // Dispatch 'create' — AlphaPack returns a stub value; what matters is
8077        // the EventStore entry emitted by the registry's gate-check path.
8078        reg.dispatch("create", serde_json::json!({"namespace": "test-ns"}))
8079            .await
8080            .unwrap();
8081
8082        let count = store.count_events(EventFilter::default()).await.unwrap();
8083        assert_eq!(count, 1, "exactly one audit event for one dispatch");
8084
8085        let page = store
8086            .query_events(
8087                EventFilter::default(),
8088                PageRequest {
8089                    limit: 10,
8090                    offset: 0,
8091                },
8092            )
8093            .await
8094            .unwrap();
8095        let ev = &page.items[0];
8096
8097        // Top-level Event fields.
8098        assert_eq!(ev.verb, "create", "ev.verb must be the dispatched verb");
8099        assert_eq!(
8100            ev.outcome,
8101            EventOutcome::Success,
8102            "ev.outcome must be Success on allow"
8103        );
8104        assert_eq!(
8105            ev.namespace, "test-ns",
8106            "ev.namespace must match the dispatch namespace"
8107        );
8108
8109        // ev.payload must hold the full AuditEvent envelope.
8110        let data = &ev.payload;
8111
8112        let audit: khive_gate::AuditEvent = serde_json::from_value(data.clone())
8113            .expect("ev.payload must deserialize to AuditEvent");
8114
8115        assert_eq!(
8116            audit.decision,
8117            khive_gate::AuditDecision::Allow,
8118            "AuditEvent.decision must be Allow"
8119        );
8120        assert_eq!(audit.verb, "create", "AuditEvent.verb must be 'create'");
8121        assert_eq!(
8122            audit.namespace, "test-ns",
8123            "AuditEvent.namespace must be preserved"
8124        );
8125        assert_eq!(
8126            audit.gate_impl, "AllowAllGate",
8127            "AuditEvent.gate_impl must name the gate implementation"
8128        );
8129        assert!(
8130            audit.deny_reason.is_none(),
8131            "AuditEvent.deny_reason must be None on Allow"
8132        );
8133        // Wire-shape check: obligations serializes as [] on AllowAllGate.
8134        let payload_json: serde_json::Value =
8135            serde_json::from_value(data.clone()).expect("data must be valid JSON");
8136        assert_eq!(
8137            payload_json["obligations"],
8138            serde_json::Value::Array(Vec::new()),
8139            "obligations must be [] on AllowAllGate"
8140        );
8141    }
8142
8143    // ---- ADR-103 Amendment 1: resource.cost_unit emission ----
8144
8145    /// Test pack whose `create` handler is a stub (mirrors `AlphaPack`) but
8146    /// overrides `registered_embedding_model_names` to a configurable set,
8147    /// exercising ADR-103 Amendment 1's `model_count` computation for
8148    /// singleton `create` at the dispatch audit-row emission seam.
8149    struct EmbeddingAwarePack {
8150        models: Vec<String>,
8151    }
8152
8153    impl khive_types::Pack for EmbeddingAwarePack {
8154        const NAME: &'static str = "embedding_aware";
8155        const NOTE_KINDS: &'static [&'static str] = &[];
8156        const ENTITY_KINDS: &'static [&'static str] = &["widget"];
8157        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
8158            name: "create",
8159            description: "create a widget (embedding-aware stub)",
8160            visibility: Visibility::Verb,
8161            category: VerbCategory::Commissive,
8162            params: &[],
8163        }];
8164    }
8165
8166    #[async_trait]
8167    impl PackRuntime for EmbeddingAwarePack {
8168        fn name(&self) -> &str {
8169            Self::NAME
8170        }
8171        fn note_kinds(&self) -> &'static [&'static str] {
8172            Self::NOTE_KINDS
8173        }
8174        fn entity_kinds(&self) -> &'static [&'static str] {
8175            Self::ENTITY_KINDS
8176        }
8177        fn handlers(&self) -> &'static [HandlerDef] {
8178            Self::HANDLERS
8179        }
8180        fn registered_embedding_model_names(&self) -> Vec<String> {
8181            self.models.clone()
8182        }
8183        async fn dispatch(
8184            &self,
8185            verb: &str,
8186            _params: Value,
8187            _registry: &VerbRegistry,
8188            _token: &NamespaceToken,
8189        ) -> Result<Value, RuntimeError> {
8190            Ok(serde_json::json!({ "pack": "embedding_aware", "verb": verb }))
8191        }
8192    }
8193
8194    /// Test pack whose one verb, `probe`, always fails — used to drive the
8195    /// general (non-link) deferred-audit Err arm without a real backend.
8196    struct FailingProbePack;
8197
8198    impl khive_types::Pack for FailingProbePack {
8199        const NAME: &'static str = "failing_probe";
8200        const NOTE_KINDS: &'static [&'static str] = &[];
8201        const ENTITY_KINDS: &'static [&'static str] = &[];
8202        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
8203            name: "probe",
8204            description: "always fails",
8205            visibility: Visibility::Verb,
8206            category: VerbCategory::Assertive,
8207            params: &[],
8208        }];
8209    }
8210
8211    #[async_trait]
8212    impl PackRuntime for FailingProbePack {
8213        fn name(&self) -> &str {
8214            Self::NAME
8215        }
8216        fn note_kinds(&self) -> &'static [&'static str] {
8217            Self::NOTE_KINDS
8218        }
8219        fn entity_kinds(&self) -> &'static [&'static str] {
8220            Self::ENTITY_KINDS
8221        }
8222        fn handlers(&self) -> &'static [HandlerDef] {
8223            Self::HANDLERS
8224        }
8225        async fn dispatch(
8226            &self,
8227            _verb: &str,
8228            _params: Value,
8229            _registry: &VerbRegistry,
8230            _token: &NamespaceToken,
8231        ) -> Result<Value, RuntimeError> {
8232            Err(RuntimeError::InvalidInput("boom".into()))
8233        }
8234    }
8235
8236    #[tokio::test]
8237    async fn resource_cost_unit_present_on_non_embedding_successful_dispatch() {
8238        let store = Arc::new(MemoryEventStore::default());
8239        let mut builder = VerbRegistryBuilder::new();
8240        builder.register(AlphaPack);
8241        builder.with_event_store(store.clone());
8242        let reg = builder.build().expect("registry builds");
8243
8244        reg.dispatch("list", serde_json::json!({})).await.unwrap();
8245
8246        let page = store
8247            .query_events(
8248                EventFilter::default(),
8249                PageRequest {
8250                    limit: 10,
8251                    offset: 0,
8252                },
8253            )
8254            .await
8255            .unwrap();
8256        assert_eq!(page.items.len(), 1);
8257        assert_eq!(
8258            page.items[0].payload["resource"],
8259            serde_json::json!({"work_class": "interactive", "cost_unit": 1}),
8260            "non-embedding-bearing verb's resource.cost_unit must be base_weight(verb) alone"
8261        );
8262    }
8263
8264    #[tokio::test]
8265    async fn resource_cost_unit_scales_with_registered_model_count_for_create() {
8266        let store = Arc::new(MemoryEventStore::default());
8267        let mut builder = VerbRegistryBuilder::new();
8268        builder.register(EmbeddingAwarePack {
8269            models: vec!["all-minilm-l6-v2".into(), "paraphrase".into()],
8270        });
8271        builder.with_event_store(store.clone());
8272        let reg = builder.build().expect("registry builds");
8273
8274        reg.dispatch("create", serde_json::json!({"kind": "widget"}))
8275            .await
8276            .unwrap();
8277
8278        let page = store
8279            .query_events(
8280                EventFilter::default(),
8281                PageRequest {
8282                    limit: 10,
8283                    offset: 0,
8284                },
8285            )
8286            .await
8287            .unwrap();
8288        // base_weight(1) + per_item_weight(1) * item_count(1) * model_count(2)
8289        assert_eq!(
8290            page.items[0].payload["resource"],
8291            serde_json::json!({"work_class": "interactive", "cost_unit": 3}),
8292        );
8293    }
8294
8295    #[tokio::test]
8296    async fn resource_cost_unit_zero_registered_models_is_base_weight_only() {
8297        let store = Arc::new(MemoryEventStore::default());
8298        let mut builder = VerbRegistryBuilder::new();
8299        builder.register(EmbeddingAwarePack { models: vec![] });
8300        builder.with_event_store(store.clone());
8301        let reg = builder.build().expect("registry builds");
8302
8303        reg.dispatch("create", serde_json::json!({"kind": "widget"}))
8304            .await
8305            .unwrap();
8306
8307        let page = store
8308            .query_events(
8309                EventFilter::default(),
8310                PageRequest {
8311                    limit: 10,
8312                    offset: 0,
8313                },
8314            )
8315            .await
8316            .unwrap();
8317        assert_eq!(
8318            page.items[0].payload["resource"]["cost_unit"], 1,
8319            "zero registered embedding models must vanish the term, not error or omit"
8320        );
8321    }
8322
8323    #[tokio::test]
8324    async fn resource_work_class_present_cost_unit_absent_when_dispatch_returns_error() {
8325        let store = Arc::new(MemoryEventStore::default());
8326        let mut builder = VerbRegistryBuilder::new();
8327        builder.register(FailingProbePack);
8328        builder.with_event_store(store.clone());
8329        let reg = builder.build().expect("registry builds");
8330
8331        let err = reg
8332            .dispatch("probe", serde_json::json!({}))
8333            .await
8334            .unwrap_err();
8335        assert!(matches!(err, RuntimeError::InvalidInput(_)));
8336
8337        let page = store
8338            .query_events(
8339                EventFilter::default(),
8340                PageRequest {
8341                    limit: 10,
8342                    offset: 0,
8343                },
8344            )
8345            .await
8346            .unwrap();
8347        assert_eq!(page.items.len(), 1);
8348        assert_eq!(page.items[0].outcome, EventOutcome::Error);
8349        // ADR-103 Decision (a): work_class is stamped on EVERY event, denial
8350        // and error included -- only Amendment 1's cost_unit field is scoped
8351        // to a successful dispatch. An errored dispatch keeps
8352        // resource.work_class and omits only resource.cost_unit, never 0.
8353        assert_eq!(
8354            page.items[0].payload["resource"],
8355            serde_json::json!({"work_class": "interactive"}),
8356            "resource must carry work_class with cost_unit OMITTED (never 0) on an \
8357             errored dispatch: {:?}",
8358            page.items[0].payload
8359        );
8360    }
8361
8362    #[tokio::test]
8363    async fn resource_work_class_present_cost_unit_absent_when_no_pack_owns_the_verb() {
8364        let store = Arc::new(MemoryEventStore::default());
8365        let mut builder = VerbRegistryBuilder::new();
8366        builder.register(AlphaPack);
8367        builder.with_event_store(store.clone());
8368        let reg = builder.build().expect("registry builds");
8369
8370        let _ = reg
8371            .dispatch("no_such_verb_resource_test", serde_json::json!({}))
8372            .await;
8373
8374        let page = store
8375            .query_events(
8376                EventFilter::default(),
8377                PageRequest {
8378                    limit: 10,
8379                    offset: 0,
8380                },
8381            )
8382            .await
8383            .unwrap();
8384        assert_eq!(page.items.len(), 1);
8385        assert_eq!(
8386            page.items[0].payload["resource"],
8387            serde_json::json!({"work_class": "interactive"})
8388        );
8389    }
8390
8391    #[tokio::test]
8392    async fn resource_work_class_present_cost_unit_absent_on_denied_dispatch() {
8393        #[derive(Debug)]
8394        struct AlwaysDenyGate;
8395        impl Gate for AlwaysDenyGate {
8396            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
8397                Ok(GateDecision::deny("test: always deny"))
8398            }
8399        }
8400        let store = Arc::new(MemoryEventStore::default());
8401        let mut builder = VerbRegistryBuilder::new();
8402        builder.register(AlphaPack);
8403        builder.with_gate(Arc::new(AlwaysDenyGate));
8404        builder.with_event_store(store.clone());
8405        let reg = builder.build().expect("registry builds");
8406
8407        let _ = reg.dispatch("list", serde_json::json!({})).await;
8408
8409        let page = store
8410            .query_events(
8411                EventFilter::default(),
8412                PageRequest {
8413                    limit: 10,
8414                    offset: 0,
8415                },
8416            )
8417            .await
8418            .unwrap();
8419        assert_eq!(page.items.len(), 1);
8420        assert_eq!(page.items[0].outcome, EventOutcome::Denied);
8421        assert_eq!(
8422            page.items[0].payload["resource"],
8423            serde_json::json!({"work_class": "interactive"})
8424        );
8425    }
8426
8427    #[tokio::test]
8428    async fn resource_cost_unit_present_on_link_singleton_success() {
8429        let store = Arc::new(MemoryEventStore::default());
8430        let edge_id = uuid::Uuid::new_v4();
8431        let source_id = uuid::Uuid::new_v4();
8432        let target_id = uuid::Uuid::new_v4();
8433        let edge_json = serde_json::json!({
8434            "id": edge_id,
8435            "namespace": "local",
8436            "source_id": source_id,
8437            "target_id": target_id,
8438            "relation": "depends_on",
8439            "weight": 1.0,
8440        });
8441        let mut builder = VerbRegistryBuilder::new();
8442        builder.register(LinkResultPack::ok(edge_json));
8443        builder.with_event_store(store.clone());
8444        let reg = builder.build().expect("registry builds");
8445
8446        reg.dispatch(
8447            "link",
8448            serde_json::json!({
8449                "source_id": source_id,
8450                "target_id": target_id,
8451                "relation": "depends_on",
8452            }),
8453        )
8454        .await
8455        .unwrap();
8456
8457        let page = store
8458            .query_events(
8459                EventFilter::default(),
8460                PageRequest {
8461                    limit: 10,
8462                    offset: 0,
8463                },
8464            )
8465            .await
8466            .unwrap();
8467        assert_eq!(
8468            page.items[0].payload["resource"],
8469            serde_json::json!({"work_class": "interactive", "cost_unit": 1}),
8470            "link has no embedding-bearing path -> base_weight(link) alone, even on the v2-enriched singleton path"
8471        );
8472    }
8473
8474    #[tokio::test]
8475    async fn resource_work_class_present_cost_unit_absent_on_link_dispatch_failure() {
8476        let store = Arc::new(MemoryEventStore::default());
8477        let mut builder = VerbRegistryBuilder::new();
8478        builder.register(LinkResultPack::err("target endpoint not found"));
8479        builder.with_event_store(store.clone());
8480        let reg = builder.build().expect("registry builds");
8481
8482        let _ = reg
8483            .dispatch(
8484                "link",
8485                serde_json::json!({
8486                    "source_id": "note:alpha",
8487                    "target_id": "note:missing",
8488                    "relation": "depends_on",
8489                }),
8490            )
8491            .await;
8492
8493        let page = store
8494            .query_events(
8495                EventFilter::default(),
8496                PageRequest {
8497                    limit: 10,
8498                    offset: 0,
8499                },
8500            )
8501            .await
8502            .unwrap();
8503        assert_eq!(page.items.len(), 1);
8504        assert_eq!(
8505            page.items[0].payload["resource"],
8506            serde_json::json!({"work_class": "interactive"})
8507        );
8508    }
8509
8510    // Registry audit event must carry target_id when dispatch params include it.
8511    #[tokio::test]
8512    async fn audit_event_threads_target_id_from_dispatch_args() {
8513        let store = Arc::new(MemoryEventStore::default());
8514        let target = uuid::Uuid::new_v4();
8515        let mut builder = VerbRegistryBuilder::new();
8516        builder.register(AlphaPack);
8517        builder.with_event_store(store.clone());
8518        builder.with_default_namespace("test-ns");
8519        let reg = builder.build().expect("registry builds");
8520
8521        reg.dispatch(
8522            "create",
8523            serde_json::json!({"namespace": "test-ns", "target_id": target}),
8524        )
8525        .await
8526        .unwrap();
8527
8528        let page = store
8529            .query_events(
8530                EventFilter::default(),
8531                PageRequest {
8532                    offset: 0,
8533                    limit: 10,
8534                },
8535            )
8536            .await
8537            .unwrap();
8538        assert_eq!(
8539            page.items[0].target_id,
8540            Some(target),
8541            "#282: audit event must carry target_id from dispatch params"
8542        );
8543    }
8544
8545    // ---- Link-verb audit enrichment ----
8546
8547    /// Test pack exposing a single `link` verb whose one-shot result is
8548    /// configured up front — lets tests drive both the success and failure
8549    /// legs of the deferred link-audit path without a real KG backend.
8550    struct LinkResultPack {
8551        result: std::sync::Mutex<Option<Result<Value, RuntimeError>>>,
8552    }
8553
8554    impl LinkResultPack {
8555        fn ok(value: Value) -> Self {
8556            Self {
8557                result: std::sync::Mutex::new(Some(Ok(value))),
8558            }
8559        }
8560        fn err(message: &str) -> Self {
8561            Self {
8562                result: std::sync::Mutex::new(Some(Err(RuntimeError::InvalidInput(
8563                    message.to_string(),
8564                )))),
8565            }
8566        }
8567    }
8568
8569    impl khive_types::Pack for LinkResultPack {
8570        const NAME: &'static str = "kg";
8571        const NOTE_KINDS: &'static [&'static str] = &[];
8572        const ENTITY_KINDS: &'static [&'static str] = &[];
8573        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
8574            name: "link",
8575            description: "test link handler",
8576            visibility: Visibility::Verb,
8577            category: VerbCategory::Commissive,
8578            params: &[],
8579        }];
8580    }
8581
8582    #[async_trait]
8583    impl PackRuntime for LinkResultPack {
8584        fn name(&self) -> &str {
8585            Self::NAME
8586        }
8587        fn note_kinds(&self) -> &'static [&'static str] {
8588            Self::NOTE_KINDS
8589        }
8590        fn entity_kinds(&self) -> &'static [&'static str] {
8591            Self::ENTITY_KINDS
8592        }
8593        fn handlers(&self) -> &'static [HandlerDef] {
8594            Self::HANDLERS
8595        }
8596        async fn dispatch(
8597            &self,
8598            _verb: &str,
8599            _params: Value,
8600            _registry: &VerbRegistry,
8601            _token: &NamespaceToken,
8602        ) -> Result<Value, RuntimeError> {
8603            self.result
8604                .lock()
8605                .unwrap()
8606                .take()
8607                .expect("LinkResultPack dispatch called more than once in a test")
8608        }
8609    }
8610
8611    #[tokio::test]
8612    async fn link_audit_enriches_successful_singleton_with_edge_v2() {
8613        let store = Arc::new(MemoryEventStore::default());
8614        let edge_id = uuid::Uuid::new_v4();
8615        let source_id = uuid::Uuid::new_v4();
8616        let target_id = uuid::Uuid::new_v4();
8617        let edge_json = serde_json::json!({
8618            "id": edge_id,
8619            "namespace": "local",
8620            "source_id": source_id,
8621            "target_id": target_id,
8622            "relation": "depends_on",
8623            "weight": 1.0,
8624        });
8625        let mut builder = VerbRegistryBuilder::new();
8626        builder.register(LinkResultPack::ok(edge_json));
8627        builder.with_event_store(store.clone());
8628        builder.with_default_namespace("test-ns");
8629        let reg = builder.build().expect("registry builds");
8630
8631        reg.dispatch(
8632            "link",
8633            serde_json::json!({
8634                "source_id": source_id,
8635                "target_id": target_id,
8636                "relation": "depends_on",
8637            }),
8638        )
8639        .await
8640        .unwrap();
8641
8642        let count = store.count_events(EventFilter::default()).await.unwrap();
8643        assert_eq!(
8644            count, 1,
8645            "exactly one deferred audit row must be persisted for a successful singleton link"
8646        );
8647        let page = store
8648            .query_events(
8649                EventFilter::default(),
8650                PageRequest {
8651                    limit: 10,
8652                    offset: 0,
8653                },
8654            )
8655            .await
8656            .unwrap();
8657        let ev = &page.items[0];
8658        assert_eq!(ev.verb, "link");
8659        assert_eq!(ev.outcome, EventOutcome::Success);
8660        assert_eq!(
8661            ev.payload_schema_version, 2,
8662            "successful singleton link uses audit schema v2"
8663        );
8664        assert_eq!(
8665            ev.target_id,
8666            Some(edge_id),
8667            "target_id must be the created/resolved edge id, not a raw caller arg"
8668        );
8669        assert_eq!(ev.payload["edge_id"], serde_json::json!(edge_id));
8670        assert_eq!(ev.payload["source_id"], serde_json::json!(source_id));
8671        assert_eq!(ev.payload["target_id"], serde_json::json!(target_id));
8672        assert_eq!(ev.payload["relation"], "depends_on");
8673        assert_eq!(ev.payload["weight"], 1.0);
8674        // v1 AuditEvent fields remain present via #[serde(flatten)].
8675        assert_eq!(ev.payload["verb"], "link");
8676        assert_eq!(ev.payload["decision"], "allow");
8677        assert!(ev.payload.get("gate_impl").is_some());
8678    }
8679
8680    #[tokio::test]
8681    async fn link_audit_falls_back_to_v1_when_dispatch_fails() {
8682        let store = Arc::new(MemoryEventStore::default());
8683        let mut builder = VerbRegistryBuilder::new();
8684        builder.register(LinkResultPack::err("target endpoint not found"));
8685        builder.with_event_store(store.clone());
8686        builder.with_default_namespace("test-ns");
8687        let reg = builder.build().expect("registry builds");
8688
8689        let err = reg
8690            .dispatch(
8691                "link",
8692                serde_json::json!({
8693                    "source_id": "note:alpha",
8694                    "target_id": "note:missing",
8695                    "relation": "depends_on",
8696                }),
8697            )
8698            .await
8699            .unwrap_err();
8700        assert!(
8701            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("not found")),
8702            "the original dispatch error must be returned unchanged"
8703        );
8704
8705        let page = store
8706            .query_events(
8707                EventFilter::default(),
8708                PageRequest {
8709                    limit: 10,
8710                    offset: 0,
8711                },
8712            )
8713            .await
8714            .unwrap();
8715        assert_eq!(
8716            page.items.len(),
8717            1,
8718            "a v1 fallback audit row must still be persisted on dispatch failure"
8719        );
8720        let ev = &page.items[0];
8721        assert_eq!(
8722            ev.payload_schema_version, 1,
8723            "failed link keeps the v1 audit shape"
8724        );
8725        // The persisted outcome must reflect the dispatch result (Err →
8726        // Error), not be hardcoded to Success from the gate's Allow decision.
8727        assert_eq!(
8728            ev.outcome,
8729            EventOutcome::Error,
8730            "outcome reflects the dispatch result (Err), not the gate decision (Allow)"
8731        );
8732        assert!(
8733            ev.duration_us >= 0,
8734            "duration_us must still be populated (measured, not the Event::new \
8735             default sentinel) on a failed dispatch"
8736        );
8737        assert!(
8738            ev.target_id.is_none(),
8739            "non-UUID caller-supplied ids do not spuriously populate target_id"
8740        );
8741        assert!(
8742            ev.payload.get("edge_id").is_none(),
8743            "v1 fallback must not carry edge enrichment fields"
8744        );
8745        let _: khive_gate::AuditEvent = serde_json::from_value(ev.payload.clone())
8746            .expect("v1 fallback payload must deserialize as AuditEvent");
8747    }
8748
8749    #[tokio::test]
8750    async fn link_audit_falls_back_to_v1_when_result_missing_edge_fields() {
8751        let store = Arc::new(MemoryEventStore::default());
8752        let target_arg = uuid::Uuid::new_v4();
8753        let mut builder = VerbRegistryBuilder::new();
8754        builder.register(LinkResultPack::ok(serde_json::json!({"ok": true})));
8755        builder.with_event_store(store.clone());
8756        builder.with_default_namespace("test-ns");
8757        let reg = builder.build().expect("registry builds");
8758
8759        reg.dispatch(
8760            "link",
8761            serde_json::json!({
8762                "source_id": uuid::Uuid::new_v4(),
8763                "target_id": target_arg,
8764                "relation": "depends_on",
8765            }),
8766        )
8767        .await
8768        .unwrap();
8769
8770        let page = store
8771            .query_events(
8772                EventFilter::default(),
8773                PageRequest {
8774                    limit: 10,
8775                    offset: 0,
8776                },
8777            )
8778            .await
8779            .unwrap();
8780        assert_eq!(page.items.len(), 1);
8781        let ev = &page.items[0];
8782        assert_eq!(
8783            ev.payload_schema_version, 1,
8784            "an unparsable success result falls back to v1 rather than dropping the audit row"
8785        );
8786        assert_eq!(ev.outcome, EventOutcome::Success);
8787        assert_eq!(
8788            ev.target_id,
8789            Some(target_arg),
8790            "v1 fallback still extracts target_id from the raw dispatch args"
8791        );
8792        assert!(ev.payload.get("edge_id").is_none());
8793    }
8794
8795    #[tokio::test]
8796    async fn link_audit_bulk_links_get_no_enrichment() {
8797        let store = Arc::new(MemoryEventStore::default());
8798        let mut builder = VerbRegistryBuilder::new();
8799        builder.register(LinkResultPack::ok(serde_json::json!({
8800            "attempted": 2, "created": 2, "skipped": 0, "failed": 0
8801        })));
8802        builder.with_event_store(store.clone());
8803        builder.with_default_namespace("test-ns");
8804        let reg = builder.build().expect("registry builds");
8805
8806        reg.dispatch(
8807            "link",
8808            serde_json::json!({
8809                "links": [
8810                    {"source_id": "a", "target_id": "b", "relation": "depends_on"},
8811                    {"source_id": "c", "target_id": "d", "relation": "depends_on"},
8812                ],
8813            }),
8814        )
8815        .await
8816        .unwrap();
8817
8818        let count = store.count_events(EventFilter::default()).await.unwrap();
8819        assert_eq!(
8820            count, 1,
8821            "bulk `links` gets exactly one v1 audit row (deferred until dispatch \
8822             resolves like every other Allow-outcome row since ADR-103 Stage 1, \
8823             but never v2-enriched — enrichment is singleton-`link`-only)"
8824        );
8825        let page = store
8826            .query_events(
8827                EventFilter::default(),
8828                PageRequest {
8829                    limit: 10,
8830                    offset: 0,
8831                },
8832            )
8833            .await
8834            .unwrap();
8835        let ev = &page.items[0];
8836        assert_eq!(
8837            ev.payload_schema_version, 1,
8838            "bulk link mode is out of scope for #676's events.target_id enrichment"
8839        );
8840        assert!(ev.target_id.is_none());
8841    }
8842
8843    #[test]
8844    fn link_audit_success_from_result_extracts_edge_fields() {
8845        let gate_req = GateRequest::new(
8846            ActorRef::anonymous(),
8847            Namespace::local(),
8848            "link",
8849            serde_json::json!({}),
8850        );
8851        let decision = GateDecision::Allow {
8852            obligations: vec![],
8853        };
8854        let audit = AuditEvent::from_check(&gate_req, &decision, "AllowAllGate");
8855
8856        let edge_id = uuid::Uuid::new_v4();
8857        let source_id = uuid::Uuid::new_v4();
8858        let target_id = uuid::Uuid::new_v4();
8859        let result = serde_json::json!({
8860            "id": edge_id,
8861            "source_id": source_id,
8862            "target_id": target_id,
8863            "relation": "depends_on",
8864            "weight": 0.5,
8865        });
8866
8867        let (returned_id, payload) = link_audit_success_from_result(audit, &result)
8868            .expect("well-formed edge JSON must produce an enriched payload");
8869        assert_eq!(returned_id, edge_id);
8870        assert_eq!(payload["edge_id"], serde_json::json!(edge_id));
8871        assert_eq!(payload["relation"], "depends_on");
8872        assert_eq!(payload["weight"], 0.5);
8873        assert_eq!(
8874            payload["verb"], "link",
8875            "v1 AuditEvent fields must flatten into the v2 payload"
8876        );
8877    }
8878
8879    #[test]
8880    fn link_audit_success_from_result_rejects_incomplete_or_malformed_result() {
8881        let gate_req = GateRequest::new(
8882            ActorRef::anonymous(),
8883            Namespace::local(),
8884            "link",
8885            serde_json::json!({}),
8886        );
8887        let decision = GateDecision::Allow {
8888            obligations: vec![],
8889        };
8890        let audit = AuditEvent::from_check(&gate_req, &decision, "AllowAllGate");
8891
8892        assert!(
8893            link_audit_success_from_result(
8894                audit.clone(),
8895                &serde_json::json!({"id": uuid::Uuid::new_v4()}),
8896            )
8897            .is_none(),
8898            "missing source_id/target_id/relation/weight must not enrich"
8899        );
8900        assert!(
8901            link_audit_success_from_result(audit, &serde_json::json!({"id": "not-a-uuid"}))
8902                .is_none(),
8903            "a non-UUID id must not enrich"
8904        );
8905    }
8906
8907    // ---- khive#948: request_id survives to the persisted audit event ----
8908    //
8909    // The pure `resource_payload`/`base_resource_payload` helpers are unit
8910    // tested in `cost_unit.rs`; these tests prove the id actually reaches
8911    // `resource.request_id` on a persisted `Event` through every one of
8912    // `dispatch_with_identity`'s four audit-append sites (denied, ordinary
8913    // success/error, singleton-link v2 success and its v1 fallback, and the
8914    // unknown-verb error path), plus the "no id supplied" omission case.
8915
8916    async fn first_event(store: &Arc<MemoryEventStore>) -> Event {
8917        let page = store
8918            .query_events(
8919                EventFilter::default(),
8920                PageRequest {
8921                    limit: 10,
8922                    offset: 0,
8923                },
8924            )
8925            .await
8926            .unwrap();
8927        assert_eq!(
8928            page.items.len(),
8929            1,
8930            "expected exactly one persisted audit event"
8931        );
8932        page.items[0].clone()
8933    }
8934
8935    #[tokio::test]
8936    async fn dispatch_with_identity_stamps_request_id_on_success() {
8937        let store = Arc::new(MemoryEventStore::default());
8938        let mut builder = VerbRegistryBuilder::new();
8939        builder.register(AlphaPack);
8940        builder.with_event_store(store.clone());
8941        let reg = builder.build().expect("registry builds");
8942
8943        reg.dispatch_with_identity(
8944            "list",
8945            serde_json::json!({"namespace": "test-ns"}),
8946            Some(RequestIdentity {
8947                request_id: Some(101),
8948                ..Default::default()
8949            }),
8950        )
8951        .await
8952        .unwrap();
8953
8954        let ev = first_event(&store).await;
8955        assert_eq!(ev.outcome, EventOutcome::Success);
8956        assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(101));
8957    }
8958
8959    #[tokio::test]
8960    async fn dispatch_with_identity_stamps_request_id_on_dispatch_error() {
8961        let store = Arc::new(MemoryEventStore::default());
8962        let mut builder = VerbRegistryBuilder::new();
8963        builder.register(FailingProbePack);
8964        builder.with_event_store(store.clone());
8965        let reg = builder.build().expect("registry builds");
8966
8967        let err = reg
8968            .dispatch_with_identity(
8969                "probe",
8970                serde_json::json!({"namespace": "test-ns"}),
8971                Some(RequestIdentity {
8972                    request_id: Some(102),
8973                    ..Default::default()
8974                }),
8975            )
8976            .await
8977            .unwrap_err();
8978        assert!(matches!(err, RuntimeError::InvalidInput(_)));
8979
8980        let ev = first_event(&store).await;
8981        assert_eq!(ev.outcome, EventOutcome::Error);
8982        assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(102));
8983    }
8984
8985    #[tokio::test]
8986    async fn dispatch_with_identity_stamps_request_id_on_denied() {
8987        #[derive(Debug)]
8988        struct AlwaysDenyGate;
8989        impl Gate for AlwaysDenyGate {
8990            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
8991                Ok(GateDecision::deny("denied by test"))
8992            }
8993        }
8994
8995        let store = Arc::new(MemoryEventStore::default());
8996        let mut builder = VerbRegistryBuilder::new();
8997        builder.register(AlphaPack);
8998        builder.with_gate(Arc::new(AlwaysDenyGate));
8999        builder.with_event_store(store.clone());
9000        let reg = builder.build().expect("registry builds");
9001
9002        let err = reg
9003            .dispatch_with_identity(
9004                "list",
9005                serde_json::json!({"namespace": "test-ns"}),
9006                Some(RequestIdentity {
9007                    request_id: Some(103),
9008                    ..Default::default()
9009                }),
9010            )
9011            .await
9012            .unwrap_err();
9013        assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
9014
9015        let ev = first_event(&store).await;
9016        assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(103));
9017    }
9018
9019    #[tokio::test]
9020    async fn dispatch_with_identity_stamps_request_id_on_link_v2_success() {
9021        let store = Arc::new(MemoryEventStore::default());
9022        let edge_id = uuid::Uuid::new_v4();
9023        let source_id = uuid::Uuid::new_v4();
9024        let target_id = uuid::Uuid::new_v4();
9025        let edge_json = serde_json::json!({
9026            "id": edge_id,
9027            "namespace": "local",
9028            "source_id": source_id,
9029            "target_id": target_id,
9030            "relation": "depends_on",
9031            "weight": 1.0,
9032        });
9033        let mut builder = VerbRegistryBuilder::new();
9034        builder.register(LinkResultPack::ok(edge_json));
9035        builder.with_event_store(store.clone());
9036        builder.with_default_namespace("test-ns");
9037        let reg = builder.build().expect("registry builds");
9038
9039        reg.dispatch_with_identity(
9040            "link",
9041            serde_json::json!({
9042                "source_id": source_id,
9043                "target_id": target_id,
9044                "relation": "depends_on",
9045            }),
9046            Some(RequestIdentity {
9047                namespace: "test-ns".to_string(),
9048                request_id: Some(104),
9049                ..Default::default()
9050            }),
9051        )
9052        .await
9053        .unwrap();
9054
9055        let ev = first_event(&store).await;
9056        assert_eq!(
9057            ev.payload_schema_version, 2,
9058            "successful singleton link uses audit schema v2"
9059        );
9060        assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(104));
9061    }
9062
9063    #[tokio::test]
9064    async fn dispatch_with_identity_stamps_request_id_on_link_v1_fallback() {
9065        let store = Arc::new(MemoryEventStore::default());
9066        let mut builder = VerbRegistryBuilder::new();
9067        builder.register(LinkResultPack::err("target endpoint not found"));
9068        builder.with_event_store(store.clone());
9069        builder.with_default_namespace("test-ns");
9070        let reg = builder.build().expect("registry builds");
9071
9072        let err = reg
9073            .dispatch_with_identity(
9074                "link",
9075                serde_json::json!({
9076                    "source_id": "note:alpha",
9077                    "target_id": "note:missing",
9078                    "relation": "depends_on",
9079                }),
9080                Some(RequestIdentity {
9081                    namespace: "test-ns".to_string(),
9082                    request_id: Some(105),
9083                    ..Default::default()
9084                }),
9085            )
9086            .await
9087            .unwrap_err();
9088        assert!(matches!(err, RuntimeError::InvalidInput(_)));
9089
9090        let ev = first_event(&store).await;
9091        assert_eq!(
9092            ev.payload_schema_version, 1,
9093            "failed link keeps the v1 audit shape"
9094        );
9095        assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(105));
9096    }
9097
9098    #[tokio::test]
9099    async fn dispatch_with_identity_stamps_request_id_on_unknown_verb() {
9100        let store = Arc::new(MemoryEventStore::default());
9101        let mut builder = VerbRegistryBuilder::new();
9102        builder.register(AlphaPack);
9103        builder.with_event_store(store.clone());
9104        let reg = builder.build().expect("registry builds");
9105
9106        let err = reg
9107            .dispatch_with_identity(
9108                "no_such_verb",
9109                serde_json::json!({}),
9110                Some(RequestIdentity {
9111                    namespace: Namespace::local().as_str().to_string(),
9112                    request_id: Some(106),
9113                    ..Default::default()
9114                }),
9115            )
9116            .await
9117            .unwrap_err();
9118        assert!(matches!(err, RuntimeError::UnknownVerb(_)));
9119
9120        let ev = first_event(&store).await;
9121        assert_eq!(ev.outcome, EventOutcome::Error);
9122        assert_eq!(ev.payload["resource"]["request_id"], serde_json::json!(106));
9123    }
9124
9125    #[tokio::test]
9126    async fn dispatch_with_identity_omits_request_id_key_when_absent() {
9127        let store = Arc::new(MemoryEventStore::default());
9128        let mut builder = VerbRegistryBuilder::new();
9129        builder.register(AlphaPack);
9130        builder.with_event_store(store.clone());
9131        let reg = builder.build().expect("registry builds");
9132
9133        // No identity at all — the pre-#948 call shape.
9134        reg.dispatch("list", serde_json::json!({"namespace": "test-ns"}))
9135            .await
9136            .unwrap();
9137
9138        let ev = first_event(&store).await;
9139        let resource = ev.payload["resource"]
9140            .as_object()
9141            .expect("resource must be an object");
9142        assert!(
9143            !resource.contains_key("request_id"),
9144            "request_id key must be entirely absent when no id is supplied, \
9145             not present as null or 0: got {resource:?}"
9146        );
9147    }
9148}
9149
9150// ---- Inter-pack dependency checking ----
9151
9152#[cfg(test)]
9153mod dep_tests {
9154    use super::*;
9155    use async_trait::async_trait;
9156    use khive_types::Pack;
9157    use serde_json::Value;
9158
9159    struct KgDepPack;
9160    struct MemoryDepPack;
9161    struct ADepPack;
9162    struct BDepPack;
9163
9164    impl Pack for KgDepPack {
9165        const NAME: &'static str = "kg_dep";
9166        const NOTE_KINDS: &'static [&'static str] = &["observation"];
9167        const ENTITY_KINDS: &'static [&'static str] = &["concept"];
9168        const HANDLERS: &'static [HandlerDef] = &[];
9169    }
9170
9171    impl Pack for MemoryDepPack {
9172        const NAME: &'static str = "memory_dep";
9173        const NOTE_KINDS: &'static [&'static str] = &["memory"];
9174        const ENTITY_KINDS: &'static [&'static str] = &[];
9175        const HANDLERS: &'static [HandlerDef] = &[];
9176        const REQUIRES: &'static [&'static str] = &["kg_dep"];
9177    }
9178
9179    impl Pack for ADepPack {
9180        const NAME: &'static str = "pack_a";
9181        const NOTE_KINDS: &'static [&'static str] = &[];
9182        const ENTITY_KINDS: &'static [&'static str] = &[];
9183        const HANDLERS: &'static [HandlerDef] = &[];
9184        const REQUIRES: &'static [&'static str] = &["pack_b"];
9185    }
9186
9187    impl Pack for BDepPack {
9188        const NAME: &'static str = "pack_b";
9189        const NOTE_KINDS: &'static [&'static str] = &[];
9190        const ENTITY_KINDS: &'static [&'static str] = &[];
9191        const HANDLERS: &'static [HandlerDef] = &[];
9192        const REQUIRES: &'static [&'static str] = &["pack_a"];
9193    }
9194
9195    #[async_trait]
9196    impl PackRuntime for KgDepPack {
9197        fn name(&self) -> &str {
9198            Self::NAME
9199        }
9200        fn note_kinds(&self) -> &'static [&'static str] {
9201            Self::NOTE_KINDS
9202        }
9203        fn entity_kinds(&self) -> &'static [&'static str] {
9204            Self::ENTITY_KINDS
9205        }
9206        fn handlers(&self) -> &'static [HandlerDef] {
9207            Self::HANDLERS
9208        }
9209        async fn dispatch(
9210            &self,
9211            verb: &str,
9212            _: Value,
9213            _: &VerbRegistry,
9214            _: &NamespaceToken,
9215        ) -> Result<Value, RuntimeError> {
9216            Err(RuntimeError::InvalidInput(format!(
9217                "KgDepPack has no verbs: {verb}"
9218            )))
9219        }
9220    }
9221
9222    #[async_trait]
9223    impl PackRuntime for MemoryDepPack {
9224        fn name(&self) -> &str {
9225            Self::NAME
9226        }
9227        fn note_kinds(&self) -> &'static [&'static str] {
9228            Self::NOTE_KINDS
9229        }
9230        fn entity_kinds(&self) -> &'static [&'static str] {
9231            Self::ENTITY_KINDS
9232        }
9233        fn handlers(&self) -> &'static [HandlerDef] {
9234            Self::HANDLERS
9235        }
9236        fn requires(&self) -> &'static [&'static str] {
9237            Self::REQUIRES
9238        }
9239        async fn dispatch(
9240            &self,
9241            verb: &str,
9242            _: Value,
9243            _: &VerbRegistry,
9244            _: &NamespaceToken,
9245        ) -> Result<Value, RuntimeError> {
9246            Err(RuntimeError::InvalidInput(format!(
9247                "MemoryDepPack has no verbs: {verb}"
9248            )))
9249        }
9250    }
9251
9252    #[async_trait]
9253    impl PackRuntime for ADepPack {
9254        fn name(&self) -> &str {
9255            Self::NAME
9256        }
9257        fn note_kinds(&self) -> &'static [&'static str] {
9258            Self::NOTE_KINDS
9259        }
9260        fn entity_kinds(&self) -> &'static [&'static str] {
9261            Self::ENTITY_KINDS
9262        }
9263        fn handlers(&self) -> &'static [HandlerDef] {
9264            Self::HANDLERS
9265        }
9266        fn requires(&self) -> &'static [&'static str] {
9267            Self::REQUIRES
9268        }
9269        async fn dispatch(
9270            &self,
9271            verb: &str,
9272            _: Value,
9273            _: &VerbRegistry,
9274            _: &NamespaceToken,
9275        ) -> Result<Value, RuntimeError> {
9276            Err(RuntimeError::InvalidInput(format!(
9277                "ADepPack has no verbs: {verb}"
9278            )))
9279        }
9280    }
9281
9282    #[async_trait]
9283    impl PackRuntime for BDepPack {
9284        fn name(&self) -> &str {
9285            Self::NAME
9286        }
9287        fn note_kinds(&self) -> &'static [&'static str] {
9288            Self::NOTE_KINDS
9289        }
9290        fn entity_kinds(&self) -> &'static [&'static str] {
9291            Self::ENTITY_KINDS
9292        }
9293        fn handlers(&self) -> &'static [HandlerDef] {
9294            Self::HANDLERS
9295        }
9296        fn requires(&self) -> &'static [&'static str] {
9297            Self::REQUIRES
9298        }
9299        async fn dispatch(
9300            &self,
9301            verb: &str,
9302            _: Value,
9303            _: &VerbRegistry,
9304            _: &NamespaceToken,
9305        ) -> Result<Value, RuntimeError> {
9306            Err(RuntimeError::InvalidInput(format!(
9307                "BDepPack has no verbs: {verb}"
9308            )))
9309        }
9310    }
9311
9312    #[test]
9313    fn test_pack_deps_happy_path() {
9314        let mut builder = VerbRegistryBuilder::new();
9315        builder.register(MemoryDepPack);
9316        builder.register(KgDepPack);
9317        let reg = builder
9318            .build()
9319            .expect("kg_dep satisfies memory_dep dependency");
9320        assert_eq!(reg.pack_requires("memory_dep").unwrap(), &["kg_dep"]);
9321        let names = reg.pack_names();
9322        let kg_pos = names.iter().position(|&n| n == "kg_dep").unwrap();
9323        let mem_pos = names.iter().position(|&n| n == "memory_dep").unwrap();
9324        assert!(
9325            kg_pos < mem_pos,
9326            "kg_dep must be loaded before memory_dep; order: {names:?}"
9327        );
9328    }
9329
9330    #[test]
9331    fn test_pack_deps_missing() {
9332        let mut builder = VerbRegistryBuilder::new();
9333        builder.register(MemoryDepPack);
9334        let err = match builder.build() {
9335            Ok(_) => panic!("expected Err, got Ok"),
9336            Err(e) => e,
9337        };
9338        assert!(
9339            matches!(err, RuntimeError::MissingPackDependency(_)),
9340            "expected MissingPackDependency, got {err:?}"
9341        );
9342        let msg = err.to_string();
9343        assert!(
9344            msg.contains("memory_dep"),
9345            "error must name the dependent pack: {msg}"
9346        );
9347        assert!(
9348            msg.contains("kg_dep"),
9349            "error must name the missing dep: {msg}"
9350        );
9351    }
9352
9353    #[test]
9354    fn test_pack_deps_circular() {
9355        let mut builder = VerbRegistryBuilder::new();
9356        builder.register(ADepPack);
9357        builder.register(BDepPack);
9358        let err = match builder.build() {
9359            Ok(_) => panic!("expected Err, got Ok"),
9360            Err(e) => e,
9361        };
9362        assert!(
9363            matches!(err, RuntimeError::CircularPackDependency(_)),
9364            "expected CircularPackDependency, got {err:?}"
9365        );
9366        let msg = err.to_string();
9367        assert!(msg.contains("pack_a"), "error must name pack_a: {msg}");
9368        assert!(msg.contains("pack_b"), "error must name pack_b: {msg}");
9369    }
9370
9371    #[test]
9372    fn test_pack_deps_no_deps() {
9373        struct NoDepsA;
9374        struct NoDepsB;
9375
9376        impl Pack for NoDepsA {
9377            const NAME: &'static str = "no_deps_a";
9378            const NOTE_KINDS: &'static [&'static str] = &[];
9379            const ENTITY_KINDS: &'static [&'static str] = &[];
9380            const HANDLERS: &'static [HandlerDef] = &[];
9381        }
9382
9383        impl Pack for NoDepsB {
9384            const NAME: &'static str = "no_deps_b";
9385            const NOTE_KINDS: &'static [&'static str] = &[];
9386            const ENTITY_KINDS: &'static [&'static str] = &[];
9387            const HANDLERS: &'static [HandlerDef] = &[];
9388        }
9389
9390        #[async_trait]
9391        impl PackRuntime for NoDepsA {
9392            fn name(&self) -> &str {
9393                Self::NAME
9394            }
9395            fn note_kinds(&self) -> &'static [&'static str] {
9396                Self::NOTE_KINDS
9397            }
9398            fn entity_kinds(&self) -> &'static [&'static str] {
9399                Self::ENTITY_KINDS
9400            }
9401            fn handlers(&self) -> &'static [HandlerDef] {
9402                Self::HANDLERS
9403            }
9404            async fn dispatch(
9405                &self,
9406                verb: &str,
9407                _: Value,
9408                _: &VerbRegistry,
9409                _: &NamespaceToken,
9410            ) -> Result<Value, RuntimeError> {
9411                Err(RuntimeError::InvalidInput(format!("NoDepsA: {verb}")))
9412            }
9413        }
9414
9415        #[async_trait]
9416        impl PackRuntime for NoDepsB {
9417            fn name(&self) -> &str {
9418                Self::NAME
9419            }
9420            fn note_kinds(&self) -> &'static [&'static str] {
9421                Self::NOTE_KINDS
9422            }
9423            fn entity_kinds(&self) -> &'static [&'static str] {
9424                Self::ENTITY_KINDS
9425            }
9426            fn handlers(&self) -> &'static [HandlerDef] {
9427                Self::HANDLERS
9428            }
9429            async fn dispatch(
9430                &self,
9431                verb: &str,
9432                _: Value,
9433                _: &VerbRegistry,
9434                _: &NamespaceToken,
9435            ) -> Result<Value, RuntimeError> {
9436                Err(RuntimeError::InvalidInput(format!("NoDepsB: {verb}")))
9437            }
9438        }
9439
9440        let mut builder = VerbRegistryBuilder::new();
9441        builder.register(NoDepsA);
9442        builder.register(NoDepsB);
9443        let reg = builder.build().expect("packs with REQUIRES=&[] build");
9444        assert_eq!(reg.pack_requires("no_deps_a").unwrap(), &[] as &[&str]);
9445        assert_eq!(reg.pack_requires("no_deps_b").unwrap(), &[] as &[&str]);
9446    }
9447}
9448
9449// ── Dispatch hook tests ─────────────────────────────────────────
9450
9451#[cfg(test)]
9452mod hook_tests {
9453    use super::*;
9454    use async_trait::async_trait;
9455    use khive_types::Pack;
9456    use std::sync::atomic::{AtomicUsize, Ordering};
9457    use std::sync::Mutex as StdMutex;
9458
9459    struct SimplePack;
9460
9461    impl Pack for SimplePack {
9462        const NAME: &'static str = "simple";
9463        const NOTE_KINDS: &'static [&'static str] = &[];
9464        const ENTITY_KINDS: &'static [&'static str] = &[];
9465        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
9466            name: "ping",
9467            description: "ping",
9468            visibility: Visibility::Verb,
9469            category: VerbCategory::Assertive,
9470            params: &[],
9471        }];
9472    }
9473
9474    #[async_trait]
9475    impl PackRuntime for SimplePack {
9476        fn name(&self) -> &str {
9477            SimplePack::NAME
9478        }
9479        fn note_kinds(&self) -> &'static [&'static str] {
9480            SimplePack::NOTE_KINDS
9481        }
9482        fn entity_kinds(&self) -> &'static [&'static str] {
9483            SimplePack::ENTITY_KINDS
9484        }
9485        fn handlers(&self) -> &'static [HandlerDef] {
9486            SimplePack::HANDLERS
9487        }
9488        async fn dispatch(
9489            &self,
9490            verb: &str,
9491            _params: Value,
9492            _registry: &VerbRegistry,
9493            _token: &NamespaceToken,
9494        ) -> Result<Value, RuntimeError> {
9495            Ok(serde_json::json!({ "verb": verb }))
9496        }
9497    }
9498
9499    struct RecallPack;
9500
9501    impl Pack for RecallPack {
9502        const NAME: &'static str = "memory";
9503        const NOTE_KINDS: &'static [&'static str] = &[];
9504        const ENTITY_KINDS: &'static [&'static str] = &[];
9505        const HANDLERS: &'static [HandlerDef] = &[HandlerDef {
9506            name: "memory.recall",
9507            description: "test recall",
9508            visibility: Visibility::Verb,
9509            category: VerbCategory::Assertive,
9510            params: &[],
9511        }];
9512    }
9513
9514    #[async_trait]
9515    impl PackRuntime for RecallPack {
9516        fn name(&self) -> &str {
9517            RecallPack::NAME
9518        }
9519        fn note_kinds(&self) -> &'static [&'static str] {
9520            RecallPack::NOTE_KINDS
9521        }
9522        fn entity_kinds(&self) -> &'static [&'static str] {
9523            RecallPack::ENTITY_KINDS
9524        }
9525        fn handlers(&self) -> &'static [HandlerDef] {
9526            RecallPack::HANDLERS
9527        }
9528        async fn dispatch(
9529            &self,
9530            _verb: &str,
9531            params: Value,
9532            _registry: &VerbRegistry,
9533            _token: &NamespaceToken,
9534        ) -> Result<Value, RuntimeError> {
9535            let hit = serde_json::json!({
9536                "id": uuid::Uuid::new_v4().to_string(),
9537                "served_by_profile_id": "custom-recall-v1",
9538                "serve_attribution": "profile",
9539            });
9540            if params.get("verbose").and_then(Value::as_bool) == Some(true) {
9541                Ok(serde_json::json!({"results": [hit]}))
9542            } else {
9543                Ok(serde_json::json!([hit]))
9544            }
9545        }
9546    }
9547
9548    #[derive(Default)]
9549    struct EventCapturingHook {
9550        event: StdMutex<Option<Event>>,
9551    }
9552
9553    #[async_trait]
9554    impl DispatchHook for EventCapturingHook {
9555        async fn on_dispatch(&self, view: &EventView) {
9556            *self.event.lock().unwrap() = Some(view.event.clone());
9557        }
9558    }
9559
9560    /// Hook that counts calls and records the last verb seen.
9561    #[derive(Default)]
9562    struct CountingHook {
9563        calls: AtomicUsize,
9564        last_verb: StdMutex<String>,
9565    }
9566
9567    #[async_trait]
9568    impl DispatchHook for CountingHook {
9569        async fn on_dispatch(&self, view: &EventView) {
9570            self.calls.fetch_add(1, Ordering::SeqCst);
9571            *self.last_verb.lock().unwrap() = view.event.verb.clone();
9572        }
9573    }
9574
9575    #[tokio::test]
9576    async fn dispatch_hook_fires_on_successful_dispatch() {
9577        let hook = Arc::new(CountingHook::default());
9578        let mut builder = VerbRegistryBuilder::new();
9579        builder.register(SimplePack);
9580        builder.with_dispatch_hook(hook.clone());
9581        let reg = builder.build().expect("registry builds");
9582
9583        reg.dispatch("ping", Value::Null).await.unwrap();
9584
9585        assert_eq!(
9586            hook.calls.load(Ordering::SeqCst),
9587            1,
9588            "hook must fire once per successful dispatch"
9589        );
9590        assert_eq!(
9591            hook.last_verb.lock().unwrap().as_str(),
9592            "ping",
9593            "hook event must carry the dispatched verb"
9594        );
9595    }
9596
9597    #[tokio::test]
9598    async fn dispatch_hook_fires_multiple_times() {
9599        let hook = Arc::new(CountingHook::default());
9600        let mut builder = VerbRegistryBuilder::new();
9601        builder.register(SimplePack);
9602        builder.with_dispatch_hook(hook.clone());
9603        let reg = builder.build().expect("registry builds");
9604
9605        reg.dispatch("ping", Value::Null).await.unwrap();
9606        reg.dispatch("ping", Value::Null).await.unwrap();
9607        reg.dispatch("ping", Value::Null).await.unwrap();
9608
9609        assert_eq!(
9610            hook.calls.load(Ordering::SeqCst),
9611            3,
9612            "hook must fire once per successful dispatch"
9613        );
9614    }
9615
9616    #[tokio::test]
9617    async fn recall_hook_copies_serve_attribution_from_bare_and_verbose_results() {
9618        let hook = Arc::new(EventCapturingHook::default());
9619        let mut builder = VerbRegistryBuilder::new();
9620        builder.register(RecallPack);
9621        builder.with_dispatch_hook(hook.clone());
9622        let reg = builder.build().expect("registry builds");
9623
9624        for params in [serde_json::json!({}), serde_json::json!({"verbose": true})] {
9625            reg.dispatch("memory.recall", params)
9626                .await
9627                .expect("recall dispatch");
9628            let event = hook.event.lock().unwrap().clone().expect("hook event");
9629            assert!(
9630                event.target_id.is_some(),
9631                "first recall id must become target"
9632            );
9633            assert_eq!(
9634                event.payload["served_by_profile_id"],
9635                serde_json::json!("custom-recall-v1")
9636            );
9637            assert_eq!(
9638                event.payload["serve_attribution"],
9639                serde_json::json!("profile")
9640            );
9641        }
9642    }
9643
9644    #[tokio::test]
9645    async fn dispatch_hook_does_not_fire_on_unknown_verb() {
9646        let hook = Arc::new(CountingHook::default());
9647        let mut builder = VerbRegistryBuilder::new();
9648        builder.register(SimplePack);
9649        builder.with_dispatch_hook(hook.clone());
9650        let reg = builder.build().expect("registry builds");
9651
9652        let _ = reg.dispatch("nonexistent", Value::Null).await;
9653
9654        assert_eq!(
9655            hook.calls.load(Ordering::SeqCst),
9656            0,
9657            "hook must NOT fire for unknown verb (dispatch returns error)"
9658        );
9659    }
9660
9661    #[tokio::test]
9662    async fn dispatch_hook_does_not_fire_on_gate_deny() {
9663        use khive_gate::{Gate, GateDecision, GateError};
9664
9665        #[derive(Debug)]
9666        struct AlwaysDenyGate;
9667        impl Gate for AlwaysDenyGate {
9668            fn check(&self, _req: &GateRequest) -> Result<GateDecision, GateError> {
9669                Ok(GateDecision::deny("test deny"))
9670            }
9671        }
9672
9673        let hook = Arc::new(CountingHook::default());
9674        let mut builder = VerbRegistryBuilder::new();
9675        builder.register(SimplePack);
9676        builder.with_gate(Arc::new(AlwaysDenyGate));
9677        builder.with_dispatch_hook(hook.clone());
9678        let reg = builder.build().expect("registry builds");
9679
9680        let err = reg.dispatch("ping", Value::Null).await.unwrap_err();
9681        assert!(matches!(err, RuntimeError::PermissionDenied { .. }));
9682
9683        assert_eq!(
9684            hook.calls.load(Ordering::SeqCst),
9685            0,
9686            "hook must NOT fire when gate denies dispatch"
9687        );
9688    }
9689
9690    #[tokio::test]
9691    async fn dispatch_hook_event_carries_namespace_from_params() {
9692        let hook = Arc::new(CountingHook::default());
9693
9694        #[derive(Default)]
9695        struct NsCapturingHook {
9696            ns: StdMutex<String>,
9697        }
9698
9699        #[async_trait]
9700        impl DispatchHook for NsCapturingHook {
9701            async fn on_dispatch(&self, view: &EventView) {
9702                *self.ns.lock().unwrap() = view.event.namespace.clone();
9703            }
9704        }
9705
9706        let ns_hook = Arc::new(NsCapturingHook::default());
9707        let mut builder = VerbRegistryBuilder::new();
9708        builder.register(SimplePack);
9709        builder.with_dispatch_hook(ns_hook.clone());
9710        let reg = builder.build().expect("registry builds");
9711
9712        reg.dispatch("ping", serde_json::json!({"namespace": "tenant-abc"}))
9713            .await
9714            .unwrap();
9715
9716        assert_eq!(
9717            ns_hook.ns.lock().unwrap().as_str(),
9718            "tenant-abc",
9719            "dispatch hook event must carry the resolved namespace"
9720        );
9721
9722        // Suppress unused-variable warning from the outer hook.
9723        drop(hook);
9724    }
9725
9726    #[tokio::test]
9727    async fn no_dispatch_hook_configured_dispatch_succeeds() {
9728        // Regression: registries without a hook must still work.
9729        let mut builder = VerbRegistryBuilder::new();
9730        builder.register(SimplePack);
9731        // No with_dispatch_hook call.
9732        let reg = builder.build().expect("registry builds");
9733
9734        let res = reg.dispatch("ping", Value::Null).await.unwrap();
9735        assert_eq!(res["verb"], "ping");
9736    }
9737}
9738
9739// ── help=true tests ──────────────────────────────────────────────
9740
9741#[cfg(test)]
9742mod help_tests {
9743    use super::*;
9744    use async_trait::async_trait;
9745    use khive_types::Pack;
9746    use std::sync::{
9747        atomic::{AtomicUsize, Ordering},
9748        Arc,
9749    };
9750
9751    // ── HelpPack: a minimal pack with one handler that records invocation count.
9752    //
9753    // Used to verify that help=true never reaches the pack's dispatch method.
9754
9755    static CREATE_PARAMS: [ParamDef; 2] = [
9756        ParamDef {
9757            name: "kind",
9758            param_type: "string",
9759            required: true,
9760            description: "Granular kind (concept | document | ...).",
9761        },
9762        ParamDef {
9763            name: "name",
9764            param_type: "string",
9765            required: false,
9766            description: "Human-readable name.",
9767        },
9768    ];
9769
9770    static RECALL_PARAMS: [ParamDef; 2] = [
9771        ParamDef {
9772            name: "query",
9773            param_type: "string",
9774            required: true,
9775            description: "Semantic recall query.",
9776        },
9777        ParamDef {
9778            name: "limit",
9779            param_type: "integer",
9780            required: false,
9781            description: "Maximum memories to return.",
9782        },
9783    ];
9784
9785    // A subhandler with no params — mirrors recall.embed / brain.emit / etc.
9786    // Used to test that help=true on a Subhandler returns callable_via_mcp: false.
9787    static EMBED_PARAMS: [ParamDef; 0] = [];
9788
9789    struct HelpPack {
9790        invocations: Arc<AtomicUsize>,
9791    }
9792
9793    impl Pack for HelpPack {
9794        const NAME: &'static str = "helptest";
9795        const NOTE_KINDS: &'static [&'static str] = &[];
9796        const ENTITY_KINDS: &'static [&'static str] = &[];
9797        const HANDLERS: &'static [HandlerDef] = &[
9798            HandlerDef {
9799                name: "create",
9800                description: "Create an entity or note",
9801                visibility: Visibility::Verb,
9802                category: VerbCategory::Commissive,
9803                params: &CREATE_PARAMS,
9804            },
9805            HandlerDef {
9806                name: "recall",
9807                description: "Recall memory notes with decay-aware hybrid ranking",
9808                visibility: Visibility::Verb,
9809                category: VerbCategory::Assertive,
9810                params: &RECALL_PARAMS,
9811            },
9812            // A Subhandler used to test that help=true returns
9813            // callable_via_mcp: false for internal verbs.
9814            HandlerDef {
9815                name: "recall.embed",
9816                description: "Return the embedding vector used by memory recall",
9817                visibility: Visibility::Subhandler,
9818                category: VerbCategory::Assertive,
9819                params: &EMBED_PARAMS,
9820            },
9821            HandlerDef {
9822                name: "link",
9823                description: "Create a typed directed edge",
9824                visibility: Visibility::Verb,
9825                category: VerbCategory::Commissive,
9826                params: &[],
9827            },
9828        ];
9829    }
9830
9831    // A pack-declared additive edge rule (mirrors the GTD pack's real
9832    // task-to-task `depends_on` rule), used to verify `link(help=true)`
9833    // surfaces pack-composed rules alongside the base entity table. The
9834    // second entry declares a rule for a special relation
9835    // (`supersedes`) that the validator's dedicated special-relation
9836    // branch never consults `pack_rule_allows` for — it must NOT be
9837    // advertised (see `test_link_help_true_matches_special_relation_validator_set`).
9838    static HELP_EDGE_RULES: [EdgeEndpointRule; 2] = [
9839        EdgeEndpointRule {
9840            relation: khive_types::EdgeRelation::DependsOn,
9841            source: EndpointKind::NoteOfKind("task"),
9842            target: EndpointKind::NoteOfKind("task"),
9843        },
9844        EdgeEndpointRule {
9845            relation: khive_types::EdgeRelation::Supersedes,
9846            source: EndpointKind::NoteOfKind("task"),
9847            target: EndpointKind::NoteOfKind("task"),
9848        },
9849    ];
9850
9851    #[async_trait]
9852    impl PackRuntime for HelpPack {
9853        fn name(&self) -> &str {
9854            HelpPack::NAME
9855        }
9856        fn note_kinds(&self) -> &'static [&'static str] {
9857            HelpPack::NOTE_KINDS
9858        }
9859        fn entity_kinds(&self) -> &'static [&'static str] {
9860            HelpPack::ENTITY_KINDS
9861        }
9862        fn handlers(&self) -> &'static [HandlerDef] {
9863            HelpPack::HANDLERS
9864        }
9865        fn edge_rules(&self) -> &'static [EdgeEndpointRule] {
9866            &HELP_EDGE_RULES
9867        }
9868        async fn dispatch(
9869            &self,
9870            verb: &str,
9871            _params: Value,
9872            _registry: &VerbRegistry,
9873            _token: &NamespaceToken,
9874        ) -> Result<Value, RuntimeError> {
9875            self.invocations.fetch_add(1, Ordering::SeqCst);
9876            Ok(serde_json::json!({ "pack": "helptest", "verb": verb }))
9877        }
9878    }
9879
9880    fn build_help_registry(invocations: Arc<AtomicUsize>) -> VerbRegistry {
9881        let mut builder = VerbRegistryBuilder::new();
9882        builder.register(HelpPack { invocations });
9883        builder.build().expect("help registry builds")
9884    }
9885
9886    /// help=true on `create` returns a schema envelope with the correct verb name,
9887    /// pack name, description, and at least the required `kind` parameter.
9888    #[tokio::test]
9889    async fn test_help_true_returns_schema_for_kg_create() {
9890        let invocations = Arc::new(AtomicUsize::new(0));
9891        let reg = build_help_registry(invocations.clone());
9892
9893        let result = reg
9894            .dispatch("create", serde_json::json!({ "help": true }))
9895            .await
9896            .expect("help=true must succeed for a known verb");
9897
9898        // Shape checks.
9899        assert_eq!(result["verb"], "create", "envelope must name the verb");
9900        assert_eq!(
9901            result["pack"], "helptest",
9902            "envelope must name the owning pack"
9903        );
9904        assert!(
9905            result["description"].as_str().is_some(),
9906            "description must be a string"
9907        );
9908
9909        // Params array must be present and non-empty.
9910        let params = result["params"]
9911            .as_array()
9912            .expect("params must be a JSON array");
9913        assert!(!params.is_empty(), "params array must not be empty");
9914
9915        // The required `kind` param must appear.
9916        let kind_param = params.iter().find(|p| p["name"] == "kind");
9917        assert!(
9918            kind_param.is_some(),
9919            "params array must include the 'kind' parameter"
9920        );
9921        let kind_param = kind_param.unwrap();
9922        assert_eq!(
9923            kind_param["required"],
9924            serde_json::json!(true),
9925            "'kind' must be required"
9926        );
9927        assert_eq!(kind_param["type"], "string", "'kind' type must be 'string'");
9928
9929        let identifier_help = result["identifier_resolution"]
9930            .as_object()
9931            .expect("help=true must include the shared identifier contract");
9932        assert!(identifier_help["full_uuid"]
9933            .as_str()
9934            .is_some_and(|text| text.contains("globally unique")));
9935        assert!(identifier_help["short_prefix"]
9936            .as_str()
9937            .is_some_and(|text| text.contains("lookup scope belongs to the consuming parameter")));
9938        assert!(identifier_help["parameter_rule"]
9939            .as_str()
9940            .is_some_and(|text| text.contains("submitted again")));
9941    }
9942
9943    /// help=true on `recall` returns a schema envelope including the `query` param.
9944    #[tokio::test]
9945    async fn test_help_true_returns_schema_for_recall() {
9946        let invocations = Arc::new(AtomicUsize::new(0));
9947        let reg = build_help_registry(invocations.clone());
9948
9949        let result = reg
9950            .dispatch("recall", serde_json::json!({ "help": true }))
9951            .await
9952            .expect("help=true must succeed for recall");
9953
9954        assert_eq!(result["verb"], "recall");
9955        assert_eq!(result["pack"], "helptest");
9956
9957        let params = result["params"]
9958            .as_array()
9959            .expect("params must be a JSON array");
9960
9961        // `query` must be present and required.
9962        let query_param = params.iter().find(|p| p["name"] == "query");
9963        assert!(query_param.is_some(), "params must include 'query'");
9964        let query_param = query_param.unwrap();
9965        assert_eq!(
9966            query_param["required"],
9967            serde_json::json!(true),
9968            "'query' must be required"
9969        );
9970
9971        // `limit` must be present and optional.
9972        let limit_param = params.iter().find(|p| p["name"] == "limit");
9973        assert!(limit_param.is_some(), "params must include 'limit'");
9974        let limit_param = limit_param.unwrap();
9975        assert_eq!(
9976            limit_param["required"],
9977            serde_json::json!(false),
9978            "'limit' must be optional"
9979        );
9980    }
9981
9982    /// `link(help=true)` (issue #964) surfaces the composed per-relation
9983    /// endpoint allowlist: the base entity-to-entity table, every loaded
9984    /// pack's additive `EDGE_RULES`, and the `annotates` note-to-any rule —
9985    /// so a batch caller can defer to the kernel's own table instead of
9986    /// re-implementing it.
9987    #[tokio::test]
9988    async fn test_link_help_true_exposes_endpoint_rules() {
9989        let invocations = Arc::new(AtomicUsize::new(0));
9990        let reg = build_help_registry(invocations.clone());
9991
9992        let result = reg
9993            .dispatch("link", serde_json::json!({ "help": true }))
9994            .await
9995            .expect("help=true must succeed for link");
9996
9997        assert_eq!(result["verb"], "link");
9998        let rules = result["endpoint_rules"]
9999            .as_array()
10000            .expect("link help must include an endpoint_rules array");
10001        assert!(!rules.is_empty(), "endpoint_rules must not be empty");
10002
10003        // A base entity-to-entity rule (khive-runtime's own table) must appear.
10004        assert!(
10005            rules.iter().any(|r| r["relation"] == "contains"
10006                && r["source"] == "entity:concept"
10007                && r["target"] == "entity:concept"),
10008            "endpoint_rules must include the base 'contains' entity rule; got {rules:#?}"
10009        );
10010
10011        // The pack-declared additive rule (HelpPack's task->task depends_on) must appear.
10012        assert!(
10013            rules.iter().any(|r| r["relation"] == "depends_on"
10014                && r["source"] == "note:task"
10015                && r["target"] == "note:task"),
10016            "endpoint_rules must include the pack-declared depends_on rule; got {rules:#?}"
10017        );
10018
10019        // The annotates note-to-any special case must appear.
10020        assert!(
10021            rules
10022                .iter()
10023                .any(|r| r["relation"] == "annotates" && r["source"] == "note:*"),
10024            "endpoint_rules must document the annotates note-to-any rule; got {rules:#?}"
10025        );
10026
10027        // help=true must remain side-effect-free.
10028        assert_eq!(
10029            invocations.load(Ordering::SeqCst),
10030            0,
10031            "link(help=true) must not invoke pack dispatch"
10032        );
10033    }
10034
10035    /// `link(help=true)`'s `endpoint_rules` must match, set-for-set, every
10036    /// endpoint pair `validate_edge_relation_endpoints`
10037    /// (`crates/khive-runtime/src/operations.rs`) actually accepts for the
10038    /// three special relations (`supersedes` / `supports` / `refutes`):
10039    ///
10040    /// - a `note -> note` row for each of the three relations (the
10041    ///   validator's dedicated special-relation branch accepts any
10042    ///   `Resolved::Note(_), Resolved::Note(_)` pair unconditionally,
10043    ///   `operations.rs:1338` / `:1527` — before `pack_rule_allows` is ever
10044    ///   reached);
10045    /// - the base entity->entity rows for the three relations
10046    ///   (`base_entity_endpoint_rules`, e.g. `concept -[supersedes]-> concept`);
10047    /// - and, critically, NOT a row for `HelpPack`'s pack-declared
10048    ///   `supersedes` rule on `note:task -> note:task`
10049    ///   (`HELP_EDGE_RULES[1]`) — because the validator's special-relation
10050    ///   branch returns before `pack_rule_allows` is consulted, that pack
10051    ///   rule is never actually enforced, so advertising it would be a false
10052    ///   promise (the exact defect this test guards against, issue #991).
10053    #[tokio::test]
10054    async fn test_link_help_true_matches_special_relation_validator_set() {
10055        let invocations = Arc::new(AtomicUsize::new(0));
10056        let reg = build_help_registry(invocations.clone());
10057
10058        let result = reg
10059            .dispatch("link", serde_json::json!({ "help": true }))
10060            .await
10061            .expect("help=true must succeed for link");
10062
10063        let rules = result["endpoint_rules"]
10064            .as_array()
10065            .expect("link help must include an endpoint_rules array");
10066
10067        for relation in ["supersedes", "supports", "refutes"] {
10068            // The unconditional note -> note row must appear.
10069            assert!(
10070                rules.iter().any(|r| r["relation"] == relation
10071                    && r["source"] == "note:*"
10072                    && r["target"] == "note:*"),
10073                "endpoint_rules must include the note:*->note:* row for '{relation}' \
10074                 (validator accepts any note->note pair unconditionally); got {rules:#?}"
10075            );
10076
10077            // HelpPack's pack-declared rule for this relation on note:task->note:task
10078            // (only Supersedes is declared in HELP_EDGE_RULES) must NOT be advertised
10079            // as a distinct entity — the validator never reaches pack_rule_allows for
10080            // special relations, so no note:task->note:task row should exist for it.
10081            assert!(
10082                !rules.iter().any(|r| r["relation"] == relation
10083                    && r["source"] == "note:task"
10084                    && r["target"] == "note:task"),
10085                "endpoint_rules must NOT advertise a pack EDGE_RULES row for special \
10086                 relation '{relation}' — validate_edge_relation_endpoints never consults \
10087                 pack_rule_allows for supersedes/supports/refutes; got {rules:#?}"
10088            );
10089        }
10090
10091        // Base entity->entity rows for the three relations (from
10092        // base_entity_endpoint_rules) must still appear alongside the note rows.
10093        for (relation, kind) in [
10094            ("supersedes", "concept"),
10095            ("supports", "concept"),
10096            ("refutes", "concept"),
10097        ] {
10098            assert!(
10099                rules.iter().any(|r| r["relation"] == relation
10100                    && r["source"] == format!("entity:{kind}")
10101                    && r["target"] == "entity:concept"),
10102                "endpoint_rules must include the base entity:{kind}->entity:concept row \
10103                 for '{relation}'; got {rules:#?}"
10104            );
10105        }
10106    }
10107
10108    #[test]
10109    fn special_relation_predicate_matches_the_dedicated_validator_set() {
10110        for relation in khive_types::EdgeRelation::ALL {
10111            assert_eq!(
10112                is_special_relation(relation),
10113                matches!(
10114                    relation,
10115                    khive_types::EdgeRelation::Supersedes
10116                        | khive_types::EdgeRelation::Supports
10117                        | khive_types::EdgeRelation::Refutes
10118                ),
10119                "unexpected special-relation classification for {relation}"
10120            );
10121        }
10122    }
10123
10124    /// help=true is intercepted before pack dispatch — the pack's dispatch method
10125    /// must never be invoked when help=true is in the params.
10126    #[tokio::test]
10127    async fn test_help_true_does_not_execute_the_verb() {
10128        let invocations = Arc::new(AtomicUsize::new(0));
10129        let reg = build_help_registry(invocations.clone());
10130
10131        // Call both verbs with help=true.
10132        reg.dispatch("create", serde_json::json!({ "help": true }))
10133            .await
10134            .expect("help=true must succeed");
10135        reg.dispatch("recall", serde_json::json!({ "help": true }))
10136            .await
10137            .expect("help=true must succeed");
10138
10139        assert_eq!(
10140            invocations.load(Ordering::SeqCst),
10141            0,
10142            "pack dispatch MUST NOT be invoked when help=true; \
10143             got {} invocation(s)",
10144            invocations.load(Ordering::SeqCst)
10145        );
10146
10147        // Confirm that a normal call (without help=true) DOES invoke dispatch.
10148        reg.dispatch("create", serde_json::json!({}))
10149            .await
10150            .expect("normal dispatch must succeed");
10151        assert_eq!(
10152            invocations.load(Ordering::SeqCst),
10153            1,
10154            "pack dispatch must fire exactly once for a normal call"
10155        );
10156    }
10157
10158    // ── Subhandler help-schema regressions ─────────────────────────────────
10159    //
10160    // Subhandler verbs must return `callable_via_mcp: false` in their help
10161    // schema so agents who read help=true before probing see accurate
10162    // availability — not a "looks callable" schema followed by permission denied.
10163
10164    /// help=true on a `Visibility::Subhandler` verb returns `callable_via_mcp: false`
10165    /// and `visibility: "internal"` rather than a plain callable-looking envelope.
10166    #[tokio::test]
10167    async fn help_true_on_subhandler_returns_callable_via_mcp_false() {
10168        let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
10169
10170        let result = reg
10171            .dispatch("recall.embed", serde_json::json!({ "help": true }))
10172            .await
10173            .expect("help=true on subhandler must succeed (no permission check on help path)");
10174
10175        assert_eq!(
10176            result["callable_via_mcp"],
10177            serde_json::json!(false),
10178            "subhandler help must carry callable_via_mcp: false"
10179        );
10180        assert_eq!(
10181            result["visibility"], "internal",
10182            "subhandler help must carry visibility: internal"
10183        );
10184        // The verb and pack fields must still be present so the caller knows
10185        // what the schema belongs to.
10186        assert_eq!(result["verb"], "recall.embed");
10187        assert_eq!(result["pack"], "helptest");
10188    }
10189
10190    /// Public Verb-visibility handlers must NOT have `callable_via_mcp: false`.
10191    #[tokio::test]
10192    async fn help_true_on_public_verb_does_not_have_callable_via_mcp_false() {
10193        let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
10194
10195        let result = reg
10196            .dispatch("create", serde_json::json!({ "help": true }))
10197            .await
10198            .expect("help=true on public verb must succeed");
10199
10200        // callable_via_mcp must be absent or true for public verbs.
10201        assert_ne!(
10202            result.get("callable_via_mcp"),
10203            Some(&serde_json::json!(false)),
10204            "public verb help must NOT carry callable_via_mcp: false"
10205        );
10206        // visibility must be absent or 'public' (never 'internal') for public verbs.
10207        assert_ne!(
10208            result.get("visibility"),
10209            Some(&serde_json::json!("internal")),
10210            "public verb help must NOT carry visibility: internal"
10211        );
10212    }
10213
10214    /// help=true on an unknown verb returns an error (same behavior as normal dispatch).
10215    #[tokio::test]
10216    async fn help_true_on_unknown_verb_returns_error() {
10217        let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
10218
10219        let err = reg
10220            .dispatch("nonexistent_verb", serde_json::json!({ "help": true }))
10221            .await
10222            .unwrap_err();
10223
10224        assert!(
10225            matches!(err, RuntimeError::UnknownVerb(_)),
10226            "help=true on unknown verb must return UnknownVerb, got {err:?}"
10227        );
10228        let msg = err.to_string();
10229        assert!(
10230            msg.contains("nonexistent_verb"),
10231            "error must name the unknown verb: {msg}"
10232        );
10233    }
10234
10235    /// Subhandler help must include params: [] even when the verb has no params.
10236    #[tokio::test]
10237    async fn help_true_on_subhandler_includes_params_field() {
10238        let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
10239
10240        let result = reg
10241            .dispatch("recall.embed", serde_json::json!({ "help": true }))
10242            .await
10243            .expect("help=true on subhandler must succeed");
10244
10245        // params must always be present (consistent shape).
10246        let params = result
10247            .get("params")
10248            .expect("subhandler help must include 'params' field");
10249        assert!(
10250            params.is_array(),
10251            "subhandler help params must be a JSON array"
10252        );
10253    }
10254
10255    // ── Unknown-verb error must not leak subhandler names ─────────
10256
10257    /// `describe_verb` on an unknown verb must list only Verb-visibility names
10258    /// in the "available" list: never subhandler names like `recall.embed`.
10259    #[tokio::test]
10260    async fn help_true_unknown_verb_available_list_excludes_subhandlers() {
10261        let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
10262
10263        let err = reg
10264            .dispatch("not_a_verb", serde_json::json!({ "help": true }))
10265            .await
10266            .unwrap_err();
10267
10268        let msg = err.to_string();
10269        // `recall.embed` is a Subhandler in HelpPack — must NOT appear in the
10270        // "available" list of an unknown-verb error.
10271        assert!(
10272            !msg.contains("recall.embed"),
10273            "unknown-verb help error must not advertise subhandler recall.embed: {msg}"
10274        );
10275        // Public verbs must still appear so the agent knows what to call.
10276        assert!(
10277            msg.contains("create"),
10278            "unknown-verb help error must still list public verb 'create': {msg}"
10279        );
10280        assert!(
10281            msg.contains("recall"),
10282            "unknown-verb help error must still list public verb 'recall': {msg}"
10283        );
10284    }
10285
10286    /// Normal dispatch on an unknown verb must also not leak subhandler names.
10287    #[tokio::test]
10288    async fn dispatch_unknown_verb_available_list_excludes_subhandlers() {
10289        let reg = build_help_registry(Arc::new(AtomicUsize::new(0)));
10290
10291        let err = reg
10292            .dispatch("not_a_verb", serde_json::json!({}))
10293            .await
10294            .unwrap_err();
10295
10296        let msg = err.to_string();
10297        // `recall.embed` is a Subhandler in HelpPack — must NOT appear in the
10298        // "available" list of an unknown-verb dispatch error.
10299        assert!(
10300            !msg.contains("recall.embed"),
10301            "dispatch unknown-verb error must not advertise subhandler recall.embed: {msg}"
10302        );
10303        // Public verbs must still appear so the agent knows what to call.
10304        assert!(
10305            msg.contains("create"),
10306            "dispatch unknown-verb error must still list public verb 'create': {msg}"
10307        );
10308        assert!(
10309            msg.contains("recall"),
10310            "dispatch unknown-verb error must still list public verb 'recall': {msg}"
10311        );
10312    }
10313
10314    // ── ADR-028 multi-backend schema routing tests ───────────────────────────
10315
10316    /// A test pack that returns a real SchemaPlan so we can assert routing.
10317    struct SchemaPack {
10318        pack_name: &'static str,
10319        statements: &'static [&'static str],
10320    }
10321
10322    impl Pack for SchemaPack {
10323        const NAME: &'static str = "schema-pack";
10324        const NOTE_KINDS: &'static [&'static str] = &[];
10325        const ENTITY_KINDS: &'static [&'static str] = &[];
10326        const HANDLERS: &'static [HandlerDef] = &[];
10327    }
10328
10329    #[async_trait]
10330    impl PackRuntime for SchemaPack {
10331        fn name(&self) -> &str {
10332            self.pack_name
10333        }
10334        fn note_kinds(&self) -> &'static [&'static str] {
10335            &[]
10336        }
10337        fn entity_kinds(&self) -> &'static [&'static str] {
10338            &[]
10339        }
10340        fn handlers(&self) -> &'static [HandlerDef] {
10341            &[]
10342        }
10343        fn schema_plan(&self) -> SchemaPlan {
10344            SchemaPlan {
10345                pack: self.pack_name,
10346                statements: self.statements,
10347            }
10348        }
10349        async fn dispatch(
10350            &self,
10351            verb: &str,
10352            _params: Value,
10353            _registry: &VerbRegistry,
10354            _token: &NamespaceToken,
10355        ) -> Result<Value, RuntimeError> {
10356            Ok(serde_json::json!({ "pack": self.pack_name, "verb": verb }))
10357        }
10358    }
10359
10360    // ADR-028: all_schema_plans_named returns (pack_name, SchemaPlan) pairs
10361    // where pack_name comes from SchemaPlan::pack (always &'static str).
10362    #[test]
10363    fn all_schema_plans_named_returns_correct_pairs() {
10364        let mut builder = VerbRegistryBuilder::new();
10365        builder.register_boxed(Box::new(SchemaPack {
10366            pack_name: "alpha",
10367            statements: &["CREATE TABLE IF NOT EXISTS t_alpha (id INTEGER PRIMARY KEY)"],
10368        }));
10369        builder.register_boxed(Box::new(SchemaPack {
10370            pack_name: "beta",
10371            statements: &[],
10372        }));
10373        let reg = builder.build().expect("registry builds");
10374
10375        let named = reg.all_schema_plans_named();
10376        assert_eq!(named.len(), 2);
10377
10378        let alpha_entry = named.iter().find(|(n, _)| *n == "alpha");
10379        let beta_entry = named.iter().find(|(n, _)| *n == "beta");
10380
10381        assert!(alpha_entry.is_some(), "alpha must appear in named plans");
10382        assert!(beta_entry.is_some(), "beta must appear in named plans");
10383
10384        let (_, alpha_plan) = alpha_entry.unwrap();
10385        assert_eq!(alpha_plan.statements.len(), 1);
10386        assert!(!alpha_plan.is_empty());
10387
10388        let (_, beta_plan) = beta_entry.unwrap();
10389        assert!(beta_plan.is_empty());
10390    }
10391
10392    // ADR-028: apply_schema_plans_with_map routes non-empty plans to the
10393    // correct per-pack backend instead of the default.
10394    //
10395    // Verification: apply DDL to routed backend, then confirm the table is
10396    // present on pack_backend and absent on default_backend by attempting to
10397    // apply the same DDL again — if the table already exists on pack_backend
10398    // the idempotent CREATE IF NOT EXISTS succeeds; applying to default_backend
10399    // would only matter if the table were routed there.  We verify isolation
10400    // by applying the plan and then running a targeted DDL on each backend
10401    // that would fail if the table did not already exist (CREATE without
10402    // IF NOT EXISTS on a duplicate raises an error), combined with a no-error
10403    // path on the correct backend.
10404    //
10405    // Simpler approach: confirm the plan applies without error (routing is
10406    // correct) and that the opposite backend returns an error when we try to
10407    // INSERT into the routed table (table-not-found = SQLITE_ERROR).
10408    #[tokio::test]
10409    async fn apply_schema_plans_with_map_routes_to_correct_backend() {
10410        use khive_storage::types::{SqlStatement, SqlValue};
10411
10412        let default_backend = khive_db::StorageBackend::memory().expect("default memory backend");
10413        let pack_backend =
10414            khive_db::StorageBackend::memory().expect("pack-specific memory backend");
10415
10416        let mut builder = VerbRegistryBuilder::new();
10417        builder.register_boxed(Box::new(SchemaPack {
10418            pack_name: "routed",
10419            statements: &["CREATE TABLE IF NOT EXISTS t_routed (id INTEGER PRIMARY KEY)"],
10420        }));
10421        let reg = builder.build().expect("registry builds");
10422
10423        let mut backend_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
10424        backend_map.insert("routed", &pack_backend);
10425
10426        reg.apply_schema_plans_with_map(&backend_map, &default_backend)
10427            .expect("schema application must not collide");
10428
10429        // On pack_backend: INSERT must succeed (table exists).
10430        let mut writer = pack_backend.sql().writer().await.expect("writer");
10431        let result = writer
10432            .execute(SqlStatement {
10433                sql: "INSERT INTO t_routed (id) VALUES (?1)".into(),
10434                params: vec![SqlValue::Integer(1)],
10435                label: None,
10436            })
10437            .await;
10438        assert!(
10439            result.is_ok(),
10440            "t_routed must exist on pack_backend after routing: {result:?}"
10441        );
10442
10443        // On default_backend: INSERT must fail (table not there).
10444        let mut default_writer = default_backend.sql().writer().await.expect("writer");
10445        let default_result = default_writer
10446            .execute(SqlStatement {
10447                sql: "INSERT INTO t_routed (id) VALUES (?1)".into(),
10448                params: vec![SqlValue::Integer(2)],
10449                label: None,
10450            })
10451            .await;
10452        assert!(
10453            default_result.is_err(),
10454            "t_routed must NOT exist on default_backend (table should not be there)"
10455        );
10456    }
10457
10458    // ADR-028: apply_schema_plans_with_map uses default backend for packs
10459    // absent from the map.
10460    #[tokio::test]
10461    async fn apply_schema_plans_with_map_falls_back_to_default_for_unmapped_packs() {
10462        use khive_storage::types::{SqlStatement, SqlValue};
10463
10464        let default_backend = khive_db::StorageBackend::memory().expect("default memory backend");
10465
10466        let mut builder = VerbRegistryBuilder::new();
10467        builder.register_boxed(Box::new(SchemaPack {
10468            pack_name: "unmapped",
10469            statements: &["CREATE TABLE IF NOT EXISTS t_unmapped (id INTEGER PRIMARY KEY)"],
10470        }));
10471        let reg = builder.build().expect("registry builds");
10472
10473        let backend_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
10474        reg.apply_schema_plans_with_map(&backend_map, &default_backend)
10475            .expect("schema application must not collide");
10476
10477        // On default_backend: INSERT must succeed (table fell back here).
10478        let mut writer = default_backend.sql().writer().await.expect("writer");
10479        let result = writer
10480            .execute(SqlStatement {
10481                sql: "INSERT INTO t_unmapped (id) VALUES (?1)".into(),
10482                params: vec![SqlValue::Integer(1)],
10483                label: None,
10484            })
10485            .await;
10486        assert!(
10487            result.is_ok(),
10488            "t_unmapped must exist on default_backend for unmapped pack: {result:?}"
10489        );
10490    }
10491
10492    // ADR-028: two packs declaring the same auxiliary table on the same
10493    // backend must cause apply_schema_plans_with_map to return an error that
10494    // names both packs and the table: it is a boot-time failure, not a
10495    // silent DDL race.
10496    #[test]
10497    fn apply_schema_plans_with_map_collision_is_an_error() {
10498        let backend = khive_db::StorageBackend::memory().expect("memory backend");
10499        let empty_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
10500
10501        let mut builder = VerbRegistryBuilder::new();
10502        builder.register_boxed(Box::new(SchemaPack {
10503            pack_name: "pack_alpha",
10504            statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
10505        }));
10506        builder.register_boxed(Box::new(SchemaPack {
10507            pack_name: "pack_beta",
10508            statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
10509        }));
10510        let registry = builder.build().expect("registry builds");
10511
10512        let result = registry.apply_schema_plans_with_map(&empty_map, &backend);
10513        assert!(
10514            result.is_err(),
10515            "two packs declaring the same table on the same backend must produce a collision error"
10516        );
10517        let err = result.unwrap_err();
10518        let msg = err.to_string();
10519        assert!(
10520            msg.contains("pack_alpha"),
10521            "collision error must name first pack; got: {msg}"
10522        );
10523        assert!(
10524            msg.contains("pack_beta"),
10525            "collision error must name second pack; got: {msg}"
10526        );
10527        assert!(
10528            msg.contains("collision_table"),
10529            "collision error must name the table; got: {msg}"
10530        );
10531    }
10532
10533    #[test]
10534    fn apply_schema_plans_with_map_read_only_collision_is_an_error_without_writes() {
10535        let dir = tempfile::tempdir().expect("tempdir");
10536        let path = dir.path().join("read_only_schema_collision.db");
10537        {
10538            let writable = khive_db::StorageBackend::sqlite(&path).expect("writable backend");
10539            writable.prepare_core_schema().expect("current schema");
10540        }
10541        #[cfg(unix)]
10542        {
10543            use std::os::unix::fs::PermissionsExt;
10544            for suffix in ["-wal", "-shm"] {
10545                let mut name = path.file_name().expect("db file name").to_os_string();
10546                name.push(suffix);
10547                let sidecar = path.parent().expect("db parent dir").join(name);
10548                if sidecar.exists() {
10549                    let mut permissions = std::fs::metadata(&sidecar)
10550                        .expect("sidecar metadata")
10551                        .permissions();
10552                    permissions.set_mode(0o444);
10553                    std::fs::set_permissions(&sidecar, permissions).expect("freeze sidecar");
10554                }
10555            }
10556        }
10557        let backend = khive_db::StorageBackend::sqlite_read_only(&path).expect("read-only backend");
10558        let empty_map: HashMap<&str, &khive_db::StorageBackend> = HashMap::new();
10559
10560        let mut builder = VerbRegistryBuilder::new();
10561        builder.register_boxed(Box::new(SchemaPack {
10562            pack_name: "pack_alpha",
10563            statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
10564        }));
10565        builder.register_boxed(Box::new(SchemaPack {
10566            pack_name: "pack_beta",
10567            statements: &["CREATE TABLE IF NOT EXISTS collision_table (id INTEGER PRIMARY KEY)"],
10568        }));
10569        let registry = builder.build().expect("registry builds");
10570        let writes_before = backend.pool().writer_acquisition_snapshot();
10571
10572        let result = registry.apply_schema_plans_with_map(&empty_map, &backend);
10573
10574        let err = result.expect_err(
10575            "read-only topology must reject the same cross-pack collision as writable topology",
10576        );
10577        let msg = err.to_string();
10578        assert!(
10579            msg.contains("pack_alpha"),
10580            "collision error must name first pack; got: {msg}"
10581        );
10582        assert!(
10583            msg.contains("pack_beta"),
10584            "collision error must name second pack; got: {msg}"
10585        );
10586        assert!(
10587            msg.contains("collision_table"),
10588            "collision error must name the table; got: {msg}"
10589        );
10590        assert_eq!(
10591            backend.pool().writer_acquisition_snapshot(),
10592            writes_before,
10593            "read-only collision validation must not acquire a writer"
10594        );
10595    }
10596}