policyai 0.4.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
//! Field definitions for PolicyAI types.
//!
//! This module defines the [`Field`] enum which represents the various types of fields
//! that can be included in a PolicyType. Each field has a name, type, optional default value,
//! and conflict resolution strategy.

use crate::{t64, OnConflict};

/// Represents a field in a PolicyType with its type, default value, and conflict resolution strategy.
///
/// Fields define the structure of data that policies work with. Each field has:
/// - A name that identifies it
/// - A type (bool, number, string, string enum, or string array)
/// - An optional default value
/// - A conflict resolution strategy for when multiple policies set the same field
///
/// # Example
///
/// ```
/// use policyai::{Field, OnConflict};
///
/// let field = Field::Bool {
///     name: "is_active".to_string(),
///     default: Some(true),
///     on_conflict: OnConflict::Default,
/// };
/// ```
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum Field {
    /// A boolean field that can be either true or false.
    #[serde(rename = "bool")]
    Bool {
        /// The name of this field.
        name: String,
        /// The default boolean value when no policy sets this field.
        default: Option<bool>,
        /// Strategy for resolving conflicts when multiple policies set this field.
        on_conflict: OnConflict,
    },
    /// A free-form string field.
    #[serde(rename = "string")]
    String {
        /// The name of this field.
        name: String,
        /// The default string value when no policy sets this field.
        default: Option<String>,
        /// Strategy for resolving conflicts when multiple policies set this field.
        on_conflict: OnConflict,
    },
    /// A string field constrained to a specific set of allowed values.
    #[serde(rename = "enum")]
    StringEnum {
        /// The name of this field.
        name: String,
        /// The allowed values for this field.
        values: Vec<String>,
        /// The default value when no policy sets this field.
        default: Option<String>,
        /// Strategy for resolving conflicts when multiple policies set this field.
        on_conflict: OnConflict,
    },
    /// An array of strings that policies can append to.
    #[serde(rename = "array")]
    StringArray {
        /// The name of this field.
        name: String,
    },
    /// A numeric field that can hold integer or floating-point values.
    #[serde(rename = "number")]
    Number {
        /// The name of this field.
        name: String,
        /// The default numeric value when no policy sets this field.
        default: Option<t64>,
        /// Strategy for resolving conflicts when multiple policies set this field.
        on_conflict: OnConflict,
    },
}

impl Field {
    /// Get the name of this field.
    pub fn name(&self) -> &str {
        match self {
            Self::Bool {
                name,
                default: _,
                on_conflict: _,
            } => name,
            Self::Number {
                name,
                default: _,
                on_conflict: _,
            } => name,
            Self::String {
                name,
                default: _,
                on_conflict: _,
            } => name,
            Self::StringEnum {
                name,
                values: _,
                default: _,
                on_conflict: _,
            } => name,
            Self::StringArray { name } => name,
        }
    }

    /// Get the default value for this field.
    ///
    /// Returns the configured default value, or null for fields without defaults.
    /// String arrays always default to an empty array.
    pub fn default_value(&self) -> serde_json::Value {
        match self {
            Self::Bool {
                name: _,
                default,
                on_conflict: _,
            } => (*default).into(),
            Self::Number {
                name: _,
                default,
                on_conflict: _,
            } => (*default).into(),
            Self::String {
                name: _,
                default,
                on_conflict: _,
            } => (*default).clone().into(),
            Self::StringEnum {
                name: _,
                values: _,
                default,
                on_conflict: _,
            } => (*default).clone().into(),
            Self::StringArray { name: _ } => serde_json::json! {[]},
        }
    }
}

impl std::fmt::Display for Field {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        match self {
            Self::Bool {
                name,
                default,
                on_conflict,
            } => match on_conflict {
                OnConflict::Default => match default {
                    Some(true) => write!(f, "{name}: bool = true")?,
                    Some(false) => write!(f, "{name}: bool = false")?,
                    None => write!(f, "{name}: bool")?,
                },
                OnConflict::Agreement => match default {
                    Some(true) => write!(f, "{name}: bool @ agreement = true")?,
                    Some(false) => write!(f, "{name}: bool @ agreement = false")?,
                    None => write!(f, "{name}: bool @ agreement")?,
                },
                OnConflict::LargestValue => match default {
                    Some(true) => write!(f, "{name}: bool @ sticky = true")?,
                    Some(false) => write!(f, "{name}: bool @ sticky = false")?,
                    None => write!(f, "{name}: bool @ sticky")?,
                },
            },
            Self::String {
                name,
                default,
                on_conflict,
            } => match on_conflict {
                OnConflict::Default => {
                    if let Some(default) = default.as_ref() {
                        write!(f, "{name}: string = {default:?}")?;
                    } else {
                        write!(f, "{name}: string")?;
                    }
                }
                OnConflict::Agreement => {
                    if let Some(default) = default.as_ref() {
                        write!(f, "{name}: string @ agreement = {default:?}")?;
                    } else {
                        write!(f, "{name}: string @ agreement")?;
                    }
                }
                OnConflict::LargestValue => {
                    if let Some(default) = default.as_ref() {
                        write!(f, "{name}: string @ last wins = {default:?}")?;
                    } else {
                        write!(f, "{name}: string @ last wins")?;
                    }
                }
            },
            Self::StringEnum {
                name,
                values,
                default,
                on_conflict,
            } => {
                let values = values
                    .iter()
                    .map(|v| format!("{v:?}"))
                    .collect::<Vec<_>>()
                    .join(", ");
                match on_conflict {
                    OnConflict::Default => {
                        if let Some(default) = default.as_ref() {
                            write!(f, "{name}: [{values}] = {default:?}")?;
                        } else {
                            write!(f, "{name}: [{values}]")?;
                        }
                    }
                    OnConflict::Agreement => {
                        if let Some(default) = default.as_ref() {
                            write!(f, "{name}: [{values}] @ agreement = {default:?}")?;
                        } else {
                            write!(f, "{name}: [{values}] @ agreement")?;
                        }
                    }
                    OnConflict::LargestValue => {
                        if let Some(default) = default.as_ref() {
                            write!(f, "{name}: [{values}] @ highest wins = {default:?}")?;
                        } else {
                            write!(f, "{name}: [{values}] @ highest wins")?;
                        }
                    }
                }
            }
            Self::StringArray { name } => {
                write!(f, "{name}: [string]")?;
            }
            Self::Number {
                name,
                default,
                on_conflict,
            } => match on_conflict {
                OnConflict::Default => {
                    if let Some(default) = default.as_ref() {
                        write!(f, "{name}: number = {}", default.0)?;
                    } else {
                        write!(f, "{name}: number")?;
                    }
                }
                OnConflict::Agreement => {
                    if let Some(default) = default.as_ref() {
                        write!(f, "{name}: number @ agreement = {}", default.0)?;
                    } else {
                        write!(f, "{name}: number @ agreement")?;
                    }
                }
                OnConflict::LargestValue => {
                    if let Some(default) = default.as_ref() {
                        write!(f, "{name}: number @ last wins = {}", default.0)?;
                    } else {
                        write!(f, "{name}: number @ last wins")?;
                    }
                }
            },
        }
        Ok(())
    }
}

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

    #[test]
    fn field_name() {
        let bool_field = Field::Bool {
            name: "is_active".to_string(),
            default: Some(true),
            on_conflict: OnConflict::Default,
        };
        assert_eq!(bool_field.name(), "is_active");

        let string_field = Field::String {
            name: "description".to_string(),
            default: Some("test".to_string()),
            on_conflict: OnConflict::Agreement,
        };
        assert_eq!(string_field.name(), "description");

        let enum_field = Field::StringEnum {
            name: "priority".to_string(),
            values: vec!["low".to_string(), "high".to_string()],
            default: None,
            on_conflict: OnConflict::LargestValue,
        };
        assert_eq!(enum_field.name(), "priority");

        let array_field = Field::StringArray {
            name: "tags".to_string(),
        };
        assert_eq!(array_field.name(), "tags");

        let number_field = Field::Number {
            name: "score".to_string(),
            default: Some(t64(42.0)),
            on_conflict: OnConflict::Default,
        };
        assert_eq!(number_field.name(), "score");
    }

    #[test]
    fn field_default_value() {
        let bool_field = Field::Bool {
            name: "is_active".to_string(),
            default: Some(true),
            on_conflict: OnConflict::Default,
        };
        assert_eq!(bool_field.default_value(), serde_json::json!(true));

        let string_field = Field::String {
            name: "description".to_string(),
            default: Some("test".to_string()),
            on_conflict: OnConflict::Agreement,
        };
        assert_eq!(string_field.default_value(), serde_json::json!("test"));

        let string_field_none = Field::String {
            name: "description".to_string(),
            default: None,
            on_conflict: OnConflict::Agreement,
        };
        assert_eq!(string_field_none.default_value(), serde_json::json!(null));

        let enum_field = Field::StringEnum {
            name: "priority".to_string(),
            values: vec!["low".to_string(), "high".to_string()],
            default: Some("low".to_string()),
            on_conflict: OnConflict::LargestValue,
        };
        assert_eq!(enum_field.default_value(), serde_json::json!("low"));

        let array_field = Field::StringArray {
            name: "tags".to_string(),
        };
        assert_eq!(array_field.default_value(), serde_json::json!([]));

        let number_field = Field::Number {
            name: "score".to_string(),
            default: Some(t64(42.5)),
            on_conflict: OnConflict::Default,
        };
        assert_eq!(number_field.default_value(), serde_json::json!(42.5));
    }

    #[test]
    fn field_display_bool() {
        let field = Field::Bool {
            name: "is_active".to_string(),
            default: Some(true),
            on_conflict: OnConflict::Default,
        };
        assert_eq!(field.to_string(), "is_active: bool = true");

        let field = Field::Bool {
            name: "is_active".to_string(),
            default: Some(false),
            on_conflict: OnConflict::Default,
        };
        assert_eq!(field.to_string(), "is_active: bool = false");

        let field = Field::Bool {
            name: "is_active".to_string(),
            default: Some(true),
            on_conflict: OnConflict::Agreement,
        };
        assert_eq!(field.to_string(), "is_active: bool @ agreement = true");

        let field = Field::Bool {
            name: "is_active".to_string(),
            default: Some(false),
            on_conflict: OnConflict::LargestValue,
        };
        assert_eq!(field.to_string(), "is_active: bool @ sticky = false");
    }

    #[test]
    fn field_display_string() {
        let field = Field::String {
            name: "description".to_string(),
            default: Some("default text".to_string()),
            on_conflict: OnConflict::Default,
        };
        assert_eq!(field.to_string(), "description: string = \"default text\"");

        let field = Field::String {
            name: "description".to_string(),
            default: None,
            on_conflict: OnConflict::Agreement,
        };
        assert_eq!(field.to_string(), "description: string @ agreement");

        let field = Field::String {
            name: "description".to_string(),
            default: Some("test".to_string()),
            on_conflict: OnConflict::LargestValue,
        };
        assert_eq!(
            field.to_string(),
            "description: string @ last wins = \"test\""
        );
    }

    #[test]
    fn field_display_string_enum() {
        let field = Field::StringEnum {
            name: "priority".to_string(),
            values: vec!["low".to_string(), "medium".to_string(), "high".to_string()],
            default: Some("medium".to_string()),
            on_conflict: OnConflict::Default,
        };
        assert_eq!(
            field.to_string(),
            "priority: [\"low\", \"medium\", \"high\"] = \"medium\""
        );

        let field = Field::StringEnum {
            name: "priority".to_string(),
            values: vec!["low".to_string(), "high".to_string()],
            default: None,
            on_conflict: OnConflict::LargestValue,
        };
        assert_eq!(
            field.to_string(),
            "priority: [\"low\", \"high\"] @ highest wins"
        );
    }

    #[test]
    fn field_display_string_array() {
        let field = Field::StringArray {
            name: "tags".to_string(),
        };
        assert_eq!(field.to_string(), "tags: [string]");
    }

    #[test]
    fn field_display_number() {
        let field = Field::Number {
            name: "score".to_string(),
            default: Some(t64(42.5)),
            on_conflict: OnConflict::Default,
        };
        assert_eq!(field.to_string(), "score: number = 42.5");

        let field = Field::Number {
            name: "score".to_string(),
            default: None,
            on_conflict: OnConflict::Agreement,
        };
        assert_eq!(field.to_string(), "score: number @ agreement");
    }

    #[test]
    fn field_serialization() {
        let field = Field::Bool {
            name: "is_active".to_string(),
            default: Some(true),
            on_conflict: OnConflict::Default,
        };
        let serialized = serde_json::to_string(&field).unwrap();
        let deserialized: Field = serde_json::from_str(&serialized).unwrap();
        assert_eq!(field, deserialized);

        let field = Field::StringArray {
            name: "tags".to_string(),
        };
        let serialized = serde_json::to_string(&field).unwrap();
        let deserialized: Field = serde_json::from_str(&serialized).unwrap();
        assert_eq!(field, deserialized);
    }
}