kkachi 0.1.8

High-performance, zero-copy library for optimizing language model prompts and programs
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
// Copyright © 2025 lituus-io <spicyzhug@gmail.com>
// All Rights Reserved.
// Licensed under PolyForm Noncommercial 1.0.0

//! Stack-allocated check builder for heuristic validation.
//!
//! The [`Checks`] builder provides a fluent API for building heuristic validators
//! that check for required patterns, forbidden patterns, length constraints, etc.
//!
//! # Examples
//!
//! ```
//! use kkachi::recursive::checks;
//!
//! let v = checks()
//!     .require("fn ")
//!     .require("->")
//!     .forbid(".unwrap()")
//!     .min_len(20);
//! ```

use crate::recursive::validate::{Score, Validate};
use regex::Regex;
use smallvec::SmallVec;
use std::sync::OnceLock;

/// Create a new checks builder.
///
/// This is the entry point for building heuristic validators.
#[inline]
pub fn checks() -> Checks {
    Checks::new()
}

/// Kind of check to perform.
#[derive(Clone)]
pub enum CheckKind {
    /// Require a substring pattern.
    Require(String),
    /// Forbid a substring pattern.
    Forbid(String),
    /// Require a regex pattern match.
    Regex(String, OnceLock<Regex>),
    /// Minimum length requirement.
    MinLen(usize),
    /// Maximum length requirement.
    MaxLen(usize),
    /// Maximum error count (for output containing error lines).
    MaxErrors(usize),
    /// Custom predicate.
    Predicate(fn(&str) -> bool, &'static str),
}

/// A single check with its metadata.
#[derive(Clone)]
pub struct Check {
    name: &'static str,
    kind: CheckKind,
    weight: f64,
    feedback: String,
}

/// Fluent builder for heuristic validation checks.
///
/// This builder accumulates checks and implements [`Validate`] to score
/// text based on how many checks pass. Weights determine the contribution
/// of each check to the final score.
///
/// # Stack Allocation
///
/// Checks are stored in a SmallVec with inline capacity for common cases,
/// avoiding heap allocation for typical usage patterns.
#[derive(Clone)]
pub struct Checks {
    checks: SmallVec<[Check; 8]>,
    total_weight: f64,
}

impl Default for Checks {
    fn default() -> Self {
        Self::new()
    }
}

impl Checks {
    /// Create a new empty checks builder.
    pub fn new() -> Self {
        Self {
            checks: SmallVec::new(),
            total_weight: 0.0,
        }
    }

    /// Add a check with the specified weight.
    fn add_check(mut self, check: Check) -> Self {
        self.total_weight += check.weight;
        self.checks.push(check);
        self
    }

    /// Require a substring pattern to be present.
    ///
    /// The check fails if the text does not contain the pattern.
    pub fn require(self, pattern: impl Into<String>) -> Self {
        let pattern = pattern.into();
        let feedback = format!("Missing required: '{}'", pattern);
        self.add_check(Check {
            name: "require",
            kind: CheckKind::Require(pattern),
            weight: 1.0,
            feedback,
        })
    }

    /// Require a substring pattern with custom weight.
    pub fn require_weighted(self, pattern: impl Into<String>, weight: f64) -> Self {
        let pattern = pattern.into();
        let feedback = format!("Missing required: '{}'", pattern);
        self.add_check(Check {
            name: "require",
            kind: CheckKind::Require(pattern),
            weight,
            feedback,
        })
    }

    /// Require multiple substring patterns to be present.
    ///
    /// Equivalent to calling `.require()` for each pattern.
    pub fn require_all<I, S>(mut self, patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        for pattern in patterns {
            self = self.require(pattern);
        }
        self
    }

    /// Require multiple substring patterns with custom weight.
    pub fn require_all_weighted<I, S>(mut self, patterns: I, weight: f64) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        for pattern in patterns {
            self = self.require_weighted(pattern, weight);
        }
        self
    }

    /// Forbid a substring pattern.
    ///
    /// The check fails if the text contains the pattern.
    pub fn forbid(self, pattern: impl Into<String>) -> Self {
        let pattern = pattern.into();
        let feedback = format!("Must not contain: '{}'", pattern);
        self.add_check(Check {
            name: "forbid",
            kind: CheckKind::Forbid(pattern),
            weight: 1.0,
            feedback,
        })
    }

    /// Forbid a substring pattern with custom weight.
    pub fn forbid_weighted(self, pattern: impl Into<String>, weight: f64) -> Self {
        let pattern = pattern.into();
        let feedback = format!("Must not contain: '{}'", pattern);
        self.add_check(Check {
            name: "forbid",
            kind: CheckKind::Forbid(pattern),
            weight,
            feedback,
        })
    }

    /// Forbid multiple substring patterns.
    ///
    /// Equivalent to calling `.forbid()` for each pattern.
    pub fn forbid_all<I, S>(mut self, patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        for pattern in patterns {
            self = self.forbid(pattern);
        }
        self
    }

    /// Forbid multiple substring patterns with custom weight.
    pub fn forbid_all_weighted<I, S>(mut self, patterns: I, weight: f64) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        for pattern in patterns {
            self = self.forbid_weighted(pattern, weight);
        }
        self
    }

    /// Require a regex pattern to match.
    ///
    /// The regex is lazily compiled on first use.
    pub fn regex(self, pattern: impl Into<String>) -> Self {
        let pattern = pattern.into();
        let feedback = format!("Regex not matched: '{}'", pattern);
        self.add_check(Check {
            name: "regex",
            kind: CheckKind::Regex(pattern, OnceLock::new()),
            weight: 1.0,
            feedback,
        })
    }

    /// Require a regex pattern with custom weight.
    pub fn regex_weighted(self, pattern: impl Into<String>, weight: f64) -> Self {
        let pattern = pattern.into();
        let feedback = format!("Regex not matched: '{}'", pattern);
        self.add_check(Check {
            name: "regex",
            kind: CheckKind::Regex(pattern, OnceLock::new()),
            weight,
            feedback,
        })
    }

    /// Require multiple regex patterns to match.
    ///
    /// Equivalent to calling `.regex()` for each pattern.
    pub fn regex_all<I, S>(mut self, patterns: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        for pattern in patterns {
            self = self.regex(pattern);
        }
        self
    }

    /// Require multiple regex patterns with custom weight.
    pub fn regex_all_weighted<I, S>(mut self, patterns: I, weight: f64) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        for pattern in patterns {
            self = self.regex_weighted(pattern, weight);
        }
        self
    }

    /// Require minimum text length.
    pub fn min_len(self, n: usize) -> Self {
        self.add_check(Check {
            name: "min_len",
            kind: CheckKind::MinLen(n),
            weight: 1.0,
            feedback: format!("Text too short (min {} chars)", n),
        })
    }

    /// Require minimum text length with custom weight.
    pub fn min_len_weighted(self, n: usize, weight: f64) -> Self {
        self.add_check(Check {
            name: "min_len",
            kind: CheckKind::MinLen(n),
            weight,
            feedback: format!("Text too short (min {} chars)", n),
        })
    }

    /// Require maximum text length.
    pub fn max_len(self, n: usize) -> Self {
        self.add_check(Check {
            name: "max_len",
            kind: CheckKind::MaxLen(n),
            weight: 1.0,
            feedback: format!("Text too long (max {} chars)", n),
        })
    }

    /// Require maximum text length with custom weight.
    pub fn max_len_weighted(self, n: usize, weight: f64) -> Self {
        self.add_check(Check {
            name: "max_len",
            kind: CheckKind::MaxLen(n),
            weight,
            feedback: format!("Text too long (max {} chars)", n),
        })
    }

    /// Limit the number of error-like lines.
    ///
    /// Counts lines containing "error", "Error", or "ERROR".
    pub fn max_errors(self, n: usize) -> Self {
        self.add_check(Check {
            name: "max_errors",
            kind: CheckKind::MaxErrors(n),
            weight: 1.0,
            feedback: format!("Too many error lines (max {})", n),
        })
    }

    /// Add a custom predicate check.
    ///
    /// The predicate receives the text and returns true if it passes.
    pub fn pred(self, name: &'static str, f: fn(&str) -> bool) -> Self {
        self.add_check(Check {
            name,
            kind: CheckKind::Predicate(f, name),
            weight: 1.0,
            feedback: format!("Predicate failed: '{}'", name),
        })
    }

    /// Add a custom predicate check with custom weight.
    pub fn pred_weighted(self, name: &'static str, f: fn(&str) -> bool, weight: f64) -> Self {
        self.add_check(Check {
            name,
            kind: CheckKind::Predicate(f, name),
            weight,
            feedback: format!("Predicate failed: '{}'", name),
        })
    }

    /// Set the weight for the most recently added check.
    ///
    /// # Panics
    ///
    /// Panics if no checks have been added yet.
    pub fn weight(mut self, w: f64) -> Self {
        if let Some(check) = self.checks.last_mut() {
            self.total_weight -= check.weight;
            check.weight = w;
            self.total_weight += w;
        }
        self
    }

    /// Set custom feedback for the most recently added check.
    pub fn feedback(mut self, msg: impl Into<String>) -> Self {
        if let Some(check) = self.checks.last_mut() {
            check.feedback = msg.into();
        }
        self
    }

    /// Conditionally require a substring pattern.
    pub fn require_if(self, cond: bool, pattern: impl Into<String>) -> Self {
        if cond {
            self.require(pattern)
        } else {
            self
        }
    }

    /// Conditionally forbid a substring pattern.
    pub fn forbid_if(self, cond: bool, pattern: impl Into<String>) -> Self {
        if cond {
            self.forbid(pattern)
        } else {
            self
        }
    }

    // =========================================================================
    // Language presets
    // =========================================================================

    /// Preset checks for Python code.
    pub fn python(self) -> Self {
        self.require("def ")
            .forbid("SyntaxError")
            .forbid("IndentationError")
    }

    /// Preset checks for Rust code.
    pub fn rust(self) -> Self {
        self.require("fn ")
            .forbid("todo!()")
            .forbid("unimplemented!()")
    }

    /// Preset checks for valid JSON.
    pub fn json(self) -> Self {
        self.pred("valid_json", |s| {
            serde_json::from_str::<serde_json::Value>(s).is_ok()
        })
    }

    /// Preset checks for YAML structure.
    pub fn yaml(self) -> Self {
        self.forbid("\t").pred("yaml_structure", |s| {
            // Basic check: has key: value pairs or list items
            s.lines()
                .any(|l| l.contains(": ") || l.trim_start().starts_with("- "))
        })
    }

    /// Preset checks for SQL statements.
    pub fn sql(self) -> Self {
        self.pred("sql_keyword", |s| {
            let upper = s.to_uppercase();
            upper.contains("SELECT")
                || upper.contains("INSERT")
                || upper.contains("UPDATE")
                || upper.contains("DELETE")
                || upper.contains("CREATE")
                || upper.contains("ALTER")
        })
    }

    /// Evaluate a single check against the text.
    fn evaluate_check(check: &Check, text: &str) -> bool {
        match &check.kind {
            CheckKind::Require(pattern) => text.contains(pattern.as_str()),
            CheckKind::Forbid(pattern) => !text.contains(pattern.as_str()),
            CheckKind::Regex(pattern, compiled) => {
                let regex = compiled.get_or_init(|| {
                    Regex::new(pattern).unwrap_or_else(|_| Regex::new("^$").unwrap())
                });
                regex.is_match(text)
            }
            CheckKind::MinLen(n) => text.len() >= *n,
            CheckKind::MaxLen(n) => text.len() <= *n,
            CheckKind::MaxErrors(n) => {
                let count = text
                    .lines()
                    .filter(|line| {
                        line.contains("error") || line.contains("Error") || line.contains("ERROR")
                    })
                    .count();
                count <= *n
            }
            CheckKind::Predicate(f, _) => f(text),
        }
    }
}

impl Validate for Checks {
    fn validate(&self, text: &str) -> Score<'static> {
        if self.checks.is_empty() {
            return Score::pass();
        }

        let mut weighted_sum = 0.0;
        let mut failed_checks = Vec::new();
        let mut breakdown = SmallVec::new();

        for check in &self.checks {
            let passed = Self::evaluate_check(check, text);
            let check_score = if passed { 1.0 } else { 0.0 };
            weighted_sum += check_score * check.weight;
            breakdown.push((check.name, check_score));

            if !passed {
                failed_checks.push(check.feedback.as_str());
            }
        }

        let final_score = if self.total_weight > 0.0 {
            weighted_sum / self.total_weight
        } else {
            1.0
        };

        if failed_checks.is_empty() {
            Score::pass().with_breakdown(breakdown)
        } else {
            let feedback = failed_checks.join("; ");
            Score::with_feedback(final_score, feedback).with_breakdown(breakdown)
        }
    }

    fn name(&self) -> &'static str {
        "checks"
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_empty_checks() {
        let v = checks();
        let score = v.validate("anything");
        assert!(score.is_perfect());
    }

    #[test]
    fn test_require() {
        let v = checks().require("fn ");
        assert!(v.validate("fn main() {}").is_perfect());
        assert!(!v.validate("let x = 1").is_perfect());
    }

    #[test]
    fn test_forbid() {
        let v = checks().forbid(".unwrap()");
        assert!(v.validate("let x = 1").is_perfect());
        assert!(!v.validate("x.unwrap()").is_perfect());
    }

    #[test]
    fn test_min_len() {
        let v = checks().min_len(10);
        assert!(v.validate("hello world").is_perfect()); // 11 chars
        assert!(!v.validate("hello").is_perfect()); // 5 chars
    }

    #[test]
    fn test_max_len() {
        let v = checks().max_len(10);
        assert!(v.validate("hello").is_perfect()); // 5 chars
        assert!(!v.validate("hello world").is_perfect()); // 11 chars
    }

    #[test]
    fn test_regex() {
        let v = checks().regex(r"fn\s+\w+");
        assert!(v.validate("fn main() {}").is_perfect());
        assert!(!v.validate("let x = 1").is_perfect());
    }

    #[test]
    fn test_max_errors() {
        let v = checks().max_errors(1);
        assert!(v.validate("line1\nline2").is_perfect());
        assert!(v.validate("error: one\nline2").is_perfect()); // 1 error
        assert!(!v.validate("error: one\nerror: two").is_perfect()); // 2 errors
    }

    #[test]
    fn test_pred() {
        let v = checks().pred("has_return", |s| s.contains("return"));
        assert!(v.validate("return 42;").is_perfect());
        assert!(!v.validate("let x = 42;").is_perfect());
    }

    #[test]
    fn test_weighted_checks() {
        let v = checks()
            .require_weighted("fn ", 0.5)
            .require_weighted("->", 0.5);

        // Both pass -> 1.0
        let score = v.validate("fn foo() -> i32 {}");
        assert!((score.value - 1.0).abs() < f64::EPSILON);

        // Only fn passes -> 0.5
        let score = v.validate("fn foo() {}");
        assert!((score.value - 0.5).abs() < f64::EPSILON);

        // Neither passes -> 0.0
        let score = v.validate("let x = 1");
        assert!((score.value - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_weight_modifier() {
        let v = checks()
            .require("fn ")
            .weight(2.0)
            .require("->")
            .weight(1.0);

        // fn passes (2.0), -> fails (0) -> 2.0/3.0
        let score = v.validate("fn foo() {}");
        assert!((score.value - 2.0 / 3.0).abs() < 0.01);
    }

    #[test]
    fn test_breakdown() {
        let v = checks().require("fn ").forbid(".unwrap()");

        let score = v.validate("fn foo() { x.unwrap() }");
        assert!(score.breakdown.is_some());

        let breakdown = score.breakdown.unwrap();
        assert_eq!(breakdown.len(), 2);
        assert_eq!(breakdown[0], ("require", 1.0)); // fn passes
        assert_eq!(breakdown[1], ("forbid", 0.0)); // unwrap fails
    }

    #[test]
    fn test_combined_checks() {
        let v = checks()
            .require("fn ")
            .require("->")
            .forbid(".unwrap()")
            .forbid("panic!")
            .min_len(20);

        // All pass
        let code = "fn parse(s: &str) -> Option<i32> { s.parse().ok() }";
        let score = v.validate(code);
        assert!(score.is_perfect());

        // Has unwrap
        let code = "fn parse(s: &str) -> i32 { s.parse().unwrap() }";
        let score = v.validate(code);
        assert!(score.value < 1.0);
    }

    #[test]
    fn test_feedback_modifier() {
        let v = checks().require("fn ").feedback("Missing function keyword");

        let score = v.validate("let x = 1");
        assert_eq!(score.feedback_str(), Some("Missing function keyword"));
    }

    #[test]
    fn test_require_all() {
        let v = checks().require_all(["fn ", "-> i32", "pub"]);

        let score = v.validate("pub fn add(a: i32, b: i32) -> i32 { a + b }");
        assert!(score.is_perfect());

        let score = v.validate("fn add(a: i32, b: i32) -> i32 { a + b }");
        assert!(!score.is_perfect()); // missing "pub"
    }

    #[test]
    fn test_forbid_all() {
        let v = checks().forbid_all([".unwrap()", "panic!", "todo!"]);

        let score = v.validate("fn safe() -> i32 { 42 }");
        assert!(score.is_perfect());

        let score = v.validate("fn bad() { panic!(\"oh no\") }");
        assert!(!score.is_perfect());
    }

    #[test]
    fn test_regex_all() {
        let v = checks().regex_all([r"fn \w+", r"-> \w+"]);

        let score = v.validate("fn add(a: i32) -> i32 { a + 1 }");
        assert!(score.is_perfect());

        let score = v.validate("let x = 42;");
        assert!(!score.is_perfect());
    }

    #[test]
    fn test_batch_with_vec() {
        let patterns: Vec<String> = vec!["fn ".to_string(), "pub ".to_string()];
        let v = checks().require_all(patterns);

        let score = v.validate("pub fn test() {}");
        assert!(score.is_perfect());
    }

    #[test]
    fn test_batch_empty_iterator() {
        let v = checks().require_all(Vec::<String>::new()).require("fn ");

        let score = v.validate("fn test() {}");
        assert!(score.is_perfect());
    }

    #[test]
    fn test_batch_mixed_with_individual() {
        let v = checks()
            .require_all(["fn ", "-> i32"])
            .forbid_all([".unwrap()", "panic!"])
            .min_len(10);

        let score = v.validate("fn add(a: i32, b: i32) -> i32 { a + b }");
        assert!(score.is_perfect());
    }

    #[test]
    fn test_batch_weighted() {
        let v = checks()
            .require_all_weighted(["fn ", "pub "], 0.5)
            .forbid_all_weighted(["unsafe", "unwrap"], 2.0);

        let score = v.validate("pub fn safe() -> i32 { 42 }");
        assert!(score.is_perfect());
    }
}