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` and `git.log` dispatch that same check,
504 /// so their read results also carry a required decision write.
505 /// - `comm.withheld_body` writes an access audit event on every call;
506 /// the record of who read a withheld original is the point of the
507 /// verb, so its accounting row is never droppable.
508 ///
509 /// What membership here means, precisely: the verb performs no domain
510 /// mutation, so its OWN per-dispatch audit/accounting row may be dropped
511 /// under transient admission pressure without the caller losing a
512 /// meaningful result (ADR-103 Amendment 3, ADR-133 Amendment 1). It does
513 /// NOT mean the handler is free of every event-plane write: `search`
514 /// still fires its own best-effort `SearchExecuted` telemetry, and
515 /// `context` still records a one-time `ConfigLocked` event, both on
516 /// independent code paths this mechanism never touches — those events
517 /// commit or fail on their own terms, unaffected by whether this
518 /// dispatch's own audit row degrades.
519 ///
520 /// Every entry here MUST be declared `VerbCategory::Assertive` in its
521 /// named pack's live vocabulary. The
522 /// `admission_degrade_safe_assertive_census_matches_live_pack_sources`
523 /// test below scans every pack that currently declares public Assertive
524 /// handlers and requires every such handler to be classified exactly
525 /// once as safe or as a known incidental writer. A new Assertive verb
526 /// therefore fails closed both at runtime and in the source census until
527 /// it receives an explicit side-effect review.
528 ///
529 /// Entries are `(owning pack name, verb)` pairs, not bare verb names:
530 /// [`Self::admission_degrade_safe`] requires the handler actually
531 /// resolved for `verb` to belong to the exact pack named here. A verb
532 /// name alone is not a sound key — any pack registered through the same
533 /// [`PackRegistry`]/[`VerbRegistryBuilder`] path can declare a handler
534 /// under any name it likes, including one that collides with a name on
535 /// this list, and unique-verb-name validation only rejects that
536 /// collision when the real owning pack is *also* loaded. A deployment
537 /// that omits the real pack (or loads a third-party pack instead) would
538 /// let a same-named write-performing handler inherit degrade-safety it
539 /// never earned. Binding to the pack closes that gap.
540 pub(super) const ADMISSION_DEGRADE_SAFE_VERBS: &'static [(&'static str, &'static str)] = &[
541 // agent
542 ("agent", "agent.observe"),
543 // exec (reads of the blob store, the run receipt and event tables, or
544 // the resolved configuration; the writers are exec.tree and
545 // exec.tree_put, Declarations, and exec.run, a Directive)
546 ("exec", "exec.tree_get"),
547 ("exec", "exec.tree_diff"),
548 ("exec", "exec.receipt"),
549 ("exec", "exec.runs"),
550 ("exec", "exec.events"),
551 ("exec", "exec.identity"),
552 // git
553 // Canonical get project check plus bounded cursor SELECT; no domain writes.
554 ("git", "git.ingest_cursor"),
555 // blob
556 ("blob", "blob.get"),
557 ("blob", "blob.stat"),
558 // brain
559 ("brain", "brain.event_counts"),
560 ("brain", "brain.event_page"),
561 ("brain", "brain.profiles"),
562 ("brain", "brain.profile"),
563 ("brain", "brain.resolve"),
564 ("brain", "brain.bindings"),
565 // charter (SQL reader only; compile reads the phrase registry and
566 // writes nothing, the other writers are Declarations and Directives)
567 ("charter", "charter.compile"),
568 ("charter", "charter.get"),
569 ("charter", "charter.list"),
570 ("charter", "charter.runs"),
571 ("charter", "charter.waiting"),
572 // Registered rollback-mode map reads: no domain or maintenance writes.
573 ("code", "code.deps"),
574 ("code", "code.list"),
575 ("code", "code.search"),
576 // comm
577 ("comm", "comm.delivered"),
578 ("comm", "comm.transport_status"),
579 ("comm", "comm.inbox"),
580 ("comm", "comm.unread"),
581 ("comm", "comm.thread"),
582 ("comm", "comm.health"),
583 ("comm", "comm.probe"),
584 // gtd
585 ("gtd", "gtd.census"),
586 ("gtd", "gtd.counts"),
587 ("gtd", "gtd.next"),
588 ("gtd", "gtd.tasks"),
589 // kg
590 ("kg", "get"),
591 ("kg", "list"),
592 ("kg", "stats"),
593 ("kg", "count"),
594 ("kg", "search"),
595 ("kg", "neighbors"),
596 ("kg", "traverse"),
597 ("kg", "context"),
598 ("kg", "query"),
599 ("kg", "resolve"),
600 ("kg", "whoami"),
601 // schema reports the loaded vocabulary and the declared endpoint
602 // matrix from the registry's in-memory declarations: no store read,
603 // no store write, no event.
604 ("kg", "schema"),
605 // scan runs the secret gate over caller-supplied text in process: no
606 // store read, no store write, no event.
607 ("kg", "scan"),
608 ("kg", "verbs"),
609 ("kg", "stream.read"),
610 ("kg", "stream.stat"),
611 // knowledge (ANN-maintaining search/suggest/compose are excluded)
612 ("knowledge", "knowledge.get"),
613 ("knowledge", "knowledge.list"),
614 ("knowledge", "knowledge.export"),
615 ("knowledge", "knowledge.stats"),
616 ("knowledge", "knowledge.fold"),
617 ("knowledge", "knowledge.topic"),
618 // moodboard
619 ("moodboard", "moodboard.model"),
620 ("moodboard", "moodboard.search"),
621 ("moodboard", "moodboard.preference"),
622 // schedule
623 ("schedule", "schedule.agenda"),
624 // session
625 ("session", "session.list"),
626 ("session", "session.resume"),
627 ("session", "session.export"),
628 ("session", "session.search"),
629 // Fixed SQL reads and file metadata only; no domain or maintenance write.
630 ("session", "session.stats"),
631 // tool (registry, grant and policy reads; tool.suggest runs the same
632 // hybrid search as the kg search and context verbs above)
633 ("tool", "tool.suggest"),
634 ("tool", "tool.describe"),
635 ("tool", "tool.list"),
636 ("tool", "tool.requests"),
637 ("tool", "tool.policies"),
638 ];
639
640 /// Sorted copy of [`Self::ADMISSION_DEGRADE_SAFE_VERBS`], built once, so
641 /// [`VerbRegistryBuilder::build`] can decide each trusted handler's
642 /// eligibility with a binary search instead of a linear scan over every
643 /// entry. Consulted exactly once per registry, at `build()` time — see
644 /// [`Self::admission_degrade_safe`] for why no per-dispatch scan exists
645 /// anymore. The source list above stays grouped by pack (with a `//
646 /// <pack>` comment per group) for human review; this is a derived,
647 /// lookup-shaped view of the same data, not a second source of truth.
648 pub(super) fn admission_degrade_safe_sorted() -> &'static [(&'static str, &'static str)] {
649 static SORTED: std::sync::LazyLock<Vec<(&'static str, &'static str)>> =
650 std::sync::LazyLock::new(|| {
651 let mut pairs = VerbRegistry::ADMISSION_DEGRADE_SAFE_VERBS.to_vec();
652 pairs.sort_unstable();
653 pairs
654 });
655 &SORTED
656 }
657
658 /// Whether `verb` is both declared [`VerbCategory::Assertive`] (the
659 /// speech-act tag for handlers that "retrieve and present facts" rather
660 /// than committing a domain change) AND explicitly opted in to
661 /// admission-pressure audit degradation via
662 /// [`Self::ADMISSION_DEGRADE_SAFE_VERBS`] under the exact pack that
663 /// registered it, AND declared by a pack the composition root actually
664 /// vouches for (see [`VerbRegistryBuilder::register_boxed`]'s doc).
665 /// Unknown, non-opted-in, wrong-pack, or untrusted-pack verbs are
666 /// conservatively `false` — fail-closed, so a new Assertive handler (or
667 /// one registered by a pack other than the one the allowlist names, or
668 /// one registered through [`VerbRegistryBuilder::register`] rather than
669 /// the trusted path) hard-fails its audit obligation like any write
670 /// until someone deliberately reviews it and adds it to the allowlist.
671 ///
672 /// `pack.name()` is a value the `PackRuntime` trait object reports about
673 /// itself — any pack registered through the public
674 /// [`VerbRegistryBuilder::register`] path can claim any name, including
675 /// one on the allowlist, whether or not the pack that name actually
676 /// belongs to is also loaded (verb names are unique per registry, so an
677 /// impostor's same-named handler is only reachable when the real pack
678 /// is absent). Binding eligibility to registration-time trust — decided
679 /// by the *caller*, never by the pack instance — is why this checks
680 /// `degrade_safe_verbs` rather than resolving `pack.name()` at query
681 /// time; [`VerbRegistryBuilder::build`] already excluded every untrusted
682 /// pack's handlers from that set.
683 ///
684 /// The whole decision is precomputed once in `VerbRegistryBuilder::build`
685 /// into [`VerbRegistry::degrade_safe_verbs`] — a verb name is unique
686 /// across `Visibility::Verb` handlers within one registry
687 /// (`validate_unique_verb_names`), so this is a single hash-set lookup,
688 /// not a per-dispatch scan over every registered pack's handler list.
689 ///
690 /// Used only to decide whether a dispatch's own audit-obligation row may
691 /// degrade to best-effort on transient audit-lane admission pressure
692 /// (`append_audit_event_best_effort`) — a read that performed no domain
693 /// write must not fail the caller just because the audit lane is
694 /// momentarily saturated. Never used for permission checking, transport
695 /// routing, or return-shape selection.
696 pub(super) fn admission_degrade_safe(&self, verb: &str) -> bool {
697 self.degrade_safe_verbs.contains(verb)
698 }
699
700 /// Transport replay eligibility from the shared operation-effects table,
701 /// restricted to trusted canonical public handlers. A read that persists a
702 /// fresh serve or telemetry row is excluded because the request id is
703 /// correlation, not deduplication.
704 /// Custom and mounted handlers cannot inherit safety from a name/category.
705 pub fn is_read_replay_safe(&self, verb: &str) -> bool {
706 self.read_replay_safe_verbs.contains(verb)
707 }
708
709 /// White-box accessor for [`Self::admission_degrade_safe`], needed
710 /// because the admission-pressure regression tests in
711 /// `tests/read_verb_admission_exhaustion.rs` compile as a separate
712 /// external binary and cannot reach a crate-private method directly —
713 /// the same reason [`audit_admission_refused_obligation_count`] and
714 /// `AuditBatch::test_snapshot` are `pub` rather than `pub(crate)`.
715 #[cfg(any(test, feature = "test-internals"))]
716 pub fn admission_degrade_safe_probe(&self, verb: &str) -> bool {
717 self.admission_degrade_safe(verb)
718 }
719}