Skip to main content

codewhale_runtime/model_context/
fragment.rs

1//! One typed, capped, marker-stable ModelContext fragment.
2//!
3//! Caps and identities are unified with `codewhale_core::fragments` — the
4//! single `crates/core` owner for the bounded fragment system (issue #5264).
5//! This crate re-exports the core caps so every injection goes through a
6//! typed fragment with a stable marker and the hard caps
7//! (per-fragment size, 10K-token ceiling, injected-item count) are enforced
8//! in one place.
9
10use std::collections::hash_map::DefaultHasher;
11use std::hash::{Hash, Hasher};
12
13/// Re-export the core hard caps — single source of truth.
14pub use codewhale_core::fragments::{
15    DEFAULT_FRAGMENT_MAX_BYTES, MAX_FRAGMENT_BYTES, MAX_FRAGMENT_TOKENS, MAX_FRAGMENTS_PER_CONTEXT,
16};
17
18/// Stable identity for a WorldState concern. Markers are public contract —
19/// do not rename without a migration note (prefix-cache + tests pin them).
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub enum FragmentId {
22    Workspace,
23    Permissions,
24    Route,
25    AgentTopology,
26    SkillsTools,
27    TokenBudget,
28    ProjectInstructions,
29    Constitution,
30}
31
32impl FragmentId {
33    #[must_use]
34    pub fn as_str(self) -> &'static str {
35        match self {
36            Self::Workspace => "workspace",
37            Self::Permissions => "permissions",
38            Self::Route => "route",
39            Self::AgentTopology => "agent_topology",
40            Self::SkillsTools => "skills_tools",
41            Self::TokenBudget => "token_budget",
42            Self::ProjectInstructions => "project_instructions",
43            Self::Constitution => "constitution",
44        }
45    }
46
47    /// Stable HTML-comment marker wrapping the fragment body.
48    #[must_use]
49    pub fn marker(self) -> &'static str {
50        match self {
51            Self::Workspace => "<!-- cw:ctx:workspace -->",
52            Self::Permissions => "<!-- cw:ctx:permissions -->",
53            Self::Route => "<!-- cw:ctx:route -->",
54            Self::AgentTopology => "<!-- cw:ctx:agent_topology -->",
55            Self::SkillsTools => "<!-- cw:ctx:skills_tools -->",
56            Self::TokenBudget => "<!-- cw:ctx:token_budget -->",
57            Self::ProjectInstructions => "<!-- cw:ctx:project_instructions -->",
58            Self::Constitution => "<!-- cw:ctx:constitution -->",
59        }
60    }
61
62    #[must_use]
63    pub fn role(self) -> FragmentRole {
64        match self {
65            Self::Workspace => FragmentRole::Workspace,
66            Self::Permissions => FragmentRole::Permissions,
67            Self::Route => FragmentRole::Route,
68            Self::AgentTopology => FragmentRole::AgentTopology,
69            Self::SkillsTools => FragmentRole::SkillsTools,
70            Self::TokenBudget => FragmentRole::TokenBudget,
71            Self::ProjectInstructions => FragmentRole::ProjectInstructions,
72            Self::Constitution => FragmentRole::Constitution,
73        }
74    }
75
76    #[must_use]
77    pub fn all() -> &'static [FragmentId] {
78        &[
79            Self::Workspace,
80            Self::Permissions,
81            Self::Route,
82            Self::AgentTopology,
83            Self::SkillsTools,
84            Self::TokenBudget,
85            Self::ProjectInstructions,
86            Self::Constitution,
87        ]
88    }
89}
90
91/// Explicit role of a fragment relative to the cache-stable constitution.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
93pub enum FragmentRole {
94    /// Workspace / repo working-set facts (volatile across sessions).
95    Workspace,
96    /// Approval / permission posture.
97    Permissions,
98    /// Active route, model, and app mode.
99    Route,
100    /// Sub-agent topology and recent completion notices.
101    AgentTopology,
102    /// Skills, plugins, and tool availability summary.
103    SkillsTools,
104    /// Token budget and compaction status.
105    TokenBudget,
106    /// Project instructions (AGENTS.md + imported instruction files).
107    ProjectInstructions,
108    /// Codewhale-specific repo constitution.
109    Constitution,
110}
111
112impl FragmentRole {
113    #[must_use]
114    pub fn as_str(self) -> &'static str {
115        match self {
116            Self::Workspace => "workspace",
117            Self::Permissions => "permissions",
118            Self::Route => "route",
119            Self::AgentTopology => "agent_topology",
120            Self::SkillsTools => "skills_tools",
121            Self::TokenBudget => "token_budget",
122            Self::ProjectInstructions => "project_instructions",
123            Self::Constitution => "constitution",
124        }
125    }
126}
127
128/// Result of comparing a fragment against its previous render.
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub enum FragmentRender {
131    /// Content hash matches previous — retain bytes; do not reinject.
132    Unchanged { marker: String, content_hash: u64 },
133    /// New or changed content — inject the capped body.
134    Updated { fragment: ModelContextFragment },
135    /// Fragment was present before and is now absent.
136    Cleared { marker: String },
137}
138
139/// One capped WorldState section with a stable marker and content hash.
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct ModelContextFragment {
142    pub id: FragmentId,
143    pub role: FragmentRole,
144    pub marker: &'static str,
145    pub max_bytes: usize,
146    pub content: String,
147    pub content_hash: u64,
148}
149
150impl ModelContextFragment {
151    #[must_use]
152    pub fn new(id: FragmentId, role: FragmentRole, raw: impl Into<String>) -> Self {
153        Self::with_max_bytes(id, role, raw, DEFAULT_FRAGMENT_MAX_BYTES)
154    }
155
156    #[must_use]
157    pub fn with_max_bytes(
158        id: FragmentId,
159        role: FragmentRole,
160        raw: impl Into<String>,
161        max_bytes: usize,
162    ) -> Self {
163        // Clamp to the global 10K-token ceiling so callers cannot opt out.
164        let clamped_max = max_bytes.min(MAX_FRAGMENT_BYTES);
165        let mut content = enforce_byte_cap(raw.into(), clamped_max);
166        // Token-ceiling safety net (4 bytes ≈ 1 token).
167        if content.len().div_ceil(4) > MAX_FRAGMENT_TOKENS {
168            content = enforce_byte_cap(content, MAX_FRAGMENT_BYTES);
169        }
170        let content_hash = hash_content(&content);
171        Self {
172            id,
173            role,
174            marker: id.marker(),
175            max_bytes: clamped_max,
176            content,
177            content_hash,
178        }
179    }
180
181    /// Return whether `haystack` contains this fragment's stable marker.
182    #[must_use]
183    pub fn matches_text(&self, haystack: &str) -> bool {
184        haystack.contains(self.marker)
185    }
186
187    /// Compare against a previous fragment of the same id.
188    #[must_use]
189    pub fn render_diff(&self, previous: Option<&Self>) -> FragmentRender {
190        match previous {
191            Some(prev) if prev.content_hash == self.content_hash && prev.marker == self.marker => {
192                FragmentRender::Unchanged {
193                    marker: self.marker.to_string(),
194                    content_hash: self.content_hash,
195                }
196            }
197            _ => FragmentRender::Updated {
198                fragment: self.clone(),
199            },
200        }
201    }
202
203    /// Full render including the stable marker header.
204    #[must_use]
205    pub fn render_marked(&self) -> String {
206        let rendered = format!("{}\n{}", self.marker, self.content.trim_end());
207        debug_assert!(self.matches_text(&rendered));
208        rendered
209    }
210}
211
212fn hash_content(content: &str) -> u64 {
213    let mut hasher = DefaultHasher::new();
214    content.hash(&mut hasher);
215    hasher.finish()
216}
217
218fn enforce_byte_cap(raw: String, max_bytes: usize) -> String {
219    if max_bytes == 0 {
220        return String::new();
221    }
222    if raw.len() <= max_bytes {
223        return raw;
224    }
225    let omitted = raw.len().saturating_sub(max_bytes);
226    let marker = format!("\n[…truncated: {omitted} bytes omitted]");
227    if marker.len() >= max_bytes {
228        return marker.chars().take(max_bytes).collect();
229    }
230    let keep = max_bytes.saturating_sub(marker.len());
231    // Truncate on a char boundary.
232    let mut end = keep;
233    while end > 0 && !raw.is_char_boundary(end) {
234        end -= 1;
235    }
236    let mut out = raw[..end].to_string();
237    out.push_str(&marker);
238    out
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn render_diff_detects_change_and_retain() {
247        let a = ModelContextFragment::new(FragmentId::Route, FragmentRole::Route, "m=a");
248        let b = ModelContextFragment::new(FragmentId::Route, FragmentRole::Route, "m=a");
249        let c = ModelContextFragment::new(FragmentId::Route, FragmentRole::Route, "m=b");
250        assert!(matches!(
251            b.render_diff(Some(&a)),
252            FragmentRender::Unchanged { .. }
253        ));
254        assert!(matches!(
255            c.render_diff(Some(&a)),
256            FragmentRender::Updated { .. }
257        ));
258        assert!(matches!(
259            a.render_diff(None),
260            FragmentRender::Updated { .. }
261        ));
262    }
263}