Skip to main content

glass_dev/development/
diff.rs

1use super::{
2    DEVELOPMENT_SCHEMA_VERSION, DevelopmentError, DevelopmentGraph, DevelopmentResult,
3    ProcessManager, Timeline,
4};
5use serde::{Deserialize, Serialize};
6use std::{collections::BTreeMap, path::Path};
7
8#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
9#[serde(rename_all = "camelCase")]
10pub struct FileChange {
11    pub path: String,
12    pub status: String,
13}
14
15#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
16#[serde(rename_all = "camelCase")]
17pub struct ProjectDiff {
18    pub schema_version: String,
19    pub files: Vec<FileChange>,
20    pub runtime: BTreeMap<String, serde_json::Value>,
21    pub semantic: BTreeMap<String, serde_json::Value>,
22    pub visual: BTreeMap<String, serde_json::Value>,
23    pub workflow: BTreeMap<String, serde_json::Value>,
24    pub test_impact: BTreeMap<String, serde_json::Value>,
25}
26
27pub fn build_diff(
28    root: &Path,
29    timeline: &Timeline,
30    graph: &DevelopmentGraph,
31    processes: &mut ProcessManager,
32) -> DevelopmentResult<ProjectDiff> {
33    let output = crate::git::git_command(root)
34        .args([
35            "-c",
36            "alias.status=",
37            "status",
38            "--short",
39            "--untracked-files=all",
40        ])
41        .output()
42        .map_err(DevelopmentError::Io)?;
43    let mut files = Vec::new();
44    if output.status.success() {
45        for line in String::from_utf8_lossy(&output.stdout).lines().take(512) {
46            if line.len() < 4 {
47                continue;
48            }
49            let status = line[..2].trim().to_string();
50            let path = line[3..].trim().to_string();
51            if !path.is_empty() {
52                files.push(FileChange { path, status });
53            }
54        }
55    }
56    let process_snapshots = processes.list();
57    let mut runtime = BTreeMap::new();
58    runtime.insert(
59        "processCount".into(),
60        serde_json::json!(process_snapshots.len()),
61    );
62    runtime.insert("processes".into(), serde_json::to_value(process_snapshots)?);
63    let mut semantic = BTreeMap::new();
64    semantic.insert(
65        "linkCount".into(),
66        serde_json::json!(graph.links.values().map(Vec::len).sum::<usize>()),
67    );
68    semantic.insert(
69        "breakpointHits".into(),
70        serde_json::json!(
71            timeline
72                .events()
73                .filter(|event| matches!(
74                    event.kind,
75                    super::DevelopmentEventKind::SemanticBreakpointHit
76                ))
77                .count()
78        ),
79    );
80    let mut visual = BTreeMap::new();
81    visual.insert("status".into(), serde_json::json!("not-captured"));
82    visual.insert(
83        "reason".into(),
84        serde_json::json!(
85            "visual evidence requires explicit capture; screenshots are never implicit"
86        ),
87    );
88    semantic.insert(
89        "entities".into(),
90        serde_json::to_value(graph.links.keys().collect::<Vec<_>>())?,
91    );
92    let mut workflow = BTreeMap::new();
93    let verification_count = timeline
94        .events()
95        .filter(|event| {
96            matches!(
97                event.kind,
98                super::DevelopmentEventKind::VerificationCompleted
99            )
100        })
101        .count();
102    workflow.insert(
103        "verificationCount".into(),
104        serde_json::json!(verification_count),
105    );
106    workflow.insert(
107        "recentEventCount".into(),
108        serde_json::json!(timeline.events().count()),
109    );
110    let mut test_impact = BTreeMap::new();
111    test_impact.insert(
112        "started".into(),
113        serde_json::json!(
114            timeline
115                .events()
116                .filter(|event| matches!(event.kind, super::DevelopmentEventKind::TestStarted))
117                .count()
118        ),
119    );
120    test_impact.insert(
121        "completed".into(),
122        serde_json::json!(
123            timeline
124                .events()
125                .filter(|event| matches!(event.kind, super::DevelopmentEventKind::TestCompleted))
126                .count()
127        ),
128    );
129    Ok(ProjectDiff {
130        schema_version: DEVELOPMENT_SCHEMA_VERSION.into(),
131        files,
132        runtime,
133        semantic,
134        visual,
135        workflow,
136        test_impact,
137    })
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143    use crate::development::{Actor, DevelopmentEventKind, Timeline};
144    use std::fs;
145
146    #[test]
147    fn diff_is_bounded_and_reports_runtime_and_semantic_sections() {
148        let root = std::env::temp_dir().join(format!("glass-diff-{}", std::process::id()));
149        let _ = fs::create_dir_all(&root);
150        let mut timeline = Timeline::open(root.join("timeline.jsonl")).unwrap();
151        timeline
152            .record(
153                Actor::local(),
154                DevelopmentEventKind::VerificationCompleted,
155                "/tmp",
156                serde_json::json!({}),
157            )
158            .unwrap();
159        let mut manager = ProcessManager::new(&root);
160        let diff =
161            build_diff(&root, &timeline, &DevelopmentGraph::default(), &mut manager).unwrap();
162        assert_eq!(diff.schema_version, DEVELOPMENT_SCHEMA_VERSION);
163        assert!(diff.runtime.contains_key("processes"));
164        assert!(diff.semantic.contains_key("entities"));
165        assert_eq!(diff.visual["status"], "not-captured");
166        let _ = fs::remove_dir_all(root);
167    }
168}