Skip to main content

Crate khive_runtime

Crate khive_runtime 

Source
Expand description

khive-runtime: composable Service API used by daemon, MCP server, and CLI.

Wraps StorageBackend and query compilation into a single Rust API surface.

Re-exports§

pub use actor_identity::actor_is_unattributed;
pub use actor_identity::resolve_actor;
pub use actor_identity::should_warn_unattributed_actor;
pub use agent_lifecycle::apply_transition;
pub use agent_lifecycle::spawn_fingerprint;
pub use agent_lifecycle::IllegalTransition;
pub use agent_lifecycle::Transition;
pub use agent_lifecycle::Trigger;
pub use atomic_message::create_notes_atomic_with_report;
pub use atomic_message::AtomicNoteSpec;
pub use atomic_plan::AddEntityPlan;
pub use atomic_plan::AddNotePlan;
pub use atomic_plan::AffectedRowGuard;
pub use atomic_plan::DeletePlan;
pub use atomic_plan::GovernanceOp;
pub use atomic_plan::GovernancePlan;
pub use atomic_plan::GtdCompletePlan;
pub use atomic_plan::GtdTransitionPlan;
pub use atomic_plan::LinkPlan;
pub use atomic_plan::MergePlan;
pub use atomic_plan::PlanPredicate;
pub use atomic_plan::PlanStatement;
pub use atomic_plan::PostCommitEffect;
pub use atomic_plan::UpdatePlan;
pub use atomic_runner::run_atomic_unit;
pub use atomic_runner::AtomicOpFailure;
pub use atomic_runner::AtomicOpPlan;
pub use atomic_runner::AtomicRunOutcome;
pub use atomic_runner::AtomicRunnerError;
pub use atomic_runner::CommittedPostCommitEffects;
pub use blob::resolve_blob_store;
pub use blob::resolve_blob_store_for_mode;
pub use blob::BlobHydrator;
pub use blob::GovernedBlobError;
pub use blob::VerifiedBlob;
pub use blob::DEFAULT_BLOB_HYDRATION_BYTES;
pub use build_info::BuildInfo;
pub use build_info::BUILD_INFO;
pub use build_info::BUILD_VERSION;
pub use config::ann_fresh_tail_enabled_from_env;
pub use config::process_ref_from_env;
pub use cost_unit::base_resource_payload;
pub use cost_unit::cost_unit_for_dispatch;
pub use cost_unit::resource_payload;
pub use curation::entity_embedding_text;
pub use curation::entity_fts_document;
pub use curation::entity_merge_guard_compared_values;
pub use curation::entity_merge_guard_error;
pub use curation::entity_merge_guard_refusal_message;
pub use curation::note_embedding_text;
pub use curation::note_fts_document;
pub use curation::validate_entity_merge_floor;
pub use curation::ContentMergeStrategy;
pub use curation::EdgeListFilter;
pub use curation::EdgePatch;
pub use curation::EntityDedupMergePolicy;
pub use curation::EntityMergeGuard;
pub use curation::EntityPatch;
pub use curation::GuardedNoteMerge;
pub use curation::MergeAssertion;
pub use curation::MergeEdgeConflictPreimage;
pub use curation::MergeEdgePreimage;
pub use curation::MergeSummary;
pub use curation::MergeTxBudgetReport;
pub use curation::MergeTxLimits;
pub use curation::NoteMergeGuard;
pub use curation::NotePatch;
pub use curation::NoteUpdatePolicy;
pub use daemon::acquire_recovery_lock;
pub use daemon::pid_path;
pub use daemon::run_daemon;
pub use daemon::socket_path;
pub use daemon::DaemonDispatch;
pub use daemon::active_phase_names;
pub use daemon::background_task_count;
pub use daemon::background_task_names;
pub use daemon::daemon_shutdown_token;
pub use daemon::recall_ledger_snapshot;
pub use daemon::register_active_phase;
pub use daemon::spawn_named_tracked_task;
pub use daemon::track_background_task;
pub use daemon::track_named_background_task;
pub use daemon::track_recall_ledger_task;
pub use daemon::DaemonRequestFrame;
pub use daemon::DaemonResponseFrame;
pub use daemon::PhaseGuard;
pub use daemon::PROTOCOL_VERSION;
pub use daemon::UNNAMED_BACKGROUND_TASK;
pub use email_message_id::EmailMessageIdDomains;
pub use email_message_id::HISTORICAL_DOMAINS_ENV;
pub use embedder_registry::EmbedderProvider;
pub use embedder_registry::EmbedderRegistry;
pub use embedder_registry::LatticeEmbedderProvider;
pub use engine_config::config_from_env;
pub use engine_config::resolve_wal_ceiling;
pub use engine_config::BackendConfig;
pub use engine_config::BackendKind;
pub use engine_config::BlobConfig;
pub use engine_config::BrainSectionConfig;
pub use engine_config::ConfigError;
pub use engine_config::EngineConfig;
pub use engine_config::GateSectionConfig;
pub use engine_config::GitWriteEntryConfig;
pub use engine_config::GitWriteSectionConfig;
pub use engine_config::KhiveConfig;
pub use engine_config::PackConfig;
pub use engine_config::ResolvedWalCeiling;
pub use engine_config::StorageSectionConfig;
pub use error::fts_text_leg_or_err;
pub use error::AdmissionFailureContext;
pub use error::AuditObligationFailure;
pub use error::AuditObligationReason;
pub use error::ChannelIngestFailureClass;
pub use error::DenialAuditOutcome;
pub use error::DenialReceipt;
pub use error::DispatchError;
pub use error::DomainDisposition;
pub use error::GuardedWriteFailure;
pub use error::ReceiptRefusal;
pub use error::RefusalEventContext;
pub use error::RefusalEventRecording;
pub use error::RefusalRecordingErrorClass;
pub use error::RuntimeError;
pub use error::RuntimeResult;
pub use error::WriterPoolCheckoutTimeoutContext;
pub use error::WriterTaskFailureContext;
pub use error::WRITER_ADMISSION_SCOPE;
pub use error::WRITER_POOL_CHECKOUT_TIMEOUT_STAGE;
pub use error::WRITER_QUEUE_SATURATED_STAGE;
pub use error::WRITER_TASK_REQUEST_FAILED_STAGE;
pub use error::WRITER_TASK_TERMINATED_STAGE;
pub use graph_traversal::PathNode;
pub use objectives::AmplifiedDecayAwareSalienceObjective;
pub use objectives::DecayAwareSalienceObjective;
pub use objectives::GraphProximityObjective;
pub use objectives::MemoryRecallPipeline;
pub use objectives::NoteCandidate;
pub use objectives::RerankerObjective;
pub use objectives::RetrievalCandidate;
pub use objectives::RrfFusionObjective;
pub use objectives::TemporalRecencyObjective;
pub use objectives::TextRelevanceObjective;
pub use objectives::VectorSimilarityObjective;
pub use operations::base_entity_endpoint_rules;
pub use operations::base_entity_rule_allows;
pub use operations::endpoint_matches;
pub use operations::hex_prefix_to_uuid_pattern;
pub use operations::merge_entry_metadata;
pub use operations::uuid_prefix_bounds;
pub use operations::ConditionalInsertStage;
pub use operations::EdgeEndpointKind;
pub use operations::EntityCreateSpec;
pub use operations::LinkSpec;
pub use operations::NoteCreateSpec;
pub use operations::NoteSearchHit;
pub use operations::NoteSearchOutcome;
pub use operations::PostCommitDegradation;
pub use operations::QueryResult;
pub use operations::Resolved;
pub use pack::resolve_explicit_namespace;
pub use pack::ChannelIngestCapability;
pub use pack::DispatchHook;
pub use pack::IngestAuditStore;
pub use pack::InterceptedDispatchResult;
pub use pack::KindHook;
pub use pack::NoteUpdateEffect;
pub use pack::PackByIdResolver;
pub use pack::PackFactory;
pub use pack::PackInstall;
pub use pack::PackLoadError;
pub use pack::PackMetadataRegistry;
pub use pack::PackRegistration;
pub use pack::PackRegistry;
pub use pack::PackRuntime;
pub use pack::PackSchemaCollisionError;
pub use pack::RequestIdentity;
pub use pack::SchemaPlan;
pub use pack::VerbRegistry;
pub use pack::VerbRegistryBuilder;
pub use pack::VerifiedActor;
pub use pack::AUDIT_PERSISTENCE_SKIPPED_READ_ONLY;
pub use phase_events::emit_phase_event;
pub use phase_events::is_benign_shutdown_cancellation;
pub use portability::ImportSummary;
pub use portability::KgArchive;
pub use preference_verification::LegacyPreferenceVerifier;
pub use preference_verification::VerifiedModelNetworkAttachment;
pub use presentation::apply_redundancy_drop;
pub use presentation::micros_to_iso;
pub use presentation::prepare_format_value;
pub use presentation::present;
pub use presentation::present_with_policy;
pub use presentation::render_format;
pub use presentation::rfc3339_to_utc_micros;
pub use presentation::OutputFormat;
pub use presentation::PresentationMode;
pub use presentation::RedundancyScope;
pub use reference_resolution::resolve_reference;
pub use reference_resolution::resolve_reference_with_entity_type;
pub use reference_resolution::ReferenceCandidate;
pub use reference_resolution::ReferenceResolution;
pub use reference_ring::ReferenceRing;
pub use reference_ring::RingEntry;
pub use registry::ObjectiveRegistry;
pub use registry::RegisteredObjective;
pub use resource::cpu_delta_us;
pub use resource::process_resource_usage;
pub use resource::ProcessResourceUsage;
pub use runtime::assert_captured_db_anchor_consistent;
pub use runtime::assert_db_anchor_consistent;
pub use runtime::expand_tilde;
pub use runtime::parse_pack_list;
pub use runtime::resolve_db_anchor;
pub use runtime::resolve_project_actor_id;
pub use runtime::runtime_config_from_khive_config;
pub use runtime::BackendId;
pub use runtime::EntityTypeValidatorFn;
pub use runtime::KhiveRuntime;
pub use runtime::NamedVectorIdentity;
pub use runtime::NamespaceToken;
pub use runtime::NoteMutationHookFn;
pub use runtime::NoteWriteValidatorFn;
pub use runtime::OpenedDiagnosticBackend;
pub use runtime::RuntimeConfig;
pub use secret_gate::SecretMatch;
pub use telemetry_config::TelemetryCarrier;
pub use telemetry_config::TelemetryChannelConfig;
pub use telemetry_config::TelemetryConfig;
pub use telemetry_config::TelemetryFailurePosture;
pub use telemetry_config::TelemetryPolicy;
pub use validation::GraphPatch;
pub use validation::GraphSnapshot;
pub use validation::RuleFn;
pub use validation::RuleId;
pub use validation::Severity;
pub use validation::ValidationContext;
pub use validation::ValidationReport;
pub use validation::ValidationRule;
pub use validation::Violation;

Modules§

actor_identity
Shared actor-identity resolution (issue #567).
agent_lifecycle
Pure lifecycle logic for the runtime-owned agent process record (ADR-142 §1).
atomic_message
Atomic multi-note write primitive: commits a set of notes — each with its FTS document and its kind-selected embedding model rows — in ONE writer transaction, instead of one create_note call per note.
atomic_plan
ADR-099 (cross-op atomicity for bulk apply) — prepared write-plan types.
atomic_prepare
ADR-099: the per-verb async prepare pass for the KG-substrate v1 admissible verbs (update, delete, link, merge), plus prepare_add_entity/prepare_add_note for the ADR-046 proposal changeset AddEntity/AddNote arms. Each prepare_* function reads current state (async, outside any transaction) and returns a plain-data crate::atomic_runner::AtomicOpPlan (crate::atomic_plan) for the synchronous commit pass (crate::atomic_runner::run_atomic_unit) to apply.
atomic_runner
ADR-099 migration step 3 (sub-slice B2) — the atomic runner: the synchronous commit-pass mechanism that applies a caller-supplied sequence of prepared write plans (crate::atomic_plan) as ONE SqlAccess::atomic_unit, under a per-op SAVEPOINT, committing every plan or rolling back the whole unit.
audit_batch
ADR-133 Slice 1: the audit-batch seam.
blob
Config-driven BlobStore selection (ADR-111 Amendment 2).
bounded_read
Size-capped reads of streams whose length the caller does not control.
build_info
Compile-time identity for the source and build that produced this runtime.
comm_recipient
Trusted in-process recipient ingest. No registry verb dispatches this API.
comm_transport
Runtime-owned sender transport persistence (ADR-105).
config
RuntimeConfig, BackendId, NamespaceToken, and embedding model helpers.
config_ledger
ADR-094 process-lifetime config lock ledger.
cost_unit
ADR-103 Amendment 1: deterministic cost_unit for the per-dispatch audit-row resource payload enrichment.
credentials
Named credential custody (ADR-192). Resolution never exposes material to packs.
curation
Curation operations: entity update/merge and edge-list filter type.
daemon
khived daemon server — persistent warm runtime over a Unix socket.
email_message_id
Configuration-bound ownership checks for outbound email Message-IDs.
embedder_registry
EmbedderRegistry — pack-extensible embedding provider surface.
engine_config
TOML-based embedding engine configuration for khive.
entity_write
Entity revision preconditions, evaluated by the shared writer transaction.
error
Runtime error types.
events_split
Events-daemon split (ADR-170): the audit lane leaves the domain store.
file_policy
Confined server file destinations shared by result sinks and blob verbs.
fusion
Fusion strategies for combining ranked result lists.
graph_traversal
input_schema
Derive a JSON Schema for a verb’s parameters from its own ParamDef list.
keyed_memory
Memory identity is published only by the final DML of its atomic create.
keyed_message
A message pair publishes its outbound identity in the final atomic statement.
mount_config
mounted_verb
note_search_ann
Pack-owned ANN candidate source for the note-substrate search vector leg.
note_write
Key and revision guards evaluated by the transaction owner.
objectives
Retrieval Objective implementations for khive-runtime.
operations
High-level operations composing storage capabilities into user-facing verbs.
pack
Pack runtime trait and verb registry.
pack_metadata
Generate object-safe pack metadata accessors from the pack’s associated constants.
phase_events
Shared helpers for ADR-103 phase-span event emission.
portability
KG export / import — portable JSON archive for namespace-scoped knowledge graphs.
preference_verification
Legacy moodboard preference-model verification, inverted behind a trait.
presentation
Verb response presentation modes and transformation.
process_group
One guarded signal to a whole process group.
process_retry
Bounded retry for a process image temporarily busy during replacement.
reference_resolution
resolve_reference: the Layer-0 deterministic reference resolver from the “unified-verb” draft ADR (Slice 1 — resolver + ring).
reference_ring
Recently-referenced ring: a bounded, per-(namespace, actor) cache of ids this actor recently touched by name, held in daemon-warm memory only.
registry
Objective registry for dynamic dispatch.
resource
Process-level resource reads (ADR-103 Stage 1).
retrieval
Retrieval operations: local embedding generation and hybrid search with RRF fusion.
runtime
KhiveRuntime — composable handle to all storage capabilities.
secret_gate
Write-time secret detection gate.
telemetry_config
time_anchor
Calendar-date → earliest-instant anchoring (ADR-169 D1), shared by every surface that accepts a date-only value against the configured display timezone. Moved verbatim from khive-pack-gtd’s handlers when brain.event_counts gained the same date-only semantics — packs do not depend on packs, so the shared rule lives here beside the display_timezone config it interprets.
usage
ADR-103 Amendment 2: dispatch-scoped executed-usage counters.
validation
Validation pipeline types for pack-contributed KG rules.

Macros§

pack_factory_metadata
Delegate a factory’s name and dependencies to the pack type it constructs.
pack_runtime_metadata
Delegate every const-backed PackRuntime metadata accessor to Self: Pack.
sql
The statement text of sql/<name>.sql, checked in at compile time.

Structs§

ActorRef
Caller identity with non-empty kind and id, validated on construction and deserialization.
AgentRecord
The runtime-owned agent process record (ADR-142 §1, “Persistent process record”).
AllowAllGate
Permissive gate — every request is allowed with no obligations.
AuditEvent
Structured audit record emitted once per gate consultation.
AuthenticatedVisibilityReceipt
Authenticated and scope-checked receipt fields for trusted proof consumers. Deliberately has no formatting or serialization implementation.
CallerEnrollmentGate
Immutable caller-enrollment policy for the built-in configuration gate.
CheckpointConfig
Configuration for the WAL checkpoint background task.
CheckpointLifecycleOwner
The event sink and namespace owned by one checkpoint task in a fan-out.
ConnectionPool
A read-write connection pool for SQLite.
EventAttribution
Runtime-resolved event attribution derived from a sealed authorization token.
EventObservation
A single entity observation recorded alongside an event.
EventReadPageRequest
EventReadPageResult
EventView
An event together with its associated observations.
GateContext
Per-request context — session, timing, transport source.
GateRequest
What the gate sees on every verb invocation.
HandlerDef
Handler metadata for discovery and documentation.
HybridSearchOutcome
Result of a hybrid search: the fused hits — text hits alone when the vector arm failed — plus the vector arm’s error, if any.
IndexRepairReport
Per-record index work that actually committed. Failed stages can coexist with repairs; rerunning repairs only the gaps that still remain.
KgNeighborRead
Query options for a KG neighbor read whose origin may live on a pack backend.
MailboxReadGate
Immutable trusted-local owner/reader policy, composed with an existing gate.
MailboxView
An authorized mailbox selection. This never replaces the real caller token.
Namespace
A validated, opaque namespace identifier.
NoteEmbeddingPolicySpec
Pack-owned embedding policy for one declared note kind.
NoteKindSpec
Kind-level schema specification for a note kind.
NoteLifecycleSpec
Lifecycle specification for a note kind.
OutboundEmailPolicy
Boot-resolved recipient policy shared by comm admission and email delivery. An absent policy permits queuing without claiming that delivery is configured.
PackSchemaPlan
DDL statements the pack needs applied to the auxiliary schema.
ParamDef
Parameter type for help=true schema envelopes.
SearchHit
A unified search result combining vector and text signals.
SearchSignals
Retained component scores before fusion and strategy-local modifiers. An absent retrieval leg has no score, which is distinct from a measured zero. Scores belong to the backend and model that produced the retained hit; vector similarities from different embedding models are not comparable.
StorageBackend
Concrete storage backend providing capability traits.
StreamAppendFailure
An unchanged source error together with evidence local to one append.
StreamAppendSpec
One append, shape-validated by the verb layer; the runtime validates the stream name and the record’s serialization before any write.
StreamBatchRefusal
The member refusal that stopped an atomic batch; nothing was written.
StreamObservation
An exact live-key observation; a null version asserts that the key is unheld. An optional identity pins which live note must hold the key at that version.
StreamWriteSpec
A keyed document write. Kinds are canonical note-kind names. A missing expected version creates only; a positive version updates only.
TraversalOptions
BFS traversal configuration controlling depth, direction, and edge filters. Deserialization rejects non-finite min_weight.

Enums§

AgentState
One of the four lifecycle states an agent process record can occupy.
AuditDecision
The outcome field of an AuditEvent.
CheckpointTick
Outcome of a single checkpoint attempt.
EffectiveCreateTags
The effective tags for note creation, retaining their source so writers can preserve the original properties when no top-level override is needed.
EventCursorWalkError
Causes left to each caller to classify and describe for its own surface.
FusionStrategy
Validated selection for combining ranked result lists.
GateDecision
Gate decision: allow (with optional obligations) or deny (with reason).
GateError
Errors returned by crate::Gate::check.
IdResolutionMode
How a uuid or array of uuid parameter resolves a caller-supplied identifier — full UUID and short hex-prefix acceptance, and whether either form is checked against a namespace. This is a property of the handler’s own resolution code, declared explicitly per parameter so VerbRegistry::describe_verb’s rendered contract can never drift from what the handler actually does (see khive-runtime’s pack.rs IdResolutionMode rendering table for the exact wording per variant).
MailboxPolicyError
Malformed mailbox policy or selector. Labels are exact values, never namespaces.
NoteEmbeddingPolicy
Which registered embedding spaces a note kind writes by default.
Obligation
Policy instructions attached to an allow; only Audit has v0 runtime handling.
ObservationRole
Role of a referent in a brain observation (candidate, selected, target, signal).
OperationAccess
Strongest caller-requested effect of a reviewed operation.
RankScoreKind
The strategy that produced a hit’s ordering score, including local modifiers.
ReferentKind
Which durable record family an event observation refers to. Edge remains relational storage rather than a fourth SubstrateKind; this narrower discriminant exists so edge lifecycle events can still be queried through observed=[edge_id].
SearchSource
Which retrieval path(s) contributed to a hit.
StreamAppendDisposition
What the append path can prove about its own failed append, independently of an enclosing dispatch or a nested error’s wire disposition.
StreamBatchMember
A batch member or its already established refusal. The mode places it.
TerminalReason
Why a record reached Terminal. Set exactly once, at the transition into Terminal.
VerbCategory
Illocutionary force classification for a verb handler.
VerbPresentationPolicy
Presentation override for a verb handler.
Visibility
Visibility tier for a handler.
WalCeilingSource
Where the effective WAL ceiling byte value was configured.

Constants§

CLASSIFIED_OPERATIONS
Exact reviewed names, including internal handlers and runtime pseudo-verbs. Sorted for lookup; unknown names must remain distinguishable from Write so the production registry census fails when a new handler needs review.
OPERATION_CLASSIFIER_VERSION
Revision of the reviewed classification contract, included in policy identity. Bump whenever a classification or the allowed-read contract changes.
RUNTIME_STAMPED_ACTOR_KINDS
Kind prefixes reserved by runtime event attribution and its identity fixtures.
SQLITE_WAL_CAPACITY_REFUSED_STAGE
Stable ADR-194 WAL capacity stages, shared with the SQLite error source. Stable ADR-194 capacity stages. The refusal stage is reserved for the WAL I/O limiter; this configuration-only slice emits only unavailable.
SQLITE_WAL_CAPACITY_UNAVAILABLE_STAGE
Stable ADR-194 WAL capacity stages, shared with the SQLite error source.

Traits§

Gate
Authorization gate consulted before each verb dispatch.

Functions§

checkpoint_once
Issue one checkpoint cycle against the task’s dedicated checkpoint connection (conn — see CheckpointConnection; NEVER the pool’s writer mutex).
classify_operation
Classify an exact registered or pseudo-verb name. No prefix/category inference. A restricting gate must deny None, just as it denies explicit Write.
deser_params
Deserialize a verb’s JSON params into T.
effective_create_tags
Resolve create-tag precedence once for writers and kind hooks.
is_valid_mailbox_actor_label
Whether an exact mailbox actor label is eligible for explicit selection.
page_budget_exceeded_error
Refusal for a page whose rows together pass a byte budget. Carries no cursor: a smaller limit reaches the same rows without skipping any.
refusal_value
A member refusal as a value: the error object a refused op carries, plus the disposition the consumer rule reads without a special case.
row_exceeds_budget_error
Refusal for a single event whose row cannot be served within a byte budget. resume_after continues strictly after that event, which stays readable by id.
run_checkpoint_task
Run the WAL checkpoint background task.
run_migrations
runtime_error_value
Project the original typed error, preserving every structured source field.
split_stamped_label
Split a kind:id label when kind is one of RUNTIME_STAMPED_ACTOR_KINDS.
visit_events_cursor_walk
Visit at most max_rows owned events in the store’s descending page order.

Type Aliases§

GateRef
Shareable handle to a Gate impl.