graphrt-core 0.9.0

Executor-agnostic graph runtime for agentic AI workflows: graph model, variable pool, scheduler, events, snapshots and built-in control nodes.
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
//! Text rules: checks the written text of a value (a model's answer, a report,
//! the payload a workflow is about to send) against rules a workflow gives.
//!
//! - **Forbid**: a phrase, a regular expression or a built-in detector (`email`,
//!   `phone`) must not appear. A rule may name a `replace` text, applied by
//!   [`fix`].
//! - **Require**: a field must state a given text ("12.5%", a product name).
//! - **Paragraphs**: a field must have a given number of paragraphs (the items of
//!   a list, or the blank-line separated blocks of a text).
//!
//! The text of a value is every string and number in it, each with the path of
//! its field (`summary`, `stores[2].note`), the paths the `grounding` checks of
//! the `llm` node report too. [`Issue`]s name the field, the rule and a message a
//! person or a revising model can act on, and [`notes`] lists them one per line.
//!
//! Used by the `text-check` node (feature `text-check`).

use std::fmt;

use indexmap::IndexMap;
use regex::{Regex, RegexBuilder};
use serde::Deserialize;

use crate::node::NodeError;
use crate::pool::{Selector, VariablePool};
use crate::value::Value;

/// Upper bound on the compiled size of one pattern.
const PATTERN_SIZE_LIMIT: usize = 1 << 20;
/// Most issues one check reports: a text full of one forbidden mark does not
/// produce an unbounded list.
pub const MAX_ISSUES: usize = 200;
/// Longest `found` text an issue carries.
const FOUND_CHARS: usize = 160;

/// Email addresses (`name@example.com`).
const EMAIL: &str = r"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}";
/// Phone numbers written in international form, with a leading `+` and 8 to 15
/// digits, spaces, dots, dashes and brackets allowed between them
/// (`+62 812-3456-7890`, `+1 (415) 555 0100`).
const PHONE: &str = r"\+\d(?:[ .\-]?\(?\d\)?){7,14}";

/// A rule that the text breaks.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Issue {
    /// Path of the field (`summary`, `items[2].note`), empty when the issue has none.
    pub field: String,
    /// Name of the rule.
    pub rule: String,
    /// What is wrong, for a person or a revising model.
    pub message: String,
    /// The text that broke the rule, when the rule shows it.
    pub found: Option<String>,
}

impl Issue {
    /// `{field, rule, message, found}` (`found` only when there is one).
    pub fn to_value(&self) -> Value {
        let mut entries = vec![
            ("field", Value::from(self.field.as_str())),
            ("rule", Value::from(self.rule.as_str())),
            ("message", Value::from(self.message.as_str())),
        ];
        if let Some(found) = &self.found {
            entries.push(("found", Value::from(found.as_str())));
        }
        Value::object(entries)
    }
}

impl fmt::Display for Issue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if !self.field.is_empty() {
            write!(f, "{}: ", self.field)?;
        }
        f.write_str(&self.message)?;
        if let Some(found) = &self.found {
            write!(f, " (\"{found}\")")?;
        }
        Ok(())
    }
}

/// The issues, one per line (`- field: message ("found")`), for a prompt or a report.
pub fn notes(issues: &[Issue]) -> String {
    issues.iter().map(|issue| format!("- {issue}")).collect::<Vec<_>>().join("\n")
}

/// A rule that is written wrong.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub struct RuleError(pub String);

/// A built-in detector of a `forbid` rule.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Detector {
    /// Email addresses.
    Email,
    /// Phone numbers in international form (a leading `+`).
    Phone,
}

impl Detector {
    fn name(self) -> &'static str {
        match self {
            Detector::Email => "email",
            Detector::Phone => "phone",
        }
    }

    fn pattern(self) -> &'static str {
        match self {
            Detector::Email => EMAIL,
            Detector::Phone => PHONE,
        }
    }

    fn message(self) -> &'static str {
        match self {
            Detector::Email => "contains an email address",
            Detector::Phone => "contains a phone number",
        }
    }
}

/// A `forbid` rule as a workflow writes it: exactly one of `text`, `pattern`
/// and `detect`.
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ForbidSpec {
    /// Name of the rule in the issues (default: the detector, else `forbid`).
    #[serde(default)]
    pub name: Option<String>,
    /// A phrase: matched in any case, with any run of spaces between its words,
    /// as whole words when it starts or ends with a letter or digit.
    #[serde(default)]
    pub text: Option<String>,
    /// A regular expression (Rust `regex` syntax: no look-around; `(?i)` for any case).
    #[serde(default)]
    pub pattern: Option<String>,
    /// A built-in detector.
    #[serde(default)]
    pub detect: Option<Detector>,
    /// The message of its issues.
    #[serde(default)]
    pub message: Option<String>,
    /// Fields the rule applies to (default: every field). A field covers the
    /// fields inside it, and `[*]` stands for any index.
    #[serde(default)]
    pub fields: Vec<String>,
    /// What [`fix`] writes instead of a match (`$1` for a group of the pattern).
    #[serde(default)]
    pub replace: Option<String>,
    /// Leave the matched text out of the issues (default: on for detectors).
    #[serde(default)]
    pub redact: Option<bool>,
}

impl ForbidSpec {
    /// Compiles the rule.
    pub fn compile(&self) -> Result<Forbid, RuleError> {
        let (pattern, name, message) = match (&self.text, &self.pattern, self.detect) {
            (Some(text), None, None) => {
                if text.trim().is_empty() {
                    return Err(RuleError("a forbid `text` must not be empty".into()));
                }
                (phrase_pattern(text), "forbid".to_owned(), format!("remove \"{}\"", text.trim()))
            }
            (None, Some(pattern), None) => {
                if pattern.is_empty() {
                    return Err(RuleError("a forbid `pattern` must not be empty".into()));
                }
                (pattern.clone(), "forbid".to_owned(), "matches a forbidden pattern".to_owned())
            }
            (None, None, Some(detector)) => {
                (detector.pattern().to_owned(), detector.name().to_owned(), detector.message().to_owned())
            }
            _ => return Err(RuleError("a forbid rule needs exactly one of `text`, `pattern` and `detect`".into())),
        };
        let regex = RegexBuilder::new(&pattern)
            .size_limit(PATTERN_SIZE_LIMIT)
            .build()
            .map_err(|e| RuleError(format!("forbid pattern `{pattern}`: {e}")))?;
        for field in &self.fields {
            check_field_pattern(field)?;
        }
        Ok(Forbid {
            name: self.name.clone().filter(|name| !name.trim().is_empty()).unwrap_or(name),
            regex,
            message: self.message.clone().filter(|message| !message.trim().is_empty()).unwrap_or(message),
            fields: self.fields.clone(),
            replace: self.replace.clone(),
            redact: self.redact.unwrap_or(self.detect.is_some()),
        })
    }
}

/// A compiled `forbid` rule.
#[derive(Clone, Debug)]
pub struct Forbid {
    name: String,
    regex: Regex,
    message: String,
    fields: Vec<String>,
    replace: Option<String>,
    redact: bool,
}

impl Forbid {
    fn applies_to(&self, field: &str) -> bool {
        self.fields.is_empty() || self.fields.iter().any(|pattern| covers(pattern, field))
    }
}

/// A `require` rule: the field states `text`, as written.
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Require {
    /// The field (it covers the fields inside it: the text of a list is all its items).
    pub field: String,
    /// The text the field must contain.
    pub text: String,
    /// The message of its issue (default: `must state "<text>"`).
    #[serde(default)]
    pub message: Option<String>,
}

/// Every rule of one check.
#[derive(Clone, Debug, Default)]
pub struct Rules {
    /// Texts that must not appear.
    pub forbid: Vec<Forbid>,
    /// Texts that must appear.
    pub require: Vec<Require>,
    /// The number of paragraphs per field.
    pub paragraphs: IndexMap<String, usize>,
    /// A field whose whole text is one of these (`N/A`) is not held to `require`
    /// and `paragraphs`.
    pub ignore: Vec<String>,
}

/// The texts of a value: `(field, text)` for every string and number, and the
/// number of items of every list.
#[derive(Clone, Debug, Default)]
pub struct Texts {
    leaves: Vec<(String, String)>,
    lists: IndexMap<String, usize>,
}

impl Texts {
    /// The texts of `value`, with field paths under `prefix` (`""` for none). A
    /// value that is a string itself is the field `prefix`, or `text` without one.
    pub fn of(value: &Value, prefix: &str) -> Self {
        let mut texts = Texts::default();
        texts.add(value, prefix);
        texts
    }

    /// Adds the texts of `value` under `prefix`.
    pub fn add(&mut self, value: &Value, prefix: &str) {
        let root =
            if prefix.is_empty() && !matches!(value, Value::Object(_) | Value::Array(_)) { "text" } else { prefix };
        self.walk(value, root.to_owned());
    }

    fn walk(&mut self, value: &Value, path: String) {
        match value {
            Value::String(text) => self.leaves.push((path, text.to_string())),
            Value::Int(_) | Value::Float(_) => self.leaves.push((path, value.to_text())),
            Value::Array(items) => {
                for (index, item) in items.iter().enumerate() {
                    self.walk(item, format!("{path}[{index}]"));
                }
                self.lists.insert(path, items.len());
            }
            Value::Object(map) => {
                for (key, item) in map.iter() {
                    let child = if path.is_empty() { key.clone() } else { format!("{path}.{key}") };
                    self.walk(item, child);
                }
            }
            // Secrets are masked, files and flags hold no written text.
            Value::Null | Value::Bool(_) | Value::Secret(_) | Value::File(_) => {}
        }
    }

    /// The text of every field `field` covers, one per line, or `None` when it covers none.
    fn joined(&self, field: &str) -> Option<String> {
        let parts: Vec<&str> =
            self.leaves.iter().filter(|(path, _)| covers(field, path)).map(|(_, text)| text.as_str()).collect();
        if parts.is_empty() { None } else { Some(parts.join("\n")) }
    }

    /// The number of paragraphs of `field`: the items of a list, else the blank
    /// line separated blocks of its text. `None` when the value has no such field.
    fn paragraphs(&self, field: &str) -> Option<usize> {
        if let Some(count) = self.lists.get(field) {
            return Some(*count);
        }
        let (_, text) = self.leaves.iter().find(|(path, _)| path == field)?;
        Some(paragraph_count(text))
    }
}

fn paragraph_count(text: &str) -> usize {
    let mut count = 0;
    let mut in_paragraph = false;
    for line in text.lines() {
        if line.trim().is_empty() {
            in_paragraph = false;
        } else if !in_paragraph {
            in_paragraph = true;
            count += 1;
        }
    }
    count
}

/// Checks `texts` against `rules`. At most [`MAX_ISSUES`] issues are returned.
pub fn check(texts: &Texts, rules: &Rules) -> Vec<Issue> {
    let mut issues = Vec::new();
    for rule in &rules.forbid {
        for (field, text) in texts.leaves.iter().filter(|(field, _)| rule.applies_to(field)) {
            for found in rule.regex.find_iter(text) {
                if issues.len() >= MAX_ISSUES {
                    return issues;
                }
                issues.push(Issue {
                    field: field.clone(),
                    rule: rule.name.clone(),
                    message: rule.message.clone(),
                    found: (!rule.redact).then(|| shorten(found.as_str())),
                });
            }
        }
    }
    let ignored = |text: &str| rules.ignore.iter().any(|ignore| ignore.trim() == text.trim());
    for rule in &rules.require {
        let Some(text) = texts.joined(&rule.field) else { continue };
        if ignored(&text) || text.contains(rule.text.as_str()) {
            continue;
        }
        if issues.len() >= MAX_ISSUES {
            return issues;
        }
        issues.push(Issue {
            field: rule.field.clone(),
            rule: "require".into(),
            message: rule.message.clone().unwrap_or_else(|| format!("must state \"{}\"", rule.text)),
            found: None,
        });
    }
    for (field, expected) in &rules.paragraphs {
        let Some(count) = texts.paragraphs(field) else { continue };
        if count == *expected || texts.joined(field).is_some_and(|text| ignored(&text)) {
            continue;
        }
        if issues.len() >= MAX_ISSUES {
            return issues;
        }
        issues.push(Issue {
            field: field.clone(),
            rule: "paragraphs".into(),
            message: format!(
                "write exactly {expected} paragraph{}, not {count}",
                if *expected == 1 { "" } else { "s" }
            ),
            found: None,
        });
    }
    issues
}

/// `value` with the `replace` of every `forbid` rule applied to the strings of
/// the fields it covers. `prefix` is the path of `value` as in [`Texts::of`].
pub fn fix(value: &Value, prefix: &str, forbid: &[Forbid]) -> Value {
    if !forbid.iter().any(|rule| rule.replace.is_some()) {
        return value.clone();
    }
    let root = if prefix.is_empty() && !matches!(value, Value::Object(_) | Value::Array(_)) { "text" } else { prefix };
    fix_at(value, root, forbid)
}

fn fix_at(value: &Value, path: &str, forbid: &[Forbid]) -> Value {
    match value {
        Value::String(text) => {
            let mut fixed = text.to_string();
            for rule in forbid.iter().filter(|rule| rule.applies_to(path)) {
                if let Some(replace) = &rule.replace {
                    fixed = rule.regex.replace_all(&fixed, replace.as_str()).into_owned();
                }
            }
            Value::from(fixed)
        }
        Value::Array(items) => Value::array(
            items.iter().enumerate().map(|(index, item)| fix_at(item, &format!("{path}[{index}]"), forbid)),
        ),
        Value::Object(map) => Value::object(map.iter().map(|(key, item)| {
            let child = if path.is_empty() { key.clone() } else { format!("{path}.{key}") };
            let fixed = fix_at(item, &child, forbid);
            (key.clone(), fixed)
        })),
        other => other.clone(),
    }
}

/// Issues another check found, such as the `unsupported` items of the
/// `grounding` of an `llm` node (`{field, number, sentence, reason, named,
/// owners}`), or the `issues` of another `text-check`. Null is none.
pub fn issues_from(value: &Value) -> Result<Vec<Issue>, RuleError> {
    let items = match value {
        Value::Null => return Ok(Vec::new()),
        Value::Array(items) => items,
        other => return Err(RuleError(format!("issues must be a list, got {}", other.type_name()))),
    };
    let mut issues = Vec::with_capacity(items.len());
    for item in items.iter() {
        let Some(map) = item.as_object() else {
            issues.push(Issue { field: String::new(), rule: "issue".into(), message: item.to_text(), found: None });
            continue;
        };
        let text = |key: &str| map.get(key).map(Value::to_text).filter(|text| !text.trim().is_empty());
        let reason = text("rule").or_else(|| text("reason")).unwrap_or_else(|| "issue".to_owned());
        let number = text("number");
        let message = match (text("message"), reason.as_str(), &number) {
            (Some(message), _, _) => message,
            (None, "attribution", Some(number)) => {
                let owners = match map.get("owners") {
                    Some(Value::Array(owners)) => owners.iter().map(Value::to_text).collect::<Vec<_>>().join(" / "),
                    _ => "another entity".to_owned(),
                };
                let named = text("named").unwrap_or_else(|| "the entity named next to it".to_owned());
                format!("{number} belongs to {owners}, not {named}")
            }
            (None, _, Some(number)) => format!("{number} is not in the facts"),
            (None, _, None) => reason.clone(),
        };
        let found = text("found").or_else(|| text("sentence")).map(|found| shorten(&found));
        issues.push(Issue { field: text("field").unwrap_or_default(), rule: reason, message, found });
    }
    Ok(issues)
}

/// The rules of a check as a workflow writes them: `forbid`, `require` and
/// `paragraphs`, each inline or a selector of a value an earlier node computed,
/// and `ignore`. Used by the `text-check` node and by `revise.checks` of the
/// `llm` node.
#[derive(Clone, Debug, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RulesConfig {
    #[serde(default)]
    pub forbid: Option<serde_json::Value>,
    #[serde(default)]
    pub require: Option<serde_json::Value>,
    #[serde(default)]
    pub paragraphs: Option<serde_json::Value>,
    #[serde(default)]
    pub ignore: Vec<String>,
}

/// Rules given in the document, or a selector of rules an earlier node computed.
#[derive(Clone, Debug)]
enum Given<T> {
    Inline(T),
    From(Selector),
}

impl<T: Clone> Given<T> {
    /// A selector is a list of strings or a dotted string, anything else is the rules themselves.
    fn parse<F>(value: &serde_json::Value, parse: F) -> Result<Self, RuleError>
    where
        F: FnOnce(&serde_json::Value) -> Result<T, RuleError>,
    {
        let is_selector = match value {
            serde_json::Value::String(_) => true,
            serde_json::Value::Array(items) => !items.is_empty() && items.iter().all(serde_json::Value::is_string),
            _ => false,
        };
        if is_selector {
            return serde_json::from_value::<Selector>(value.clone())
                .map(Given::From)
                .map_err(|e| RuleError(e.to_string()));
        }
        parse(value).map(Given::Inline)
    }

    fn selector(&self) -> Option<&Selector> {
        match self {
            Given::From(selector) => Some(selector),
            Given::Inline(_) => None,
        }
    }

    /// The rules: inline ones, or the value of the selector read with `parse` (null is `empty`).
    fn resolve<F>(&self, pool: &VariablePool, empty: T, parse: F) -> Result<T, NodeError>
    where
        F: FnOnce(&serde_json::Value) -> Result<T, RuleError>,
    {
        match self {
            Given::Inline(rules) => Ok(rules.clone()),
            Given::From(selector) => match pool.get_or_null(selector) {
                Value::Null => Ok(empty),
                value => parse(&value.to_json()).map_err(|e| NodeError::invalid_input(format!("`{selector}`: {e}"))),
            },
        }
    }
}

/// [`RulesConfig`] parsed: inline rules compiled, selectors kept for the run.
#[derive(Clone, Debug, Default)]
pub struct RuleSources {
    forbid: Option<Given<Vec<Forbid>>>,
    require: Option<Given<Vec<Require>>>,
    paragraphs: Option<Given<IndexMap<String, usize>>>,
    ignore: Vec<String>,
}

impl RuleSources {
    /// Parses the rules. An error names the field it is about (`forbid`, `require`, `paragraphs`).
    pub fn parse(config: &RulesConfig) -> Result<Self, (&'static str, RuleError)> {
        let forbid = config
            .forbid
            .as_ref()
            .map(|value| Given::parse(value, parse_forbid))
            .transpose()
            .map_err(|e| ("forbid", e))?;
        let require = config
            .require
            .as_ref()
            .map(|value| Given::parse(value, parse_require))
            .transpose()
            .map_err(|e| ("require", e))?;
        let paragraphs = config
            .paragraphs
            .as_ref()
            .map(|value| Given::parse(value, parse_paragraphs))
            .transpose()
            .map_err(|e| ("paragraphs", e))?;
        Ok(Self { forbid, require, paragraphs, ignore: config.ignore.clone() })
    }

    /// Whether no rule is given.
    pub fn is_empty(&self) -> bool {
        self.forbid.is_none() && self.require.is_none() && self.paragraphs.is_none()
    }

    /// The rules for a run: computed rules are read from `pool`, a missing value is no rules.
    pub fn resolve(&self, pool: &VariablePool) -> Result<Rules, NodeError> {
        let forbid = match &self.forbid {
            Some(given) => given.resolve(pool, Vec::new(), parse_forbid)?,
            None => Vec::new(),
        };
        let require = match &self.require {
            Some(given) => given.resolve(pool, Vec::new(), parse_require)?,
            None => Vec::new(),
        };
        let paragraphs = match &self.paragraphs {
            Some(given) => given.resolve(pool, IndexMap::new(), parse_paragraphs)?,
            None => IndexMap::new(),
        };
        Ok(Rules { forbid, require, paragraphs, ignore: self.ignore.clone() })
    }

    /// The selectors of computed rules.
    pub fn selectors(&self) -> Vec<Selector> {
        let mut out = Vec::new();
        out.extend(self.forbid.as_ref().and_then(Given::selector).cloned());
        out.extend(self.require.as_ref().and_then(Given::selector).cloned());
        out.extend(self.paragraphs.as_ref().and_then(Given::selector).cloned());
        out
    }
}

/// Rules are objects: serde would also read a list (`["a", "b"]`) as one.
fn objects(value: &serde_json::Value, what: &str) -> Result<(), RuleError> {
    match value {
        serde_json::Value::Array(items) if items.iter().all(serde_json::Value::is_object) => Ok(()),
        _ => Err(RuleError(format!("{what} must be a list of rules (objects)"))),
    }
}

fn parse_forbid(value: &serde_json::Value) -> Result<Vec<Forbid>, RuleError> {
    objects(value, "forbid")?;
    let specs: Vec<ForbidSpec> =
        serde_json::from_value(value.clone()).map_err(|e| RuleError(format!("forbid must be a list of rules: {e}")))?;
    specs.iter().map(ForbidSpec::compile).collect()
}

fn parse_require(value: &serde_json::Value) -> Result<Vec<Require>, RuleError> {
    objects(value, "require")?;
    let rules: Vec<Require> = serde_json::from_value(value.clone())
        .map_err(|e| RuleError(format!("require must be a list of `{{field, text}}`: {e}")))?;
    for rule in &rules {
        check_field_pattern(&rule.field)?;
        if rule.text.is_empty() {
            return Err(RuleError(format!("require of `{}`: `text` must not be empty", rule.field)));
        }
    }
    Ok(rules)
}

fn parse_paragraphs(value: &serde_json::Value) -> Result<IndexMap<String, usize>, RuleError> {
    let counts: IndexMap<String, usize> = serde_json::from_value(value.clone())
        .map_err(|e| RuleError(format!("paragraphs must map fields to counts: {e}")))?;
    for field in counts.keys() {
        check_field_pattern(field)?;
    }
    Ok(counts)
}

/// JSON Schema properties of [`RulesConfig`] (`forbid`, `require`, `paragraphs`, `ignore`).
pub fn rules_schema() -> serde_json::Value {
    use serde_json::json;

    use crate::catalog::schema::selector;

    let field = json!({ "type": "string", "minLength": 1, "description": "Field path (`summary`, `items[*].note`); it covers the fields inside it" });
    let forbid_rule = json!({
        "type": "object",
        "properties": {
            "name": { "type": "string", "description": "Name of the rule in the issues" },
            "text": { "type": "string", "minLength": 1, "description": "A phrase: any case, any spacing, whole words" },
            "pattern": { "type": "string", "minLength": 1, "description": "A regular expression (no look-around; `(?i)` for any case)" },
            "detect": { "type": "string", "enum": ["email", "phone"], "description": "A built-in detector" },
            "message": { "type": "string", "description": "The message of its issues" },
            "fields": { "type": "array", "items": field.clone(), "description": "Fields the rule applies to (default: all)" },
            "replace": { "type": "string", "description": "What `fixed` writes instead of a match (`$1` for a group)" },
            "redact": { "type": "boolean", "description": "Leave the matched text out of the issues (default: on for detectors)" }
        },
        "additionalProperties": false
    });
    let require_rule = json!({
        "type": "object",
        "properties": {
            "field": field.clone(),
            "text": { "type": "string", "minLength": 1, "description": "The text the field must contain, as written" },
            "message": { "type": "string" }
        },
        "required": ["field", "text"],
        "additionalProperties": false
    });
    let or_selector = |inline: serde_json::Value, description: &str| json!({ "description": description, "anyOf": [inline, selector()] });
    json!({
        "forbid": or_selector(json!({ "type": "array", "items": forbid_rule }), "Texts that must not appear, or a selector of such rules"),
        "require": or_selector(json!({ "type": "array", "items": require_rule }), "Texts a field must state, or a selector of such rules"),
        "paragraphs": or_selector(
            json!({ "type": "object", "additionalProperties": { "type": "integer", "minimum": 0 } }),
            "Paragraphs per field (`{field: count}`), or a selector of such an object"
        ),
        "ignore": { "type": "array", "items": { "type": "string" }, "description": "Whole texts (`N/A`) that `require` and `paragraphs` skip" }
    })
}

/// A field pattern is a path (`summary`, `items[2].note`, `items[*].note`).
pub fn check_field_pattern(pattern: &str) -> Result<(), RuleError> {
    if pattern.trim().is_empty() {
        return Err(RuleError("a field must not be empty".into()));
    }
    Ok(())
}

/// Whether the field `pattern` covers `field`: the same path, or a field inside
/// it (`notes` covers `notes[2]` and `notes.title`), with `[*]` for any index.
pub fn covers(pattern: &str, field: &str) -> bool {
    let (mut pattern, mut field) = (pattern, field);
    while let Some(next) = pattern.chars().next() {
        if let Some(rest) = pattern.strip_prefix("[*]") {
            let Some(index) = field.strip_prefix('[') else { return false };
            let digits = index.bytes().take_while(u8::is_ascii_digit).count();
            let Some(after) = index.get(digits..).and_then(|after| after.strip_prefix(']')) else { return false };
            if digits == 0 {
                return false;
            }
            (pattern, field) = (rest, after);
        } else {
            let Some(after) = field.strip_prefix(next) else { return false };
            (pattern, field) = (pattern.get(next.len_utf8()..).unwrap_or_default(), after);
        }
    }
    field.is_empty() || field.starts_with('.') || field.starts_with('[')
}

/// A phrase as a pattern: any case, any run of spaces between words, whole
/// words where it starts or ends with a word character.
fn phrase_pattern(text: &str) -> String {
    let text = text.trim();
    let words: Vec<String> = text.split_whitespace().map(regex::escape).collect();
    let mut pattern = String::from("(?i)");
    let is_word = |c: Option<char>| c.is_some_and(|c| c.is_alphanumeric() || c == '_');
    if is_word(text.chars().next()) {
        pattern.push_str(r"\b");
    }
    pattern.push_str(&words.join(r"\s+"));
    if is_word(text.chars().last()) {
        pattern.push_str(r"\b");
    }
    pattern
}

fn shorten(text: &str) -> String {
    let text = text.trim();
    match text.char_indices().nth(FOUND_CHARS).and_then(|(cut, _)| text.get(..cut)) {
        Some(head) => format!("{head}…"),
        None => text.to_owned(),
    }
}

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

    fn json(value: serde_json::Value) -> Value {
        Value::from_json(value)
    }

    fn forbid(spec: serde_json::Value) -> Forbid {
        serde_json::from_value::<ForbidSpec>(spec).unwrap().compile().unwrap()
    }

    fn rules_with_forbid(specs: Vec<serde_json::Value>) -> Rules {
        Rules { forbid: specs.into_iter().map(forbid).collect(), ..Rules::default() }
    }

    #[test]
    fn fields_cover_the_fields_inside_them() {
        assert!(covers("notes", "notes"));
        assert!(covers("notes", "notes[2]"));
        assert!(covers("notes", "notes.title"));
        assert!(!covers("notes", "notes_extra"));
        assert!(covers("stores[*].note", "stores[12].note"));
        assert!(!covers("stores[*].note", "stores.note"));
        assert!(covers("stores[1]", "stores[1].note"));
        assert!(!covers("stores[1]", "stores[10].note"));
    }

    #[test]
    fn texts_have_field_paths_and_list_counts() {
        let texts = Texts::of(&json(serde_json::json!({"a": ["x", "y"], "b": {"c": 12.5, "d": true}})), "");
        assert_eq!(
            texts.leaves,
            vec![("a[0]".into(), "x".into()), ("a[1]".into(), "y".into()), ("b.c".into(), "12.5".into())]
        );
        assert_eq!(texts.lists.get("a"), Some(&2));
        assert_eq!(Texts::of(&Value::from("plain"), "").leaves, vec![("text".into(), "plain".into())]);
        assert_eq!(Texts::of(&Value::from("plain"), "draft.text").leaves[0].0, "draft.text");
    }

    #[test]
    fn a_phrase_matches_in_any_case_and_spacing_as_whole_words() {
        let rules = rules_with_forbid(vec![serde_json::json!({"text": "Spring  Sale", "message": "not running"})]);
        let texts = Texts::of(
            &json(serde_json::json!({"a": "The spring sale ended.", "b": "Springsale", "c": "SPRING\nSALE!"})),
            "",
        );
        let issues = check(&texts, &rules);
        assert_eq!(issues.iter().map(|i| i.field.as_str()).collect::<Vec<_>>(), vec!["a", "c"]);
        assert_eq!(issues[0].message, "not running");
        assert_eq!(issues[0].found.as_deref(), Some("spring sale"));
    }

    #[test]
    fn a_mark_is_found_wherever_it_stands() {
        let rules = rules_with_forbid(vec![serde_json::json!({"name": "semicolon", "text": ";", "replace": "."})]);
        let value = json(serde_json::json!({"a": "One; two;three"}));
        let issues = check(&Texts::of(&value, ""), &rules);
        assert_eq!(issues.len(), 2);
        assert_eq!(issues[0].rule, "semicolon");
        assert_eq!(issues[0].message, "remove \";\"");
        assert_eq!(fix(&value, "", &rules.forbid).to_json(), serde_json::json!({"a": "One. two.three"}));
    }

    #[test]
    fn a_pattern_may_be_limited_to_fields_and_fixed_with_groups() {
        let rules = rules_with_forbid(vec![serde_json::json!({
            "pattern": r"(?i)\b(fell|declined)\s+(by\s+)?-(\d)",
            "message": "no minus after a falling verb",
            "fields": ["notes[*]"],
            "replace": "$1 $2$3"
        })]);
        let value = json(serde_json::json!({"notes": ["Sales fell by -5%."], "title": "Sales fell -5%"}));
        let issues = check(&Texts::of(&value, ""), &rules);
        assert_eq!(issues.len(), 1);
        assert_eq!(issues[0].field, "notes[0]");
        assert_eq!(issues[0].found.as_deref(), Some("fell by -5"));
        let fixed = fix(&value, "", &rules.forbid).to_json();
        assert_eq!(fixed, serde_json::json!({"notes": ["Sales fell by 5%."], "title": "Sales fell -5%"}));
    }

    #[test]
    fn detectors_find_contacts_and_hide_them() {
        let rules =
            rules_with_forbid(vec![serde_json::json!({"detect": "email"}), serde_json::json!({"detect": "phone"})]);
        let value = json(serde_json::json!({
            "rows": [{"note": "write to jane.doe@example.co.uk"}, {"note": "call +62 812-3456-7890"}],
            "fine": "growth of +12.5% in 2026-10, 1,234,567 visits, version 1.2.3"
        }));
        let issues = check(&Texts::of(&value, ""), &rules);
        assert_eq!(issues.len(), 2, "{issues:?}");
        assert_eq!((issues[0].rule.as_str(), issues[0].field.as_str()), ("email", "rows[0].note"));
        assert_eq!((issues[1].rule.as_str(), issues[1].field.as_str()), ("phone", "rows[1].note"));
        assert!(issues.iter().all(|issue| issue.found.is_none()));
        assert_eq!(issues[0].to_string(), "rows[0].note: contains an email address");
    }

    #[test]
    fn numbers_are_text_too() {
        let rules = rules_with_forbid(vec![serde_json::json!({"name": "id", "pattern": r"^\d{12,}$"})]);
        let issues = check(&Texts::of(&json(serde_json::json!({"id": 6281234567890_i64})), ""), &rules);
        assert_eq!(issues.len(), 1);
    }

    #[test]
    fn wrong_rules_are_refused() {
        let compile = |spec: serde_json::Value| serde_json::from_value::<ForbidSpec>(spec).unwrap().compile();
        assert!(compile(serde_json::json!({})).is_err());
        assert!(compile(serde_json::json!({"text": ";", "pattern": ";"})).is_err());
        assert!(compile(serde_json::json!({"text": "  "})).is_err());
        let error = compile(serde_json::json!({"pattern": "(?<!x)y"})).unwrap_err();
        assert!(error.0.contains("forbid pattern"), "{error}");
        assert!(serde_json::from_value::<ForbidSpec>(serde_json::json!({"txt": ";"})).is_err());
    }

    #[test]
    fn required_texts_are_looked_for_in_the_whole_field() {
        let rules = Rules {
            require: vec![
                Require { field: "notes".into(), text: "12.5%".into(), message: None },
                Require { field: "notes".into(), text: "Spring".into(), message: Some("name the campaign".into()) },
                Require { field: "missing".into(), text: "x".into(), message: None },
                Require { field: "empty".into(), text: "x".into(), message: None },
            ],
            ignore: vec!["N/A".into()],
            ..Rules::default()
        };
        let value = json(serde_json::json!({"notes": ["Sales rose.", "Up 12.5% on May."], "empty": " N/A "}));
        let issues = check(&Texts::of(&value, ""), &rules);
        assert_eq!(issues.len(), 1, "{issues:?}");
        assert_eq!(issues[0].to_string(), "notes: name the campaign");
    }

    #[test]
    fn paragraphs_count_list_items_or_text_blocks() {
        let rules = Rules {
            paragraphs: IndexMap::from([("list".into(), 2), ("text".into(), 2), ("one".into(), 1), ("na".into(), 3)]),
            ignore: vec!["N/A".into()],
            ..Rules::default()
        };
        let value = json(serde_json::json!({
            "list": ["a", "b", "c"], "text": "First.\n\n\nSecond\nstill second.", "one": "a\n\nb", "na": ["N/A"]
        }));
        let issues = check(&Texts::of(&value, ""), &rules);
        assert_eq!(
            notes(&issues),
            "- list: write exactly 2 paragraphs, not 3\n- one: write exactly 1 paragraph, not 2"
        );
    }

    #[test]
    fn issues_of_other_checks_read_as_notes() {
        let unsupported = json(serde_json::json!([
            {"field": "summary", "number": "31%", "sentence": "Toys took 31%.", "reason": "attribution",
             "named": "Toys", "owners": ["Electronics"]},
            {"field": "notes[1]", "number": "48", "sentence": "We sold 48.", "reason": "value"},
            {"field": "x", "rule": "custom", "message": "say it plainly"},
            "free text"
        ]));
        let issues = issues_from(&unsupported).unwrap();
        assert_eq!(
            notes(&issues),
            "- summary: 31% belongs to Electronics, not Toys (\"Toys took 31%.\")\n\
             - notes[1]: 48 is not in the facts (\"We sold 48.\")\n\
             - x: say it plainly\n\
             - free text"
        );
        assert!(issues_from(&Value::Null).unwrap().is_empty());
        assert!(issues_from(&Value::from("x")).is_err());
    }

    #[test]
    fn issues_are_capped() {
        let rules = rules_with_forbid(vec![serde_json::json!({"text": ";"})]);
        let issues = check(&Texts::of(&Value::from(";".repeat(MAX_ISSUES + 50)), ""), &rules);
        assert_eq!(issues.len(), MAX_ISSUES);
    }
}