cognis-core 0.2.1

Core traits and types for the Cognis LLM framework
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
//! Runtime validators for tool arguments.
//!
//! These helpers are called by code generated by `#[cognis::tool]`
//! (in `cognis-macros`) after JSON deserialization succeeds but before the
//! tool body runs. A constraint violation returns
//! [`CognisError::ToolValidationError`] with a field-scoped message — which
//! [`BaseTool::run`] already routes through [`ErrorHandler`], allowing agent
//! authors to surface validator messages back to the LLM for self-correction.
//!
//! # Schema/runtime duality
//!
//! Every validator here has a **matching schema attribute** in
//! `#[derive(JsonSchema)]` (see `cognis_macros::JsonSchema`). The schema
//! attribute emits JSON Schema keywords the LLM can see; the runtime helper
//! enforces the same constraint after deserialization. Keeping them in sync
//! is the feature's main purpose — don't add one without the other.

use std::sync::OnceLock;

use crate::error::{CognisError, Result};

/// Private re-export of the `regex` crate for use by `#[cognis::tool]`-
/// generated code. Users of the macro do **not** need `regex` in their
/// own `Cargo.toml` — the macro emits references through this path.
#[doc(hidden)]
pub mod __regex {
    pub use regex::*;
}

/// Trait for types that can validate their own field constraints after
/// deserialization. Typically implemented by code generated from
/// `#[cognis::tool]` — each struct's `validate()` is a list of calls into the
/// `check_*` helpers in this module.
///
/// The default impl returns `Ok(())`, making it cheap to derive on structs
/// with no validators.
pub trait ValidateArgs {
    /// Run all field validators. Returns the first violation found as a
    /// [`CognisError::ToolValidationError`].
    fn validate(&self) -> Result<()> {
        Ok(())
    }
}

/// Validate that `value` lies within `[min, max]` (inclusive on both ends).
///
/// `None` bounds are skipped. `NaN` inputs are rejected explicitly (they
/// silently fail all comparisons otherwise).
pub fn check_range(field: &str, value: f64, min: Option<f64>, max: Option<f64>) -> Result<()> {
    if value.is_nan() {
        return Err(CognisError::ToolValidationError(format!(
            "field `{field}`: value is NaN"
        )));
    }
    if let Some(m) = min {
        if value < m {
            return Err(CognisError::ToolValidationError(format!(
                "field `{field}`: {value} is less than minimum {m}"
            )));
        }
    }
    if let Some(m) = max {
        if value > m {
            return Err(CognisError::ToolValidationError(format!(
                "field `{field}`: {value} is greater than maximum {m}"
            )));
        }
    }
    Ok(())
}

/// Validate that `len` lies within `[min, max]` (inclusive on both ends).
///
/// Callers pass `.chars().count()` for `String` (Unicode-correct length) or
/// `.len()` for `Vec<T>`. See [`check_format`] for format-specific string
/// validation.
pub fn check_length(field: &str, len: usize, min: Option<usize>, max: Option<usize>) -> Result<()> {
    if let Some(m) = min {
        if len < m {
            return Err(CognisError::ToolValidationError(format!(
                "field `{field}`: length {len} is less than minimum {m}"
            )));
        }
    }
    if let Some(m) = max {
        if len > m {
            return Err(CognisError::ToolValidationError(format!(
                "field `{field}`: length {len} is greater than maximum {m}"
            )));
        }
    }
    Ok(())
}

/// Validate that `value` is one of the `allowed` variants.
pub fn check_enum<S: AsRef<str>>(field: &str, value: &str, allowed: &[S]) -> Result<()> {
    if allowed.iter().any(|a| a.as_ref() == value) {
        return Ok(());
    }
    let list = allowed
        .iter()
        .map(|a| format!("`{}`", a.as_ref()))
        .collect::<Vec<_>>()
        .join(", ");
    Err(CognisError::ToolValidationError(format!(
        "field `{field}`: \"{value}\" must be one of [{list}]"
    )))
}

/// Validate that `value` matches `re`. The `Regex` is expected to be
/// precompiled once (typically via `std::sync::OnceLock` in macro-generated
/// code) and passed in by reference.
pub fn check_pattern(field: &str, value: &str, re: &regex::Regex) -> Result<()> {
    if re.is_match(value) {
        Ok(())
    } else {
        Err(CognisError::ToolValidationError(format!(
            "field `{field}`: \"{value}\" does not match pattern `{pat}`",
            pat = re.as_str(),
        )))
    }
}

/// String formats supported by `#[schema(format(...))]`.
///
/// `Email` and `Uuid` are regex-checked at runtime. `Ipv4` and `Ipv6` are
/// parsed via `std::net::{Ipv4Addr, Ipv6Addr}` for strict RFC-compliant
/// validation. `Uri` and `DateTime` are emitted into the JSON Schema (for
/// the LLM) but **not** enforced at runtime — their real-world grammars are
/// too permissive for a cheap check to add value. Users who need strict
/// parsing should validate inside the tool body.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
    /// RFC 5322-ish email (regex-checked).
    Email,
    /// URI — schema-only; not validated at runtime.
    Uri,
    /// RFC 4122 UUID (regex-checked, case-insensitive).
    Uuid,
    /// ISO 8601 date-time — schema-only; not validated at runtime.
    DateTime,
    /// Dotted-quad IPv4 address (parsed via `std::net::Ipv4Addr`).
    Ipv4,
    /// Colon-separated IPv6 address (parsed via `std::net::Ipv6Addr`).
    Ipv6,
}

impl Format {
    /// Canonical JSON-Schema `format` keyword value for this variant.
    pub fn as_str(&self) -> &'static str {
        match self {
            Format::Email => "email",
            Format::Uri => "uri",
            Format::Uuid => "uuid",
            Format::DateTime => "date-time",
            Format::Ipv4 => "ipv4",
            Format::Ipv6 => "ipv6",
        }
    }
}

// Infallible regex construction: patterns are static string literals that are
// validated by the test suite. `OnceLock::get_or_init` takes an infallible
// closure, so `expect` is the idiomatic way to surface a compile-time-known
// panic if the regex source were ever corrupted during refactoring.
fn email_regex() -> &'static regex::Regex {
    static R: OnceLock<regex::Regex> = OnceLock::new();
    R.get_or_init(|| regex::Regex::new(r"^[^\s@]+@[^\s@]+\.[^\s@]+$").expect("valid email regex"))
}

fn uuid_regex() -> &'static regex::Regex {
    static R: OnceLock<regex::Regex> = OnceLock::new();
    R.get_or_init(|| {
        regex::Regex::new(r"(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
            .expect("valid uuid regex")
    })
}

/// Validate that `value` matches the named format.
///
/// `Email` and `Uuid` use regex-backed checks. `Ipv4` and `Ipv6` are parsed
/// via `std::net::{Ipv4Addr, Ipv6Addr}` for strict RFC-compliant validation
/// (the stdlib parsers reject edge cases like multiple `::` compressions
/// that a regex can miss). `Uri` and `DateTime` are schema-only — they
/// always return `Ok` at runtime; parse inside the tool body if you need
/// strict validation.
pub fn check_format(field: &str, value: &str, format: Format) -> Result<()> {
    match format {
        Format::Email => {
            if email_regex().is_match(value) {
                Ok(())
            } else {
                Err(CognisError::ToolValidationError(format!(
                    "field `{field}`: \"{value}\" is not a valid email"
                )))
            }
        }
        Format::Uuid => {
            if uuid_regex().is_match(value) {
                Ok(())
            } else {
                Err(CognisError::ToolValidationError(format!(
                    "field `{field}`: \"{value}\" is not a valid uuid"
                )))
            }
        }
        Format::Ipv4 => value
            .parse::<std::net::Ipv4Addr>()
            .map(|_| ())
            .map_err(|_| {
                CognisError::ToolValidationError(format!(
                    "field `{field}`: \"{value}\" is not a valid ipv4"
                ))
            }),
        Format::Ipv6 => value
            .parse::<std::net::Ipv6Addr>()
            .map(|_| ())
            .map_err(|_| {
                CognisError::ToolValidationError(format!(
                    "field `{field}`: \"{value}\" is not a valid ipv6"
                ))
            }),
        Format::Uri | Format::DateTime => Ok(()),
    }
}

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

    fn assert_validation_err(r: Result<()>, needle: &str) {
        match r {
            Err(CognisError::ToolValidationError(msg)) => assert!(
                msg.contains(needle),
                "expected msg to contain {needle:?}, got {msg:?}"
            ),
            other => panic!("expected ToolValidationError, got {other:?}"),
        }
    }

    #[test]
    fn range_passes_within_bounds() {
        assert!(check_range("limit", 5.0, Some(1.0), Some(50.0)).is_ok());
    }

    #[test]
    fn range_passes_on_boundaries_inclusive() {
        assert!(check_range("x", 1.0, Some(1.0), Some(50.0)).is_ok());
        assert!(check_range("x", 50.0, Some(1.0), Some(50.0)).is_ok());
    }

    #[test]
    fn range_rejects_below_min() {
        assert_validation_err(check_range("limit", 0.5, Some(1.0), Some(50.0)), "limit");
    }

    #[test]
    fn range_rejects_above_max() {
        assert_validation_err(
            check_range("limit", 100.0, Some(1.0), Some(50.0)),
            "maximum",
        );
    }

    #[test]
    fn range_with_only_min_ignores_max() {
        assert!(check_range("x", 1e9, Some(0.0), None).is_ok());
    }

    #[test]
    fn range_with_only_max_ignores_min() {
        assert!(check_range("x", -1e9, None, Some(10.0)).is_ok());
    }

    #[test]
    fn range_rejects_nan() {
        assert_validation_err(check_range("x", f64::NAN, Some(0.0), Some(10.0)), "NaN");
    }

    #[test]
    fn length_passes_within_bounds() {
        assert!(check_length("name", 5, Some(1), Some(10)).is_ok());
    }

    #[test]
    fn length_rejects_below_min() {
        assert_validation_err(check_length("name", 0, Some(1), Some(10)), "minimum");
    }

    #[test]
    fn length_rejects_above_max() {
        assert_validation_err(check_length("name", 11, Some(1), Some(10)), "maximum");
    }

    #[test]
    fn length_boundaries_inclusive() {
        assert!(check_length("name", 1, Some(1), Some(10)).is_ok());
        assert!(check_length("name", 10, Some(1), Some(10)).is_ok());
    }

    #[test]
    fn enum_accepts_listed_value() {
        assert!(check_enum("order", "asc", &["asc", "desc"]).is_ok());
        assert!(check_enum("order", "desc", &["asc", "desc"]).is_ok());
    }

    #[test]
    fn enum_rejects_unlisted_value() {
        assert_validation_err(check_enum("order", "random", &["asc", "desc"]), "one of");
    }

    #[test]
    fn enum_error_includes_allowed_values() {
        let err = check_enum("order", "x", &["asc", "desc"]).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("asc") && msg.contains("desc"), "got {msg}");
    }

    #[test]
    fn enum_accepts_owned_strings() {
        let allowed = vec!["asc".to_string(), "desc".to_string()];
        assert!(check_enum("order", "asc", &allowed).is_ok());
        assert_validation_err(check_enum("order", "nope", &allowed), "nope");
    }

    #[test]
    fn pattern_accepts_match() {
        let re = regex::Regex::new("^[a-z]+$").unwrap();
        assert!(check_pattern("slug", "hello", &re).is_ok());
    }

    #[test]
    fn pattern_rejects_non_match() {
        let re = regex::Regex::new("^[a-z]+$").unwrap();
        assert_validation_err(check_pattern("slug", "Hello", &re), "pattern");
    }

    #[test]
    fn pattern_error_includes_pattern_string() {
        let re = regex::Regex::new("^[a-z]+$").unwrap();
        let err = check_pattern("slug", "Hi", &re).unwrap_err();
        assert!(err.to_string().contains("^[a-z]+$"), "got {err}");
    }

    #[test]
    fn format_email_accepts_basic_address() {
        assert!(check_format("to", "a@b.c", Format::Email).is_ok());
    }

    #[test]
    fn format_email_rejects_bare_token() {
        assert_validation_err(check_format("to", "no-at-sign", Format::Email), "email");
    }

    #[test]
    fn format_uuid_accepts_v4() {
        assert!(check_format("id", "550e8400-e29b-41d4-a716-446655440000", Format::Uuid,).is_ok());
    }

    #[test]
    fn format_uuid_rejects_non_uuid() {
        assert_validation_err(check_format("id", "not-a-uuid", Format::Uuid), "uuid");
    }

    #[test]
    fn format_ipv4_accepts() {
        assert!(check_format("ip", "192.168.1.1", Format::Ipv4).is_ok());
    }

    #[test]
    fn format_ipv4_rejects() {
        assert_validation_err(check_format("ip", "300.1.1.1", Format::Ipv4), "ipv4");
    }

    #[test]
    fn format_uri_is_schema_only_passthrough() {
        assert!(check_format("link", "anything goes here", Format::Uri).is_ok());
        assert!(check_format("t", "whatever", Format::DateTime).is_ok());
    }

    #[test]
    fn format_ipv6_rejects_malformed_with_multiple_double_colons() {
        // `::1::2` has two `::` compressions, which is invalid per RFC 4291
        // — the old permissive regex was flagged by cubic for accepting cases
        // like this. std::net::Ipv6Addr::from_str correctly rejects it.
        assert_validation_err(check_format("ip", "::1::2", Format::Ipv6), "ipv6");
    }

    #[test]
    fn format_ipv6_accepts_standard_forms() {
        assert!(check_format("ip", "::1", Format::Ipv6).is_ok());
        assert!(check_format("ip", "2001:db8::1", Format::Ipv6).is_ok());
        assert!(check_format(
            "ip",
            "fe80:0000:0000:0000:0202:b3ff:fe1e:8329",
            Format::Ipv6,
        )
        .is_ok());
    }

    #[test]
    fn validate_args_default_impl_compiles() {
        struct X;
        impl ValidateArgs for X {}
        assert!(X.validate().is_ok());
    }

    #[test]
    fn validate_args_custom_impl_surfaces_error() {
        struct Y {
            limit: u32,
        }
        impl ValidateArgs for Y {
            fn validate(&self) -> Result<()> {
                check_range("limit", self.limit as f64, Some(1.0), Some(50.0))
            }
        }
        assert!(Y { limit: 10 }.validate().is_ok());
        assert_validation_err(Y { limit: 100 }.validate(), "maximum");
    }

    #[test]
    fn format_as_str_returns_canonical_names() {
        assert_eq!(Format::Email.as_str(), "email");
        assert_eq!(Format::DateTime.as_str(), "date-time");
        assert_eq!(Format::Uri.as_str(), "uri");
    }

    #[test]
    fn length_with_no_bounds_accepts_anything() {
        assert!(check_length("x", 0, None, None).is_ok());
        assert!(check_length("x", 1_000_000, None, None).is_ok());
    }

    #[test]
    fn enum_rejects_empty_string_when_not_listed() {
        assert_validation_err(check_enum("x", "", &["a", "b"]), "must be one of");
    }

    #[test]
    fn length_uses_unicode_char_count_contract() {
        // 5 Japanese chars = 15 UTF-8 bytes — the doc contract says callers
        // use .chars().count(), so these tests encode the call-site expectation.
        let s = "こんにちは";
        assert_eq!(s.chars().count(), 5);
        assert!(check_length("greeting", s.chars().count(), Some(1), Some(5)).is_ok());
        assert_validation_err(
            check_length("greeting", s.chars().count(), Some(1), Some(4)),
            "maximum",
        );
    }
}