knowledge_runtime/lib.rs
1//! # knowledge-runtime
2//!
3//! Hardened scaffold / bounded first-pass orchestration layer for `semantic-memory`.
4//!
5//! This crate provides intent classification, route planning, entity resolution,
6//! result merging, and projection lifecycle tracking on top of `semantic-memory`.
7//!
8//! ## Authority Model
9//!
10//! This crate NEVER owns source truth. All facts, episodes, documents, and
11//! conversation messages live in `semantic-memory`. This crate owns only:
12//! - Derived projections (entity registry, projection tracker)
13//! - Query pipeline logic (classification, planning, merge)
14//! - Observability traces
15//!
16//! Deleting any projection forces recomputation but causes no data loss.
17//!
18//! ## Query Pipeline
19//!
20//! ```text
21//! query text
22//! -> classify (QueryMode: semantic | entity | temporal | mixed)
23//! -> plan (RoutePlan with legs)
24//! -> execute (per-leg retrieval via semantic-memory adapter)
25//! -> merge (fuse duplicates with provenance, normalize, boost, rank, truncate)
26//! -> results + QueryTrace (including degradation warnings)
27//! ```
28//!
29//! ## Implemented Now
30//!
31//! - **Rule-based intent classification**: heuristic extraction of entity mentions
32//! (`@name`, `"quoted"`), temporal keywords, and mixed signals.
33//! - **Route planning**: translates classified query modes into retrieval legs.
34//! - **Projection-backed retrieval for imported knowledge**: imported claim,
35//! relation, and episode rows are queried directly through `semantic-memory`'s
36//! public projection APIs.
37//! - **Hybrid fallback where projection substrate is absent**: namespace-only
38//! BM25/vector retrieval remains available when a supported projection route
39//! is unavailable for the queried leg.
40//! - **Entity search**: scope-aware registry resolution plus bounded imported
41//! alias candidate expansion before fallback.
42//! - **Deterministic result merge with provenance fusion**: duplicates across legs are
43//! fused (not discarded), retaining union of source legs and per-leg scores. Tie-breaking
44//! is three-tier: score > source leg count > lexicographic identity key. Multi-leg
45//! support gets a configurable score boost.
46//! - **Scope-aware entity registry**: entities are partitioned by `ScopeKey` (namespace +
47//! domain + workspace_id + repo_id). Resolution falls back from narrow scope to
48//! namespace-only when needed, with fallback visible in results.
49//! - **Scope enforcement transparency**: projection-backed routes enforce full
50//! scope directly. `ScopePartiallyEnforced` is emitted only when execution
51//! must fall back to namespace-only hybrid retrieval.
52//! - **Scope-aware code identity**: code entity IDs include repo_id/workspace_id/namespace
53//! so the same qualified path in different repos yields different IDs.
54//! - **Projection lifecycle observability**: health, staleness (time-based + explicit),
55//! invalidation by scope/kind/id, stale cause, and version metadata. The tracker
56//! currently emits `Healthy`, `Stale`, and `Missing`; reserved compatibility
57//! variants remain in the public enum but are not emitted by the tracker today.
58//! - **Import staleness detection**: the runtime checks `semantic-memory`'s last import
59//! timestamp for the queried namespace and emits `ProjectionImportStale` warnings when
60//! data may be outdated. Import freshness is surfaced as a query warning today,
61//! not as a dedicated tracker health transition.
62//! - **Query traces with degradation warnings**: unsupported temporal downgrade,
63//! partial scope enforcement on hybrid fallback, entity scope fallback, and
64//! import staleness are all surfaced in `QueryTrace::warnings`. Helper methods
65//! (`is_degraded()`, `has_temporal_downgrade()`, etc.) make warnings inspectable.
66//! - **Strict enforcement modes (KR-001/KR-002)**: `strict_temporal` and `strict_scope`
67//! config flags convert degradation warnings into hard errors for callers that
68//! require guaranteed temporal/scope semantics rather than best-effort.
69//! - **Rebuild driver interface (KR-003)**: the [`RebuildDriver`] trait provides a
70//! defined contract for external callers to drive projection rebuilds. The
71//! [`rebuild_stale`] convenience function polls the tracker and drives rebuilds
72//! automatically. The tracker remains observability-only.
73//!
74//! ## Not Real Yet (Deferred)
75//!
76//! - **Range temporal expressions**: projection-backed temporal execution is
77//! implemented for concrete as-of markers such as `today`, `yesterday`,
78//! `last week`, and `this month`. Range-style phrases such as `before`,
79//! `after`, `since`, and `between` still degrade explicitly.
80//! - **Namespace-only hybrid scope**: `semantic-memory` hybrid search only
81//! pushes namespace. When runtime must use that path for a scoped query, the
82//! limitation is surfaced via `QueryWarning::ScopePartiallyEnforced` or
83//! `RuntimeError::ScopeNotFullyEnforced`.
84//! - **Projection persistence**: the `persist` config flag is rejected at
85//! validation time. Durable runtime projections are not implemented in this
86//! crate today.
87//! - **Projection rebuild execution**: the tracker is observability-only; it records
88//! build/failure events but does not schedule, execute, or retry rebuilds.
89//! External callers implement the [`RebuildDriver`] trait to drive actual rebuilds
90//! and report outcomes back to the tracker (KR-003).
91//! - **LLM-based intent classification**: classifier is rule-based heuristic.
92//! - **Evidence handle external dereference**: this layer does not resolve
93//! evidence handles against external stores.
94//! - **Advanced fuzzy entity resolution**: bounded candidate expansion exists,
95//! but there is no embedding-based or graph-ML entity resolver.
96
97pub mod adapters;
98pub mod config;
99pub mod entity;
100pub mod error;
101pub mod evidence;
102pub mod ids;
103mod inference;
104pub mod obs;
105pub mod projection;
106pub mod query;
107pub mod runtime;
108pub mod temporal;
109pub mod views;
110
111// Re-export primary public types.
112pub use config::RuntimeConfig;
113pub use error::RuntimeError;
114pub use ids::{EntityId, ProjectionId, ProjectionKind, Scope, ScopeKey};
115pub use inference::{InferenceAdvisory, InferenceExplanation, RiskGateDecision};
116pub use runtime::{
117 EntityCacheHandle, KnowledgeRuntime, ProjectedPromotionState, ProjectedVerificationLifecycle,
118 ProjectedVerificationSummary,
119};
120
121// Re-export commonly used inner types.
122pub use entity::code_ids::{CodeEntity, CodeEntityKind};
123pub use entity::registry::{Entity, EntityKind, EntityRegistry, MatchQuality, ResolveResult};
124pub use evidence::support::{AnswerBundle, EvidenceItem, EvidenceRelevance, SearchEvidenceBundle};
125pub use obs::trace::{
126 ProjectionAction, ProjectionTrace, QueryTrace, QueryWarning, RuntimeQueryProvenanceV1,
127};
128pub use projection::lifecycle::{
129 InvalidationEvent, ProjectionActionResult, ProjectionHealth, ProjectionMeta, ProjectionTracker,
130 ProjectionVersion, StaleCause,
131};
132pub use projection::rebuild::{rebuild_stale, RebuildDriver, RebuildOutcome};
133pub use query::classify::{ClassifyResult, QueryMode};
134pub use query::merge::{MergePolicy, MergedItem, MergedResults};
135pub use query::route::{LegFilter, RetrievalStrategy, RouteLeg, RoutePlan};
136pub use temporal::claims::{TemporalClaim, TemporalContradictionStatus};
137pub use views::{
138 CompiledObligationRuntimeViewV1, CompositionConflictRuntimeViewV1, ContinuityRuntimeViewV1,
139 DelegationRuntimeViewV1, DeployabilityRuntimeViewV1, EffectRuntimeViewV1,
140 EffectiveConstitutionViewV1, PolicyImpactDiffRuntimeViewV1,
141};