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