weave-content 0.2.23

Content DSL parser, validator, and builder for OSINT case files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use rayon::prelude::*;

use crate::entity::{Entity, Label};
use crate::parser::ParseError;

/// Maximum length of entity filename stem (without `.md`).
const MAX_FILENAME_LEN: usize = 200;

/// A loaded entity with its source file path.
#[derive(Debug)]
pub struct RegistryEntry {
    pub entity: Entity,
    pub path: PathBuf,
    pub tags: Vec<String>,
}

/// Entity registry: holds all shared entities loaded from `people/` and
/// `organizations/` directories. Provides name-based lookup for cross-file
/// resolution.
#[derive(Debug)]
pub struct EntityRegistry {
    entries: Vec<RegistryEntry>,
    /// Name → index into `entries`. Names are case-sensitive.
    name_index: HashMap<String, usize>,
    /// Content root directory for computing file-path slugs.
    content_root: Option<PathBuf>,
}

impl EntityRegistry {
    /// Build a registry from a content root directory.
    ///
    /// Scans `{root}/people/**/*.md` and `{root}/organizations/**/*.md`, parses
    /// each file, validates for duplicates and filename mismatches. Supports both
    /// flat and nested (country-based) directory layouts.
    pub fn load(root: &Path) -> Result<Self, Vec<ParseError>> {
        let mut entries = Vec::new();
        let mut errors = Vec::new();

        let actor_dir = root.join("people");
        let institution_dir = root.join("organizations");

        load_directory(&actor_dir, Label::Person, &mut entries, &mut errors);
        load_directory(
            &institution_dir,
            Label::Organization,
            &mut entries,
            &mut errors,
        );

        // Build name index and detect duplicates
        let name_index = build_name_index(&entries, &mut errors);

        if errors.iter().any(|e| e.message.starts_with("duplicate")) {
            return Err(errors);
        }

        // Filename mismatch warnings are non-fatal, report via errors but don't fail
        // (caller can filter by message prefix if needed)

        if errors.iter().any(|e| !e.message.starts_with("warning:")) {
            return Err(errors);
        }

        // Warnings only -- attach them but succeed
        if !errors.is_empty() {
            for err in &errors {
                eprintln!("{err}");
            }
        }

        Ok(Self {
            entries,
            name_index,
            content_root: Some(root.to_path_buf()),
        })
    }

    /// Build a registry from pre-parsed entries.
    pub fn from_entries(entries: Vec<RegistryEntry>) -> Result<Self, Vec<ParseError>> {
        let mut errors = Vec::new();
        let name_index = build_name_index(&entries, &mut errors);

        let has_errors = errors.iter().any(|e| !e.message.starts_with("warning:"));
        if has_errors {
            return Err(errors);
        }

        Ok(Self {
            entries,
            name_index,
            content_root: None,
        })
    }

    /// Look up an entity by name. Returns None if not found.
    pub fn get_by_name(&self, name: &str) -> Option<&RegistryEntry> {
        self.name_index.get(name).map(|&idx| &self.entries[idx])
    }

    /// Number of entities in the registry.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the registry is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// All entity names in the registry.
    pub fn names(&self) -> Vec<&str> {
        self.entries
            .iter()
            .map(|e| e.entity.name.as_str())
            .collect()
    }

    /// All registry entries.
    pub fn entries(&self) -> &[RegistryEntry] {
        &self.entries
    }

    /// Compute the file-path slug for an entry (path relative to content root, minus `.md`).
    /// Returns `None` if content root is not set.
    pub fn slug_for(&self, entry: &RegistryEntry) -> Option<String> {
        let root = self.content_root.as_ref()?;
        path_to_slug(&entry.path, root)
    }

    /// Content root directory, if set.
    pub fn content_root(&self) -> Option<&Path> {
        self.content_root.as_deref()
    }
}

/// Compute file-path slug from an absolute path relative to content root.
/// Returns the path minus the `.md` extension, e.g. `people/id/harvey-moeis`.
pub fn path_to_slug(path: &Path, content_root: &Path) -> Option<String> {
    let relative = path.strip_prefix(content_root).ok()?;
    let s = relative.to_str()?;
    Some(s.strip_suffix(".md").unwrap_or(s).to_string())
}

/// Load all `.md` files from a directory tree, parsing each as an entity file.
/// Supports both flat (`people/*.md`) and nested (`people/<country>/*.md`)
/// layouts. Uses rayon to parse files in parallel.
fn load_directory(
    dir: &Path,
    label: Label,
    entries: &mut Vec<RegistryEntry>,
    errors: &mut Vec<ParseError>,
) {
    let mut paths = Vec::new();
    collect_md_files(dir, &mut paths, 0);

    // Sort for deterministic ordering
    paths.sort();

    // Parse all files in parallel, collect results
    let results: Vec<ParseResult> = paths
        .par_iter()
        .map(|path| parse_entity_file(path, label))
        .collect();

    // Merge results sequentially to preserve deterministic order
    for result in results {
        if let Some(entry) = result.entry {
            entries.push(entry);
        }
        errors.extend(result.errors);
    }
}

/// Recursively collect `.md` files from a directory tree.
/// Max depth 2 supports `people/<country>/file.md` layout.
fn collect_md_files(dir: &Path, paths: &mut Vec<PathBuf>, depth: usize) {
    const MAX_DEPTH: usize = 2;
    if depth > MAX_DEPTH {
        return;
    }

    let Ok(read_dir) = std::fs::read_dir(dir) else {
        return;
    };

    let mut dir_entries: Vec<_> = read_dir.filter_map(Result::ok).collect();
    dir_entries.sort_by_key(std::fs::DirEntry::file_name);

    for entry in dir_entries {
        let path = entry.path();
        if path.is_dir() {
            collect_md_files(&path, paths, depth + 1);
        } else if path.extension().and_then(|e| e.to_str()) == Some("md") {
            paths.push(path);
        }
    }
}

/// Result of parsing a single entity file.
struct ParseResult {
    entry: Option<RegistryEntry>,
    errors: Vec<ParseError>,
}

/// Parse a single entity file, returning the entry and any errors/warnings.
fn parse_entity_file(path: &Path, label: Label) -> ParseResult {
    let content = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(e) => {
            return ParseResult {
                entry: None,
                errors: vec![ParseError {
                    line: 0,
                    message: format!("{}: error reading file: {e}", path.display()),
                }],
            };
        }
    };

    let parsed = match crate::parser::parse_entity_file(&content) {
        Ok(p) => p,
        Err(parse_errors) => {
            return ParseResult {
                entry: None,
                errors: parse_errors
                    .into_iter()
                    .map(|err| ParseError {
                        line: err.line,
                        message: format!("{}: {}", path.display(), err.message),
                    })
                    .collect(),
            };
        }
    };

    let mut field_errors = Vec::new();
    let mut entity = crate::entity::parse_entity_file_body(
        &parsed.name,
        &parsed.body,
        label,
        parsed.id,
        parsed.title_line,
        &mut field_errors,
    );
    entity.tags.clone_from(&parsed.tags);

    let mut errors: Vec<ParseError> = field_errors
        .into_iter()
        .map(|err| ParseError {
            line: err.line,
            message: format!("{}: {}", path.display(), err.message),
        })
        .collect();

    // Validate filename matches content
    validate_filename(path, &entity, &mut errors);

    ParseResult {
        entry: Some(RegistryEntry {
            entity,
            path: path.to_path_buf(),
            tags: parsed.tags,
        }),
        errors,
    }
}

/// Build name → index map, detecting duplicate names.
fn build_name_index(
    entries: &[RegistryEntry],
    errors: &mut Vec<ParseError>,
) -> HashMap<String, usize> {
    let mut index = HashMap::new();

    for (i, entry) in entries.iter().enumerate() {
        let name = &entry.entity.name;
        if let Some(&existing_idx) = index.get(name.as_str()) {
            let existing: &RegistryEntry = &entries[existing_idx];
            errors.push(ParseError {
                line: entry.entity.line,
                message: format!(
                    "duplicate entity name {name:?} in {} (first defined in {})",
                    entry.path.display(),
                    existing.path.display(),
                ),
            });
        } else {
            index.insert(name.clone(), i);
        }
    }

    index
}

/// Warn if entity filename doesn't match content.
/// Expected: `<name>--<qualifier>.md` in kebab-case.
fn validate_filename(path: &Path, entity: &Entity, errors: &mut Vec<ParseError>) {
    let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
        return;
    };

    if stem.len() > MAX_FILENAME_LEN {
        errors.push(ParseError {
            line: 0,
            message: format!(
                "warning: {}: filename stem exceeds {MAX_FILENAME_LEN} chars",
                path.display()
            ),
        });
    }

    let expected_name = to_kebab_case(&entity.name);
    let qualifier = entity
        .fields
        .iter()
        .find(|(k, _)| k == "qualifier")
        .and_then(|(_, v)| match v {
            crate::entity::FieldValue::Single(s) => Some(s.as_str()),
            crate::entity::FieldValue::List(_) => None,
        });

    let expected_stem = match qualifier {
        Some(q) => format!("{expected_name}--{}", to_kebab_case(q)),
        None => expected_name,
    };

    if stem != expected_stem {
        errors.push(ParseError {
            line: 0,
            message: format!(
                "warning: {}: filename {stem:?} doesn't match expected {expected_stem:?}",
                path.display()
            ),
        });
    }
}

/// Convert a display name to kebab-case for filename comparison.
fn to_kebab_case(s: &str) -> String {
    s.chars()
        .map(|c| {
            if c.is_alphanumeric() {
                c.to_ascii_lowercase()
            } else {
                '-'
            }
        })
        .collect::<String>()
        .split('-')
        .filter(|p| !p.is_empty())
        .collect::<Vec<_>>()
        .join("-")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::entity::{Entity, FieldValue, Label};

    fn make_entry(name: &str, label: Label, path: &str) -> RegistryEntry {
        RegistryEntry {
            entity: Entity {
                name: name.to_string(),
                label,
                fields: Vec::new(),
                id: None,
                line: 1,
                tags: Vec::new(),
                slug: None,
            },
            path: PathBuf::from(path),
            tags: Vec::new(),
        }
    }

    #[test]
    fn registry_from_entries_lookup() {
        let entries = vec![
            make_entry("Alice", Label::Person, "people/alice.md"),
            make_entry("Corp Inc", Label::Organization, "organizations/corp-inc.md"),
        ];

        let registry = EntityRegistry::from_entries(entries).unwrap();
        assert_eq!(registry.len(), 2);
        assert!(registry.get_by_name("Alice").is_some());
        assert!(registry.get_by_name("Corp Inc").is_some());
        assert!(registry.get_by_name("Bob").is_none());
    }

    #[test]
    fn registry_detects_duplicate_names() {
        let entries = vec![
            make_entry("Alice", Label::Person, "people/alice-a.md"),
            make_entry("Alice", Label::Person, "people/alice-b.md"),
        ];

        let errors = EntityRegistry::from_entries(entries).unwrap_err();
        assert!(errors.iter().any(|e| e.message.contains("duplicate")));
    }

    #[test]
    fn registry_names_list() {
        let entries = vec![
            make_entry("Alice", Label::Person, "people/alice.md"),
            make_entry("Bob", Label::Person, "people/bob.md"),
        ];

        let registry = EntityRegistry::from_entries(entries).unwrap();
        let names = registry.names();
        assert!(names.contains(&"Alice"));
        assert!(names.contains(&"Bob"));
    }

    #[test]
    fn to_kebab_case_conversion() {
        assert_eq!(to_kebab_case("Mark Bonnick"), "mark-bonnick");
        assert_eq!(to_kebab_case("Arsenal FC"), "arsenal-fc");
        assert_eq!(
            to_kebab_case("English Football Club"),
            "english-football-club"
        );
        assert_eq!(to_kebab_case("Bob"), "bob");
    }

    #[test]
    fn validate_filename_matching() {
        let entity = Entity {
            name: "Mark Bonnick".to_string(),
            label: Label::Person,
            fields: vec![(
                "qualifier".to_string(),
                FieldValue::Single("Arsenal Kit Manager".to_string()),
            )],
            id: None,
            line: 1,
            tags: Vec::new(),
            slug: None,
        };

        let mut errors = Vec::new();

        // Correct filename
        validate_filename(
            Path::new("people/mark-bonnick--arsenal-kit-manager.md"),
            &entity,
            &mut errors,
        );
        assert!(errors.is_empty(), "errors: {errors:?}");

        // Wrong filename
        validate_filename(Path::new("people/wrong-name.md"), &entity, &mut errors);
        assert!(errors.iter().any(|e| e.message.contains("warning:")));
    }

    #[test]
    fn validate_filename_no_qualifier() {
        let entity = Entity {
            name: "Bob".to_string(),
            label: Label::Person,
            fields: Vec::new(),
            id: None,
            line: 1,
            tags: Vec::new(),
            slug: None,
        };

        let mut errors = Vec::new();
        validate_filename(Path::new("people/bob.md"), &entity, &mut errors);
        assert!(errors.is_empty(), "errors: {errors:?}");
    }

    #[test]
    fn empty_registry() {
        let registry = EntityRegistry::from_entries(Vec::new()).unwrap();
        assert!(registry.is_empty());
        assert_eq!(registry.len(), 0);
        assert!(registry.get_by_name("anything").is_none());
    }
}