Skip to main content

weave_content/
relationship.rs

1use std::collections::HashSet;
2
3use crate::parser::{ParseError, SourceEntry};
4
5/// Maximum relationships per file.
6const MAX_RELATIONSHIPS_PER_FILE: usize = 200;
7
8/// All known relationship types, organized by category per ADR-014 ยง3.
9const KNOWN_REL_TYPES: &[&str] = &[
10    // Organizational
11    "employed_by",
12    "member_of",
13    "leads",
14    "founded",
15    "owns",
16    "subsidiary_of",
17    // Legal/Criminal
18    "charged_with",
19    "convicted_of",
20    "investigated_by",
21    "prosecuted_by",
22    "defended_by",
23    "testified_in",
24    "sentenced_to",
25    "appealed",
26    "acquitted_of",
27    "pardoned_by",
28    "arrested_by",
29    // Financial
30    "paid_to",
31    "received_from",
32    "funded_by",
33    "awarded_contract",
34    "approved_budget",
35    "seized_from",
36    // Governance
37    "appointed_by",
38    "approved_by",
39    "regulated_by",
40    "licensed_by",
41    "lobbied",
42    // Personal
43    "family_of",
44    "associate_of",
45    // Temporal
46    "preceded_by",
47    // Document
48    "documents",
49    "authorizes",
50    "references",
51    // Case
52    "related_to",
53    "part_of",
54    "involved_in",
55    // Source
56    "sourced_by",
57];
58
59/// Known fields on relationships (nested bullets).
60const REL_FIELDS: &[&str] = &[
61    "id",
62    "source",
63    "description",
64    "amounts",
65    "valid_from",
66    "valid_until",
67];
68
69/// A parsed relationship.
70#[derive(Debug)]
71#[allow(clippy::struct_field_names)]
72pub struct Rel {
73    pub source_name: String,
74    pub target_name: String,
75    pub rel_type: String,
76    pub source_urls: Vec<String>,
77    pub fields: Vec<(String, String)>,
78    /// Stored NULID from `id:` field (None if not yet generated).
79    pub id: Option<String>,
80    /// Line number (1-indexed) in the original file.
81    pub line: usize,
82}
83
84/// Parse relationships from the `## Relationships` section body.
85///
86/// `entity_names` is the set of entity names defined in the file (for resolution).
87/// `default_sources` are the front matter sources used when no `source:` override.
88#[allow(clippy::implicit_hasher)]
89#[allow(clippy::too_many_lines)]
90pub fn parse_relationships(
91    body: &str,
92    section_start_line: usize,
93    entity_names: &HashSet<&str>,
94    default_sources: &[SourceEntry],
95    errors: &mut Vec<ParseError>,
96) -> Vec<Rel> {
97    let lines: Vec<&str> = body.lines().collect();
98    let mut rels: Vec<Rel> = Vec::new();
99
100    // Current relationship being built
101    let mut current: Option<RelBuilder> = None;
102
103    for (i, line) in lines.iter().enumerate() {
104        let file_line = section_start_line + 1 + i;
105        let trimmed = line.trim();
106
107        // Top-level bullet: `- Source -> Target: type`
108        if trimmed.starts_with("- ") && !line.starts_with("  ") {
109            // Flush previous
110            if let Some(builder) = current.take() {
111                rels.push(builder.finish(default_sources));
112            }
113
114            let item = &trimmed[2..];
115            match parse_rel_line(item) {
116                Some((source, target, rel_type)) => {
117                    // Validate rel_type
118                    if !KNOWN_REL_TYPES.contains(&rel_type.as_str()) {
119                        errors.push(ParseError {
120                            line: file_line,
121                            message: format!(
122                                "unknown relationship type {rel_type:?} (known: {})",
123                                KNOWN_REL_TYPES.join(", ")
124                            ),
125                        });
126                    }
127
128                    // Validate entity names
129                    if !entity_names.contains(&source.as_str()) {
130                        errors.push(ParseError {
131                            line: file_line,
132                            message: format!(
133                                "entity {source:?} in relationship not defined in file"
134                            ),
135                        });
136                    }
137                    if !entity_names.contains(&target.as_str()) {
138                        errors.push(ParseError {
139                            line: file_line,
140                            message: format!(
141                                "entity {target:?} in relationship not defined in file"
142                            ),
143                        });
144                    }
145
146                    current = Some(RelBuilder {
147                        source_name: source,
148                        target_name: target,
149                        rel_type,
150                        source_urls: Vec::new(),
151                        fields: Vec::new(),
152                        id: None,
153                        line: file_line,
154                    });
155                }
156                None => {
157                    errors.push(ParseError {
158                        line: file_line,
159                        message: format!(
160                            "invalid relationship syntax: expected `- Source -> Target: type`, got {trimmed:?}"
161                        ),
162                    });
163                }
164            }
165            continue;
166        }
167
168        // Indented field: `  key: value`
169        if line.starts_with("  ") && current.is_some() {
170            if let Some((key, value)) = parse_kv(trimmed) {
171                if !REL_FIELDS.contains(&key.as_str()) {
172                    errors.push(ParseError {
173                        line: file_line,
174                        message: format!("unknown relationship field {key:?}"),
175                    });
176                    continue;
177                }
178
179                let builder = current.as_mut().unwrap_or_else(|| unreachable!());
180
181                if key == "id" {
182                    builder.id = Some(value);
183                } else if key == "source" {
184                    if !value.starts_with("https://") {
185                        errors.push(ParseError {
186                            line: file_line,
187                            message: format!("relationship source URL must be HTTPS: {value:?}"),
188                        });
189                    }
190                    builder.source_urls.push(value);
191                } else {
192                    // Validate field constraints
193                    validate_rel_field(&key, &value, file_line, errors);
194                    builder.fields.push((key, value));
195                }
196            } else {
197                errors.push(ParseError {
198                    line: file_line,
199                    message: format!(
200                        "invalid field syntax: expected `key: value`, got {trimmed:?}"
201                    ),
202                });
203            }
204        }
205
206        // Ignore blank lines
207    }
208
209    // Flush last
210    if let Some(builder) = current.take() {
211        rels.push(builder.finish(default_sources));
212    }
213
214    // Boundary check
215    if rels.len() > MAX_RELATIONSHIPS_PER_FILE {
216        errors.push(ParseError {
217            line: section_start_line,
218            message: format!(
219                "too many relationships (max {MAX_RELATIONSHIPS_PER_FILE}, got {})",
220                rels.len()
221            ),
222        });
223    }
224
225    rels
226}
227
228struct RelBuilder {
229    source_name: String,
230    target_name: String,
231    rel_type: String,
232    source_urls: Vec<String>,
233    fields: Vec<(String, String)>,
234    id: Option<String>,
235    line: usize,
236}
237
238impl RelBuilder {
239    fn finish(self, default_sources: &[SourceEntry]) -> Rel {
240        let source_urls = if self.source_urls.is_empty() {
241            default_sources
242                .iter()
243                .map(|s| s.url().to_string())
244                .collect()
245        } else {
246            self.source_urls
247        };
248
249        Rel {
250            source_name: self.source_name,
251            target_name: self.target_name,
252            rel_type: self.rel_type,
253            source_urls,
254            fields: self.fields,
255            id: self.id,
256            line: self.line,
257        }
258    }
259}
260
261/// Parse `Source -> Target: type` from a relationship bullet.
262fn parse_rel_line(item: &str) -> Option<(String, String, String)> {
263    let arrow_pos = item.find(" -> ")?;
264    let source = item[..arrow_pos].trim();
265    let after_arrow = &item[arrow_pos + 4..];
266
267    let colon_pos = after_arrow.rfind(':')?;
268    let target = after_arrow[..colon_pos].trim();
269    let rel_type = after_arrow[colon_pos + 1..]
270        .trim()
271        .to_lowercase()
272        .replace(' ', "_");
273
274    if source.is_empty() || target.is_empty() || rel_type.is_empty() {
275        return None;
276    }
277
278    Some((source.to_string(), target.to_string(), rel_type))
279}
280
281fn parse_kv(s: &str) -> Option<(String, String)> {
282    let colon = s.find(':')?;
283    let key = s[..colon].trim();
284    if key.is_empty() {
285        return None;
286    }
287    let value = s[colon + 1..].trim();
288    Some((key.to_string(), value.to_string()))
289}
290
291fn validate_rel_field(key: &str, value: &str, line: usize, errors: &mut Vec<ParseError>) {
292    let max = match key {
293        "description" => 1000,
294        "amounts" => 200,
295        "valid_from" | "valid_until" => 10,
296        _ => return,
297    };
298
299    if value.len() > max {
300        errors.push(ParseError {
301            line,
302            message: format!(
303                "relationship field {key:?} exceeds {max} chars (got {})",
304                value.len()
305            ),
306        });
307    }
308
309    // Date format validation
310    if matches!(key, "valid_from" | "valid_until") && !value.is_empty() {
311        let valid = matches!(value.len(), 4 | 7 | 10)
312            && value.chars().enumerate().all(|(i, c)| match i {
313                4 | 7 => c == '-',
314                _ => c.is_ascii_digit(),
315            });
316        if !valid {
317            errors.push(ParseError {
318                line,
319                message: format!(
320                    "relationship field {key:?} must be YYYY, YYYY-MM, or YYYY-MM-DD, got {value:?}"
321                ),
322            });
323        }
324    }
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    #[test]
332    fn parse_basic_relationship() {
333        let body = "\n- Alice -> Bob: employed_by\n";
334        let names = HashSet::from(["Alice", "Bob"]);
335        let sources = vec![SourceEntry::Url("https://example.com/src".into())];
336        let mut errors = Vec::new();
337
338        let rels = parse_relationships(body, 50, &names, &sources, &mut errors);
339        assert!(errors.is_empty(), "errors: {errors:?}");
340        assert_eq!(rels.len(), 1);
341        assert_eq!(rels[0].source_name, "Alice");
342        assert_eq!(rels[0].target_name, "Bob");
343        assert_eq!(rels[0].rel_type, "employed_by");
344        // Should default to front matter sources
345        assert_eq!(rels[0].source_urls, vec!["https://example.com/src"]);
346    }
347
348    #[test]
349    fn parse_relationship_with_source_override() {
350        let body = [
351            "",
352            "- Alice -> Bob: associate_of",
353            "  source: https://specific.com/article",
354            "",
355        ]
356        .join("\n");
357        let names = HashSet::from(["Alice", "Bob"]);
358        let sources = vec![SourceEntry::Url("https://default.com".into())];
359        let mut errors = Vec::new();
360
361        let rels = parse_relationships(&body, 10, &names, &sources, &mut errors);
362        assert!(errors.is_empty(), "errors: {errors:?}");
363        assert_eq!(rels[0].source_urls, vec!["https://specific.com/article"]);
364    }
365
366    #[test]
367    fn parse_relationship_with_fields() {
368        let body = [
369            "",
370            "- Alice -> Corp: paid_to",
371            "  amounts: 50000 EUR",
372            "  valid_from: 2020-01",
373            "  description: Campaign donation",
374            "",
375        ]
376        .join("\n");
377        let names = HashSet::from(["Alice", "Corp"]);
378        let mut errors = Vec::new();
379
380        let rels = parse_relationships(&body, 10, &names, &[], &mut errors);
381        assert!(errors.is_empty(), "errors: {errors:?}");
382        assert_eq!(rels[0].fields.len(), 3);
383    }
384
385    #[test]
386    fn reject_unknown_rel_type() {
387        let body = "\n- Alice -> Bob: best_friends\n";
388        let names = HashSet::from(["Alice", "Bob"]);
389        let mut errors = Vec::new();
390
391        parse_relationships(body, 1, &names, &[], &mut errors);
392        assert!(
393            errors
394                .iter()
395                .any(|e| e.message.contains("unknown relationship type"))
396        );
397    }
398
399    #[test]
400    fn reject_unresolved_entity() {
401        let body = "\n- Alice -> Unknown: employed_by\n";
402        let names = HashSet::from(["Alice"]);
403        let mut errors = Vec::new();
404
405        parse_relationships(body, 1, &names, &[], &mut errors);
406        assert!(
407            errors
408                .iter()
409                .any(|e| e.message.contains("not defined in file"))
410        );
411    }
412
413    #[test]
414    fn reject_non_https_source_override() {
415        let body = [
416            "",
417            "- Alice -> Bob: associate_of",
418            "  source: http://insecure.com",
419            "",
420        ]
421        .join("\n");
422        let names = HashSet::from(["Alice", "Bob"]);
423        let mut errors = Vec::new();
424
425        parse_relationships(&body, 1, &names, &[], &mut errors);
426        assert!(errors.iter().any(|e| e.message.contains("HTTPS")));
427    }
428
429    #[test]
430    fn reject_unknown_rel_field() {
431        let body = ["", "- Alice -> Bob: associate_of", "  foobar: value", ""].join("\n");
432        let names = HashSet::from(["Alice", "Bob"]);
433        let mut errors = Vec::new();
434
435        parse_relationships(&body, 1, &names, &[], &mut errors);
436        assert!(
437            errors
438                .iter()
439                .any(|e| e.message.contains("unknown relationship field"))
440        );
441    }
442
443    #[test]
444    fn multiple_relationships() {
445        let body = [
446            "",
447            "- Alice -> Bob: employed_by",
448            "- Bob -> Corp: member_of",
449            "- Corp -> Alice: charged_with",
450            "",
451        ]
452        .join("\n");
453        let names = HashSet::from(["Alice", "Bob", "Corp"]);
454        let mut errors = Vec::new();
455
456        let rels = parse_relationships(&body, 1, &names, &[], &mut errors);
457        assert!(errors.is_empty(), "errors: {errors:?}");
458        assert_eq!(rels.len(), 3);
459    }
460
461    #[test]
462    fn parse_rel_line_syntax() {
463        let result = parse_rel_line("Mark Bonnick -> Arsenal FC: employed_by");
464        assert_eq!(
465            result,
466            Some((
467                "Mark Bonnick".into(),
468                "Arsenal FC".into(),
469                "employed_by".into()
470            ))
471        );
472    }
473
474    #[test]
475    fn parse_rel_line_invalid() {
476        assert!(parse_rel_line("not a relationship").is_none());
477        assert!(parse_rel_line("-> Target: type").is_none());
478        assert!(parse_rel_line("Source -> : type").is_none());
479    }
480
481    #[test]
482    fn relationship_date_validation() {
483        let body = [
484            "",
485            "- Alice -> Bob: associate_of",
486            "  valid_from: not-a-date",
487            "",
488        ]
489        .join("\n");
490        let names = HashSet::from(["Alice", "Bob"]);
491        let mut errors = Vec::new();
492
493        parse_relationships(&body, 1, &names, &[], &mut errors);
494        assert!(errors.iter().any(|e| e.message.contains("YYYY")));
495    }
496
497    #[test]
498    fn multiple_source_overrides() {
499        let body = [
500            "",
501            "- Alice -> Bob: associate_of",
502            "  source: https://first.com",
503            "  source: https://second.com",
504            "",
505        ]
506        .join("\n");
507        let names = HashSet::from(["Alice", "Bob"]);
508        let mut errors = Vec::new();
509
510        let rels = parse_relationships(&body, 1, &names, &[], &mut errors);
511        assert!(errors.is_empty(), "errors: {errors:?}");
512        assert_eq!(rels[0].source_urls.len(), 2);
513    }
514}