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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
//! # Garrison Port - Conversation Memory Operations Interface
//!
//! Port trait defining how the application interacts with conversation memory storage (Garrison).
//!
//! ## Purpose
//!
//! The Garrison Port provides a unified abstraction for storing and retrieving conversation
//! history and context. It enables Paladin agents to maintain memory across interactions,
//! learn from past conversations, and provide contextually aware responses. The port supports:
//!
//! - **Short-Term Memory**: Recent conversation history (CRUD operations)
//! - **Semantic Search**: Text-based search across historical conversations
//! - **Long-Term Memory**: Vector embedding-based semantic similarity search (optional)
//! - **Statistics**: Token counts and storage metrics for memory management
//!
//! By decoupling memory operations from specific storage backends, Garrison Port enables:
//! - Switching between in-memory, database, or distributed storage
//! - Testing with mock implementations
//! - Optimizing for different use cases (speed vs. persistence vs. scale)
//!
//! ## Hexagonal Architecture
//!
//! This is an **output port** in the application layer. It defines the interface for memory
//! operations, allowing Paladin agents to maintain conversation context without depending on
//! specific storage implementations (SQL databases, NoSQL stores, in-memory caches).
//!
//! **Adapter Implementations:**
//! - `InMemoryGarrison` - Fast, volatile memory for development/testing
//! - `SqliteGarrison` - Persistent file-based storage for single-agent deployments
//! - `PostgresGarrison` - Scalable database storage for production multi-agent systems
//! - `RedisGarrison` - Distributed cache for high-performance, multi-instance deployments
//!
//! ## Thread Safety
//!
//! All implementations must be `Send + Sync` to support concurrent async operations.
//! Multiple Paladin agents may access the same Garrison simultaneously. Implementations
//! should handle concurrent reads/writes safely.
//!
//! ## Error Handling
//!
//! Operations return `Result<T, GarrisonError>` with specific error variants for:
//! - Storage failures (transient or permanent)
//! - Serialization issues (data format problems)
//! - Tokenization errors (token counting failures)
//! - Not found errors (missing entries)
//!
//! See [`GarrisonError`] for all error categories and handling strategies.
//!
//! ## Traits
//!
//! - [`GarrisonPort`]: Basic memory operations (CRUD, search, stats)
//! - [`LongTermGarrisonPort`]: Extended operations with vector embeddings for semantic search
//!
//! ## Examples
//!
//! ### Basic Usage
//!
//! ```rust,no_run
//! use paladin::application::ports::output::garrison_port::GarrisonPort;
//! use paladin::core::platform::container::garrison::{GarrisonEntry, ConversationRole};
//!
//! async fn conversation_memory(garrison: &dyn GarrisonPort) -> Result<(), Box<dyn std::error::Error>> {
//! // Store user message
//! let user_msg = GarrisonEntry::new(
//! ConversationRole::User,
//! "What is the capital of France?".to_string()
//! );
//! garrison.remember(user_msg).await?;
//!
//! // Store assistant response
//! let assistant_msg = GarrisonEntry::new(
//! ConversationRole::Assistant,
//! "The capital of France is Paris.".to_string()
//! );
//! garrison.remember(assistant_msg).await?;
//!
//! // Recall recent conversation
//! let recent = garrison.recall_recent(10).await?;
//! println!("Last {} messages:", recent.len());
//! for entry in recent {
//! println!("{:?}: {}", entry.role, entry.content);
//! }
//!
//! Ok(())
//! }
//! ```
//!
//! ### Search and Statistics
//!
//! ```rust,no_run
//! use paladin::application::ports::output::garrison_port::GarrisonPort;
//!
//! async fn search_history(garrison: &dyn GarrisonPort) -> Result<(), Box<dyn std::error::Error>> {
//! // Search for specific topics
//! let results = garrison.search("machine learning", 5).await?;
//! println!("Found {} messages about machine learning", results.len());
//!
//! // Check memory usage
//! let stats = garrison.stats().await?;
//! println!("Garrison stats:");
//! println!(" Entries: {}", stats.entry_count);
//! println!(" Tokens: {}", stats.total_tokens);
//! if let Some(size) = stats.size_bytes {
//! println!(" Size: {} KB", size / 1024);
//! }
//!
//! Ok(())
//! }
//! ```
//!
//! ### Custom Implementation
//!
//! ```rust,no_run
//! use paladin::application::ports::output::garrison_port::{GarrisonPort, GarrisonError, GarrisonStats};
//! use paladin::core::platform::container::garrison::GarrisonEntry;
//! use async_trait::async_trait;
//! use std::sync::{Arc, Mutex};
//!
//! struct CustomGarrison {
//! entries: Arc<Mutex<Vec<GarrisonEntry>>>,
//! }
//!
//! #[async_trait]
//! impl GarrisonPort for CustomGarrison {
//! async fn remember(&self, entry: GarrisonEntry) -> Result<(), GarrisonError> {
//! self.entries.lock().unwrap().push(entry);
//! Ok(())
//! }
//!
//! async fn recall_recent(&self, limit: usize) -> Result<Vec<GarrisonEntry>, GarrisonError> {
//! let entries = self.entries.lock().unwrap();
//! let start = entries.len().saturating_sub(limit);
//! Ok(entries[start..].to_vec())
//! }
//!
//! async fn search(&self, query: &str, limit: usize) -> Result<Vec<GarrisonEntry>, GarrisonError> {
//! let entries = self.entries.lock().unwrap();
//! let results: Vec<_> = entries
//! .iter()
//! .filter(|e| e.content.contains(query))
//! .take(limit)
//! .cloned()
//! .collect();
//! Ok(results)
//! }
//!
//! async fn forget_all(&self) -> Result<(), GarrisonError> {
//! self.entries.lock().unwrap().clear();
//! Ok(())
//! }
//!
//! async fn stats(&self) -> Result<GarrisonStats, GarrisonError> {
//! let entries = self.entries.lock().unwrap();
//! Ok(GarrisonStats {
//! entry_count: entries.len(),
//! total_tokens: entries.iter().map(|e| e.content.split_whitespace().count() as u32).sum(),
//! size_bytes: None,
//! })
//! }
//! }
//! ```
//!
//! ## Implementation Notes
//!
//! ### Performance Considerations
//! - **Batch Operations**: Retrieve multiple recent entries in one call rather than individual lookups
//! - **Indexing**: Index content for fast text search (full-text search indexes recommended)
//! - **Pagination**: Use `limit` parameters to avoid loading excessive data
//! - **Caching**: Cache frequently accessed recent entries
//! - **Token Counting**: Pre-calculate and store token counts to avoid re-computation
//!
//! ### Best Practices
//! 1. **Memory Management**: Monitor `stats()` and implement eviction policies (LRU, time-based)
//! 2. **Concurrent Access**: Use appropriate locking/transactions for thread safety
//! 3. **Error Recovery**: Implement retry logic for transient storage errors
//! 4. **Data Retention**: Implement `forget_all()` carefully with confirmation prompts
//! 5. **Search Optimization**: Use specialized search indexes rather than full table scans
//!
//! ### Common Pitfalls
//! - Don't hold locks during async operations (deadlock risk)
//! - Don't store entries without enforcing size limits (memory exhaustion)
//! - Don't use `forget_all()` in production without backup mechanisms
//! - Don't perform token counting synchronously on every insert (performance)
//!
//! ## Related Ports
//!
//! - [`SanctumPort`](crate::output::sanctum_port::SanctumPort) - Long-term persistent memory with vector embeddings (superset of LongTermGarrisonPort)
//! - [`EmbeddingPort`](crate::output::embedding_port::EmbeddingPort) - Generate vector embeddings for semantic search
//! - [`LlmPort`](crate::output::llm_port::LlmPort) - LLM integration (uses Garrison for conversation context)
//! - [`CitadelPort`](crate::output::citadel_port::CitadelPort) - State persistence for entire Paladin agents
//!
//! ## See Also
//!
//! - [Application Ports](crate::application::ports)
//! - [Garrison Domain](paladin_core::platform::container::garrison)
//! - [Infrastructure Adapters](crate::infrastructure::adapters::garrison)
use async_trait;
use GarrisonEntry;
use ;
pub use GarrisonError;
/// Statistics about a Garrison's current state.
///
/// Provides metrics for monitoring memory usage, token consumption, and storage capacity.
/// Use these statistics to implement eviction policies, display memory status to users,
/// and optimize Paladin agent performance.
///
/// # Fields
///
/// - `entry_count`: Number of conversation entries currently stored
/// - `total_tokens`: Cumulative token count across all entries (for LLM context management)
/// - `size_bytes`: Approximate storage size in bytes (implementation-dependent)
///
/// # Examples
///
/// ```rust
/// use paladin::application::ports::output::garrison_port::GarrisonStats;
///
/// let stats = GarrisonStats {
/// entry_count: 150,
/// total_tokens: 8000,
/// size_bytes: Some(102400), // ~100 KB
/// };
///
/// // Check if approaching token limit
/// const MAX_TOKENS: u32 = 10000;
/// if stats.total_tokens > MAX_TOKENS * 80 / 100 {
/// println!("Warning: Using {}% of token capacity",
/// stats.total_tokens * 100 / MAX_TOKENS);
/// }
/// ```
// GarrisonError is re-exported from core for API compatibility.
/// Port for basic Garrison memory operations.
///
/// This trait defines the core interface for storing and retrieving conversation
/// history. All Garrison implementations must implement this trait to enable Paladin
/// agents to maintain context across interactions.
///
/// # Capabilities
///
/// - **Storage**: Add new conversation entries with [`remember`](Self::remember)
/// - **Retrieval**: Get recent entries with [`recall_recent`](Self::recall_recent)
/// - **Search**: Find entries by text query with [`search`](Self::search)
/// - **Management**: Clear all entries with [`forget_all`](Self::forget_all)
/// - **Monitoring**: Get storage statistics with [`stats`](Self::stats)
///
/// # Thread Safety
///
/// All implementations must be `Send + Sync` to support async operations across
/// thread boundaries. Multiple Paladin agents may access the same Garrison concurrently.
///
/// # Implementation Requirements
///
/// Implementations should:
/// 1. Store entries in chronological order
/// 2. Return recent entries from oldest to newest
/// 3. Support concurrent read/write operations safely
/// 4. Handle storage failures gracefully (return appropriate errors)
/// 5. Calculate token counts accurately for context window management
///
/// # Examples
///
/// ## Basic Conversation Storage
///
/// ```rust,no_run
/// use paladin::application::ports::output::garrison_port::GarrisonPort;
/// use paladin::core::platform::container::garrison::{GarrisonEntry, ConversationRole};
///
/// async fn conversation_flow(garrison: &dyn GarrisonPort) -> Result<(), Box<dyn std::error::Error>> {
/// // Store user input
/// let user_entry = GarrisonEntry::new(
/// ConversationRole::User,
/// "What is Rust?".to_string()
/// );
/// garrison.remember(user_entry).await?;
///
/// // Store assistant response
/// let assistant_entry = GarrisonEntry::new(
/// ConversationRole::Assistant,
/// "Rust is a systems programming language...".to_string()
/// );
/// garrison.remember(assistant_entry).await?;
///
/// // Retrieve for next interaction
/// let history = garrison.recall_recent(10).await?;
/// println!("Context has {} messages", history.len());
///
/// Ok(())
/// }
/// ```
///
/// ## Memory Management
///
/// ```rust,no_run
/// use paladin::application::ports::output::garrison_port::GarrisonPort;
///
/// async fn manage_memory(garrison: &dyn GarrisonPort) -> Result<(), Box<dyn std::error::Error>> {
/// // Check current usage
/// let stats = garrison.stats().await?;
/// println!("Entries: {}, Tokens: {}", stats.entry_count, stats.total_tokens);
///
/// // Implement eviction policy
/// const MAX_TOKENS: u32 = 8000;
/// if stats.total_tokens > MAX_TOKENS {
/// println!("Approaching token limit, consider clearing old entries");
/// // In production: implement LRU or time-based eviction
/// }
///
/// Ok(())
/// }
/// ```
///
/// ## Search Historical Context
///
/// ```rust,no_run
/// use paladin::application::ports::output::garrison_port::GarrisonPort;
///
/// async fn search_context(garrison: &dyn GarrisonPort) -> Result<(), Box<dyn std::error::Error>> {
/// // Find past discussions about specific topics
/// let results = garrison.search("deployment", 5).await?;
///
/// if results.is_empty() {
/// println!("No prior discussions about deployment");
/// } else {
/// println!("Found {} relevant messages:", results.len());
/// for entry in results {
/// println!(" - {:?}: {}", entry.role, entry.content.chars().take(50).collect::<String>());
/// }
/// }
///
/// Ok(())
/// }
/// ```
///
/// # Implementation Notes
///
/// ## Performance Optimization
/// - Cache recently accessed entries to reduce storage lookups
/// - Use database indexes on timestamp/role columns for fast `recall_recent()`
/// - Implement full-text search indexes for `search()` queries
/// - Pre-calculate token counts on insert rather than on-demand
///
/// ## Concurrency Patterns
/// ```rust,ignore
/// // Good: Async-safe lock-free design
/// use tokio::sync::RwLock;
/// struct MyGarrison {
/// entries: Arc<RwLock<Vec<GarrisonEntry>>>,
/// }
///
/// // Avoid: Blocking mutex in async context
/// // use std::sync::Mutex; // DON'T do this in async code
/// ```
///
/// ## Error Handling Best Practices
/// - Return `StorageError` for transient failures (database timeout)
/// - Return `SerializationError` for permanent data issues
/// - Log errors before returning for debugging
/// - Implement retry logic in adapter, not in port trait
///
/// # See Also
///
/// - [`LongTermGarrisonPort`] - Extended trait with vector embedding support
/// - [`SanctumPort`] - Long-term persistent memory (alternative/superset)
/// - [`GarrisonEntry`](paladin_core::platform::container::garrison::GarrisonEntry) - Entry data structure
/// Extended port for long-term memory with semantic search capabilities.
///
/// This trait extends [`GarrisonPort`] with vector embedding support for semantic
/// similarity search. Use this when you need to find conceptually similar past
/// conversations, not just exact text matches.
///
/// # Capabilities
///
/// Beyond basic [`GarrisonPort`] operations:
/// - **Semantic Storage**: Store entries with vector embeddings
/// - **Similarity Search**: Find entries by semantic similarity (cosine distance)
///
/// # Use Cases
///
/// - **Knowledge Base**: Find related past solutions when user asks new questions
/// - **Context Retrieval**: Pull in relevant historical context based on current topic
/// - **Deduplication**: Detect similar/duplicate queries before processing
/// - **Recommendation**: Suggest related past conversations to users
///
/// # Embedding Models
///
/// This trait is agnostic to embedding model choice. Common options:
/// - OpenAI `text-embedding-3-small` (1536 dimensions)
/// - OpenAI `text-embedding-3-large` (3072 dimensions)
/// - Sentence Transformers (768 dimensions)
/// - Custom fine-tuned models
///
/// **Important**: All entries in a Garrison must use the same embedding model
/// and dimension for accurate similarity comparisons.
///
/// # Thread Safety
///
/// Same requirements as [`GarrisonPort`]: implementations must be `Send + Sync`.
///
/// # Examples
///
/// ## Semantic Context Retrieval
///
/// ```rust,no_run
/// use paladin::application::ports::output::garrison_port::LongTermGarrisonPort;
/// use paladin::application::ports::output::embedding_port::EmbeddingPort;
/// use paladin::core::platform::container::garrison::{GarrisonEntry, ConversationRole};
///
/// async fn semantic_context(
/// garrison: &dyn LongTermGarrisonPort,
/// embedder: &dyn EmbeddingPort,
/// query: &str,
/// ) -> Result<(), Box<dyn std::error::Error>> {
/// // Generate query embedding
/// let embedding = embedder.embed_text(query).await?;
///
/// // Find semantically similar past conversations
/// let similar = garrison.search_similar(embedding.vector, 5).await?;
///
/// println!("Found {} related discussions:", similar.len());
/// for entry in similar {
/// println!(" {:?}: {}...", entry.role,
/// entry.content.chars().take(60).collect::<String>());
/// }
///
/// Ok(())
/// }
/// ```
///
/// ## Store with Embeddings
///
/// ```rust,no_run
/// use paladin::application::ports::output::garrison_port::LongTermGarrisonPort;
/// use paladin::application::ports::output::embedding_port::EmbeddingPort;
/// use paladin::core::platform::container::garrison::{GarrisonEntry, ConversationRole};
///
/// async fn store_with_embedding(
/// garrison: &dyn LongTermGarrisonPort,
/// embedder: &dyn EmbeddingPort,
/// ) -> Result<(), Box<dyn std::error::Error>> {
/// let content = "How do I deploy a Rust application to production?";
///
/// // Create entry
/// let entry = GarrisonEntry::new(
/// ConversationRole::User,
/// content.to_string()
/// );
///
/// // Generate embedding
/// let embedding = embedder.embed_text(content).await?;
///
/// // Store with semantic searchability
/// garrison.remember_with_embedding(entry, embedding.vector.clone()).await?;
///
/// println!("Stored entry with {}-dimensional embedding", embedding.vector.len());
/// Ok(())
/// }
/// ```
///
/// ## Hybrid Search (Text + Semantic)
///
/// ```rust,no_run
/// use paladin::application::ports::output::garrison_port::{GarrisonPort, LongTermGarrisonPort};
/// use paladin::application::ports::output::embedding_port::EmbeddingPort;
/// use paladin::core::platform::container::garrison::GarrisonEntry;
///
/// async fn hybrid_search(
/// garrison: &dyn LongTermGarrisonPort,
/// embedder: &dyn EmbeddingPort,
/// query: &str,
/// ) -> Result<Vec<GarrisonEntry>, Box<dyn std::error::Error>> {
/// // Text-based search (fast, exact matches)
/// let text_results = garrison.search(query, 10).await?;
///
/// // Semantic search (slower, conceptual matches)
/// let embedding = embedder.embed_text(query).await?;
/// let semantic_results = garrison.search_similar(embedding.vector, 10).await?;
///
/// // Combine results (deduplicate by ID if applicable)
/// let mut combined = text_results;
/// combined.extend(semantic_results);
///
/// Ok(combined)
/// }
/// ```
///
/// # Implementation Notes
///
/// ## Vector Storage
/// - Use specialized vector databases (Qdrant, Pinecone, Weaviate)
/// - Or vector extensions for SQL (pgvector for PostgreSQL)
/// - Store embeddings as BLOB/BYTEA with indexes
///
/// ## Similarity Calculation
/// - Use cosine similarity: `dot(a, b) / (norm(a) * norm(b))`
/// - Normalize embeddings before storage for faster cosine similarity
/// - Consider approximate nearest neighbor (ANN) indexes for large datasets
///
/// ## Performance Optimization
/// ```rust,ignore
/// // Pre-normalize embeddings for faster similarity search
/// fn normalize(embedding: &[f32]) -> Vec<f32> {
/// let norm: f32 = embedding.iter().map(|x| x * x).sum::<f32>().sqrt();
/// embedding.iter().map(|x| x / norm).collect()
/// }
/// ```
///
/// ## Best Practices
/// 1. **Embedding Consistency**: Always use same model and dimension
/// 2. **Batch Embedding**: Generate embeddings in batches for efficiency
/// 3. **Cache Embeddings**: Don't regenerate for same content
/// 4. **Dimension Validation**: Validate embedding dimensions on insert
/// 5. **Index Strategy**: Use HNSW or IVF indexes for large-scale similarity search
///
/// ## Common Pitfalls
/// - Mixing embeddings from different models (invalid similarity scores)
/// - Not normalizing embeddings (inconsistent cosine similarity)
/// - Linear scan for similarity (use ANN indexes)
/// - Storing embeddings as JSON (inefficient, use binary format)
///
/// # See Also
///
/// - [`GarrisonPort`] - Base trait (this extends it)
/// - [`SanctumPort`] - Production-grade long-term memory with embeddings
/// - [`EmbeddingPort`] - Generate vector embeddings
/// - [Vector Embeddings Guide](https://platform.openai.com/docs/guides/embeddings)