Files
zclaw_openfang/crates/zclaw-growth/src/lib.rs
iven 4b15ead8e7 feat(hermes): implement intelligence pipeline — 4 chunks, 684 tests passing
Hermes Intelligence Pipeline closes breakpoints in ZCLAW's existing
intelligence components with 4 self-contained modules:

Chunk 1 — Self-improvement Loop:
- ExperienceStore (zclaw-growth): FTS5+TF-IDF wrapper with scope prefix
- ExperienceExtractor (desktop/intelligence): template-based extraction
  from successful proposals with implicit keyword detection

Chunk 2 — User Modeling:
- UserProfileStore (zclaw-memory): SQLite-backed structured profiles
  with industry/role/expertise/comm_style/recent_topics/pain_points
- UserProfiler (desktop/intelligence): fact classification by category
  (Preference/Knowledge/Behavior) with profile summary formatting

Chunk 3 — NL Cron Chinese Time Parser:
- NlScheduleParser (zclaw-runtime): 6 pattern matchers for Chinese time
  expressions (每天/每周/工作日/间隔/每月/一次性) producing cron expressions
- Period-aware hour adjustment (下午3点→15, 晚上8点→20)
- Schedule intent detection + task description extraction

Chunk 4 — Trajectory Compression:
- TrajectoryStore (zclaw-memory): trajectory_events + compressed_trajectories
- TrajectoryRecorderMiddleware (zclaw-runtime/middleware): priority 650,
  async non-blocking event recording via tokio::spawn
- TrajectoryCompressor (desktop/intelligence): dedup, request classification,
  satisfaction detection, execution chain JSON

Schema migrations: v2→v3 (user_profiles), v3→v4 (trajectory tables)
2026-04-09 17:47:43 +08:00

148 lines
4.5 KiB
Rust

//! ZCLAW Agent Growth System
//!
//! This crate provides the agent growth functionality for ZCLAW,
//! enabling agents to learn and evolve from conversations.
//!
//! # Architecture
//!
//! The growth system consists of four main components:
//!
//! 1. **MemoryExtractor** (`extractor`) - Analyzes conversations and extracts
//! preferences, knowledge, and experience using LLM.
//!
//! 2. **MemoryRetriever** (`retriever`) - Performs semantic search over
//! stored memories to find contextually relevant information.
//!
//! 3. **PromptInjector** (`injector`) - Injects retrieved memories into
//! the system prompt with token budget control.
//!
//! 4. **GrowthTracker** (`tracker`) - Tracks growth metrics and evolution
//! over time.
//!
//! # Storage
//!
//! All memories are stored in OpenViking with a URI structure:
//!
//! ```text
//! agent://{agent_id}/
//! ├── preferences/{category} - User preferences
//! ├── knowledge/{domain} - Accumulated knowledge
//! ├── experience/{skill} - Skill/tool experience
//! └── sessions/{session_id}/ - Conversation history
//! ├── raw - Original conversation (L0)
//! ├── summary - Summary (L1)
//! └── keywords - Keywords (L2)
//! ```
//!
//! # Usage
//!
//! ```rust,ignore
//! use zclaw_growth::{MemoryExtractor, MemoryRetriever, PromptInjector, VikingAdapter};
//!
//! // Create components
//! let viking = VikingAdapter::in_memory();
//! let retriever = MemoryRetriever::new(Arc::new(viking.clone()));
//! let injector = PromptInjector::new();
//!
//! // Before conversation: retrieve relevant memories
//! let memories = retriever.retrieve(&agent_id, &user_input).await?;
//!
//! // Inject into system prompt
//! let enhanced_prompt = injector.inject(&base_prompt, &memories);
//!
//! // After conversation: extract and store new memories
//! let extracted = extractor.extract(&messages, session_id).await?;
//! extractor.store_memories(&agent_id, &extracted).await?;
//! ```
pub mod types;
pub mod extractor;
pub mod retriever;
pub mod injector;
pub mod tracker;
pub mod viking_adapter;
pub mod storage;
pub mod retrieval;
pub mod summarizer;
pub mod experience_store;
// Re-export main types for convenience
pub use types::{
DecayResult,
ExtractedMemory,
ExtractionConfig,
GrowthStats,
MemoryEntry,
MemoryType,
RetrievalConfig,
RetrievalResult,
UriBuilder,
effective_importance,
};
pub use extractor::{LlmDriverForExtraction, MemoryExtractor};
pub use retriever::{MemoryRetriever, MemoryStats};
pub use injector::{InjectionFormat, PromptInjector};
pub use tracker::{AgentMetadata, GrowthTracker, LearningEvent};
pub use viking_adapter::{FindOptions, VikingAdapter, VikingLevel, VikingStorage};
pub use storage::SqliteStorage;
pub use experience_store::{Experience, ExperienceStore};
pub use retrieval::{EmbeddingClient, MemoryCache, QueryAnalyzer, SemanticScorer};
pub use summarizer::SummaryLlmDriver;
/// Growth system configuration
#[derive(Debug, Clone)]
pub struct GrowthConfig {
/// Enable/disable growth system
pub enabled: bool,
/// Retrieval configuration
pub retrieval: RetrievalConfig,
/// Extraction configuration
pub extraction: ExtractionConfig,
/// Auto-extract after each conversation
pub auto_extract: bool,
}
impl Default for GrowthConfig {
fn default() -> Self {
Self {
enabled: true,
retrieval: RetrievalConfig::default(),
extraction: ExtractionConfig::default(),
auto_extract: true,
}
}
}
/// Convenience function to create a complete growth system
pub fn create_growth_system(
viking: std::sync::Arc<VikingAdapter>,
llm_driver: std::sync::Arc<dyn LlmDriverForExtraction>,
) -> (MemoryExtractor, MemoryRetriever, PromptInjector, GrowthTracker) {
let extractor = MemoryExtractor::new(llm_driver).with_viking(viking.clone());
let retriever = MemoryRetriever::new(viking.clone());
let injector = PromptInjector::new();
let tracker = GrowthTracker::new(viking);
(extractor, retriever, injector, tracker)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_growth_config_default() {
let config = GrowthConfig::default();
assert!(config.enabled);
assert!(config.auto_extract);
assert_eq!(config.retrieval.max_tokens, 500);
}
#[test]
fn test_memory_type_reexport() {
let mt = MemoryType::Preference;
assert_eq!(format!("{}", mt), "preferences");
}
}