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

Version: 3.0.0

The BedRock module reduces problems to fundamental axioms through recursive analysis,
then rebuilds understanding using Tree-of-Thoughts exploration.

## 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

BedRock applies Elon Musk-style first principles thinking to decompose complex
problems into fundamental components, identify axiomatic truths, surface hidden
assumptions, and reconstruct understanding from verified foundations.

Key capabilities:

- Recursive problem decomposition to fundamental principles
- Axiom identification with confidence scoring
- Hidden assumption exposure and analysis
- Tree-of-Thoughts exploration for optimal reasoning paths
- Confidence-weighted reconstruction from fundamentals

## Configuration

### BedRockConfig

Configuration struct controlling BedRock analysis depth and behavior.

```rust
pub struct BedRockConfig {
    pub max_depth: usize,
    pub axiom_threshold: f64,
    pub branching_factor: usize,
    pub min_confidence: f64,
    pub strict_assumptions: bool,
    pub max_principles: usize,
}
```

#### Fields

| Field                | Type    | Required | Default | Description                                                            |
| -------------------- | ------- | -------- | ------- | ---------------------------------------------------------------------- |
| `max_depth`          | `usize` | Yes      | `3`     | Maximum decomposition depth. Controls recursion depth.                 |
| `axiom_threshold`    | `f64`   | Yes      | `0.85`  | Minimum fundamentality score for axioms. Range: 0.0-1.0.               |
| `branching_factor`   | `usize` | Yes      | `3`     | Parallel thought branches per principle. Enables exploration.          |
| `min_confidence`     | `f64`   | Yes      | `0.5`   | Minimum confidence threshold for principles. Range: 0.0-1.0.           |
| `strict_assumptions` | `bool`  | Yes      | `true`  | Require all assumptions to be explicitly stated. Ensures completeness. |
| `max_principles`     | `usize` | Yes      | `20`    | Maximum principles to identify. Prevents combinatorial explosion.      |

#### Implementation

```rust
impl Default for BedRockConfig {
    fn default() -> Self {
        Self {
            max_depth: 3,
            axiom_threshold: 0.85,
            branching_factor: 3,
            min_confidence: 0.5,
            strict_assumptions: true,
            max_principles: 20,
        }
    }
}

impl BedRockConfig {
    /// Fast decomposition mode - shallow analysis
    pub fn fast() -> Self {
        Self {
            max_depth: 2,
            axiom_threshold: 0.7,
            branching_factor: 2,
            min_confidence: 0.4,
            strict_assumptions: false,
            max_principles: 10,
        }
    }

    /// Deep analysis mode - comprehensive decomposition
    pub fn deep() -> Self {
        Self {
            max_depth: 5,
            axiom_threshold: 0.9,
            branching_factor: 5,
            min_confidence: 0.6,
            strict_assumptions: true,
            max_principles: 30,
        }
    }
}
```

## Core Types

### BedRock

Main module struct implementing the ThinkToolModule trait.

```rust
pub struct BedRock {
    config: ThinkToolModuleConfig,
    bedrock_config: BedRockConfig,
}
```

#### Fields

| Field            | Type                    | Description                               |
| ---------------- | ----------------------- | ----------------------------------------- |
| `config`         | `ThinkToolModuleConfig` | Standard module configuration metadata    |
| `bedrock_config` | `BedRockConfig`         | BedRock-specific configuration parameters |

### BedRockResult

Structured output from BedRock execution containing decomposition analysis.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BedRockResult {
    pub principles: Vec<Principle>,
    pub axioms: Vec<Principle>,
    pub assumptions: Vec<Principle>,
    pub reconstruction: String,
    pub confidence: f64,
    pub decomposition_tree: Option<DecompositionNode>,
    pub exploration_paths: Vec<ExplorationPath>,
}
```

#### Fields

| Field                | Type                        | Description                             |
| -------------------- | --------------------------- | --------------------------------------- |
| `principles`         | `Vec<Principle>`            | Identified fundamental principles       |
| `axioms`             | `Vec<Principle>`            | Verified axiomatic principles           |
| `assumptions`        | `Vec<Principle>`            | Exposed assumptions                     |
| `reconstruction`     | `String`                    | Rebuilt understanding from fundamentals |
| `confidence`         | `f64`                       | Overall confidence in decomposition     |
| `decomposition_tree` | `Option<DecompositionNode>` | Hierarchical decomposition structure    |
| `exploration_paths`  | `Vec<ExplorationPath>`      | Tree-of-Thoughts exploration paths      |

### Principle

Fundamental principle identified during decomposition.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Principle {
    pub id: usize,
    pub statement: String,
    pub r#type: PrincipleType,
    pub confidence: f64,
    pub dependencies: Vec<usize>,
    pub evidence: String,
    pub challenges: Vec<String>,
    pub reliability_weight: f64,
    pub depth: usize,
}
```

#### Fields

| Field                | Type            | Description                            |
| -------------------- | --------------- | -------------------------------------- |
| `id`                 | `usize`         | Unique identifier within this analysis |
| `statement`          | `String`        | The principle statement                |
| `type`               | `PrincipleType` | Classification of principle            |
| `confidence`         | `f64`           | Confidence in principle accuracy       |
| `dependencies`       | `Vec<usize>`    | IDs of dependent principles            |
| `evidence`           | `String`        | Supporting evidence                    |
| `challenges`         | `Vec<String>`   | Potential counter-arguments            |
| `reliability_weight` | `f64`           | Weight based on principle type         |
| `depth`              | `usize`         | Decomposition depth level              |

### PrincipleType

Classification of principle nature affecting reliability.

```rust
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PrincipleType {
    Axiom,      // Self-evident truth requiring no proof
    Derived,    // Logically derived from axioms
    Assumption, // Assumed for the sake of argument
    Empirical,  // Based on empirical observation/data
    Definition, // Definitional statement clarifying terminology
    Contested,  // Claim requiring verification
}
```

#### Reliability Weights

| Type         | Weight | Description           |
| ------------ | ------ | --------------------- |
| `Axiom`      | 1.0    | Highest reliability   |
| `Definition` | 0.95   | Very high reliability |
| `Empirical`  | 0.80   | High reliability      |
| `Derived`    | 0.75   | Moderate reliability  |
| `Assumption` | 0.50   | Low reliability       |
| `Contested`  | 0.30   | Lowest reliability    |

### DecompositionNode

Node in the hierarchical decomposition tree.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DecompositionNode {
    pub principle_id: usize,
    pub children: Vec<DecompositionNode>,
    pub level: usize,
    pub exploration_score: f64,
}
```

#### Fields

| Field               | Type                     | Description                            |
| ------------------- | ------------------------ | -------------------------------------- |
| `principle_id`      | `usize`                  | ID of principle at this node           |
| `children`          | `Vec<DecompositionNode>` | Child decomposition nodes              |
| `level`             | `usize`                  | Depth level in decomposition           |
| `exploration_score` | `f64`                    | Score for Tree-of-Thoughts exploration |

### ExplorationPath

Path explored during Tree-of-Thoughts analysis.

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExplorationPath {
    pub path_id: usize,
    pub principles: Vec<usize>,
    pub confidence_trajectory: Vec<f64>,
    pub exploration_score: f64,
    pub optimal: bool,
}
```

#### Fields

| Field                   | Type         | Description                        |
| ----------------------- | ------------ | ---------------------------------- |
| `path_id`               | `usize`      | Unique identifier for this path    |
| `principles`            | `Vec<usize>` | Principle IDs in exploration order |
| `confidence_trajectory` | `Vec<f64>`   | Confidence evolution along path    |
| `exploration_score`     | `f64`        | Overall path quality score         |
| `optimal`               | `bool`       | Whether this is an optimal path    |

## Methods

### BedRock::new()

Create a new BedRock module with default configuration.

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

Returns: `BedRock` instance with default settings.

Example:

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

### BedRock::with_config()

Create a new BedRock module with custom configuration.

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

Parameters:

- `config`: `BedRockConfig` - Custom configuration parameters

Returns: `BedRock` instance with specified configuration.

Example:

```rust
let config = BedRockConfig::deep();
let module = BedRock::with_config(config);
```

### BedRock::decompose()

Direct decomposition of a problem statement.

```rust
pub fn decompose(&self, problem: &str) -> Result<BedRockResult>
```

Parameters:

- `problem`: `&str` - Problem statement to decompose

Returns: `Result<BedRockResult>` - Decomposition results or error.

Example:

```rust
let module = BedRock::new();
let result = module.decompose("Why are electric vehicles better than gas cars?")?;
```

### BedRock::execute()

Execute the BedRock module synchronously.

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

Parameters:

- `context`: `&ThinkToolContext` - Execution context with problem statement

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

Example:

```rust
let module = BedRock::new();
let context = ThinkToolContext::new("Analyze the root causes of climate change");
let result = module.execute(&context)?;
```

### BedRock::config()

Get the module configuration.

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

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

Example:

```rust
let module = BedRock::new();
let config = module.config();
assert_eq!(config.max_depth, 3);
```

## Usage Examples

### Basic Decomposition

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

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

// Direct decomposition
let result = module.decompose("Why do startups fail?")?;

// Access identified axioms
let axioms = &result.axioms;
println!("Found {} axiomatic principles:", axioms.len());
for axiom in axioms {
    println!("- {} (confidence: {:.2})", axiom.statement, axiom.confidence);
}

// Access exposed assumptions
let assumptions = &result.assumptions;
println!("\nExposed {} assumptions:", assumptions.len());
for assumption in assumptions {
    println!("- {} (challenges: {:?})", assumption.statement, assumption.challenges);
}
```

### Context-Based Execution

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

// Create module with custom configuration
let module = BedRock::with_config(
    BedRockConfig {
        max_depth: 4,
        axiom_threshold: 0.9,
        ..Default::default()
    }
);

// Prepare context
let context = ThinkToolContext::new("What are the fundamental barriers to fusion power?");

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

// Access reconstruction
let reconstruction = result.get_str("reconstruction").unwrap();
println!("Reconstructed understanding:\n{}", reconstruction);

// Access decomposition tree
if let Some(tree) = result.get("decomposition_tree") {
    println!("Hierarchical decomposition completed");
}
```

### Deep Analysis Configuration

```rust
use reasonkit::thinktool::modules::{BedRock, BedRockConfig, ThinkToolContext};

// Configure for comprehensive decomposition
let config = BedRockConfig::deep();
let module = BedRock::with_config(config);

// Complex problem analysis
let context = ThinkToolContext::new(
    "Analyze the fundamental economic principles underlying cryptocurrency valuation"
);

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

// Access exploration paths
let paths = result.get_array("exploration_paths").unwrap();
println!("Explored {} reasoning paths", paths.len());

// Find optimal path
for path in paths {
    let optimal = path.get("optimal").and_then(|v| v.as_bool()).unwrap_or(false);
    if optimal {
        println!("Found optimal reasoning path");
        break;
    }
}
```

## Error Handling

BedRock defines specific error types for decomposition failures:

### BedRockError

Enumeration of all possible module-specific errors.

```rust
#[derive(Error, Debug, Clone)]
pub enum BedRockError {
    DecompositionFailed { reason: String },
    AxiomIdentificationFailed { reason: String },
    CircularDependency { principles: Vec<usize> },
    ReconstructionFailed { reason: String },
    TreeExplorationTimeout { duration_ms: u64 },
    PrincipleLimitExceeded { count: usize, max: usize },
}
```

### Error Descriptions

| Error Variant               | Parameters     | Description                            |
| --------------------------- | -------------- | -------------------------------------- |
| `DecompositionFailed`       | `reason`       | Unable to decompose the problem        |
| `AxiomIdentificationFailed` | `reason`       | Could not identify fundamental axioms  |
| `CircularDependency`        | `principles`   | Found circular reasoning in principles |
| `ReconstructionFailed`      | `reason`       | Unable to rebuild from fundamentals    |
| `TreeExplorationTimeout`    | `duration_ms`  | Tree-of-Thoughts exploration timed out |
| `PrincipleLimitExceeded`    | `count`, `max` | Exceeded maximum principle limit       |

### Error Conversion

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

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

### Handling Errors

```rust
use reasonkit::thinktool::modules::{BedRock, ThinkToolContext, BedRockError};

let module = BedRock::new();
let context = ThinkToolContext::new("Complex philosophical question");

match module.execute(&context) {
    Ok(result) => {
        // Process successful result
        println!("Decomposition completed with confidence: {}", result.confidence);
    }
    Err(e) => {
        // Handle specific BedRock errors
        if let Some(br_err) = e.downcast_ref::<BedRockError>() {
            match br_err {
                BedRockError::DecompositionFailed { reason } => {
                    eprintln!("Decomposition failed: {}", reason);
                }
                BedRockError::TreeExplorationTimeout { duration_ms } => {
                    eprintln!("Exploration timed out after {}ms", duration_ms);
                }
                BedRockError::CircularDependency { principles } => {
                    eprintln!("Circular dependency in principles: {:?}", principles);
                }
                _ => eprintln!("BedRock error: {}", br_err),
            }
        } else {
            // Handle other errors
            eprintln!("Other error: {}", e);
        }
    }
}
```

## Performance Considerations

1. **Decomposition Depth**: Control `max_depth` to manage recursion complexity
2. **Branching Factor**: Adjust `branching_factor` for exploration breadth vs. speed
3. **Principle Limit**: Set `max_principles` to prevent combinatorial explosion
4. **Axiom Threshold**: Tune `axiom_threshold` for desired fundamentality rigor
5. **Strict Assumptions**: Disable for faster execution when completeness is less critical

## Integration Notes

When using BedRock in protocol execution:

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

// ProtocolExecutor handles LLM integration automatically
let executor = ProtocolExecutor::new()?;
let result = executor.execute(
    "bedrock",
    ProtocolInput::query("Fundamental question about reality")
).await?;
```

The protocol-based approach provides:

- Automatic LLM selection for complex decomposition tasks
- Streaming output for real-time progress monitoring
- Built-in retry logic for failed decomposition steps
- Comprehensive execution tracing and audit capabilities