mindkit 0.1.0

A generic sequential thinking toolkit for AI reasoning systems
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
use schemars::JsonSchema;
use serde::Deserialize;
use std::fmt::Write;

/// Valid thought types for structured reasoning patterns
pub const VALID_THOUGHT_TYPES: &[&str] = &["analytical", "critical", "synthesis", "validation"];

/// Input structure for the thinking tool
#[derive(Deserialize, JsonSchema, Clone)]
pub struct ThinkInput {
    /// Your current thinking step, which can include regular analytical steps, revisions of previous thoughts, questions about previous decisions, realizations about needing more analysis, changes in approach, hypothesis generation, or hypothesis verification
    pub thought: String,

    /// True if you need more thinking, even if at what seemed like the end
    #[serde(rename = "nextThoughtNeeded")]
    pub next_thought_needed: bool,

    /// Current number in sequence (can go beyond initial total if needed)
    #[serde(rename = "thoughtNumber")]
    pub thought_number: u32,

    /// Current estimate of thoughts needed (can be adjusted up/down)
    #[serde(rename = "totalThoughts")]
    pub total_thoughts: u32,

    /// A boolean indicating if this thought revises previous thinking
    #[serde(rename = "isRevision", skip_serializing_if = "Option::is_none")]
    pub is_revision: Option<bool>,

    /// If isRevision is true, which thought number is being reconsidered
    #[serde(rename = "revisesThought", skip_serializing_if = "Option::is_none")]
    pub revises_thought: Option<u32>,

    /// If branching, which thought number is the branching point
    #[serde(rename = "branchFromThought", skip_serializing_if = "Option::is_none")]
    pub branch_from_thought: Option<u32>,

    /// Identifier for the current branch (if any)
    #[serde(rename = "branchId", skip_serializing_if = "Option::is_none")]
    pub branch_id: Option<String>,

    /// If reaching end but realizing more thoughts needed
    #[serde(rename = "needsMoreThoughts", skip_serializing_if = "Option::is_none")]
    pub needs_more_thoughts: Option<bool>,

    /// Custom analytical lens to apply (e.g., "Rust best practices", "security")
    #[serde(rename = "customLens", skip_serializing_if = "Option::is_none")]
    pub custom_lens: Option<String>,

    /// Type of thought for structured reasoning patterns
    /// Valid values: "analytical" (default reasoning mode), "critical" (actively looks for flaws and issues),
    /// "synthesis" (combines multiple perspectives), "validation" (verifies conclusions)
    #[serde(rename = "thoughtType", skip_serializing_if = "Option::is_none")]
    pub thought_type: Option<String>,

    /// Confidence level in the current reasoning (0.0-1.0)
    #[serde(rename = "confidence", skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f32>,
}

/// Internal representation of thought data
#[derive(Clone)]
pub struct ThoughtData {
    pub thought: String,
    pub thought_number: u32,
    pub total_thoughts: u32,
    pub next_thought_needed: bool,
    pub is_revision: Option<bool>,
    pub revises_thought: Option<u32>,
    pub branch_from_thought: Option<u32>,
    pub branch_id: Option<String>,
    pub needs_more_thoughts: Option<bool>,
    pub custom_lens: Option<String>,
    pub thought_type: Option<String>,
    pub confidence: Option<f32>,
}

/// Result of processing a thinking input
pub struct ThinkResult {
    pub formatted_output: String,
    pub is_error: bool,
}

impl From<ThinkInput> for ThoughtData {
    fn from(input: ThinkInput) -> Self {
        // Auto-adjust total_thoughts if thought_number exceeds it
        let adjusted_total = if input.thought_number > input.total_thoughts {
            input.thought_number
        } else {
            input.total_thoughts
        };

        ThoughtData {
            thought: input.thought,
            thought_number: input.thought_number,
            total_thoughts: adjusted_total,
            next_thought_needed: input.next_thought_needed,
            is_revision: input.is_revision,
            revises_thought: input.revises_thought,
            branch_from_thought: input.branch_from_thought,
            branch_id: input.branch_id,
            needs_more_thoughts: input.needs_more_thoughts,
            custom_lens: input.custom_lens,
            thought_type: input.thought_type,
            confidence: input.confidence,
        }
    }
}

/// Core processing function that's independent of any MCP server implementation
#[must_use]
pub fn process_thinking(input: ThinkInput) -> ThinkResult {
    // Validate input
    if input.thought_number == 0 || input.total_thoughts == 0 {
        return ThinkResult {
            formatted_output: "Error: Thought numbers must be positive".to_string(),
            is_error: true,
        };
    }

    // Validate thought type if provided
    if let Some(ref thought_type) = input.thought_type {
        if !VALID_THOUGHT_TYPES.contains(&thought_type.as_str()) {
            return ThinkResult {
                formatted_output: format!(
                    "Error: Invalid thought type '{thought_type}'. Valid types are: analytical, critical, synthesis, validation"
                ),
                is_error: true,
            };
        }
    }

    // Convert to internal representation
    let mut thought_data = ThoughtData::from(input);

    // Apply critical analysis if thought type is critical
    if thought_data
        .thought_type
        .as_ref()
        .is_some_and(|t| t == "critical")
    {
        thought_data.thought = apply_critical_analysis(&thought_data.thought);
    }

    // Apply custom lens if specified
    if let Some(ref lens) = thought_data.custom_lens {
        thought_data.thought = apply_custom_lens(&thought_data.thought, lens);
    }

    // Adjust confidence based on critical findings
    if thought_data
        .thought_type
        .as_ref()
        .is_some_and(|t| t == "critical")
        && thought_data.thought.contains("⚠️")
    {
        // Lower confidence when critical issues are found
        thought_data.confidence = thought_data
            .confidence
            .map(|c| (c * 0.8).max(0.1))
            .or(Some(0.7));
    }

    // Format the thought
    let formatted_output = format_thought(&thought_data);

    ThinkResult {
        formatted_output,
        is_error: false,
    }
}

/// Formats a thought for display without colors (WASM-compatible)
fn format_thought(thought_data: &ThoughtData) -> String {
    let is_revision = thought_data.is_revision.unwrap_or(false);
    let is_branch = thought_data.branch_from_thought.is_some();
    let _is_critical = thought_data
        .thought_type
        .as_ref()
        .is_some_and(|t| t == "critical");

    // Determine the icon based on thought type and modes
    let icon = match thought_data.thought_type.as_deref() {
        Some("critical") => "🔍",
        Some("synthesis") => "🔗",
        Some("validation") => "",
        Some("analytical") | None => {
            if is_revision {
                "🔄"
            } else if is_branch {
                "🌿"
            } else if thought_data.custom_lens.is_some() {
                "🎯"
            } else {
                "💭"
            }
        }
        Some(_) => "💭", // Default for any other value
    };

    // Build the metadata part
    let mut metadata = format!(
        "{icon} {}/{}",
        thought_data.thought_number, thought_data.total_thoughts
    );

    // Add thought type if specified
    if let Some(thought_type) = &thought_data.thought_type {
        let _ = write!(metadata, " [{thought_type}]");
    }

    // Add custom lens info
    if let Some(lens) = &thought_data.custom_lens {
        let _ = write!(metadata, " 🔎{lens}");
    }

    // Add confidence if present
    if let Some(confidence) = thought_data.confidence {
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let confidence_pct = (confidence * 100.0) as u32;
        let _ = write!(metadata, " {confidence_pct}%");
    }

    // Add revision info
    if is_revision {
        if let Some(revises) = thought_data.revises_thought {
            let _ = write!(metadata, " ↺#{revises}");
        }
    }

    // Add branch info
    if is_branch {
        if let Some(branch_from) = thought_data.branch_from_thought {
            let _ = write!(metadata, " └#{branch_from}");
        }
        if let Some(branch_id) = &thought_data.branch_id {
            let _ = write!(metadata, "[{branch_id}]");
        }
    }

    // Add expanding indicator
    if thought_data.needs_more_thoughts.unwrap_or(false) {
        metadata.push_str(" (+)");
    }

    // Format the main thought
    let formatted_thought = thought_data.thought.clone();

    // Single-line format with pipe separator
    format!("{metadata} | {formatted_thought}")
}

/// Apply critical analysis to a thought
fn apply_critical_analysis(thought: &str) -> String {
    let mut analysis = thought.to_string();

    // Add critical analysis markers based on content
    if thought.contains("assume") || thought.contains("probably") || thought.contains("might") {
        analysis.push_str(" [⚠️ ASSUMPTION DETECTED: Verify this claim]");
    }

    if thought.contains("all") || thought.contains("never") || thought.contains("always") {
        analysis.push_str(" [⚠️ ABSOLUTE STATEMENT: Consider edge cases]");
    }

    if thought.contains("obviously") || thought.contains("clearly") {
        analysis.push_str(" [⚠️ IMPLICIT BIAS: What might not be obvious?]");
    }

    analysis
}

/// Apply a custom lens filter to a thought
fn apply_custom_lens(thought: &str, lens: &str) -> String {
    let mut filtered = thought.to_string();

    // Apply lens-specific analysis
    match lens.to_lowercase().as_str() {
        lens if lens.contains("rust") => {
            if thought.contains("memory") || thought.contains("pointer") {
                filtered.push_str(" [🔎 RUST: Consider ownership and borrowing rules]");
            }
            if thought.contains("error") || thought.contains("fail") {
                filtered.push_str(" [🔎 RUST: Use Result<T, E> for error handling]");
            }
        }
        lens if lens.contains("security") => {
            if thought.contains("input") || thought.contains("user") {
                filtered.push_str(" [🔎 SECURITY: Validate and sanitize all inputs]");
            }
            if thought.contains("auth") || thought.contains("token") {
                filtered.push_str(" [🔎 SECURITY: Ensure proper authentication]");
            }
        }
        lens if lens.contains("performance") => {
            if thought.contains("loop") || thought.contains("iterate") {
                filtered.push_str(" [🔎 PERFORMANCE: Check algorithmic complexity]");
            }
            if thought.contains("memory") || thought.contains("allocat") {
                filtered.push_str(" [🔎 PERFORMANCE: Monitor memory usage]");
            }
        }
        _ => {
            let _ = write!(filtered, " [🔎 {lens}: Applied custom perspective]");
        }
    }

    filtered
}

/// Text wrapping utility function
#[allow(dead_code)]
fn wrap_text(text: &str, width: usize) -> Vec<String> {
    let mut lines = Vec::new();
    let words: Vec<&str> = text.split_whitespace().collect();
    let mut current_line = String::new();

    for word in words {
        if current_line.len() + word.len() + 1 > width && !current_line.is_empty() {
            lines.push(current_line.clone());
            current_line.clear();
        }

        if !current_line.is_empty() {
            current_line.push(' ');
        }
        current_line.push_str(word);
    }

    if !current_line.is_empty() {
        lines.push(current_line);
    }

    if lines.is_empty() {
        lines.push(String::new());
    }

    lines
}

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

    fn create_basic_input() -> ThinkInput {
        ThinkInput {
            thought: "Test thought".to_string(),
            next_thought_needed: true,
            thought_number: 1,
            total_thoughts: 3,
            is_revision: None,
            revises_thought: None,
            branch_from_thought: None,
            branch_id: None,
            needs_more_thoughts: None,
            custom_lens: None,
            thought_type: None,
            confidence: None,
        }
    }

    #[test]
    fn test_basic_thinking() {
        let input = create_basic_input();
        let result = process_thinking(input);

        assert!(!result.is_error);
        assert!(result.formatted_output.contains("💭 1/3 | Test thought"));
    }

    #[test]
    fn test_analytical_thought_type() {
        let mut input = create_basic_input();
        input.thought_type = Some("analytical".to_string());

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(
            result
                .formatted_output
                .contains("💭 1/3 [analytical] | Test thought")
        );
    }

    #[test]
    fn test_critical_thought_type() {
        let mut input = create_basic_input();
        input.thought = "This will always work perfectly".to_string();
        input.thought_type = Some("critical".to_string());

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("🔍"));
        assert!(result.formatted_output.contains("[critical]"));
        assert!(result.formatted_output.contains("ABSOLUTE STATEMENT"));
    }

    #[test]
    fn test_synthesis_thought_type() {
        let mut input = create_basic_input();
        input.thought_type = Some("synthesis".to_string());

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(
            result
                .formatted_output
                .contains("🔗 1/3 [synthesis] | Test thought")
        );
    }

    #[test]
    fn test_validation_thought_type() {
        let mut input = create_basic_input();
        input.thought_type = Some("validation".to_string());

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(
            result
                .formatted_output
                .contains("✓ 1/3 [validation] | Test thought")
        );
    }

    #[test]
    fn test_invalid_thought_type() {
        let mut input = create_basic_input();
        input.thought_type = Some("invalid_type".to_string());

        let result = process_thinking(input);
        assert!(result.is_error);
        assert!(result.formatted_output.contains("Invalid thought type"));
    }

    #[test]
    fn test_revision_tracking() {
        let mut input = create_basic_input();
        input.thought_number = 3;
        input.is_revision = Some(true);
        input.revises_thought = Some(2);

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("🔄"));
        assert!(result.formatted_output.contains("↺#2"));
    }

    #[test]
    fn test_branching_thoughts() {
        let mut input = create_basic_input();
        input.thought_number = 4;
        input.total_thoughts = 5;
        input.branch_from_thought = Some(3);
        input.branch_id = Some("alt-1".to_string());

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("🌿"));
        assert!(result.formatted_output.contains("└#3[alt-1]"));
    }

    #[test]
    fn test_custom_lens_rust() {
        let mut input = create_basic_input();
        input.thought = "Need to handle memory allocation here".to_string();
        input.custom_lens = Some("rust".to_string());

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("🎯"));
        assert!(result.formatted_output.contains("🔎rust"));
        assert!(result.formatted_output.contains("ownership and borrowing"));
    }

    #[test]
    fn test_custom_lens_security() {
        let mut input = create_basic_input();
        input.thought = "Processing user input from the form".to_string();
        input.custom_lens = Some("security".to_string());

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("🔎security"));
        assert!(result.formatted_output.contains("Validate and sanitize"));
    }

    #[test]
    fn test_custom_lens_performance() {
        let mut input = create_basic_input();
        input.thought = "Need to iterate through all items".to_string();
        input.custom_lens = Some("performance".to_string());

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("🔎performance"));
        assert!(result.formatted_output.contains("algorithmic complexity"));
    }

    #[test]
    fn test_confidence_tracking() {
        let mut input = create_basic_input();
        input.confidence = Some(0.85);

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("85%"));
    }

    #[test]
    fn test_needs_more_thoughts() {
        let mut input = create_basic_input();
        input.needs_more_thoughts = Some(true);

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("(+)"));
    }

    #[test]
    fn test_auto_adjust_total_thoughts() {
        let mut input = create_basic_input();
        input.thought_number = 5;
        input.total_thoughts = 3;

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("5/5"));
    }

    #[test]
    fn test_zero_thought_number_error() {
        let mut input = create_basic_input();
        input.thought_number = 0;

        let result = process_thinking(input);
        assert!(result.is_error);
        assert!(result.formatted_output.contains("must be positive"));
    }

    #[test]
    fn test_zero_total_thoughts_error() {
        let mut input = create_basic_input();
        input.total_thoughts = 0;

        let result = process_thinking(input);
        assert!(result.is_error);
        assert!(result.formatted_output.contains("must be positive"));
    }

    #[test]
    fn test_critical_analysis_assumptions() {
        let mut input = create_basic_input();
        input.thought = "I assume this will probably work".to_string();
        input.thought_type = Some("critical".to_string());

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("ASSUMPTION DETECTED"));
    }

    #[test]
    fn test_critical_analysis_absolutes() {
        let mut input = create_basic_input();
        input.thought = "This never fails".to_string();
        input.thought_type = Some("critical".to_string());

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("ABSOLUTE STATEMENT"));
    }

    #[test]
    fn test_critical_analysis_bias() {
        let mut input = create_basic_input();
        input.thought = "obviously this is the best approach".to_string();
        input.thought_type = Some("critical".to_string());

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("IMPLICIT BIAS"));
    }

    #[test]
    fn test_critical_confidence_adjustment() {
        let mut input = create_basic_input();
        input.thought = "This approach assumes perfect conditions".to_string();
        input.thought_type = Some("critical".to_string());
        input.confidence = Some(0.9);

        let result = process_thinking(input);
        assert!(!result.is_error);
        // Confidence should be reduced when critical issues found
        assert!(result.formatted_output.contains("72%"));
    }

    #[test]
    fn test_complex_combined_features() {
        let input = ThinkInput {
            thought: "Revising my security analysis of the authentication system".to_string(),
            next_thought_needed: true,
            thought_number: 7,
            total_thoughts: 5, // Will be auto-adjusted
            is_revision: Some(true),
            revises_thought: Some(4),
            branch_from_thought: None,
            branch_id: None,
            needs_more_thoughts: Some(true),
            custom_lens: Some("security".to_string()),
            thought_type: Some("critical".to_string()),
            confidence: Some(0.75),
        };

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("🔍")); // Critical type
        assert!(result.formatted_output.contains("7/7")); // Auto-adjusted
        assert!(result.formatted_output.contains("🔎security"));
        assert!(result.formatted_output.contains("75%"));
        assert!(result.formatted_output.contains("↺#4"));
        assert!(result.formatted_output.contains("(+)"));
    }

    #[test]
    fn test_text_wrapping() {
        let text = "This is a very long line that should be wrapped at the appropriate width to ensure readability";
        let lines = wrap_text(text, 20);

        assert!(lines.len() > 1);
        assert!(lines.iter().all(|line| line.len() <= 20));
    }

    #[test]
    fn test_empty_thought() {
        let mut input = create_basic_input();
        input.thought = "".to_string();

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("💭 1/3 | "));
    }

    #[test]
    fn test_special_characters_in_thought() {
        let mut input = create_basic_input();
        input.thought = "Testing with special chars: !@#$%^&*(){}[]|\\<>?".to_string();

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("!@#$%^&*(){}[]|\\<>?"));
    }

    #[test]
    fn test_unicode_in_thought() {
        let mut input = create_basic_input();
        input.thought = "Testing with unicode: 你好 🌍 café ñ".to_string();

        let result = process_thinking(input);
        assert!(!result.is_error);
        assert!(result.formatted_output.contains("你好 🌍 café ñ"));
    }
}