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_notecall 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), plusprepare_add_entity/prepare_add_notefor the ADR-046 proposal changesetAddEntity/AddNotearms. Eachprepare_*function reads current state (async, outside any transaction) and returns a plain-datacrate::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 ONESqlAccess::atomic_unit, under a per-opSAVEPOINT, committing every plan or rolling back the whole unit. - audit_
batch - ADR-133 Slice 1: the audit-batch seam.
- blob
- Config-driven
BlobStoreselection (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_unitfor the per-dispatch audit-rowresourcepayload 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
ParamDeflist. - 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 whenbrain.event_countsgained the same date-only semantics — packs do not depend on packs, so the shared rule lives here beside thedisplay_timezoneconfig 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
PackRuntimemetadata accessor toSelf: Pack. - sql
- The statement text of
sql/<name>.sql, checked in at compile time.
Structs§
- Actor
Ref - Caller identity with non-empty
kindandid, validated on construction and deserialization. - Agent
Record - The runtime-owned agent process record (ADR-142 §1, “Persistent process record”).
- Allow
AllGate - Permissive gate — every request is allowed with no obligations.
- Audit
Event - Structured audit record emitted once per gate consultation.
- Authenticated
Visibility Receipt - Authenticated and scope-checked receipt fields for trusted proof consumers. Deliberately has no formatting or serialization implementation.
- Caller
Enrollment Gate - Immutable caller-enrollment policy for the built-in configuration gate.
- Checkpoint
Config - Configuration for the WAL checkpoint background task.
- Checkpoint
Lifecycle Owner - The event sink and namespace owned by one checkpoint task in a fan-out.
- Connection
Pool - A read-write connection pool for SQLite.
- Event
Attribution - Runtime-resolved event attribution derived from a sealed authorization token.
- Event
Observation - A single entity observation recorded alongside an event.
- Event
Read Page Request - Event
Read Page Result - Event
View - An event together with its associated observations.
- Gate
Context - Per-request context — session, timing, transport source.
- Gate
Request - What the gate sees on every verb invocation.
- Handler
Def - Handler metadata for discovery and documentation.
- Hybrid
Search Outcome - Result of a hybrid search: the fused hits — text hits alone when the vector arm failed — plus the vector arm’s error, if any.
- Index
Repair Report - Per-record index work that actually committed. Failed stages can coexist with repairs; rerunning repairs only the gaps that still remain.
- KgNeighbor
Read - Query options for a KG neighbor read whose origin may live on a pack backend.
- Mailbox
Read Gate - Immutable trusted-local owner/reader policy, composed with an existing gate.
- Mailbox
View - An authorized mailbox selection. This never replaces the real caller token.
- Namespace
- A validated, opaque namespace identifier.
- Note
Embedding Policy Spec - Pack-owned embedding policy for one declared note kind.
- Note
Kind Spec - Kind-level schema specification for a note kind.
- Note
Lifecycle Spec - Lifecycle specification for a note kind.
- Outbound
Email Policy - Boot-resolved recipient policy shared by comm admission and email delivery. An absent policy permits queuing without claiming that delivery is configured.
- Pack
Schema Plan - DDL statements the pack needs applied to the auxiliary schema.
- Param
Def - Parameter type for
help=trueschema envelopes. - Search
Hit - A unified search result combining vector and text signals.
- Search
Signals - 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.
- Storage
Backend - Concrete storage backend providing capability traits.
- Stream
Append Failure - An unchanged source error together with evidence local to one append.
- Stream
Append Spec - One append, shape-validated by the verb layer; the runtime validates the stream name and the record’s serialization before any write.
- Stream
Batch Refusal - The member refusal that stopped an atomic batch; nothing was written.
- Stream
Observation - 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.
- Stream
Write Spec - A keyed document write. Kinds are canonical note-kind names. A missing expected version creates only; a positive version updates only.
- Traversal
Options - BFS traversal configuration controlling depth, direction, and edge filters. Deserialization rejects non-finite min_weight.
Enums§
- Agent
State - One of the four lifecycle states an agent process record can occupy.
- Audit
Decision - The outcome field of an
AuditEvent. - Checkpoint
Tick - Outcome of a single checkpoint attempt.
- Effective
Create Tags - The effective tags for note creation, retaining their source so writers can preserve the original properties when no top-level override is needed.
- Event
Cursor Walk Error - Causes left to each caller to classify and describe for its own surface.
- Fusion
Strategy - Validated selection for combining ranked result lists.
- Gate
Decision - Gate decision: allow (with optional obligations) or deny (with reason).
- Gate
Error - Errors returned by
crate::Gate::check. - IdResolution
Mode - How a
uuidorarray of uuidparameter 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 soVerbRegistry::describe_verb’s rendered contract can never drift from what the handler actually does (see khive-runtime’spack.rsIdResolutionModerendering table for the exact wording per variant). - Mailbox
Policy Error - Malformed mailbox policy or selector. Labels are exact values, never namespaces.
- Note
Embedding Policy - Which registered embedding spaces a note kind writes by default.
- Obligation
- Policy instructions attached to an allow; only
Audithas v0 runtime handling. - Observation
Role - Role of a referent in a brain observation (candidate, selected, target, signal).
- Operation
Access - Strongest caller-requested effect of a reviewed operation.
- Rank
Score Kind - The strategy that produced a hit’s ordering score, including local modifiers.
- Referent
Kind - 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 throughobserved=[edge_id]. - Search
Source - Which retrieval path(s) contributed to a hit.
- Stream
Append Disposition - What the append path can prove about its own failed append, independently of an enclosing dispatch or a nested error’s wire disposition.
- Stream
Batch Member - A batch member or its already established refusal. The mode places it.
- Terminal
Reason - Why a record reached
Terminal. Set exactly once, at the transition intoTerminal. - Verb
Category - Illocutionary force classification for a verb handler.
- Verb
Presentation Policy - Presentation override for a verb handler.
- Visibility
- Visibility tier for a handler.
- WalCeiling
Source - 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— seeCheckpointConnection; 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
paramsintoT. - 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
limitreaches 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_aftercontinues 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:idlabel whenkindis one ofRUNTIME_STAMPED_ACTOR_KINDS. - visit_
events_ cursor_ walk - Visit at most
max_rowsowned events in the store’s descending page order.
Type Aliases§
- GateRef
- Shareable handle to a
Gateimpl.