Skip to main content

khive_runtime/
lib.rs

1//! khive-runtime: composable Service API used by daemon, MCP server, and CLI.
2//!
3//! Wraps `StorageBackend` and query compilation into a single Rust API surface.
4
5mod canonical_apply;
6pub use canonical_apply::prepare_canonical_changeset;
7
8#[cfg(test)]
9mod test_process;
10
11pub mod actor_identity;
12pub mod agent_lifecycle;
13#[doc(hidden)]
14pub use khive_retrieval::ann::registry as ann_registry;
15pub mod atomic_message;
16pub mod atomic_plan;
17pub mod atomic_prepare;
18pub mod atomic_runner;
19pub mod attachment_cutover;
20pub use attachment_cutover::{
21    coordinate_attachment_cutover, coordinate_empty_secondary_attachment_cutover,
22    legacy_preference_model_count, require_secondary_attachment_empty,
23};
24pub mod audit_batch;
25pub mod audit_error;
26pub mod backend_handle;
27pub mod blob;
28pub mod blob_tree;
29pub mod bounded_read;
30pub mod build_info;
31mod code_map_runtime;
32pub use code_map_runtime::{
33    CodeMapRegistry, FileIdentity, RegisteredCodeMap, RegistrationGeneration,
34};
35pub mod comm_recipient;
36pub mod comm_transport;
37pub mod config;
38pub mod config_ledger;
39pub mod context;
40pub mod cost_unit;
41pub mod credentials;
42pub mod node_pins;
43mod visibility_receipts;
44pub use visibility_receipts::AuthenticatedVisibilityReceipt;
45pub mod curation;
46pub mod daemon;
47pub mod email_message_id;
48pub mod embedder_registry;
49pub mod embedding;
50pub mod embedding_reranker;
51pub mod embedding_warning;
52pub mod engine_config;
53pub mod entity_write;
54pub mod error;
55mod error_projection;
56mod event_actor_scope;
57mod event_cursor_walk;
58mod event_page;
59mod event_plane_read;
60mod event_store_guard;
61pub mod events_split;
62mod fence_identity;
63pub mod file_policy;
64pub mod fusion;
65pub mod graph_traversal;
66pub mod hooks;
67mod index_repair;
68#[cfg(feature = "native-rerank")]
69pub mod native_reranker;
70pub use index_repair::IndexRepairReport;
71pub mod channel_section;
72#[cfg(test)]
73mod channel_section_tests;
74pub mod channel_send;
75pub mod graph_lint;
76pub mod input_schema;
77pub mod keyed_memory;
78#[cfg(test)]
79mod keyed_memory_tests;
80pub mod keyed_message;
81mod kg_read;
82mod live_until;
83mod mailbox_view;
84mod note_create;
85mod note_index;
86mod note_read;
87pub mod note_search_ann;
88mod note_store_guard;
89mod note_validation;
90pub mod note_write;
91#[cfg(test)]
92mod note_write_tests;
93pub mod objectives;
94pub mod operations;
95mod outbound_email_policy;
96pub use outbound_email_policy::OutboundEmailPolicy;
97pub use outbound_email_policy::{
98    inbound_email_is_suppressed, outbound_email_is_suppressed, EmailSuppression,
99    EmailSuppressionKind, EmailSuppressionScope, SuppressionMirror,
100};
101pub mod pack;
102pub mod pack_metadata;
103mod params;
104pub mod phase_events;
105pub mod portability;
106pub mod preference_verification;
107pub mod presentation;
108pub mod process_group;
109pub mod process_retry;
110pub mod reference_resolution;
111pub mod reference_ring;
112pub mod registry;
113pub mod resource;
114pub mod resource_admission;
115pub mod retrieval;
116pub mod runtime;
117pub mod search_audit;
118pub mod secret_gate;
119pub(crate) mod secret_gate_finalizer;
120mod sql_include;
121#[cfg(test)]
122mod stage_overlap_tests;
123mod stage_seam;
124mod streams;
125pub mod telemetry_config;
126pub use streams::{
127    refusal_value, StreamAppendDisposition, StreamAppendFailure, StreamAppendSpec,
128    StreamBatchMember, StreamBatchRefusal, StreamObservation, StreamWriteSpec,
129};
130pub mod time_anchor;
131pub use khive_storage::usage;
132pub mod validation;
133
134pub use context::{ContextContributor, ContextRequest, ContextSlice, ScoreSemantics};
135
136pub use actor_identity::{actor_is_unattributed, resolve_actor, should_warn_unattributed_actor};
137pub use agent_lifecycle::{
138    apply_transition, spawn_fingerprint, AgentRecord, AgentState, IllegalTransition,
139    TerminalReason, Transition, Trigger,
140};
141pub use atomic_message::{create_notes_atomic_with_report, AtomicNoteSpec};
142pub use atomic_plan::{
143    AddEntityPlan, AddNotePlan, AffectedRowGuard, DeletePlan, GovernanceOp, GovernancePlan,
144    GtdCompletePlan, GtdTransitionPlan, LinkPlan, MergePlan, PlanPredicate, PlanStatement,
145    PostCommitEffect, UpdatePlan,
146};
147pub use atomic_runner::{
148    run_atomic_unit, AtomicOpFailure, AtomicOpPlan, AtomicRunOutcome, AtomicRunnerError,
149    CommittedPostCommitEffects,
150};
151pub use backend_handle::{BackendHandle, BackendHandleError, RetrievalTier};
152pub use blob::{
153    resolve_blob_store, resolve_blob_store_for_mode, BlobHydrator, GovernedBlobError, VerifiedBlob,
154    DEFAULT_BLOB_HYDRATION_BYTES,
155};
156pub use build_info::{BuildInfo, BUILD_INFO, BUILD_VERSION};
157pub use config::{
158    ann_fresh_tail_enabled_from_env, client_cwd_from_process, process_ref_from_env,
159    WalCeilingSource,
160};
161pub use cost_unit::{base_resource_payload, cost_unit_for_dispatch, resource_payload};
162pub use curation::{
163    entity_embedding_text, entity_fts_document, entity_merge_guard_compared_values,
164    entity_merge_guard_error, entity_merge_guard_refusal_message, note_embedding_text,
165    note_fts_document, validate_entity_merge_floor, ContentMergeStrategy, EdgeListFilter,
166    EdgePatch, EntityDedupMergePolicy, EntityMergeGuard, EntityPatch, GuardedNoteMerge,
167    MergeAssertion, MergeEdgeConflictPreimage, MergeEdgePreimage, MergeSummary,
168    MergeTxBudgetReport, MergeTxLimits, NoteMergeGuard, NotePatch, NoteUpdatePolicy,
169};
170#[cfg(unix)]
171pub use daemon::{acquire_recovery_lock, pid_path, run_daemon, socket_path, DaemonDispatch};
172pub use daemon::{
173    active_phase_names, background_task_count, background_task_names, daemon_shutdown_token,
174    recall_ledger_snapshot, register_active_phase, spawn_named_tracked_task, track_background_task,
175    track_named_background_task, track_recall_ledger_task, DaemonRequestFrame, DaemonResponseFrame,
176    PhaseGuard, PROTOCOL_VERSION, UNNAMED_BACKGROUND_TASK,
177};
178pub use email_message_id::{EmailMessageIdDomains, HISTORICAL_DOMAINS_ENV};
179pub use embedder_registry::{EmbedderProvider, EmbedderRegistry, LatticeEmbedderProvider};
180pub use embedding::{EmbeddingModelRecord, EmbeddingModelStatus};
181pub use embedding_reranker::{EmbeddingCosineReranker, EmbeddingRerankHit};
182pub use engine_config::{
183    config_from_env, read_computer_key, resolve_wal_ceiling, BackendConfig, BackendKind,
184    BlobConfig, BrainSectionConfig, CodeIngestSectionConfig, CodeMapConfig, ComputerEndpoint,
185    ComputerKey, ComputerKeyError, ComputerKeyRefusal, ComputerSectionConfig, ConfigError,
186    EngineConfig, GateSectionConfig, GitDigestSectionConfig, GitRepoAccess, GitWriteEntryConfig,
187    GitWriteSectionConfig, KhiveConfig, KnowledgeSectionConfig, PackConfig, ResolvedWalCeiling,
188    ShareSectionConfig, ShareTargetConfig, StorageSectionConfig, COMMAND_RUNNING_PACKS,
189    COMPUTER_ROUTABLE_PACKS, DEFAULT_COMPUTER_CALL_TIMEOUT_S, DEFAULT_SHARE_FILES,
190    DEFAULT_SHARE_TOTAL_BYTES, MAX_COMPUTER_CALL_TIMEOUT_S, MAX_COMPUTER_KEY_BYTES,
191    MAX_SHARE_FILES, MAX_SHARE_FILE_BYTES, MAX_SHARE_TOTAL_BYTES,
192};
193pub use error::{
194    fts_text_leg_or_err, AdmissionFailureContext, AuditObligationFailure, AuditObligationReason,
195    ChannelIngestFailureClass, DenialAuditOutcome, DenialReceipt, DispatchError, DomainDisposition,
196    GuardedWriteFailure, ReceiptRefusal, RefusalEventContext, RefusalEventRecording,
197    RefusalRecordingErrorClass, RuntimeError, RuntimeResult, WriterPoolCheckoutTimeoutContext,
198    WriterTaskFailureContext, SQLITE_WAL_CAPACITY_REFUSED_STAGE,
199    SQLITE_WAL_CAPACITY_UNAVAILABLE_STAGE, WRITER_ADMISSION_SCOPE,
200    WRITER_POOL_CHECKOUT_TIMEOUT_STAGE, WRITER_QUEUE_SATURATED_STAGE,
201    WRITER_TASK_REQUEST_FAILED_STAGE, WRITER_TASK_TERMINATED_STAGE,
202};
203pub use error_projection::{
204    failure_entry_parts, failure_error_disposition, runtime_error_value, FailureEntryParts,
205    FailureEntrySource,
206};
207pub use event_actor_scope::{resolve_event_actor_read_scope, EventActorReadScope};
208pub use event_cursor_walk::{visit_events_cursor_walk, EventCursorWalkError};
209pub use event_page::{
210    page_budget_exceeded_error, row_exceeds_budget_error, EventReadPageRequest, EventReadPageResult,
211};
212#[cfg(any(test, feature = "test-internals"))]
213#[doc(hidden)]
214pub use event_plane_read::test_support_exports as event_plane_read_test_support;
215pub use event_store_guard::EventAttribution;
216pub use fusion::FusionStrategy;
217pub use graph_traversal::PathNode;
218pub use kg_read::KgNeighborRead;
219pub use khive_db::env::{env_flag, env_parse_or};
220pub use khive_db::{
221    checkpoint_once, run_checkpoint_task, run_migrations, stores::event::event_insert_statements,
222    CheckpointConfig, CheckpointLifecycleOwner, CheckpointTick, ConnectionPool, StorageBackend,
223};
224pub use khive_gate::{
225    classify_operation, is_valid_mailbox_actor_label, split_stamped_label, ActorRef, AllowAllGate,
226    AuditDecision, AuditEvent, CallerEnrollmentGate, Gate, GateContext, GateDecision, GateError,
227    GateRef, GateRequest, MailboxPolicyError, MailboxReadGate, Obligation, OperationAccess,
228    CLASSIFIED_OPERATIONS, OPERATION_CLASSIFIER_VERSION, RUNTIME_STAMPED_ACTOR_KINDS,
229};
230pub use khive_storage::types::TraversalOptions;
231pub use khive_storage::{EventObservation, EventView, ObservationRole, ReferentKind};
232pub use khive_types::namespace::Namespace;
233pub use mailbox_view::MailboxView;
234#[cfg(feature = "native-rerank")]
235pub use native_reranker::RuntimeRerankDocumentResolver;
236pub use note_create::{effective_create_tags, EffectiveCreateTags};
237pub use objectives::{
238    AmplifiedDecayAwareSalienceObjective, DecayAwareSalienceObjective, GraphProximityObjective,
239    MemoryRecallPipeline, NoteCandidate, RerankerObjective, RetrievalCandidate, RrfFusionObjective,
240    TemporalRecencyObjective, TextRelevanceObjective, VectorSimilarityObjective,
241};
242#[cfg(any(test, feature = "fault-injection"))]
243pub use operations::{
244    arm_entity_compensation_fail_scoped, arm_fts_fail_many_partial_scoped,
245    arm_fts_fail_many_scoped, arm_fts_fail_scoped, arm_prefix_resolve_fail_scoped,
246    arm_rollback_cleanup_fail, arm_vector_fail_after, arm_vector_fail_scoped, FaultInjectionArm,
247};
248pub use operations::{
249    base_entity_endpoint_rules, base_entity_rule_allows, endpoint_matches,
250    hex_prefix_to_uuid_pattern, merge_entry_metadata, uuid_prefix_bounds, ConditionalInsertStage,
251    EdgeEndpointKind, EntityCreateSpec, LinkSpec, NoteCreateSpec, NoteSearchHit, NoteSearchOutcome,
252    PostCommitDegradation, PrefixScope, QueryResult, Resolved,
253};
254pub use pack::{
255    resolve_explicit_namespace, ChannelIngestCapability, DispatchHook, HandlerDef,
256    IdResolutionMode, IngestAuditStore, InterceptedDispatchResult, KindHook, NoteEmbeddingPolicy,
257    NoteEmbeddingPolicySpec, NoteKindSpec, NoteLifecycleSpec, NoteUpdateEffect, PackByIdResolver,
258    PackFactory, PackInstall, PackLoadError, PackMetadataRegistry, PackRegistration, PackRegistry,
259    PackRuntime, PackSchemaCollisionError, PackSchemaPlan, ParamDef, RequestIdentity, SchemaPlan,
260    VerbCategory, VerbPresentationPolicy, VerbRegistry, VerbRegistryBuilder, VerifiedActor,
261    Visibility, AUDIT_PERSISTENCE_SKIPPED_READ_ONLY,
262};
263pub use params::{deser_params, integer_params_from_whole_floats};
264pub use phase_events::{emit_phase_event, is_benign_shutdown_cancellation};
265pub use portability::{ImportSummary, KgArchive};
266pub use preference_verification::{LegacyPreferenceVerifier, VerifiedModelNetworkAttachment};
267pub use presentation::{
268    apply_redundancy_drop, micros_to_iso, prepare_format_value, present, present_with_policy,
269    render_format, rfc3339_to_utc_micros, OutputFormat, PresentationMode, RedundancyScope,
270};
271pub use reference_resolution::{
272    resolve_reference, resolve_reference_with_entity_type, ReferenceCandidate, ReferenceResolution,
273};
274pub use reference_ring::{ReferenceRing, RingEntry};
275pub use registry::{ObjectiveRegistry, RegisteredObjective};
276pub use resource::{cpu_delta_us, process_resource_usage, ProcessResourceUsage};
277pub use retrieval::{HybridSearchOutcome, RankScoreKind, SearchHit, SearchSignals, SearchSource};
278pub use runtime::{
279    assert_captured_db_anchor_consistent, assert_db_anchor_consistent, expand_tilde,
280    parse_pack_list, resolve_db_anchor, resolve_project_actor_id,
281    resolve_project_requires_attributed_actor, runtime_config_from_khive_config, BackendId,
282    EntityTypeValidatorFn, KhiveRuntime, NamedVectorIdentity, NamespaceToken, NoteMutationHookFn,
283    NoteWriteValidatorFn, OpenedDiagnosticBackend, RuntimeConfig,
284};
285pub use secret_gate::SecretMatch;
286pub use secret_gate_finalizer::{
287    EntityCandidateAdmission, EntityCandidateContext, EntityCandidateMutation,
288    EntityCandidateOrigin, EntityCandidatePrepared, EntityFinalizationPlan,
289};
290pub use telemetry_config::{
291    TelemetryCarrier, TelemetryChannelConfig, TelemetryConfig, TelemetryFailurePosture,
292    TelemetryPolicy,
293};
294pub use validation::{
295    GraphPatch, GraphSnapshot, RuleFn, RuleId, Severity, ValidationContext, ValidationReport,
296    ValidationRule, Violation,
297};
298
299#[cfg(test)]
300mod mount_config_tests;
301
302pub mod mount_config;
303
304pub mod mounted_verb;