Skip to main content

glass_dev/development/
graph.rs

1use super::{DevelopmentError, DevelopmentResult, MAX_FILE_BYTES, read_bounded_utf8};
2use serde::{Deserialize, Serialize};
3use std::{
4    collections::BTreeMap,
5    fs,
6    path::{Component, Path},
7};
8
9#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
10#[serde(rename_all = "camelCase")]
11pub struct SourceLocation {
12    pub path: String,
13    pub start_line: u32,
14    pub end_line: u32,
15}
16
17impl SourceLocation {
18    pub fn new(path: impl Into<String>, start_line: u32, end_line: u32) -> DevelopmentResult<Self> {
19        let path = path.into();
20        let candidate = Path::new(&path);
21        if path.is_empty()
22            || candidate.is_absolute()
23            || candidate.components().any(|component| {
24                matches!(
25                    component,
26                    Component::ParentDir | Component::RootDir | Component::Prefix(_)
27                )
28            })
29            || start_line == 0
30            || end_line < start_line
31        {
32            return Err(DevelopmentError::InvalidInput(
33                "source location requires a relative path and ordered one-based lines".into(),
34            ));
35        }
36        Ok(Self {
37            path,
38            start_line,
39            end_line,
40        })
41    }
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
45#[serde(rename_all = "camelCase")]
46pub enum LinkProvenance {
47    ExplicitMarker,
48    RuntimeObservation,
49    StaticAnalysis,
50    Inferred,
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
54#[serde(rename_all = "camelCase")]
55pub struct LinkEvidence {
56    pub provenance: LinkProvenance,
57    pub detail: String,
58    pub confidence: f32,
59}
60
61#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
62#[serde(rename_all = "camelCase")]
63pub struct RuntimeLink {
64    pub entity_id: String,
65    pub source: SourceLocation,
66    pub evidence: LinkEvidence,
67}
68
69#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
70#[serde(rename_all = "camelCase")]
71pub struct DevelopmentGraph {
72    pub links: BTreeMap<String, Vec<RuntimeLink>>,
73}
74
75impl DevelopmentGraph {
76    pub fn load(path: &Path) -> DevelopmentResult<Self> {
77        if !path.is_file() {
78            return Ok(Self::default());
79        }
80        let metadata = fs::metadata(path)?;
81        if metadata.len() > 2 * 1024 * 1024 {
82            return Err(DevelopmentError::InvalidInput(
83                "development graph exceeds the 2 MiB storage limit".into(),
84            ));
85        }
86        let candidate: Self = serde_json::from_slice(&fs::read(path)?)?;
87        let mut validated = Self::default();
88        for links in candidate.links.into_values() {
89            for link in links {
90                validated.link(link)?;
91            }
92        }
93        Ok(validated)
94    }
95
96    pub fn save(&self, path: &Path) -> DevelopmentResult<()> {
97        if let Some(parent) = path.parent() {
98            fs::create_dir_all(parent)?;
99        }
100        let bytes = serde_json::to_vec_pretty(self)?;
101        if bytes.len() > 2 * 1024 * 1024 {
102            return Err(DevelopmentError::InvalidInput(
103                "development graph exceeds the 2 MiB storage limit".into(),
104            ));
105        }
106        let temporary = path.with_extension(format!("json.tmp-{}", std::process::id()));
107        fs::write(&temporary, bytes)?;
108        if let Err(error) = fs::rename(&temporary, path) {
109            let _ = fs::remove_file(&temporary);
110            return Err(error.into());
111        }
112        Ok(())
113    }
114
115    pub fn link(&mut self, link: RuntimeLink) -> DevelopmentResult<()> {
116        if link.entity_id.is_empty() || link.entity_id.len() > 256 {
117            return Err(DevelopmentError::InvalidInput(
118                "runtime entity ID must be 1-256 bytes".into(),
119            ));
120        }
121        if !link.evidence.confidence.is_finite()
122            || !(0.0..=1.0).contains(&link.evidence.confidence)
123            || link.evidence.detail.len() > 2048
124        {
125            return Err(DevelopmentError::InvalidInput(
126                "link evidence must have finite confidence in [0,1] and bounded detail".into(),
127            ));
128        }
129        let links = self.links.entry(link.entity_id.clone()).or_default();
130        if let Some(existing) = links
131            .iter_mut()
132            .find(|existing| existing.source == link.source)
133        {
134            *existing = link;
135        } else {
136            if links.len() >= 16 {
137                return Err(DevelopmentError::InvalidInput(
138                    "one runtime entity cannot have more than 16 source links".into(),
139                ));
140            }
141            links.push(link);
142        }
143        Ok(())
144    }
145
146    pub fn links_for(&self, entity_id: &str) -> &[RuntimeLink] {
147        self.links.get(entity_id).map(Vec::as_slice).unwrap_or(&[])
148    }
149
150    pub fn best_link(&self, entity_id: &str) -> Option<&RuntimeLink> {
151        self.links_for(entity_id).iter().max_by(|left, right| {
152            left.evidence
153                .confidence
154                .total_cmp(&right.evidence.confidence)
155        })
156    }
157
158    pub fn entities_for_source(&self, path: &str, line: Option<u32>) -> Vec<&RuntimeLink> {
159        let mut links = self
160            .links
161            .values()
162            .flatten()
163            .filter(|link| {
164                link.source.path == path
165                    && line.is_none_or(|line| {
166                        (link.source.start_line..=link.source.end_line).contains(&line)
167                    })
168            })
169            .collect::<Vec<_>>();
170        links.sort_by(|left, right| {
171            right
172                .evidence
173                .confidence
174                .total_cmp(&left.evidence.confidence)
175                .then_with(|| left.entity_id.cmp(&right.entity_id))
176        });
177        links
178    }
179
180    pub fn discover_explicit_markers(
181        &mut self,
182        root: &Path,
183    ) -> DevelopmentResult<Vec<RuntimeLink>> {
184        let mut discovered = Vec::new();
185        discover_in_directory(root, root, &mut discovered)?;
186        for link in &discovered {
187            self.link(link.clone())?;
188        }
189        Ok(discovered)
190    }
191}
192
193fn discover_in_directory(
194    root: &Path,
195    directory: &Path,
196    discovered: &mut Vec<RuntimeLink>,
197) -> DevelopmentResult<()> {
198    if discovered.len() >= 512 {
199        return Ok(());
200    }
201    let mut entries = fs::read_dir(directory)?.collect::<Result<Vec<_>, _>>()?;
202    entries.sort_by_key(|entry| entry.file_name());
203    for entry in entries {
204        let path = entry.path();
205        let name = entry.file_name();
206        if matches!(
207            name.to_str(),
208            Some(".git" | "target" | "node_modules" | ".glass")
209        ) {
210            continue;
211        }
212        let metadata = fs::symlink_metadata(&path)?;
213        if metadata.file_type().is_symlink() {
214            continue;
215        }
216        if metadata.is_dir() {
217            discover_in_directory(root, &path, discovered)?;
218        } else if metadata.is_file() && metadata.len() <= MAX_FILE_BYTES as u64 {
219            let Some(extension) = path.extension().and_then(|value| value.to_str()) else {
220                continue;
221            };
222            if !matches!(
223                extension,
224                "rs" | "js" | "jsx" | "ts" | "tsx" | "vue" | "svelte" | "html"
225            ) {
226                continue;
227            }
228            let Ok(content) = read_bounded_utf8(&path, MAX_FILE_BYTES, "graph source file") else {
229                continue;
230            };
231            for (index, line) in content.lines().enumerate() {
232                for marker in ["data-glass-entity=\"", "glass:entity="] {
233                    let Some(start) = line.find(marker).map(|start| start + marker.len()) else {
234                        continue;
235                    };
236                    let tail = &line[start..];
237                    let entity = tail
238                        .split(|character: char| {
239                            character.is_whitespace()
240                                || matches!(character, '\"' | '\'' | '>' | ')' | ']' | '}')
241                        })
242                        .next()
243                        .unwrap_or("");
244                    if entity.is_empty() || entity.len() > 256 {
245                        continue;
246                    }
247                    let relative = path
248                        .strip_prefix(root)
249                        .map_err(|_| DevelopmentError::PathOutsideWorkspace(path.clone()))?
250                        .components()
251                        .map(|component| component.as_os_str().to_string_lossy())
252                        .collect::<Vec<_>>()
253                        .join("/");
254                    discovered.push(RuntimeLink {
255                        entity_id: entity.into(),
256                        source: SourceLocation::new(relative, index as u32 + 1, index as u32 + 1)?,
257                        evidence: LinkEvidence {
258                            provenance: LinkProvenance::ExplicitMarker,
259                            detail: format!("source marker `{marker}`"),
260                            confidence: 1.0,
261                        },
262                    });
263                }
264            }
265        }
266    }
267    Ok(())
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[test]
275    fn best_link_preserves_provenance_instead_of_fabricating_certainty() {
276        let source = SourceLocation::new("src/app.ts", 10, 12).unwrap();
277        let mut graph = DevelopmentGraph::default();
278        graph
279            .link(RuntimeLink {
280                entity_id: "button.submit".into(),
281                source,
282                evidence: LinkEvidence {
283                    provenance: LinkProvenance::Inferred,
284                    detail: "matched explicit entity marker".into(),
285                    confidence: 0.61,
286                },
287            })
288            .unwrap();
289        assert_eq!(
290            graph
291                .best_link("button.submit")
292                .unwrap()
293                .evidence
294                .confidence,
295            0.61
296        );
297        assert_eq!(
298            graph
299                .best_link("button.submit")
300                .unwrap()
301                .evidence
302                .provenance,
303            LinkProvenance::Inferred
304        );
305    }
306
307    #[test]
308    fn explicit_markers_create_bidirectional_links() {
309        let root = std::env::temp_dir().join(format!("glass-graph-{}", std::process::id()));
310        let _ = fs::remove_dir_all(&root);
311        fs::create_dir_all(root.join("src")).unwrap();
312        fs::write(
313            root.join("src/button.tsx"),
314            "<button data-glass-entity=\"action.checkout.submit\">Pay</button>\n",
315        )
316        .unwrap();
317        let mut graph = DevelopmentGraph::default();
318        graph.discover_explicit_markers(&root).unwrap();
319        assert_eq!(
320            graph
321                .best_link("action.checkout.submit")
322                .unwrap()
323                .source
324                .start_line,
325            1
326        );
327        assert_eq!(
328            graph.entities_for_source("src/button.tsx", Some(1)).len(),
329            1
330        );
331        let _ = fs::remove_dir_all(root);
332    }
333}