Skip to main content

khive_runtime/pack/
registry_access.rs

1use std::sync::Arc;
2
3use khive_gate::{GateDecision, GateRequest};
4use khive_storage::EventStore;
5use khive_types::{EventOutcome, Namespace};
6use serde_json::Value;
7
8use crate::error::RuntimeError;
9use crate::runtime::NamespaceToken;
10use crate::KhiveRuntime;
11
12use super::{
13    append_audit_event_best_effort, audit_admission_refused_obligation_count,
14    audit_admission_refused_obligation_last_at_ms, audit_admission_unresolved_obligation_count,
15    audit_admission_unresolved_obligation_last_at_ms, audit_retry_exhausted_obligation_count,
16    audit_retry_exhausted_obligation_last_at_ms, build_audit_storage_event, fold_audit_obligation,
17    masked_audit_event, VerbRegistry, AUDIT_PERSISTENCE_SKIPPED_READ_ONLY,
18};
19#[cfg(doc)]
20use super::{PackRegistry, RequestIdentity, VerbCategory, VerbRegistryBuilder};
21
22impl VerbRegistry {
23    /// Intercept registered search with the ordinary registry's read projection.
24    ///
25    /// The existing intercept owns authorization and audit exactly once. Its
26    /// coordinator read projection remains unchanged; this callback preserves
27    /// the ordinary registry's local primary and implicit actor visibility.
28    /// Missing or disabled owners fall through to ordinary dispatch unchanged.
29    pub async fn dispatch_search_with_registry_scope<'a, M, F, Fut>(
30        &'a self,
31        params: &serde_json::Value,
32        identity: Option<&crate::RequestIdentity>,
33        dispatch: F,
34    ) -> Option<Result<crate::InterceptedDispatchResult<M>, crate::DispatchError>>
35    where
36        F: FnOnce(&'a dyn crate::PackRuntime, crate::NamespaceToken) -> Fut,
37        Fut: std::future::Future<
38            Output = Result<crate::InterceptedDispatchResult<M>, crate::RuntimeError>,
39        >,
40    {
41        if self.is_verb_disabled("search") {
42            return None;
43        }
44        let owner: &'a dyn crate::PackRuntime = self
45            .packs
46            .iter()
47            .find(|pack| {
48                pack.handlers()
49                    .iter()
50                    .any(|handler| handler.name == "search")
51            })?
52            .as_ref();
53        Some(
54            self.dispatch_intercepted_with_token_and_disposition(
55                "search",
56                params,
57                identity,
58                move |gate_token| async move {
59                    let token = if gate_token.gate_explicit_namespace().is_some() {
60                        gate_token
61                    } else {
62                        let mut visible = match identity {
63                            Some(identity) => identity
64                                .visible_namespaces
65                                .iter()
66                                .filter_map(|namespace| Namespace::parse(namespace).ok())
67                                .collect(),
68                            None => self.visible_namespaces.clone(),
69                        };
70                        if let Some(namespace) = gate_token
71                            .actor()
72                            .binding_id()
73                            .filter(|id| *id != Namespace::LOCAL)
74                            .and_then(|id| Namespace::parse(id).ok())
75                        {
76                            visible.push(namespace);
77                        }
78                        visible.push(Namespace::local());
79                        NamespaceToken::mint_with_visibility(
80                            Namespace::local(),
81                            visible,
82                            gate_token.actor().clone(),
83                        )
84                        .with_gate_namespace(gate_token.gate_namespace().clone())
85                        .with_gate_explicit_namespace(
86                            gate_token.gate_explicit_namespace().map(str::to_owned),
87                        )
88                        .with_request_id(gate_token.request_id())
89                        .with_owned_namespaces(gate_token.owned_namespaces().to_vec())
90                        .with_process_ref(gate_token.process_ref().map(str::to_owned))
91                    };
92                    dispatch(owner, token).await
93                },
94            )
95            .await,
96        )
97    }
98
99    /// Select the owning pack's backend for a note-kind KG read. The caller
100    /// keeps its already-authorized token; this only selects storage.
101    pub fn kg_note_read_runtime_for_kind<'a>(
102        &'a self,
103        runtime: &'a KhiveRuntime,
104        kind: &str,
105    ) -> &'a KhiveRuntime {
106        let Some(resolver) = &self.kg_read_resolver else {
107            return runtime;
108        };
109        let Some(owner) = self
110            .packs
111            .iter()
112            .find(|pack| pack.note_kinds().contains(&kind))
113        else {
114            return runtime;
115        };
116        resolver.runtime_for_pack(owner.name())
117    }
118
119    /// Resolve a KG entity/note handle across the configured backend inventory.
120    ///
121    /// The caller must supply its dispatch-authorized token. By-ID reads do not
122    /// filter the stored namespace (ADR-007); no new token is minted here. With
123    /// ordinary single-runtime registration, retain the supplied runtime's
124    /// existing behavior. This does not route mutations or pack-private records.
125    pub async fn resolve_kg_read_by_id(
126        &self,
127        runtime: &KhiveRuntime,
128        token: &NamespaceToken,
129        id: uuid::Uuid,
130        include_deleted: bool,
131    ) -> Result<Option<crate::Resolved>, RuntimeError> {
132        match &self.kg_read_resolver {
133            Some(resolver) => resolver.by_id(token, id, include_deleted).await,
134            None if include_deleted => runtime.resolve_by_id_including_deleted(token, id).await,
135            None => runtime.resolve_by_id(token, id).await,
136        }
137    }
138
139    /// Find the unique configured backend holding an entity for deletion.
140    /// Includes tombstones so soft deletion cannot hide a duplicate owner.
141    /// The dispatch-authorized token is preserved; lookup is namespace-agnostic.
142    pub async fn resolve_entity_delete_runtime(
143        &self,
144        runtime: &KhiveRuntime,
145        token: &NamespaceToken,
146        id: uuid::Uuid,
147    ) -> Result<Option<KhiveRuntime>, RuntimeError> {
148        match &self.kg_read_resolver {
149            Some(resolver) => resolver.entity_runtime(token, id).await,
150            None => {
151                let store = runtime.entities(token)?;
152                let entity = store.get_entity_including_deleted(id).await?;
153                Ok(entity.map(|_| runtime.clone()))
154            }
155        }
156    }
157
158    /// Clean main-backend attachments after no live or tombstoned owner remains.
159    /// A live or tombstoned entity on any configured backend keeps its roots.
160    pub async fn cleanup_deleted_entity_attachments(
161        &self,
162        runtime: &KhiveRuntime,
163        token: &NamespaceToken,
164        id: uuid::Uuid,
165    ) -> Result<bool, RuntimeError> {
166        if self
167            .resolve_entity_delete_runtime(runtime, token, id)
168            .await?
169            .is_some()
170        {
171            return Ok(false);
172        }
173        runtime.delete_entity_attachments_on_core(id).await
174    }
175
176    /// Recheck a merged-entity read against the kept id before returning it.
177    /// The submitted argument shape is the verb's ordinary shape with the
178    /// effective id substituted. The dispatch's original check remains its
179    /// own audit row; this consultation records the effective target as a
180    /// second row without changing the public GateRequest schema.
181    pub async fn authorize_effective_kg_read(
182        &self,
183        token: &NamespaceToken,
184        verb: &str,
185        mut effective_args: Value,
186        effective_id: uuid::Uuid,
187    ) -> Result<(), RuntimeError> {
188        if let Some(namespace) = token.gate_explicit_namespace() {
189            effective_args["namespace"] = Value::String(namespace.to_owned());
190        }
191        let gate_req = GateRequest::new(
192            token.actor().clone(),
193            token.gate_namespace().clone(),
194            verb,
195            effective_args,
196        );
197        self.authorize_secondary_kg_operation(token, gate_req, Some(effective_id))
198            .await
199    }
200
201    /// Check the canonical wrapper for a proposal worker using its applying caller.
202    pub async fn authorize_canonical_changeset(
203        &self,
204        token: &NamespaceToken,
205        delta: &str,
206    ) -> Result<(), RuntimeError> {
207        let verb = "apply_changeset";
208        if self.is_verb_disabled(verb) {
209            return Err(self.unknown_verb_error(verb));
210        }
211        let mut args = serde_json::json!({"delta": delta});
212        if let Some(namespace) = token.gate_explicit_namespace() {
213            args["namespace"] = Value::String(namespace.to_owned());
214        }
215        let request = GateRequest::new(
216            token.actor().clone(),
217            token.gate_namespace().clone(),
218            verb,
219            args,
220        );
221        self.authorize_secondary_kg_operation(token, request, None)
222            .await
223    }
224
225    pub(crate) async fn authorize_canonical_operation(
226        &self,
227        token: &NamespaceToken,
228        verb: &str,
229        mut args: Value,
230        target_id: uuid::Uuid,
231    ) -> Result<NamespaceToken, RuntimeError> {
232        if !matches!(verb, "create" | "link" | "update" | "delete") {
233            return Err(RuntimeError::InvalidInput(
234                "unsupported canonical constituent verb".into(),
235            ));
236        }
237        if self.is_verb_disabled(verb) {
238            return Err(self.unknown_verb_error(verb));
239        }
240        if args.get("namespace").is_none() {
241            if let Some(namespace) = token.gate_explicit_namespace() {
242                args["namespace"] = Value::String(namespace.to_owned());
243            }
244        }
245        let namespace = match args.get("namespace") {
246            Some(Value::String(value)) => Namespace::parse(value)
247                .map_err(|_| RuntimeError::InvalidInput("invalid namespace".into()))?,
248            Some(_) => return Err(RuntimeError::InvalidInput("invalid namespace".into())),
249            None => token.gate_namespace().clone(),
250        };
251        let request =
252            GateRequest::new(token.actor().clone(), namespace.clone(), verb, args.clone());
253        self.authorize_secondary_kg_operation(token, request, Some(target_id))
254            .await?;
255        Ok(token
256            .with_namespace(namespace.clone())
257            .with_gate_namespace(namespace)
258            .with_gate_explicit_namespace(
259                args.get("namespace")
260                    .and_then(Value::as_str)
261                    .map(str::to_owned),
262            )
263            .with_request_id(token.request_id()))
264    }
265
266    async fn authorize_secondary_kg_operation(
267        &self,
268        token: &NamespaceToken,
269        gate_req: GateRequest,
270        effective_id: Option<uuid::Uuid>,
271    ) -> Result<(), RuntimeError> {
272        let verb = gate_req.verb.as_str();
273        let decision = khive_gate::check_with_mailbox_policy(self.gate.as_ref(), &gate_req);
274        match decision {
275            Ok(decision) => {
276                let audit = masked_audit_event(&gate_req, &decision, self.gate.impl_name());
277                tracing::info!(
278                    audit_event = %serde_json::to_string(&audit)
279                        .unwrap_or_else(|_| "{\"error\":\"serialize\"}".into()),
280                    effective_target_id = ?effective_id,
281                    "gate.check"
282                );
283                let denied = matches!(&decision, GateDecision::Deny { .. });
284                let receipt = if let Some(store) = &self.event_store {
285                    let mut event = build_audit_storage_event(
286                        &gate_req,
287                        &audit,
288                        if denied {
289                            EventOutcome::Denied
290                        } else {
291                            EventOutcome::Success
292                        },
293                        Some(crate::cost_unit::base_resource_payload(token.request_id())),
294                    );
295                    if let Some(id) = effective_id {
296                        event = event.with_target(id);
297                    }
298                    if denied {
299                        self.append_gate_denied_row(store, event, verb).await
300                    } else {
301                        let outcome = append_audit_event_best_effort(
302                            self.audit_batch.as_ref(),
303                            store,
304                            event,
305                            verb,
306                            crate::audit_batch::AuditProducer::EffectiveTargetCheck,
307                            false,
308                        )
309                        .await;
310                        fold_audit_obligation(Ok(()), outcome, |_| Value::Null)?;
311                        crate::error::DenialReceipt::no_store()
312                    }
313                } else {
314                    crate::error::DenialReceipt::no_store()
315                };
316                match decision {
317                    GateDecision::Allow { .. } => Ok(()),
318                    GateDecision::Deny { reason } => Err(RuntimeError::PermissionDenied {
319                        verb: verb.to_string(),
320                        reason,
321                        receipt: Box::new(receipt),
322                    }),
323                }
324            }
325            Err(error) => Err(self
326                .gate_unavailable_error(&gate_req, &error, token.request_id(), effective_id)
327                .await),
328        }
329    }
330
331    /// Resolve a prefix across the same inventory, rejecting distinct UUIDs.
332    ///
333    /// Retains the local prefix scanner's entity/note/event/edge collision domain,
334    /// including sidecar events. The returned UUID is not a substrate assertion:
335    /// consumers must still fetch/type-check it. All backend failures propagate.
336    pub async fn resolve_kg_read_prefix(
337        &self,
338        runtime: &KhiveRuntime,
339        _token: &NamespaceToken,
340        prefix: &str,
341        include_deleted: bool,
342    ) -> Result<Option<uuid::Uuid>, RuntimeError> {
343        match &self.kg_read_resolver {
344            Some(resolver) => resolver.prefix(prefix, include_deleted).await,
345            None if include_deleted => {
346                runtime
347                    .resolve_prefix_unfiltered_including_deleted(prefix)
348                    .await
349            }
350            None => runtime.resolve_prefix_unfiltered(prefix).await,
351        }
352    }
353
354    /// This registry's construction-baked default namespace.
355    ///
356    /// Used as the fallback when a request carries no [`RequestIdentity`]
357    /// override (ADR-096 Fork 1) and by transports that need to advertise
358    /// their own resolved identity when forwarding to a warm daemon.
359    pub fn default_namespace(&self) -> &str {
360        &self.default_namespace
361    }
362
363    /// This registry's construction-baked actor identity label, if configured
364    /// (ADR-057). `None` means dispatch mints `ActorRef::anonymous()` absent a
365    /// per-request [`RequestIdentity`] override (ADR-096 Fork 1).
366    pub fn actor_id(&self) -> Option<&str> {
367        self.actor_id.as_deref()
368    }
369
370    /// This registry's construction-baked extra read-visibility namespaces
371    /// (ADR-007 Rev 4 Rule 3b), used absent a per-request [`RequestIdentity`]
372    /// override (ADR-096 Fork 1).
373    pub fn visible_namespaces(&self) -> &[Namespace] {
374        &self.visible_namespaces
375    }
376
377    /// This registry's construction-baked `[actor] owned_namespaces`
378    /// (ADR-021 Delta 1), used absent a per-request [`RequestIdentity`]
379    /// override. Declared by the caller, never inferred; read only by the
380    /// `memory.apply_batch` old-row namespace check.
381    pub fn owned_namespaces(&self) -> &[Namespace] {
382        &self.owned_namespaces
383    }
384
385    /// This registry's configured audit `EventStore`, if any (ADR-094).
386    ///
387    /// Lets background tasks that hold a `VerbRegistry` but do not go through
388    /// `dispatch` (e.g. the email channel poll loop) append best-effort
389    /// lifecycle events to the same sink gate-check audit rows use, without
390    /// threading a second `Option<Arc<dyn EventStore>>` field through every
391    /// caller. `None` means either the historical tracing-only default or an
392    /// intentionally read-only audit backend; callers that need to distinguish
393    /// those cases use [`Self::audit_persistence_advisory`].
394    pub fn event_store(&self) -> Option<Arc<dyn EventStore>> {
395        self.event_store.clone()
396    }
397
398    /// Process-lifetime audit-batch health counters for this registry's
399    /// ADR-133 seam, if one is configured. `None` exactly when
400    /// [`Self::event_store`] is `None` — the same condition under which no
401    /// batch exists to report on. The `db_diagnostics` verb feeds this into
402    /// `KhiveRuntime::db_diagnostics_with_audit_metrics` so an operator can
403    /// see flush failures and pure-observability degradation instead of the
404    /// permanently-unavailable placeholder a bare `KhiveRuntime` reports.
405    ///
406    /// `admission_refused_obligations`, `retry_exhausted_obligations`,
407    /// and `admission_unresolved_obligations`
408    /// are sourced separately from [`audit_admission_refused_obligation_count`],
409    /// [`audit_retry_exhausted_obligation_count`], and
410    /// [`audit_admission_unresolved_obligation_count`] rather than from
411    /// `batch.health_metrics()`: they count a decision made in
412    /// `append_audit_event_best_effort` (ADR-103 Amendment 3 / ADR-133
413    /// Amendment 1), not a property of the batch itself, so they are
414    /// process-wide like the rest of this struct's fields rather than
415    /// per-`AuditBatch`.
416    pub fn audit_batch_metrics(&self) -> Option<khive_db::diagnostics::RuntimeAuditBatchMetrics> {
417        self.audit_batch.as_ref().map(|batch| {
418            let m = batch.health_metrics();
419            khive_db::diagnostics::RuntimeAuditBatchMetrics {
420                flush_failures: m.flush_failures,
421                degraded_rows: m.degraded_rows,
422                degraded: m.degraded,
423                admission_refused_obligations: audit_admission_refused_obligation_count(),
424                admission_refused_obligations_last_at_ms:
425                    audit_admission_refused_obligation_last_at_ms(),
426                retry_exhausted_obligations: audit_retry_exhausted_obligation_count(),
427                retry_exhausted_obligations_last_at_ms: audit_retry_exhausted_obligation_last_at_ms(
428                ),
429                admission_unresolved_obligations: audit_admission_unresolved_obligation_count(),
430                admission_unresolved_obligations_last_at_ms:
431                    audit_admission_unresolved_obligation_last_at_ms(),
432                audit_success_rows_omitted: self.audit_success_rows_omitted_counts(),
433                audit_success_rows_sampled_out: self.audit_success_rows_sampled_out_counts(),
434                audit_success_rows_forced: self.audit_success_rows_forced_counts(),
435            }
436        })
437    }
438
439    /// This registry's shared ADR-133 audit-batch seam. The recall handler
440    /// uses this same instance for its best-effort `RecallExecuted` rows.
441    /// `None` when no `EventStore` was configured (the batch is constructed
442    /// from one). Admission-pressure mechanism tests also use it so they
443    /// can saturate and drain the SAME instance a real dispatch uses
444    /// (#2117, #2147, #2208, #2217) instead of testing a
445    /// look-alike.
446    pub fn audit_batch_handle(&self) -> Option<Arc<crate::audit_batch::AuditBatch>> {
447        self.audit_batch.clone()
448    }
449
450    /// Stop admitting new audit rows and wait for every already-accepted row
451    /// to reach a terminal state (ADR-133).
452    ///
453    /// A no-op returning `Ok(())` when no `EventStore` — and therefore no
454    /// audit-batch seam — is configured. Callers that own this registry's
455    /// shutdown sequence should call this before tearing down the writer or
456    /// database so no accepted audit row is silently dropped mid-flight.
457    pub async fn shutdown_audit_batch(
458        &self,
459    ) -> Result<(), crate::audit_batch::AuditTerminalReason> {
460        use crate::audit_batch::AuditBatchControl;
461        match &self.audit_batch {
462            Some(audit_batch) => audit_batch.close_and_drain().await,
463            None => Ok(()),
464        }
465    }
466
467    /// Advisory for a dispatch whose configured audit sink is read-only.
468    ///
469    /// The MCP transport places this beside successful per-operation results;
470    /// `None` means audit persistence is configured normally or was never
471    /// configured at all.
472    pub fn audit_persistence_advisory(&self) -> Option<Value> {
473        self.audit_store_read_only.then(|| {
474            serde_json::json!({
475                "code": AUDIT_PERSISTENCE_SKIPPED_READ_ONLY,
476                "severity": "warning",
477                "component": "audit_event_store",
478                "reason": "read_only_backend",
479                "message": "operation completed, but its dispatch audit event was not persisted because the audit backend is read-only",
480            })
481        })
482    }
483
484    /// Explicit, fail-closed opt-in for admission-pressure audit degradation
485    /// (#2147/#2217). `VerbCategory::Assertive` alone is NOT a
486    /// sound proxy for "safe to drop this dispatch's own audit row under
487    /// audit-lane admission pressure": several Assertive handlers have
488    /// their own durable or accounting-bearing side effects. The reviewed
489    /// exclusions are:
490    /// - `memory.recall` dispatches `brain.record_serve` as a background
491    ///   write; degrading `memory.recall`'s row raises the risk that a
492    ///   serve goes unaccounted for if the ledger dispatch itself later
493    ///   also races admission pressure.
494    /// - `db_diagnostics` may backfill WAL frames via a PASSIVE checkpoint
495    ///   probe — physical I/O, not a pure in-memory read.
496    /// - `knowledge.search`, `knowledge.suggest`, and auto
497    ///   `knowledge.compose` may start persistent ANN consumer/checkpoint
498    ///   maintenance from their nominal read path.
499    /// - `git.checkout`, `git.diff` and `git.reconcile` persist a durable
500    ///   receipt on every dispatch (checkout and diff also write a manifest
501    ///   or diff blob), so their accounting row is not droppable.
502    /// - `tool.check` persists a policy decision receipt. `git.receipts`,
503    ///   `git.gates`, `git.status`, `git.log` and `git.pr_state` dispatch that same check,
504    ///   so their read results also carry a required decision write.
505    /// - `exec.tree_diff` writes the full change list as a blob whenever its
506    ///   reply cuts the list (ADR-181 Amendment 18), so a read result can
507    ///   carry a required write.
508    /// - `comm.withheld_body` writes an access audit event on every call;
509    ///   the record of who read a withheld original is the point of the
510    ///   verb, so its accounting row is never droppable.
511    ///
512    /// What membership here means, precisely: the verb performs no domain
513    /// mutation, so its OWN per-dispatch audit/accounting row may be dropped
514    /// under transient admission pressure without the caller losing a
515    /// meaningful result (ADR-103 Amendment 3, ADR-133 Amendment 1). It does
516    /// NOT mean the handler is free of every event-plane write: `search`
517    /// still fires its own best-effort `SearchExecuted` telemetry, and
518    /// `context` still records a one-time `ConfigLocked` event, both on
519    /// independent code paths this mechanism never touches — those events
520    /// commit or fail on their own terms, unaffected by whether this
521    /// dispatch's own audit row degrades.
522    ///
523    /// Every entry here MUST be declared `VerbCategory::Assertive` in its
524    /// named pack's live vocabulary. The
525    /// `admission_degrade_safe_assertive_census_matches_live_pack_sources`
526    /// test below scans every pack that currently declares public Assertive
527    /// handlers and requires every such handler to be classified exactly
528    /// once as safe or as a known incidental writer. A new Assertive verb
529    /// therefore fails closed both at runtime and in the source census until
530    /// it receives an explicit side-effect review.
531    ///
532    /// Entries are `(owning pack name, verb)` pairs, not bare verb names:
533    /// [`Self::admission_degrade_safe`] requires the handler actually
534    /// resolved for `verb` to belong to the exact pack named here. A verb
535    /// name alone is not a sound key — any pack registered through the same
536    /// [`PackRegistry`]/[`VerbRegistryBuilder`] path can declare a handler
537    /// under any name it likes, including one that collides with a name on
538    /// this list, and unique-verb-name validation only rejects that
539    /// collision when the real owning pack is *also* loaded. A deployment
540    /// that omits the real pack (or loads a third-party pack instead) would
541    /// let a same-named write-performing handler inherit degrade-safety it
542    /// never earned. Binding to the pack closes that gap.
543    pub(super) const ADMISSION_DEGRADE_SAFE_VERBS: &'static [(&'static str, &'static str)] = &[
544        // agent
545        ("agent", "agent.observe"),
546        // exec (reads of the blob store, the run receipt and event tables, or
547        // the resolved configuration; the writers are exec.tree and
548        // exec.tree_put, Declarations, and exec.run, a Directive; exec.tree_diff
549        // writes a change-list blob when it cuts the list, so it is not here)
550        ("exec", "exec.tree_get"),
551        ("exec", "exec.receipt"),
552        ("exec", "exec.runs"),
553        ("exec", "exec.events"),
554        ("exec", "exec.identity"),
555        // git
556        // Canonical get project check plus bounded cursor SELECT; no domain writes.
557        ("git", "git.ingest_cursor"),
558        // blob
559        ("blob", "blob.get"),
560        ("blob", "blob.stat"),
561        // brain
562        ("brain", "brain.event_counts"),
563        ("brain", "brain.event_page"),
564        ("brain", "brain.profiles"),
565        ("brain", "brain.profile"),
566        ("brain", "brain.resolve"),
567        ("brain", "brain.bindings"),
568        // charter (SQL reader only; compile reads the phrase registry and
569        // writes nothing, the other writers are Declarations and Directives)
570        ("charter", "charter.compile"),
571        ("charter", "charter.get"),
572        ("charter", "charter.list"),
573        ("charter", "charter.runs"),
574        ("charter", "charter.waiting"),
575        // Registered rollback-mode map reads: no domain or maintenance writes.
576        ("code", "code.deps"),
577        ("code", "code.list"),
578        ("code", "code.search"),
579        // comm
580        ("comm", "comm.delivered"),
581        ("comm", "comm.transport_status"),
582        ("comm", "comm.inbox"),
583        ("comm", "comm.unread"),
584        ("comm", "comm.thread"),
585        ("comm", "comm.health"),
586        ("comm", "comm.probe"),
587        // gtd
588        ("gtd", "gtd.census"),
589        ("gtd", "gtd.counts"),
590        ("gtd", "gtd.next"),
591        ("gtd", "gtd.tasks"),
592        // kg
593        ("kg", "get"),
594        ("kg", "list"),
595        ("kg", "stats"),
596        ("kg", "count"),
597        ("kg", "search"),
598        ("kg", "neighbors"),
599        ("kg", "traverse"),
600        ("kg", "context"),
601        ("kg", "query"),
602        ("kg", "resolve"),
603        ("kg", "whoami"),
604        // schema reports the loaded vocabulary and the declared endpoint
605        // matrix from the registry's in-memory declarations: no store read,
606        // no store write, no event.
607        ("kg", "schema"),
608        // scan runs the secret gate over caller-supplied text in process: no
609        // store read, no store write, no event.
610        ("kg", "scan"),
611        ("kg", "verbs"),
612        ("kg", "stream.read"),
613        ("kg", "stream.stat"),
614        // knowledge (ANN-maintaining search/suggest/compose are excluded)
615        ("knowledge", "knowledge.get"),
616        ("knowledge", "knowledge.list"),
617        ("knowledge", "knowledge.export"),
618        ("knowledge", "knowledge.stats"),
619        ("knowledge", "knowledge.fold"),
620        ("knowledge", "knowledge.topic"),
621        // moodboard
622        ("moodboard", "moodboard.model"),
623        ("moodboard", "moodboard.search"),
624        ("moodboard", "moodboard.preference"),
625        // schedule
626        ("schedule", "schedule.agenda"),
627        // session
628        ("session", "session.list"),
629        ("session", "session.resume"),
630        ("session", "session.export"),
631        ("session", "session.search"),
632        // Fixed SQL reads and file metadata only; no domain or maintenance write.
633        ("session", "session.stats"),
634        // tool (registry, grant and policy reads; tool.suggest runs the same
635        // hybrid search as the kg search and context verbs above)
636        ("tool", "tool.suggest"),
637        ("tool", "tool.describe"),
638        ("tool", "tool.list"),
639        ("tool", "tool.requests"),
640        ("tool", "tool.policies"),
641    ];
642
643    /// Sorted copy of [`Self::ADMISSION_DEGRADE_SAFE_VERBS`], built once, so
644    /// [`VerbRegistryBuilder::build`] can decide each trusted handler's
645    /// eligibility with a binary search instead of a linear scan over every
646    /// entry. Consulted exactly once per registry, at `build()` time — see
647    /// [`Self::admission_degrade_safe`] for why no per-dispatch scan exists
648    /// anymore. The source list above stays grouped by pack (with a `//
649    /// <pack>` comment per group) for human review; this is a derived,
650    /// lookup-shaped view of the same data, not a second source of truth.
651    pub(super) fn admission_degrade_safe_sorted() -> &'static [(&'static str, &'static str)] {
652        static SORTED: std::sync::LazyLock<Vec<(&'static str, &'static str)>> =
653            std::sync::LazyLock::new(|| {
654                let mut pairs = VerbRegistry::ADMISSION_DEGRADE_SAFE_VERBS.to_vec();
655                pairs.sort_unstable();
656                pairs
657            });
658        &SORTED
659    }
660
661    /// Whether `verb` is both declared [`VerbCategory::Assertive`] (the
662    /// speech-act tag for handlers that "retrieve and present facts" rather
663    /// than committing a domain change) AND explicitly opted in to
664    /// admission-pressure audit degradation via
665    /// [`Self::ADMISSION_DEGRADE_SAFE_VERBS`] under the exact pack that
666    /// registered it, AND declared by a pack the composition root actually
667    /// vouches for (see [`VerbRegistryBuilder::register_boxed`]'s doc).
668    /// Unknown, non-opted-in, wrong-pack, or untrusted-pack verbs are
669    /// conservatively `false` — fail-closed, so a new Assertive handler (or
670    /// one registered by a pack other than the one the allowlist names, or
671    /// one registered through [`VerbRegistryBuilder::register`] rather than
672    /// the trusted path) hard-fails its audit obligation like any write
673    /// until someone deliberately reviews it and adds it to the allowlist.
674    ///
675    /// `pack.name()` is a value the `PackRuntime` trait object reports about
676    /// itself — any pack registered through the public
677    /// [`VerbRegistryBuilder::register`] path can claim any name, including
678    /// one on the allowlist, whether or not the pack that name actually
679    /// belongs to is also loaded (verb names are unique per registry, so an
680    /// impostor's same-named handler is only reachable when the real pack
681    /// is absent). Binding eligibility to registration-time trust — decided
682    /// by the *caller*, never by the pack instance — is why this checks
683    /// `degrade_safe_verbs` rather than resolving `pack.name()` at query
684    /// time; [`VerbRegistryBuilder::build`] already excluded every untrusted
685    /// pack's handlers from that set.
686    ///
687    /// The whole decision is precomputed once in `VerbRegistryBuilder::build`
688    /// into [`VerbRegistry::degrade_safe_verbs`] — a verb name is unique
689    /// across `Visibility::Verb` handlers within one registry
690    /// (`validate_unique_verb_names`), so this is a single hash-set lookup,
691    /// not a per-dispatch scan over every registered pack's handler list.
692    ///
693    /// Used only to decide whether a dispatch's own audit-obligation row may
694    /// degrade to best-effort on transient audit-lane admission pressure
695    /// (`append_audit_event_best_effort`) — a read that performed no domain
696    /// write must not fail the caller just because the audit lane is
697    /// momentarily saturated. Never used for permission checking, transport
698    /// routing, or return-shape selection.
699    pub(super) fn admission_degrade_safe(&self, verb: &str) -> bool {
700        self.degrade_safe_verbs.contains(verb)
701    }
702
703    /// Transport replay eligibility from the shared operation-effects table,
704    /// restricted to trusted canonical public handlers. A read that persists a
705    /// fresh serve or telemetry row is excluded because the request id is
706    /// correlation, not deduplication.
707    /// Custom and mounted handlers cannot inherit safety from a name/category.
708    pub fn is_read_replay_safe(&self, verb: &str) -> bool {
709        self.read_replay_safe_verbs.contains(verb)
710    }
711
712    /// White-box accessor for [`Self::admission_degrade_safe`], needed
713    /// because the admission-pressure regression tests in
714    /// `tests/read_verb_admission_exhaustion.rs` compile as a separate
715    /// external binary and cannot reach a crate-private method directly —
716    /// the same reason [`audit_admission_refused_obligation_count`] and
717    /// `AuditBatch::test_snapshot` are `pub` rather than `pub(crate)`.
718    #[cfg(any(test, feature = "test-internals"))]
719    pub fn admission_degrade_safe_probe(&self, verb: &str) -> bool {
720        self.admission_degrade_safe(verb)
721    }
722}