Skip to main content

merry_runtime/context/
input.rs

1use super::ContextError;
2use crate::memory::ActivatedMemory;
3
4const FNV_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
5const FNV_PRIME: u64 = 0x100000001b3;
6
7fn validate_non_blank(field: &'static str, value: &str) -> Result<(), ContextError> {
8    if value.trim().is_empty() {
9        return Err(ContextError::BlankField { field });
10    }
11
12    Ok(())
13}
14
15fn sanitize_context_text(field: &'static str, value: String) -> Result<String, ContextError> {
16    let cleaned = match crate::user_input::sanitize_freeform_text(&value) {
17        std::borrow::Cow::Borrowed(_) => value,
18        std::borrow::Cow::Owned(cleaned) => cleaned,
19    };
20    validate_non_blank(field, &cleaned)?;
21    Ok(cleaned)
22}
23
24fn validate_no_control_characters(field: &'static str, value: &str) -> Result<(), ContextError> {
25    if value
26        .chars()
27        .any(|character| character.is_control() && character != '\n' && character != '\t')
28    {
29        return Err(ContextError::InvalidControlCharacter { field });
30    }
31
32    Ok(())
33}
34
35pub(crate) fn stable_content_hash(bytes: &[u8]) -> String {
36    let mut hash = FNV_OFFSET_BASIS;
37    for byte in bytes {
38        hash = (hash ^ u64::from(*byte)).wrapping_mul(FNV_PRIME);
39    }
40    format!("fnv1a64:{hash:016x}")
41}
42/// Session-owned context state and internal projections.
43///
44/// The fields are private so public callers can compile only snapshots created
45/// by the runtime session that owns context entries and crate-internal
46/// projections.
47///
48/// Treat this as an opaque view of session state. It is cloneable for
49/// deterministic compilation and tests, but external callers should not depend
50/// on its internal storage shape.
51///
52/// ```compile_fail
53/// use merry_runtime::{ContextEntry, SessionContextSnapshot};
54///
55/// let entries: Vec<ContextEntry> = Vec::new();
56///
57/// let _ = SessionContextSnapshot { entries };
58/// ```
59#[derive(Debug, Clone)]
60pub struct SessionContextSnapshot {
61    entries: Vec<ContextEntry>,
62    memories: Vec<ActivatedMemory>,
63    compacted_checkpoint: Option<CompactedCheckpoint>,
64}
65
66impl SessionContextSnapshot {
67    pub(crate) fn new(
68        entries: Vec<ContextEntry>,
69        memories: Vec<ActivatedMemory>,
70        compacted_checkpoint: Option<CompactedCheckpoint>,
71    ) -> Self {
72        Self {
73            entries,
74            memories,
75            compacted_checkpoint,
76        }
77    }
78
79    pub(super) fn entries(&self) -> &[ContextEntry] {
80        &self.entries
81    }
82
83    pub(super) fn memories(&self) -> &[ActivatedMemory] {
84        &self.memories
85    }
86
87    pub(super) fn compacted_checkpoint(&self) -> Option<&CompactedCheckpoint> {
88        self.compacted_checkpoint.as_ref()
89    }
90
91    #[cfg(test)]
92    pub(crate) fn compacted_checkpoint_for_tests(&self) -> Option<&CompactedCheckpoint> {
93        self.compacted_checkpoint.as_ref()
94    }
95}
96
97/// Structured input item for the public context compiler view.
98///
99/// The MVP public view has only summary/note entries. Crate-internal projections,
100/// including activated memory, are carried by [`SessionContextSnapshot`] rather
101/// than exposed as public entries.
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub enum ContextEntry {
104    /// A compact runtime context summary or dynamic note.
105    Summary(ContextSummary),
106}
107
108impl ContextEntry {
109    /// Creates a summary context entry.
110    #[must_use]
111    pub fn summary(summary: ContextSummary) -> Self {
112        Self::Summary(summary)
113    }
114
115    pub(crate) fn as_summary(&self) -> &ContextSummary {
116        match self {
117            Self::Summary(summary) => summary,
118        }
119    }
120}
121
122/// Runtime-owned dynamic context note or summary entry.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct ContextSummary {
125    id: String,
126    text: String,
127}
128
129impl ContextSummary {
130    /// Creates a validated context summary.
131    pub fn new(id: impl Into<String>, text: impl Into<String>) -> Result<Self, ContextError> {
132        let id = id.into();
133        validate_non_blank("context summary id", &id)?;
134
135        let text = text.into();
136        validate_non_blank("context summary text", &text)?;
137
138        Ok(Self { id, text })
139    }
140
141    /// Stable summary identifier used for deterministic ordering.
142    #[must_use]
143    pub fn id(&self) -> &str {
144        &self.id
145    }
146
147    /// Text for this summary.
148    #[must_use]
149    pub fn text(&self) -> &str {
150        &self.text
151    }
152}
153
154/// Stable project instructions explicitly loaded by runtime construction.
155///
156/// Project rules are durable prompt policy such as `AGENTS.md`. They are not
157/// ledger projection, context summaries, or tool-result observations.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct ProjectRules {
160    source_path: String,
161    text: String,
162    content_hash: String,
163}
164
165impl ProjectRules {
166    /// Creates validated project rules for the stable request prefix.
167    pub fn new(
168        source_path: impl Into<String>,
169        text: impl Into<String>,
170    ) -> Result<Self, ContextError> {
171        let source_path = source_path.into();
172        validate_non_blank("project rules source path", &source_path)?;
173        validate_no_control_characters("project rules source path", &source_path)?;
174
175        let text = sanitize_context_text("project rules text", text.into())?;
176
177        let content_hash = stable_content_hash(text.as_bytes());
178        Ok(Self {
179            source_path,
180            text,
181            content_hash,
182        })
183    }
184
185    /// Project-relative source path or label for these rules.
186    #[must_use]
187    pub fn source_path(&self) -> &str {
188        &self.source_path
189    }
190
191    /// Exact project rules text.
192    #[must_use]
193    pub fn text(&self) -> &str {
194        &self.text
195    }
196
197    /// Stable non-cryptographic fingerprint of the rules text.
198    #[must_use]
199    pub fn content_hash(&self) -> &str {
200        &self.content_hash
201    }
202
203    /// Renders the exact provider-neutral project-rules stable-prefix block.
204    #[must_use]
205    pub fn to_stable_prefix_message_text(&self) -> String {
206        format!(
207            "project-rules-source:{}\nproject-rules-content-hash:{}\n{}",
208            self.source_path, self.content_hash, self.text
209        )
210    }
211}
212
213/// Current task objective pinned by a future `/task`-style control command.
214///
215/// A task anchor is session control-plane context. It is neither durable
216/// project policy nor ordinary ordered transcript history, so request compilation
217/// renders it outside the stable prefix and before checkpoint/context/body
218/// projection.
219#[derive(Debug, Clone, PartialEq, Eq)]
220pub struct TaskAnchor {
221    objective: String,
222}
223
224impl TaskAnchor {
225    /// Creates a validated task anchor objective.
226    pub fn new(objective: impl Into<String>) -> Result<Self, ContextError> {
227        let objective = sanitize_context_text("task anchor objective", objective.into())?;
228        Ok(Self { objective })
229    }
230
231    /// Current pinned task objective.
232    #[must_use]
233    pub fn objective(&self) -> &str {
234        &self.objective
235    }
236
237    pub(crate) fn to_dynamic_control_message_text(&self) -> String {
238        format!("task-anchor:\n{}", self.objective)
239    }
240}
241
242/// Runtime-owned checkpoint left after compacting earlier dynamic state.
243///
244/// This prompt-facing context is intentionally narrower than arbitrary context
245/// projection: ordinary ledger facts, artifact payloads, and tool-result
246/// observations must not enter through this path until a checkpoint/compaction
247/// boundary has selected and compacted them.
248#[derive(Debug, Clone, PartialEq, Eq)]
249pub struct CompactedCheckpoint {
250    text: String,
251}
252
253/// Payload-free notice that a prose checkpoint is installed.
254#[derive(Debug, Clone, Copy, PartialEq, Eq)]
255pub struct CompactedCheckpointSummary;
256
257impl CompactedCheckpoint {
258    /// Creates validated compacted checkpoint text.
259    pub fn new(text: impl Into<String>) -> Result<Self, ContextError> {
260        let text = sanitize_context_text("compacted checkpoint text", text.into())?;
261
262        Ok(Self { text })
263    }
264
265    /// Compacted checkpoint text selected by a checkpoint/compaction boundary.
266    #[must_use]
267    pub fn text(&self) -> &str {
268        &self.text
269    }
270
271    /// Payload-free summary for diagnostics. This excludes the checkpoint text.
272    #[must_use]
273    pub fn summary(&self) -> CompactedCheckpointSummary {
274        CompactedCheckpointSummary
275    }
276}