zeph_context/input.rs
1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Input types for context assembly.
5//!
6//! [`ContextAssemblyInput`] collects all references needed for one assembly turn.
7//! [`ContextMemoryView`] is a snapshot of memory-subsystem configuration that the
8//! assembler reads but never mutates — callers in `zeph-core` populate it from
9//! `MemoryState` before each assembly pass.
10
11use std::borrow::Cow;
12use std::sync::Arc;
13
14use zeph_config::{
15 DocumentConfig, GraphConfig, PersonaConfig, ReasoningConfig, TrajectoryConfig, TreeConfig,
16};
17use zeph_memory::semantic::SemanticMemory;
18use zeph_memory::{ConversationId, TokenCounter};
19
20use crate::manager::ContextManager;
21
22/// All borrowed data needed to assemble context for one agent turn.
23///
24/// All fields are shared references — `ContextAssembler::gather` never mutates any state.
25/// The caller (in `zeph-core`) is responsible for populating this struct and passing it to
26/// [`crate::assembler::ContextAssembler::gather`].
27pub struct ContextAssemblyInput<'a> {
28 /// Snapshot of memory subsystem configuration for this turn.
29 pub memory: &'a ContextMemoryView,
30 /// Context lifecycle state machine.
31 pub context_manager: &'a ContextManager,
32 /// Token counter for budget enforcement.
33 pub token_counter: &'a TokenCounter,
34 /// Text of the skills prompt injected in the last turn (used for budget calculation).
35 pub skills_prompt: &'a str,
36 /// Index RAG accessor. `None` when code-index is disabled.
37 pub index: Option<&'a dyn IndexAccess>,
38 /// Learning engine corrections config. `None` when self-learning is disabled.
39 pub correction_config: Option<CorrectionConfig>,
40 /// Current value of the sidequest turn counter, for adaptive strategy selection.
41 pub sidequest_turn_counter: u64,
42 /// Message window snapshot used for strategy resolution and system-prompt extraction.
43 pub messages: &'a [zeph_llm::provider::Message],
44 /// The user query for the current turn, used as the search query for all memory lookups.
45 pub query: &'a str,
46 /// Content scrubber for PII removal. Passed as a function pointer to avoid a dependency
47 /// on `zeph-core`'s redact module.
48 pub scrub: fn(&str) -> Cow<'_, str>,
49}
50
51/// Configuration extracted from `LearningEngine` needed by correction recall.
52///
53/// Populated from `LearningEngine::config` in `zeph-core` and passed into
54/// [`ContextAssemblyInput`].
55#[derive(Debug, Clone, Copy)]
56pub struct CorrectionConfig {
57 /// Whether correction detection is active.
58 pub correction_detection: bool,
59 /// Maximum number of corrections to recall per turn.
60 pub correction_recall_limit: u32,
61 /// Minimum similarity score for a correction to be considered relevant.
62 pub correction_min_similarity: f32,
63}
64
65/// Read-only snapshot of memory subsystem state needed for context assembly.
66///
67/// This struct is populated by the caller (`zeph-core`) from `MemoryState` before each
68/// assembly pass. It contains only the fields that [`crate::assembler::ContextAssembler`]
69/// actually reads — no `Agent` methods, no mutation.
70pub struct ContextMemoryView {
71 // ── persistence fields ────────────────────────────────────────────────────
72 /// Semantic memory backend. `None` when memory is disabled.
73 pub memory: Option<Arc<SemanticMemory>>,
74 /// Active conversation ID. `None` before the first message is persisted.
75 pub conversation_id: Option<ConversationId>,
76 /// Maximum number of semantic recall hits injected per turn.
77 pub recall_limit: usize,
78 /// Minimum semantic similarity score for cross-session recall (0.0–1.0).
79 pub cross_session_score_threshold: f32,
80
81 // ── compaction fields ─────────────────────────────────────────────────────
82 /// Context assembly strategy (`FullHistory` / `MemoryFirst` / `Adaptive`).
83 pub context_strategy: zeph_config::ContextStrategy,
84 /// Turn threshold for `Adaptive` strategy crossover.
85 pub crossover_turn_threshold: u32,
86 /// Cached session digest text and token count, loaded at session start.
87 pub cached_session_digest: Option<(String, usize)>,
88
89 // ── extraction fields ─────────────────────────────────────────────────────
90 /// Knowledge graph configuration.
91 pub graph_config: GraphConfig,
92 /// Document RAG configuration.
93 pub document_config: DocumentConfig,
94 /// Persona memory configuration.
95 pub persona_config: PersonaConfig,
96 /// Trajectory-informed memory configuration.
97 pub trajectory_config: TrajectoryConfig,
98 /// `ReasoningBank` configuration (#3343).
99 pub reasoning_config: ReasoningConfig,
100
101 // ── subsystem fields ──────────────────────────────────────────────────────
102 /// `TiMem` temporal-hierarchical memory tree configuration.
103 pub tree_config: TreeConfig,
104}
105
106/// Read-only access to a code-index retriever.
107///
108/// Implemented by `IndexState` in `zeph-core`. The assembler calls only `fetch_code_rag`
109/// to populate the `code_context` slot.
110///
111/// The return type uses `Pin<Box<dyn Future>>` rather than `async fn` to preserve
112/// dyn-compatibility: the trait is used as `&dyn IndexAccess` in `ContextAssemblyInput`.
113pub trait IndexAccess: Send + Sync {
114 /// Retrieve up to `budget_tokens` of code context for the given `query`.
115 ///
116 /// Returns `None` when no relevant context is found or when code-index is disabled.
117 ///
118 /// # Errors
119 ///
120 /// Propagates errors from the underlying code retriever.
121 fn fetch_code_rag<'a>(
122 &'a self,
123 query: &'a str,
124 budget_tokens: usize,
125 ) -> std::pin::Pin<
126 Box<
127 dyn std::future::Future<Output = Result<Option<String>, crate::error::ContextError>>
128 + Send
129 + 'a,
130 >,
131 >;
132}