Skip to main content

khive_runtime/pack/
dispatch.rs

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