Skip to main content

glass_dev/
intelligence.rs

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