policyai 0.3.0

PolicyAI provides a mechanism for unstructured, composable policies that transform unstructured text into structured outputs.
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
use crate::{number_is_equal, t64, OnConflict, Report};

///////////////////////////////////////////// BoolMask /////////////////////////////////////////////

/// Represents a boolean field mask for policy application.
///
/// A BoolMask handles the extraction and conflict resolution of boolean values
/// from unstructured data based on policy rules.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct BoolMask {
    /// Index of the policy this mask belongs to
    pub policy_index: usize,
    /// Original field name from the policy definition
    pub name: String,
    /// Masked field name unlikely to be in LLM training data
    pub mask: String,
    /// Default value when the field is not present
    pub default: bool,
    /// Expected boolean value that activates this policy rule
    pub is_true: bool,
    /// Strategy for resolving conflicts when multiple policies set different values
    pub on_conflict: OnConflict,
}

impl BoolMask {
    /// Create a new BoolMask with the specified parameters.
    ///
    /// # Arguments
    ///
    /// * `policy_index` - The index of the policy this mask belongs to
    /// * `name` - The original field name from the policy definition
    /// * `mask` - The masked field name unlikely to be in LLM training data
    /// * `default` - The default boolean value when field is absent
    /// * `is_true` - The boolean value that activates this policy rule
    /// * `on_conflict` - Strategy for resolving conflicts between policies
    ///
    /// # Example
    ///
    /// ```
    /// use policyai::{BoolMask, OnConflict};
    /// let mask = BoolMask::new(
    ///     1,
    ///     "urgent".to_string(),
    ///     "field_abc123".to_string(),
    ///     false,
    ///     true,
    ///     OnConflict::Agreement
    /// );
    /// ```
    pub fn new(
        policy_index: usize,
        name: String,
        mask: String,
        default: bool,
        is_true: bool,
        on_conflict: OnConflict,
    ) -> Self {
        Self {
            policy_index,
            name,
            mask,
            default,
            is_true,
            on_conflict,
        }
    }

    /// Apply this boolean mask to intermediate representation data.
    ///
    /// Extracts the boolean value from the IR and reports it to the given Report
    /// if it matches the expected value, otherwise reports the default.
    ///
    /// # Arguments
    ///
    /// * `ir` - The intermediate representation JSON from the LLM
    /// * `report` - The report to write results and errors to
    ///
    /// # Example
    ///
    /// ```
    /// # use policyai::{BoolMask, OnConflict, Report};
    /// let mask = BoolMask::new(1, "urgent".to_string(), "field_abc".to_string(), false, true, OnConflict::Default);
    /// let ir = serde_json::json!({"field_abc": true});
    /// let mut report = Report::new(vec![], vec![], vec![], vec![], vec![], vec![], vec![]);
    /// mask.apply_to(&ir, &mut report);
    /// ```
    pub fn apply_to(&self, ir: &serde_json::Value, report: &mut Report) {
        match ir.get(&self.mask) {
            Some(serde_json::Value::Bool(ret)) => {
                if *ret == self.is_true {
                    report.report_bool(self.policy_index, &self.name, *ret, self.on_conflict);
                } else {
                    report.report_bool_default(&self.name, self.default);
                }
            }
            Some(_) => {
                report.report_type_check_failure(
                    file!(),
                    line!(),
                    &format!("expected boolean for {}", self.name),
                );
            }
            None => {
                report.report_bool_default(&self.name, self.default);
            }
        }
    }
}

//////////////////////////////////////////// NumberMask ////////////////////////////////////////////

/// Represents a numeric field mask for policy application.
///
/// A NumberMask handles the extraction and conflict resolution of numeric values
/// from unstructured data based on policy rules.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct NumberMask {
    /// Index of the policy this mask belongs to
    pub policy_index: usize,
    /// Original field name from the policy definition
    pub name: String,
    /// Masked field name unlikely to be in LLM training data
    pub mask: String,
    /// Default value when the field is not present
    pub default: Option<t64>,
    /// Expected numeric value for this policy rule
    pub value: Option<serde_json::Number>,
    /// Strategy for resolving conflicts when multiple policies set different values
    pub on_conflict: OnConflict,
}

impl NumberMask {
    /// Create a new NumberMask with the specified parameters.
    ///
    /// # Arguments
    ///
    /// * `policy_index` - The index of the policy this mask belongs to
    /// * `name` - The original field name from the policy definition
    /// * `mask` - The masked field name unlikely to be in LLM training data
    /// * `default` - The default numeric value when field is absent
    /// * `value` - The expected numeric value for this mask
    /// * `on_conflict` - Strategy for resolving conflicts between policies
    ///
    /// # Example
    ///
    /// ```
    /// use policyai::{NumberMask, OnConflict, t64};
    /// let mask = NumberMask::new(
    ///     1,
    ///     "priority".to_string(),
    ///     "field_xyz789".to_string(),
    ///     Some(t64(0.0)),
    ///     Some(serde_json::Number::from(42)),
    ///     OnConflict::LargestValue
    /// );
    /// ```
    pub fn new(
        policy_index: usize,
        name: String,
        mask: String,
        default: Option<t64>,
        value: Option<serde_json::Number>,
        on_conflict: OnConflict,
    ) -> Self {
        Self {
            policy_index,
            name,
            mask,
            default,
            value,
            on_conflict,
        }
    }

    /// Apply this numeric mask to intermediate representation data.
    ///
    /// Extracts the numeric value from the IR and reports it to the given Report,
    /// applying conflict resolution strategies as needed.
    ///
    /// # Arguments
    ///
    /// * `ir` - The intermediate representation JSON from the LLM
    /// * `report` - The report to write results and errors to
    ///
    /// # Example
    ///
    /// ```
    /// # use policyai::{NumberMask, OnConflict, Report, t64};
    /// # use claudius::MessageParam;
    /// let mask = NumberMask::new(1, "score".to_string(), "field_num".to_string(), Some(t64(0.0)), Some(serde_json::Number::from(42)), OnConflict::Default);
    /// let ir = serde_json::json!({"field_num": 42});
    /// let mut report = Report::new(vec![], vec![], vec![], vec![], vec![], vec![], vec![]);
    /// mask.apply_to(&ir, &mut report);
    /// ```
    pub fn apply_to(&self, ir: &serde_json::Value, report: &mut Report) {
        match ir.get(&self.mask) {
            Some(serde_json::Value::Number(value)) => {
                if let Some(expected_value) = &self.value {
                    if number_is_equal(value, expected_value) {
                        report.report_number(
                            self.policy_index,
                            &self.name,
                            value.clone(),
                            self.on_conflict,
                        );
                    } else {
                        report.report_policy_index(self.policy_index);
                        report.report_number_conflict(
                            &self.name,
                            value.clone(),
                            expected_value.clone(),
                        );
                    }
                } else {
                    report.report_number(
                        self.policy_index,
                        &self.name,
                        value.clone(),
                        self.on_conflict,
                    );
                }
            }
            Some(_) => {
                report.report_type_check_failure(
                    file!(),
                    line!(),
                    &format!("expected number for {}", self.name),
                );
            }
            None => {
                if let Some(default) = self.default.as_ref() {
                    if let Some(default) = serde_json::Number::from_f64(default.0) {
                        report.report_number_default(&self.name, default);
                    } else {
                        report.report_invariant_violation(
                            file!(),
                            line!(),
                            "cannot cast to number",
                        );
                    }
                }
            }
        }
    }
}

//////////////////////////////////////////// StringMask ////////////////////////////////////////////

/// Represents a string field mask for policy application.
///
/// A StringMask handles the extraction and conflict resolution of string values
/// from unstructured data based on policy rules.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct StringMask {
    /// Index of the policy this mask belongs to
    pub policy_index: usize,
    /// Original field name from the policy definition
    pub name: String,
    /// Masked field name unlikely to be in LLM training data
    pub mask: String,
    /// Default value when the field is not present
    pub default: Option<String>,
    /// Expected string value for this policy rule
    pub value: Option<String>,
    /// Strategy for resolving conflicts when multiple policies set different values
    pub on_conflict: OnConflict,
}

impl StringMask {
    /// Create a new StringMask with the specified parameters.
    ///
    /// # Arguments
    ///
    /// * `policy_index` - The index of the policy this mask belongs to
    /// * `name` - The original field name from the policy definition
    /// * `mask` - The masked field name unlikely to be in LLM training data
    /// * `default` - The default string value when field is absent
    /// * `value` - The expected string value for this mask
    /// * `on_conflict` - Strategy for resolving conflicts between policies
    ///
    /// # Example
    ///
    /// ```
    /// use policyai::{StringMask, OnConflict};
    /// let mask = StringMask::new(
    ///     1,
    ///     "category".to_string(),
    ///     "field_str456".to_string(),
    ///     Some("default".to_string()),
    ///     Some("urgent".to_string()),
    ///     OnConflict::Agreement
    /// );
    /// ```
    pub fn new(
        policy_index: usize,
        name: String,
        mask: String,
        default: Option<String>,
        value: Option<String>,
        on_conflict: OnConflict,
    ) -> Self {
        Self {
            policy_index,
            name,
            mask,
            default,
            value,
            on_conflict,
        }
    }

    /// Apply this string mask to intermediate representation data.
    ///
    /// Extracts the string value from the IR and reports it to the given Report,
    /// applying conflict resolution strategies as needed.
    ///
    /// # Arguments
    ///
    /// * `ir` - The intermediate representation JSON from the LLM
    /// * `report` - The report to write results and errors to
    ///
    /// # Example
    ///
    /// ```
    /// # use policyai::{StringMask, OnConflict, Report};
    /// # use claudius::MessageParam;
    /// let mask = StringMask::new(1, "title".to_string(), "field_str".to_string(), None, Some("important".to_string()), OnConflict::Default);
    /// let ir = serde_json::json!({"field_str": "important"});
    /// let mut report = Report::new(vec![], vec![], vec![], vec![], vec![], vec![], vec![]);
    /// mask.apply_to(&ir, &mut report);
    /// ```
    pub fn apply_to(&self, ir: &serde_json::Value, report: &mut Report) {
        match ir.get(&self.mask) {
            Some(serde_json::Value::String(value)) => {
                if let Some(expected_value) = &self.value {
                    if value == expected_value {
                        report.report_string(
                            self.policy_index,
                            &self.name,
                            value.clone(),
                            self.on_conflict,
                        );
                    } else {
                        report.report_policy_index(self.policy_index);
                        report.report_string_conflict(
                            &self.name,
                            value.clone(),
                            expected_value.clone(),
                        );
                    }
                } else {
                    report.report_string(
                        self.policy_index,
                        &self.name,
                        value.clone(),
                        self.on_conflict,
                    );
                }
            }
            Some(_) => {
                report.report_type_check_failure(
                    file!(),
                    line!(),
                    &format!("expected string for {}", self.name),
                );
            }
            _ => {
                if let Some(default) = self.default.as_ref() {
                    report.report_string_default(&self.name, default);
                }
            }
        }
    }
}

////////////////////////////////////////// StringArrayMask /////////////////////////////////////////

/// Represents a string array field mask for policy application.
///
/// A StringArrayMask handles the extraction of arrays of strings from
/// unstructured data, collecting all matching string values into an array.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct StringArrayMask {
    /// Index of the policy this mask belongs to
    pub policy_index: usize,
    /// Original field name from the policy definition
    pub name: String,
    /// Masked field name unlikely to be in LLM training data
    pub mask: String,
}

impl StringArrayMask {
    /// Create a new StringArrayMask with the specified parameters.
    ///
    /// # Arguments
    ///
    /// * `policy_index` - The index of the policy this mask belongs to
    /// * `name` - The original field name from the policy definition
    /// * `mask` - The masked field name unlikely to be in LLM training data
    /// * `_value` - The expected string values (currently unused)
    ///
    /// # Example
    ///
    /// ```
    /// use policyai::StringArrayMask;
    /// let mask = StringArrayMask::new(
    ///     1,
    ///     "tags".to_string(),
    ///     "field_arr789".to_string(),
    ///     vec!["tag1".to_string(), "tag2".to_string()]
    /// );
    /// ```
    pub fn new(policy_index: usize, name: String, mask: String, _value: Vec<String>) -> Self {
        Self {
            policy_index,
            name,
            mask,
        }
    }

    /// Apply this string array mask to intermediate representation data.
    ///
    /// Extracts string arrays from the IR (supporting nested arrays) and reports
    /// each individual string to the given Report.
    ///
    /// # Arguments
    ///
    /// * `ir` - The intermediate representation JSON from the LLM
    /// * `report` - The report to write results and errors to
    ///
    /// # Example
    ///
    /// ```
    /// # use policyai::{StringArrayMask, Report};
    /// # use claudius::MessageParam;
    /// let mask = StringArrayMask::new(1, "tags".to_string(), "field_arr".to_string(), vec![]);
    /// let ir = serde_json::json!({"field_arr": ["tag1", "tag2"]});
    /// let mut report = Report::new(vec![], vec![], vec![], vec![], vec![], vec![], vec![]);
    /// mask.apply_to(&ir, &mut report);
    /// ```
    pub fn apply_to(&self, ir: &serde_json::Value, report: &mut Report) {
        fn extract_strings(value: &serde_json::Value, depth: usize) -> Option<Vec<String>> {
            if depth == 0 {
                None
            } else if let serde_json::Value::String(s) = value {
                Some(vec![s.clone()])
            } else if let serde_json::Value::Array(a) = value {
                let mut all = vec![];
                for v in a {
                    all.extend(extract_strings(v, depth - 1)?.into_iter());
                }
                Some(all)
            } else {
                None
            }
        }
        if let Some(reported) = ir.get(&self.mask) {
            match extract_strings(reported, 128) {
                Some(strings) => {
                    if strings.is_empty() {
                        report.init_empty_string_array(self.policy_index, &self.name);
                    } else {
                        for s in strings {
                            report.report_string_array(self.policy_index, &self.name, s);
                        }
                    }
                }
                None => {
                    report.report_type_check_failure(
                        file!(),
                        line!(),
                        &format!("expected [string] for {}", self.name),
                    );
                }
            }
        }
    }
}

////////////////////////////////////////// StringEnumMask //////////////////////////////////////////

/// Represents a string enumeration field mask for policy application.
///
/// A StringEnumMask handles boolean-style enumeration values where the presence
/// of a specific enum value is indicated by a boolean flag in the intermediate representation.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct StringEnumMask {
    /// Index of the policy this mask belongs to
    pub policy_index: usize,
    /// Original field name from the policy definition
    pub name: String,
    /// Masked field name unlikely to be in LLM training data
    pub mask: String,
    /// The specific enum value this mask represents
    pub value: Option<String>,
    /// Default enum value when the field is not present
    pub default: Option<String>,
    /// Strategy for resolving conflicts when multiple policies set different values
    pub on_conflict: OnConflict,
}

impl StringEnumMask {
    /// Create a new StringEnumMask with the specified parameters.
    ///
    /// # Arguments
    ///
    /// * `policy_index` - The index of the policy this mask belongs to
    /// * `name` - The original field name from the policy definition
    /// * `mask` - The masked field name unlikely to be in LLM training data
    /// * `value` - The specific enum value this mask represents
    /// * `default` - The default enum value when field is absent
    /// * `on_conflict` - Strategy for resolving conflicts between policies
    ///
    /// # Example
    ///
    /// ```
    /// use policyai::{StringEnumMask, OnConflict};
    /// let mask = StringEnumMask::new(
    ///     1,
    ///     "status".to_string(),
    ///     "field_enum456".to_string(),
    ///     Some("active".to_string()),
    ///     Some("inactive".to_string()),
    ///     OnConflict::LargestValue
    /// );
    /// ```
    pub fn new(
        policy_index: usize,
        name: String,
        mask: String,
        value: Option<String>,
        default: Option<String>,
        on_conflict: OnConflict,
    ) -> Self {
        Self {
            policy_index,
            name,
            mask,
            value,
            default,
            on_conflict,
        }
    }

    /// Apply this string enum mask to intermediate representation data.
    ///
    /// Checks for a boolean flag in the IR and if true, reports the associated
    /// enum value. This supports enum fields where each possible value is
    /// represented as a separate boolean flag.
    ///
    /// # Arguments
    ///
    /// * `ir` - The intermediate representation JSON from the LLM
    /// * `report` - The report to write results and errors to
    ///
    /// # Example
    ///
    /// ```
    /// # use policyai::{StringEnumMask, OnConflict, Report};
    /// # use claudius::MessageParam;
    /// let mask = StringEnumMask::new(1, "priority".to_string(), "field_enum".to_string(), Some("high".to_string()), None, OnConflict::Default);
    /// let ir = serde_json::json!({"field_enum": true});
    /// let mut report = Report::new(vec![], vec![], vec![], vec![], vec![], vec![], vec![]);
    /// mask.apply_to(&ir, &mut report);
    /// ```
    pub fn apply_to(&self, ir: &serde_json::Value, report: &mut Report) {
        match ir.get(&self.mask) {
            Some(serde_json::Value::Bool(value)) => {
                if *value {
                    if let Some(enum_value) = &self.value {
                        report.report_string_enum(
                            self.policy_index,
                            &self.name,
                            enum_value.clone(),
                            self.on_conflict,
                        );
                    } else {
                        report.report_policy_index(self.policy_index);
                        report.report_string_enum_conflict(
                            &self.name,
                            value.to_string(),
                            "null".to_string(),
                        );
                    }
                } else if let Some(default) = self.default.as_ref() {
                    report.report_string_default(&self.name, default);
                }
            }
            Some(_) => {
                report.report_type_check_failure(
                    file!(),
                    line!(),
                    &format!("expected string for {}", self.name),
                );
            }
            _ => {
                if let Some(default) = self.default.as_ref() {
                    report.report_string_default(&self.name, default);
                }
            }
        }
    }
}