Skip to main content

aidaemon_work/mandates/
validate.rs

1//! Bounds and normalization for the text and lists a mandate tool call
2//! carries. The owner tool (`manage_mandates`) and the review tool
3//! (`mandate_review`) both validate through these, so a limit is stated once.
4
5use crate::traits::{MandateDecisionOutcome, MandateTerminationKind};
6
7/// Longest single policy entry (constraint, criterion, stop condition).
8pub const MAX_POLICY_ENTRY_TEXT: usize = 500;
9/// Longest learning note a review records.
10pub const MAX_LEARNING_NOTE_TEXT: usize = 1024;
11/// Most evidence receipts one decision cites.
12pub const MAX_EVIDENCE_RECEIPTS: usize = 16;
13
14pub fn required_trimmed<'a>(value: Option<&'a str>, name: &str) -> anyhow::Result<&'a str> {
15    value
16        .map(str::trim)
17        .filter(|value| !value.is_empty())
18        .ok_or_else(|| anyhow::anyhow!("{name} is required"))
19}
20
21/// A dispatcher fact the call needs (from its `ToolCallContext`).
22pub fn required_call_fact<'a>(value: Option<&'a str>, fact: &str) -> anyhow::Result<&'a str> {
23    value
24        .map(str::trim)
25        .filter(|value| !value.is_empty())
26        .ok_or_else(|| anyhow::anyhow!("the {fact} fact is missing from the call context"))
27}
28
29pub fn required_bounded_trimmed<'a>(
30    value: Option<&'a str>,
31    name: &str,
32    max_text: usize,
33) -> anyhow::Result<&'a str> {
34    let value = required_trimmed(value, name)?;
35    validate_bounded_text(value, name, max_text)?;
36    Ok(value)
37}
38
39pub fn validate_bounded_text(value: &str, name: &str, max_text: usize) -> anyhow::Result<()> {
40    anyhow::ensure!(
41        value.chars().count() <= max_text && value.len() <= max_text,
42        "{name} exceeds its {max_text}-character/byte bound"
43    );
44    Ok(())
45}
46
47pub fn bounded_optional_text(
48    value: Option<&str>,
49    name: &str,
50    max_text: usize,
51) -> anyhow::Result<Option<String>> {
52    let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) else {
53        return Ok(None);
54    };
55    validate_bounded_text(value, name, max_text)?;
56    Ok(Some(value.to_string()))
57}
58
59pub fn normalized_termination_fields(
60    outcome: MandateDecisionOutcome,
61    termination_kind: Option<&str>,
62    termination_match: Option<&str>,
63) -> anyhow::Result<(Option<MandateTerminationKind>, Option<String>)> {
64    // Some structured-tool providers populate every optional schema field with
65    // a default. The explicit typed outcome is authoritative, so STOP-only
66    // metadata on ACT/WAIT/ASK must not turn a safe non-action into a failed
67    // review. It is ignored rather than reinterpreted as a termination.
68    if outcome != MandateDecisionOutcome::Stop {
69        return Ok((None, None));
70    }
71    let kind = termination_kind
72        .map(str::trim)
73        .filter(|value| !value.is_empty())
74        .map(|value| {
75            MandateTerminationKind::parse(value).ok_or_else(|| {
76                anyhow::anyhow!(
77                    "termination_kind must be success_criteria_satisfied, stop_condition_met, or safety_termination"
78                )
79            })
80        })
81        .transpose()?;
82    anyhow::ensure!(kind.is_some(), "STOP requires termination_kind");
83    let matched = bounded_optional_text(
84        termination_match,
85        "termination_match",
86        MAX_POLICY_ENTRY_TEXT,
87    )?;
88    Ok((kind, matched))
89}
90
91pub fn validate_act_evidence(
92    outcome: MandateDecisionOutcome,
93    observations: &[String],
94    evidence_receipt_ids: &[String],
95) -> anyhow::Result<()> {
96    if outcome == MandateDecisionOutcome::Act {
97        anyhow::ensure!(
98            !observations.is_empty() && !evidence_receipt_ids.is_empty(),
99            "ACT requires at least one current-run sourced observation and its durable evidence receipt; choose WAIT when no evidence shows that intervention is worthwhile"
100        );
101    }
102    Ok(())
103}
104
105pub fn normalized_learning_note(
106    learning_note: Option<&str>,
107    learning_evidence_receipt_ids: Option<&[String]>,
108) -> anyhow::Result<Option<(String, Vec<String>)>> {
109    let Some(summary) =
110        bounded_optional_text(learning_note, "learning_note", MAX_LEARNING_NOTE_TEXT)?
111    else {
112        // Structured-tool providers may populate this optional companion field
113        // even when learning_note is empty. With no note there is nothing to
114        // persist, so ignore the orphan defaults before the decision commit.
115        return Ok(None);
116    };
117    let evidence = clean_strings(learning_evidence_receipt_ids);
118    validate_bounded_strings(
119        &evidence,
120        "learning_evidence_receipt_ids",
121        MAX_EVIDENCE_RECEIPTS,
122        256,
123        4 * 1024,
124    )?;
125    anyhow::ensure!(
126        !evidence.is_empty(),
127        "learning_note requires learning_evidence_receipt_ids"
128    );
129    Ok(Some((summary, evidence)))
130}
131
132pub fn learning_note_fields_complete(
133    learning_note: Option<&str>,
134    evidence: Option<&[String]>,
135) -> bool {
136    learning_note.is_some_and(|value| !value.trim().is_empty())
137        && evidence.is_some_and(|values| values.iter().any(|value| !value.trim().is_empty()))
138}
139
140pub fn clean_strings(values: Option<&[String]>) -> Vec<String> {
141    values
142        .unwrap_or_default()
143        .iter()
144        .map(|value| value.trim())
145        .filter(|value| !value.is_empty())
146        .map(str::to_string)
147        .collect()
148}
149
150pub fn validate_bounded_strings(
151    values: &[String],
152    name: &str,
153    max_entries: usize,
154    max_entry_text: usize,
155    max_serialized_bytes: usize,
156) -> anyhow::Result<()> {
157    anyhow::ensure!(
158        values.len() <= max_entries,
159        "{name} cannot contain more than {max_entries} entries"
160    );
161    for value in values {
162        validate_bounded_text(value, &format!("one {name} entry"), max_entry_text)?;
163    }
164    anyhow::ensure!(
165        serde_json::to_vec(values)?.len() <= max_serialized_bytes,
166        "{name} exceed their serialized {max_serialized_bytes}-byte bound"
167    );
168    Ok(())
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    #[test]
176    fn clean_strings_removes_empty_constraints() {
177        let values = vec!["  truthful ".to_string(), " ".to_string()];
178        assert_eq!(clean_strings(Some(&values)), vec!["truthful"]);
179    }
180
181    #[test]
182    fn non_stop_outcomes_ignore_generator_supplied_stop_metadata() {
183        let (kind, matched) = normalized_termination_fields(
184            MandateDecisionOutcome::Wait,
185            Some("success_criteria_satisfied"),
186            Some("provider-filled default"),
187        )
188        .unwrap();
189        assert!(kind.is_none());
190        assert!(matched.is_none());
191
192        assert!(normalized_termination_fields(MandateDecisionOutcome::Stop, None, None).is_err());
193    }
194
195    #[test]
196    fn act_requires_sourced_evidence_while_non_actions_do_not_manufacture_it() {
197        let observations = vec!["The monitored value crossed its confirmed threshold".to_string()];
198        let receipts = vec!["tool-call-1".to_string()];
199        assert!(validate_act_evidence(MandateDecisionOutcome::Act, &[], &receipts).is_err());
200        assert!(validate_act_evidence(MandateDecisionOutcome::Act, &observations, &[]).is_err());
201        assert!(
202            validate_act_evidence(MandateDecisionOutcome::Act, &observations, &receipts).is_ok()
203        );
204        assert!(validate_act_evidence(MandateDecisionOutcome::Wait, &[], &[]).is_ok());
205    }
206
207    #[test]
208    fn empty_learning_note_ignores_generator_supplied_receipt_defaults_before_commit() {
209        let receipts = vec!["provider-filled-default".to_string()];
210        assert!(
211            normalized_learning_note(Some(""), Some(&receipts))
212                .unwrap()
213                .is_none()
214        );
215        assert!(normalized_learning_note(Some("real learning"), None).is_err());
216    }
217
218    #[test]
219    fn partial_optional_learning_metadata_is_not_decision_blocking() {
220        assert!(!learning_note_fields_complete(
221            Some("possible learning"),
222            None
223        ));
224    }
225}