mod rank;
pub use rank::{RecordKey, RecordRanking};
use serde_json::{Map, Value, json};
use super::{Kind, TurnRecord};
use crate::conversation::rank::{Bounds, Order, bounds};
use crate::memory::search::matching::{lower, terms, window};
use crate::store::time::Stamp;
pub const SEARCHABLE: [Kind; 5] = [
Kind::Prompt,
Kind::Reply,
Kind::System,
Kind::ToolResult,
Kind::ToolCall,
];
#[derive(Clone, Debug)]
pub struct RecordSearch {
pub terms: Vec<String>,
pub conversations: Option<Vec<String>>,
pub kinds: Vec<Kind>,
pub order: Order,
pub bounds: Bounds,
pub limit: usize,
}
impl RecordSearch {
pub fn new(
query: &str,
kinds: Option<Vec<Kind>>,
order: Order,
since: Option<String>,
before: Option<String>,
limit: usize,
) -> Result<Self, String> {
let count = query.split_whitespace().count();
if !(1..=1024).contains(&query.chars().count()) || !(1..=16).contains(&count) {
return Err("query requires 1..1024 characters and 1..16 whitespace terms".into());
}
let mut chosen = Vec::new();
for kind in kinds.unwrap_or_else(|| SEARCHABLE.to_vec()) {
if !kind.searchable() {
return Err(format!("kind {:?} is not searchable", kind.as_str()));
}
if !chosen.contains(&kind) {
chosen.push(kind);
}
}
if !(1..=100).contains(&limit) {
return Err("limit must be between 1 and 100".into());
}
Ok(Self {
terms: terms(query),
conversations: None,
kinds: chosen,
order,
bounds: bounds(since.as_deref(), before.as_deref())?,
limit,
})
}
}
fn matched(record: &TurnRecord) -> (Option<String>, String) {
let name = record
.name
.as_deref()
.filter(|_| record.kind == Kind::ToolCall)
.map(lower);
(name, lower(&record.text))
}
pub fn record_facts(record: &TurnRecord, terms: &[String]) -> (Vec<u32>, u64) {
let (name, text) = matched(record);
let count = |folded: &str, term: &str| folded.matches(term).count();
let counts = terms
.iter()
.map(|term| {
let found = name.as_deref().map_or(0, |name| count(name, term)) + count(&text, term);
u32::try_from(found).unwrap_or(u32::MAX)
})
.collect();
let length = name.map_or(0, |name| name.chars().count() as u64 + 1);
(counts, length + text.chars().count() as u64)
}
pub fn record_excerpt(text: &str, terms: &[String]) -> (usize, String) {
let folded = lower(text);
let first = terms
.iter()
.filter_map(|term| folded.find(term.as_str()))
.min();
window(text, first.unwrap_or(0))
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RecordHit {
pub conversation_id: String,
pub turn: u64,
pub seq: u64,
pub message: u64,
pub kind: Kind,
pub call_id: Option<String>,
pub name: Option<String>,
pub created_at: Stamp,
pub actor: Option<String>,
pub size: u64,
pub excerpt: (usize, String),
pub score: Option<u64>,
}
impl RecordHit {
pub fn to_json(&self) -> Value {
let mut map = Map::new();
map.insert("conversation_id".into(), json!(self.conversation_id));
map.insert("turn".into(), json!(self.turn));
map.insert("seq".into(), json!(self.seq));
map.insert("message".into(), json!(self.message));
map.insert("kind".into(), json!(self.kind.as_str()));
map.insert("call_id".into(), json!(self.call_id));
map.insert("name".into(), json!(self.name));
map.insert("created_at".into(), json!(self.created_at.z()));
map.insert("actor".into(), json!(self.actor));
map.insert("size".into(), json!(self.size));
let (offset, text) = &self.excerpt;
map.insert("excerpt".into(), json!({"offset": offset, "text": text}));
if let Some(score) = self.score {
map.insert("score".into(), json!(score));
}
Value::Object(map)
}
}