| 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 | |
| 10 | use std::collections::hash_map::DefaultHasher; |
| 11 | use std::hash::{Hash, Hasher}; |
| 12 | |
| 13 | /// Re-export the core hard caps — single source of truth. |
| 14 | pub 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)] |
| 21 | pub enum FragmentId { |
| 22 | Workspace, |
| 23 | Permissions, |
| 24 | Route, |
| 25 | AgentTopology, |
| 26 | SkillsTools, |
| 27 | SessionRelay, |
| 28 | ProjectInstructions, |
| 29 | Constitution, |
| 30 | } |
| 31 | |
| 32 | impl 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 | /// 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::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 | /// Explicit role of a fragment relative to the cache-stable constitution. |
| 92 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 93 | pub 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 | SessionRelay, |
| 106 | /// Project instructions (AGENTS.md + imported instruction files). |
| 107 | ProjectInstructions, |
| 108 | /// Codewhale-specific repo constitution. |
| 109 | Constitution, |
| 110 | } |
| 111 | |
| 112 | impl 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 | /// Result of comparing a fragment against its previous render. |
| 129 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 130 | pub 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)] |
| 141 | pub 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 | |
| 150 | impl 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 | |
| 212 | fn hash_content(content: &str) -> u64 { |
| 213 | let mut hasher = DefaultHasher::new(); |
| 214 | content.hash(&mut hasher); |
| 215 | hasher.finish() |
| 216 | } |
| 217 | |
| 218 | fn 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 | let mut cut = max_bytes; |
| 229 | while !marker.is_char_boundary(cut) { |
| 230 | cut -= 1; |
| 231 | } |
| 232 | return marker[..cut].to_string(); |
| 233 | } |
| 234 | let keep = max_bytes.saturating_sub(marker.len()); |
| 235 | // Truncate on a char boundary. |
| 236 | let mut end = keep; |
| 237 | while end > 0 && !raw.is_char_boundary(end) { |
| 238 | end -= 1; |
| 239 | } |
| 240 | let mut out = raw[..end].to_string(); |
| 241 | out.push_str(&marker); |
| 242 | out |
| 243 | } |
| 244 | |
| 245 | #[cfg(test)] |
| 246 | mod tests { |
| 247 | use super::*; |
| 248 | |
| 249 | #[test] |
| 250 | fn tiny_byte_cap_never_exceeds_its_bytes() { |
| 251 | for max in 1..48 { |
| 252 | assert!(enforce_byte_cap("x".repeat(100), max).len() <= max); |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | #[test] |
| 257 | fn render_diff_detects_change_and_retain() { |
| 258 | let a = ModelContextFragment::new(FragmentId::Route, FragmentRole::Route, "m=a"); |
| 259 | let b = ModelContextFragment::new(FragmentId::Route, FragmentRole::Route, "m=a"); |
| 260 | let c = ModelContextFragment::new(FragmentId::Route, FragmentRole::Route, "m=b"); |
| 261 | assert!(matches!( |
| 262 | b.render_diff(Some(&a)), |
| 263 | FragmentRender::Unchanged { .. } |
| 264 | )); |
| 265 | assert!(matches!( |
| 266 | c.render_diff(Some(&a)), |
| 267 | FragmentRender::Updated { .. } |
| 268 | )); |
| 269 | assert!(matches!( |
| 270 | a.render_diff(None), |
| 271 | FragmentRender::Updated { .. } |
| 272 | )); |
| 273 | } |
| 274 | } |
| 275 |