kcode_kennedy_subagent_context/
lib.rs1#![forbid(unsafe_code)]
4
5use std::collections::{BTreeMap, BTreeSet};
6
7use kcode_agent_runtime::StateUpdate;
8use kcode_dev_tools::{ManagedSourceKind, SourceSnapshot};
9use kcode_kweb_context::{Context as KwebContext, NodeDraft, ProjectionItem, StagedCreate};
10
11const KWEB_PREFIX: &str = "kweb:";
12const MANAGED_PREFIX: &str = "managed:";
13
14#[derive(Clone, Debug, Default, Eq, PartialEq)]
16pub struct StateChanges {
17 pub updates: Vec<StateUpdate>,
19}
20
21impl StateChanges {
22 pub fn is_empty(&self) -> bool {
24 self.updates.is_empty()
25 }
26
27 pub fn display_text(&self) -> String {
29 self.updates
30 .iter()
31 .filter_map(|update| update.text.as_deref())
32 .collect::<Vec<_>>()
33 .join("\n\n")
34 }
35
36 pub fn displayed_state_keys(&self) -> Vec<String> {
38 self.updates
39 .iter()
40 .filter(|update| update.text.is_some())
41 .map(|update| update.key.clone())
42 .collect()
43 }
44}
45
46#[derive(Clone, Debug, Eq, PartialEq)]
48pub struct SourceState {
49 pub key: String,
51 pub text: String,
53 pub update: Option<StateUpdate>,
55}
56
57#[derive(Clone, Debug)]
59pub struct Context {
60 kweb: KwebContext,
61 states: BTreeMap<String, String>,
62 kweb_keys: BTreeSet<String>,
63 staged_node_ids: BTreeSet<String>,
64}
65
66impl Context {
67 pub fn new(root_node_ids: Vec<String>) -> anyhow::Result<Self> {
69 Ok(Self {
70 kweb: KwebContext::new(root_node_ids).map_err(anyhow::Error::new)?,
71 states: BTreeMap::new(),
72 kweb_keys: BTreeSet::new(),
73 staged_node_ids: BTreeSet::new(),
74 })
75 }
76
77 pub fn kweb(&self) -> &KwebContext {
79 &self.kweb
80 }
81
82 pub fn kweb_mut(&mut self) -> &mut KwebContext {
84 &mut self.kweb
85 }
86
87 pub fn include_staged_nodes(&mut self, ids: impl IntoIterator<Item = String>) {
89 self.staged_node_ids.extend(ids);
90 }
91
92 pub fn reconcile_kweb(
94 &mut self,
95 updates: &BTreeMap<String, NodeDraft>,
96 creates: &[StagedCreate],
97 ) -> anyhow::Result<StateChanges> {
98 let visible_updates = updates
99 .iter()
100 .filter(|(id, _)| self.kweb.contains_full_node(id))
101 .map(|(id, update)| (id.clone(), update.clone()))
102 .collect();
103 let visible_creates = creates
104 .iter()
105 .filter(|create| self.staged_node_ids.contains(&create.pending_id))
106 .cloned()
107 .collect::<Vec<_>>();
108 let projected = self
109 .kweb
110 .projection(&visible_updates, &visible_creates)
111 .map_err(anyhow::Error::new)?;
112 let next_keys = projected
113 .iter()
114 .map(|item| kweb_key(&item.key))
115 .collect::<BTreeSet<_>>();
116 let mut changes = StateChanges::default();
117
118 for key in self.kweb_keys.difference(&next_keys) {
119 self.states.remove(key);
120 changes.updates.push(StateUpdate {
121 key: key.clone(),
122 text: None,
123 });
124 }
125 for item in projected {
126 self.apply_kweb_item(item, &mut changes);
127 }
128 self.kweb_keys = next_keys;
129 Ok(changes)
130 }
131
132 pub fn apply_source_snapshot(&mut self, snapshot: SourceSnapshot) -> SourceState {
134 let state = source_state(&snapshot);
135 let update = (self.states.get(&state.key) != Some(&state.text)).then(|| StateUpdate {
136 key: state.key.clone(),
137 text: Some(state.text.clone()),
138 });
139 self.states.insert(state.key.clone(), state.text.clone());
140 SourceState { update, ..state }
141 }
142
143 pub fn source_state(&self, snapshot: &SourceSnapshot) -> SourceState {
145 let mut state = source_state(snapshot);
146 state.update = (self.states.get(&state.key) != Some(&state.text)).then(|| StateUpdate {
147 key: state.key.clone(),
148 text: Some(state.text.clone()),
149 });
150 state
151 }
152
153 pub fn source_is_open(&self, kind: ManagedSourceKind, name: &str) -> bool {
155 self.states.contains_key(&managed_key(kind, name))
156 }
157
158 fn apply_kweb_item(&mut self, item: ProjectionItem, changes: &mut StateChanges) {
159 let key = kweb_key(&item.key);
160 let text = format!("Current {}:\n{}", item.name, item.text);
161 if self.states.get(&key) != Some(&text) {
162 self.states.insert(key.clone(), text.clone());
163 changes.updates.push(StateUpdate {
164 key,
165 text: Some(text),
166 });
167 }
168 }
169}
170
171fn source_state(snapshot: &SourceSnapshot) -> SourceState {
172 SourceState {
173 key: managed_key(snapshot.kind, &snapshot.name),
174 text: format!(
175 "Current Managed {} {}:\n{}",
176 snapshot.kind.label(),
177 snapshot.name,
178 snapshot.text
179 ),
180 update: None,
181 }
182}
183
184fn kweb_key(logical: &str) -> String {
185 format!("{KWEB_PREFIX}{logical}")
186}
187
188fn managed_key(kind: ManagedSourceKind, name: &str) -> String {
189 let kind = match kind {
190 ManagedSourceKind::RustLibrary => "rust-library",
191 ManagedSourceKind::WebLibrary => "web-library",
192 ManagedSourceKind::RustBinary => "rust-binary",
193 };
194 format!("{MANAGED_PREFIX}{kind}:{name}")
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200 use kcode_kweb_context::Node;
201
202 fn node(description: &str) -> Node {
203 Node {
204 id: "AAAAAAAE".into(),
205 short_name: "Root".into(),
206 short_description: "Summary".into(),
207 long_description: description.into(),
208 owner: "self".into(),
209 fixed_connections: Vec::new(),
210 recent_connections: Vec::new(),
211 objects: Vec::new(),
212 last_modified_by: "test".into(),
213 last_modified_at: None,
214 }
215 }
216
217 #[test]
218 fn kweb_changes_reuse_stable_keys_without_boxes() {
219 let mut context = Context::new(vec!["AAAAAAAE".into()]).unwrap();
220 context
221 .kweb_mut()
222 .apply_load(node("old"), Vec::new())
223 .unwrap();
224 let first = context.reconcile_kweb(&BTreeMap::new(), &[]).unwrap();
225 assert_eq!(first.updates[0].key, "kweb:AAAAAAAE");
226 assert!(first.display_text().contains("old"));
227
228 context.kweb_mut().refresh([node("new")]).unwrap();
229 let second = context.reconcile_kweb(&BTreeMap::new(), &[]).unwrap();
230 assert_eq!(second.updates.len(), 1);
231 assert_eq!(second.updates[0].key, "kweb:AAAAAAAE");
232 assert!(second.updates[0].text.as_deref().unwrap().contains("new"));
233 }
234
235 #[test]
236 fn managed_sources_are_isolated_by_kind_and_name() {
237 let mut context = Context::new(vec!["AAAAAAAE".into()]).unwrap();
238 let snapshot = SourceSnapshot {
239 kind: ManagedSourceKind::RustLibrary,
240 name: "example".into(),
241 text: "source".into(),
242 };
243 let applied = context.apply_source_snapshot(snapshot.clone());
244 assert_eq!(applied.key, "managed:rust-library:example");
245 assert!(applied.update.is_some());
246 assert!(context.source_is_open(snapshot.kind, &snapshot.name));
247 assert!(context.apply_source_snapshot(snapshot).update.is_none());
248 assert!(!context.source_is_open(ManagedSourceKind::WebLibrary, "example"));
249 }
250
251 #[test]
252 fn kweb_projection_hides_unloaded_parent_plan_state() {
253 let mut context = Context::new(vec!["AAAAAAAE".into()]).unwrap();
254 context
255 .kweb_mut()
256 .apply_load(node("loaded"), Vec::new())
257 .unwrap();
258 let unrelated_id = "AAAAAAAI".to_owned();
259 let updates = BTreeMap::from([(
260 unrelated_id,
261 NodeDraft {
262 short_name: "Hidden".into(),
263 short_description: "Hidden".into(),
264 long_description: "unrelated parent update".into(),
265 owner: "self".into(),
266 fixed_connections: Vec::new(),
267 recent_connections: Vec::new(),
268 objects: Vec::new(),
269 },
270 )]);
271 let hidden = StagedCreate {
272 pending_id: "pending:hidden".into(),
273 data: updates.values().next().unwrap().clone(),
274 };
275
276 let changes = context
277 .reconcile_kweb(&updates, std::slice::from_ref(&hidden))
278 .unwrap();
279 assert!(!changes.display_text().contains("unrelated parent update"));
280 assert!(!changes.display_text().contains("pending:hidden"));
281
282 context.include_staged_nodes([hidden.pending_id.clone()]);
283 let changes = context.reconcile_kweb(&updates, &[hidden]).unwrap();
284 assert!(changes.display_text().contains("pending:hidden"));
285 }
286}