rag_plusplus_core/trajectory/
mod.rs

1//! Trajectory Memory Module
2//!
3//! High-performance algorithms for trajectory-structured memory, implementing
4//! concepts from IRCP (Inverse Ring Contextual Propagation) and RCP (Ring
5//! Contextual Propagation).
6//!
7//! # Components
8//!
9//! | Module | Purpose |
10//! |--------|---------|
11//! | [`graph`] | DAG traversal, path finding, branch detection |
12//! | [`phase`] | Phase inference from episode patterns |
13//! | [`salience`] | Importance weighting for bounded forgetting |
14//! | [`ring`] | Circular topology for multi-scale context (includes DualRing) |
15//! | [`coordinate`] | 5D positioning system (DLM coordinates with complexity) |
16//! | [`coordinate_tree`] | Tree operations with O(log n) LCA via binary lifting |
17//! | [`conservation`] | Conservation metrics for forgetting validation |
18//! | [`ircp`] | Inverse Ring Contextual Propagation attention |
19//! | [`chainlink`] | ChainLink interaction framework with 4-component estimation |
20//! | [`branch`] | Branch state machine for split/merge/recover operations |
21//! | [`chain`] | Multi-chain management for conversation tracking |
22//!
23//! # Conceptual Framework
24//!
25//! - **Trajectory**: A sequence of experiences (episodes) forming a path through time
26//! - **Episode**: A unit of experience (message turn, interaction, decision point)
27//! - **Phase**: A qualitative state within a trajectory:
28//!   - `Exploration`: Initial inquiry, questions, topic discovery
29//!   - `Consolidation`: Building understanding, code implementation
30//!   - `Synthesis`: Summarization, decisions, conclusions
31//!   - `Debugging`: Error resolution, troubleshooting
32//!   - `Planning`: Roadmaps, structured plans
33//! - **Salience**: Importance weight [0, 1] for bounded forgetting
34//! - **Conservation**: Metrics ensuring memory operations preserve invariants
35//!
36//! # Coordinate System (5D DLM)
37//!
38//! Each episode has a 5D position (extending TPO with complexity):
39//!
40//! | Dimension | Type | Meaning |
41//! |-----------|------|---------|
42//! | `depth` | u32 | Distance from root (0 = root) |
43//! | `sibling_order` | u32 | Position among siblings |
44//! | `homogeneity` | f32 | Semantic similarity to parent [0, 1] |
45//! | `temporal` | f32 | Normalized timestamp [0, 1] |
46//! | `complexity` | u32 | Message complexity (n_parts from DLM) |
47//!
48//! # Dual Ring Structure (IRCP/RCP)
49//!
50//! The `DualRing` provides two simultaneous orderings over the same episodes:
51//!
52//! | Ring | Direction | Ordering | Use Case |
53//! |------|-----------|----------|----------|
54//! | **Temporal** (RCP) | Forward | Time/causal sequence | "What context led here?" |
55//! | **Influence** (IRCP) | Inverse | By influence weight | "What had most impact?" |
56//!
57//! ```text
58//! Temporal Ring (RCP):     [E₀] → [E₁] → [E₂] → [E₃] → [E₄] ─┐
59//!                            ↑                                 │
60//!                            └─────────────────────────────────┘
61//!
62//! Influence Ring (IRCP):   [E₂] → [E₄] → [E₀] → [E₃] → [E₁] ─┐
63//!                            ↑     (sorted by influence)      │
64//!                            └────────────────────────────────┘
65//! ```
66//!
67//! # Conservation Laws
68//!
69//! Per RCP, memory operations should preserve:
70//!
71//! | Law | Formula | Meaning |
72//! |-----|---------|---------|
73//! | Magnitude | Σ aᵢ‖eᵢ‖ = const | Context doesn't disappear |
74//! | Energy | ½Σᵢⱼ aᵢaⱼ cos(eᵢ,eⱼ) | Attention capacity conserved |
75//! | Information | -Σ aᵢ log(aᵢ) | Shannon entropy of attention |
76//!
77//! # Performance
78//!
79//! These algorithms are implemented in Rust for performance because they run
80//! repeatedly during retrieval and corpus maintenance. Key optimizations:
81//!
82//! - SIMD-accelerated distance computations (via `distance` module)
83//! - Cache-friendly contiguous storage in Ring topology
84//! - O(1) neighbor access in ring structure
85//! - Efficient hash-based DAG traversal
86//!
87//! # Example Usage
88//!
89//! ```ignore
90//! use rag_plusplus_core::trajectory::{
91//!     TrajectoryGraph, Edge, EdgeType, PathSelectionPolicy,
92//!     PhaseInferencer, TurnFeatures, TrajectoryPhase,
93//!     SalienceScorer, SalienceFactors, Feedback,
94//!     Ring, TrajectoryCoordinate,
95//!     ConservationMetrics,
96//! };
97//!
98//! // Build trajectory graph from edges
99//! let edges = vec![
100//!     Edge { parent: 1, child: 2, edge_type: EdgeType::Continuation },
101//!     Edge { parent: 2, child: 3, edge_type: EdgeType::Continuation },
102//! ];
103//! let graph = TrajectoryGraph::from_edges(edges.iter().copied());
104//!
105//! // Find primary path through DAG
106//! let primary = graph.find_primary_path(PathSelectionPolicy::FeedbackFirst);
107//!
108//! // Infer phases from episode features
109//! let inferencer = PhaseInferencer::new();
110//! let features = TurnFeatures::from_content(1, "user", "What is this?");
111//! let (phase, confidence) = inferencer.infer_single(&features).unwrap();
112//!
113//! // Compute salience scores
114//! let scorer = SalienceScorer::new();
115//! let factors = SalienceFactors {
116//!     turn_id: 1,
117//!     feedback: Some(Feedback::ThumbsUp),
118//!     ..Default::default()
119//! };
120//! let salience = scorer.score_single(&factors, None);
121//!
122//! // Build ring structure
123//! let ring = Ring::new(vec![1, 2, 3, 4, 5]);
124//! let distance = ring.ring_distance(0, 3); // Shortest path: 2
125//!
126//! // Validate conservation
127//! let embeddings = vec![vec![1.0, 0.0, 0.0], vec![0.0, 1.0, 0.0]];
128//! let refs: Vec<&[f32]> = embeddings.iter().map(|e| e.as_slice()).collect();
129//! let attention = vec![0.5, 0.5];
130//! let metrics = ConservationMetrics::compute(&refs, &attention);
131//! ```
132
133pub mod branch;
134pub mod chain;
135pub mod chainlink;
136pub mod conservation;
137pub mod coordinate;
138pub mod coordinate_tree;
139pub mod graph;
140pub mod ircp;
141pub mod path_quality;
142pub mod phase;
143pub mod ring;
144pub mod salience;
145
146// Re-exports
147pub use conservation::{
148    ConservationMetrics, ConservationViolation, ConservationConfig,
149    ConservationTracker, weighted_centroid, weighted_covariance,
150};
151pub use coordinate::{
152    TrajectoryCoordinate, NormalizedCoordinate,
153    // 5D coordinates (TPO extension with complexity dimension)
154    TrajectoryCoordinate5D, NormalizedCoordinate5D,
155    // DLM weight configuration for distance calculations
156    DLMWeights,
157    compute_trajectory_coordinates,
158};
159pub use graph::{
160    TrajectoryGraph, Episode, Edge, EdgeType, NodeId,
161    PathSelectionPolicy, TraversalOrder, BranchInfo, PathResult,
162};
163pub use phase::{
164    TrajectoryPhase, PhaseInferencer, PhaseConfig,
165    TurnFeatures, PhaseTransition,
166};
167
168// Backward compatibility - ConversationPhase is deprecated in favor of TrajectoryPhase
169#[allow(deprecated)]
170pub use phase::ConversationPhase;
171pub use ring::{
172    Ring, RingNode, EpisodeRing, build_weighted_ring,
173    // Dual ring structure for IRCP/RCP
174    DualRing, DualRingNode, build_dual_ring, build_dual_ring_with_attention,
175};
176pub use path_quality::{
177    PathQuality, PathQualityWeights, PathQualityFactors,
178};
179pub use salience::{
180    SalienceScorer, SalienceConfig, SalienceFactors,
181    TurnSalience, CorpusSalienceStats, Feedback,
182};
183pub use ircp::{
184    IRCPPropagator, IRCPConfig, AttentionWeights,
185    batch_compute_attention, compute_attention_matrix,
186};
187pub use chainlink::{
188    ChainLink, ChainLinkEstimator, ChainLinkEstimatorConfig,
189    ChainLinkEstimate, LinkType,
190    compute_chain_matrix, find_strongest_links,
191};
192pub use coordinate_tree::{
193    CoordinateTree, TreeNode, build_coordinate_tree,
194};
195pub use branch::{
196    // Branch state machine for split/merge/recover operations
197    BranchStateMachine, BranchContext, SplitResult, MergeResult,
198    // Core branch types
199    Branch, BranchId, BranchOperation, BranchStatus, ForkPoint, BranchError,
200    // Branch resolution for "lost branch" recovery
201    BranchResolver, RecoverableBranch, RecoveryStrategy, LostReason,
202};
203pub use chain::{
204    // Chain manager for multi-conversation tracking
205    ChainManager, ChainId, ChainMetadata, ChainManagerConfig,
206    ChainManagerError, ChainManagerStats,
207    // Cross-chain links
208    CrossChainLink, CrossChainLinkType, LinkStrength,
209    find_cross_chain_links, detect_knowledge_transfer,
210    KNOWLEDGE_TRANSFER_PATTERNS,
211};