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
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! Domain types for the OSINT case graph.
//!
//! These types represent the target data model per ADR-014. They are
//! pure value objects with no infrastructure dependencies.

use std::fmt;

use serde::Serialize;

// ---------------------------------------------------------------------------
// Entity labels
// ---------------------------------------------------------------------------

/// Graph node label — determines which fields are valid on an entity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum EntityLabel {
    Person,
    Organization,
    Event,
    Document,
    Asset,
    Case,
}

impl fmt::Display for EntityLabel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Person => write!(f, "person"),
            Self::Organization => write!(f, "organization"),
            Self::Event => write!(f, "event"),
            Self::Document => write!(f, "document"),
            Self::Asset => write!(f, "asset"),
            Self::Case => write!(f, "case"),
        }
    }
}

// ---------------------------------------------------------------------------
// Person enums
// ---------------------------------------------------------------------------

/// Role a person holds (multiple allowed per person).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Role {
    Politician,
    Executive,
    CivilServant,
    Military,
    Judiciary,
    LawEnforcement,
    Journalist,
    Academic,
    Activist,
    Athlete,
    Lawyer,
    Lobbyist,
    Banker,
    Accountant,
    Consultant,
    /// Free-form value not in the predefined list.
    Custom(String),
}

/// Maximum length of a custom enum value.
const MAX_CUSTOM_LEN: usize = 100;

impl Role {
    /// All known non-custom values as `&str`.
    pub const KNOWN: &[&str] = &[
        "politician",
        "executive",
        "civil_servant",
        "military",
        "judiciary",
        "law_enforcement",
        "journalist",
        "academic",
        "activist",
        "athlete",
        "lawyer",
        "lobbyist",
        "banker",
        "accountant",
        "consultant",
    ];
}

/// Status of a person.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PersonStatus {
    Active,
    Deceased,
    Imprisoned,
    Fugitive,
    Acquitted,
}

impl PersonStatus {
    pub const KNOWN: &[&str] = &["active", "deceased", "imprisoned", "fugitive", "acquitted"];
}

// ---------------------------------------------------------------------------
// Organization enums
// ---------------------------------------------------------------------------

/// Type of organization.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum OrgType {
    GovernmentMinistry,
    GovernmentAgency,
    LocalGovernment,
    Legislature,
    Court,
    LawEnforcement,
    Prosecutor,
    Regulator,
    PoliticalParty,
    StateEnterprise,
    Corporation,
    Bank,
    Ngo,
    Media,
    University,
    SportsClub,
    SportsBody,
    TradeUnion,
    LobbyGroup,
    Military,
    ReligiousBody,
    Custom(String),
}

impl OrgType {
    pub const KNOWN: &[&str] = &[
        "government_ministry",
        "government_agency",
        "local_government",
        "legislature",
        "court",
        "law_enforcement",
        "prosecutor",
        "regulator",
        "political_party",
        "state_enterprise",
        "corporation",
        "bank",
        "ngo",
        "media",
        "university",
        "sports_club",
        "sports_body",
        "trade_union",
        "lobby_group",
        "military",
        "religious_body",
    ];
}

/// Status of an organization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum OrgStatus {
    Active,
    Dissolved,
    Suspended,
    Merged,
}

impl OrgStatus {
    pub const KNOWN: &[&str] = &["active", "dissolved", "suspended", "merged"];
}

// ---------------------------------------------------------------------------
// Event enums
// ---------------------------------------------------------------------------

/// Type of event.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum EventType {
    Arrest,
    Indictment,
    Trial,
    Conviction,
    Acquittal,
    Sentencing,
    Appeal,
    Pardon,
    Parole,
    Bribery,
    Embezzlement,
    Fraud,
    Extortion,
    MoneyLaundering,
    Murder,
    Assault,
    Dismissal,
    Resignation,
    Appointment,
    Election,
    InvestigationOpened,
    InvestigationClosed,
    Raid,
    Seizure,
    Warrant,
    FugitiveFlight,
    FugitiveCapture,
    PolicyChange,
    ContractAward,
    FinancialDefault,
    Bailout,
    WhistleblowerReport,
    Custom(String),
}

impl EventType {
    pub const KNOWN: &[&str] = &[
        "arrest",
        "indictment",
        "trial",
        "conviction",
        "acquittal",
        "sentencing",
        "appeal",
        "pardon",
        "parole",
        "bribery",
        "embezzlement",
        "fraud",
        "extortion",
        "money_laundering",
        "murder",
        "assault",
        "dismissal",
        "resignation",
        "appointment",
        "election",
        "investigation_opened",
        "investigation_closed",
        "raid",
        "seizure",
        "warrant",
        "fugitive_flight",
        "fugitive_capture",
        "policy_change",
        "contract_award",
        "financial_default",
        "bailout",
        "whistleblower_report",
    ];
}

/// Event severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Severity {
    Minor,
    Significant,
    Major,
    Critical,
}

impl Severity {
    pub const KNOWN: &[&str] = &["minor", "significant", "major", "critical"];
}

// ---------------------------------------------------------------------------
// Document enums
// ---------------------------------------------------------------------------

/// Type of document.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DocType {
    CourtRuling,
    Indictment,
    ChargeSheet,
    Warrant,
    Contract,
    Permit,
    AuditReport,
    FinancialDisclosure,
    Legislation,
    Regulation,
    PressRelease,
    InvestigationReport,
    SanctionsNotice,
    Custom(String),
}

impl DocType {
    pub const KNOWN: &[&str] = &[
        "court_ruling",
        "indictment",
        "charge_sheet",
        "warrant",
        "contract",
        "permit",
        "audit_report",
        "financial_disclosure",
        "legislation",
        "regulation",
        "press_release",
        "investigation_report",
        "sanctions_notice",
    ];
}

// ---------------------------------------------------------------------------
// Asset enums
// ---------------------------------------------------------------------------

/// Type of asset.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AssetType {
    Cash,
    BankAccount,
    RealEstate,
    Vehicle,
    Equity,
    ContractValue,
    Grant,
    BudgetAllocation,
    SeizedAsset,
    Custom(String),
}

impl AssetType {
    pub const KNOWN: &[&str] = &[
        "cash",
        "bank_account",
        "real_estate",
        "vehicle",
        "equity",
        "contract_value",
        "grant",
        "budget_allocation",
        "seized_asset",
    ];
}

/// Status of an asset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AssetStatus {
    Active,
    Frozen,
    Seized,
    Forfeited,
    Returned,
}

impl AssetStatus {
    pub const KNOWN: &[&str] = &["active", "frozen", "seized", "forfeited", "returned"];
}

// ---------------------------------------------------------------------------
// Case enums
// ---------------------------------------------------------------------------

/// Type of case.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CaseType {
    Corruption,
    Fraud,
    Bribery,
    Embezzlement,
    Murder,
    CivilRights,
    Regulatory,
    Political,
    Custom(String),
}

impl CaseType {
    pub const KNOWN: &[&str] = &[
        "corruption",
        "fraud",
        "bribery",
        "embezzlement",
        "murder",
        "civil_rights",
        "regulatory",
        "political",
    ];
}

/// Status of a case.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CaseStatus {
    Open,
    UnderInvestigation,
    Trial,
    Convicted,
    Acquitted,
    Closed,
    Appeal,
}

impl CaseStatus {
    pub const KNOWN: &[&str] = &[
        "open",
        "under_investigation",
        "trial",
        "convicted",
        "acquitted",
        "closed",
        "appeal",
    ];
}

// ---------------------------------------------------------------------------
// Structured value types
// ---------------------------------------------------------------------------

/// Monetary amount with currency and human-readable display.
///
/// `amount` is in the smallest currency unit (e.g. cents for USD, sen for IDR).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Money {
    pub amount: i64,
    pub currency: String,
    pub display: String,
}

/// Maximum length of the `currency` field (ISO 4217 = 3 chars).
pub const MAX_CURRENCY_LEN: usize = 3;

/// Maximum length of the `display` field.
pub const MAX_MONEY_DISPLAY_LEN: usize = 100;

/// Geographic jurisdiction: ISO 3166-1 country code with optional subdivision.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Jurisdiction {
    /// ISO 3166-1 alpha-2 country code (e.g. `ID`, `GB`).
    pub country: String,
    /// Optional subdivision name (e.g. `South Sulawesi`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subdivision: Option<String>,
}

/// Maximum length of the `country` field (ISO 3166-1 alpha-2 = 2 chars).
pub const MAX_COUNTRY_LEN: usize = 2;

/// Maximum length of the `subdivision` field.
pub const MAX_SUBDIVISION_LEN: usize = 200;

/// A source of information (news article, official document, etc.).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Source {
    /// HTTPS URL of the source.
    pub url: String,
    /// Extracted domain (e.g. `kompas.com`).
    pub domain: String,
    /// Article or document title.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Publication date (ISO 8601 date string).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub published_at: Option<String>,
    /// Wayback Machine or other archive URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub archived_url: Option<String>,
    /// ISO 639-1 language code (e.g. `id`, `en`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
}

/// Maximum length of a source URL.
pub const MAX_SOURCE_URL_LEN: usize = 2048;

/// Maximum length of a source domain.
pub const MAX_SOURCE_DOMAIN_LEN: usize = 253;

/// Maximum length of a source title.
pub const MAX_SOURCE_TITLE_LEN: usize = 300;

/// Maximum length of a source language code (ISO 639-1 = 2 chars).
pub const MAX_SOURCE_LANGUAGE_LEN: usize = 2;

// ---------------------------------------------------------------------------
// Parsing helpers
// ---------------------------------------------------------------------------

/// Parse a `custom:Value` string. Returns `Some(value)` if the prefix is
/// present and the value is within length limits, `None` otherwise.
pub fn parse_custom(value: &str) -> Option<&str> {
    let custom = value.strip_prefix("custom:")?;
    if custom.is_empty() || custom.len() > MAX_CUSTOM_LEN {
        return None;
    }
    Some(custom)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn entity_label_display() {
        assert_eq!(EntityLabel::Person.to_string(), "person");
        assert_eq!(EntityLabel::Organization.to_string(), "organization");
        assert_eq!(EntityLabel::Event.to_string(), "event");
        assert_eq!(EntityLabel::Document.to_string(), "document");
        assert_eq!(EntityLabel::Asset.to_string(), "asset");
        assert_eq!(EntityLabel::Case.to_string(), "case");
    }

    #[test]
    fn entity_label_serializes_snake_case() {
        let json = serde_json::to_string(&EntityLabel::Organization).unwrap_or_default();
        assert_eq!(json, "\"organization\"");
    }

    #[test]
    fn money_serialization() {
        let m = Money {
            amount: 500_000_000_000,
            currency: "IDR".into(),
            display: "Rp 500 billion".into(),
        };
        let json = serde_json::to_string(&m).unwrap_or_default();
        assert!(json.contains("\"amount\":500000000000"));
        assert!(json.contains("\"currency\":\"IDR\""));
        assert!(json.contains("\"display\":\"Rp 500 billion\""));
    }

    #[test]
    fn jurisdiction_without_subdivision() {
        let j = Jurisdiction {
            country: "ID".into(),
            subdivision: None,
        };
        let json = serde_json::to_string(&j).unwrap_or_default();
        assert!(json.contains("\"country\":\"ID\""));
        assert!(!json.contains("subdivision"));
    }

    #[test]
    fn jurisdiction_with_subdivision() {
        let j = Jurisdiction {
            country: "ID".into(),
            subdivision: Some("South Sulawesi".into()),
        };
        let json = serde_json::to_string(&j).unwrap_or_default();
        assert!(json.contains("\"subdivision\":\"South Sulawesi\""));
    }

    #[test]
    fn source_minimal() {
        let s = Source {
            url: "https://kompas.com/article".into(),
            domain: "kompas.com".into(),
            title: None,
            published_at: None,
            archived_url: None,
            language: None,
        };
        let json = serde_json::to_string(&s).unwrap_or_default();
        assert!(json.contains("\"domain\":\"kompas.com\""));
        assert!(!json.contains("title"));
        assert!(!json.contains("language"));
    }

    #[test]
    fn source_full() {
        let s = Source {
            url: "https://kompas.com/article".into(),
            domain: "kompas.com".into(),
            title: Some("Breaking news".into()),
            published_at: Some("2024-01-15".into()),
            archived_url: Some(
                "https://web.archive.org/web/2024/https://kompas.com/article".into(),
            ),
            language: Some("id".into()),
        };
        let json = serde_json::to_string(&s).unwrap_or_default();
        assert!(json.contains("\"title\":\"Breaking news\""));
        assert!(json.contains("\"language\":\"id\""));
    }

    #[test]
    fn parse_custom_valid() {
        assert_eq!(parse_custom("custom:Kit Manager"), Some("Kit Manager"));
    }

    #[test]
    fn parse_custom_empty() {
        assert_eq!(parse_custom("custom:"), None);
    }

    #[test]
    fn parse_custom_too_long() {
        let long = format!("custom:{}", "a".repeat(101));
        assert_eq!(parse_custom(&long), None);
    }

    #[test]
    fn parse_custom_no_prefix() {
        assert_eq!(parse_custom("politician"), None);
    }

    #[test]
    fn role_known_values_count() {
        assert_eq!(Role::KNOWN.len(), 15);
    }

    #[test]
    fn event_type_known_values_count() {
        assert_eq!(EventType::KNOWN.len(), 32);
    }

    #[test]
    fn org_type_known_values_count() {
        assert_eq!(OrgType::KNOWN.len(), 21);
    }

    #[test]
    fn severity_known_values_count() {
        assert_eq!(Severity::KNOWN.len(), 4);
    }
}