1use std::collections::{BTreeMap, BTreeSet, HashMap};
8use std::path::{Path, PathBuf};
9
10use crate::embed::{Embedder, cosine};
11use crate::files::{one_line, slug, title_of};
12use crate::{
13 Change, Context, DEFAULT_LIMIT, Error, Found, MAX_LIMIT, Memory, New, Problem, Scope, search,
14 split_id, time,
15};
16
17pub(crate) const RELATED_BASE: u32 = 500;
21pub(crate) const NEAR: f32 = 0.5;
24
25pub(crate) const IN_PROJECT: &str = "IN_PROJECT";
28pub(crate) const IN_SESSION: &str = "IN_SESSION";
29pub(crate) const ABOUT_FILE: &str = "ABOUT_FILE";
30pub(crate) const ABOUT_PANE: &str = "ABOUT_PANE";
31pub(crate) const LINKS_TO: &str = "LINKS_TO";
32
33#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct CollectorRow {
38 pub collector: String,
39 pub at_unix_ms: u64,
40 pub pane: String,
42 pub session: Option<String>,
43 pub cwd: Option<PathBuf>,
44 pub command: Option<String>,
45 pub fields: Vec<(String, String)>,
46 pub context: Vec<String>,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct Summary {
52 pub session: String,
53 pub text: String,
54 pub updated_unix_ms: u64,
55}
56
57pub(crate) type Vectors = HashMap<String, Vec<f32>>;
59
60pub(crate) fn key(scope: Scope, owner: &str, name: &str) -> String {
63 format!("{}\0{owner}\0{name}", scope.name())
64}
65
66pub(crate) fn owner(cx: &Context, scope: Scope) -> Result<String, Error> {
73 Ok(match scope {
74 Scope::User | Scope::Host => String::new(),
75 Scope::Project => {
76 let root = crate::project_of(cx)?;
77 std::fs::canonicalize(&root)
78 .unwrap_or(root)
79 .display()
80 .to_string()
81 }
82 Scope::Session => crate::session_of(cx)?.to_owned(),
83 })
84}
85
86pub(crate) fn scopes(cx: &Context, scope: Option<Scope>) -> Vec<Scope> {
88 scope.map_or_else(|| crate::reach(cx), |s| vec![s])
89}
90
91pub(crate) fn newest_first(items: &mut [(String, Memory)]) {
93 items.sort_by(|(_, a), (_, b)| {
94 b.updated_unix_ms
95 .cmp(&a.updated_unix_ms)
96 .then(a.id.cmp(&b.id))
97 });
98}
99
100pub(crate) fn wanted(
103 cx: &Context,
104 scope: Scope,
105 owner: &str,
106 links: &[String],
107 mut exists: impl FnMut(&str) -> Result<bool, Error>,
108) -> Result<BTreeSet<(&'static str, String)>, Error> {
109 let mut out = BTreeSet::new();
110 match scope {
111 Scope::Project => {
112 out.insert((IN_PROJECT, owner.to_owned()));
113 }
114 Scope::Session => {
115 out.insert((IN_SESSION, owner.to_owned()));
116 }
117 Scope::User | Scope::Host => {}
118 }
119 for l in links {
120 let l = l.trim();
121 if l.is_empty() || l.contains("://") {
122 continue;
123 }
124 if let Ok((s, name)) = split_id(l)
126 && let Ok(o) = self::owner(cx, s)
127 {
128 let target = key(s, &o, name);
129 if exists(&target)? {
130 out.insert((LINKS_TO, target));
131 continue;
132 }
133 }
134 if let Some(pane) = l.strip_prefix("pane:") {
135 out.insert((ABOUT_PANE, pane.trim().to_owned()));
136 continue;
137 }
138 if l.starts_with('%') && l.len() > 1 && l[1..].bytes().all(|b| b.is_ascii_digit()) {
139 out.insert((ABOUT_PANE, l.to_owned()));
140 continue;
141 }
142 let p = Path::new(l);
144 let path = if p.is_relative() && scope == Scope::Project {
145 Path::new(owner).join(p).display().to_string()
146 } else {
147 l.to_owned()
148 };
149 out.insert((ABOUT_FILE, path));
150 }
151 Ok(out)
152}
153
154pub(crate) fn fresh(
158 cx: &Context,
159 new: New,
160 mut taken: impl FnMut(&str) -> Result<bool, Error>,
161) -> Result<(String, String, Memory), Error> {
162 if new.text.trim().is_empty() {
163 return Err(Error::Invalid("a memory needs text".into()));
164 }
165 let owner = owner(cx, new.scope)?;
166 let title = new
167 .title
168 .as_deref()
169 .map(one_line)
170 .filter(|t| !t.is_empty())
171 .unwrap_or_else(|| title_of(&new.text));
172 let description = new
173 .description
174 .as_deref()
175 .map(one_line)
176 .filter(|d| !d.is_empty())
177 .unwrap_or_else(|| title.clone());
178 let base = slug(&title);
179 let mut name = base.clone();
180 for n in 2.. {
181 if !taken(&key(new.scope, &owner, &name))? {
182 break;
183 }
184 name = format!("{base}-{n}");
185 }
186 let now = time::now_ms();
187 let m = Memory {
188 id: format!("{}/{name}", new.scope.name()),
189 scope: new.scope,
190 kind: new.kind,
191 title,
192 description,
193 text: new.text.trim_end().to_owned(),
194 links: new.links,
195 created_unix_ms: now,
196 updated_unix_ms: now,
197 path: None,
198 score: None,
199 };
200 Ok((key(new.scope, &owner, &name), owner, m))
201}
202
203pub(crate) fn changed(mut m: Memory, change: Change) -> Result<Memory, Error> {
205 if let Some(t) = change.text {
206 if t.trim().is_empty() {
207 return Err(Error::Invalid("a memory needs text".into()));
208 }
209 m.text = t.trim_end().to_owned();
210 }
211 if let Some(kind) = change.kind {
212 m.kind = kind;
213 }
214 if let Some(t) = change.title.as_deref().map(one_line) {
215 if t.is_empty() {
216 return Err(Error::Invalid("a title cannot be empty".into()));
217 }
218 m.title = t;
219 }
220 if let Some(d) = change.description.as_deref() {
221 m.description = one_line(d);
222 }
223 if let Some(l) = change.links {
224 m.links = l;
225 }
226 m.updated_unix_ms = time::now_ms().max(m.updated_unix_ms);
227 Ok(m)
228}
229
230pub(crate) fn placed(cx: &Context, m: &Memory) -> Result<(String, String, Memory), Error> {
232 if m.text.trim().is_empty() {
233 return Err(Error::Invalid("a memory needs text".into()));
234 }
235 let (scope, name) = split_id(&m.id)?;
236 if scope != m.scope {
237 return Err(Error::Invalid(format!(
238 "`{}` is not in the {} scope",
239 m.id,
240 m.scope.name()
241 )));
242 }
243 let owner = owner(cx, scope)?;
244 let mut m = m.clone();
245 m.text = m.text.trim_end().to_owned();
246 m.path = None;
247 m.score = None;
248 Ok((key(scope, &owner, name), owner, m))
249}
250
251pub(crate) fn shown(rel: &str, target: &str) -> String {
253 if rel == LINKS_TO {
254 let mut parts = target.split('\0');
255 let scope = parts.next().unwrap_or_default();
256 let name = parts.nth(1).unwrap_or_default();
257 format!("{scope}/{name}")
258 } else {
259 target.to_owned()
260 }
261}
262
263pub(crate) fn vector_text(m: &Memory) -> String {
265 format!("{}\n{}\n{}", m.title, m.description, m.text)
266}
267
268pub(crate) fn held(from: i64, to: Option<i64>, at: i64) -> bool {
271 from <= at && to.is_none_or(|t| t > at)
272}
273
274pub(crate) fn now_us() -> i64 {
276 std::time::SystemTime::now()
277 .duration_since(std::time::UNIX_EPOCH)
278 .map_or(0, |d| i64::try_from(d.as_micros()).unwrap_or(i64::MAX))
279}
280
281pub(crate) fn ms_to_us(unix_ms: u64) -> i64 {
283 i64::try_from(unix_ms)
284 .unwrap_or(i64::MAX)
285 .saturating_mul(1000)
286}
287
288pub(crate) trait Recall {
290 fn neighbours(&self, keys: &[String]) -> Result<BTreeMap<String, u32>, Error>;
293
294 fn vectors(
297 &self,
298 e: &dyn Embedder,
299 query: &str,
300 items: &[(String, Memory)],
301 ) -> Result<(Vec<f32>, Vectors), Error>;
302
303 fn place(&self) -> PathBuf;
305}
306
307pub(crate) fn recall(
312 store: &dyn Recall,
313 embedder: Option<&dyn Embedder>,
314 all: Vec<(String, Memory)>,
315 query: &str,
316 limit: Option<usize>,
317) -> Result<Found, Error> {
318 let limit = limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT);
319 let mut terms = search::words(query);
320 terms.sort();
321 terms.dedup();
322 if terms.is_empty() {
323 let items = all.into_iter().take(limit).map(|(_, m)| m).collect();
324 return Ok(Found {
325 items,
326 problems: Vec::new(),
327 });
328 }
329 let mut problems = Vec::new();
330 let mut picked: BTreeMap<String, Memory> = BTreeMap::new();
332 for (k, m) in &all {
333 let score = search::score(&terms, m);
334 if score > 0 {
335 let mut m = m.clone();
336 m.score = Some(score);
337 picked.insert(k.clone(), m);
338 }
339 }
340 let mut seeds: Vec<(&String, &Memory)> = picked.iter().collect();
342 seeds.sort_by_key(|a| std::cmp::Reverse(a.1.score));
343 let seeds: Vec<String> = seeds
344 .into_iter()
345 .take(limit)
346 .map(|(k, _)| k.clone())
347 .collect();
348 let near = if seeds.is_empty() {
349 BTreeMap::new()
350 } else {
351 store.neighbours(&seeds)?
352 };
353 for (k, m) in &all {
354 if picked.contains_key(k) {
355 continue;
356 }
357 if let Some(n) = near.get(k) {
358 let mut m = m.clone();
359 m.score = Some(RELATED_BASE + 10 * (*n).min(49));
360 picked.insert(k.clone(), m);
361 }
362 }
363 if let Some(e) = embedder {
365 let rest: Vec<(String, Memory)> = all
366 .iter()
367 .filter(|(k, _)| !picked.contains_key(k))
368 .cloned()
369 .collect();
370 if !rest.is_empty() {
371 match store.vectors(e, query, &rest) {
374 Ok((q, have)) => {
375 for (k, m) in rest {
376 let sim = have.get(&k).map_or(0.0, |v| cosine(&q, v));
377 if sim >= NEAR {
378 let mut m = m;
379 m.score = Some(((sim * 400.0) as u32).clamp(1, RELATED_BASE - 1));
380 picked.insert(k, m);
381 }
382 }
383 }
384 Err(err) => problems.push(Problem {
385 path: store.place(),
386 message: format!("recalled without vectors: embedder {}: {err}", e.model()),
387 }),
388 }
389 }
390 }
391 let mut items: Vec<Memory> = picked.into_values().collect();
392 items.sort_by(|a, b| {
393 b.score
394 .cmp(&a.score)
395 .then(b.updated_unix_ms.cmp(&a.updated_unix_ms))
396 .then(a.id.cmp(&b.id))
397 });
398 items.truncate(limit);
399 Ok(Found { items, problems })
400}