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