Skip to main content

khive_runtime/pack/
dispatch.rs

1use std::sync::Arc;
2use std::time::Instant;
3
4use khive_gate::{AuditEvent, GateDecision, GateRequest};
5use khive_storage::{Event, EventStore, EventView, SubstrateKind};
6use khive_types::{EventKind, EventOutcome, Namespace, Visibility};
7use serde_json::Value;
8
9use crate::error::{AuditObligationFailure, DispatchError, RuntimeError};
10use crate::runtime::NamespaceToken;
11
12use super::audit::{
13    enrich_search_success, enrich_stream_truncate_success, stamp_client_cwd, stamp_error_class,
14};
15use super::request_identity::edge_endpoint_table;
16#[cfg(doc)]
17use super::IdResolutionMode;
18use super::{
19    append_audit_event_best_effort, build_audit_storage_event, fold_audit_obligation,
20    identifier_resolution_help, link_audit_success_from_result, masked_audit_event,
21    persist_git_digest_receipt, resolution_mode_contract, resolve_explicit_namespace,
22    GitDigestReceiptOutcome, InterceptedDispatchResult, RequestIdentity, VerbRegistry,
23    VerifiedActor,
24};
25
26impl VerbRegistry {
27    /// Return the help schema envelope for a verb.
28    ///
29    /// Walks registered packs for the first matching `HandlerDef` and returns a
30    /// structured JSON envelope. Subhandlers carry `callable_via_mcp: false`.
31    /// Every envelope carries the shared `identifier_resolution` contract.
32    /// `link`'s envelope additionally carries `endpoint_rules` — the composed
33    /// per-relation source/target allowlist (issue #964) — so batch callers can
34    /// defer to the kernel's own table instead of re-implementing it locally.
35    /// Every `uuid`/`array of uuid` parameter description has its
36    /// declared [`IdResolutionMode`]'s contract text appended — the same
37    /// text rendered under `identifier_resolution.resolution_modes` — so the
38    /// full-UUID-vs-short-prefix rule is stated once per mode (in
39    /// `resolution_mode_contract`) and inherited by every matching param,
40    /// instead of restating it per param across every `HandlerDef` in every
41    /// pack. Parameters whose mode is [`IdResolutionMode::NotApplicable`]
42    /// (every non-identifier parameter) are left unchanged.
43    /// Unknown or disabled verbs return `RuntimeError::UnknownVerb`. Full shape documented
44    /// in `docs/protocol.md` §Request Schema.
45    pub fn describe_verb(&self, verb: &str) -> Result<Value, RuntimeError> {
46        if self.is_verb_disabled(verb) {
47            return Err(self.unknown_verb_error(verb));
48        }
49        for pack in self.packs.iter() {
50            for handler in pack.handlers().iter() {
51                if handler.name == verb {
52                    let category = format!("{:?}", handler.category);
53                    let params_arr: Vec<Value> = handler
54                        .params
55                        .iter()
56                        .map(|p| {
57                            let description = match resolution_mode_contract(p.resolution_mode) {
58                                Some(contract) => format!("{} {}", p.description, contract),
59                                None => p.description.to_string(),
60                            };
61                            serde_json::json!({
62                                "name": p.name,
63                                "type": p.param_type,
64                                "required": p.required,
65                                "description": description,
66                            })
67                        })
68                        .collect();
69                    // Subhandlers are not callable via the MCP request surface;
70                    // the help payload must match the behaviour the dispatch
71                    // path enforces so callers reading `help=true` before
72                    // probing see accurate availability.
73                    if matches!(handler.visibility, Visibility::Subhandler) {
74                        return Ok(serde_json::json!({
75                            "verb": verb,
76                            "pack": pack.name(),
77                            "description": handler.description,
78                            "category": category,
79                            "params": params_arr,
80                            "identifier_resolution": identifier_resolution_help(),
81                            "visibility": "internal",
82                            "callable_via_mcp": false,
83                            "note": "This is an internal subhandler. Calling it via the MCP \
84                                     request surface returns permission denied. It can only be \
85                                     invoked by internal runtime callers.",
86                        }));
87                    }
88                    let mut envelope = serde_json::json!({
89                        "verb": verb,
90                        "pack": pack.name(),
91                        "description": handler.description,
92                        "category": category,
93                        "params": params_arr,
94                        "identifier_resolution": identifier_resolution_help(),
95                    });
96                    // A pack that authored its own schema keeps it; every other
97                    // verb gets one derived from the declarations the runtime
98                    // already holds, so a bridged model has a schema to read
99                    // instead of parsing the prose `params[].type`.
100                    if let Some(schema) = pack.input_schema(verb) {
101                        envelope["input_schema"] = schema;
102                    } else {
103                        let described: Vec<(String, String)> = params_arr
104                            .iter()
105                            .map(|p| {
106                                (
107                                    p["name"].as_str().unwrap_or_default().to_string(),
108                                    p["description"].as_str().unwrap_or_default().to_string(),
109                                )
110                            })
111                            .collect();
112                        if let Some(schema) =
113                            crate::input_schema::derive_input_schema(handler.params, &described)
114                        {
115                            envelope["input_schema"] = schema;
116                        }
117                    }
118                    if verb == "link" {
119                        envelope["endpoint_rules"] = Value::Array(edge_endpoint_table(&self.packs));
120                    }
121                    return Ok(envelope);
122                }
123            }
124        }
125        // Verb-visibility handler names, precomputed at build() time (internal
126        // subhandlers are excluded so they are not advertised in the
127        // unknown-verb error).
128        Err(self.unknown_verb_error(verb))
129    }
130
131    /// Check whether the gate permits writes into `ns`.
132    ///
133    /// Performs a gate evaluation with verb `"authorize"` before any background
134    /// loop is spawned (ADR-056 §6).  Returns `Ok(())` when the gate allows the
135    /// namespace, or `Err(RuntimeError::PermissionDenied{..})` when denied.
136    /// Gate errors (implementation failures) are surfaced as
137    /// `RuntimeError::Internal` carrying the stable classified reason; the
138    /// bounded, masked backend detail goes to the server-side log here, since
139    /// callers log the returned error.
140    pub fn authorize_namespace(&self, ns: Namespace) -> Result<(), RuntimeError> {
141        let actor = crate::actor_identity::resolve_actor(self.actor_id.as_deref());
142        let req = GateRequest::new(actor, ns, "authorize", serde_json::Value::Null);
143        match self.gate.check(&req) {
144            Ok(decision) if decision.is_allow() => Ok(()),
145            Ok(GateDecision::Deny { reason }) => {
146                Err(RuntimeError::permission_denied("authorize", reason))
147            }
148            Ok(_) => Err(RuntimeError::permission_denied("authorize", "gate denied")),
149            Err(e) => {
150                tracing::warn!(
151                    error = %crate::secret_gate::bounded_masked_log_text(&e.to_string()),
152                    "authorize_namespace: gate check failed (fail-closed)"
153                );
154                Err(RuntimeError::Internal(format!(
155                    "gate error: {}",
156                    e.wire_reason()
157                )))
158            }
159        }
160    }
161
162    /// Gate and execute an operation handled outside normal pack dispatch.
163    ///
164    /// Multi-backend transports use this to route an operation through a
165    /// coordinator while retaining [`Self::dispatch_with_identity`]'s gate and
166    /// audit lifecycle. Deny is authoritative, gate errors fail closed, and an
167    /// allowed audit is persisted after the intercepted operation resolves so
168    /// its outcome and duration reflect the operation result. Successful
169    /// `git.digest` interception uses the same strict durable-receipt exception
170    /// as normal pack dispatch.
171    pub async fn dispatch_intercepted_with_identity<F, Fut>(
172        &self,
173        verb: &str,
174        params: &Value,
175        identity: Option<&RequestIdentity>,
176        dispatch: F,
177    ) -> Result<Value, RuntimeError>
178    where
179        F: FnOnce(Namespace) -> Fut,
180        Fut: std::future::Future<Output = Result<Value, RuntimeError>>,
181    {
182        self.dispatch_intercepted_with_metadata_with_identity(
183            verb,
184            params,
185            identity,
186            |namespace| async move {
187                dispatch(namespace)
188                    .await
189                    .map(|result| InterceptedDispatchResult::new(result, ()))
190            },
191        )
192        .await
193        .map(|outcome| outcome.result)
194    }
195
196    /// Gate and execute an intercepted operation whose transport needs typed
197    /// metadata in addition to the canonical verb result.
198    ///
199    /// Audit accounting always receives `outcome.result`; `outcome.metadata`
200    /// crosses the dispatch seam unchanged for the transport to place beside
201    /// that result in its own envelope.
202    pub async fn dispatch_intercepted_with_metadata_with_identity<M, F, Fut>(
203        &self,
204        verb: &str,
205        params: &Value,
206        identity: Option<&RequestIdentity>,
207        dispatch: F,
208    ) -> Result<InterceptedDispatchResult<M>, RuntimeError>
209    where
210        F: FnOnce(Namespace) -> Fut,
211        Fut: std::future::Future<Output = Result<InterceptedDispatchResult<M>, RuntimeError>>,
212    {
213        self.dispatch_intercepted_with_metadata_and_disposition(verb, params, identity, dispatch)
214            .await
215            .map_err(DispatchError::into_source)
216    }
217
218    /// Append the `GateDenied` row of a refused dispatch and report what the
219    /// caller may cite: the row's id when it committed, otherwise why not.
220    pub(super) async fn append_gate_denied_row(
221        &self,
222        store: &Arc<dyn EventStore>,
223        event: Event,
224        verb: &str,
225    ) -> crate::error::DenialReceipt {
226        let audit_event_id = event.id;
227        match append_audit_event_best_effort(
228            self.audit_batch.as_ref(),
229            store,
230            event,
231            verb,
232            crate::audit_batch::AuditProducer::GateDenied,
233            false,
234        )
235        .await
236        {
237            Ok(()) => crate::error::DenialReceipt {
238                audit_event_id: Some(audit_event_id),
239                audit_outcome: crate::error::DenialAuditOutcome::Committed,
240            },
241            Err(failure) => crate::error::DenialReceipt {
242                audit_event_id: None,
243                audit_outcome: crate::error::DenialAuditOutcome::NotCommitted(failure.wire_code()),
244            },
245        }
246    }
247
248    /// Execute an intercepted operation while retaining this boundary's failure provenance.
249    /// Successful canonical results and typed metadata are returned unchanged.
250    pub async fn dispatch_intercepted_with_metadata_and_disposition<M, F, Fut>(
251        &self,
252        verb: &str,
253        params: &Value,
254        identity: Option<&RequestIdentity>,
255        dispatch: F,
256    ) -> Result<InterceptedDispatchResult<M>, DispatchError>
257    where
258        F: FnOnce(Namespace) -> Fut,
259        Fut: std::future::Future<Output = Result<InterceptedDispatchResult<M>, RuntimeError>>,
260    {
261        self.dispatch_intercepted_with_token_and_disposition(verb, params, identity, |token| {
262            dispatch(token.gate_namespace().clone())
263        })
264        .await
265    }
266
267    /// Intercept an operation with the sealed caller token minted after the
268    /// gate decision. Coordinated reads retain the resolved actor and their
269    /// existing namespace selection without reconstructing identity from args.
270    pub async fn dispatch_intercepted_with_token_and_disposition<M, F, Fut>(
271        &self,
272        verb: &str,
273        params: &Value,
274        identity: Option<&RequestIdentity>,
275        dispatch: F,
276    ) -> Result<InterceptedDispatchResult<M>, DispatchError>
277    where
278        F: FnOnce(NamespaceToken) -> Fut,
279        Fut: std::future::Future<Output = Result<InterceptedDispatchResult<M>, RuntimeError>>,
280    {
281        if self.is_verb_disabled(verb) {
282            // Use the ordinary unknown-verb path, including attribution and audit,
283            // without invoking an interceptor that could perform the mutation.
284            self.dispatch_with_disposition(verb, params.clone(), identity.cloned())
285                .await?;
286            return Err(DispatchError::before_dispatch(
287                self.unknown_verb_error(verb),
288            ));
289        }
290        let request_id = identity.and_then(|id| id.request_id);
291        let gate_req = self
292            .gate_request_with_identity(verb, params, identity)
293            .map_err(DispatchError::before_dispatch)?;
294        let gate_decision = khive_gate::check_with_mailbox_policy(self.gate.as_ref(), &gate_req);
295        let mut deferred_audit = match gate_decision {
296            Ok(decision) => {
297                let audit = masked_audit_event(&gate_req, &decision, self.gate.impl_name());
298                tracing::info!(
299                    audit_event = %serde_json::to_string(&audit)
300                        .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
301                    "gate.check"
302                );
303                if let GateDecision::Deny { reason } = decision {
304                    let receipt = match &self.event_store {
305                        Some(store) => {
306                            let event = build_audit_storage_event(
307                                &gate_req,
308                                &audit,
309                                EventOutcome::Denied,
310                                Some(crate::cost_unit::base_resource_payload(request_id)),
311                            );
312                            // The dispatch returns `PermissionDenied` below
313                            // whether or not this row commits — a deny never
314                            // reports success — so a commit failure has no
315                            // caller-visible outcome to fold into; the receipt
316                            // on the refusal says whether the row the caller
317                            // could cite exists.
318                            self.append_gate_denied_row(store, event, verb).await
319                        }
320                        None => crate::error::DenialReceipt::no_store(),
321                    };
322                    return Err(DispatchError::before_dispatch(
323                        RuntimeError::PermissionDenied {
324                            verb: verb.to_string(),
325                            reason,
326                            receipt: Box::new(receipt),
327                        },
328                    ));
329                }
330                Some(audit)
331            }
332            Err(err) => {
333                return Err(DispatchError::before_dispatch(
334                    self.gate_unavailable_error(&gate_req, &err, request_id, None)
335                        .await,
336                ));
337            }
338        };
339
340        let started = Instant::now();
341        let token = self.mint_intercepted_read_token(&gate_req, params, identity);
342        let (mut result, search_arms) =
343            crate::search_audit::capture(verb == "search", async { dispatch(token).await }).await;
344        let domain_succeeded = result.is_ok();
345        let duration_us = started.elapsed().as_micros() as i64;
346        let receipt_outcome = if verb == "git.digest" && result.is_ok() {
347            let resource = result.as_ref().ok().map(|outcome| {
348                crate::cost_unit::resource_payload(
349                    verb,
350                    &gate_req.args,
351                    &outcome.result,
352                    || 0,
353                    request_id,
354                )
355            });
356            // The receipt helper operates on the canonical verb result. Move
357            // that value out temporarily so it can turn receipt failures into
358            // the outer dispatch error without discarding successful typed
359            // transport metadata.
360            let mut receipt_result: Result<Value, RuntimeError> = match result.as_mut() {
361                Ok(outcome) => Ok(std::mem::take(&mut outcome.result)),
362                Err(_) => unreachable!("git.digest receipt path is guarded by result.is_ok()"),
363            };
364            let outcome = persist_git_digest_receipt(
365                self.event_store.as_ref(),
366                self.audit_batch.as_ref(),
367                &gate_req,
368                deferred_audit.as_ref(),
369                &mut receipt_result,
370                duration_us,
371                resource,
372            )
373            .await;
374            match receipt_result {
375                Ok(receipted_result) => {
376                    if let Ok(intercepted) = &mut result {
377                        intercepted.result = receipted_result;
378                    }
379                }
380                Err(error) => result = Err(error),
381            }
382            Some(outcome)
383        } else {
384            None
385        };
386        if receipt_outcome.is_none()
387            || receipt_outcome == Some(GitDigestReceiptOutcome::BuildRejected)
388        {
389            if let Some(audit) = deferred_audit.take() {
390                let audit_outcome = self
391                    .persist_intercepted_audit(
392                        &gate_req,
393                        audit,
394                        result.as_ref().map(|outcome| &outcome.result),
395                        duration_us,
396                        request_id,
397                        search_arms,
398                    )
399                    .await;
400                result = fold_audit_obligation(result, audit_outcome, |outcome| outcome.result);
401            }
402        }
403        result.map_err(|error| DispatchError::after_handler(error, domain_succeeded))
404    }
405
406    async fn persist_intercepted_audit(
407        &self,
408        gate_req: &GateRequest,
409        audit: AuditEvent,
410        result: Result<&Value, &RuntimeError>,
411        duration_us: i64,
412        request_id: Option<u64>,
413        search_arms: crate::search_audit::SearchArms,
414    ) -> Result<(), AuditObligationFailure> {
415        let verb = gate_req.verb.as_str();
416        let Some(store) = &self.event_store else {
417            return Ok(());
418        };
419        let success_row = self.audit_success_row_action(verb, result.ok());
420        if success_row.is_skipped() {
421            return Ok(());
422        }
423        let mut event = match result {
424            Ok(value) if verb == "link" && gate_req.args.get("links").is_none() => {
425                let resource = crate::cost_unit::resource_payload(
426                    verb,
427                    &gate_req.args,
428                    value,
429                    || 0,
430                    request_id,
431                );
432                match link_audit_success_from_result(audit.clone(), value) {
433                    Some((edge_id, mut payload)) => {
434                        if let Value::Object(ref mut map) = payload {
435                            map.insert("resource".to_string(), resource);
436                        }
437                        let mut event = Event::new(
438                            gate_req.namespace.as_str(),
439                            gate_req.verb.as_str(),
440                            EventKind::Audit,
441                            SubstrateKind::Event,
442                            format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
443                        )
444                        .with_outcome(EventOutcome::Success)
445                        .with_target(edge_id)
446                        .with_payload(payload)
447                        .with_payload_schema_version(2)
448                        .with_duration_us(duration_us);
449                        stamp_client_cwd(&mut event, gate_req);
450                        event
451                    }
452                    None => build_audit_storage_event(
453                        gate_req,
454                        &audit,
455                        EventOutcome::Success,
456                        Some(resource),
457                    )
458                    .with_duration_us(duration_us),
459                }
460            }
461            Ok(value) => build_audit_storage_event(
462                gate_req,
463                &audit,
464                EventOutcome::Success,
465                Some(success_row.resource(crate::cost_unit::resource_payload(
466                    verb,
467                    &gate_req.args,
468                    value,
469                    || 0,
470                    request_id,
471                ))),
472            )
473            .with_duration_us(duration_us),
474            Err(_) => build_audit_storage_event(
475                gate_req,
476                &audit,
477                EventOutcome::Error,
478                Some(crate::cost_unit::base_resource_payload(request_id)),
479            )
480            .with_duration_us(duration_us),
481        };
482        match result {
483            Ok(value) => {
484                enrich_stream_truncate_success(&mut event, gate_req, value);
485                enrich_search_success(&mut event, gate_req, value, search_arms);
486            }
487            Err(error) => stamp_error_class(&mut event, error.audit_error_class()),
488        }
489        let producer = if result.is_ok() {
490            crate::audit_batch::AuditProducer::DispatchSucceeded
491        } else {
492            crate::audit_batch::AuditProducer::DispatchFailed
493        };
494        append_audit_event_best_effort(
495            self.audit_batch.as_ref(),
496            store,
497            event,
498            verb,
499            producer,
500            self.admission_degrade_safe(verb),
501        )
502        .await
503    }
504
505    /// A create refusal may reveal its key holder only when the same caller can list it.
506    pub fn allows_note_key_disclosure(
507        &self,
508        token: &NamespaceToken,
509        kind: &str,
510        key: &str,
511    ) -> bool {
512        let request = GateRequest::new(
513            token.actor().clone(),
514            token.namespace().clone(),
515            "list",
516            serde_json::json!({"kind":"note", "note_kind":kind, "key_prefix":key}),
517        );
518        self.gate
519            .check(&request)
520            .is_ok_and(|decision| decision.is_allow())
521    }
522
523    /// A keyed entity create may reveal the key's holder only when the same
524    /// caller can list entities of that kind (ADR-221 section 1).
525    pub fn allows_entity_key_disclosure(&self, token: &NamespaceToken, kind: &str) -> bool {
526        let request = GateRequest::new(
527            token.actor().clone(),
528            token.namespace().clone(),
529            "list",
530            serde_json::json!({"kind": kind}),
531        );
532        self.gate
533            .check(&request)
534            .is_ok_and(|decision| decision.is_allow())
535    }
536
537    /// The caller's declared owned namespaces for one dispatch: the per-request
538    /// identity's list when an identity is supplied, else the registry's baked
539    /// list. Entries that fail `Namespace::parse` are dropped, so a malformed
540    /// declaration can only shrink what the caller owns, never widen it.
541    fn owned_namespaces_for(&self, identity: Option<&RequestIdentity>) -> Vec<Namespace> {
542        match identity {
543            Some(identity) => identity
544                .owned_namespaces
545                .iter()
546                .filter_map(|namespace| Namespace::parse(namespace).ok())
547                .collect(),
548            None => self.owned_namespaces.clone(),
549        }
550    }
551
552    fn mint_intercepted_read_token(
553        &self,
554        gate_req: &GateRequest,
555        params: &Value,
556        identity: Option<&RequestIdentity>,
557    ) -> NamespaceToken {
558        // Preserve the coordinator's existing namespace selection: the gate
559        // namespace is primary, and explicit namespace input stays narrow.
560        let visible = if params.get("namespace").is_some() {
561            Vec::new()
562        } else {
563            let mut visible = match identity {
564                Some(identity) => identity
565                    .visible_namespaces
566                    .iter()
567                    .filter_map(|namespace| Namespace::parse(namespace).ok())
568                    .collect(),
569                None => self.visible_namespaces.clone(),
570            };
571            visible.push(Namespace::local());
572            visible
573        };
574        NamespaceToken::mint_with_visibility(
575            gate_req.namespace.clone(),
576            visible,
577            gate_req.actor.clone(),
578        )
579        .with_gate_namespace(gate_req.namespace.clone())
580        .with_gate_explicit_namespace(
581            params
582                .get("namespace")
583                .and_then(Value::as_str)
584                .map(str::to_owned),
585        )
586        .with_request_id(identity.and_then(|identity| identity.request_id))
587        .with_owned_namespaces(self.owned_namespaces_for(identity))
588        .with_process_ref(match identity {
589            Some(identity) => identity.process_ref.clone(),
590            None => crate::config::process_ref_from_env(),
591        })
592    }
593
594    fn gate_request_with_identity(
595        &self,
596        verb: &str,
597        params: &Value,
598        identity: Option<&RequestIdentity>,
599    ) -> Result<GateRequest, RuntimeError> {
600        let default_namespace = identity
601            .map(|id| id.namespace.as_str())
602            .unwrap_or(self.default_namespace.as_str());
603        let namespace = resolve_explicit_namespace(params, default_namespace)?;
604        let actor_id = identity
605            .map(|id| id.actor_id.as_deref())
606            .unwrap_or(self.actor_id.as_deref());
607        let actor = crate::actor_identity::resolve_actor(actor_id);
608        // GateRequest.args deliberately captures submitted dispatch arguments.
609        // The handler's canonicalization and kind hooks have not run; a policy
610        // requiring their effective values belongs after that handler work.
611        let req = GateRequest::new(actor, namespace, verb, params.clone());
612        crate::mailbox_view::validate_mailbox_request(&req)?;
613        Ok(req)
614    }
615
616    pub(super) async fn gate_unavailable_error(
617        &self,
618        gate_req: &GateRequest,
619        error: &khive_gate::GateError,
620        request_id: Option<u64>,
621        effective_target: Option<uuid::Uuid>,
622    ) -> RuntimeError {
623        let audit = AuditEvent::gate_unavailable(gate_req, self.gate.impl_name())
624            .with_operation_attribution(
625                khive_storage::operation_context::current_operation_attribution(),
626            );
627        tracing::info!(
628            audit_event = %serde_json::to_string(&audit)
629                .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
630            "gate.check"
631        );
632        tracing::warn!(
633            verb = %gate_req.verb,
634            error = %crate::secret_gate::bounded_masked_log_text(&error.to_string()),
635            "gate check failed (fail-closed)"
636        );
637        let failure = RuntimeError::GateUnavailable {
638            verb: gate_req.verb.clone(),
639            // Caller-visible: a stable, classified reason derived from the
640            // `GateError` variant only. `error`'s `Display` text is logged
641            // above (server-side, via `tracing::warn!`) and must never be
642            // interpolated here — a gate backend's error message can embed
643            // connection details, addresses, or credentials.
644            reason: error.wire_reason().to_string(),
645        };
646        if let Some(store) = &self.event_store {
647            let mut event = build_audit_storage_event(
648                gate_req,
649                &audit,
650                EventOutcome::Error,
651                Some(crate::cost_unit::base_resource_payload(request_id)),
652            );
653            stamp_error_class(&mut event, failure.audit_error_class());
654            if let Some(target) = effective_target {
655                event = event.with_target(target);
656            }
657            let _ = append_audit_event_best_effort(
658                self.audit_batch.as_ref(),
659                store,
660                event,
661                gate_req.verb.as_str(),
662                crate::audit_batch::AuditProducer::GateUnavailable,
663                false,
664            )
665            .await;
666        }
667        failure
668    }
669
670    /// Dispatch a verb to the first pack that handles it.
671    ///
672    /// Routes through the gate, then invokes the matching pack handler. When
673    /// `params["help"] == true`, short-circuits to `describe_verb` with no side effects.
674    /// Gate errors fail closed. Full dispatch flow documented in `docs/protocol.md`.
675    ///
676    /// Equivalent to `self.dispatch_with_identity(verb, params, None)` — uses
677    /// this registry's construction-baked `default_namespace` / `actor_id` /
678    /// `visible_namespaces`.
679    pub async fn dispatch(&self, verb: &str, params: Value) -> Result<Value, RuntimeError> {
680        self.dispatch_with_identity(verb, params, None).await
681    }
682
683    /// Dispatch a verb, optionally overriding this registry's baked identity
684    /// scalars for exactly this call (ADR-096 Fork 1).
685    ///
686    /// `identity = None` behaves exactly like [`Self::dispatch`]. `identity =
687    /// Some(id)` uses `id.namespace` / `id.actor_id` / `id.visible_namespaces`
688    /// in place of `self.default_namespace` / `self.actor_id` /
689    /// `self.visible_namespaces` for this call's namespace resolution, gate
690    /// request, and token minting. The registry's own fields are never mutated,
691    /// so concurrent calls with different (or no) identity are independent.
692    /// See `docs/api/pack.md#dispatch_with_identity` for why this enables one warm
693    /// registry to serve many attribution identities over a shared backend.
694    pub async fn dispatch_with_identity(
695        &self,
696        verb: &str,
697        params: Value,
698        identity: Option<RequestIdentity>,
699    ) -> Result<Value, RuntimeError> {
700        self.dispatch_with_disposition(verb, params, identity)
701            .await
702            .map_err(DispatchError::into_source)
703    }
704
705    /// Dispatch with provenance for this operation's own domain result.
706    /// Errors returned by a nested dispatch remain handler errors at this boundary.
707    pub async fn dispatch_with_disposition(
708        &self,
709        verb: &str,
710        params: Value,
711        identity: Option<RequestIdentity>,
712    ) -> Result<Value, DispatchError> {
713        // help=true interception: short-circuit before gate/pack.
714        if params.get("help").and_then(Value::as_bool) == Some(true) {
715            let result = match self.describe_verb(verb) {
716                Ok(value) => Ok(value),
717                Err(error) => match self.mounted_verb_catalog().await {
718                    Ok(catalog) => catalog
719                        .into_iter()
720                        .find(|entry| entry["verb"] == verb)
721                        .ok_or(error),
722                    Err(error) => Err(error),
723                },
724            };
725            return result.map_err(DispatchError::before_dispatch);
726        }
727        // Resolve namespace before `params` is moved into pack.dispatch, so the
728        // post-dispatch hook can reference it.
729        //
730        // Absent `namespace` and a present-but-malformed `namespace` are
731        // different cases. A present non-string value (null, number, bool,
732        // array, object) is explicit caller input that failed to parse and
733        // must fail closed, not silently coerce to the default namespace.
734        // Only a genuinely absent key defaults. Shared with the multi-backend
735        // coordinator intercept via `resolve_explicit_namespace` so every MCP
736        // ingress path applies the same fail-closed rule.
737        let explicit_namespace = params.get("namespace").is_some_and(Value::is_string);
738        // The caller-supplied correlation id (khive#948), if any. Read once
739        // here so it is in scope for every audit-append site below,
740        // including the ones that run before pack dispatch is attempted.
741        let request_id: Option<u64> = identity.as_ref().and_then(|id| id.request_id);
742        // Thread the configured actor identity into the gate request so the
743        // gate can distinguish human vs agent callers at the dispatch seam.
744        // Resolved once via the shared actor-identity policy and reused for
745        // token minting below, so the gate's notion of "who is the caller"
746        // and the storage token's notion can never drift apart.
747        let gate_req = self
748            .gate_request_with_identity(verb, &params, identity.as_ref())
749            .map_err(DispatchError::before_dispatch)?;
750        let ns = gate_req.namespace.clone();
751        let resolved_actor = gate_req.actor.clone();
752
753        // Consult the gate.
754        //
755        // - Ok(Allow) → proceed to pack dispatch (tracing + optional EventStore).
756        // - Ok(Deny) → emit audit, persist if store configured, return PermissionDenied.
757        // - Err(_) → emit an outage audit and return GateUnavailable.
758        let gate_decision = khive_gate::check_with_mailbox_policy(self.gate.as_ref(), &gate_req);
759        let (gate_blocked, mut deferred_audit) = match gate_decision {
760            Ok(decision) => {
761                let is_deny = matches!(decision, GateDecision::Deny { .. });
762
763                // Emit audit event via tracing.
764                let audit = masked_audit_event(&gate_req, &decision, self.gate.impl_name());
765                tracing::info!(
766                    audit_event = %serde_json::to_string(&audit)
767                        .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
768                    "gate.check"
769                );
770
771                // Drain only the runtime retained with this audit sink. The
772                // owned batch has released its ledger guard before any append.
773                // Namespace/actor and the best-effort audit path stay unchanged.
774                if let (Some(store), Some(runtime)) = (&self.event_store, &self.config_lock_runtime)
775                {
776                    for (key, value) in runtime.drain_config_locked() {
777                        let payload = serde_json::json!({ "key": key, "value": value });
778                        let storage_event = Event::new(
779                            gate_req.namespace.as_str(),
780                            "config.lock",
781                            EventKind::ConfigLocked,
782                            SubstrateKind::Event,
783                            format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
784                        )
785                        .with_payload(payload);
786                        // ConfigLocked is pure observability: the helper
787                        // never returns `Err` for it, so there is
788                        // nothing to fold.
789                        let _ = append_audit_event_best_effort(
790                            self.audit_batch.as_ref(),
791                            store,
792                            storage_event,
793                            "config.lock",
794                            crate::audit_batch::AuditProducer::ConfigLocked,
795                            false,
796                        )
797                        .await;
798                    }
799                }
800
801                // Every Allow-outcome audit row defers its append until pack
802                // dispatch returns, so the row can carry the measured
803                // dispatch time in `duration_us` (persisting before dispatch
804                // ran always recorded the `Event::new` default of 0). A
805                // singleton `link` call (no `links` bulk array) additionally
806                // enriches the deferred row with the created/resolved edge
807                // fields (schema v2) once dispatch resolves. Denied calls
808                // have no dispatch to wait for and keep the immediate v1
809                // append below.
810                //
811                // Accepted trade-off for ordinary verbs: a crash between this
812                // Allow decision and the deferred append loses the audit row.
813                // `git.digest` narrows the caller-visible contract below: it
814                // never returns success until the deferred receipt append is
815                // confirmed, though a process crash can still leave committed
816                // ingest writes with no response and no completed receipt.
817                let defer_audit = !is_deny;
818
819                // Persist to EventStore immediately only for denied calls;
820                // the receipt rides on the refusal so the caller can cite
821                // the row.
822                let reason = if is_deny {
823                    let reason = match decision {
824                        GateDecision::Deny { reason } => reason,
825                        _ => String::new(),
826                    };
827                    let receipt = match &self.event_store {
828                        Some(store) => {
829                            // ADR-103 Decision (a): the closed `work_class` enum
830                            // is stamped on every event, denial included -- only
831                            // `resource.cost_unit` is scoped to a successful
832                            // dispatch by Amendment 1. `base_resource_payload()`
833                            // carries `work_class` alone, no `cost_unit` key.
834                            let storage_event = build_audit_storage_event(
835                                &gate_req,
836                                &audit,
837                                EventOutcome::Denied,
838                                Some(crate::cost_unit::base_resource_payload(request_id)),
839                            );
840                            // This path always returns `PermissionDenied`
841                            // below, so there is no success outcome to fold a
842                            // commit failure into; the receipt says whether
843                            // the row exists.
844                            self.append_gate_denied_row(store, storage_event, verb)
845                                .await
846                        }
847                        None => crate::error::DenialReceipt::no_store(),
848                    };
849                    Some((reason, receipt))
850                } else {
851                    None
852                };
853                let deferred = if defer_audit { Some(audit) } else { None };
854                (reason, deferred)
855            }
856            Err(err) => {
857                return Err(DispatchError::before_dispatch(
858                    self.gate_unavailable_error(&gate_req, &err, request_id, None)
859                        .await,
860                ));
861            }
862        };
863
864        // Hard enforcement: Deny is authoritative.
865        if let Some((reason, receipt)) = gate_blocked {
866            return Err(DispatchError::before_dispatch(
867                RuntimeError::PermissionDenied {
868                    verb: verb.to_string(),
869                    reason,
870                    receipt: Box::new(receipt),
871                },
872            ));
873        }
874
875        // Mint the authorized storage token at the dispatch boundary.
876        //
877        // Writes pin to `local` by default. Actor identity and config
878        // `[actor] id` are attribution and gate-context inputs only: they
879        // never route storage. The explicit `namespace=` request param is a
880        // precise single-namespace escape: the caller deliberately
881        // reads/writes exactly that one set; it is NOT widened by `visible_namespaces`.
882        //
883        // When actor_id is configured, mint a token carrying that actor
884        // label so that comm.inbox applies the to_actor filter for directed delivery.
885        // Otherwise, use ActorRef::anonymous() and inbox falls back to party-line.
886        // `actor_id_str` already reflects the per-request identity override
887        // when supplied (resolved above into `resolved_actor`, mirrored into
888        // the gate request). Reusing the same value here guarantees the
889        // gate's actor and the storage token's actor can never diverge.
890        //
891        // On the default (no explicit `namespace=`) path, the read scope
892        // widens to `['local'] ∪ visible_namespaces` (baked, or the
893        // per-request override). `'local'` is always included
894        // (mint_with_visibility deduplicates). Writes remain pinned to
895        // `'local'`. Per-actor distinctions use view-layer tag filters
896        // (assignee, actor_id, from/to), not namespace partitions. `ns`/
897        // `explicit_namespace` were already validated above: reuse them
898        // instead of re-reading `params["namespace"]` with `as_str()`, which
899        // would silently drop malformed non-string values again.
900        let token = if explicit_namespace {
901            // Explicit escape: precise single-namespace scope, read+write. NOT widened.
902            NamespaceToken::mint_with_visibility(ns.clone(), vec![], resolved_actor)
903        } else {
904            // Default path: write namespace = local; read scope = ['local'] ∪ visible_namespaces.
905            let primary = Namespace::local();
906            let mut extra_visible: Vec<Namespace> = match identity.as_ref() {
907                Some(id) => id
908                    .visible_namespaces
909                    .iter()
910                    .filter_map(|s| match Namespace::parse(s) {
911                        Ok(parsed) => Some(parsed),
912                        Err(e) => {
913                            tracing::warn!(
914                                namespace = %s,
915                                error = %e,
916                                "dispatch_with_identity: skipping invalid visible_namespace \
917                                 entry from per-request identity"
918                            );
919                            None
920                        }
921                    })
922                    .collect(),
923                None => self.visible_namespaces.clone(),
924            };
925            // ADR-007 Rev 4 Rule 3b, applied once at the seam every identity
926            // path shares: a non-`local` actor reads its own namespace by
927            // default (its episodic memories land there), whether the identity
928            // came from the config loader, a daemon frame, a scheduled replay
929            // or an embedding host. Writes stay pinned to `local` (Rule 0).
930            if let Some(actor_namespace) = resolved_actor
931                .binding_id()
932                .filter(|id| *id != Namespace::LOCAL)
933                .and_then(|id| Namespace::parse(id).ok())
934            {
935                extra_visible.push(actor_namespace);
936            }
937            extra_visible.push(Namespace::local()); // 'local' always readable; mint dedups
938            NamespaceToken::mint_with_visibility(primary, extra_visible, resolved_actor)
939        }
940        .with_gate_namespace(ns.clone())
941        .with_gate_explicit_namespace(
942            params
943                .get("namespace")
944                .and_then(Value::as_str)
945                .map(str::to_owned),
946        )
947        .with_request_id(request_id)
948        .with_owned_namespaces(self.owned_namespaces_for(identity.as_ref()))
949        .with_process_ref(match identity.as_ref() {
950            Some(id) => id.process_ref.clone(),
951            None => crate::config::process_ref_from_env(),
952        });
953
954        for pack in self.packs.iter().filter(|_| !self.is_verb_disabled(verb)) {
955            let handler_def = pack.handlers().iter().find(|v| v.name == verb);
956            let mounted_name = pack.mounted_namespace().and_then(|prefix| {
957                verb.strip_prefix(prefix)
958                    .and_then(|suffix| suffix.strip_prefix('.'))
959            });
960            if handler_def.is_some() || mounted_name.is_some() {
961                let definition = if let Some(name) = mounted_name {
962                    pack.mounted_catalog().await.and_then(|catalog| {
963                        catalog
964                            .into_iter()
965                            .find(|definition| definition.name == name)
966                            .map(Some)
967                            .ok_or_else(|| RuntimeError::UnknownVerb(verb.to_owned()))
968                    })
969                } else {
970                    Ok(None)
971                };
972                // Strip `namespace` from params before forwarding to packs.
973                // The registry has already consumed it to mint the NamespaceToken.
974                //
975                // Exception: if the handler's own `params` schema declares
976                // `"namespace"` as a valid field (e.g. brain.bind, brain.unbind,
977                // brain.bindings, brain.resolve), the field is a *business* argument
978                // — not a transport routing key — and must be passed through
979                // unchanged. Stripping it would silently default the binding to the
980                // "*" wildcard, broadening profile scope across namespaces.
981                let handler_accepts_namespace = handler_def
982                    .is_some_and(|h| h.params.iter().any(|p| p.name == "namespace"))
983                    || definition
984                        .as_ref()
985                        .ok()
986                        .and_then(|value| value.as_ref())
987                        .is_some_and(|definition| {
988                            definition
989                                .input_schema
990                                .get("properties")
991                                .is_some_and(|properties| properties.get("namespace").is_some())
992                        });
993                let mut params = if !handler_accepts_namespace {
994                    if let Value::Object(mut map) = params {
995                        map.remove("namespace");
996                        Value::Object(map)
997                    } else {
998                        params
999                    }
1000                } else {
1001                    params
1002                };
1003                if let Some(handler) = handler_def {
1004                    crate::params::integer_params_from_whole_floats(&mut params, handler.params);
1005                }
1006                let dispatch_start = Instant::now();
1007                let mounted_audit = definition.as_ref().ok().and_then(|v| v.as_ref()).map(|v| {
1008                    serde_json::json!({"mount": pack.name(), "effect": v.effect, "generation": v.generation})
1009                });
1010                let (mut result, search_arms) =
1011                    crate::search_audit::capture(verb == "search", async {
1012                        match definition {
1013                            Ok(Some(definition)) => {
1014                                pack.dispatch_mounted(&definition, verb, params, self, &token)
1015                                    .await
1016                            }
1017                            Ok(None) => pack.dispatch(verb, params, self, &token).await,
1018                            Err(error) => Err(error),
1019                        }
1020                    })
1021                    .await;
1022                let domain_succeeded = result.is_ok();
1023                let dispatch_us = dispatch_start.elapsed().as_micros() as i64;
1024
1025                // Unlike ordinary audit rows, a successful `git.digest`
1026                // response is returned only after its complete report has
1027                // been durably persisted as a schema-v2 audit receipt. The
1028                // receipt helper borrows the deferred audit row so malformed
1029                // handler output can still fall back to one generic Error
1030                // audit. Handler errors use that same ordinary path below.
1031                let git_digest_receipt_outcome = if verb == "git.digest" && result.is_ok() {
1032                    let resource = result.as_ref().ok().map(|value| {
1033                        crate::cost_unit::resource_payload(
1034                            verb,
1035                            &gate_req.args,
1036                            value,
1037                            || pack.registered_embedding_model_names().len() as i64,
1038                            request_id,
1039                        )
1040                    });
1041                    Some(
1042                        persist_git_digest_receipt(
1043                            self.event_store.as_ref(),
1044                            self.audit_batch.as_ref(),
1045                            &gate_req,
1046                            deferred_audit.as_ref(),
1047                            &mut result,
1048                            dispatch_us,
1049                            resource,
1050                        )
1051                        .await,
1052                    )
1053                } else {
1054                    None
1055                };
1056
1057                // Append the deferred Allow-outcome audit row now that
1058                // dispatch has resolved, so `duration_us` carries the
1059                // measured `dispatch_us` instead of the `Event::new` default
1060                // of 0. A successful singleton `link` call enriches the row
1061                // with the created/resolved edge (schema v2); anything that
1062                // cannot be enriched, or is not a singleton `link` call,
1063                // falls back to the generic v1 audit shape so no audit row
1064                // is ever dropped for the deferred path.
1065                let needs_generic_audit = git_digest_receipt_outcome.is_none()
1066                    || git_digest_receipt_outcome == Some(GitDigestReceiptOutcome::BuildRejected);
1067                if let (true, Some(audit)) = (needs_generic_audit, deferred_audit.take()) {
1068                    if let Some(store) = &self.event_store {
1069                        let success_row = self.audit_success_row_action(verb, result.as_ref().ok());
1070                        let is_link_singleton =
1071                            verb == "link" && gate_req.args.get("links").is_none();
1072                        // Read-only pass over `result` first: every arm below
1073                        // only needs `audit_outcome` afterward, and folding a
1074                        // failure into `result` requires a mutable borrow
1075                        // that cannot coexist with the `&result` match below.
1076                        let audit_outcome: Result<(), AuditObligationFailure> = match &result {
1077                            _ if success_row.is_skipped() => Ok(()),
1078                            Ok(ok_val) if is_link_singleton => {
1079                                // ADR-103 Amendment 1: `link` (singleton or
1080                                // bulk) has no embedding-bearing path — edges
1081                                // carry no embedded body — so cost_unit is
1082                                // always base_weight("link") alone. The
1083                                // registered-model closure is never invoked
1084                                // (per_item_weight("link", ..) short-circuits
1085                                // to 0 before `model_count` reads it).
1086                                let resource = crate::cost_unit::resource_payload(
1087                                    verb,
1088                                    &gate_req.args,
1089                                    ok_val,
1090                                    || pack.registered_embedding_model_names().len() as i64,
1091                                    request_id,
1092                                );
1093                                match link_audit_success_from_result(audit.clone(), ok_val) {
1094                                    Some((edge_id, mut payload)) => {
1095                                        if let Value::Object(ref mut map) = payload {
1096                                            map.insert("resource".to_string(), resource);
1097                                        }
1098                                        let mut storage_event = Event::new(
1099                                            gate_req.namespace.as_str(),
1100                                            gate_req.verb.as_str(),
1101                                            EventKind::Audit,
1102                                            SubstrateKind::Event,
1103                                            format!(
1104                                                "{}:{}",
1105                                                gate_req.actor.kind, gate_req.actor.id
1106                                            ),
1107                                        )
1108                                        .with_outcome(EventOutcome::Success)
1109                                        .with_target(edge_id)
1110                                        .with_payload(payload)
1111                                        .with_payload_schema_version(2)
1112                                        .with_duration_us(dispatch_us);
1113                                        stamp_client_cwd(&mut storage_event, &gate_req);
1114                                        append_audit_event_best_effort(
1115                                            self.audit_batch.as_ref(),
1116                                            store,
1117                                            storage_event,
1118                                            verb,
1119                                            crate::audit_batch::AuditProducer::DispatchSucceeded,
1120                                            self.admission_degrade_safe(verb),
1121                                        )
1122                                        .await
1123                                    }
1124                                    None => {
1125                                        tracing::warn!(
1126                                            verb,
1127                                            "link audit v2 enrichment parse failed; \
1128                                             falling back to v1 audit shape"
1129                                        );
1130                                        let storage_event = build_audit_storage_event(
1131                                            &gate_req,
1132                                            &audit,
1133                                            EventOutcome::Success,
1134                                            Some(resource),
1135                                        )
1136                                        .with_duration_us(dispatch_us);
1137                                        append_audit_event_best_effort(
1138                                            self.audit_batch.as_ref(),
1139                                            store,
1140                                            storage_event,
1141                                            verb,
1142                                            crate::audit_batch::AuditProducer::DispatchSucceeded,
1143                                            self.admission_degrade_safe(verb),
1144                                        )
1145                                        .await
1146                                    }
1147                                }
1148                            }
1149                            _ => {
1150                                // The persisted audit outcome must reflect
1151                                // the dispatch result, not be hardcoded to
1152                                // Success — otherwise a failed dispatch is
1153                                // recorded as successful work and disappears
1154                                // from `outcome=error` queries.
1155                                //
1156                                // ADR-103 Amendment 1: `resource.cost_unit` is
1157                                // computed ONLY on a successful dispatch —
1158                                // there is no handler `Value` to read
1159                                // `item_count` from on an error, and the
1160                                // amendment's "absence has exactly two
1161                                // meanings" rule requires the field be
1162                                // omitted, never defaulted to 0, on an
1163                                // errored dispatch. `work_class` itself is
1164                                // NOT one of those two omission cases
1165                                // (ADR-103 Decision (a) stamps it on every
1166                                // event), so an errored dispatch still gets
1167                                // `resource: {"work_class": "interactive"}`,
1168                                // just with no `cost_unit` key.
1169                                let (outcome, resource) = match &result {
1170                                    Ok(ok_val) => (
1171                                        EventOutcome::Success,
1172                                        Some(success_row.resource(
1173                                            crate::cost_unit::resource_payload(
1174                                                verb,
1175                                                &gate_req.args,
1176                                                ok_val,
1177                                                || {
1178                                                    pack.registered_embedding_model_names().len()
1179                                                        as i64
1180                                                },
1181                                                request_id,
1182                                            ),
1183                                        )),
1184                                    ),
1185                                    Err(_) => (
1186                                        EventOutcome::Error,
1187                                        Some(crate::cost_unit::base_resource_payload(request_id)),
1188                                    ),
1189                                };
1190                                let producer = if result.is_ok() {
1191                                    crate::audit_batch::AuditProducer::DispatchSucceeded
1192                                } else {
1193                                    crate::audit_batch::AuditProducer::DispatchFailed
1194                                };
1195                                let mut storage_event =
1196                                    build_audit_storage_event(&gate_req, &audit, outcome, resource)
1197                                        .with_duration_us(dispatch_us);
1198                                if let Ok(value) = &result {
1199                                    enrich_stream_truncate_success(
1200                                        &mut storage_event,
1201                                        &gate_req,
1202                                        value,
1203                                    );
1204                                    enrich_search_success(
1205                                        &mut storage_event,
1206                                        &gate_req,
1207                                        value,
1208                                        search_arms,
1209                                    );
1210                                }
1211                                if let Err(error) = &result {
1212                                    stamp_error_class(
1213                                        &mut storage_event,
1214                                        error.audit_error_class(),
1215                                    );
1216                                }
1217                                if let Some(metadata) = &mounted_audit {
1218                                    storage_event.payload["mounted_tool"] = metadata.clone();
1219                                }
1220                                append_audit_event_best_effort(
1221                                    self.audit_batch.as_ref(),
1222                                    store,
1223                                    storage_event,
1224                                    verb,
1225                                    producer,
1226                                    self.admission_degrade_safe(verb),
1227                                )
1228                                .await
1229                            }
1230                        };
1231                        // Only a would-be-success dispatch can be flipped by
1232                        // an obligation failure (ADR-133 D2/D3/D4): an
1233                        // already-erroring dispatch (DispatchFailed producer)
1234                        // keeps its original error, matching
1235                        // `fold_audit_obligation`'s contract.
1236                        result =
1237                            fold_audit_obligation(result, audit_outcome, std::convert::identity);
1238                    }
1239                }
1240
1241                // Post-dispatch hook: fires on success, opt-in.
1242                if let (Ok(ref ok_val), Some(hook)) = (&result, &self.dispatch_hook) {
1243                    let mut dispatch_event = Event::new(
1244                        ns.as_str(),
1245                        verb,
1246                        EventKind::Audit,
1247                        SubstrateKind::Event,
1248                        pack.name(),
1249                    )
1250                    .with_outcome(EventOutcome::Success)
1251                    .with_duration_us(dispatch_us);
1252
1253                    // For recall verbs: extract the first result's id as
1254                    // target_id so the brain temporal posterior can observe
1255                    // real hit/miss and latency. Copy the serve-attribution
1256                    // fields from that same hit so the hook credits the profile
1257                    // that actually served instead of always crediting default.
1258                    if verb == "memory.recall" {
1259                        let first_result =
1260                            ok_val.as_array().and_then(|arr| arr.first()).or_else(|| {
1261                                ok_val
1262                                    .get("results")
1263                                    .and_then(Value::as_array)
1264                                    .and_then(|arr| arr.first())
1265                            });
1266                        let first_note_id = first_result
1267                            .and_then(|v| v.get("id"))
1268                            .and_then(|v| v.as_str())
1269                            .and_then(|s| s.parse::<uuid::Uuid>().ok());
1270                        if let Some(note_id) = first_note_id {
1271                            dispatch_event = dispatch_event.with_target(note_id);
1272                        }
1273                        let mut payload = serde_json::Map::new();
1274                        if let Some(profile_id) = first_result
1275                            .and_then(|v| v.get("served_by_profile_id"))
1276                            .and_then(Value::as_str)
1277                        {
1278                            payload.insert(
1279                                "served_by_profile_id".to_string(),
1280                                Value::String(profile_id.to_string()),
1281                            );
1282                        }
1283                        if let Some(attribution) = first_result
1284                            .and_then(|v| v.get("serve_attribution"))
1285                            .and_then(Value::as_str)
1286                        {
1287                            payload.insert(
1288                                "serve_attribution".to_string(),
1289                                Value::String(attribution.to_string()),
1290                            );
1291                        }
1292                        dispatch_event = dispatch_event.with_payload(Value::Object(payload));
1293                        // No first result → target_id stays None (RecallMiss
1294                        // in brain's event interpreter).
1295                    }
1296
1297                    let dispatch_view = EventView {
1298                        event: dispatch_event,
1299                        observations: Vec::new(),
1300                    };
1301                    let hook = Arc::clone(hook);
1302                    hook.on_dispatch(&dispatch_view).await;
1303                }
1304
1305                // Recently-referenced ring admission: only by-id touches admit
1306                // an id. Runs unconditionally (not gated on `dispatch_hook`,
1307                // which is opt-in) because the ring is a core
1308                // dispatch-boundary capability, not an observer.
1309                //
1310                // Keyed on `token.namespace()`, NOT `ns`: `ns` is the
1311                // gate-resolved namespace, which on the default
1312                // (non-explicit) dispatch path can be a non-local
1313                // `default_namespace` (e.g. "foreign") while the storage
1314                // token that actually created/touched the record is pinned
1315                // to `local`. The ring must be keyed on the namespace the
1316                // record actually lives in: the same namespace
1317                // `resolve_reference`'s ring lookup uses: or admission and
1318                // lookup silently diverge on any non-local `default_namespace`
1319                // config.
1320                if let Ok(ref ok_val) = result {
1321                    let admissions = crate::reference_ring::ring_admissions_for(verb, ok_val);
1322                    if !admissions.is_empty() {
1323                        let actor_key = format!("{}:{}", gate_req.actor.kind, gate_req.actor.id);
1324                        for (id, name) in admissions {
1325                            self.reference_ring.admit(
1326                                token.namespace().as_str(),
1327                                &actor_key,
1328                                id,
1329                                name,
1330                            );
1331                        }
1332                    }
1333                }
1334
1335                return result
1336                    .map_err(|error| DispatchError::after_handler(error, domain_succeeded));
1337            }
1338        }
1339
1340        // No pack owns this verb: the gate allowed it, but no dispatch runs.
1341        // Persist the deferred audit row now (duration stays at the
1342        // `Event::new` default of 0 — no dispatch occurred to measure) so an
1343        // allowed-but-unknown verb is never silently dropped from the audit
1344        // trail (matches the "no audit row is ever dropped" contract above).
1345        let failure = self.unknown_verb_error(verb);
1346        if let Some(audit) = deferred_audit.take() {
1347            if let Some(store) = &self.event_store {
1348                // Dispatch is about to return `UnknownVerb` below (no pack
1349                // owns this verb), so the persisted outcome must be `Error`,
1350                // not `Success`. `work_class` is still stamped (ADR-103
1351                // Decision (a)); `resource.cost_unit` is omitted, matching
1352                // every other errored-dispatch row.
1353                let mut storage_event = build_audit_storage_event(
1354                    &gate_req,
1355                    &audit,
1356                    EventOutcome::Error,
1357                    Some(crate::cost_unit::base_resource_payload(request_id)),
1358                );
1359                stamp_error_class(&mut storage_event, failure.audit_error_class());
1360                // Dispatch already returns `UnknownVerb` below regardless, so
1361                // — as with the deny paths above — there is no success
1362                // outcome to fold a commit failure into.
1363                let _ = append_audit_event_best_effort(
1364                    self.audit_batch.as_ref(),
1365                    store,
1366                    storage_event,
1367                    verb,
1368                    crate::audit_batch::AuditProducer::UnknownVerb,
1369                    false,
1370                )
1371                .await;
1372            }
1373        }
1374
1375        // Verb-visibility handler names, precomputed at build() time (internal
1376        // subhandlers are excluded so they are not advertised in the
1377        // unknown-verb error).
1378        Err(DispatchError::before_dispatch(failure))
1379    }
1380
1381    /// Dispatch a verb under an out-of-band verified actor identity.
1382    ///
1383    /// `verified_actor` is a typed [`VerifiedActor`] (constructor rejects blank
1384    /// identifiers) — only code holding a `VerbRegistry` handle can supply it.
1385    /// `dispatch_as` never reads `params["actor"]` to derive the effective actor;
1386    /// individual verbs may still accept an `actor` field for their own documented
1387    /// business semantics, unrelated to the acting principal. Every pack handler
1388    /// that reads "who is calling" resolves it from the `NamespaceToken` the
1389    /// dispatch boundary mints, so `verified_actor` becomes exactly the principal
1390    /// those handlers observe.
1391    ///
1392    /// Equivalent to `dispatch_with_identity(verb, params, Some(identity))` with
1393    /// `identity.actor_id = Some(verified_actor)` and every other identity scalar
1394    /// (namespace, visible namespaces) left at this registry's construction-baked
1395    /// value. [`Self::dispatch`] and [`Self::dispatch_with_identity`] are unaffected.
1396    /// See `docs/api/pack.md#dispatch_as` for the embedding-host use case and the
1397    /// blank-identifier safety rationale.
1398    pub async fn dispatch_as(
1399        &self,
1400        verb: &str,
1401        params: Value,
1402        verified_actor: VerifiedActor,
1403    ) -> Result<Value, RuntimeError> {
1404        let identity = RequestIdentity {
1405            namespace: self.default_namespace.clone(),
1406            actor_id: Some(verified_actor.into_inner()),
1407            visible_namespaces: self
1408                .visible_namespaces
1409                .iter()
1410                .map(|ns| ns.as_str().to_string())
1411                .collect(),
1412            owned_namespaces: self
1413                .owned_namespaces
1414                .iter()
1415                .map(|ns| ns.as_str().to_string())
1416                .collect(),
1417            process_ref: crate::config::process_ref_from_env(),
1418            request_id: None,
1419        };
1420        self.dispatch_with_identity(verb, params, Some(identity))
1421            .await
1422    }
1423}