brainwires-cognition 0.8.0

Unified intelligence layer — knowledge graphs, adaptive prompting, RAG, spectral math, and code analysis for the Brainwires Agent Framework
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
//! Technique Library with BKS Integration
//!
//! This module provides a library of all 15 prompting techniques with metadata,
//! integrated with the Behavioral Knowledge System (BKS) for querying shared
//! technique effectiveness across users.

use super::techniques::{
    ComplexityLevel, PromptingTechnique, TaskCharacteristic, TechniqueCategory, TechniqueMetadata,
};
#[cfg(feature = "knowledge")]
use crate::knowledge::bks_pks::{BehavioralKnowledgeCache, BehavioralTruth};
use anyhow::Result;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::Mutex;

/// Library of all prompting techniques
pub struct TechniqueLibrary {
    techniques: HashMap<PromptingTechnique, TechniqueMetadata>,
    bks_cache: Option<Arc<Mutex<BehavioralKnowledgeCache>>>,
}

impl TechniqueLibrary {
    /// Create a new technique library with all 15 techniques
    pub fn new() -> Self {
        let mut techniques = HashMap::new();

        // === Role Assignment (1 technique) ===
        techniques.insert(
            PromptingTechnique::RolePlaying,
            TechniqueMetadata::new(
                PromptingTechnique::RolePlaying,
                TechniqueCategory::RoleAssignment,
                "Role Playing",
                "Assign expert role to elicit domain-specific knowledge",
                "You are a {role} with expertise in {domain}. ",
                vec![
                    TaskCharacteristic::MultiStepReasoning,
                    TaskCharacteristic::CodeGeneration,
                    TaskCharacteristic::AlgorithmicProblem,
                ],
                0.0, // Always usable
                ComplexityLevel::Simple,
                true,
            ),
        );

        // === Emotional Stimulus (2 techniques) ===
        techniques.insert(
            PromptingTechnique::EmotionPrompting,
            TechniqueMetadata::new(
                PromptingTechnique::EmotionPrompting,
                TechniqueCategory::EmotionalStimulus,
                "Emotion Prompting",
                "Add emotional cues to increase engagement",
                "This is an important {task_type} that requires {quality}. ",
                vec![
                    TaskCharacteristic::MultiStepReasoning,
                    TaskCharacteristic::NumericalCalculation,
                ],
                0.0,
                ComplexityLevel::Simple,
                true,
            ),
        );

        techniques.insert(
            PromptingTechnique::StressPrompting,
            TechniqueMetadata::new(
                PromptingTechnique::StressPrompting,
                TechniqueCategory::EmotionalStimulus,
                "Stress Prompting",
                "Induce moderate stress conditions for focus",
                "This task requires immediate attention and precision. Time is limited. ",
                vec![
                    TaskCharacteristic::LogicalDeduction,
                    TaskCharacteristic::AlgorithmicProblem,
                ],
                0.0,
                ComplexityLevel::Simple,
                true,
            ),
        );

        // === Reasoning (7 techniques) ===
        techniques.insert(
            PromptingTechnique::ChainOfThought,
            TechniqueMetadata::new(
                PromptingTechnique::ChainOfThought,
                TechniqueCategory::Reasoning,
                "Chain-of-Thought",
                "Require explicit step-by-step reasoning",
                "Think step by step. Show your reasoning process clearly. ",
                vec![
                    TaskCharacteristic::MultiStepReasoning,
                    TaskCharacteristic::LogicalDeduction,
                    TaskCharacteristic::NumericalCalculation,
                ],
                0.0, // Always usable
                ComplexityLevel::Simple,
                true,
            ),
        );

        techniques.insert(
            PromptingTechnique::LogicOfThought,
            TechniqueMetadata::new(
                PromptingTechnique::LogicOfThought,
                TechniqueCategory::Reasoning,
                "Logic-of-Thought",
                "Embed propositional logic for formal reasoning",
                "Use propositional logic notation. Let P, Q, R represent propositions. Apply logical inference rules. ",
                vec![
                    TaskCharacteristic::LogicalDeduction,
                    TaskCharacteristic::MultiStepReasoning,
                ],
                0.8, // Requires high SEAL quality
                ComplexityLevel::Advanced,
                true,
            ),
        );

        techniques.insert(
            PromptingTechnique::LeastToMost,
            TechniqueMetadata::new(
                PromptingTechnique::LeastToMost,
                TechniqueCategory::Reasoning,
                "Least-to-Most",
                "Decompose into simpler sub-problems progressively",
                "Break this problem into simpler sub-problems. Solve from simplest to most complex. ",
                vec![
                    TaskCharacteristic::MultiStepReasoning,
                    TaskCharacteristic::AlgorithmicProblem,
                ],
                0.5, // Moderate complexity
                ComplexityLevel::Moderate,
                true,
            ),
        );

        techniques.insert(
            PromptingTechnique::ThreadOfThought,
            TechniqueMetadata::new(
                PromptingTechnique::ThreadOfThought,
                TechniqueCategory::Reasoning,
                "Thread-of-Thought",
                "Summarize long contexts progressively",
                "Summarize the context progressively as you reason through it. Maintain a running summary. ",
                vec![
                    TaskCharacteristic::LongContextSummarization,
                    TaskCharacteristic::MultiStepReasoning,
                ],
                0.7, // Advanced technique
                ComplexityLevel::Advanced,
                true,
            ),
        );

        techniques.insert(
            PromptingTechnique::PlanAndSolve,
            TechniqueMetadata::new(
                PromptingTechnique::PlanAndSolve,
                TechniqueCategory::Reasoning,
                "Plan-and-Solve",
                "Generate execution plan first, then solve step by step",
                "First, devise a plan. Then, solve the problem step by step according to the plan. ",
                vec![
                    TaskCharacteristic::MultiStepReasoning,
                    TaskCharacteristic::LogicalDeduction,
                    TaskCharacteristic::AlgorithmicProblem,
                ],
                0.5, // Moderate complexity
                ComplexityLevel::Moderate,
                true,
            ),
        );

        techniques.insert(
            PromptingTechnique::SkeletonOfThought,
            TechniqueMetadata::new(
                PromptingTechnique::SkeletonOfThought,
                TechniqueCategory::Reasoning,
                "Skeleton-of-Thought",
                "Generate skeleton, then fill details",
                "First, generate a skeleton outline. Then, fill in the details for each part. ",
                vec![
                    TaskCharacteristic::CreativeGeneration,
                    TaskCharacteristic::CodeGeneration,
                ],
                0.7, // Advanced technique
                ComplexityLevel::Advanced,
                true,
            ),
        );

        techniques.insert(
            PromptingTechnique::ScratchpadPrompting,
            TechniqueMetadata::new(
                PromptingTechnique::ScratchpadPrompting,
                TechniqueCategory::Reasoning,
                "Scratchpad Prompting",
                "Provide draft space for intermediate steps",
                "Use the following scratchpad format for intermediate calculations:\n\
                <scratchpad>\n\
                [Your work here]\n\
                </scratchpad>\n",
                vec![
                    TaskCharacteristic::NumericalCalculation,
                    TaskCharacteristic::AlgorithmicProblem,
                ],
                0.0,
                ComplexityLevel::Simple,
                true,
            ),
        );

        // === Others (6 techniques) ===
        techniques.insert(
            PromptingTechnique::DecomposedPrompting,
            TechniqueMetadata::new(
                PromptingTechnique::DecomposedPrompting,
                TechniqueCategory::Others,
                "Decomposed Prompting",
                "Break into sub-tasks explicitly",
                "Decompose this task into independent sub-tasks. Solve each sub-task separately. ",
                vec![
                    TaskCharacteristic::MultiStepReasoning,
                    TaskCharacteristic::AlgorithmicProblem,
                ],
                0.5,
                ComplexityLevel::Moderate,
                true,
            ),
        );

        techniques.insert(
            PromptingTechnique::IgnoreIrrelevantConditions,
            TechniqueMetadata::new(
                PromptingTechnique::IgnoreIrrelevantConditions,
                TechniqueCategory::Others,
                "Ignore Irrelevant Conditions",
                "Detect and disregard noise in the problem",
                "Identify and ignore any irrelevant information. Focus only on what's essential. ",
                vec![
                    TaskCharacteristic::LogicalDeduction,
                    TaskCharacteristic::MultiStepReasoning,
                ],
                0.6,
                ComplexityLevel::Moderate,
                true,
            ),
        );

        techniques.insert(
            PromptingTechnique::HighlightedCoT,
            TechniqueMetadata::new(
                PromptingTechnique::HighlightedCoT,
                TechniqueCategory::Others,
                "Highlighted CoT",
                "Highlight essential information before reasoning",
                "First, highlight the essential information. Then, reason step by step based on the highlights. ",
                vec![
                    TaskCharacteristic::MultiStepReasoning,
                    TaskCharacteristic::LogicalDeduction,
                ],
                0.5,
                ComplexityLevel::Moderate,
                true,
            ),
        );

        techniques.insert(
            PromptingTechnique::SkillsInContext,
            TechniqueMetadata::new(
                PromptingTechnique::SkillsInContext,
                TechniqueCategory::Others,
                "Skills-in-Context",
                "Compose basic skills for complex tasks",
                "Identify the basic skills required. Compose them systematically to solve the task. ",
                vec![
                    TaskCharacteristic::AlgorithmicProblem,
                    TaskCharacteristic::CodeGeneration,
                ],
                0.7,
                ComplexityLevel::Advanced,
                true,
            ),
        );

        techniques.insert(
            PromptingTechnique::AutomaticInformationFiltering,
            TechniqueMetadata::new(
                PromptingTechnique::AutomaticInformationFiltering,
                TechniqueCategory::Others,
                "Automatic Information Filtering",
                "Preprocess to remove irrelevant information",
                "Filter the input to retain only relevant information before processing. ",
                vec![
                    TaskCharacteristic::LongContextSummarization,
                    TaskCharacteristic::LogicalDeduction,
                ],
                0.6,
                ComplexityLevel::Moderate,
                true,
            ),
        );

        Self {
            techniques,
            bks_cache: None,
        }
    }

    /// Set BKS cache for querying shared technique effectiveness
    pub fn with_bks(mut self, bks_cache: Arc<Mutex<BehavioralKnowledgeCache>>) -> Self {
        self.bks_cache = Some(bks_cache);
        self
    }

    /// Get technique metadata by enum
    pub fn get(&self, technique: &PromptingTechnique) -> Option<&TechniqueMetadata> {
        self.techniques.get(technique)
    }

    /// Get all techniques
    pub fn get_all(&self) -> Vec<&TechniqueMetadata> {
        self.techniques.values().collect()
    }

    /// Get techniques filtered by SEAL quality score
    pub fn get_by_seal_quality(&self, seal_quality: f32) -> Vec<&TechniqueMetadata> {
        self.techniques
            .values()
            .filter(|t| t.min_seal_quality <= seal_quality)
            .collect()
    }

    /// Get techniques by category
    pub fn get_by_category(&self, category: TechniqueCategory) -> Vec<&TechniqueMetadata> {
        self.techniques
            .values()
            .filter(|t| t.category == category)
            .collect()
    }

    /// Query BKS for technique effectiveness in a specific cluster
    ///
    /// Returns techniques that have been successfully promoted to BKS for this cluster,
    /// indicating they work well based on collective user experience.
    pub async fn get_bks_recommended_techniques(
        &self,
        cluster_id: &str,
    ) -> Result<Vec<PromptingTechnique>> {
        if let Some(ref bks_cache) = self.bks_cache {
            let bks = bks_cache.lock().await;

            // Query BKS for truths matching the cluster context
            // Example: "For numerical_reasoning, ChainOfThought achieves 92% success"
            let truths = bks.get_matching_truths(cluster_id);

            let mut recommended = Vec::new();
            for truth in truths {
                // Parse technique from truth rule/rationale
                if let Some(technique) = self.parse_technique_from_truth(truth) {
                    recommended.push(technique);
                }
            }

            Ok(recommended)
        } else {
            Ok(Vec::new())
        }
    }

    /// Parse technique enum from BKS truth rule/rationale
    fn parse_technique_from_truth(&self, truth: &BehavioralTruth) -> Option<PromptingTechnique> {
        // Example rule: "Use ChainOfThought for numerical reasoning"
        // Example rationale: "ChainOfThought achieves 92% success rate"
        let text = format!("{} {}", truth.rule, truth.rationale);

        for (technique_enum, metadata) in &self.techniques {
            // Check if technique name appears in the truth text
            if text.contains(&metadata.name) || text.contains(technique_enum.to_str()) {
                return Some(technique_enum.clone());
            }
        }

        None
    }

    /// Get count of techniques by complexity level
    pub fn count_by_complexity(&self, level: ComplexityLevel) -> usize {
        self.techniques
            .values()
            .filter(|t| t.complexity_level == level)
            .count()
    }
}

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

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

    #[test]
    fn test_library_contains_all_15_techniques() {
        let library = TechniqueLibrary::new();
        assert_eq!(library.techniques.len(), 15);
    }

    #[test]
    fn test_library_categories() {
        let library = TechniqueLibrary::new();

        assert_eq!(
            library
                .get_by_category(TechniqueCategory::RoleAssignment)
                .len(),
            1
        );
        assert_eq!(
            library
                .get_by_category(TechniqueCategory::EmotionalStimulus)
                .len(),
            2
        );
        assert_eq!(
            library.get_by_category(TechniqueCategory::Reasoning).len(),
            7
        );
        assert_eq!(library.get_by_category(TechniqueCategory::Others).len(), 5);
    }

    #[test]
    fn test_seal_quality_filtering() {
        let library = TechniqueLibrary::new();

        // Low quality (0.3) → only simple techniques
        let low_quality = library.get_by_seal_quality(0.3);
        assert!(low_quality.iter().all(|t| t.min_seal_quality <= 0.3));

        // High quality (0.9) → all techniques available
        let high_quality = library.get_by_seal_quality(0.9);
        assert_eq!(high_quality.len(), 15); // All techniques pass
    }

    #[test]
    fn test_technique_string_conversion() {
        assert_eq!(
            PromptingTechnique::parse_id("chain_of_thought").unwrap(),
            PromptingTechnique::ChainOfThought
        );
        assert_eq!(
            PromptingTechnique::parse_id("CoT").unwrap(),
            PromptingTechnique::ChainOfThought
        );
        assert_eq!(
            PromptingTechnique::ChainOfThought.to_str(),
            "chain_of_thought"
        );
    }
}