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    /// The caller's declared owned namespaces for one dispatch: the per-request
520    /// identity's list when an identity is supplied, else the registry's baked
521    /// list. Entries that fail `Namespace::parse` are dropped, so a malformed
522    /// declaration can only shrink what the caller owns, never widen it.
523    fn owned_namespaces_for(&self, identity: Option<&RequestIdentity>) -> Vec<Namespace> {
524        match identity {
525            Some(identity) => identity
526                .owned_namespaces
527                .iter()
528                .filter_map(|namespace| Namespace::parse(namespace).ok())
529                .collect(),
530            None => self.owned_namespaces.clone(),
531        }
532    }
533
534    fn mint_intercepted_read_token(
535        &self,
536        gate_req: &GateRequest,
537        params: &Value,
538        identity: Option<&RequestIdentity>,
539    ) -> NamespaceToken {
540        // Preserve the coordinator's existing namespace selection: the gate
541        // namespace is primary, and explicit namespace input stays narrow.
542        let visible = if params.get("namespace").is_some() {
543            Vec::new()
544        } else {
545            let mut visible = match identity {
546                Some(identity) => identity
547                    .visible_namespaces
548                    .iter()
549                    .filter_map(|namespace| Namespace::parse(namespace).ok())
550                    .collect(),
551                None => self.visible_namespaces.clone(),
552            };
553            visible.push(Namespace::local());
554            visible
555        };
556        NamespaceToken::mint_with_visibility(
557            gate_req.namespace.clone(),
558            visible,
559            gate_req.actor.clone(),
560        )
561        .with_gate_namespace(gate_req.namespace.clone())
562        .with_gate_explicit_namespace(
563            params
564                .get("namespace")
565                .and_then(Value::as_str)
566                .map(str::to_owned),
567        )
568        .with_request_id(identity.and_then(|identity| identity.request_id))
569        .with_owned_namespaces(self.owned_namespaces_for(identity))
570        .with_process_ref(match identity {
571            Some(identity) => identity.process_ref.clone(),
572            None => crate::config::process_ref_from_env(),
573        })
574    }
575
576    fn gate_request_with_identity(
577        &self,
578        verb: &str,
579        params: &Value,
580        identity: Option<&RequestIdentity>,
581    ) -> Result<GateRequest, RuntimeError> {
582        let default_namespace = identity
583            .map(|id| id.namespace.as_str())
584            .unwrap_or(self.default_namespace.as_str());
585        let namespace = resolve_explicit_namespace(params, default_namespace)?;
586        let actor_id = identity
587            .map(|id| id.actor_id.as_deref())
588            .unwrap_or(self.actor_id.as_deref());
589        let actor = crate::actor_identity::resolve_actor(actor_id);
590        // GateRequest.args deliberately captures submitted dispatch arguments.
591        // The handler's canonicalization and kind hooks have not run; a policy
592        // requiring their effective values belongs after that handler work.
593        let req = GateRequest::new(actor, namespace, verb, params.clone());
594        crate::mailbox_view::validate_mailbox_request(&req)?;
595        Ok(req)
596    }
597
598    pub(super) async fn gate_unavailable_error(
599        &self,
600        gate_req: &GateRequest,
601        error: &khive_gate::GateError,
602        request_id: Option<u64>,
603        effective_target: Option<uuid::Uuid>,
604    ) -> RuntimeError {
605        let audit = AuditEvent::gate_unavailable(gate_req, self.gate.impl_name())
606            .with_operation_attribution(
607                khive_storage::operation_context::current_operation_attribution(),
608            );
609        tracing::info!(
610            audit_event = %serde_json::to_string(&audit)
611                .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
612            "gate.check"
613        );
614        tracing::warn!(
615            verb = %gate_req.verb,
616            error = %crate::secret_gate::bounded_masked_log_text(&error.to_string()),
617            "gate check failed (fail-closed)"
618        );
619        let failure = RuntimeError::GateUnavailable {
620            verb: gate_req.verb.clone(),
621            // Caller-visible: a stable, classified reason derived from the
622            // `GateError` variant only. `error`'s `Display` text is logged
623            // above (server-side, via `tracing::warn!`) and must never be
624            // interpolated here — a gate backend's error message can embed
625            // connection details, addresses, or credentials.
626            reason: error.wire_reason().to_string(),
627        };
628        if let Some(store) = &self.event_store {
629            let mut event = build_audit_storage_event(
630                gate_req,
631                &audit,
632                EventOutcome::Error,
633                Some(crate::cost_unit::base_resource_payload(request_id)),
634            );
635            stamp_error_class(&mut event, failure.audit_error_class());
636            if let Some(target) = effective_target {
637                event = event.with_target(target);
638            }
639            let _ = append_audit_event_best_effort(
640                self.audit_batch.as_ref(),
641                store,
642                event,
643                gate_req.verb.as_str(),
644                crate::audit_batch::AuditProducer::GateUnavailable,
645                false,
646            )
647            .await;
648        }
649        failure
650    }
651
652    /// Dispatch a verb to the first pack that handles it.
653    ///
654    /// Routes through the gate, then invokes the matching pack handler. When
655    /// `params["help"] == true`, short-circuits to `describe_verb` with no side effects.
656    /// Gate errors fail closed. Full dispatch flow documented in `docs/protocol.md`.
657    ///
658    /// Equivalent to `self.dispatch_with_identity(verb, params, None)` — uses
659    /// this registry's construction-baked `default_namespace` / `actor_id` /
660    /// `visible_namespaces`.
661    pub async fn dispatch(&self, verb: &str, params: Value) -> Result<Value, RuntimeError> {
662        self.dispatch_with_identity(verb, params, None).await
663    }
664
665    /// Dispatch a verb, optionally overriding this registry's baked identity
666    /// scalars for exactly this call (ADR-096 Fork 1).
667    ///
668    /// `identity = None` behaves exactly like [`Self::dispatch`]. `identity =
669    /// Some(id)` uses `id.namespace` / `id.actor_id` / `id.visible_namespaces`
670    /// in place of `self.default_namespace` / `self.actor_id` /
671    /// `self.visible_namespaces` for this call's namespace resolution, gate
672    /// request, and token minting. The registry's own fields are never mutated,
673    /// so concurrent calls with different (or no) identity are independent.
674    /// See `docs/api/pack.md#dispatch_with_identity` for why this enables one warm
675    /// registry to serve many attribution identities over a shared backend.
676    pub async fn dispatch_with_identity(
677        &self,
678        verb: &str,
679        params: Value,
680        identity: Option<RequestIdentity>,
681    ) -> Result<Value, RuntimeError> {
682        self.dispatch_with_disposition(verb, params, identity)
683            .await
684            .map_err(DispatchError::into_source)
685    }
686
687    /// Dispatch with provenance for this operation's own domain result.
688    /// Errors returned by a nested dispatch remain handler errors at this boundary.
689    pub async fn dispatch_with_disposition(
690        &self,
691        verb: &str,
692        params: Value,
693        identity: Option<RequestIdentity>,
694    ) -> Result<Value, DispatchError> {
695        // help=true interception: short-circuit before gate/pack.
696        if params.get("help").and_then(Value::as_bool) == Some(true) {
697            let result = match self.describe_verb(verb) {
698                Ok(value) => Ok(value),
699                Err(error) => match self.mounted_verb_catalog().await {
700                    Ok(catalog) => catalog
701                        .into_iter()
702                        .find(|entry| entry["verb"] == verb)
703                        .ok_or(error),
704                    Err(error) => Err(error),
705                },
706            };
707            return result.map_err(DispatchError::before_dispatch);
708        }
709        // Resolve namespace before `params` is moved into pack.dispatch, so the
710        // post-dispatch hook can reference it.
711        //
712        // Absent `namespace` and a present-but-malformed `namespace` are
713        // different cases. A present non-string value (null, number, bool,
714        // array, object) is explicit caller input that failed to parse and
715        // must fail closed, not silently coerce to the default namespace.
716        // Only a genuinely absent key defaults. Shared with the multi-backend
717        // coordinator intercept via `resolve_explicit_namespace` so every MCP
718        // ingress path applies the same fail-closed rule.
719        let explicit_namespace = params.get("namespace").is_some_and(Value::is_string);
720        // The caller-supplied correlation id (khive#948), if any. Read once
721        // here so it is in scope for every audit-append site below,
722        // including the ones that run before pack dispatch is attempted.
723        let request_id: Option<u64> = identity.as_ref().and_then(|id| id.request_id);
724        // Thread the configured actor identity into the gate request so the
725        // gate can distinguish human vs agent callers at the dispatch seam.
726        // Resolved once via the shared actor-identity policy and reused for
727        // token minting below, so the gate's notion of "who is the caller"
728        // and the storage token's notion can never drift apart.
729        let gate_req = self
730            .gate_request_with_identity(verb, &params, identity.as_ref())
731            .map_err(DispatchError::before_dispatch)?;
732        let ns = gate_req.namespace.clone();
733        let resolved_actor = gate_req.actor.clone();
734
735        // Consult the gate.
736        //
737        // - Ok(Allow) → proceed to pack dispatch (tracing + optional EventStore).
738        // - Ok(Deny) → emit audit, persist if store configured, return PermissionDenied.
739        // - Err(_) → emit an outage audit and return GateUnavailable.
740        let gate_decision = khive_gate::check_with_mailbox_policy(self.gate.as_ref(), &gate_req);
741        let (gate_blocked, mut deferred_audit) = match gate_decision {
742            Ok(decision) => {
743                let is_deny = matches!(decision, GateDecision::Deny { .. });
744
745                // Emit audit event via tracing.
746                let audit = masked_audit_event(&gate_req, &decision, self.gate.impl_name());
747                tracing::info!(
748                    audit_event = %serde_json::to_string(&audit)
749                        .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
750                    "gate.check"
751                );
752
753                // Drain only the runtime retained with this audit sink. The
754                // owned batch has released its ledger guard before any append.
755                // Namespace/actor and the best-effort audit path stay unchanged.
756                if let (Some(store), Some(runtime)) = (&self.event_store, &self.config_lock_runtime)
757                {
758                    for (key, value) in runtime.drain_config_locked() {
759                        let payload = serde_json::json!({ "key": key, "value": value });
760                        let storage_event = Event::new(
761                            gate_req.namespace.as_str(),
762                            "config.lock",
763                            EventKind::ConfigLocked,
764                            SubstrateKind::Event,
765                            format!("{}:{}", gate_req.actor.kind, gate_req.actor.id),
766                        )
767                        .with_payload(payload);
768                        // ConfigLocked is pure observability: the helper
769                        // never returns `Err` for it, so there is
770                        // nothing to fold.
771                        let _ = append_audit_event_best_effort(
772                            self.audit_batch.as_ref(),
773                            store,
774                            storage_event,
775                            "config.lock",
776                            crate::audit_batch::AuditProducer::ConfigLocked,
777                            false,
778                        )
779                        .await;
780                    }
781                }
782
783                // Every Allow-outcome audit row defers its append until pack
784                // dispatch returns, so the row can carry the measured
785                // dispatch time in `duration_us` (persisting before dispatch
786                // ran always recorded the `Event::new` default of 0). A
787                // singleton `link` call (no `links` bulk array) additionally
788                // enriches the deferred row with the created/resolved edge
789                // fields (schema v2) once dispatch resolves. Denied calls
790                // have no dispatch to wait for and keep the immediate v1
791                // append below.
792                //
793                // Accepted trade-off for ordinary verbs: a crash between this
794                // Allow decision and the deferred append loses the audit row.
795                // `git.digest` narrows the caller-visible contract below: it
796                // never returns success until the deferred receipt append is
797                // confirmed, though a process crash can still leave committed
798                // ingest writes with no response and no completed receipt.
799                let defer_audit = !is_deny;
800
801                // Persist to EventStore immediately only for denied calls;
802                // the receipt rides on the refusal so the caller can cite
803                // the row.
804                let reason = if is_deny {
805                    let reason = match decision {
806                        GateDecision::Deny { reason } => reason,
807                        _ => String::new(),
808                    };
809                    let receipt = match &self.event_store {
810                        Some(store) => {
811                            // ADR-103 Decision (a): the closed `work_class` enum
812                            // is stamped on every event, denial included -- only
813                            // `resource.cost_unit` is scoped to a successful
814                            // dispatch by Amendment 1. `base_resource_payload()`
815                            // carries `work_class` alone, no `cost_unit` key.
816                            let storage_event = build_audit_storage_event(
817                                &gate_req,
818                                &audit,
819                                EventOutcome::Denied,
820                                Some(crate::cost_unit::base_resource_payload(request_id)),
821                            );
822                            // This path always returns `PermissionDenied`
823                            // below, so there is no success outcome to fold a
824                            // commit failure into; the receipt says whether
825                            // the row exists.
826                            self.append_gate_denied_row(store, storage_event, verb)
827                                .await
828                        }
829                        None => crate::error::DenialReceipt::no_store(),
830                    };
831                    Some((reason, receipt))
832                } else {
833                    None
834                };
835                let deferred = if defer_audit { Some(audit) } else { None };
836                (reason, deferred)
837            }
838            Err(err) => {
839                return Err(DispatchError::before_dispatch(
840                    self.gate_unavailable_error(&gate_req, &err, request_id, None)
841                        .await,
842                ));
843            }
844        };
845
846        // Hard enforcement: Deny is authoritative.
847        if let Some((reason, receipt)) = gate_blocked {
848            return Err(DispatchError::before_dispatch(
849                RuntimeError::PermissionDenied {
850                    verb: verb.to_string(),
851                    reason,
852                    receipt: Box::new(receipt),
853                },
854            ));
855        }
856
857        // Mint the authorized storage token at the dispatch boundary.
858        //
859        // Writes pin to `local` by default. Actor identity and config
860        // `[actor] id` are attribution and gate-context inputs only: they
861        // never route storage. The explicit `namespace=` request param is a
862        // precise single-namespace escape: the caller deliberately
863        // reads/writes exactly that one set; it is NOT widened by `visible_namespaces`.
864        //
865        // When actor_id is configured, mint a token carrying that actor
866        // label so that comm.inbox applies the to_actor filter for directed delivery.
867        // Otherwise, use ActorRef::anonymous() and inbox falls back to party-line.
868        // `actor_id_str` already reflects the per-request identity override
869        // when supplied (resolved above into `resolved_actor`, mirrored into
870        // the gate request). Reusing the same value here guarantees the
871        // gate's actor and the storage token's actor can never diverge.
872        //
873        // On the default (no explicit `namespace=`) path, the read scope
874        // widens to `['local'] ∪ visible_namespaces` (baked, or the
875        // per-request override). `'local'` is always included
876        // (mint_with_visibility deduplicates). Writes remain pinned to
877        // `'local'`. Per-actor distinctions use view-layer tag filters
878        // (assignee, actor_id, from/to), not namespace partitions. `ns`/
879        // `explicit_namespace` were already validated above: reuse them
880        // instead of re-reading `params["namespace"]` with `as_str()`, which
881        // would silently drop malformed non-string values again.
882        let token = if explicit_namespace {
883            // Explicit escape: precise single-namespace scope, read+write. NOT widened.
884            NamespaceToken::mint_with_visibility(ns.clone(), vec![], resolved_actor)
885        } else {
886            // Default path: write namespace = local; read scope = ['local'] ∪ visible_namespaces.
887            let primary = Namespace::local();
888            let mut extra_visible: Vec<Namespace> = match identity.as_ref() {
889                Some(id) => id
890                    .visible_namespaces
891                    .iter()
892                    .filter_map(|s| match Namespace::parse(s) {
893                        Ok(parsed) => Some(parsed),
894                        Err(e) => {
895                            tracing::warn!(
896                                namespace = %s,
897                                error = %e,
898                                "dispatch_with_identity: skipping invalid visible_namespace \
899                                 entry from per-request identity"
900                            );
901                            None
902                        }
903                    })
904                    .collect(),
905                None => self.visible_namespaces.clone(),
906            };
907            // ADR-007 Rev 4 Rule 3b, applied once at the seam every identity
908            // path shares: a non-`local` actor reads its own namespace by
909            // default (its episodic memories land there), whether the identity
910            // came from the config loader, a daemon frame, a scheduled replay
911            // or an embedding host. Writes stay pinned to `local` (Rule 0).
912            if let Some(actor_namespace) = resolved_actor
913                .binding_id()
914                .filter(|id| *id != Namespace::LOCAL)
915                .and_then(|id| Namespace::parse(id).ok())
916            {
917                extra_visible.push(actor_namespace);
918            }
919            extra_visible.push(Namespace::local()); // 'local' always readable; mint dedups
920            NamespaceToken::mint_with_visibility(primary, extra_visible, resolved_actor)
921        }
922        .with_gate_namespace(ns.clone())
923        .with_gate_explicit_namespace(
924            params
925                .get("namespace")
926                .and_then(Value::as_str)
927                .map(str::to_owned),
928        )
929        .with_request_id(request_id)
930        .with_owned_namespaces(self.owned_namespaces_for(identity.as_ref()))
931        .with_process_ref(match identity.as_ref() {
932            Some(id) => id.process_ref.clone(),
933            None => crate::config::process_ref_from_env(),
934        });
935
936        for pack in self.packs.iter().filter(|_| !self.is_verb_disabled(verb)) {
937            let handler_def = pack.handlers().iter().find(|v| v.name == verb);
938            let mounted_name = pack.mounted_namespace().and_then(|prefix| {
939                verb.strip_prefix(prefix)
940                    .and_then(|suffix| suffix.strip_prefix('.'))
941            });
942            if handler_def.is_some() || mounted_name.is_some() {
943                let definition = if let Some(name) = mounted_name {
944                    pack.mounted_catalog().await.and_then(|catalog| {
945                        catalog
946                            .into_iter()
947                            .find(|definition| definition.name == name)
948                            .map(Some)
949                            .ok_or_else(|| RuntimeError::UnknownVerb(verb.to_owned()))
950                    })
951                } else {
952                    Ok(None)
953                };
954                // Strip `namespace` from params before forwarding to packs.
955                // The registry has already consumed it to mint the NamespaceToken.
956                //
957                // Exception: if the handler's own `params` schema declares
958                // `"namespace"` as a valid field (e.g. brain.bind, brain.unbind,
959                // brain.bindings, brain.resolve), the field is a *business* argument
960                // — not a transport routing key — and must be passed through
961                // unchanged. Stripping it would silently default the binding to the
962                // "*" wildcard, broadening profile scope across namespaces.
963                let handler_accepts_namespace = handler_def
964                    .is_some_and(|h| h.params.iter().any(|p| p.name == "namespace"))
965                    || definition
966                        .as_ref()
967                        .ok()
968                        .and_then(|value| value.as_ref())
969                        .is_some_and(|definition| {
970                            definition
971                                .input_schema
972                                .get("properties")
973                                .is_some_and(|properties| properties.get("namespace").is_some())
974                        });
975                let mut params = if !handler_accepts_namespace {
976                    if let Value::Object(mut map) = params {
977                        map.remove("namespace");
978                        Value::Object(map)
979                    } else {
980                        params
981                    }
982                } else {
983                    params
984                };
985                if let Some(handler) = handler_def {
986                    crate::params::integer_params_from_whole_floats(&mut params, handler.params);
987                }
988                let dispatch_start = Instant::now();
989                let mounted_audit = definition.as_ref().ok().and_then(|v| v.as_ref()).map(|v| {
990                    serde_json::json!({"mount": pack.name(), "effect": v.effect, "generation": v.generation})
991                });
992                let (mut result, search_arms) =
993                    crate::search_audit::capture(verb == "search", async {
994                        match definition {
995                            Ok(Some(definition)) => {
996                                pack.dispatch_mounted(&definition, verb, params, self, &token)
997                                    .await
998                            }
999                            Ok(None) => pack.dispatch(verb, params, self, &token).await,
1000                            Err(error) => Err(error),
1001                        }
1002                    })
1003                    .await;
1004                let domain_succeeded = result.is_ok();
1005                let dispatch_us = dispatch_start.elapsed().as_micros() as i64;
1006
1007                // Unlike ordinary audit rows, a successful `git.digest`
1008                // response is returned only after its complete report has
1009                // been durably persisted as a schema-v2 audit receipt. The
1010                // receipt helper borrows the deferred audit row so malformed
1011                // handler output can still fall back to one generic Error
1012                // audit. Handler errors use that same ordinary path below.
1013                let git_digest_receipt_outcome = if verb == "git.digest" && result.is_ok() {
1014                    let resource = result.as_ref().ok().map(|value| {
1015                        crate::cost_unit::resource_payload(
1016                            verb,
1017                            &gate_req.args,
1018                            value,
1019                            || pack.registered_embedding_model_names().len() as i64,
1020                            request_id,
1021                        )
1022                    });
1023                    Some(
1024                        persist_git_digest_receipt(
1025                            self.event_store.as_ref(),
1026                            self.audit_batch.as_ref(),
1027                            &gate_req,
1028                            deferred_audit.as_ref(),
1029                            &mut result,
1030                            dispatch_us,
1031                            resource,
1032                        )
1033                        .await,
1034                    )
1035                } else {
1036                    None
1037                };
1038
1039                // Append the deferred Allow-outcome audit row now that
1040                // dispatch has resolved, so `duration_us` carries the
1041                // measured `dispatch_us` instead of the `Event::new` default
1042                // of 0. A successful singleton `link` call enriches the row
1043                // with the created/resolved edge (schema v2); anything that
1044                // cannot be enriched, or is not a singleton `link` call,
1045                // falls back to the generic v1 audit shape so no audit row
1046                // is ever dropped for the deferred path.
1047                let needs_generic_audit = git_digest_receipt_outcome.is_none()
1048                    || git_digest_receipt_outcome == Some(GitDigestReceiptOutcome::BuildRejected);
1049                if let (true, Some(audit)) = (needs_generic_audit, deferred_audit.take()) {
1050                    if let Some(store) = &self.event_store {
1051                        let success_row = self.audit_success_row_action(verb, result.as_ref().ok());
1052                        let is_link_singleton =
1053                            verb == "link" && gate_req.args.get("links").is_none();
1054                        // Read-only pass over `result` first: every arm below
1055                        // only needs `audit_outcome` afterward, and folding a
1056                        // failure into `result` requires a mutable borrow
1057                        // that cannot coexist with the `&result` match below.
1058                        let audit_outcome: Result<(), AuditObligationFailure> = match &result {
1059                            _ if success_row.is_skipped() => Ok(()),
1060                            Ok(ok_val) if is_link_singleton => {
1061                                // ADR-103 Amendment 1: `link` (singleton or
1062                                // bulk) has no embedding-bearing path — edges
1063                                // carry no embedded body — so cost_unit is
1064                                // always base_weight("link") alone. The
1065                                // registered-model closure is never invoked
1066                                // (per_item_weight("link", ..) short-circuits
1067                                // to 0 before `model_count` reads it).
1068                                let resource = crate::cost_unit::resource_payload(
1069                                    verb,
1070                                    &gate_req.args,
1071                                    ok_val,
1072                                    || pack.registered_embedding_model_names().len() as i64,
1073                                    request_id,
1074                                );
1075                                match link_audit_success_from_result(audit.clone(), ok_val) {
1076                                    Some((edge_id, mut payload)) => {
1077                                        if let Value::Object(ref mut map) = payload {
1078                                            map.insert("resource".to_string(), resource);
1079                                        }
1080                                        let storage_event = Event::new(
1081                                            gate_req.namespace.as_str(),
1082                                            gate_req.verb.as_str(),
1083                                            EventKind::Audit,
1084                                            SubstrateKind::Event,
1085                                            format!(
1086                                                "{}:{}",
1087                                                gate_req.actor.kind, gate_req.actor.id
1088                                            ),
1089                                        )
1090                                        .with_outcome(EventOutcome::Success)
1091                                        .with_target(edge_id)
1092                                        .with_payload(payload)
1093                                        .with_payload_schema_version(2)
1094                                        .with_duration_us(dispatch_us);
1095                                        append_audit_event_best_effort(
1096                                            self.audit_batch.as_ref(),
1097                                            store,
1098                                            storage_event,
1099                                            verb,
1100                                            crate::audit_batch::AuditProducer::DispatchSucceeded,
1101                                            self.admission_degrade_safe(verb),
1102                                        )
1103                                        .await
1104                                    }
1105                                    None => {
1106                                        tracing::warn!(
1107                                            verb,
1108                                            "link audit v2 enrichment parse failed; \
1109                                             falling back to v1 audit shape"
1110                                        );
1111                                        let storage_event = build_audit_storage_event(
1112                                            &gate_req,
1113                                            &audit,
1114                                            EventOutcome::Success,
1115                                            Some(resource),
1116                                        )
1117                                        .with_duration_us(dispatch_us);
1118                                        append_audit_event_best_effort(
1119                                            self.audit_batch.as_ref(),
1120                                            store,
1121                                            storage_event,
1122                                            verb,
1123                                            crate::audit_batch::AuditProducer::DispatchSucceeded,
1124                                            self.admission_degrade_safe(verb),
1125                                        )
1126                                        .await
1127                                    }
1128                                }
1129                            }
1130                            _ => {
1131                                // The persisted audit outcome must reflect
1132                                // the dispatch result, not be hardcoded to
1133                                // Success — otherwise a failed dispatch is
1134                                // recorded as successful work and disappears
1135                                // from `outcome=error` queries.
1136                                //
1137                                // ADR-103 Amendment 1: `resource.cost_unit` is
1138                                // computed ONLY on a successful dispatch —
1139                                // there is no handler `Value` to read
1140                                // `item_count` from on an error, and the
1141                                // amendment's "absence has exactly two
1142                                // meanings" rule requires the field be
1143                                // omitted, never defaulted to 0, on an
1144                                // errored dispatch. `work_class` itself is
1145                                // NOT one of those two omission cases
1146                                // (ADR-103 Decision (a) stamps it on every
1147                                // event), so an errored dispatch still gets
1148                                // `resource: {"work_class": "interactive"}`,
1149                                // just with no `cost_unit` key.
1150                                let (outcome, resource) = match &result {
1151                                    Ok(ok_val) => (
1152                                        EventOutcome::Success,
1153                                        Some(success_row.resource(
1154                                            crate::cost_unit::resource_payload(
1155                                                verb,
1156                                                &gate_req.args,
1157                                                ok_val,
1158                                                || {
1159                                                    pack.registered_embedding_model_names().len()
1160                                                        as i64
1161                                                },
1162                                                request_id,
1163                                            ),
1164                                        )),
1165                                    ),
1166                                    Err(_) => (
1167                                        EventOutcome::Error,
1168                                        Some(crate::cost_unit::base_resource_payload(request_id)),
1169                                    ),
1170                                };
1171                                let producer = if result.is_ok() {
1172                                    crate::audit_batch::AuditProducer::DispatchSucceeded
1173                                } else {
1174                                    crate::audit_batch::AuditProducer::DispatchFailed
1175                                };
1176                                let mut storage_event =
1177                                    build_audit_storage_event(&gate_req, &audit, outcome, resource)
1178                                        .with_duration_us(dispatch_us);
1179                                if let Ok(value) = &result {
1180                                    enrich_stream_truncate_success(
1181                                        &mut storage_event,
1182                                        &gate_req,
1183                                        value,
1184                                    );
1185                                    enrich_search_success(
1186                                        &mut storage_event,
1187                                        &gate_req,
1188                                        value,
1189                                        search_arms,
1190                                    );
1191                                }
1192                                if let Err(error) = &result {
1193                                    stamp_error_class(
1194                                        &mut storage_event,
1195                                        error.audit_error_class(),
1196                                    );
1197                                }
1198                                if let Some(metadata) = &mounted_audit {
1199                                    storage_event.payload["mounted_tool"] = metadata.clone();
1200                                }
1201                                append_audit_event_best_effort(
1202                                    self.audit_batch.as_ref(),
1203                                    store,
1204                                    storage_event,
1205                                    verb,
1206                                    producer,
1207                                    self.admission_degrade_safe(verb),
1208                                )
1209                                .await
1210                            }
1211                        };
1212                        // Only a would-be-success dispatch can be flipped by
1213                        // an obligation failure (ADR-133 D2/D3/D4): an
1214                        // already-erroring dispatch (DispatchFailed producer)
1215                        // keeps its original error, matching
1216                        // `fold_audit_obligation`'s contract.
1217                        result =
1218                            fold_audit_obligation(result, audit_outcome, std::convert::identity);
1219                    }
1220                }
1221
1222                // Post-dispatch hook: fires on success, opt-in.
1223                if let (Ok(ref ok_val), Some(hook)) = (&result, &self.dispatch_hook) {
1224                    let mut dispatch_event = Event::new(
1225                        ns.as_str(),
1226                        verb,
1227                        EventKind::Audit,
1228                        SubstrateKind::Event,
1229                        pack.name(),
1230                    )
1231                    .with_outcome(EventOutcome::Success)
1232                    .with_duration_us(dispatch_us);
1233
1234                    // For recall verbs: extract the first result's id as
1235                    // target_id so the brain temporal posterior can observe
1236                    // real hit/miss and latency. Copy the serve-attribution
1237                    // fields from that same hit so the hook credits the profile
1238                    // that actually served instead of always crediting default.
1239                    if verb == "memory.recall" {
1240                        let first_result =
1241                            ok_val.as_array().and_then(|arr| arr.first()).or_else(|| {
1242                                ok_val
1243                                    .get("results")
1244                                    .and_then(Value::as_array)
1245                                    .and_then(|arr| arr.first())
1246                            });
1247                        let first_note_id = first_result
1248                            .and_then(|v| v.get("id"))
1249                            .and_then(|v| v.as_str())
1250                            .and_then(|s| s.parse::<uuid::Uuid>().ok());
1251                        if let Some(note_id) = first_note_id {
1252                            dispatch_event = dispatch_event.with_target(note_id);
1253                        }
1254                        let mut payload = serde_json::Map::new();
1255                        if let Some(profile_id) = first_result
1256                            .and_then(|v| v.get("served_by_profile_id"))
1257                            .and_then(Value::as_str)
1258                        {
1259                            payload.insert(
1260                                "served_by_profile_id".to_string(),
1261                                Value::String(profile_id.to_string()),
1262                            );
1263                        }
1264                        if let Some(attribution) = first_result
1265                            .and_then(|v| v.get("serve_attribution"))
1266                            .and_then(Value::as_str)
1267                        {
1268                            payload.insert(
1269                                "serve_attribution".to_string(),
1270                                Value::String(attribution.to_string()),
1271                            );
1272                        }
1273                        dispatch_event = dispatch_event.with_payload(Value::Object(payload));
1274                        // No first result → target_id stays None (RecallMiss
1275                        // in brain's event interpreter).
1276                    }
1277
1278                    let dispatch_view = EventView {
1279                        event: dispatch_event,
1280                        observations: Vec::new(),
1281                    };
1282                    let hook = Arc::clone(hook);
1283                    hook.on_dispatch(&dispatch_view).await;
1284                }
1285
1286                // Recently-referenced ring admission: only by-id touches admit
1287                // an id. Runs unconditionally (not gated on `dispatch_hook`,
1288                // which is opt-in) because the ring is a core
1289                // dispatch-boundary capability, not an observer.
1290                //
1291                // Keyed on `token.namespace()`, NOT `ns`: `ns` is the
1292                // gate-resolved namespace, which on the default
1293                // (non-explicit) dispatch path can be a non-local
1294                // `default_namespace` (e.g. "foreign") while the storage
1295                // token that actually created/touched the record is pinned
1296                // to `local`. The ring must be keyed on the namespace the
1297                // record actually lives in: the same namespace
1298                // `resolve_reference`'s ring lookup uses: or admission and
1299                // lookup silently diverge on any non-local `default_namespace`
1300                // config.
1301                if let Ok(ref ok_val) = result {
1302                    let admissions = crate::reference_ring::ring_admissions_for(verb, ok_val);
1303                    if !admissions.is_empty() {
1304                        let actor_key = format!("{}:{}", gate_req.actor.kind, gate_req.actor.id);
1305                        for (id, name) in admissions {
1306                            self.reference_ring.admit(
1307                                token.namespace().as_str(),
1308                                &actor_key,
1309                                id,
1310                                name,
1311                            );
1312                        }
1313                    }
1314                }
1315
1316                return result
1317                    .map_err(|error| DispatchError::after_handler(error, domain_succeeded));
1318            }
1319        }
1320
1321        // No pack owns this verb: the gate allowed it, but no dispatch runs.
1322        // Persist the deferred audit row now (duration stays at the
1323        // `Event::new` default of 0 — no dispatch occurred to measure) so an
1324        // allowed-but-unknown verb is never silently dropped from the audit
1325        // trail (matches the "no audit row is ever dropped" contract above).
1326        let failure = self.unknown_verb_error(verb);
1327        if let Some(audit) = deferred_audit.take() {
1328            if let Some(store) = &self.event_store {
1329                // Dispatch is about to return `UnknownVerb` below (no pack
1330                // owns this verb), so the persisted outcome must be `Error`,
1331                // not `Success`. `work_class` is still stamped (ADR-103
1332                // Decision (a)); `resource.cost_unit` is omitted, matching
1333                // every other errored-dispatch row.
1334                let mut storage_event = build_audit_storage_event(
1335                    &gate_req,
1336                    &audit,
1337                    EventOutcome::Error,
1338                    Some(crate::cost_unit::base_resource_payload(request_id)),
1339                );
1340                stamp_error_class(&mut storage_event, failure.audit_error_class());
1341                // Dispatch already returns `UnknownVerb` below regardless, so
1342                // — as with the deny paths above — there is no success
1343                // outcome to fold a commit failure into.
1344                let _ = append_audit_event_best_effort(
1345                    self.audit_batch.as_ref(),
1346                    store,
1347                    storage_event,
1348                    verb,
1349                    crate::audit_batch::AuditProducer::UnknownVerb,
1350                    false,
1351                )
1352                .await;
1353            }
1354        }
1355
1356        // Verb-visibility handler names, precomputed at build() time (internal
1357        // subhandlers are excluded so they are not advertised in the
1358        // unknown-verb error).
1359        Err(DispatchError::before_dispatch(failure))
1360    }
1361
1362    /// Dispatch a verb under an out-of-band verified actor identity.
1363    ///
1364    /// `verified_actor` is a typed [`VerifiedActor`] (constructor rejects blank
1365    /// identifiers) — only code holding a `VerbRegistry` handle can supply it.
1366    /// `dispatch_as` never reads `params["actor"]` to derive the effective actor;
1367    /// individual verbs may still accept an `actor` field for their own documented
1368    /// business semantics, unrelated to the acting principal. Every pack handler
1369    /// that reads "who is calling" resolves it from the `NamespaceToken` the
1370    /// dispatch boundary mints, so `verified_actor` becomes exactly the principal
1371    /// those handlers observe.
1372    ///
1373    /// Equivalent to `dispatch_with_identity(verb, params, Some(identity))` with
1374    /// `identity.actor_id = Some(verified_actor)` and every other identity scalar
1375    /// (namespace, visible namespaces) left at this registry's construction-baked
1376    /// value. [`Self::dispatch`] and [`Self::dispatch_with_identity`] are unaffected.
1377    /// See `docs/api/pack.md#dispatch_as` for the embedding-host use case and the
1378    /// blank-identifier safety rationale.
1379    pub async fn dispatch_as(
1380        &self,
1381        verb: &str,
1382        params: Value,
1383        verified_actor: VerifiedActor,
1384    ) -> Result<Value, RuntimeError> {
1385        let identity = RequestIdentity {
1386            namespace: self.default_namespace.clone(),
1387            actor_id: Some(verified_actor.into_inner()),
1388            visible_namespaces: self
1389                .visible_namespaces
1390                .iter()
1391                .map(|ns| ns.as_str().to_string())
1392                .collect(),
1393            owned_namespaces: self
1394                .owned_namespaces
1395                .iter()
1396                .map(|ns| ns.as_str().to_string())
1397                .collect(),
1398            process_ref: crate::config::process_ref_from_env(),
1399            request_id: None,
1400        };
1401        self.dispatch_with_identity(verb, params, Some(identity))
1402            .await
1403    }
1404}