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_common::PlannedToolHint;
15use zeph_common::memory::{CompressionLevel, ContextMemoryBackend};
16use zeph_config::{
17 DocumentConfig, GraphConfig, PersonaConfig, ReasoningConfig, TrajectoryConfig, TreeConfig,
18};
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 dyn zeph_common::memory::TokenCounting,
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 /// Compression tiers active for this turn, derived from the retrieval policy.
50 ///
51 /// The assembler skips fetchers whose tier is not present in this slice.
52 /// An empty slice means "no tier filtering" — all fetchers run subject to their own budget
53 /// gates. This is the defensive default: a caller that accidentally passes an empty slice
54 /// will get the same behaviour as before this field existed, rather than silently dropping
55 /// all memory recall.
56 ///
57 /// A caller computing this from a config-driven policy must guarantee non-empty intent or
58 /// accept that an empty slice disables tier-based filtering entirely.
59 pub active_levels: &'a [CompressionLevel],
60 /// Pre-built memory router for this turn. Built by `zeph-core` via `build_memory_router()`
61 /// and passed in to avoid a `zeph-memory` dependency inside `zeph-context`.
62 pub router: Box<dyn zeph_common::memory::AsyncMemoryRouter + Send + Sync>,
63 /// Lookahead hints from the orchestration DAG for plan-aware scoring.
64 ///
65 /// Pass `&[]` when no DAG context is available (PAACE data structure only in MVP).
66 pub planned_next_tools: &'a [PlannedToolHint],
67}
68
69/// Configuration extracted from `LearningEngine` needed by correction recall.
70///
71/// Populated from `LearningEngine::config` in `zeph-core` and passed into
72/// [`ContextAssemblyInput`].
73#[derive(Debug, Clone, Copy)]
74pub struct CorrectionConfig {
75 /// Whether correction detection is active.
76 pub correction_detection: bool,
77 /// Maximum number of corrections to recall per turn.
78 pub correction_recall_limit: u32,
79 /// Minimum similarity score for a correction to be considered relevant.
80 pub correction_min_similarity: f32,
81}
82
83/// Read-only snapshot of memory subsystem state needed for context assembly.
84///
85/// This struct is populated by the caller (`zeph-core`) from `MemoryState` before each
86/// assembly pass. It contains only the fields that [`crate::assembler::ContextAssembler`]
87/// actually reads — no `Agent` methods, no mutation.
88pub struct ContextMemoryView {
89 // ── persistence fields ────────────────────────────────────────────────────
90 /// Semantic memory backend. `None` when memory is disabled.
91 pub memory: Option<Arc<dyn ContextMemoryBackend>>,
92 /// Active conversation ID (`conversations.id` raw value). `None` before the first message is persisted.
93 pub conversation_id: Option<i64>,
94 /// Maximum number of semantic recall hits injected per turn.
95 pub recall_limit: usize,
96 /// Minimum semantic similarity score for cross-session recall (0.0–1.0).
97 pub cross_session_score_threshold: f32,
98
99 // ── compaction fields ─────────────────────────────────────────────────────
100 /// Context assembly strategy (`FullHistory` / `MemoryFirst` / `Adaptive`).
101 pub context_strategy: zeph_config::ContextStrategy,
102 /// Turn threshold for `Adaptive` strategy crossover.
103 pub crossover_turn_threshold: u32,
104 /// Cached session digest text and token count, loaded at session start.
105 pub cached_session_digest: Option<(String, usize)>,
106
107 // ── extraction fields ─────────────────────────────────────────────────────
108 /// Knowledge graph configuration.
109 pub graph_config: GraphConfig,
110 /// Document RAG configuration.
111 pub document_config: DocumentConfig,
112 /// Persona memory configuration.
113 pub persona_config: PersonaConfig,
114 /// Trajectory-informed memory configuration.
115 pub trajectory_config: TrajectoryConfig,
116 /// `ReasoningBank` configuration (#3343).
117 pub reasoning_config: ReasoningConfig,
118 /// `MemCoT` semantic state configuration (#3574).
119 pub memcot_config: zeph_config::MemCotConfig,
120 /// Current `MemCoT` semantic state buffer snapshot. `Some` when `MemCoT` is enabled and the
121 /// accumulator has distilled at least one turn.
122 pub memcot_state: Option<String>,
123
124 // ── subsystem fields ──────────────────────────────────────────────────────
125 /// `TiMem` temporal-hierarchical memory tree configuration.
126 pub tree_config: TreeConfig,
127}
128
129/// Read-only access to a code-index retriever.
130///
131/// Implemented by `IndexState` in `zeph-core`. The assembler calls only `fetch_code_rag`
132/// to populate the `code_context` slot.
133///
134/// The return type uses `Pin<Box<dyn Future>>` rather than `async fn` to preserve
135/// dyn-compatibility: the trait is used as `&dyn IndexAccess` in `ContextAssemblyInput`.
136pub trait IndexAccess: Send + Sync {
137 /// Retrieve up to `budget_tokens` of code context for the given `query`.
138 ///
139 /// Returns `None` when no relevant context is found or when code-index is disabled.
140 ///
141 /// # Errors
142 ///
143 /// Propagates errors from the underlying code retriever.
144 fn fetch_code_rag<'a>(
145 &'a self,
146 query: &'a str,
147 budget_tokens: usize,
148 ) -> std::pin::Pin<
149 Box<
150 dyn std::future::Future<Output = Result<Option<String>, crate::error::AssemblerError>>
151 + Send
152 + 'a,
153 >,
154 >;
155}