| 1 | //! WorldState: ordered collection of ModelContext fragments with diff render. |
| 2 | |
| 3 | use std::collections::BTreeMap; |
| 4 | |
| 5 | use crate::models::SystemBlock; |
| 6 | |
| 7 | use super::fragment::{FragmentId, FragmentRender, FragmentRole, ModelContextFragment}; |
| 8 | |
| 9 | /// Incremental render of WorldState against a previous snapshot. |
| 10 | #[derive(Debug, Clone, PartialEq, Eq, Default)] |
| 11 | #[allow(dead_code)] // public diff surface; production hosts call render_diff next (TUI-DOG-011) |
| 12 | pub struct WorldStateDiff { |
| 13 | /// Fragments whose content hash changed (or are new). |
| 14 | pub updated: Vec<ModelContextFragment>, |
| 15 | /// Markers that matched the previous snapshot byte-for-byte. |
| 16 | pub retained: Vec<String>, |
| 17 | /// Markers present previously and now cleared. |
| 18 | pub cleared: Vec<String>, |
| 19 | } |
| 20 | |
| 21 | impl WorldStateDiff { |
| 22 | /// Materialize only the updated fragments (retain-unchanged contract). |
| 23 | #[must_use] |
| 24 | #[allow(dead_code)] // incremental text for inspectors / streaming cutover (TUI-DOG-011) |
| 25 | pub fn render_incremental_text(&self) -> String { |
| 26 | let mut parts = Vec::with_capacity(self.updated.len() + self.cleared.len()); |
| 27 | for fragment in &self.updated { |
| 28 | parts.push(fragment.render_marked()); |
| 29 | } |
| 30 | for marker in &self.cleared { |
| 31 | parts.push(format!("{marker}\n[cleared]")); |
| 32 | } |
| 33 | parts.join("\n\n") |
| 34 | } |
| 35 | |
| 36 | #[must_use] |
| 37 | #[allow(dead_code)] // noop probe for retain-unchanged hosts (TUI-DOG-011) |
| 38 | pub fn is_noop(&self) -> bool { |
| 39 | self.updated.is_empty() && self.cleared.is_empty() |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | /// Mutable mid-session context layer living below the constitution prefix. |
| 44 | #[derive(Debug, Clone, PartialEq, Eq, Default)] |
| 45 | pub struct WorldState { |
| 46 | fragments: BTreeMap<FragmentId, ModelContextFragment>, |
| 47 | } |
| 48 | |
| 49 | impl WorldState { |
| 50 | #[must_use] |
| 51 | pub fn new() -> Self { |
| 52 | Self::default() |
| 53 | } |
| 54 | |
| 55 | /// Insert or replace a fragment. Returns retain-unchanged when the hash |
| 56 | /// matches the previous value for that id. |
| 57 | pub fn upsert(&mut self, fragment: ModelContextFragment) -> FragmentRender { |
| 58 | let previous = self.fragments.get(&fragment.id).cloned(); |
| 59 | let render = fragment.render_diff(previous.as_ref()); |
| 60 | if matches!(render, FragmentRender::Updated { .. }) { |
| 61 | self.fragments.insert(fragment.id, fragment); |
| 62 | } |
| 63 | render |
| 64 | } |
| 65 | |
| 66 | /// Remove a fragment, returning Cleared when it existed. |
| 67 | #[allow(dead_code)] // clear/get/is_empty/render_* for host adapters (TUI-DOG-011) |
| 68 | pub fn clear(&mut self, id: FragmentId) -> FragmentRender { |
| 69 | match self.fragments.remove(&id) { |
| 70 | Some(prev) => FragmentRender::Cleared { |
| 71 | marker: prev.marker.to_string(), |
| 72 | }, |
| 73 | None => FragmentRender::Cleared { |
| 74 | marker: id.marker().to_string(), |
| 75 | }, |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | #[must_use] |
| 80 | #[allow(dead_code)] // public WorldState query surface (TUI-DOG-011) |
| 81 | pub fn get(&self, id: FragmentId) -> Option<&ModelContextFragment> { |
| 82 | self.fragments.get(&id) |
| 83 | } |
| 84 | |
| 85 | #[must_use] |
| 86 | pub fn len(&self) -> usize { |
| 87 | self.fragments.len() |
| 88 | } |
| 89 | |
| 90 | #[must_use] |
| 91 | #[allow(dead_code)] // public WorldState query surface (TUI-DOG-011) |
| 92 | pub fn is_empty(&self) -> bool { |
| 93 | self.fragments.is_empty() |
| 94 | } |
| 95 | |
| 96 | /// Full render of every fragment in stable `FragmentId` order. |
| 97 | #[must_use] |
| 98 | #[allow(dead_code)] // full render for Text fallback / inspectors (TUI-DOG-011) |
| 99 | pub fn render_full(&self) -> String { |
| 100 | self.fragments |
| 101 | .values() |
| 102 | .map(ModelContextFragment::render_marked) |
| 103 | .collect::<Vec<_>>() |
| 104 | .join("\n\n") |
| 105 | } |
| 106 | |
| 107 | /// Diff against a previous WorldState. Unchanged fragments are retained |
| 108 | /// (listed, not reinjected into `updated`). |
| 109 | #[must_use] |
| 110 | #[allow(dead_code)] // incremental retain-unchanged API for prompt hosts (TUI-DOG-011) |
| 111 | pub fn render_diff(&self, previous: Option<&WorldState>) -> WorldStateDiff { |
| 112 | let Some(previous) = previous else { |
| 113 | return WorldStateDiff { |
| 114 | updated: self.fragments.values().cloned().collect(), |
| 115 | retained: Vec::new(), |
| 116 | cleared: Vec::new(), |
| 117 | }; |
| 118 | }; |
| 119 | |
| 120 | let mut diff = WorldStateDiff::default(); |
| 121 | for id in FragmentId::all() { |
| 122 | match (previous.fragments.get(id), self.fragments.get(id)) { |
| 123 | (Some(prev), Some(next)) => match next.render_diff(Some(prev)) { |
| 124 | FragmentRender::Unchanged { marker, .. } => diff.retained.push(marker), |
| 125 | FragmentRender::Updated { fragment } => diff.updated.push(fragment), |
| 126 | FragmentRender::Cleared { marker } => diff.cleared.push(marker), |
| 127 | }, |
| 128 | (None, Some(next)) => diff.updated.push(next.clone()), |
| 129 | (Some(prev), None) => diff.cleared.push(prev.marker.to_string()), |
| 130 | (None, None) => {} |
| 131 | } |
| 132 | } |
| 133 | diff |
| 134 | } |
| 135 | |
| 136 | /// Convenience builders for the candidate volatile concerns. |
| 137 | #[must_use] |
| 138 | pub fn with_workspace(mut self, body: impl Into<String>) -> Self { |
| 139 | self.upsert(ModelContextFragment::new( |
| 140 | FragmentId::Workspace, |
| 141 | FragmentRole::Workspace, |
| 142 | body, |
| 143 | )); |
| 144 | self |
| 145 | } |
| 146 | |
| 147 | #[must_use] |
| 148 | pub fn with_permissions(mut self, body: impl Into<String>) -> Self { |
| 149 | self.upsert(ModelContextFragment::new( |
| 150 | FragmentId::Permissions, |
| 151 | FragmentRole::Permissions, |
| 152 | body, |
| 153 | )); |
| 154 | self |
| 155 | } |
| 156 | |
| 157 | #[must_use] |
| 158 | pub fn with_route(mut self, body: impl Into<String>) -> Self { |
| 159 | self.upsert(ModelContextFragment::new( |
| 160 | FragmentId::Route, |
| 161 | FragmentRole::Route, |
| 162 | body, |
| 163 | )); |
| 164 | self |
| 165 | } |
| 166 | |
| 167 | #[must_use] |
| 168 | pub fn with_agent_topology(mut self, body: impl Into<String>) -> Self { |
| 169 | self.upsert(ModelContextFragment::new( |
| 170 | FragmentId::AgentTopology, |
| 171 | FragmentRole::AgentTopology, |
| 172 | body, |
| 173 | )); |
| 174 | self |
| 175 | } |
| 176 | |
| 177 | #[must_use] |
| 178 | pub fn with_skills_tools(mut self, body: impl Into<String>) -> Self { |
| 179 | self.upsert(ModelContextFragment::new( |
| 180 | FragmentId::SkillsTools, |
| 181 | FragmentRole::SkillsTools, |
| 182 | body, |
| 183 | )); |
| 184 | self |
| 185 | } |
| 186 | |
| 187 | #[must_use] |
| 188 | pub fn with_token_budget(mut self, body: impl Into<String>) -> Self { |
| 189 | self.upsert(ModelContextFragment::new( |
| 190 | FragmentId::TokenBudget, |
| 191 | FragmentRole::TokenBudget, |
| 192 | body, |
| 193 | )); |
| 194 | self |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | /// Constitution (cache-stable) + WorldState (volatile) assembly point. |
| 199 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 200 | pub struct WorldStateSnapshot { |
| 201 | pub constitution: String, |
| 202 | pub world_state: WorldState, |
| 203 | } |
| 204 | |
| 205 | impl WorldStateSnapshot { |
| 206 | /// Structured blocks: constitution first (cacheable), then each fragment. |
| 207 | #[must_use] |
| 208 | pub fn to_system_blocks(&self) -> Vec<SystemBlock> { |
| 209 | let mut blocks = Vec::with_capacity(1 + self.world_state.len()); |
| 210 | blocks.push(SystemBlock { |
| 211 | block_type: "text".to_string(), |
| 212 | text: self.constitution.trim().to_string(), |
| 213 | cache_control: None, |
| 214 | }); |
| 215 | for fragment in self.world_state.fragments.values() { |
| 216 | blocks.push(SystemBlock { |
| 217 | block_type: "text".to_string(), |
| 218 | text: fragment.render_marked(), |
| 219 | cache_control: None, |
| 220 | }); |
| 221 | } |
| 222 | blocks |
| 223 | } |
| 224 | |
| 225 | /// Flat text fallback for callers that still expect `SystemPrompt::Text`. |
| 226 | #[must_use] |
| 227 | #[allow(dead_code)] // Text fallback while Blocks path is primary (TUI-DOG-011) |
| 228 | pub fn render_text(&self) -> String { |
| 229 | let world = self.world_state.render_full(); |
| 230 | if world.is_empty() { |
| 231 | self.constitution.trim().to_string() |
| 232 | } else { |
| 233 | format!("{}\n\n{}", self.constitution.trim(), world) |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | /// Incremental world-state update text (constitution omitted — stable). |
| 238 | #[must_use] |
| 239 | #[allow(dead_code)] // incremental WorldState for streaming cutover (TUI-DOG-011) |
| 240 | pub fn render_world_diff(&self, previous: Option<&WorldState>) -> WorldStateDiff { |
| 241 | self.world_state.render_diff(previous) |
| 242 | } |
| 243 | } |
| 244 |