weave-content 0.2.10

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
#![deny(unsafe_code)]
#![deny(clippy::unwrap_used)]
#![deny(clippy::expect_used)]
#![allow(clippy::missing_errors_doc)]

pub mod build_cache;
pub mod cache;
pub mod domain;
pub mod entity;
pub mod html;
pub mod nulid_gen;
pub mod output;
pub mod parser;
pub mod registry;
pub mod relationship;
pub mod tags;
pub mod timeline;
pub mod verifier;
pub mod writeback;

use std::collections::HashSet;

use crate::entity::Entity;
use crate::parser::{ParseError, ParsedCase, SectionKind};
use crate::relationship::Rel;

/// Parse a case file fully: front matter, entities, relationships, timeline.
/// Returns the parsed case, inline entities, and relationships (including NEXT from timeline).
///
/// When a registry is provided, relationship and timeline names are resolved
/// against both inline events AND the global entity registry.
pub fn parse_full(
    content: &str,
    reg: Option<&registry::EntityRegistry>,
) -> Result<(ParsedCase, Vec<Entity>, Vec<Rel>), Vec<ParseError>> {
    let case = parser::parse(content)?;
    let mut errors = Vec::new();

    let mut all_entities = Vec::new();
    for section in &case.sections {
        if matches!(
            section.kind,
            SectionKind::Events | SectionKind::Documents | SectionKind::Assets
        ) {
            let entities =
                entity::parse_entities(&section.body, section.kind, section.line, &mut errors);
            all_entities.extend(entities);
        }
    }

    // Build combined name set: inline events + registry entities
    let mut entity_names: HashSet<&str> = all_entities.iter().map(|e| e.name.as_str()).collect();
    if let Some(registry) = reg {
        for name in registry.names() {
            entity_names.insert(name);
        }
    }

    let event_names: HashSet<&str> = all_entities
        .iter()
        .filter(|e| e.label == entity::Label::Event)
        .map(|e| e.name.as_str())
        .collect();

    let mut all_rels = Vec::new();
    for section in &case.sections {
        if section.kind == SectionKind::Relationships {
            let rels = relationship::parse_relationships(
                &section.body,
                section.line,
                &entity_names,
                &case.sources,
                &mut errors,
            );
            all_rels.extend(rels);
        }
    }

    for section in &case.sections {
        if section.kind == SectionKind::Timeline {
            let rels =
                timeline::parse_timeline(&section.body, section.line, &event_names, &mut errors);
            all_rels.extend(rels);
        }
    }

    if errors.is_empty() {
        Ok((case, all_entities, all_rels))
    } else {
        Err(errors)
    }
}

/// Collect registry entities referenced by relationships in this case.
pub fn collect_referenced_registry_entities(
    rels: &[Rel],
    inline_entities: &[Entity],
    reg: &registry::EntityRegistry,
) -> Vec<Entity> {
    let inline_names: HashSet<&str> = inline_entities.iter().map(|e| e.name.as_str()).collect();
    let mut referenced = Vec::new();
    let mut seen_names: HashSet<String> = HashSet::new();

    for rel in rels {
        for name in [&rel.source_name, &rel.target_name] {
            if !inline_names.contains(name.as_str())
                && seen_names.insert(name.clone())
                && let Some(entry) = reg.get_by_name(name)
            {
                referenced.push(entry.entity.clone());
            }
        }
    }

    referenced
}

/// Build a `CaseOutput` from a case file path.
/// Handles parsing and ID writeback.
pub fn build_case_output(
    path: &str,
    reg: &registry::EntityRegistry,
) -> Result<output::CaseOutput, i32> {
    let mut written = HashSet::new();
    build_case_output_tracked(path, reg, &mut written)
}

/// Build a `CaseOutput` from a case file path, tracking which entity files
/// have already been written back. This avoids re-reading entity files from
/// disk when multiple cases reference the same shared entity.
#[allow(clippy::implicit_hasher)]
pub fn build_case_output_tracked(
    path: &str,
    reg: &registry::EntityRegistry,
    written_entities: &mut HashSet<std::path::PathBuf>,
) -> Result<output::CaseOutput, i32> {
    let content = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("{path}: error reading file: {e}");
            return Err(2);
        }
    };

    let (case, entities, rels) = match parse_full(&content, Some(reg)) {
        Ok(result) => result,
        Err(errors) => {
            for err in &errors {
                eprintln!("{path}:{err}");
            }
            return Err(1);
        }
    };

    let referenced_entities = collect_referenced_registry_entities(&rels, &entities, reg);

    let build_result = match output::build_output(
        &case.id,
        &case.title,
        &case.summary,
        &case.tags,
        &case.sources,
        &entities,
        &rels,
        &referenced_entities,
    ) {
        Ok(out) => out,
        Err(errors) => {
            for err in &errors {
                eprintln!("{path}:{err}");
            }
            return Err(1);
        }
    };

    let case_output = build_result.output;

    // Write back generated IDs to source case file
    if !build_result.case_pending.is_empty() {
        let mut pending = build_result.case_pending;
        if let Some(modified) = writeback::apply_writebacks(&content, &mut pending) {
            if let Err(e) = writeback::write_file(std::path::Path::new(path), &modified) {
                eprintln!("{e}");
                return Err(2);
            }
            let count = pending.len();
            eprintln!("{path}: wrote {count} generated ID(s) back to file");
        }
    }

    // Write back generated IDs to entity files
    if let Some(code) =
        writeback_registry_entities(&build_result.registry_pending, reg, written_entities)
    {
        return Err(code);
    }

    eprintln!(
        "{path}: built ({} nodes, {} relationships)",
        case_output.nodes.len(),
        case_output.relationships.len()
    );
    Ok(case_output)
}

/// Write back generated IDs to registry entity files.
/// Tracks already-written paths in `written` to avoid redundant disk reads.
/// Returns `Some(exit_code)` on error, `None` on success.
fn writeback_registry_entities(
    pending: &[(String, writeback::PendingId)],
    reg: &registry::EntityRegistry,
    written: &mut HashSet<std::path::PathBuf>,
) -> Option<i32> {
    for (entity_name, pending_id) in pending {
        let Some(entry) = reg.get_by_name(entity_name) else {
            continue;
        };
        let entity_path = &entry.path;

        // Skip if this entity file was already written by a previous case.
        if !written.insert(entity_path.clone()) {
            continue;
        }

        // Also skip if the entity already has an ID in the registry
        // (loaded from file at startup).
        if entry.entity.id.is_some() {
            continue;
        }

        let entity_content = match std::fs::read_to_string(entity_path) {
            Ok(c) => c,
            Err(e) => {
                eprintln!("{}: error reading file: {e}", entity_path.display());
                return Some(2);
            }
        };

        let fm_end = writeback::find_front_matter_end(&entity_content);
        let mut ids = vec![writeback::PendingId {
            line: fm_end.unwrap_or(2),
            id: pending_id.id.clone(),
            kind: writeback::WriteBackKind::EntityFrontMatter,
        }];
        if let Some(modified) = writeback::apply_writebacks(&entity_content, &mut ids) {
            if let Err(e) = writeback::write_file(entity_path, &modified) {
                eprintln!("{e}");
                return Some(2);
            }
            eprintln!("{}: wrote generated ID back to file", entity_path.display());
        }
    }
    None
}

/// Check whether a file's YAML front matter already contains an `id:` field.
#[cfg(test)]
fn front_matter_has_id(content: &str) -> bool {
    let mut in_front_matter = false;
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed == "---" && !in_front_matter {
            in_front_matter = true;
        } else if trimmed == "---" && in_front_matter {
            return false; // end of front matter, no id found
        } else if in_front_matter && trimmed.starts_with("id:") {
            return true;
        }
    }
    false
}

/// Resolve the content root directory.
///
/// Priority: explicit `--root` flag > parent of given path > current directory.
pub fn resolve_content_root(path: Option<&str>, root: Option<&str>) -> std::path::PathBuf {
    if let Some(r) = root {
        return std::path::PathBuf::from(r);
    }
    if let Some(p) = path {
        let p = std::path::Path::new(p);
        if p.is_file() {
            if let Some(parent) = p.parent() {
                for ancestor in parent.ancestors() {
                    if ancestor.join("cases").is_dir()
                        || ancestor.join("people").is_dir()
                        || ancestor.join("organizations").is_dir()
                    {
                        return ancestor.to_path_buf();
                    }
                }
                return parent.to_path_buf();
            }
        } else if p.is_dir() {
            return p.to_path_buf();
        }
    }
    std::path::PathBuf::from(".")
}

/// Load entity registry from content root. Returns empty registry if no entity dirs exist.
pub fn load_registry(content_root: &std::path::Path) -> Result<registry::EntityRegistry, i32> {
    match registry::EntityRegistry::load(content_root) {
        Ok(reg) => Ok(reg),
        Err(errors) => {
            for err in &errors {
                eprintln!("registry: {err}");
            }
            Err(1)
        }
    }
}

/// Load tag registry from content root. Returns empty registry if no tags.yaml exists.
pub fn load_tag_registry(content_root: &std::path::Path) -> Result<tags::TagRegistry, i32> {
    match tags::TagRegistry::load(content_root) {
        Ok(reg) => Ok(reg),
        Err(errors) => {
            for err in &errors {
                eprintln!("tags: {err}");
            }
            Err(1)
        }
    }
}

/// Resolve case file paths from path argument.
/// If path is a file, returns just that file.
/// If path is a directory (or None), auto-discovers `cases/**/*.md`.
pub fn resolve_case_files(
    path: Option<&str>,
    content_root: &std::path::Path,
) -> Result<Vec<String>, i32> {
    if let Some(p) = path {
        let p_path = std::path::Path::new(p);
        if p_path.is_file() {
            return Ok(vec![p.to_string()]);
        }
        if !p_path.is_dir() {
            eprintln!("{p}: not a file or directory");
            return Err(2);
        }
    }

    let cases_dir = content_root.join("cases");
    if !cases_dir.is_dir() {
        return Ok(Vec::new());
    }

    let mut files = Vec::new();
    discover_md_files(&cases_dir, &mut files, 0);
    files.sort();
    Ok(files)
}

/// Recursively discover .md files in a directory (max 5 levels deep for cases/country/category/year/).
fn discover_md_files(dir: &std::path::Path, files: &mut Vec<String>, depth: usize) {
    const MAX_DEPTH: usize = 5;
    if depth > MAX_DEPTH {
        return;
    }

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

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

    for entry in entries {
        let path = entry.path();
        if path.is_dir() {
            discover_md_files(&path, files, depth + 1);
        } else if path.extension().and_then(|e| e.to_str()) == Some("md")
            && let Some(s) = path.to_str()
        {
            files.push(s.to_string());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn front_matter_has_id_present() {
        let content = "---\nid: 01JABC000000000000000000AA\n---\n\n# Test\n";
        assert!(front_matter_has_id(content));
    }

    #[test]
    fn front_matter_has_id_absent() {
        let content = "---\n---\n\n# Test\n";
        assert!(!front_matter_has_id(content));
    }

    #[test]
    fn front_matter_has_id_with_other_fields() {
        let content = "---\nother: value\nid: 01JABC000000000000000000AA\n---\n\n# Test\n";
        assert!(front_matter_has_id(content));
    }

    #[test]
    fn front_matter_has_id_no_front_matter() {
        let content = "# Test\n\nNo front matter here.\n";
        assert!(!front_matter_has_id(content));
    }

    #[test]
    fn front_matter_has_id_outside_front_matter() {
        // `id:` appearing in the body should not count
        let content = "---\n---\n\n# Test\n\n- id: some-value\n";
        assert!(!front_matter_has_id(content));
    }
}