codewhale_runtime/model_context/
fragment.rs1use std::collections::hash_map::DefaultHasher;
11use std::hash::{Hash, Hasher};
12
13pub use codewhale_core::fragments::{
15 DEFAULT_FRAGMENT_MAX_BYTES, MAX_FRAGMENT_BYTES, MAX_FRAGMENT_TOKENS, MAX_FRAGMENTS_PER_CONTEXT,
16};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub enum FragmentId {
22 Workspace,
23 Permissions,
24 Route,
25 AgentTopology,
26 SkillsTools,
27 SessionRelay,
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::SessionRelay => "session_relay",
42 Self::ProjectInstructions => "project_instructions",
43 Self::Constitution => "constitution",
44 }
45 }
46
47 #[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::SessionRelay => "<!-- cw:ctx:session_relay -->",
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::SessionRelay => FragmentRole::SessionRelay,
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::SessionRelay,
85 Self::ProjectInstructions,
86 Self::Constitution,
87 ]
88 }
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
93pub enum FragmentRole {
94 Workspace,
96 Permissions,
98 Route,
100 AgentTopology,
102 SkillsTools,
104 SessionRelay,
106 ProjectInstructions,
108 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::SessionRelay => "session_relay",
122 Self::ProjectInstructions => "project_instructions",
123 Self::Constitution => "constitution",
124 }
125 }
126}
127
128#[derive(Debug, Clone, PartialEq, Eq)]
130pub enum FragmentRender {
131 Unchanged { marker: String, content_hash: u64 },
133 Updated { fragment: ModelContextFragment },
135 Cleared { marker: String },
137}
138
139#[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 let clamped_max = max_bytes.min(MAX_FRAGMENT_BYTES);
165 let mut content = enforce_byte_cap(raw.into(), clamped_max);
166 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 #[must_use]
183 pub fn matches_text(&self, haystack: &str) -> bool {
184 haystack.contains(self.marker)
185 }
186
187 #[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 #[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 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}