reasonkit-core 0.1.8

The Reasoning Engine — Auditable Reasoning for Production AI | Rust-Native | Turn Prompts into Protocols
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
//! Composite Instruction Constraints for MiniMax M2
//!
//! Implements M2's composite instruction constraints including:
//! - System Prompts
//! - User Queries
//! - Memory Context
//! - Tool Schemas
//!
//! Single-violation-failure scoring for robust constraint management.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Composite instruction constraint types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CompositeInstruction {
    SystemPrompt(SystemPrompt),
    UserQuery(UserQuery),
    MemoryContext(MemoryContext),
    ToolSchema(ToolSchema),
}

/// System prompt constraint with validation rules
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemPrompt {
    pub template: String,
    pub constraints: Vec<PromptConstraint>,
    pub variables: HashMap<String, String>,
    pub token_limit: Option<u32>,
}

/// User query constraint with preprocessing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserQuery {
    pub raw_text: String,
    pub sanitized_text: String,
    pub intent: QueryIntent,
    pub complexity_score: f64,
    pub required_tools: Vec<String>,
}

/// Memory context constraint with retention rules
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryContext {
    pub context_id: String,
    pub content: String,
    pub relevance_score: f64,
    pub retention_policy: RetentionPolicy,
    pub dependencies: Vec<String>,
}

/// Tool schema constraint with validation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolSchema {
    pub tool_name: String,
    pub input_schema: SchemaDefinition,
    pub output_schema: SchemaDefinition,
    pub constraints: Vec<FieldConstraint>,
}

/// Prompt constraint validation types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PromptConstraint {
    MaxTokens(u32),
    MinConfidence(f64),
    RequiredKeywords(Vec<String>),
    ForbiddenKeywords(Vec<String>),
    StyleGuide(String),
}

/// Query intent classification
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum QueryIntent {
    Creative,
    Analytical,
    Verification,
    Decision,
    Explanation,
    Critique,
}

/// Memory retention policy
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RetentionPolicy {
    Session,
    ShortTerm(u32), // minutes
    LongTerm(u32),  // days
    Permanent,
}

/// Schema definition for tool inputs/outputs
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaDefinition {
    pub format: SchemaFormat,
    pub fields: Vec<SchemaField>,
    pub validation_rules: Vec<ValidationRule>,
}

/// Schema field definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SchemaField {
    pub name: String,
    pub field_type: FieldType,
    pub required: bool,
    pub constraints: Vec<FieldConstraint>,
}

/// Field constraint types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FieldConstraint {
    MinLength(u32),
    MaxLength(u32),
    Pattern(String),
    Enum(Vec<String>),
    Range(f64, f64),
}

/// Schema format types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SchemaFormat {
    JSON,
    XML,
    YAML,
    PlainText,
}

/// Field type definitions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FieldType {
    String,
    Integer,
    Float,
    Boolean,
    Array(Box<FieldType>),
    Object,
}

/// Validation rule for schemas
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationRule {
    pub rule_type: String,
    pub parameters: HashMap<String, serde_json::Value>,
    pub severity: ViolationSeverity,
}

/// Constraint violation tracking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConstraintViolation {
    pub instruction_type: String,
    pub violation_type: String,
    pub description: String,
    pub severity: ViolationSeverity,
    pub location: Option<String>,
}

/// Violation severity levels
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ViolationSeverity {
    Info,
    Warning,
    Error,
    Critical,
}

/// Single-violation-failure result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ConstraintResult {
    Passed(f64), // Score from 0.0 to 1.0
    Failed(Vec<ConstraintViolation>),
    Pending,
}

/// Constraint engine for M2 composite instructions
pub struct ConstraintEngine {
    constraints: HashMap<String, CompositeInstruction>,
    #[allow(dead_code)]
    violation_history: Vec<ConstraintViolation>,
    #[allow(dead_code)]
    performance_tracker: PerformanceTracker,
}

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

impl ConstraintEngine {
    /// Create new constraint engine
    pub fn new() -> Self {
        Self {
            constraints: HashMap::new(),
            violation_history: Vec::new(),
            performance_tracker: PerformanceTracker::new(),
        }
    }

    /// Add composite instruction constraint
    pub fn add_constraint(&mut self, id: String, instruction: CompositeInstruction) {
        self.constraints.insert(id, instruction);
    }

    /// Validate all constraints with single-violation-failure
    pub fn validate_all(&self, inputs: &ValidationInputs) -> ConstraintResult {
        let mut violations = Vec::new();
        let mut total_score = 1.0;

        // Validate system prompt constraints
        if let Some(system_prompt) = inputs.system_prompt.as_ref() {
            match self.validate_system_prompt(system_prompt) {
                Ok(score) => {
                    total_score *= score;
                }
                Err(violation) => {
                    if violation.severity == ViolationSeverity::Critical {
                        violations.push(violation);
                        return ConstraintResult::Failed(violations);
                    }
                    violations.push(violation);
                }
            }
        }

        // Validate user query constraints
        if let Some(user_query) = inputs.user_query.as_ref() {
            match self.validate_user_query(user_query) {
                Ok(score) => {
                    total_score *= score;
                }
                Err(violation) => {
                    if violation.severity == ViolationSeverity::Critical {
                        violations.push(violation);
                        return ConstraintResult::Failed(violations);
                    }
                    violations.push(violation);
                }
            }
        }

        // Validate memory context constraints
        if let Some(memory_context) = inputs.memory_context.as_ref() {
            match self.validate_memory_context(memory_context) {
                Ok(score) => {
                    total_score *= score;
                }
                Err(violation) => {
                    if violation.severity == ViolationSeverity::Critical {
                        violations.push(violation);
                        return ConstraintResult::Failed(violations);
                    }
                    violations.push(violation);
                }
            }
        }

        // Validate tool schema constraints
        for (tool_name, schema) in &inputs.tool_schemas {
            match self.validate_tool_schema(tool_name, schema) {
                Ok(score) => {
                    total_score *= score;
                }
                Err(violation) => {
                    if violation.severity == ViolationSeverity::Critical {
                        violations.push(violation);
                        return ConstraintResult::Failed(violations);
                    }
                    violations.push(violation);
                }
            }
        }

        if !violations.is_empty() {
            ConstraintResult::Failed(violations)
        } else {
            ConstraintResult::Passed(total_score)
        }
    }

    /// Validate system prompt constraints
    fn validate_system_prompt(&self, prompt: &SystemPrompt) -> Result<f64, ConstraintViolation> {
        let mut score = 1.0;

        // Check token limit
        if let Some(limit) = prompt.token_limit {
            let token_count = self.count_tokens(&prompt.template);
            if token_count > limit {
                return Err(ConstraintViolation {
                    instruction_type: "SystemPrompt".to_string(),
                    violation_type: "TokenLimitExceeded".to_string(),
                    description: format!("Prompt exceeds token limit: {} > {}", token_count, limit),
                    severity: ViolationSeverity::Error,
                    location: Some("template".to_string()),
                });
            }
            score *= 0.9; // Penalize for being close to limit
        }

        // Check required keywords
        for constraint in &prompt.constraints {
            match constraint {
                PromptConstraint::RequiredKeywords(keywords) => {
                    for keyword in keywords {
                        if !prompt
                            .template
                            .to_lowercase()
                            .contains(&keyword.to_lowercase())
                        {
                            return Err(ConstraintViolation {
                                instruction_type: "SystemPrompt".to_string(),
                                violation_type: "MissingRequiredKeyword".to_string(),
                                description: format!("Required keyword '{}' not found", keyword),
                                severity: ViolationSeverity::Warning,
                                location: Some("template".to_string()),
                            });
                        }
                    }
                }
                PromptConstraint::ForbiddenKeywords(keywords) => {
                    for keyword in keywords {
                        if prompt
                            .template
                            .to_lowercase()
                            .contains(&keyword.to_lowercase())
                        {
                            return Err(ConstraintViolation {
                                instruction_type: "SystemPrompt".to_string(),
                                violation_type: "ForbiddenKeyword".to_string(),
                                description: format!("Forbidden keyword '{}' found", keyword),
                                severity: ViolationSeverity::Error,
                                location: Some("template".to_string()),
                            });
                        }
                    }
                }
                _ => {} // Other constraints handled elsewhere
            }
        }

        Ok(score)
    }

    /// Validate user query constraints
    fn validate_user_query(&self, query: &UserQuery) -> Result<f64, ConstraintViolation> {
        let mut score = 1.0;

        // Check complexity score
        if query.complexity_score > 1.0 {
            return Err(ConstraintViolation {
                instruction_type: "UserQuery".to_string(),
                violation_type: "ComplexityTooHigh".to_string(),
                description: format!(
                    "Query complexity score too high: {}",
                    query.complexity_score
                ),
                severity: ViolationSeverity::Warning,
                location: None,
            });
        }

        // Check for required tools
        for tool in &query.required_tools {
            if !self.is_tool_available(tool) {
                return Err(ConstraintViolation {
                    instruction_type: "UserQuery".to_string(),
                    violation_type: "UnavailableTool".to_string(),
                    description: format!("Required tool '{}' not available", tool),
                    severity: ViolationSeverity::Critical,
                    location: None,
                });
            }
        }

        // Check sanitization
        if query.raw_text != query.sanitized_text {
            score *= 0.8; // Penalize for needing sanitization
        }

        Ok(score)
    }

    /// Validate memory context constraints
    fn validate_memory_context(&self, context: &MemoryContext) -> Result<f64, ConstraintViolation> {
        let score = 1.0;

        // Check relevance score
        if context.relevance_score < 0.3 {
            return Err(ConstraintViolation {
                instruction_type: "MemoryContext".to_string(),
                violation_type: "LowRelevance".to_string(),
                description: format!(
                    "Memory context relevance too low: {}",
                    context.relevance_score
                ),
                severity: ViolationSeverity::Warning,
                location: None,
            });
        }

        // Check retention policy compatibility
        if let RetentionPolicy::Permanent = &context.retention_policy {
            // Permanent memory should have high relevance
            if context.relevance_score < 0.8 {
                return Err(ConstraintViolation {
                    instruction_type: "MemoryContext".to_string(),
                    violation_type: "PermanentMemoryLowRelevance".to_string(),
                    description: "Permanent memory must have high relevance".to_string(),
                    severity: ViolationSeverity::Error,
                    location: None,
                });
            }
        }

        Ok(score)
    }

    /// Validate tool schema constraints
    fn validate_tool_schema(
        &self,
        tool_name: &str,
        schema: &ToolSchema,
    ) -> Result<f64, ConstraintViolation> {
        let score = 1.0;

        // Validate input schema against field constraints
        for constraint in &schema.constraints {
            // Each FieldConstraint applies to the schema as a whole
            if !self.validate_field_constraint(&schema.input_schema, constraint) {
                return Err(ConstraintViolation {
                    instruction_type: "ToolSchema".to_string(),
                    violation_type: "SchemaValidationFailed".to_string(),
                    description: format!(
                        "Schema validation failed for tool {} with constraint {:?}",
                        tool_name, constraint
                    ),
                    severity: ViolationSeverity::Error,
                    location: Some("input_schema".to_string()),
                });
            }
        }

        Ok(score)
    }

    /// Helper methods
    fn count_tokens(&self, text: &str) -> u32 {
        // Simple token counting - in real implementation, use proper tokenizer
        text.split_whitespace().count() as u32
    }

    fn is_tool_available(&self, tool_name: &str) -> bool {
        // Check if tool is available in the current context
        // This would integrate with the actual tool registry
        matches!(
            tool_name,
            "gigathink" | "laserlogic" | "bedrock" | "proofguard" | "brutalhonesty"
        )
    }

    #[allow(dead_code)]
    fn validate_schema_rule(&self, _schema: &SchemaDefinition, _rule: &ValidationRule) -> bool {
        // Implement schema rule validation
        // This would check actual data against the schema rules
        true // Placeholder
    }

    fn validate_field_constraint(
        &self,
        schema: &SchemaDefinition,
        constraint: &FieldConstraint,
    ) -> bool {
        // Validate schema against field constraints
        match constraint {
            FieldConstraint::MinLength(min) => {
                schema.fields.iter().all(|f| f.name.len() >= *min as usize)
            }
            FieldConstraint::MaxLength(max) => {
                schema.fields.iter().all(|f| f.name.len() <= *max as usize)
            }
            FieldConstraint::Pattern(_pattern) => true, // Would need regex validation
            FieldConstraint::Enum(_values) => true,     // Would check if values are in enum
            FieldConstraint::Range(_min, _max) => true, // Would check numeric ranges
        }
    }
}

/// Input data for constraint validation
#[derive(Debug, Clone)]
pub struct ValidationInputs<'a> {
    pub system_prompt: Option<&'a SystemPrompt>,
    pub user_query: Option<&'a UserQuery>,
    pub memory_context: Option<&'a MemoryContext>,
    pub tool_schemas: HashMap<&'a str, &'a ToolSchema>,
}

impl<'a> Default for ValidationInputs<'a> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a> ValidationInputs<'a> {
    pub fn new() -> Self {
        Self {
            system_prompt: None,
            user_query: None,
            memory_context: None,
            tool_schemas: HashMap::new(),
        }
    }

    pub fn with_system_prompt(mut self, prompt: &'a SystemPrompt) -> Self {
        self.system_prompt = Some(prompt);
        self
    }

    pub fn with_user_query(mut self, query: &'a UserQuery) -> Self {
        self.user_query = Some(query);
        self
    }

    pub fn with_memory_context(mut self, context: &'a MemoryContext) -> Self {
        self.memory_context = Some(context);
        self
    }

    pub fn add_tool_schema(mut self, name: &'a str, schema: &'a ToolSchema) -> Self {
        self.tool_schemas.insert(name, schema);
        self
    }
}

/// Performance tracking for constraint engine
pub struct PerformanceTracker {
    total_validations: u64,
    successful_validations: u64,
    average_score: f64,
}

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

impl PerformanceTracker {
    pub fn new() -> Self {
        Self {
            total_validations: 0,
            successful_validations: 0,
            average_score: 1.0,
        }
    }

    pub fn record_validation(&mut self, result: &ConstraintResult) {
        self.total_validations += 1;

        if let ConstraintResult::Passed(score) = result {
            self.successful_validations += 1;
            self.average_score = (self.average_score * (self.total_validations - 1) as f64 + score)
                / self.total_validations as f64;
        }
    }

    pub fn get_success_rate(&self) -> f64 {
        if self.total_validations > 0 {
            self.successful_validations as f64 / self.total_validations as f64
        } else {
            0.0
        }
    }
}

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

    #[test]
    fn test_constraint_engine_creation() {
        let engine = ConstraintEngine::new();
        assert_eq!(engine.constraints.len(), 0);
    }

    #[test]
    fn test_system_prompt_validation() {
        let engine = ConstraintEngine::new();

        let prompt = SystemPrompt {
            template: "This is a test prompt with required keyword".to_string(),
            constraints: vec![PromptConstraint::RequiredKeywords(vec![
                "required".to_string()
            ])],
            variables: HashMap::new(),
            token_limit: Some(100),
        };

        let inputs = ValidationInputs::new().with_system_prompt(&prompt);
        let result = engine.validate_all(&inputs);

        match result {
            ConstraintResult::Passed(_) => {
                // Should pass with required keyword
            }
            ConstraintResult::Failed(violations) => {
                panic!("Unexpected validation failure: {:?}", violations);
            }
            ConstraintResult::Pending => panic!("Expected immediate result"),
        }
    }

    #[test]
    fn test_single_violation_failure() {
        let engine = ConstraintEngine::new();

        let prompt = SystemPrompt {
            template: "Forbidden word here".to_string(),
            constraints: vec![PromptConstraint::ForbiddenKeywords(vec![
                "forbidden".to_string()
            ])],
            variables: HashMap::new(),
            token_limit: None,
        };

        let inputs = ValidationInputs::new().with_system_prompt(&prompt);
        let result = engine.validate_all(&inputs);

        match result {
            ConstraintResult::Failed(violations) => {
                assert_eq!(violations.len(), 1);
                assert_eq!(violations[0].violation_type, "ForbiddenKeyword");
            }
            _ => panic!("Expected failure for forbidden keyword"),
        }
    }
}