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
//! Protocol definition types
//!
//! Defines the schema for ThinkTool protocols with full serde support.
//!
//! # Serialization
//!
//! Protocols support JSON serialization via `to_json()` / `from_json()`:
//!
//! ```rust,ignore
//! let json = protocol.to_json()?;
//! let restored = Protocol::from_json(&json)?;
//! ```
//!
//! For high-performance serialization of simpler types (e.g., traces, metrics),
//! see `crate::integrations::performance::fast_serialize()` when compiled with
//! `--features performance`.
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
/// A ThinkTool Protocol definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Protocol {
/// Unique protocol identifier (e.g., "gigathink", "laserlogic")
pub id: String,
/// Human-readable name
pub name: String,
/// Protocol version (semver)
pub version: String,
/// Brief description
pub description: String,
/// Reasoning strategy category
pub strategy: ReasoningStrategy,
/// Input specification
pub input: InputSpec,
/// Protocol steps (ordered)
pub steps: Vec<ProtocolStep>,
/// Output specification
pub output: OutputSpec,
/// Validation rules
#[serde(default)]
pub validation: Vec<ValidationRule>,
/// Metadata for composition
#[serde(default)]
pub metadata: ProtocolMetadata,
}
/// Reasoning strategy categories
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[derive(Default)]
pub enum ReasoningStrategy {
/// Divergent thinking - maximize perspectives
Expansive,
/// Convergent thinking - deduce conclusions
Deductive,
/// Break down to fundamentals
#[default]
Analytical,
/// Challenge and critique
Adversarial,
/// Cross-reference and confirm
Verification,
/// Weigh options systematically
Decision,
/// Scientific method
Empirical,
}
/// Input specification for a protocol
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct InputSpec {
/// Required input fields
#[serde(default)]
pub required: Vec<String>,
/// Optional input fields
#[serde(default)]
pub optional: Vec<String>,
}
/// Output specification for a protocol
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct OutputSpec {
/// Output format name
pub format: String,
/// Output fields
#[serde(default)]
pub fields: Vec<String>,
}
/// A single step in a protocol
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProtocolStep {
/// Step identifier within protocol
pub id: String,
/// What this step does
pub action: StepAction,
/// Prompt template (with {{placeholders}})
pub prompt_template: String,
/// Expected output format
pub output_format: StepOutputFormat,
/// Minimum confidence to proceed (0.0 - 1.0)
#[serde(default = "default_min_confidence")]
pub min_confidence: f64,
/// Dependencies on previous steps
#[serde(default)]
pub depends_on: Vec<String>,
/// Optional branching conditions
#[serde(default)]
pub branch: Option<BranchCondition>,
}
fn default_min_confidence() -> f64 {
0.7
}
/// Step action types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum StepAction {
/// Generate perspectives/ideas
Generate {
/// Minimum number of items to generate
#[serde(default = "default_min_count")]
min_count: usize,
/// Maximum number of items to generate
#[serde(default = "default_max_count")]
max_count: usize,
},
/// Analyze/evaluate input
Analyze {
/// Criteria for analysis
#[serde(default)]
criteria: Vec<String>,
},
/// Synthesize multiple inputs
Synthesize {
/// Aggregation method to use
#[serde(default)]
aggregation: AggregationType,
},
/// Validate against rules
Validate {
/// Validation rules to apply
#[serde(default)]
rules: Vec<String>,
},
/// Challenge/critique
Critique {
/// Severity level for critique
#[serde(default)]
severity: CritiqueSeverity,
},
/// Make decision
Decide {
/// Decision method to use
#[serde(default)]
method: DecisionMethod,
},
/// Cross-reference sources
CrossReference {
/// Minimum number of sources required
#[serde(default = "default_min_sources")]
min_sources: usize,
},
}
fn default_min_count() -> usize {
3
}
fn default_max_count() -> usize {
10
}
fn default_min_sources() -> usize {
3
}
/// Output format for a step
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StepOutputFormat {
/// Free-form text
#[default]
Text,
/// Numbered/bulleted list
List,
/// Key-value structured data
Structured,
/// Numeric score (0.0 - 1.0)
Score,
/// Boolean decision
Boolean,
}
/// Aggregation types for synthesis
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AggregationType {
/// Group by themes
#[default]
ThematicClustering,
/// Simple concatenation
Concatenate,
/// Weighted by confidence
WeightedMerge,
/// Majority voting
Consensus,
}
/// Severity levels for critique
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CritiqueSeverity {
/// Light review
Light,
/// Standard critique
#[default]
Standard,
/// Adversarial challenge
Adversarial,
/// Maximum scrutiny
Brutal,
}
/// Methods for decision making
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DecisionMethod {
/// Simple pros/cons
#[default]
ProsCons,
/// Multi-criteria analysis
MultiCriteria,
/// Expected value calculation
ExpectedValue,
/// Regret minimization
RegretMinimization,
}
/// Conditional branching
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum BranchCondition {
/// Branch if confidence below threshold
ConfidenceBelow {
/// Confidence threshold value
threshold: f64,
},
/// Branch if confidence above threshold
ConfidenceAbove {
/// Confidence threshold value
threshold: f64,
},
/// Branch based on output value
OutputEquals {
/// Field name to check
field: String,
/// Expected value
value: String,
},
/// Always execute (unconditional)
Always,
}
/// Validation rule for protocol output
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "rule", rename_all = "snake_case")]
pub enum ValidationRule {
/// Minimum number of items
MinCount {
/// Field name to validate
field: String,
/// Minimum count value
value: usize,
},
/// Maximum number of items
MaxCount {
/// Field name to validate
field: String,
/// Maximum count value
value: usize,
},
/// Confidence must be in range
ConfidenceRange {
/// Minimum confidence value
min: f64,
/// Maximum confidence value
max: f64,
},
/// Field must be present
Required {
/// Required field name
field: String,
},
/// Custom validation (expression)
Custom {
/// Validation expression
expression: String,
},
}
/// Protocol metadata for composition and optimization
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ProtocolMetadata {
/// Category tag
#[serde(default)]
pub category: String,
/// Protocols this can be composed with
#[serde(default)]
pub composable_with: Vec<String>,
/// Typical token usage
#[serde(default)]
pub typical_tokens: u32,
/// Estimated latency in milliseconds
#[serde(default)]
pub estimated_latency_ms: u32,
/// Additional key-value metadata
#[serde(default)]
pub extra: HashMap<String, serde_json::Value>,
}
impl Protocol {
/// Create a new protocol with required fields
pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
Self {
id: id.into(),
name: name.into(),
version: "1.0.0".to_string(),
description: String::new(),
strategy: ReasoningStrategy::default(),
input: InputSpec::default(),
steps: Vec::new(),
output: OutputSpec::default(),
validation: Vec::new(),
metadata: ProtocolMetadata::default(),
}
}
/// Add a step to the protocol
pub fn with_step(mut self, step: ProtocolStep) -> Self {
self.steps.push(step);
self
}
/// Set the reasoning strategy
pub fn with_strategy(mut self, strategy: ReasoningStrategy) -> Self {
self.strategy = strategy;
self
}
/// Validate protocol definition
pub fn validate(&self) -> Result<(), Vec<String>> {
let mut errors = Vec::new();
if self.id.is_empty() {
errors.push("Protocol ID cannot be empty".to_string());
}
if self.steps.is_empty() {
errors.push("Protocol must have at least one step".to_string());
}
// Check step dependencies
let step_ids: Vec<&str> = self.steps.iter().map(|s| s.id.as_str()).collect();
for step in &self.steps {
for dep in &step.depends_on {
if !step_ids.contains(&dep.as_str()) {
errors.push(format!(
"Step '{}' depends on unknown step '{}'",
step.id, dep
));
}
}
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
/// Serialize protocol to JSON (standard serde)
///
/// Note: Protocol uses `to_json()` rather than bitcode due to complex
/// serde attributes. For hot-path data serialization, use
/// `crate::integrations::performance::fast_serialize()` with simpler types.
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string(self)
}
/// Serialize protocol to pretty JSON (standard serde)
pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
serde_json::to_string_pretty(self)
}
/// Deserialize protocol from JSON
pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(json)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_protocol_creation() {
let protocol = Protocol::new("test", "Test Protocol")
.with_strategy(ReasoningStrategy::Expansive)
.with_step(ProtocolStep {
id: "step1".to_string(),
action: StepAction::Generate {
min_count: 5,
max_count: 10,
},
prompt_template: "Generate ideas for: {{query}}".to_string(),
output_format: StepOutputFormat::List,
min_confidence: 0.7,
depends_on: Vec::new(),
branch: None,
});
assert_eq!(protocol.id, "test");
assert_eq!(protocol.steps.len(), 1);
assert!(protocol.validate().is_ok());
}
#[test]
fn test_protocol_validation_empty_steps() {
let protocol = Protocol::new("test", "Test Protocol");
let result = protocol.validate();
assert!(result.is_err());
assert!(result
.unwrap_err()
.iter()
.any(|e| e.contains("at least one step")));
}
#[test]
fn test_step_action_serialization() {
let action = StepAction::Generate {
min_count: 5,
max_count: 10,
};
let json = serde_json::to_string(&action).expect("Failed to serialize");
assert!(json.contains("generate"));
let parsed: StepAction = serde_json::from_str(&json).expect("Failed to deserialize");
match parsed {
StepAction::Generate {
min_count,
max_count,
} => {
assert_eq!(min_count, 5);
assert_eq!(max_count, 10);
}
_ => panic!("Wrong action type"),
}
}
#[test]
fn test_protocol_json_roundtrip() {
let protocol = Protocol::new("test", "Test Protocol")
.with_strategy(ReasoningStrategy::Expansive)
.with_step(ProtocolStep {
id: "step1".to_string(),
action: StepAction::Generate {
min_count: 5,
max_count: 10,
},
prompt_template: "Generate: {{query}}".to_string(),
output_format: StepOutputFormat::List,
min_confidence: 0.7,
depends_on: Vec::new(),
branch: None,
});
// Test JSON round-trip
let json = protocol.to_json().expect("Failed to serialize to JSON");
let restored = Protocol::from_json(&json).expect("Failed to deserialize from JSON");
assert_eq!(protocol.id, restored.id);
assert_eq!(protocol.steps.len(), restored.steps.len());
}
#[cfg(feature = "performance")]
#[test]
fn test_fast_serialize_simple_types() {
// Note: bitcode serde works best with simple types.
// Complex enums with #[serde(tag = "type")] require native bitcode derives.
// For Protocol structs, use to_json() / from_json() instead.
use crate::integrations::performance::{fast_deserialize, fast_serialize};
// Test with owned String data that bitcode handles well
let simple_data: Vec<String> = vec![
"gigathink".to_string(),
"laserlogic".to_string(),
"bedrock".to_string(),
];
let bytes = fast_serialize(&simple_data).expect("Failed to serialize");
let restored: Vec<String> = fast_deserialize(&bytes).expect("Failed to deserialize");
assert_eq!(simple_data, restored);
// Protocol metadata works (no complex enums)
let metadata = ProtocolMetadata {
category: "reasoning".to_string(),
composable_with: vec!["laserlogic".to_string()],
typical_tokens: 500,
estimated_latency_ms: 100,
extra: std::collections::HashMap::new(),
};
let bytes = fast_serialize(&metadata).expect("Failed to serialize metadata");
let restored: ProtocolMetadata = fast_deserialize(&bytes).expect("Failed to deserialize");
assert_eq!(metadata.category, restored.category);
}
}