1use glass_browser::development::{DevelopmentError, DevelopmentResult};
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6use std::collections::{BTreeMap, BTreeSet, VecDeque};
7use std::time::{SystemTime, UNIX_EPOCH};
8
9const MAX_NODES: usize = 8_192;
10const MAX_EDGES: usize = 32_768;
11const MAX_EVENTS: usize = 16_384;
12const MAX_EVIDENCE_BYTES: usize = 64 * 1024;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "camelCase")]
16pub enum DevelopmentNodeKind {
17 Repository,
18 File,
19 Symbol,
20 Process,
21 Port,
22 Request,
23 Debugger,
24 Breakpoint,
25 StackFrame,
26 BrowserTarget,
27 BrowserRevision,
28 SemanticEntity,
29 Workflow,
30 Test,
31 Diagnostic,
32 GitCommit,
33 Agent,
34 ToolCall,
35 Experiment,
36 Verification,
37 Kernel,
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
41#[serde(rename_all = "camelCase")]
42pub struct DevelopmentNode {
43 pub id: String,
44 pub kind: DevelopmentNodeKind,
45 pub label: String,
46 pub revision: u64,
47 pub stale: bool,
48 pub evidence: Value,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
52#[serde(rename_all = "camelCase")]
53pub struct DevelopmentEdge {
54 pub id: u64,
55 pub from: String,
56 pub to: String,
57 pub relation: String,
58 pub revision: u64,
59 pub stale: bool,
60 pub provenance: String,
61 pub evidence: Value,
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
65#[serde(rename_all = "camelCase")]
66pub struct ObservableDevelopmentEvent {
67 pub sequence: u64,
68 pub occurred_at_ms: u128,
69 pub actor: String,
70 pub subsystem: String,
71 pub kind: String,
72 pub resource: Option<String>,
73 pub workspace_revision: u64,
74 pub evidence: Value,
75 pub rationale: Option<String>,
76}
77
78#[derive(Debug, Clone, Serialize, Deserialize)]
79#[serde(rename_all = "camelCase")]
80pub struct CausalPath {
81 pub nodes: Vec<DevelopmentNode>,
82 pub edges: Vec<DevelopmentEdge>,
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize)]
86#[serde(rename_all = "camelCase")]
87pub struct ReplayDiff {
88 pub from_sequence: u64,
89 pub to_sequence: u64,
90 pub actors: BTreeSet<String>,
91 pub subsystems: BTreeSet<String>,
92 pub resources: BTreeSet<String>,
93 pub events: Vec<ObservableDevelopmentEvent>,
94}
95
96pub struct ObservableEventInput<'a> {
97 pub actor: &'a str,
98 pub subsystem: &'a str,
99 pub kind: &'a str,
100 pub resource: Option<&'a str>,
101 pub workspace_revision: u64,
102 pub evidence: Value,
103 pub rationale: Option<&'a str>,
104}
105
106pub struct DevelopmentIntelligence {
108 nodes: BTreeMap<String, DevelopmentNode>,
109 edges: VecDeque<DevelopmentEdge>,
110 events: VecDeque<ObservableDevelopmentEvent>,
111 next_edge: u64,
112 next_event: u64,
113}
114
115impl Default for DevelopmentIntelligence {
116 fn default() -> Self {
117 Self {
118 nodes: BTreeMap::new(),
119 edges: VecDeque::new(),
120 events: VecDeque::new(),
121 next_edge: 1,
122 next_event: 1,
123 }
124 }
125}
126
127impl DevelopmentIntelligence {
128 pub fn upsert_node(&mut self, node: DevelopmentNode) -> DevelopmentResult<()> {
129 validate_identifier(&node.id, "node")?;
130 validate_text(&node.label, "node label", 1024)?;
131 validate_evidence(&node.evidence)?;
132 if self.nodes.len() == MAX_NODES && !self.nodes.contains_key(&node.id) {
133 return Err(DevelopmentError::Conflict(format!(
134 "development graph reached its {MAX_NODES} node limit"
135 )));
136 }
137 if let Some(existing) = self.nodes.get(&node.id)
138 && node.revision < existing.revision
139 {
140 return Err(DevelopmentError::Conflict(format!(
141 "stale node revision {} for {} at revision {}",
142 node.revision, node.id, existing.revision
143 )));
144 }
145 self.nodes.insert(node.id.clone(), node);
146 Ok(())
147 }
148
149 pub fn link(
150 &mut self,
151 from: &str,
152 to: &str,
153 relation: &str,
154 revision: u64,
155 provenance: &str,
156 evidence: Value,
157 ) -> DevelopmentResult<u64> {
158 if !self.nodes.contains_key(from) || !self.nodes.contains_key(to) {
159 return Err(DevelopmentError::NotFound(
160 "causal edges require existing endpoint nodes".into(),
161 ));
162 }
163 validate_text(relation, "edge relation", 128)?;
164 validate_text(provenance, "edge provenance", 1024)?;
165 validate_evidence(&evidence)?;
166 if self.edges.len() == MAX_EDGES {
167 self.edges.pop_front();
168 }
169 let id = self.next_edge;
170 self.next_edge = self.next_edge.checked_add(1).ok_or_else(|| {
171 DevelopmentError::Conflict("development graph edge sequence overflowed".into())
172 })?;
173 self.edges.push_back(DevelopmentEdge {
174 id,
175 from: from.into(),
176 to: to.into(),
177 relation: relation.into(),
178 revision,
179 stale: false,
180 provenance: provenance.into(),
181 evidence,
182 });
183 Ok(id)
184 }
185
186 pub fn record(&mut self, input: ObservableEventInput<'_>) -> DevelopmentResult<u64> {
187 validate_text(input.actor, "event actor", 256)?;
188 validate_text(input.subsystem, "event subsystem", 128)?;
189 validate_text(input.kind, "event kind", 128)?;
190 if let Some(resource) = input.resource {
191 validate_text(resource, "event resource", 4096)?;
192 }
193 if let Some(rationale) = input.rationale {
194 validate_text(rationale, "event rationale", 4096)?;
195 }
196 validate_evidence(&input.evidence)?;
197 if self.events.len() == MAX_EVENTS {
198 self.events.pop_front();
199 }
200 let sequence = self.next_event;
201 self.next_event = self.next_event.checked_add(1).ok_or_else(|| {
202 DevelopmentError::Conflict("development replay sequence overflowed".into())
203 })?;
204 self.events.push_back(ObservableDevelopmentEvent {
205 sequence,
206 occurred_at_ms: now_ms(),
207 actor: input.actor.into(),
208 subsystem: input.subsystem.into(),
209 kind: input.kind.into(),
210 resource: input.resource.map(str::to_string),
211 workspace_revision: input.workspace_revision,
212 evidence: input.evidence,
213 rationale: input.rationale.map(str::to_string),
214 });
215 Ok(sequence)
216 }
217
218 pub fn invalidate_before(&mut self, revision: u64) -> usize {
219 let mut invalidated = 0;
220 for node in self.nodes.values_mut() {
221 if node.revision < revision && !node.stale {
222 node.stale = true;
223 invalidated += 1;
224 }
225 }
226 for edge in &mut self.edges {
227 if edge.revision < revision && !edge.stale {
228 edge.stale = true;
229 invalidated += 1;
230 }
231 }
232 invalidated
233 }
234
235 pub fn node(&self, id: &str) -> Option<&DevelopmentNode> {
236 self.nodes.get(id)
237 }
238
239 pub fn nodes(&self) -> impl Iterator<Item = &DevelopmentNode> {
240 self.nodes.values()
241 }
242
243 pub fn edges(&self) -> impl Iterator<Item = &DevelopmentEdge> {
244 self.edges.iter()
245 }
246
247 pub fn query_kind(&self, kind: DevelopmentNodeKind) -> Vec<&DevelopmentNode> {
248 self.nodes
249 .values()
250 .filter(|node| node.kind == kind && !node.stale)
251 .collect()
252 }
253
254 pub fn path(&self, from: &str, to: &str) -> DevelopmentResult<CausalPath> {
255 if !self.nodes.contains_key(from) || !self.nodes.contains_key(to) {
256 return Err(DevelopmentError::NotFound("causal path endpoint".into()));
257 }
258 let mut queue = VecDeque::from([from.to_string()]);
259 let mut visited = BTreeSet::from([from.to_string()]);
260 let mut previous = BTreeMap::<String, (String, u64)>::new();
261 while let Some(current) = queue.pop_front() {
262 if current == to {
263 break;
264 }
265 for edge in self.edges.iter().filter(|edge| !edge.stale) {
266 let next = if edge.from == current {
267 Some(edge.to.as_str())
268 } else if edge.to == current {
269 Some(edge.from.as_str())
270 } else {
271 None
272 };
273 if let Some(next) = next
274 && visited.insert(next.to_string())
275 {
276 previous.insert(next.to_string(), (current.clone(), edge.id));
277 queue.push_back(next.to_string());
278 }
279 }
280 }
281 if !visited.contains(to) {
282 return Err(DevelopmentError::NotFound(format!(
283 "causal path from {from} to {to}"
284 )));
285 }
286 let mut node_ids = vec![to.to_string()];
287 let mut edge_ids = Vec::new();
288 let mut cursor = to;
289 while cursor != from {
290 let (parent, edge) = previous.get(cursor).ok_or_else(|| {
291 DevelopmentError::Conflict("causal path reconstruction failed".into())
292 })?;
293 edge_ids.push(*edge);
294 node_ids.push(parent.clone());
295 cursor = parent;
296 }
297 node_ids.reverse();
298 edge_ids.reverse();
299 Ok(CausalPath {
300 nodes: node_ids
301 .iter()
302 .filter_map(|id| self.nodes.get(id).cloned())
303 .collect(),
304 edges: edge_ids
305 .iter()
306 .filter_map(|id| self.edges.iter().find(|edge| edge.id == *id).cloned())
307 .collect(),
308 })
309 }
310
311 pub fn replay(
312 &self,
313 since: u64,
314 limit: usize,
315 ) -> DevelopmentResult<Vec<ObservableDevelopmentEvent>> {
316 if limit == 0 || limit > 4096 {
317 return Err(DevelopmentError::InvalidInput(
318 "replay limit must be 1..=4096".into(),
319 ));
320 }
321 Ok(self
322 .events
323 .iter()
324 .filter(|event| event.sequence > since)
325 .take(limit)
326 .cloned()
327 .collect())
328 }
329
330 pub fn replay_diff(&self, from: u64, to: u64) -> DevelopmentResult<ReplayDiff> {
331 if from >= to {
332 return Err(DevelopmentError::InvalidInput(
333 "replay diff requires an increasing sequence range".into(),
334 ));
335 }
336 let events = self
337 .events
338 .iter()
339 .filter(|event| event.sequence > from && event.sequence <= to)
340 .cloned()
341 .collect::<Vec<_>>();
342 Ok(ReplayDiff {
343 from_sequence: from,
344 to_sequence: to,
345 actors: events.iter().map(|event| event.actor.clone()).collect(),
346 subsystems: events.iter().map(|event| event.subsystem.clone()).collect(),
347 resources: events
348 .iter()
349 .filter_map(|event| event.resource.clone())
350 .collect(),
351 events,
352 })
353 }
354}
355
356fn validate_identifier(value: &str, description: &str) -> DevelopmentResult<()> {
357 if value.is_empty()
358 || value.len() > 512
359 || value.chars().any(|character| character.is_control())
360 {
361 return Err(DevelopmentError::InvalidInput(format!(
362 "{description} identifier must contain 1..=512 non-control bytes"
363 )));
364 }
365 Ok(())
366}
367
368fn validate_text(value: &str, description: &str, limit: usize) -> DevelopmentResult<()> {
369 if value.is_empty() || value.len() > limit || value.contains('\0') {
370 return Err(DevelopmentError::InvalidInput(format!(
371 "{description} must contain 1..={limit} bytes without NUL"
372 )));
373 }
374 Ok(())
375}
376
377fn validate_evidence(evidence: &Value) -> DevelopmentResult<()> {
378 if serde_json::to_vec(evidence)?.len() > MAX_EVIDENCE_BYTES {
379 return Err(DevelopmentError::InvalidInput(format!(
380 "development evidence exceeds {MAX_EVIDENCE_BYTES} bytes"
381 )));
382 }
383 Ok(())
384}
385
386fn now_ms() -> u128 {
387 SystemTime::now()
388 .duration_since(UNIX_EPOCH)
389 .unwrap_or_default()
390 .as_millis()
391}
392
393#[cfg(test)]
394mod tests {
395 use super::*;
396
397 #[test]
398 fn graph_explains_paths_and_invalidates_stale_evidence() {
399 let mut graph = DevelopmentIntelligence::default();
400 for (id, kind) in [
401 ("file:checkout.rs", DevelopmentNodeKind::File),
402 ("test:checkout", DevelopmentNodeKind::Test),
403 ("browser:error", DevelopmentNodeKind::SemanticEntity),
404 ] {
405 graph
406 .upsert_node(DevelopmentNode {
407 id: id.into(),
408 kind,
409 label: id.into(),
410 revision: 4,
411 stale: false,
412 evidence: Value::Null,
413 })
414 .unwrap();
415 }
416 graph
417 .link(
418 "file:checkout.rs",
419 "test:checkout",
420 "coveredBy",
421 4,
422 "cargo test",
423 Value::Null,
424 )
425 .unwrap();
426 graph
427 .link(
428 "test:checkout",
429 "browser:error",
430 "observes",
431 4,
432 "workflow evidence",
433 Value::Null,
434 )
435 .unwrap();
436 let path = graph.path("file:checkout.rs", "browser:error").unwrap();
437 assert_eq!(path.nodes.len(), 3);
438 assert_eq!(path.edges.len(), 2);
439 assert_eq!(graph.invalidate_before(5), 5);
440 assert!(graph.path("file:checkout.rs", "browser:error").is_err());
441 }
442
443 #[test]
444 fn replay_diff_contains_only_observable_evidence() {
445 let mut replay = DevelopmentIntelligence::default();
446 replay
447 .record(ObservableEventInput {
448 actor: "agent-1",
449 subsystem: "tool",
450 kind: "called",
451 resource: Some("file:src/lib.rs"),
452 workspace_revision: 1,
453 evidence: serde_json::json!({"tool":"glass.file.write"}),
454 rationale: Some("apply requested change"),
455 })
456 .unwrap();
457 replay
458 .record(ObservableEventInput {
459 actor: "tester",
460 subsystem: "test",
461 kind: "passed",
462 resource: Some("test:unit"),
463 workspace_revision: 2,
464 evidence: serde_json::json!({"exitCode":0}),
465 rationale: None,
466 })
467 .unwrap();
468 let diff = replay.replay_diff(0, 2).unwrap();
469 assert_eq!(diff.events.len(), 2);
470 assert!(diff.actors.contains("agent-1"));
471 assert!(diff.subsystems.contains("test"));
472 }
473}