1use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8use std::sync::Mutex;
9
10use super::adapter::*;
11
12pub(crate) const META_CACHE_VERSION: u32 = 1;
16
17pub(crate) const META_CACHE_WRITE_INTERVAL_MS: i64 = 10 * 60 * 1000;
19
20#[derive(serde::Deserialize)]
21struct MetaCacheFile {
22 version: u32,
23 entries: HashMap<String, (i64, Option<SessionMeta>)>,
24}
25
26#[derive(serde::Serialize)]
27struct MetaCacheFileRef<'a> {
28 version: u32,
29 entries: &'a HashMap<String, (i64, Option<SessionMeta>)>,
30}
31
32const SNIPPET_MAX_CHARS: usize = 400;
42const SNIPPET_LEAD_CHARS: usize = 120;
44
45#[derive(Debug, Clone, Default)]
47pub struct HistorySearchOptions {
48 pub query: String,
51 pub role: Option<String>,
53 pub tool: Option<String>,
60 pub limit: usize,
62 pub since_ms: Option<i64>,
64 pub until_ms: Option<i64>,
66 pub max_sessions: Option<usize>,
69 pub include_inferred: bool,
72 pub deadline: Option<std::time::Instant>,
77}
78
79#[derive(Debug, Clone, serde::Serialize)]
81pub struct HistorySearchHit {
82 pub session_id: String,
83 pub file_path: String,
84 pub timestamp: i64,
85 pub role: String,
86 pub snippet: String,
87 #[serde(skip_serializing_if = "Option::is_none")]
89 pub tool_name: Option<String>,
90 pub source: &'static str,
93 pub attribution: &'static str,
97}
98
99#[derive(Debug, Clone)]
101pub(crate) enum Source {
102 Transcript,
103 Record(super::record::RecordSession),
104}
105
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub(crate) enum Attribution {
109 AgentRecord,
111 Inferred,
113}
114
115#[derive(Debug, Clone)]
117pub(crate) struct SearchCandidate {
118 pub meta: SessionMeta,
119 pub source: Source,
120 pub attribution: Attribution,
121}
122
123impl SearchCandidate {
124 fn source_label(&self) -> &'static str {
125 match self.source {
126 Source::Transcript => "provider_transcript",
127 Source::Record(_) => "agentmux_record",
128 }
129 }
130 fn attribution_label(&self) -> &'static str {
131 match self.attribution {
132 Attribution::AgentRecord => "agent_record",
133 Attribution::Inferred => "inferred",
134 }
135 }
136}
137
138#[derive(Debug, Clone, serde::Serialize)]
140pub struct HistorySearchOutcome {
141 pub hits: Vec<HistorySearchHit>,
142 pub sessions_scanned: u32,
144 pub total_sessions: u32,
146 pub truncated: bool,
150 pub complete: bool,
156 pub incomplete_reasons: Vec<&'static str>,
159 pub sessions_skipped: u32,
161 pub sessions_unreadable: Vec<UnreadableSession>,
163 pub sessions_partly_read: Vec<UnreadableSession>,
165 pub discovery_errors: Vec<String>,
168 pub ledger_sessions: u32,
170 pub record_only_sessions: u32,
173 pub inferred_sessions_excluded: u32,
177 #[serde(skip_serializing_if = "Option::is_none")]
179 pub hint: Option<&'static str>,
180}
181
182const TIME_LIMIT_HINT: &str =
184 "The search stopped at its time limit: the hits are from the newest sessions read so far, not from all of them. \
185 Narrow it with since and until (a time range), role, tool or a smaller max_sessions, and search again.";
186
187const DISCOVERY_ERRORS_LISTED: usize = 20;
189
190impl HistorySearchOutcome {
191 pub fn add_discovery_errors(&mut self, problems: Vec<String>) {
193 if problems.is_empty() {
194 return;
195 }
196 let total = problems.len();
197 self.discovery_errors = problems.into_iter().take(DISCOVERY_ERRORS_LISTED).collect();
198 if total > DISCOVERY_ERRORS_LISTED {
199 self.discovery_errors.push(format!("… and {} more", total - DISCOVERY_ERRORS_LISTED));
200 }
201 self.incomplete_reasons.push("discovery_errors");
202 self.complete = false;
203 }
204}
205
206#[derive(Debug, Clone, serde::Serialize)]
208pub struct UnreadableSession {
209 pub session_id: String,
210 pub reason: String,
211}
212
213fn tool_name_matches(recorded: &str, wanted: &str) -> bool {
218 let recorded = recorded.to_ascii_lowercase();
219 let wanted = wanted.to_ascii_lowercase();
220 recorded == wanted
221 || (recorded.starts_with("mcp__") && recorded.ends_with(&format!("__{wanted}")))
222}
223
224fn within_window(timestamp_ms: i64, opts: &HistorySearchOptions) -> bool {
228 timestamp_ms == 0
229 || (opts.since_ms.is_none_or(|since| timestamp_ms >= since)
230 && opts.until_ms.is_none_or(|until| timestamp_ms <= until))
231}
232
233fn find_case_insensitive(haystack: &str, needle_lower: &str) -> Option<usize> {
247 if needle_lower.is_empty() {
248 return None;
249 }
250 let mut lowered = String::with_capacity(haystack.len());
251 let mut origin: Vec<usize> = Vec::with_capacity(haystack.len() + 1);
253 for (orig_idx, ch) in haystack.char_indices() {
254 for lc in ch.to_lowercase() {
255 let mut buf = [0u8; 4];
256 let encoded = lc.encode_utf8(&mut buf);
257 for _ in 0..encoded.len() {
258 origin.push(orig_idx);
259 }
260 lowered.push_str(encoded);
261 }
262 }
263 origin.push(haystack.len());
264 let at = lowered.find(needle_lower)?;
265 origin.get(at).copied()
268}
269
270fn snippet_around(haystack: &str, match_at: usize) -> String {
273 let start = haystack[..match_at]
274 .char_indices()
275 .rev()
276 .take(SNIPPET_LEAD_CHARS)
277 .last()
278 .map(|(i, _)| i)
279 .unwrap_or(match_at);
280 let tail: String = haystack[start..].chars().take(SNIPPET_MAX_CHARS).collect();
281 let mut out = String::new();
282 if start > 0 {
283 out.push('…');
284 }
285 out.push_str(&tail);
286 if start + tail.len() < haystack.len() {
287 out.push('…');
288 }
289 out
290}
291
292fn match_message(
294 candidate: &SearchCandidate,
295 msg: &HistoryMessage,
296 needle: &str,
297 opts: &HistorySearchOptions,
298) -> Vec<HistorySearchHit> {
299 let meta = &candidate.meta;
300 let mut hits = Vec::new();
301
302 for tu in &msg.tool_uses {
314 if let Some(want) = opts.tool.as_deref() {
315 if !tool_name_matches(&tu.name, want) {
316 continue;
317 }
318 let at = if needle.is_empty() {
321 Some(0)
322 } else {
323 find_case_insensitive(&tu.argument_summary, needle)
324 };
325 if let Some(at) = at {
326 hits.push(HistorySearchHit {
327 session_id: meta.session_id.clone(),
328 file_path: meta.file_path.clone(),
329 timestamp: msg.timestamp,
330 role: msg.role.clone(),
331 snippet: snippet_around(&tu.argument_summary, at),
332 tool_name: Some(tu.name.clone()),
333 source: candidate.source_label(),
334 attribution: candidate.attribution_label(),
335 });
336 }
337 continue;
338 }
339 if needle.is_empty() {
340 continue;
341 }
342 let at = if find_case_insensitive(&tu.name, needle).is_some() {
346 Some(0)
347 } else {
348 find_case_insensitive(&tu.argument_summary, needle)
349 };
350 if let Some(at) = at {
351 hits.push(HistorySearchHit {
352 session_id: meta.session_id.clone(),
353 file_path: meta.file_path.clone(),
354 timestamp: msg.timestamp,
355 role: msg.role.clone(),
356 snippet: snippet_around(&tu.argument_summary, at),
357 tool_name: Some(tu.name.clone()),
358 source: candidate.source_label(),
359 attribution: candidate.attribution_label(),
360 });
361 }
362 }
363
364 if opts.tool.is_none() && !needle.is_empty() {
367 if let Some(at) = find_case_insensitive(&msg.content, needle) {
368 hits.push(HistorySearchHit {
369 session_id: meta.session_id.clone(),
370 file_path: meta.file_path.clone(),
371 timestamp: msg.timestamp,
372 role: msg.role.clone(),
373 snippet: snippet_around(&msg.content, at),
374 tool_name: None,
375 source: candidate.source_label(),
376 attribution: candidate.attribution_label(),
377 });
378 }
379 }
380
381 hits
382}
383
384pub(crate) fn search_candidates(
389 candidates: &[SearchCandidate],
390 opts: &HistorySearchOptions,
391 load: &dyn Fn(&SearchCandidate) -> Result<Option<HistorySession>, HistoryError>,
392) -> HistorySearchOutcome {
393 let needle = opts.query.to_lowercase();
394 let mut hits: Vec<HistorySearchHit> = Vec::new();
395 let mut sessions_scanned = 0u32;
396 let mut sessions_unreadable: Vec<UnreadableSession> = Vec::new();
397 let mut sessions_partly_read: Vec<UnreadableSession> = Vec::new();
398 let mut truncated = false;
399
400 let opened = opts.max_sessions.map_or(candidates.len(), |max| max.min(candidates.len()));
401 let mut sessions_skipped = (candidates.len() - opened) as u32;
402 let mut timed_out = false;
403
404 for (position, candidate) in candidates[..opened].iter().enumerate() {
405 let meta = &candidate.meta;
406 if hits.len() >= opts.limit {
407 truncated = true;
409 break;
410 }
411 if opts.deadline.is_some_and(|deadline| std::time::Instant::now() >= deadline) {
412 timed_out = true;
414 sessions_skipped += (opened - position) as u32;
415 break;
416 }
417 let session = match load(candidate) {
421 Ok(Some(session)) => session,
422 Ok(None) => {
423 sessions_unreadable.push(UnreadableSession {
424 session_id: meta.session_id.clone(),
425 reason: "no longer readable (moved, deleted or emptied)".into(),
426 });
427 continue;
428 }
429 Err(e) => {
430 sessions_unreadable.push(UnreadableSession {
431 session_id: meta.session_id.clone(),
432 reason: e.to_string(),
433 });
434 continue;
435 }
436 };
437 sessions_scanned += 1;
438 if session.skipped_records > 0 {
439 sessions_partly_read.push(UnreadableSession {
440 session_id: meta.session_id.clone(),
441 reason: format!(
442 "{} record(s) could not be read and were not searched",
443 session.skipped_records
444 ),
445 });
446 }
447 for msg in &session.messages {
448 if let Some(role) = opts.role.as_deref() {
449 if msg.role != role {
450 continue;
451 }
452 }
453 if !within_window(msg.timestamp, opts) {
454 continue;
455 }
456 if hits.len() >= opts.limit {
457 truncated = true;
458 break;
459 }
460 for hit in match_message(candidate, msg, &needle, opts) {
461 if hits.len() >= opts.limit {
462 truncated = true;
463 break;
464 }
465 hits.push(hit);
466 }
467 }
468 }
469
470 let mut incomplete_reasons = Vec::new();
471 if truncated {
472 incomplete_reasons.push("hit_limit");
473 }
474 if candidates.len() > opened {
475 incomplete_reasons.push("max_sessions");
476 }
477 if timed_out {
478 incomplete_reasons.push("time_limit");
479 }
480 if !sessions_unreadable.is_empty() {
481 incomplete_reasons.push("unreadable_sessions");
482 }
483 if !sessions_partly_read.is_empty() {
484 incomplete_reasons.push("unreadable_records");
485 }
486 HistorySearchOutcome {
487 hits,
488 sessions_scanned,
489 total_sessions: candidates.len() as u32,
490 truncated,
491 complete: incomplete_reasons.is_empty(),
492 incomplete_reasons,
493 sessions_skipped,
494 sessions_unreadable,
495 sessions_partly_read,
496 discovery_errors: Vec::new(),
497 ledger_sessions: 0,
498 record_only_sessions: 0,
499 inferred_sessions_excluded: 0,
500 hint: timed_out.then_some(TIME_LIMIT_HINT),
501 }
502}
503
504fn default_isolated_roots() -> Vec<PathBuf> {
509 let shared = std::env::var_os("AGENTMUX_SHARED_DIR")
510 .map(PathBuf::from)
511 .or_else(|| crate::srv_info::agentmux_root().map(|root| root.join("shared")));
512 match shared {
513 Some(s) => vec![s.join("providers"), s.join("identities")],
514 None => Vec::new(),
515 }
516}
517
518pub(crate) fn normalize_working_dir(dir: &str) -> String {
527 let unified = dir.replace('\\', "/");
528 let trimmed = unified.trim_end_matches('/');
529 if cfg!(windows) {
530 trimmed.to_lowercase()
531 } else {
532 trimmed.to_string()
533 }
534}
535
536#[derive(Debug, PartialEq, Eq)]
538pub enum FirstBuild {
539 Built { discovered: u32 },
541 AlreadyBuilt,
543 Busy,
545}
546
547pub struct SessionIndex {
549 sessions: Mutex<HashMap<String, SessionMeta>>,
551 by_working_dir: Mutex<HashMap<String, Vec<String>>>,
576 by_identity: Mutex<HashMap<String, Vec<String>>>,
584 meta_cache: Mutex<HashMap<String, (i64, Option<SessionMeta>)>>,
589 cache_file: Option<PathBuf>,
595 cache_loaded: std::sync::atomic::AtomicBool,
597 cache_written_at_ms: std::sync::atomic::AtomicI64,
599 pub(super) refresh_lock: Mutex<()>,
602 refreshed_at_ms: std::sync::atomic::AtomicI64,
604 refreshes_started: std::sync::atomic::AtomicU64,
607 last_finished_refresh: std::sync::atomic::AtomicU64,
611 discovery_problems: Mutex<Vec<String>>,
614 adapters: Vec<Box<dyn HistoryAdapter>>,
616 isolated_roots: Vec<PathBuf>,
618}
619
620impl SessionIndex {
621 pub fn new(adapters: Vec<Box<dyn HistoryAdapter>>) -> Self {
622 Self::with_isolated_roots(adapters, default_isolated_roots())
623 }
624
625 pub fn with_isolated_roots(
627 adapters: Vec<Box<dyn HistoryAdapter>>,
628 isolated_roots: Vec<PathBuf>,
629 ) -> Self {
630 SessionIndex {
631 sessions: Mutex::new(HashMap::new()),
632 by_working_dir: Mutex::new(HashMap::new()),
633 by_identity: Mutex::new(HashMap::new()),
634 meta_cache: Mutex::new(HashMap::new()),
635 cache_file: None,
636 cache_loaded: std::sync::atomic::AtomicBool::new(false),
637 cache_written_at_ms: std::sync::atomic::AtomicI64::new(0),
638 refresh_lock: Mutex::new(()),
639 refreshed_at_ms: std::sync::atomic::AtomicI64::new(0),
640 refreshes_started: std::sync::atomic::AtomicU64::new(0),
641 last_finished_refresh: std::sync::atomic::AtomicU64::new(0),
642 discovery_problems: Mutex::new(Vec::new()),
643 adapters,
644 isolated_roots,
645 }
646 }
647
648 pub fn with_cache_file(mut self, path: PathBuf) -> Self {
653 self.cache_file = Some(path);
654 self
655 }
656
657 pub fn refreshed_at_ms(&self) -> i64 {
659 self.refreshed_at_ms.load(std::sync::atomic::Ordering::Acquire)
660 }
661
662 pub fn try_refresh(&self) -> Option<(u32, u32, u32)> {
665 let guard = match self.refresh_lock.try_lock() {
666 Ok(g) => g,
667 Err(std::sync::TryLockError::Poisoned(p)) => p.into_inner(),
668 Err(std::sync::TryLockError::WouldBlock) => return None,
669 };
670 Some(self.refresh_holding(guard))
671 }
672
673 pub fn try_first_build(&self) -> FirstBuild {
678 let guard = match self.refresh_lock.try_lock() {
679 Ok(g) => g,
680 Err(std::sync::TryLockError::Poisoned(p)) => p.into_inner(),
681 Err(std::sync::TryLockError::WouldBlock) => return FirstBuild::Busy,
682 };
683 if self.refreshed_at_ms() > 0 {
684 return FirstBuild::AlreadyBuilt;
685 }
686 let (discovered, _, _) = self.refresh_holding(guard);
687 FirstBuild::Built { discovered }
688 }
689
690 fn load_cache_file_once(&self) {
694 use std::sync::atomic::Ordering;
695 let Some(path) = &self.cache_file else { return };
696 if self.cache_loaded.swap(true, Ordering::AcqRel) {
697 return;
698 }
699 let Ok(bytes) = std::fs::read(path) else { return };
700 match serde_json::from_slice::<MetaCacheFile>(&bytes) {
701 Ok(file) if file.version == META_CACHE_VERSION => {
702 let mut cache = self.meta_cache.lock().unwrap();
703 if cache.is_empty() {
704 tracing::info!(entries = file.entries.len(), "history: loaded the saved metadata cache");
705 *cache = file.entries;
706 }
707 }
708 Ok(file) => tracing::info!(version = file.version, "history: saved metadata cache is another version; rebuilding"),
709 Err(e) => tracing::warn!(error = %e, "history: saved metadata cache unreadable; rebuilding"),
710 }
711 }
712
713 fn write_cache_file(&self, cache: &HashMap<String, (i64, Option<SessionMeta>)>, changed: bool) {
719 use std::sync::atomic::Ordering;
720 let Some(path) = &self.cache_file else { return };
721 let now = chrono::Utc::now().timestamp_millis();
722 let last = self.cache_written_at_ms.load(Ordering::Acquire);
723 if !changed && last > 0 {
724 return;
725 }
726 if last > 0 && now - last < META_CACHE_WRITE_INTERVAL_MS {
727 return;
728 }
729 let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
730 let write = || -> std::io::Result<()> {
731 if let Some(dir) = path.parent() {
732 std::fs::create_dir_all(dir)?;
733 }
734 let body = serde_json::to_vec(&MetaCacheFileRef { version: META_CACHE_VERSION, entries: cache })
735 .map_err(std::io::Error::other)?;
736 std::fs::write(&tmp, body)?;
737 std::fs::rename(&tmp, path)
738 };
739 self.cache_written_at_ms.store(now.max(1), Ordering::Release);
744 match write() {
745 Ok(()) => tracing::debug!(entries = cache.len(), "history: saved the metadata cache"),
746 Err(e) => {
747 let _ = std::fs::remove_file(&tmp);
750 tracing::warn!(error = %e, path = %path.display(), "history: couldn't save the metadata cache");
751 }
752 }
753 }
754
755 fn is_isolated(&self, path: &Path) -> bool {
758 self.isolated_roots.iter().any(|r| path.starts_with(r))
759 }
760
761 pub fn refresh(&self) -> (u32, u32, u32) {
764 let guard = self.refresh_lock.lock().unwrap_or_else(|p| p.into_inner());
765 self.refresh_holding(guard)
766 }
767
768 pub fn refresh_covering_now(&self) {
776 use std::sync::atomic::Ordering;
777 let started_before_this_call = self.refreshes_started.load(Ordering::Acquire);
778 let guard = self.refresh_lock.lock().unwrap_or_else(|p| p.into_inner());
779 if self.last_finished_refresh.load(Ordering::Acquire) > started_before_this_call {
780 return;
781 }
782 self.refresh_holding(guard);
783 }
784
785 pub fn discovery_problems(&self) -> Vec<String> {
788 self.discovery_problems.lock().unwrap().clone()
789 }
790
791 fn refresh_holding(&self, _refreshing: std::sync::MutexGuard<'_, ()>) -> (u32, u32, u32) {
792 use std::sync::atomic::Ordering;
793 let this_refresh = self.refreshes_started.fetch_add(1, Ordering::AcqRel) + 1;
794 let mut problems: Vec<String> = Vec::new();
795 let mut discovered: u32 = 0;
796 let mut updated: u32 = 0;
797 let mut new_count: u32 = 0;
798 self.load_cache_file_once();
799 let old_cache = std::mem::take(&mut *self.meta_cache.lock().unwrap());
800 let mut parsed: u32 = 0;
801 let mut reused: usize = 0;
802 let mut new_cache: HashMap<String, (i64, Option<SessionMeta>)> = HashMap::with_capacity(old_cache.len());
803
804 let mut new_sessions: HashMap<String, SessionMeta> = HashMap::new();
805 let mut new_by_identity: HashMap<String, Vec<String>> = HashMap::new();
806 let mut new_by_working_dir: HashMap<String, Vec<String>> = HashMap::new();
807
808 for adapter in &self.adapters {
809 let files = match adapter.discover() {
810 Ok(found) => {
811 problems.extend(found.problems);
812 found.files
813 }
814 Err(e) => {
815 tracing::warn!(
816 "history: failed to discover {} files: {}",
817 adapter.provider(),
818 e
819 );
820 problems.push(format!("{} discovery failed: {e}", adapter.provider()));
821 continue;
822 }
823 };
824
825 discovered += files.len() as u32;
826
827 for file in &files {
828 let extracted = match old_cache.get(&file.file_path) {
829 Some((mtime, cached)) if *mtime == file.mtime_ms => {
830 reused += 1;
831 Ok(cached.clone())
832 }
833 _ => {
834 parsed += 1;
835 adapter.extract_meta(&file.file_path)
836 }
837 };
838 if let Ok(ref meta) = extracted {
839 new_cache.insert(file.file_path.clone(), (file.mtime_ms, meta.clone()));
840 }
841 match extracted {
842 Ok(Some(meta)) => {
843 if !meta.identity_id.is_empty() {
844 new_by_identity
845 .entry(meta.identity_id.clone())
846 .or_default()
847 .push(meta.session_id.clone());
848 }
849 if !meta.working_directory.is_empty() {
850 new_by_working_dir
851 .entry(normalize_working_dir(&meta.working_directory))
852 .or_default()
853 .push(meta.session_id.clone());
854 }
855 new_sessions.insert(meta.session_id.clone(), meta);
856 }
857 Ok(None) => {} Err(e) => {
859 tracing::debug!(
860 "history: failed to extract meta from {}: {}",
861 file.file_path,
862 e
863 );
864 problems.push(format!("{}: {e}", file.file_path));
867 }
868 }
869 }
870 }
871
872 let mut sessions = self.sessions.lock().unwrap();
874 for (id, _meta) in &new_sessions {
875 if sessions.contains_key(id) {
876 updated += 1;
877 } else {
878 new_count += 1;
879 }
880 }
881
882 *sessions = new_sessions;
883 *self.by_identity.lock().unwrap() = new_by_identity;
884 *self.by_working_dir.lock().unwrap() = new_by_working_dir;
885 drop(sessions);
886 let changed = parsed > 0 || reused < old_cache.len();
888 self.write_cache_file(&new_cache, changed);
889 tracing::debug!(parsed, reused, "history: refresh reused cached metadata");
890 *self.meta_cache.lock().unwrap() = new_cache;
891 if !problems.is_empty() {
892 tracing::warn!(count = problems.len(), first = %problems[0], "history: discovery couldn't read everything");
893 }
894 *self.discovery_problems.lock().unwrap() = problems;
895 self.refreshed_at_ms.store(
896 chrono::Utc::now().timestamp_millis().max(1),
897 Ordering::Release,
898 );
899 self.last_finished_refresh.store(this_refresh, Ordering::Release);
900
901 (discovered, updated, new_count)
902 }
903
904 pub fn list_for_working_directory(&self, working_directory: &str) -> Vec<SessionMeta> {
911 if working_directory.is_empty() {
912 return Vec::new();
913 }
914 let key = normalize_working_dir(working_directory);
915 let sessions = self.sessions.lock().unwrap();
917 let by_working_dir = self.by_working_dir.lock().unwrap();
918 let Some(session_ids) = by_working_dir.get(&key) else {
919 return Vec::new();
920 };
921 session_ids.iter().filter_map(|id| sessions.get(id)).cloned().collect()
922 }
923
924 pub fn list_for_identity(
933 &self,
934 identity_id: &str,
935 offset: usize,
936 limit: usize,
937 sort_by: &str,
938 sort_dir: &str,
939 ) -> (Vec<SessionMeta>, u32, bool) {
940 let sessions = self.sessions.lock().unwrap();
947 let by_identity = self.by_identity.lock().unwrap();
948 let Some(session_ids) = by_identity.get(identity_id) else {
949 return (Vec::new(), 0, false);
950 };
951 let mut filtered: Vec<&SessionMeta> =
952 session_ids.iter().filter_map(|id| sessions.get(id)).collect();
953 Self::sort_sessions(&mut filtered, sort_by, sort_dir);
954
955 let total = filtered.len() as u32;
956 let has_more = offset + limit < filtered.len();
957 let page: Vec<SessionMeta> = filtered.into_iter().skip(offset).take(limit).cloned().collect();
958 (page, total, has_more)
959 }
960
961 pub(crate) fn sort_sessions(filtered: &mut [&SessionMeta], sort_by: &str, sort_dir: &str) {
965 let desc = sort_dir != "asc";
966 match sort_by {
967 "created_at" | "created" => {
968 filtered.sort_by(|a, b| {
969 if desc {
970 b.created_at.cmp(&a.created_at)
971 } else {
972 a.created_at.cmp(&b.created_at)
973 }
974 });
975 }
976 "messages" => {
977 filtered.sort_by(|a, b| {
978 if desc {
979 b.message_count.cmp(&a.message_count)
980 } else {
981 a.message_count.cmp(&b.message_count)
982 }
983 });
984 }
985 "tokens" => {
986 filtered.sort_by(|a, b| {
987 if desc {
988 b.total_tokens.cmp(&a.total_tokens)
989 } else {
990 a.total_tokens.cmp(&b.total_tokens)
991 }
992 });
993 }
994 _ => {
995 filtered.sort_by(|a, b| {
997 if desc {
998 b.modified_at.cmp(&a.modified_at)
999 } else {
1000 a.modified_at.cmp(&b.modified_at)
1001 }
1002 });
1003 }
1004 }
1005 }
1006
1007 pub fn list(
1009 &self,
1010 provider: Option<&str>,
1011 project: Option<&str>,
1012 offset: usize,
1013 limit: usize,
1014 sort_by: &str,
1015 sort_dir: &str,
1016 ) -> (Vec<SessionMeta>, u32, bool) {
1017 let sessions = self.sessions.lock().unwrap();
1018
1019 let mut filtered: Vec<&SessionMeta> = sessions
1020 .values()
1021 .filter(|s| {
1022 if let Some(p) = provider {
1023 if s.provider != p {
1024 return false;
1025 }
1026 }
1027 if let Some(proj) = project {
1028 if !s.working_directory.contains(proj) {
1029 return false;
1030 }
1031 }
1032 true
1033 })
1034 .collect();
1035
1036 Self::sort_sessions(&mut filtered, sort_by, sort_dir);
1037
1038 let total = filtered.len() as u32;
1039 let has_more = offset + limit < filtered.len();
1040 let page: Vec<SessionMeta> = filtered
1041 .into_iter()
1042 .skip(offset)
1043 .take(limit)
1044 .cloned()
1045 .collect();
1046
1047 (page, total, has_more)
1048 }
1049
1050 pub fn get_meta(&self, session_id: &str) -> Option<SessionMeta> {
1052 let sessions = self.sessions.lock().unwrap();
1053 sessions.get(session_id).cloned()
1054 }
1055
1056 pub fn get_full(&self, session_id: &str) -> Result<Option<HistorySession>, HistoryError> {
1058 let meta = match self.get_meta(session_id) {
1059 Some(m) => m,
1060 None => return Ok(None),
1061 };
1062
1063 for adapter in &self.adapters {
1065 if adapter.provider() == meta.provider {
1066 return adapter.parse_file(&meta.file_path);
1067 }
1068 }
1069
1070 Err(HistoryError::Other(format!(
1071 "no adapter for provider: {}",
1072 meta.provider
1073 )))
1074 }
1075
1076 #[cfg(test)]
1095 pub fn search_sessions(
1096 &self,
1097 candidates: &[SessionMeta],
1098 opts: &HistorySearchOptions,
1099 ) -> HistorySearchOutcome {
1100 let candidates: Vec<SearchCandidate> = candidates
1101 .iter()
1102 .map(|meta| SearchCandidate {
1103 meta: meta.clone(),
1104 source: Source::Transcript,
1105 attribution: Attribution::AgentRecord,
1106 })
1107 .collect();
1108 search_candidates(&candidates, opts, &|c| self.get_full(&c.meta.session_id))
1109 }
1110
1111 #[cfg(test)]
1113 pub fn is_empty(&self) -> bool {
1114 self.sessions.lock().unwrap().is_empty()
1115 }
1116
1117 pub fn delete(&self, session_id: &str) -> Result<bool, HistoryError> {
1122 let meta = match self.get_meta(session_id) {
1123 Some(m) => m,
1124 None => return Ok(false),
1125 };
1126 let path = Path::new(&meta.file_path);
1127 if !self.is_isolated(path) {
1130 return Err(HistoryError::Other(format!(
1131 "refusing to delete '{}' — it lives in your personal {} home, not AgentMux's",
1132 meta.file_path, meta.provider
1133 )));
1134 }
1135 match std::fs::remove_file(path) {
1139 Ok(()) => {}
1140 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1141 Err(e) => return Err(e.into()),
1142 }
1143 if let Some(parent) = path.parent() {
1146 let sidecar = parent.join(session_id);
1147 if sidecar.is_dir() {
1148 let _ = std::fs::remove_dir_all(&sidecar);
1149 }
1150 }
1151 self.sessions.lock().unwrap().remove(session_id);
1152 Ok(true)
1153 }
1154
1155 pub fn clear(&self, provider: Option<&str>, project: Option<&str>) -> u32 {
1158 let ids: Vec<String> = {
1161 let sessions = self.sessions.lock().unwrap();
1162 sessions
1163 .values()
1164 .filter(|s| provider.map_or(true, |p| s.provider == p))
1165 .filter(|s| project.map_or(true, |proj| s.working_directory.contains(proj)))
1166 .filter(|s| self.is_isolated(Path::new(&s.file_path)))
1168 .map(|s| s.session_id.clone())
1169 .collect()
1170 };
1171 let mut deleted = 0;
1172 for id in ids {
1173 if matches!(self.delete(&id), Ok(true)) {
1174 deleted += 1;
1175 }
1176 }
1177 deleted
1178 }
1179}
1180
1181#[cfg(test)]
1182mod tests {
1183 use super::*;
1184 use std::fs;
1185 use std::path::PathBuf;
1186
1187 struct MockAdapter {
1190 files: Vec<DiscoveredFile>,
1191 provider: String,
1192 working_directory: String,
1193 identity_id: String,
1194 }
1195 impl HistoryAdapter for MockAdapter {
1196 fn provider(&self) -> &str {
1197 &self.provider
1198 }
1199 fn discover_files(&self) -> Result<Vec<DiscoveredFile>, HistoryError> {
1200 Ok(self
1201 .files
1202 .iter()
1203 .map(|f| DiscoveredFile { file_path: f.file_path.clone(), mtime_ms: f.mtime_ms })
1204 .collect())
1205 }
1206 fn extract_meta(&self, file_path: &str) -> Result<Option<SessionMeta>, HistoryError> {
1207 let id = PathBuf::from(file_path)
1208 .file_stem()
1209 .map(|s| s.to_string_lossy().into_owned())
1210 .unwrap_or_default();
1211 Ok(Some(SessionMeta {
1212 session_id: id,
1213 file_path: file_path.to_string(),
1214 provider: self.provider.clone(),
1215 model: String::new(),
1216 slug: String::new(),
1217 working_directory: self.working_directory.clone(),
1218 created_at: 0,
1219 modified_at: 0,
1220 message_count: 0,
1221 first_user_message: String::new(),
1222 file_size_bytes: 0,
1223 git_branch: String::new(),
1224 total_tokens: 0,
1225 subagent_count: 0,
1226 identity_id: self.identity_id.clone(),
1227 starts_undated: false,
1228 }))
1229 }
1230 fn parse_file(&self, _: &str) -> Result<Option<HistorySession>, HistoryError> {
1231 Ok(None)
1232 }
1233 }
1234
1235 fn write_session(dir: &std::path::Path, id: &str) -> String {
1236 let f = dir.join(format!("{id}.jsonl"));
1237 fs::write(&f, b"{}").unwrap();
1238 f.to_string_lossy().into_owned()
1239 }
1240
1241 #[test]
1242 fn delete_removes_file_and_index_entry() {
1243 let dir = std::env::temp_dir().join(format!("amux-hist-del-{}", std::process::id()));
1244 fs::create_dir_all(&dir).unwrap();
1245 let fp = write_session(&dir, "sess-abc");
1246 let sidecar = dir.join("sess-abc");
1248 fs::create_dir_all(sidecar.join("subagents")).unwrap();
1249
1250 let idx = SessionIndex::with_isolated_roots(
1251 vec![Box::new(MockAdapter {
1252 files: vec![DiscoveredFile { file_path: fp.clone(), mtime_ms: 0 }],
1253 provider: "mock".into(),
1254 working_directory: "/proj".into(),
1255 identity_id: String::new(),
1256 })],
1257 vec![dir.clone()],
1258 );
1259 idx.refresh();
1260 assert!(idx.get_meta("sess-abc").is_some());
1261
1262 assert!(matches!(idx.delete("sess-abc"), Ok(true)));
1263 assert!(!std::path::Path::new(&fp).exists(), "transcript removed");
1264 assert!(!sidecar.exists(), "subagents sidecar removed");
1265 assert!(idx.get_meta("sess-abc").is_none(), "dropped from index");
1266 assert!(matches!(idx.delete("sess-abc"), Ok(false)), "second delete is a no-op");
1267
1268 let _ = fs::remove_dir_all(&dir);
1269 }
1270
1271 #[test]
1272 fn clear_respects_provider_filter() {
1273 let dir = std::env::temp_dir().join(format!("amux-hist-clr-{}", std::process::id()));
1274 fs::create_dir_all(&dir).unwrap();
1275 let a = write_session(&dir, "a");
1276 let b = write_session(&dir, "b");
1277
1278 let idx = SessionIndex::with_isolated_roots(
1279 vec![Box::new(MockAdapter {
1280 files: vec![
1281 DiscoveredFile { file_path: a.clone(), mtime_ms: 0 },
1282 DiscoveredFile { file_path: b.clone(), mtime_ms: 0 },
1283 ],
1284 provider: "mock".into(),
1285 working_directory: "/proj".into(),
1286 identity_id: String::new(),
1287 })],
1288 vec![dir.clone()],
1289 );
1290 idx.refresh();
1291
1292 assert_eq!(idx.clear(Some("other"), None), 0);
1294 assert!(std::path::Path::new(&a).exists());
1295 assert_eq!(idx.clear(Some("mock"), None), 2);
1296 assert!(!std::path::Path::new(&a).exists() && !std::path::Path::new(&b).exists());
1297 assert!(idx.is_empty());
1298
1299 let _ = fs::remove_dir_all(&dir);
1300 }
1301
1302 #[test]
1303 fn refuses_to_delete_outside_isolated_roots() {
1304 let dir = std::env::temp_dir().join(format!("amux-hist-guard-{}", std::process::id()));
1307 fs::create_dir_all(&dir).unwrap();
1308 let fp = write_session(&dir, "personal-sess");
1309
1310 let idx = SessionIndex::with_isolated_roots(
1311 vec![Box::new(MockAdapter {
1312 files: vec![DiscoveredFile { file_path: fp.clone(), mtime_ms: 0 }],
1313 provider: "claude".into(),
1314 working_directory: "/home/me/.claude".into(),
1315 identity_id: String::new(),
1316 })],
1317 vec![std::env::temp_dir().join("amux-some-other-isolated-root")],
1319 );
1320 idx.refresh();
1321
1322 assert!(idx.delete("personal-sess").is_err(), "single delete must refuse");
1323 assert!(std::path::Path::new(&fp).exists(), "file must be intact");
1324 assert_eq!(idx.clear(None, None), 0, "clear-all must skip it");
1325 assert!(std::path::Path::new(&fp).exists(), "still intact after clear");
1326
1327 let _ = fs::remove_dir_all(&dir);
1328 }
1329
1330 #[test]
1336 fn list_for_identity_returns_only_that_identitys_sessions() {
1337 let dir = std::env::temp_dir().join(format!("amux-hist-idx-{}", std::process::id()));
1338 fs::create_dir_all(&dir).unwrap();
1339 let a1 = write_session(&dir, "a1");
1340 let a2 = write_session(&dir, "a2");
1341 let b1 = write_session(&dir, "b1");
1342 let unattributed = write_session(&dir, "unattributed");
1343
1344 let idx = SessionIndex::with_isolated_roots(
1345 vec![
1346 Box::new(MockAdapter {
1347 files: vec![
1348 DiscoveredFile { file_path: a1, mtime_ms: 1 },
1349 DiscoveredFile { file_path: a2, mtime_ms: 2 },
1350 ],
1351 provider: "mock".into(),
1352 working_directory: "/proj".into(),
1353 identity_id: "identity-a".into(),
1354 }),
1355 Box::new(MockAdapter {
1356 files: vec![DiscoveredFile { file_path: b1, mtime_ms: 1 }],
1357 provider: "mock".into(),
1358 working_directory: "/proj".into(),
1359 identity_id: "identity-b".into(),
1360 }),
1361 Box::new(MockAdapter {
1362 files: vec![DiscoveredFile { file_path: unattributed, mtime_ms: 1 }],
1363 provider: "mock".into(),
1364 working_directory: "/proj".into(),
1365 identity_id: String::new(),
1366 }),
1367 ],
1368 vec![dir.clone()],
1369 );
1370 idx.refresh();
1371
1372 let (sessions_a, total_a, _) = idx.list_for_identity("identity-a", 0, 10, "created_at", "desc");
1373 assert_eq!(total_a, 2);
1374 let ids_a: std::collections::HashSet<_> = sessions_a.iter().map(|s| s.session_id.clone()).collect();
1375 assert_eq!(ids_a, std::collections::HashSet::from(["a1".to_string(), "a2".to_string()]));
1376
1377 let (sessions_b, total_b, _) = idx.list_for_identity("identity-b", 0, 10, "created_at", "desc");
1378 assert_eq!(total_b, 1);
1379 assert_eq!(sessions_b[0].session_id, "b1");
1380
1381 let _ = fs::remove_dir_all(&dir);
1382 }
1383
1384 #[test]
1385 fn list_for_identity_returns_empty_for_an_unknown_identity() {
1386 let idx = SessionIndex::with_isolated_roots(vec![], vec![]);
1387 idx.refresh();
1388 let (sessions, total, has_more) = idx.list_for_identity("no-such-identity", 0, 10, "created_at", "desc");
1389 assert!(sessions.is_empty());
1390 assert_eq!(total, 0);
1391 assert!(!has_more);
1392 }
1393
1394 #[test]
1395 fn list_for_identity_paginates_and_respects_sort_direction() {
1396 let dir = std::env::temp_dir().join(format!("amux-hist-idx-page-{}", std::process::id()));
1397 fs::create_dir_all(&dir).unwrap();
1398 let files: Vec<DiscoveredFile> = (0..3)
1399 .map(|i| DiscoveredFile { file_path: write_session(&dir, &format!("s{i}")), mtime_ms: i })
1400 .collect();
1401
1402 let idx = SessionIndex::with_isolated_roots(
1403 vec![Box::new(MockAdapter {
1404 files,
1405 provider: "mock".into(),
1406 working_directory: "/proj".into(),
1407 identity_id: "identity-a".into(),
1408 })],
1409 vec![dir.clone()],
1410 );
1411 idx.refresh();
1412
1413 let (page1, total, has_more) = idx.list_for_identity("identity-a", 0, 2, "created_at", "desc");
1414 assert_eq!(total, 3);
1415 assert_eq!(page1.len(), 2);
1416 assert!(has_more);
1417 let (page2, _, has_more2) = idx.list_for_identity("identity-a", 2, 2, "created_at", "desc");
1418 assert_eq!(page2.len(), 1);
1419 assert!(!has_more2);
1420
1421 let _ = fs::remove_dir_all(&dir);
1422 }
1423
1424 #[test]
1438 fn concurrent_refresh_and_lookups_do_not_deadlock() {
1439 use std::sync::mpsc;
1440 use std::sync::Arc;
1441 use std::time::Duration;
1442
1443 let dir = std::env::temp_dir().join(format!("amux-hist-lockorder-{}", std::process::id()));
1444 std::fs::create_dir_all(&dir).unwrap();
1445 let f = write_session(&dir, "lock-order-session");
1446
1447 let index = Arc::new(SessionIndex::with_isolated_roots(
1448 vec![Box::new(MockAdapter {
1449 files: vec![DiscoveredFile { file_path: f, mtime_ms: 1 }],
1450 provider: "mock".into(),
1451 working_directory: "/proj".into(),
1452 identity_id: "acct-lock".into(),
1453 })],
1454 vec![dir.clone()],
1455 ));
1456
1457 const ITERATIONS: usize = 300;
1458 let (tx, rx) = mpsc::channel();
1459
1460 for worker in 0..3 {
1461 let idx = Arc::clone(&index);
1462 let tx = tx.clone();
1463 std::thread::spawn(move || {
1464 for _ in 0..ITERATIONS {
1465 match worker {
1466 0 => {
1467 idx.refresh();
1468 }
1469 1 => {
1470 idx.list_for_working_directory("/proj");
1471 }
1472 _ => {
1473 idx.list_for_identity("acct-lock", 0, 10, "created_at", "desc");
1474 }
1475 }
1476 }
1477 let _ = tx.send(worker);
1478 });
1479 }
1480 drop(tx);
1481
1482 for _ in 0..3 {
1483 rx.recv_timeout(Duration::from_secs(30)).expect(
1484 "deadlock: a worker never finished. `refresh()` holds `sessions` while \
1485 swapping the index maps, so every reader must take `sessions` FIRST — \
1486 see the lock-order invariant on `SessionIndex::by_working_dir`",
1487 );
1488 }
1489
1490 std::fs::remove_dir_all(&dir).ok();
1491 }
1492
1493 #[test]
1494 fn refresh_rebuilds_the_identity_index_from_scratch_each_time() {
1495 let dir = std::env::temp_dir().join(format!("amux-hist-idx-rebuild-{}", std::process::id()));
1499 fs::create_dir_all(&dir).unwrap();
1500 let fp = write_session(&dir, "moved");
1501
1502 let idx = SessionIndex::with_isolated_roots(
1503 vec![Box::new(MockAdapter {
1504 files: vec![DiscoveredFile { file_path: fp.clone(), mtime_ms: 1 }],
1505 provider: "mock".into(),
1506 working_directory: "/proj".into(),
1507 identity_id: "identity-old".into(),
1508 })],
1509 vec![dir.clone()],
1510 );
1511 idx.refresh();
1512 assert_eq!(idx.list_for_identity("identity-old", 0, 10, "created_at", "desc").1, 1);
1513
1514 let idx2 = SessionIndex::with_isolated_roots(
1515 vec![Box::new(MockAdapter {
1516 files: vec![DiscoveredFile { file_path: fp, mtime_ms: 1 }],
1517 provider: "mock".into(),
1518 working_directory: "/proj".into(),
1519 identity_id: "identity-new".into(),
1520 })],
1521 vec![dir.clone()],
1522 );
1523 idx2.refresh();
1524 assert_eq!(idx2.list_for_identity("identity-old", 0, 10, "created_at", "desc").1, 0, "stale identity must not linger");
1525 assert_eq!(idx2.list_for_identity("identity-new", 0, 10, "created_at", "desc").1, 1);
1526
1527 let _ = fs::remove_dir_all(&dir);
1528 }
1529
1530 struct SearchMockAdapter {
1536 sessions: HashMap<String, Vec<HistoryMessage>>,
1537 parsed: Mutex<Vec<String>>,
1538 }
1539
1540 impl HistoryAdapter for SearchMockAdapter {
1541 fn provider(&self) -> &str {
1542 "mock"
1543 }
1544 fn discover_files(&self) -> Result<Vec<DiscoveredFile>, HistoryError> {
1545 Ok(self
1546 .sessions
1547 .keys()
1548 .map(|id| DiscoveredFile { file_path: format!("/tmp/{id}.jsonl"), mtime_ms: 0 })
1549 .collect())
1550 }
1551 fn extract_meta(&self, file_path: &str) -> Result<Option<SessionMeta>, HistoryError> {
1552 let id = PathBuf::from(file_path)
1553 .file_stem()
1554 .map(|s| s.to_string_lossy().into_owned())
1555 .unwrap_or_default();
1556 Ok(Some(SessionMeta {
1557 session_id: id,
1558 file_path: file_path.to_string(),
1559 provider: "mock".into(),
1560 model: String::new(),
1561 slug: String::new(),
1562 working_directory: "/proj".into(),
1563 created_at: 0,
1564 modified_at: 0,
1565 message_count: 0,
1566 first_user_message: String::new(),
1567 file_size_bytes: 0,
1568 git_branch: String::new(),
1569 total_tokens: 0,
1570 subagent_count: 0,
1571 identity_id: String::new(),
1572 starts_undated: false,
1573 }))
1574 }
1575 fn parse_file(&self, file_path: &str) -> Result<Option<HistorySession>, HistoryError> {
1576 self.parsed.lock().unwrap().push(file_path.to_string());
1577 let id = PathBuf::from(file_path)
1578 .file_stem()
1579 .map(|s| s.to_string_lossy().into_owned())
1580 .unwrap_or_default();
1581 if id.starts_with("corrupt") {
1582 return Err(HistoryError::Other("unexpected end of JSON".into()));
1583 }
1584 let Some(messages) = self.sessions.get(&id) else { return Ok(None) };
1585 let meta = self.extract_meta(file_path)?.unwrap();
1586 let skipped_records = if id.starts_with("partial") { 2 } else { 0 };
1587 Ok(Some(HistorySession { meta, messages: messages.clone(), skipped_records }))
1588 }
1589 }
1590
1591 fn msg(role: &str, content: &str, tools: Vec<(&str, &str)>) -> HistoryMessage {
1592 HistoryMessage {
1593 role: role.to_string(),
1594 content: content.to_string(),
1595 timestamp: 100, origin: None,
1596 tool_uses: tools
1597 .into_iter()
1598 .map(|(n, a)| ToolUseSummary { name: n.to_string(), argument_summary: a.to_string() })
1599 .collect(),
1600 }
1601 }
1602
1603 fn search_index(sessions: Vec<(&str, Vec<HistoryMessage>)>) -> SessionIndex {
1604 let map: HashMap<String, Vec<HistoryMessage>> =
1605 sessions.into_iter().map(|(id, m)| (id.to_string(), m)).collect();
1606 let idx = SessionIndex::new(vec![Box::new(SearchMockAdapter {
1607 sessions: map,
1608 parsed: Mutex::new(Vec::new()),
1609 })]);
1610 idx.refresh();
1611 idx
1612 }
1613
1614 fn opts(query: &str) -> HistorySearchOptions {
1615 HistorySearchOptions { query: query.into(), limit: 50, ..Default::default() }
1616 }
1617
1618 fn at(timestamp: i64, content: &str) -> HistoryMessage {
1619 HistoryMessage { timestamp, ..msg("assistant", content, vec![]) }
1620 }
1621
1622 #[test]
1623 fn a_bare_tool_name_matches_the_mcp_prefixed_call() {
1624 let idx = search_index(vec![(
1628 "s1",
1629 vec![msg("assistant", "sent", vec![("mcp__agentmux__SendMessage", r#"{"to":"Agent4"}"#)])],
1630 )]);
1631 let cands = vec![idx.get_meta("s1").unwrap()];
1632 for wanted in ["SendMessage", "sendmessage", "mcp__agentmux__SendMessage"] {
1633 let mut o = opts("");
1634 o.tool = Some(wanted.into());
1635 let out = idx.search_sessions(&cands, &o);
1636 assert_eq!(out.hits.len(), 1, "tool: {wanted}");
1637 assert_eq!(out.hits[0].tool_name.as_deref(), Some("mcp__agentmux__SendMessage"));
1638 }
1639 let mut other = opts("");
1640 other.tool = Some("Message".into());
1641 assert!(idx.search_sessions(&cands, &other).hits.is_empty(), "a suffix alone is not a name");
1642 }
1643
1644 #[test]
1645 fn messages_outside_the_time_window_are_not_hits() {
1646 let idx = search_index(vec![(
1647 "s1",
1648 vec![at(1_000, "deploy early"), at(5_000, "deploy late"), at(0, "deploy undated")],
1649 )]);
1650 let cands = vec![idx.get_meta("s1").unwrap()];
1651 let mut o = opts("deploy");
1652 o.since_ms = Some(2_000);
1653 let snippets: Vec<String> = idx.search_sessions(&cands, &o).hits.into_iter().map(|h| h.snippet).collect();
1654 assert_eq!(snippets, vec!["deploy late", "deploy undated"]);
1657
1658 let mut o = opts("deploy");
1659 o.until_ms = Some(2_000);
1660 let snippets: Vec<String> = idx.search_sessions(&cands, &o).hits.into_iter().map(|h| h.snippet).collect();
1661 assert_eq!(snippets, vec!["deploy early", "deploy undated"]);
1662 }
1663
1664 #[test]
1665 fn a_full_search_says_it_is_complete() {
1666 let idx = search_index(vec![("s1", vec![msg("assistant", "nothing relevant", vec![])])]);
1667 let cands = vec![idx.get_meta("s1").unwrap()];
1668 let out = idx.search_sessions(&cands, &opts("never said"));
1669 assert!(out.hits.is_empty());
1670 assert!(out.complete, "every candidate was read to the end");
1671 assert!(out.incomplete_reasons.is_empty());
1672 }
1673
1674 #[test]
1675 fn a_max_sessions_cut_is_counted_and_makes_the_answer_incomplete() {
1676 let idx = search_index(vec![
1677 ("a", vec![msg("assistant", "x", vec![])]),
1678 ("b", vec![msg("assistant", "x", vec![])]),
1679 ("c", vec![msg("assistant", "x", vec![])]),
1680 ]);
1681 let cands: Vec<SessionMeta> = ["a", "b", "c"].iter().map(|id| idx.get_meta(id).unwrap()).collect();
1682 let mut o = opts("absent");
1683 o.max_sessions = Some(1);
1684 let out = idx.search_sessions(&cands, &o);
1685 assert_eq!(out.total_sessions, 3, "counted before the cut");
1686 assert_eq!(out.sessions_scanned, 1);
1687 assert_eq!(out.sessions_skipped, 2);
1688 assert!(!out.complete);
1689 assert_eq!(out.incomplete_reasons, vec!["max_sessions"]);
1690 }
1691
1692 #[test]
1693 fn a_session_with_unreadable_records_makes_the_answer_incomplete() {
1694 let idx = search_index(vec![("partial-1", vec![msg("assistant", "deploy done", vec![])])]);
1698 let cands = vec![idx.get_meta("partial-1").unwrap()];
1699 let out = idx.search_sessions(&cands, &opts("deploy"));
1700 assert_eq!(out.hits.len(), 1);
1701 assert_eq!(out.sessions_scanned, 1, "it was read, partly");
1702 assert_eq!(out.sessions_partly_read.len(), 1);
1703 assert_eq!(out.sessions_partly_read[0].session_id, "partial-1");
1704 assert!(out.sessions_partly_read[0].reason.contains("2 record"), "{}", out.sessions_partly_read[0].reason);
1705 assert!(!out.complete);
1706 assert_eq!(out.incomplete_reasons, vec!["unreadable_records"]);
1707 }
1708
1709 #[test]
1710 fn an_unreadable_session_is_reported_not_counted_as_scanned() {
1711 let idx = search_index(vec![
1712 ("good", vec![msg("assistant", "x", vec![])]),
1713 ("corrupt-1", vec![]),
1714 ]);
1715 let cands: Vec<SessionMeta> =
1716 ["good", "corrupt-1"].iter().map(|id| idx.get_meta(id).unwrap()).collect();
1717 let out = idx.search_sessions(&cands, &opts("absent"));
1718 assert_eq!(out.sessions_scanned, 1, "only the session actually read");
1719 assert_eq!(out.sessions_unreadable.len(), 1);
1720 assert_eq!(out.sessions_unreadable[0].session_id, "corrupt-1");
1721 assert!(out.sessions_unreadable[0].reason.contains("unexpected end of JSON"));
1722 assert!(!out.complete);
1723 assert_eq!(out.incomplete_reasons, vec!["unreadable_sessions"]);
1724 }
1725
1726 #[test]
1727 fn search_matches_message_content() {
1728 let idx = search_index(vec![("s1", vec![msg("assistant", "I merged the WAN signing PR", vec![])])]);
1729 let cands = vec![idx.get_meta("s1").unwrap()];
1730 let out = idx.search_sessions(&cands, &opts("wan signing"));
1731 assert_eq!(out.hits.len(), 1);
1732 assert!(out.hits[0].snippet.contains("WAN signing"), "snippet carries the match");
1733 assert!(!out.truncated);
1734 }
1735
1736 #[test]
1737 fn search_matches_a_tool_call_structurally_not_just_prose() {
1738 let args = r#"{"to":"Agent4","message":"following up"}"#;
1742 let idx = search_index(vec![(
1743 "s1",
1744 vec![msg("assistant", "sure, sending now", vec![("SendMessage", args)])],
1745 )]);
1746 let cands = vec![idx.get_meta("s1").unwrap()];
1747
1748 let mut o = opts("");
1749 o.tool = Some("sendmessage".into()); let out = idx.search_sessions(&cands, &o);
1751 assert_eq!(out.hits.len(), 1);
1752 assert_eq!(out.hits[0].tool_name.as_deref(), Some("SendMessage"));
1753 assert!(out.hits[0].snippet.contains("Agent4"));
1754
1755 let mut o2 = opts("agent4");
1757 o2.tool = Some("SendMessage".into());
1758 assert_eq!(idx.search_sessions(&cands, &o2).hits.len(), 1);
1759 let mut o3 = opts("agent9");
1760 o3.tool = Some("SendMessage".into());
1761 assert_eq!(idx.search_sessions(&cands, &o3).hits.len(), 0);
1762 }
1763
1764 #[test]
1765 fn an_exhausted_budget_is_distinguishable_from_no_matches() {
1766 let many: Vec<HistoryMessage> =
1771 (0..10).map(|i| msg("assistant", &format!("hit number {i}"), vec![])).collect();
1772 let idx = search_index(vec![("s1", many)]);
1773 let cands = vec![idx.get_meta("s1").unwrap()];
1774
1775 let mut limited = opts("hit number");
1776 limited.limit = 3;
1777 let out = idx.search_sessions(&cands, &limited);
1778 assert_eq!(out.hits.len(), 3);
1779 assert!(out.truncated, "stopping on budget must be reported");
1780 assert!(!out.complete);
1781 assert_eq!(out.incomplete_reasons, vec!["hit_limit"]);
1782
1783 let absent = idx.search_sessions(&cands, &opts("never appears anywhere"));
1784 assert!(absent.hits.is_empty());
1785 assert!(!absent.truncated, "genuinely-no-matches must NOT look truncated");
1786 assert!(absent.complete);
1787 }
1788
1789 #[test]
1790 fn search_only_opens_the_sessions_it_is_handed() {
1791 let idx = search_index(vec![
1794 ("keep", vec![msg("assistant", "findme", vec![])]),
1795 ("skip", vec![msg("assistant", "findme", vec![])]),
1796 ]);
1797 let cands = vec![idx.get_meta("keep").unwrap()];
1798 let out = idx.search_sessions(&cands, &opts("findme"));
1799 assert_eq!(out.hits.len(), 1);
1800 assert_eq!(out.sessions_scanned, 1);
1801 assert_eq!(out.total_sessions, 1);
1802 assert_eq!(out.hits[0].session_id, "keep");
1803 }
1804
1805 #[test]
1806 fn role_filter_narrows_to_one_side_of_the_conversation() {
1807 let idx = search_index(vec![(
1808 "s1",
1809 vec![msg("user", "deploy it", vec![]), msg("assistant", "deploy it? confirming first", vec![])],
1810 )]);
1811 let cands = vec![idx.get_meta("s1").unwrap()];
1812 let mut o = opts("deploy it");
1813 o.role = Some("user".into());
1814 let out = idx.search_sessions(&cands, &o);
1815 assert_eq!(out.hits.len(), 1);
1816 assert_eq!(out.hits[0].role, "user");
1817 }
1818
1819 #[test]
1820 fn a_snippet_is_bounded_even_for_a_pathologically_large_message() {
1821 let huge = format!("{}NEEDLE{}", "x".repeat(50_000), "y".repeat(50_000));
1823 let idx = search_index(vec![("s1", vec![msg("assistant", &huge, vec![])])]);
1824 let cands = vec![idx.get_meta("s1").unwrap()];
1825 let out = idx.search_sessions(&cands, &opts("needle"));
1826 assert_eq!(out.hits.len(), 1);
1827 assert!(out.hits[0].snippet.chars().count() <= SNIPPET_MAX_CHARS + 2, "snippet stays bounded");
1828 assert!(out.hits[0].snippet.contains("NEEDLE"), "and still shows the match");
1829 }
1830
1831 #[test]
1838 fn a_tool_hit_snippet_contains_the_match_even_far_into_a_long_argument() {
1839 let args = format!("{}NEEDLE_TARGET{}", "p".repeat(3_000), "q".repeat(100));
1844 let idx = search_index(vec![("s1", vec![msg("assistant", "sent", vec![("SendMessage", &args)])])]);
1845 let cands = vec![idx.get_meta("s1").unwrap()];
1846
1847 let mut o = opts("needle_target");
1848 o.tool = Some("SendMessage".into());
1849 let out = idx.search_sessions(&cands, &o);
1850 assert_eq!(out.hits.len(), 1);
1851 assert!(
1852 out.hits[0].snippet.contains("NEEDLE_TARGET"),
1853 "snippet must show the match, not the start of the arguments: {}",
1854 out.hits[0].snippet
1855 );
1856 }
1857
1858 #[test]
1859 fn an_untooled_tool_hit_offsets_against_the_arguments_not_name_plus_arguments() {
1860 let args = format!("{}FIND_ME{}", "z".repeat(1_000), "w".repeat(1_000));
1864 let idx = search_index(vec![(
1865 "s1",
1866 vec![msg("assistant", "no prose match here", vec![("SomeVeryLongToolNameIndeed", &args)])],
1867 )]);
1868 let cands = vec![idx.get_meta("s1").unwrap()];
1869
1870 let out = idx.search_sessions(&cands, &opts("find_me"));
1871 assert_eq!(out.hits.len(), 1);
1872 assert_eq!(out.hits[0].tool_name.as_deref(), Some("SomeVeryLongToolNameIndeed"));
1873 assert!(
1874 out.hits[0].snippet.contains("FIND_ME"),
1875 "snippet window must be centred on the real match: {}",
1876 out.hits[0].snippet
1877 );
1878 }
1879
1880 #[test]
1881 fn matching_is_safe_when_lowercasing_changes_byte_length() {
1882 let content = format!("{}NEEDLE tail", "İ".repeat(200));
1888 let idx = search_index(vec![("s1", vec![msg("assistant", &content, vec![])])]);
1889 let cands = vec![idx.get_meta("s1").unwrap()];
1890
1891 let out = idx.search_sessions(&cands, &opts("needle"));
1892 assert_eq!(out.hits.len(), 1);
1893 assert!(
1894 out.hits[0].snippet.contains("NEEDLE"),
1895 "snippet must still contain the match: {}",
1896 out.hits[0].snippet
1897 );
1898 }
1899
1900 #[test]
1901 fn case_insensitive_find_reports_offsets_into_the_original_string() {
1902 assert_eq!(find_case_insensitive("Hello World", "world"), Some(6));
1904 assert_eq!(find_case_insensitive("abc", "zzz"), None);
1905 assert_eq!(find_case_insensitive("abc", ""), None);
1906
1907 let s = "İX";
1910 assert_eq!(find_case_insensitive(s, "x"), Some(2));
1911 assert!(s.is_char_boundary(find_case_insensitive(s, "x").unwrap()));
1912 }
1913
1914 #[test]
1915 fn a_search_that_runs_out_of_time_answers_with_what_it_read_and_says_how_to_narrow() {
1916 let idx = search_index(vec![
1917 ("s1", vec![at(2_000, "deploy one")]),
1918 ("s2", vec![at(1_000, "deploy two")]),
1919 ("s3", vec![at(500, "deploy three")]),
1920 ]);
1921 let cands: Vec<SearchCandidate> = ["s1", "s2", "s3"]
1922 .iter()
1923 .map(|id| SearchCandidate { meta: idx.get_meta(id).unwrap(), source: Source::Transcript, attribution: Attribution::AgentRecord })
1924 .collect();
1925 let mut o = opts("deploy");
1927 o.deadline = Some(std::time::Instant::now() + std::time::Duration::from_millis(150));
1928 let out = search_candidates(&cands, &o, &|c| {
1929 std::thread::sleep(std::time::Duration::from_millis(300));
1930 idx.get_full(&c.meta.session_id)
1931 });
1932 assert_eq!(out.sessions_scanned, 1, "{out:?}");
1933 assert_eq!(out.sessions_skipped, 2);
1934 assert_eq!(out.hits.len(), 1);
1935 assert!(!out.complete, "a partial answer is never a complete one");
1936 assert!(out.incomplete_reasons.contains(&"time_limit"));
1937 assert!(!out.incomplete_reasons.contains(&"max_sessions"), "nothing was cut by max_sessions");
1938 assert!(out.hint.is_some_and(|h| h.contains("since and until")));
1939 }
1940
1941 #[test]
1942 fn a_search_with_time_to_spare_is_complete_and_has_no_hint() {
1943 let idx = search_index(vec![("s1", vec![at(2_000, "deploy one")]), ("s2", vec![at(1_000, "deploy two")])]);
1944 let cands = vec![idx.get_meta("s1").unwrap(), idx.get_meta("s2").unwrap()];
1945 let mut o = opts("deploy");
1946 o.deadline = Some(std::time::Instant::now() + std::time::Duration::from_secs(60));
1947 let out = idx.search_sessions(&cands, &o);
1948 assert_eq!((out.hits.len(), out.complete, out.hint), (2, true, None));
1949 assert!(out.incomplete_reasons.is_empty());
1950 }
1951
1952 #[test]
1953 fn a_search_already_out_of_time_reads_nothing_and_counts_every_session_skipped() {
1954 let idx = search_index(vec![("s1", vec![at(2_000, "deploy one")]), ("s2", vec![at(1_000, "deploy two")])]);
1955 let cands = vec![idx.get_meta("s1").unwrap(), idx.get_meta("s2").unwrap()];
1956 let mut o = opts("deploy");
1957 o.deadline = Some(std::time::Instant::now());
1958 let out = idx.search_sessions(&cands, &o);
1959 assert_eq!((out.sessions_scanned, out.sessions_skipped, out.hits.len()), (0, 2, 0));
1960 assert!(!out.complete);
1961 assert_eq!(out.incomplete_reasons, vec!["time_limit"]);
1962 }
1963}
1964
1965#[cfg(test)]
1966mod refresh_tests {
1967 use super::*;
1971 use std::sync::Arc;
1972
1973 struct ChangingAdapter {
1976 files: Mutex<Vec<DiscoveredFile>>,
1977 extracted: Mutex<Vec<String>>,
1978 }
1979
1980 impl ChangingAdapter {
1981 fn new(files: &[(&str, i64)]) -> Arc<Self> {
1982 Arc::new(Self {
1983 files: Mutex::new(
1984 files
1985 .iter()
1986 .map(|(p, m)| DiscoveredFile { file_path: p.to_string(), mtime_ms: *m })
1987 .collect(),
1988 ),
1989 extracted: Mutex::new(Vec::new()),
1990 })
1991 }
1992 fn set(&self, files: &[(&str, i64)]) {
1993 *self.files.lock().unwrap() = files
1994 .iter()
1995 .map(|(p, m)| DiscoveredFile { file_path: p.to_string(), mtime_ms: *m })
1996 .collect();
1997 }
1998 fn take_extracted(&self) -> Vec<String> {
1999 let mut v = std::mem::take(&mut *self.extracted.lock().unwrap());
2000 v.sort();
2001 v
2002 }
2003 }
2004
2005 impl HistoryAdapter for Arc<ChangingAdapter> {
2006 fn provider(&self) -> &str {
2007 "mock"
2008 }
2009 fn discover_files(&self) -> Result<Vec<DiscoveredFile>, HistoryError> {
2010 Ok(self
2011 .files
2012 .lock()
2013 .unwrap()
2014 .iter()
2015 .map(|f| DiscoveredFile { file_path: f.file_path.clone(), mtime_ms: f.mtime_ms })
2016 .collect())
2017 }
2018 fn extract_meta(&self, file_path: &str) -> Result<Option<SessionMeta>, HistoryError> {
2019 self.extracted.lock().unwrap().push(file_path.to_string());
2020 let id = PathBuf::from(file_path)
2021 .file_stem()
2022 .map(|s| s.to_string_lossy().into_owned())
2023 .unwrap_or_default();
2024 Ok(Some(SessionMeta {
2025 session_id: id,
2026 file_path: file_path.to_string(),
2027 provider: "mock".into(),
2028 model: String::new(),
2029 slug: String::new(),
2030 working_directory: "/proj".into(),
2031 created_at: 0,
2032 modified_at: 0,
2033 message_count: 0,
2034 first_user_message: String::new(),
2035 file_size_bytes: 0,
2036 git_branch: String::new(),
2037 total_tokens: 0,
2038 subagent_count: 0,
2039 identity_id: String::new(),
2040 starts_undated: false,
2041 }))
2042 }
2043 fn parse_file(&self, _: &str) -> Result<Option<HistorySession>, HistoryError> {
2044 Ok(None)
2045 }
2046 }
2047
2048 fn index_over(adapter: &Arc<ChangingAdapter>) -> SessionIndex {
2049 SessionIndex::with_isolated_roots(vec![Box::new(adapter.clone())], vec![])
2050 }
2051
2052 #[test]
2055 fn a_new_index_with_the_saved_cache_reparses_only_what_changed() {
2056 let dir = tempfile::tempdir().unwrap();
2057 let cache = dir.path().join("history").join("session-meta-cache.json");
2058 let a = ChangingAdapter::new(&[("/h/a.jsonl", 1), ("/h/b.jsonl", 1)]);
2059 let first = index_over(&a).with_cache_file(cache.clone());
2060 first.refresh();
2061 assert_eq!(a.take_extracted(), vec!["/h/a.jsonl", "/h/b.jsonl"]);
2062 assert!(cache.exists(), "the first build saves the cache");
2063
2064 a.set(&[("/h/a.jsonl", 1), ("/h/b.jsonl", 2), ("/h/c.jsonl", 1)]);
2066 let second = index_over(&a).with_cache_file(cache.clone());
2067 second.refresh();
2068 assert_eq!(a.take_extracted(), vec!["/h/b.jsonl", "/h/c.jsonl"], "a came from the saved cache");
2069 assert!(second.get_meta("a").is_some() && second.get_meta("c").is_some());
2070 }
2071
2072 #[test]
2075 fn an_unwritable_cache_waits_out_the_interval_and_leaves_no_temp_file() {
2076 let dir = tempfile::tempdir().unwrap();
2077 let blocker = dir.path().join("not-a-dir");
2078 std::fs::write(&blocker, b"a file where the cache dir would be").unwrap();
2079 let cache = blocker.join("session-meta-cache.json");
2080 let a = ChangingAdapter::new(&[("/h/a.jsonl", 1)]);
2081 let idx = index_over(&a).with_cache_file(cache.clone());
2082 idx.refresh();
2083 let first_try = idx.cache_written_at_ms.load(std::sync::atomic::Ordering::Acquire);
2084 assert!(first_try > 0, "the failed attempt is recorded");
2085 a.set(&[("/h/a.jsonl", 2)]);
2086 idx.refresh();
2087 assert_eq!(idx.cache_written_at_ms.load(std::sync::atomic::Ordering::Acquire), first_try, "not retried within the interval");
2088 let leftovers: Vec<_> = std::fs::read_dir(dir.path()).unwrap().filter_map(|e| e.ok()).map(|e| e.file_name()).collect();
2089 assert_eq!(leftovers.len(), 1, "only the blocker file: {leftovers:?}");
2090 }
2091
2092 #[test]
2093 fn a_saved_cache_of_another_version_is_rebuilt_not_trusted() {
2094 let dir = tempfile::tempdir().unwrap();
2095 let cache = dir.path().join("session-meta-cache.json");
2096 std::fs::write(&cache, br#"{"version":999,"entries":{"/h/a.jsonl":[1,null]}}"#).unwrap();
2097 let a = ChangingAdapter::new(&[("/h/a.jsonl", 1)]);
2098 let idx = index_over(&a).with_cache_file(cache);
2099 idx.refresh();
2100 assert_eq!(a.take_extracted(), vec!["/h/a.jsonl"]);
2101 assert!(idx.get_meta("a").is_some(), "the stale entry (no meta) wasn't used");
2102 }
2103
2104 #[test]
2105 fn an_unreadable_saved_cache_is_ignored() {
2106 let dir = tempfile::tempdir().unwrap();
2107 let cache = dir.path().join("session-meta-cache.json");
2108 std::fs::write(&cache, b"not json").unwrap();
2109 let a = ChangingAdapter::new(&[("/h/a.jsonl", 1)]);
2110 let idx = index_over(&a).with_cache_file(cache.clone());
2111 idx.refresh();
2112 assert_eq!(a.take_extracted(), vec!["/h/a.jsonl"]);
2113 let saved: serde_json::Value = serde_json::from_slice(&std::fs::read(&cache).unwrap()).unwrap();
2114 assert_eq!(saved["version"], serde_json::json!(META_CACHE_VERSION), "rewritten after the build");
2115 }
2116
2117 #[test]
2118 fn a_second_refresh_reparses_only_what_changed() {
2119 let a = ChangingAdapter::new(&[("/h/a.jsonl", 1), ("/h/b.jsonl", 1)]);
2120 let idx = index_over(&a);
2121 idx.refresh();
2122 assert_eq!(a.take_extracted(), vec!["/h/a.jsonl", "/h/b.jsonl"]);
2123
2124 idx.refresh();
2125 assert!(a.take_extracted().is_empty(), "unchanged files must not be re-parsed");
2126
2127 a.set(&[("/h/a.jsonl", 2), ("/h/b.jsonl", 1), ("/h/c.jsonl", 1)]);
2128 idx.refresh();
2129 assert_eq!(a.take_extracted(), vec!["/h/a.jsonl", "/h/c.jsonl"]);
2130 assert!(idx.get_meta("c").is_some());
2131 }
2132
2133 #[test]
2134 fn a_file_gone_from_disk_leaves_the_index() {
2135 let a = ChangingAdapter::new(&[("/h/a.jsonl", 1), ("/h/b.jsonl", 1)]);
2136 let idx = index_over(&a);
2137 idx.refresh();
2138 a.set(&[("/h/a.jsonl", 1)]);
2139 idx.refresh();
2140 assert!(idx.get_meta("b").is_none());
2141 assert!(idx.get_meta("a").is_some());
2142 assert!(a.take_extracted().len() == 2, "only the first refresh parsed");
2143 }
2144
2145 #[test]
2146 fn refreshed_at_is_zero_until_the_first_refresh_completes() {
2147 let a = ChangingAdapter::new(&[("/h/a.jsonl", 1)]);
2148 let idx = index_over(&a);
2149 assert_eq!(idx.refreshed_at_ms(), 0);
2150 idx.refresh();
2151 assert!(idx.refreshed_at_ms() > 0);
2152 }
2153
2154 #[test]
2157 fn try_refresh_does_not_wait_for_a_refresh_in_progress() {
2158 let a = ChangingAdapter::new(&[("/h/a.jsonl", 1)]);
2159 let idx = index_over(&a);
2160 let _running = idx.refresh_lock.lock().unwrap();
2161 assert!(idx.try_refresh().is_none());
2162 assert!(a.take_extracted().is_empty());
2163 }
2164
2165 #[test]
2166 fn try_refresh_refreshes_when_nothing_else_is() {
2167 let a = ChangingAdapter::new(&[("/h/a.jsonl", 1)]);
2168 let idx = index_over(&a);
2169 assert!(idx.try_refresh().is_some());
2170 assert!(idx.get_meta("a").is_some());
2171 }
2172
2173 struct SlowAdapter {
2175 walks: std::sync::atomic::AtomicUsize,
2176 }
2177
2178 impl HistoryAdapter for Arc<SlowAdapter> {
2179 fn provider(&self) -> &str {
2180 "mock"
2181 }
2182 fn discover_files(&self) -> Result<Vec<DiscoveredFile>, HistoryError> {
2183 self.walks.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2184 std::thread::sleep(std::time::Duration::from_millis(150));
2185 Ok(Vec::new())
2186 }
2187 fn extract_meta(&self, _: &str) -> Result<Option<SessionMeta>, HistoryError> {
2188 Ok(None)
2189 }
2190 fn parse_file(&self, _: &str) -> Result<Option<HistorySession>, HistoryError> {
2191 Ok(None)
2192 }
2193 }
2194
2195 #[test]
2201 fn concurrent_searches_share_refreshes() {
2202 let a = Arc::new(SlowAdapter { walks: Default::default() });
2203 let idx = Arc::new(SessionIndex::with_isolated_roots(vec![Box::new(a.clone())], vec![]));
2204 let barrier = Arc::new(std::sync::Barrier::new(8));
2205 let threads: Vec<_> = (0..8)
2206 .map(|_| {
2207 let (idx, barrier) = (idx.clone(), barrier.clone());
2208 std::thread::spawn(move || {
2209 barrier.wait();
2210 idx.refresh_covering_now();
2211 })
2212 })
2213 .collect();
2214 for t in threads {
2215 t.join().unwrap();
2216 }
2217 let walks = a.walks.load(std::sync::atomic::Ordering::SeqCst);
2218 assert!((1..=2).contains(&walks), "8 simultaneous searches walked {walks} times");
2219 }
2220
2221 #[test]
2224 fn a_refresh_finished_before_the_request_is_not_reused() {
2225 let a = Arc::new(SlowAdapter { walks: Default::default() });
2226 let idx = SessionIndex::with_isolated_roots(vec![Box::new(a.clone())], vec![]);
2227 idx.refresh();
2228 idx.refresh_covering_now();
2229 assert_eq!(a.walks.load(std::sync::atomic::Ordering::SeqCst), 2);
2230 }
2231
2232 struct ProblemAdapter {
2234 problems: Mutex<Vec<String>>,
2235 }
2236
2237 impl HistoryAdapter for Arc<ProblemAdapter> {
2238 fn provider(&self) -> &str {
2239 "mock"
2240 }
2241 fn discover_files(&self) -> Result<Vec<DiscoveredFile>, HistoryError> {
2242 Ok(vec![DiscoveredFile { file_path: "/h/locked.jsonl".into(), mtime_ms: 1 }])
2243 }
2244 fn discover(&self) -> Result<Discovery, HistoryError> {
2245 Ok(Discovery { files: self.discover_files()?, problems: self.problems.lock().unwrap().clone() })
2246 }
2247 fn extract_meta(&self, _: &str) -> Result<Option<SessionMeta>, HistoryError> {
2248 Err(HistoryError::Other("sharing violation".into()))
2249 }
2250 fn parse_file(&self, _: &str) -> Result<Option<HistorySession>, HistoryError> {
2251 Ok(None)
2252 }
2253 }
2254
2255 #[test]
2260 fn what_discovery_could_not_read_is_kept_with_the_snapshot() {
2261 let a = Arc::new(ProblemAdapter { problems: Mutex::new(vec!["/h/private: Access is denied".into()]) });
2262 let idx = SessionIndex::with_isolated_roots(vec![Box::new(a.clone())], vec![]);
2263 idx.refresh();
2264 let problems = idx.discovery_problems();
2265 assert!(problems.iter().any(|p| p.contains("/h/private")), "{problems:?}");
2266 assert!(
2267 problems.iter().any(|p| p.contains("locked.jsonl") && p.contains("sharing violation")),
2268 "a transcript that couldn't be indexed is a problem too: {problems:?}"
2269 );
2270
2271 a.problems.lock().unwrap().clear();
2272 idx.refresh();
2273 assert_eq!(idx.discovery_problems().len(), 1, "each refresh replaces the last one's problems");
2274 }
2275
2276 #[test]
2279 fn try_first_build_skips_when_busy_or_already_built() {
2280 let idx = SessionIndex::with_isolated_roots(vec![], vec![]);
2281 {
2282 let _running = idx.refresh_lock.lock().unwrap();
2283 assert_eq!(idx.try_first_build(), FirstBuild::Busy);
2284 }
2285 assert_eq!(idx.try_first_build(), FirstBuild::Built { discovered: 0 });
2286 let built_at = idx.refreshed_at_ms();
2287 assert!(built_at > 0);
2288 assert_eq!(idx.try_first_build(), FirstBuild::AlreadyBuilt);
2289 assert_eq!(idx.refreshed_at_ms(), built_at);
2290 }
2291}