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