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
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
# LaserLogic Module API Documentation

Version: 3.0.0

The LaserLogic module performs rigorous logical analysis with first-order logic
translation, formal fallacy detection, and argument structure validation.

## Table of Contents

1. [Module Overview]#module-overview
2. [Configuration]#configuration
3. [Core Types]#core-types
4. [Methods]#methods
5. [Usage Examples]#usage-examples
6. [Error Handling]#error-handling

## Module Overview

LaserLogic applies precision deductive reasoning to validate arguments and detect
logical fallacies. It translates natural language to formal logic, checks validity
and soundness, and identifies common reasoning errors.

Key capabilities:
- First-order logic (FOL) translation and validation
- Formal fallacy detection (10+ types)
- Argument structure validation
- Syllogism analysis
- Contradiction detection
- Confidence scoring based on logical rigor

## Configuration

### LaserLogicConfig

Configuration struct controlling LaserLogic analysis depth and features.

```rust
pub struct LaserLogicConfig {
    pub detect_fallacies: bool,
    pub check_validity: bool,
    pub check_soundness: bool,
    pub max_premise_depth: usize,
    pub analyze_syllogisms: bool,
    pub detect_contradictions: bool,
    pub confidence_threshold: f64,
    pub verbose_output: bool,
}
```

#### Fields

| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `detect_fallacies` | `bool` | Yes | `true` | Enable detection of logical fallacies. Improves argument quality. |
| `check_validity` | `bool` | Yes | `true` | Enable validity checking (conclusion follows from premises). Core functionality. |
| `check_soundness` | `bool` | Yes | `true` | Enable soundness checking (valid + true premises). Comprehensive validation. |
| `max_premise_depth` | `usize` | Yes | `10` | Maximum number of premises to analyze. Prevents complexity overload. |
| `analyze_syllogisms` | `bool` | Yes | `true` | Enable syllogism detection and analysis. Handles classical logic forms. |
| `detect_contradictions` | `bool` | Yes | `true` | Enable contradiction detection. Ensures logical consistency. |
| `confidence_threshold` | `f64` | Yes | `0.7` | Minimum confidence threshold for conclusions. Range: 0.0-1.0. |
| `verbose_output` | `bool` | Yes | `false` | Enable verbose output with reasoning steps. Useful for debugging. |

#### Implementation

```rust
impl Default for LaserLogicConfig {
    fn default() -> Self {
        Self {
            detect_fallacies: true,
            check_validity: true,
            check_soundness: true,
            max_premise_depth: 10,
            analyze_syllogisms: true,
            detect_contradictions: true,
            confidence_threshold: 0.7,
            verbose_output: false,
        }
    }
}

impl LaserLogicConfig {
    /// Quick check mode - validity and basic fallacy detection only
    pub fn quick() -> Self {
        Self {
            detect_fallacies: true,
            check_validity: true,
            check_soundness: false,
            max_premise_depth: 5,
            analyze_syllogisms: false,
            detect_contradictions: false,
            confidence_threshold: 0.6,
            verbose_output: false,
        }
    }

    /// Deep analysis mode - all features enabled
    pub fn deep() -> Self {
        Self {
            detect_fallacies: true,
            check_validity: true,
            check_soundness: true,
            max_premise_depth: 20,
            analyze_syllogisms: true,
            detect_contradictions: true,
            confidence_threshold: 0.8,
            verbose_output: true,
        }
    }
}
```

## Core Types

### LaserLogic

Main module struct implementing the ThinkToolModule trait.

```rust
pub struct LaserLogic {
    config: ThinkToolModuleConfig,
    laser_config: LaserLogicConfig,
}
```

#### Fields

| Field | Type | Description |
|-------|------|-------------|
| `config` | `ThinkToolModuleConfig` | Standard module configuration metadata |
| `laser_config` | `LaserLogicConfig` | LaserLogic-specific configuration parameters |

### LaserLogicResult

Structured output from LaserLogic execution containing logical analysis.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LaserLogicResult {
    pub argument_form: Option<ArgumentForm>,
    pub validity_status: ValidityStatus,
    pub soundness_status: SoundnessStatus,
    pub premises: Vec<Premise>,
    pub fallacies: Vec<DetectedFallacy>,
    pub contradictions: Vec<Contradiction>,
    pub confidence: f64,
    pub analysis_steps: Option<Vec<String>>,
}
```

#### Fields

| Field | Type | Description |
|-------|------|-------------|
| `argument_form` | `Option<ArgumentForm>` | Identified argument structure |
| `validity_status` | `ValidityStatus` | Validity assessment |
| `soundness_status` | `SoundnessStatus` | Soundness assessment |
| `premises` | `Vec<Premise>` | Analyzed premises |
| `fallacies` | `Vec<DetectedFallacy>` | Detected logical fallacies |
| `contradictions` | `Vec<Contradiction>` | Found contradictions |
| `confidence` | `f64` | Overall confidence in analysis |
| `analysis_steps` | `Option<Vec<String>>` | Detailed reasoning steps (when verbose) |

### Premise

Individual premise in an argument with classification and confidence.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Premise {
    pub id: usize,
    pub text: String,
    pub r#type: PremiseType,
    pub confidence: f64,
    pub issues: Vec<String>,
    pub logical_form: Option<Formula>,
}
```

#### Fields

| Field | Type | Description |
|-------|------|-------------|
| `id` | `usize` | Unique identifier |
| `text` | `String` | Premise statement |
| `type` | `PremiseType` | Classification of premise |
| `confidence` | `f64` | Confidence in premise accuracy |
| `issues` | `Vec<String>` | Potential issues with premise |
| `logical_form` | `Option<Formula>` | First-order logic translation |

### PremiseType

Classification of premise types for targeted analysis.

```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PremiseType {
    Factual,      // Based on observable facts
    Definitional, // Clarifies terminology
    Assumptive,   // Assumed for argument's sake
    Inferential,  // Derived from other premises
    Normative,    // Value-based statements
    Conditional,  // If-then statements
}
```

### DetectedFallacy

Identification of logical fallacies with explanation and severity.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetectedFallacy {
    pub fallacy: Fallacy,
    pub premise_index: Option<usize>,
    pub description: String,
    pub severity: FlawSeverity,
    pub counter_example: Option<String>,
}
```

#### Fields

| Field | Type | Description |
|-------|------|-------------|
| `fallacy` | `Fallacy` | Type of logical fallacy |
| `premise_index` | `Option<usize>` | Which premise contains the fallacy |
| `description` | `String` | Explanation of the fallacy |
| `severity` | `FlawSeverity` | Seriousness of the fallacy |
| `counter_example` | `Option<String>` | Example showing why it's fallacious |

### Fallacy

Enumeration of detectable logical fallacies.

```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Fallacy {
    AdHominem,
    StrawMan,
    FalseDilemma,
    SlipperySlope,
    CircularReasoning,
    AppealToAuthority,
    HastyGeneralization,
    RedHerring,
    FalseCause,
    BeggingTheQuestion,
    Equivocation,
    AppealToEmotion,
}
```

### ArgumentForm

Classification of argument structures for specialized handling.

```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ArgumentForm {
    pub form_type: ArgumentFormType,
    pub major_premise: Option<usize>,
    pub minor_premise: Option<usize>,
    pub conclusion: Option<usize>,
}
```

#### Fields

| Field | Type | Description |
|-------|------|-------------|
| `form_type` | `ArgumentFormType` | Type of argument structure |
| `major_premise` | `Option<usize>` | Index of major premise |
| `minor_premise` | `Option<usize>` | Index of minor premise |
| `conclusion` | `Option<usize>` | Index of conclusion |

### ArgumentFormType

Types of recognized argument forms.

```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArgumentFormType {
    CategoricalSyllogism,
    HypotheticalSyllogism,
    DisjunctiveSyllogism,
    ModusPonens,
    ModusTollens,
    Enthymeme,
    Sorites,
}
```

### ValidityStatus

Assessment of whether conclusion logically follows from premises.

```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ValidityStatus {
    Valid,      // Conclusion follows logically
    Invalid,    // Conclusion does not follow
    Uncertain,  // Cannot determine validity
    Partial,    // Some parts valid, others not
}
```

### SoundnessStatus

Assessment combining validity with premise truth.

```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SoundnessStatus {
    Sound,      // Valid and true premises
    Unsound,    // Invalid or false premises
    Contested,  // Premise truth disputed
    Provisional, // Temporarily sound
}
```

### Contradiction

Logical contradiction between premises or with conclusion.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Contradiction {
    pub r#type: ContradictionType,
    pub premise_indices: Vec<usize>,
    pub description: String,
    pub severity: FlawSeverity,
}
```

#### Fields

| Field | Type | Description |
|-------|------|-------------|
| `type` | `ContradictionType` | Type of contradiction |
| `premise_indices` | `Vec<usize>` | Indices of contradictory premises |
| `description` | `String` | Explanation of contradiction |
| `severity` | `FlawSeverity` | Seriousness of contradiction |

### ContradictionType

Types of logical contradictions.

```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContradictionType {
    Direct,     // Explicit contradiction (A and not-A)
    Implicit,   // Indirect contradiction
    Temporal,   // Time-based inconsistency
    Modal,      // Possibility/necessity conflict
}
```

## Methods

### LaserLogic::new()

Create a new LaserLogic module with default configuration.

```rust
pub fn new() -> Self
```

Returns: `LaserLogic` instance with default settings.

Example:
```rust
let module = LaserLogic::new();
assert_eq!(module.name(), "LaserLogic");
assert_eq!(module.version(), "3.0.0");
```

### LaserLogic::with_config()

Create a new LaserLogic module with custom configuration.

```rust
pub fn with_config(config: LaserLogicConfig) -> Self
```

Parameters:
- `config`: `LaserLogicConfig` - Custom configuration parameters

Returns: `LaserLogic` instance with specified configuration.

Example:
```rust
let config = LaserLogicConfig::deep();
let module = LaserLogic::with_config(config);
```

### LaserLogic::analyze_argument()

Direct analysis of a logical argument with premises and conclusion.

```rust
pub fn analyze_argument(
    &self, 
    premises: &[&str], 
    conclusion: &str
) -> Result<LaserLogicResult>
```

Parameters:
- `premises`: `&[&str]` - Slice of premise statements
- `conclusion`: `&str` - Conclusion statement to evaluate

Returns: `Result<LaserLogicResult>` - Analysis results or error.

Example:
```rust
let module = LaserLogic::new();
let result = module.analyze_argument(
    &["All humans are mortal", "Socrates is human"],
    "Socrates is mortal"
)?;
```

### LaserLogic::execute()

Execute the LaserLogic module synchronously.

```rust
impl ThinkToolModule for LaserLogic {
    fn execute(&self, context: &ThinkToolContext) -> Result<ThinkToolOutput>
}
```

Parameters:
- `context`: `&ThinkToolContext` - Execution context with JSON argument data

Returns: `Result<ThinkToolOutput>` - Structured output or error.

Example:
```rust
let module = LaserLogic::new();
let context = ThinkToolContext::new(r#"{
    "premises": ["All birds can fly", "Penguins are birds"],
    "conclusion": "Penguins can fly"
}"#);
let result = module.execute(&context)?;
```

### LaserLogic::config()

Get the module configuration.

```rust
pub fn config(&self) -> &LaserLogicConfig
```

Returns: `&LaserLogicConfig` - Reference to current configuration.

Example:
```rust
let module = LaserLogic::new();
let config = module.config();
assert!(config.detect_fallacies);
```

## Usage Examples

### Basic Argument Analysis

```rust
use reasonkit::thinktool::modules::{LaserLogic, ThinkToolContext, ThinkToolModule};

// Create module with default settings
let module = LaserLogic::new();

// Direct argument analysis
let result = module.analyze_argument(
    &["All mammals are warm-blooded", "Whales are mammals"],
    "Whales are warm-blooded"
)?;

// Check validity
match result.validity_status {
    ValidityStatus::Valid => println!("Argument is logically valid"),
    ValidityStatus::Invalid => println!("Argument contains logical errors"),
    _ => println!("Validity uncertain"),
}

// Check for fallacies
if !result.fallacies.is_empty() {
    println!("Found {} fallacies:", result.fallacies.len());
    for fallacy in &result.fallacies {
        println!("- {}: {}", fallacy.fallacy, fallacy.description);
    }
}
```

### JSON Context-Based Execution

```rust
use reasonkit::thinktool::modules::{LaserLogic, ThinkToolContext, ThinkToolModule};

// Create module with custom configuration
let module = LaserLogic::with_config(
    LaserLogicConfig::quick()
);

// Prepare JSON context
let context = ThinkToolContext::new(r#"{
    "premises": [
        "If it rains, then the ground gets wet",
        "The ground is wet"
    ],
    "conclusion": "It rained"
}"#);

// Execute analysis
let result = module.execute(&context)?;

// Access fallacy detection
let fallacies = result.get_array("fallacies").unwrap();
if !fallacies.is_empty() {
    println!("Detected fallacy: Affirming the consequent");
}
```

### Deep Analysis Configuration

```rust
use reasonkit::thinktool::modules::{LaserLogic, LaserLogicConfig, ThinkToolContext};

// Configure for comprehensive analysis
let config = LaserLogicConfig {
    max_premise_depth: 15,
    analyze_syllogisms: true,
    detect_contradictions: true,
    verbose_output: true,
    ..LaserLogicConfig::deep()
};

let module = LaserLogic::with_config(config);

// Complex argument analysis
let context = ThinkToolContext::new(r#"{
    "premises": [
        "All philosophers are thinkers",
        "Some thinkers are logicians",
        "No logicians are illogical"
    ],
    "conclusion": "Some philosophers are logical"
}"#);

let result = module.execute(&context)?;

// Access detailed analysis steps
if let Some(steps) = result.get_array("analysis_steps") {
    println!("Analysis steps:");
    for step in steps {
        println!("- {}", step.as_str().unwrap());
    }
}
```

## Error Handling

LaserLogic defines specific error types for logical analysis failures:

### LaserLogicError

Enumeration of all possible module-specific errors.

```rust
#[derive(Error, Debug, Clone)]
pub enum LaserLogicError {
    InvalidArgumentFormat { message: String },
    TooManyPremises { count: usize, max: usize },
    AnalysisTimeout { duration_ms: u64 },
    FolTranslationFailed { reason: String },
    FallacyDetectionFailed { reason: String },
    ContradictionDetectionFailed { reason: String },
}
```

### Error Descriptions

| Error Variant | Parameters | Description |
|---------------|------------|-------------|
| `InvalidArgumentFormat` | `message` | Malformed argument input JSON |
| `TooManyPremises` | `count`, `max` | Exceeded maximum premise limit |
| `AnalysisTimeout` | `duration_ms` | Logical analysis took too long |
| `FolTranslationFailed` | `reason` | Failed to translate to first-order logic |
| `FallacyDetectionFailed` | `reason` | Error during fallacy detection |
| `ContradictionDetectionFailed` | `reason` | Error detecting contradictions |

### Error Conversion

All LaserLogicError variants are automatically converted to the standard Error type:

```rust
impl From<LaserLogicError> for Error {
    fn from(err: LaserLogicError) -> Self {
        Error::ThinkToolExecutionError(err.to_string())
    }
}
```

### Handling Errors

```rust
use reasonkit::thinktool::modules::{LaserLogic, ThinkToolContext, LaserLogicError};

let module = LaserLogic::new();
let context = ThinkToolContext::new(r#"{"invalid": "json"}"#); // Malformed JSON

match module.execute(&context) {
    Ok(result) => {
        // Process successful result
        println!("Analysis completed with confidence: {}", result.confidence);
    }
    Err(e) => {
        // Handle specific LaserLogic errors
        if let Some(ll_err) = e.downcast_ref::<LaserLogicError>() {
            match ll_err {
                LaserLogicError::InvalidArgumentFormat { message } => {
                    eprintln!("Invalid argument format: {}", message);
                }
                LaserLogicError::TooManyPremises { count, max } => {
                    eprintln!("Too many premises: {} (max: {})", count, max);
                }
                LaserLogicError::AnalysisTimeout { duration_ms } => {
                    eprintln!("Analysis timed out after {}ms", duration_ms);
                }
                _ => eprintln!("LaserLogic error: {}", ll_err),
            }
        } else {
            // Handle other errors
            eprintln!("Other error: {}", e);
        }
    }
}
```

## Performance Considerations

1. **Premise Limit**: Control `max_premise_depth` to manage complexity
2. **Feature Selection**: Disable unused features (e.g., syllogism analysis)
3. **Verbose Output**: Disable for production use to reduce overhead
4. **Timeout Settings**: Set appropriate timeouts based on argument complexity
5. **Fallacy Detection**: Can be disabled for speed-critical applications

## Integration Notes

When using LaserLogic in protocol execution:

```rust
use reasonkit::thinktool::{ProtocolExecutor, ProtocolInput};

// ProtocolExecutor handles LLM integration automatically
let executor = ProtocolExecutor::new()?;
let result = executor.execute(
    "laserlogic", 
    ProtocolInput::json(r#"{"premises": [...], "conclusion": "..."}"#)
).await?;
```

The protocol-based approach provides:
- Automatic LLM selection for complex translations
- Streaming output for real-time progress
- Built-in retry logic for failed logical operations
- Comprehensive execution tracing and audit trails