Skip to main content

KnowledgeRuntime

Struct KnowledgeRuntime 

Source
pub struct KnowledgeRuntime { /* private fields */ }
Expand description

The main runtime handle.

KnowledgeRuntime orchestrates query classification, route planning, retrieval execution, and result merging. It owns derived projections (entity registry, projection tracker) but NEVER owns source truth — all facts, episodes, and documents live in semantic-memory.

§What is implemented

  • Rule-based query classification (semantic, entity, temporal, mixed)
  • Route planning from classification
  • Projection-backed retrieval for imported claims, relations, and episodes with hybrid fallback only when the projection substrate is unavailable
  • Entity search with scope-aware registry resolution and bounded imported alias candidate expansion
  • Result merge with duplicate fusion and multi-leg provenance
  • Projection health/status tracking with invalidation by scope/kind
  • Query traces with degradation warnings
  • Dedicated explain/audit entrypoints for imported evidence refs
  • Temporal search execution on supported projection routes: Temporal legs resolve supported expressions to concrete as-of timestamps and query imported versions directly. Explicit bitemporal parameters in query_temporal() are now also applied on projection-backed hybrid and entity routes. Unsupported expressions or missing projection substrate degrade explicitly when strict mode is off.
  • Route-aware scope enforcement: Full scope is enforced on projection-backed routes. ScopePartiallyEnforced is emitted only when execution must fall back to namespace-only hybrid retrieval.
  • Non-authoritative entity cache: The entity registry is accessible via refresh_entity_cache() which returns a fenced EntityCacheHandle that only exposes cache-refresh operations. Direct mutable access to the registry has been removed to enforce non-authoritative semantics.

§What is NOT implemented

  • Range temporal expressions: before, after, since, between, and similar range-oriented phrases still degrade explicitly because the runtime currently supports only concrete as-of timestamps on projection routes.
  • Projection persistence: Not implemented in this crate today. The persist config field is retained for serde backward compatibility but rejected at validation time (InvalidConfig error). Projections are derived, non-authoritative, and rebuildable from upstream state.
  • Projection rebuild execution: The tracker records build/failure events but does not trigger actual rebuilds. Callers must drive rebuilds. The projection tracker is observability-only, not an orchestration primitive. It records state transitions (build, failure, invalidation) for inspection and diagnostics. It does NOT schedule, execute, or retry projection rebuilds. Any rebuild logic must live in an external orchestrator that reads tracker state and calls the appropriate APIs.
  • LLM-based classification: Classifier is rule-based heuristic.
  • Advanced explain/audit cross-system dereference: The runtime does not dereference raw evidence handles.

Implementations§

Source§

impl KnowledgeRuntime

Source

pub async fn latest_inference_advisory( &self, scope: Option<&Scope>, ) -> Result<Option<InferenceAdvisory>, RuntimeError>

Compile the latest rebuildable kernel payload for a scope into a non-authoritative inference advisory.

Source

pub async fn latest_inference_explanation( &self, scope: Option<&Scope>, ) -> Result<Option<InferenceExplanation>, RuntimeError>

Expose witnesses, residuals, syndromes, calibration, and refutation state for the latest rebuildable kernel payload.

Source

pub async fn latest_risk_gate_decision( &self, scope: Option<&Scope>, ) -> Result<Option<RiskGateDecision>, RuntimeError>

Gate risk-influencing use of runtime kernel output on explicit artifacts.

Source

pub async fn latest_risk_gate( &self, scope: Option<&Scope>, ) -> Result<Option<RiskGateDecision>, RuntimeError>

Compatibility wrapper for callers using the earlier method name.

Source§

impl KnowledgeRuntime

Source

pub fn new( config: RuntimeConfig, adapter: SemanticMemoryAdapter, ) -> Result<Self, RuntimeError>

Create a new runtime from a config and a semantic-memory adapter.

Returns InvalidConfig if the config contains invalid values, including projection.persist = true (persistence is not implemented).

Source

pub async fn query( &self, query: &str, scope: Option<&Scope>, ) -> Result<(Vec<SearchResult>, QueryTrace), RuntimeError>

Execute a query through the full pipeline: classify -> plan -> execute -> merge.

Returns merged results and a query trace for observability. The trace includes any degradation warnings (e.g. temporal downgrade).

Generates a fresh TraceCtx internally. To supply a caller-owned trace context (for cross-crate correlation), use query_with_trace().

Source

pub async fn query_with_trace( &self, query: &str, scope: Option<&Scope>, trace_ctx: Option<TraceCtx>, ) -> Result<(Vec<SearchResult>, QueryTrace), RuntimeError>

Execute a query with an optional caller-supplied TraceCtx.

If trace_ctx is None, a fresh trace context is generated. This is the primary query entry point for callers that need cross-crate trace correlation (e.g., bridge -> runtime -> memory).

§Scope enforcement

Scope handling is route-aware. Projection-backed routes enforce the full scope directly against imported rows. Namespace-only hybrid fallback emits ScopePartiallyEnforced only when the runtime lacks a projection-backed route for the requested leg and strict scope is disabled.

Source

pub async fn query_with_inference_explanation( &self, query: &str, scope: Option<&Scope>, trace_ctx: Option<TraceCtx>, ) -> Result<(Vec<SearchResult>, QueryTrace, Option<InferenceExplanation>), RuntimeError>

Execute a query and attach the latest non-authoritative kernel explanation available for the queried scope.

Source

pub async fn query_temporal( &self, query: &str, scope: Option<&Scope>, valid_at: &str, recorded_at_or_before: &str, ) -> Result<(Vec<SearchResult>, QueryTrace), RuntimeError>

Execute a temporal query with explicit bitemporal semantics.

This is the public equivalent for: as_of(valid_t, recorded_t_or_before).

valid_at filters by projection-valid time, while recorded_at_or_before filters by importer transaction time. This method keeps the same warning behavior as the normal pipeline for scope and temporal fallback on supported routes.

Source

pub async fn query_temporal_with_trace( &self, query: &str, scope: Option<&Scope>, trace_ctx: Option<TraceCtx>, valid_at: &str, recorded_at_or_before: &str, ) -> Result<(Vec<SearchResult>, QueryTrace), RuntimeError>

Execute an explicit-temporal query with an explicit trace context.

See query_temporal for semantics.

Source

pub async fn query_evidence_refs_for_claim( &self, claim_id: &str, claim_version_id: Option<&str>, scope: Option<&Scope>, limit: usize, ) -> Result<Vec<ProjectionEvidenceRef>, RuntimeError>

Query evidence references for a claim via the explicit explain/audit path.

This returns imported evidence handles as opaque rows and does not alter normal retrieval behavior.

Source

pub async fn query_evidence_refs_for_claim_as_of( &self, claim_id: &str, claim_version_id: Option<&str>, scope: Option<&Scope>, recorded_at_or_before: &str, limit: usize, ) -> Result<Vec<ProjectionEvidenceRef>, RuntimeError>

Query evidence references for a claim as of a transaction-time cutoff.

Source

pub async fn query_verification_summary_for_claim( &self, claim_id: &str, claim_version_id: Option<&str>, scope: Option<&Scope>, ) -> Result<Option<ProjectedVerificationSummary>, RuntimeError>

Query the projected verification summary for a claim.

This reads imported claim rows only. It does not reconstruct truth from raw evidence dereference, and it does not mutate runtime state.

Source

pub async fn query_verification_summary_for_claim_as_of( &self, claim_id: &str, claim_version_id: Option<&str>, scope: Option<&Scope>, recorded_at_or_before: &str, ) -> Result<Option<ProjectedVerificationSummary>, RuntimeError>

Query the projected verification summary for a claim as of a recorded-time cutoff.

Source

pub fn classify(&self, query: &str) -> ClassifyResult

Classify a query without executing it.

Source

pub fn plan(&self, query: &str, scope: Option<&Scope>) -> RoutePlan

Plan a query without executing it.

Source

pub fn entity_registry(&self) -> &EntityRegistry

Access the entity registry for read-only lookup.

Source

pub fn refresh_entity_cache(&mut self) -> EntityCacheHandle<'_>

Get a cache-refresh handle for loading entities from upstream canonical state.

§Authority boundary

The entity registry is a derived, non-authoritative cache. This handle only exposes cache-refresh operations — not authority-like mutation.

Use this for:

  • Loading entities from upstream memory canonical state
  • Rebuilding the cache after invalidation
  • Clearing scope or full cache for rebuild
  • Test setup

Runtime MUST NOT become an authoritative source of identity state.

Source

pub fn projection_health(&self, id: &ProjectionId) -> ProjectionHealth

Get the health of a specific projection.

Observability only. This reads tracker state; the tracker does not execute rebuilds or schedule any work based on health status.

Source

pub fn projection_status( &self, kind: Option<&ProjectionKind>, scope: Option<&ScopeKey>, ) -> Vec<&ProjectionMeta>

Query projection status by optional kind and scope filters.

Source

pub fn record_projection_build( &mut self, id: ProjectionId, source_count: usize, build_duration_ms: u64, version: Option<ProjectionVersion>, )

Record that a projection was successfully built.

Source

pub fn record_projection_failure(&mut self, id: ProjectionId, error: String)

Record that a projection build failed.

Source

pub fn invalidate_projections( &mut self, event: &InvalidationEvent, ) -> ProjectionActionResult

Invalidate specific projections.

Source

pub fn invalidate_projections_by_kind( &mut self, kind: &ProjectionKind, scope: &ScopeKey, cause: StaleCause, ) -> ProjectionActionResult

Invalidate all projections of a given kind within a scope.

Source

pub fn invalidate_scope( &mut self, scope: &ScopeKey, cause: StaleCause, ) -> ProjectionActionResult

Invalidate all projections within a scope.

Source

pub fn clear_projection_scope( &mut self, scope: &ScopeKey, ) -> ProjectionActionResult

Clear all projections within a scope.

Source

pub fn projection_tracker(&self) -> &ProjectionTracker

Access the projection tracker directly (read-only).

Observability only, not orchestration. The tracker records projection lifecycle events (build, invalidation, failure) but does not trigger, schedule, or retry any work. External callers must drive rebuild execution and report outcomes via record_projection_build() / record_projection_failure().

Source

pub fn adapter(&self) -> &SemanticMemoryAdapter

Access the underlying semantic-memory adapter.

Source

pub fn config(&self) -> &RuntimeConfig

Access the runtime config.

Trait Implementations§

Source§

impl Debug for KnowledgeRuntime

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more