Skip to main content

agentmux_srv_core/backend/history/
index.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! In-memory session index built from adapter discovery.
5
6use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8use std::sync::Mutex;
9
10use super::adapter::*;
11
12/// Format version of the saved metadata cache (`SessionIndex::with_cache_file`).
13/// Bump when `SessionMeta` or what `extract_meta` derives changes meaning, so
14/// a stale file is rebuilt rather than trusted.
15pub(crate) const META_CACHE_VERSION: u32 = 1;
16
17/// The saved metadata cache is rewritten at most this often (when changed).
18pub(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
32/// Max characters of matched text returned per hit.
33///
34/// A single history message can be hundreds of KB, and this tool must never be
35/// the reason a caller blows its own context window — the problem it exists to
36/// solve is an agent not being able to audit itself, which is made worse, not
37/// better, by an answer too large to read. Not theoretical: the
38/// `GetAgentTranscript` call that motivated
39/// `SPEC_AGENT_HISTORY_SEARCH_2026_09_17.md` returned 112 KB and had to be
40/// spilled to a file.
41const SNIPPET_MAX_CHARS: usize = 400;
42/// Characters of leading context kept before the match inside a snippet.
43const SNIPPET_LEAD_CHARS: usize = 120;
44
45/// Query parameters for [`SessionIndex::search_sessions`].
46#[derive(Debug, Clone, Default)]
47pub struct HistorySearchOptions {
48    /// Case-insensitive substring. Matched against message content, tool
49    /// names, and tool argument summaries.
50    pub query: String,
51    /// Restrict to `"user"` or `"assistant"` messages.
52    pub role: Option<String>,
53    /// Only match tool calls whose name equals this (case-insensitive).
54    ///
55    /// Its own parameter rather than folding into `query` because "find where
56    /// I *called* SendMessage" is a different question from "find where I
57    /// wrote the word SendMessage", and only the structural answer settles an
58    /// audit.
59    pub tool: Option<String>,
60    /// Max hits to return before reporting `truncated`.
61    pub limit: usize,
62    /// Only messages at or after this instant (Unix ms).
63    pub since_ms: Option<i64>,
64    /// Only messages at or before this instant (Unix ms).
65    pub until_ms: Option<i64>,
66    /// Open at most this many of the candidates, in the order given. The rest
67    /// are counted in `sessions_skipped`, never silently dropped.
68    pub max_sessions: Option<usize>,
69    /// Also search sessions found only by working directory or account, not
70    /// in the agent's own record (see `HistoryService::search_for_agent`).
71    pub include_inferred: bool,
72    /// Stop opening sessions at this instant and answer with what was read: the answer is then not `complete`
73    /// (`incomplete_reasons` holds `"time_limit"`, the rest counts in `sessions_skipped`) and carries a `hint`
74    /// on how to narrow. A caller waits only so long, and a partial answer says more than a timeout. `None`
75    /// is no limit.
76    pub deadline: Option<std::time::Instant>,
77}
78
79/// One match.
80#[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    /// `Some(name)` when the hit is a tool call rather than message prose.
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub tool_name: Option<String>,
90    /// Where the text was read: `"provider_transcript"` or `"agentmux_record"`
91    /// (the transcript is gone; AgentMux's own record of the session).
92    pub source: &'static str,
93    /// Why the session is the caller's: `"agent_record"` (its id is in the
94    /// agent's own record or segment log) or `"inferred"` (found by working
95    /// directory or account only).
96    pub attribution: &'static str,
97}
98
99/// Where a searched session's content comes from.
100#[derive(Debug, Clone)]
101pub(crate) enum Source {
102    Transcript,
103    Record(super::record::RecordSession),
104}
105
106/// Why a session is the caller's.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub(crate) enum Attribution {
109    /// Its id is in the agent's own record or segment log.
110    AgentRecord,
111    /// Found by working directory or account only.
112    Inferred,
113}
114
115/// A session a search may open.
116#[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/// Result of a bounded search.
139#[derive(Debug, Clone, serde::Serialize)]
140pub struct HistorySearchOutcome {
141    pub hits: Vec<HistorySearchHit>,
142    /// Sessions actually opened and read.
143    pub sessions_scanned: u32,
144    /// Candidates in the caller's window, counted before `max_sessions`.
145    pub total_sessions: u32,
146    /// True when the scan stopped on `limit` rather than exhausting every
147    /// candidate — see `search_sessions`' doc comment for why this must never
148    /// be conflated with "no matches".
149    pub truncated: bool,
150    /// True only when every candidate was read to the end: nothing cut by
151    /// `max_sessions`, nothing unreadable, no hit limit reached. An empty
152    /// `hits` is evidence that something did not happen only when this is
153    /// true; otherwise the answer is "unknown", and `incomplete_reasons`
154    /// says why.
155    pub complete: bool,
156    /// `"hit_limit"`, `"max_sessions"`, `"time_limit"`, `"unreadable_sessions"`,
157    /// `"unreadable_records"`, `"discovery_errors"`.
158    pub incomplete_reasons: Vec<&'static str>,
159    /// Candidates left unopened: by `max_sessions`, or by the time limit.
160    pub sessions_skipped: u32,
161    /// Candidates that could not be read, and why.
162    pub sessions_unreadable: Vec<UnreadableSession>,
163    /// Candidates searched, but with records that could not be read.
164    pub sessions_partly_read: Vec<UnreadableSession>,
165    /// What the index refresh behind this search couldn't read. A session
166    /// there may be missing from the candidates.
167    pub discovery_errors: Vec<String>,
168    /// Sessions the agent's own record or segment log names.
169    pub ledger_sessions: u32,
170    /// Of those, sessions whose provider transcript is gone, searched in
171    /// AgentMux's record instead.
172    pub record_only_sessions: u32,
173    /// Sessions found only by working directory or account and left out,
174    /// because the agent's own record doesn't name them. `include_inferred`
175    /// searches them too.
176    pub inferred_sessions_excluded: u32,
177    /// How to get a complete answer, when the search stopped at its time limit.
178    #[serde(skip_serializing_if = "Option::is_none")]
179    pub hint: Option<&'static str>,
180}
181
182/// What a search that ran out of time tells the caller to do.
183const 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
187/// At most this many discovery errors are listed in a search's answer.
188const DISCOVERY_ERRORS_LISTED: usize = 20;
189
190impl HistorySearchOutcome {
191    /// Record that the snapshot this search read couldn't see everything.
192    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/// A candidate session the search could not read.
207#[derive(Debug, Clone, serde::Serialize)]
208pub struct UnreadableSession {
209    pub session_id: String,
210    pub reason: String,
211}
212
213/// Whether a recorded tool name is the tool the caller named. Claude records
214/// an MCP tool with its server prefix (`mcp__agentmux__SendMessage`) while
215/// callers — and SearchHistory's own schema — name it bare (`SendMessage`), so
216/// both forms match. Case-insensitive.
217fn 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
224/// Whether a message falls inside the caller's time window. A message with
225/// no timestamp (0) can't be placed outside it, and dropping it could only
226/// hide evidence, so it's kept.
227fn 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
233/// Case-insensitive substring search returning a byte offset into the
234/// **original** haystack, not into a lowercased copy of it.
235///
236/// The naive version of this (`haystack.to_lowercase().find(needle)`, then
237/// slice `haystack` at the result) is wrong, and wrong in a way that can
238/// panic: lowercasing is not length-preserving. Turkish `İ` (U+0130, 2 bytes)
239/// lowercases to `i̇` (3 bytes), so every such character before the match
240/// shifts the two strings out of alignment — slicing the original at an offset
241/// derived from the lowercased copy can land mid-character and panic, or
242/// silently return a misaligned snippet. Caught by reagentx P1 on PR #3321.
243///
244/// So the lowercase mapping is built explicitly, recording which original byte
245/// each lowercased byte came from.
246fn 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    // lowered-byte-offset -> original-byte-offset
252    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    // Always a char boundary in the original: every entry is the start index
266    // of the char that produced it.
267    origin.get(at).copied()
268}
269
270/// Bound a matched region to something a caller can actually read, keeping a
271/// little context before the match so the hit is interpretable.
272fn 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
292/// Every match within one message: its prose, plus each tool call.
293fn 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    // Tool-call matches. When `tool` is set the search is structural: the
303    // filter is the tool NAME, and an empty query then means "every call to
304    // it" rather than "no matches".
305    //
306    // Every snippet offset below is resolved against the exact string the
307    // snippet is cut from. Deriving an offset from one string and slicing
308    // another — e.g. finding in `"{name} {args}"` and slicing `args` — puts
309    // the window in the wrong place, and for a long argument summary silently
310    // returns evidence that does not contain the match. A hit whose snippet
311    // omits the match is worse than no hit: it looks like verification.
312    // Both were reagentx P1s on PR #3321.
313    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            // Empty query + tool filter = "every call to this tool", so the
319            // start of the arguments is the right window.
320            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        // No tool filter: the query may match the tool's NAME or its
343        // arguments. Searched separately so the snippet offset always belongs
344        // to `argument_summary`, the string actually being cut.
345        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    // Prose match — skipped entirely when the caller asked a structural
365    // tool-only question.
366    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
384/// Search message content and tool calls across a chosen set of sessions,
385/// whose content `load` reads — from a provider transcript or from AgentMux's
386/// record. See [`SessionIndex::search_sessions`] for why stopping early is
387/// always reported.
388pub(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            // More candidates remained that were never opened.
408            truncated = true;
409            break;
410        }
411        if opts.deadline.is_some_and(|deadline| std::time::Instant::now() >= deadline) {
412            // Out of time: the sessions not yet opened are counted, never dropped silently.
413            timed_out = true;
414            sessions_skipped += (opened - position) as u32;
415            break;
416        }
417        // A session that fails to parse is skipped, not fatal: one
418        // malformed file must not make the whole audit unanswerable. But
419        // it's reported, never counted as read.
420        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
504/// AgentMux-ISOLATED provider-home roots under which delete/clear is permitted:
505/// `<shared>/providers/` and `<shared>/identities/`. Anything outside these
506/// (the user's personal `~/.claude` / `~/.config/claude-*`) is OFF-LIMITS so a
507/// "clear all" can never nuke transcripts AgentMux didn't create.
508fn 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
518/// Normalize a working directory for use as an index key.
519///
520/// Separators are unified and trailing ones dropped so the same directory
521/// written `C:\x\y`, `C:/x/y` and `C:/x/y/` all collide on one key. Case is
522/// folded on Windows only: its filesystem is case-insensitive, so `C:\Users`
523/// and `c:\users` are genuinely the same directory — but on Linux they are
524/// two different directories, and folding case there would merge the history
525/// of two unrelated agents.
526pub(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/// Outcome of [`SessionIndex::try_first_build`].
537#[derive(Debug, PartialEq, Eq)]
538pub enum FirstBuild {
539    /// This call ran the first build.
540    Built { discovered: u32 },
541    /// Another caller already finished it.
542    AlreadyBuilt,
543    /// A refresh (possibly the first build) is running right now.
544    Busy,
545}
546
547/// In-memory index of discovered sessions.
548pub struct SessionIndex {
549    /// session_id -> SessionMeta
550    sessions: Mutex<HashMap<String, SessionMeta>>,
551    /// normalized working directory -> session_ids.
552    ///
553    /// The identity index below can only find sessions for an agent that has
554    /// a `db_agent_identity_links` row binding it to the account its
555    /// transcripts were written under. An agent running on ambient
556    /// credentials has no such row (and its registry record's `identity_id`
557    /// reads `"default"`), so for that — the common — case the identity index
558    /// resolves to nothing at all while the transcripts sit on disk perfectly
559    /// intact. The working directory is recorded both in the transcript
560    /// itself (`cwd`) and on the agent's own row, which makes it the join key
561    /// that actually holds for those agents. See
562    /// `docs/specs/SPEC_CROSS_CHANNEL_AGENT_HISTORY_RESOLUTION_2026_09_21.md`.
563    /// **LOCK ORDER — `sessions` is always acquired BEFORE this map, and
564    /// before `by_identity`.** Never the reverse, anywhere.
565    ///
566    /// `refresh()` holds the `sessions` guard while it swaps both index maps
567    /// in, so it takes `sessions -> by_working_dir`. A reader that took
568    /// `by_working_dir -> sessions` would be a textbook AB-BA deadlock the
569    /// moment a `refresh()` (triggered by any `list`/`sessions_for_agent`
570    /// call) overlapped it on the shared `Arc<SessionIndex>` — thread A
571    /// holding `sessions` and blocking on the map, thread B holding the map
572    /// and blocking on `sessions`. Both readers below therefore take
573    /// `sessions` first, even though reading the map first would read more
574    /// naturally. reagentx P1 on PR #3480.
575    by_working_dir: Mutex<HashMap<String, Vec<String>>>,
576    /// identity_id -> session_ids (only non-empty `SessionMeta::identity_id`
577    /// values are indexed here). Maintained alongside `sessions` so "this
578    /// identity's sessions" is an O(k) HashMap lookup + small per-identity
579    /// sort, not an O(total sessions) scan of everything on disk — see
580    /// `list_for_identity` and
581    /// `docs/specs/SPEC_AGENT_IDENTITY_HISTORY_PERSISTENCE_PROTOCOL_2026_08_16.md`
582    /// §4.4.
583    by_identity: Mutex<HashMap<String, Vec<String>>>,
584    /// file path -> (mtime it was parsed at, what it parsed to). A cold
585    /// refresh JSON-parses every line of every transcript on the machine
586    /// (42k files / 3.8 GB on one real host), so later refreshes reuse this
587    /// for files whose mtime hasn't moved. Only touched under `refresh_lock`.
588    meta_cache: Mutex<HashMap<String, (i64, Option<SessionMeta>)>>,
589    /// Where `meta_cache` is kept between launches (`with_cache_file`), so the
590    /// first refresh after a start parses only transcripts that changed since,
591    /// instead of every transcript on the machine (63k sessions took 92–154 s
592    /// per launch; SPEC_AGENT_OPEN_LATENCY_2026_09_27.md §4.3). `None`: kept in
593    /// memory only.
594    cache_file: Option<PathBuf>,
595    /// The cache file has been read (once, at the first refresh).
596    cache_loaded: std::sync::atomic::AtomicBool,
597    /// Unix ms when the cache file was last written; 0 = never.
598    cache_written_at_ms: std::sync::atomic::AtomicI64,
599    /// Serializes refreshes. Held for a whole refresh, never while taking any
600    /// lock above, so it adds no ordering constraint.
601    pub(super) refresh_lock: Mutex<()>,
602    /// Unix ms when the last refresh finished; 0 = never.
603    refreshed_at_ms: std::sync::atomic::AtomicI64,
604    /// Refreshes started so far; each takes the next number, under
605    /// `refresh_lock`, before it lists anything.
606    refreshes_started: std::sync::atomic::AtomicU64,
607    /// The number of the last refresh that finished. A request that finds it
608    /// higher than `refreshes_started` was when the request began knows a
609    /// refresh listed the disk after it began — see [`Self::refresh_covering_now`].
610    last_finished_refresh: std::sync::atomic::AtomicU64,
611    /// What the last refresh couldn't read (see [`Discovery::problems`]),
612    /// kept with the snapshot it produced.
613    discovery_problems: Mutex<Vec<String>>,
614    /// Adapters for all registered providers
615    adapters: Vec<Box<dyn HistoryAdapter>>,
616    /// Roots under which destructive ops (delete/clear) are allowed.
617    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    /// Construct with explicit isolated roots (used by new() and tests).
626    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    /// Keep the parsed-metadata cache in `path` between launches. Read at the
649    /// first refresh (not here: the file can be tens of MB, and construction
650    /// runs at srv startup), written after the first build and then at most
651    /// every [`META_CACHE_WRITE_INTERVAL_MS`], only when something changed.
652    pub fn with_cache_file(mut self, path: PathBuf) -> Self {
653        self.cache_file = Some(path);
654        self
655    }
656
657    /// Unix ms when the last refresh finished; 0 if none has.
658    pub fn refreshed_at_ms(&self) -> i64 {
659        self.refreshed_at_ms.load(std::sync::atomic::Ordering::Acquire)
660    }
661
662    /// [`Self::refresh`], unless another refresh is already running — then
663    /// `None` at once instead of waiting it out.
664    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    /// The first build, unless one isn't needed or can't start now: never
674    /// waits on the refresh lock, and checks "already built" while holding it
675    /// (`refreshed_at_ms` is stored under the lock), so it can't follow
676    /// another caller's first build with a second full pass.
677    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    /// Fill `meta_cache` from the cache file, once per index, if it is still
691    /// empty. A missing, unreadable or other-version file is ignored: the
692    /// refresh then parses everything, as it always did.
693    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    /// Save `cache` to the cache file when it changed: always after the first
714    /// build, then at most every `META_CACHE_WRITE_INTERVAL_MS` (searches also
715    /// refresh, and the file is tens of MB). Written to a temporary file and
716    /// renamed over the old one, so a reader (another srv instance) never sees
717    /// half a file. Failures are logged, never fatal: the cache only saves time.
718    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        // Recorded whether or not the write works: an unwritable cache (a
740        // read-only shared dir, a full disk) then waits out the interval too,
741        // instead of being serialized and retried on every refresh — and
742        // searches refresh.
743        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                // Never leave a partial or orphaned temporary file (tens of MB,
748                // one per srv process) in the shared dir.
749                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    /// True if `path` lives under an AgentMux-isolated provider home and is
756    /// therefore safe to delete. Personal global homes are never isolated.
757    fn is_isolated(&self, path: &Path) -> bool {
758        self.isolated_roots.iter().any(|r| path.starts_with(r))
759    }
760
761    /// Full scan: discover all files and extract metadata.
762    /// Returns (discovered, updated, new) counts.
763    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    /// Make the snapshot include every session on disk when this call began,
769    /// sharing the work with concurrent callers. A refresh that started after
770    /// this call began already listed everything this call needs, so once it
771    /// has finished there's nothing left to do; otherwise this runs its own.
772    /// However many searches arrive together, that's at most two walks —
773    /// every search running its own, one after another, put the fourth past
774    /// the MCP's 10 s timeout on a heavy host (Codex P1 on #3693).
775    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    /// What the last refresh couldn't read — a session there may be missing
786    /// from the snapshot.
787    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) => {} // empty/invalid session
858                    Err(e) => {
859                        tracing::debug!(
860                            "history: failed to extract meta from {}: {}",
861                            file.file_path,
862                            e
863                        );
864                        // A transcript that couldn't be indexed is missing
865                        // from the snapshot, whoever it belongs to.
866                        problems.push(format!("{}: {e}", file.file_path));
867                    }
868                }
869            }
870        }
871
872        // Compare with existing index
873        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        // Something to save: a transcript parsed afresh, or one gone since.
887        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    /// Every session recorded as having run in `working_directory`.
905    ///
906    /// Matching is on the normalized full path ([`normalize_working_dir`]),
907    /// never a substring: `list`'s `project` filter uses `contains`, which
908    /// would make an agent in `/agents/foo` also claim every session from
909    /// `/agents/foo-2`.
910    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        // `sessions` FIRST — see the lock-order invariant on `by_working_dir`.
916        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    /// This identity's sessions, sorted/paginated the same way `list` is —
925    /// but via the `by_identity` index instead of scanning every session on
926    /// disk. `identity_id` is a bundle/account id (`SessionMeta::identity_id`
927    /// — see its own doc comment); resolving an `agent_id` to one is the
928    /// caller's job (`Store::agent_identity_list_for_agent`), not this
929    /// index's — a bundle is a filesystem fact, which agent(s) claim it is
930    /// a database fact, and this module has no Store access by design (it's
931    /// pure discovery/indexing over the filesystem).
932    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        // `sessions` FIRST — see the lock-order invariant on `by_working_dir`.
941        // This ordering was inverted here BEFORE PR #3480 (`refresh()` has
942        // always held `sessions` while swapping `by_identity` in), so the same
943        // AB-BA deadlock was already latent on `main` for the identity index.
944        // Fixed alongside the `by_working_dir` one rather than leaving a known
945        // instance of the bug in place next to its fix.
946        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    /// Shared sort logic between `list` (scans everything) and
962    /// `list_for_identity` (scans one identity's sessions) — extracted so
963    /// the two can't silently diverge on sort semantics.
964    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                // Default: modified_at desc
996                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    /// List sessions with pagination and optional filters.
1008    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    /// Get a session by ID — returns just the meta from index.
1051    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    /// Full parse of a session by ID.
1057    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        // Find the adapter for this provider
1064        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    /// Search message content and tool calls across a specific, already-chosen
1077    /// set of sessions.
1078    ///
1079    /// `SPEC_AGENT_HISTORY_SEARCH_2026_09_17.md` §3.1/§3.2. The caller picks
1080    /// the candidate sessions (normally `HistoryService::search_for_agent`,
1081    /// which resolves them from the agent's linked identities and applies the
1082    /// `since`/`until` window) — this function only scans what it is handed,
1083    /// so the expensive `get_full` parse never touches a session the caller
1084    /// already ruled out on cheap indexed metadata.
1085    ///
1086    /// Bounded deliberately: it stops at `limit` hits and reports whether it
1087    /// stopped early. **That signal is load-bearing.** A search that silently
1088    /// truncates and returns nothing reproduces the exact failure this whole
1089    /// feature exists to prevent — an agent concluding "I never did that" from
1090    /// an incomplete audit — so "no matches" and "ran out of budget" must never
1091    /// look the same to a caller. The same goes for every other way a
1092    /// candidate goes unread (a `max_sessions` cut, a file that won't parse):
1093    /// each is counted, and any of them makes the answer not `complete`.
1094    #[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    /// Check if the index has been populated.
1112    #[cfg(test)]
1113    pub fn is_empty(&self) -> bool {
1114        self.sessions.lock().unwrap().is_empty()
1115    }
1116
1117    /// Delete a session: remove its on-disk transcript (and the sibling
1118    /// `<session_id>/` subagents dir Claude keeps next to it) and drop it from
1119    /// the index. Returns Ok(true) if a file was removed, Ok(false) if the
1120    /// session id is unknown.
1121    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        // Safety: only delete inside AgentMux-isolated homes — never the user's
1128        // personal Claude/Codex/... transcripts that the browse also surfaces.
1129        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        // Treat an already-removed file (GC'd out-of-band) as success so the
1136        // stale index entry still gets dropped (otherwise clear-all can't
1137        // converge and the index stays non-empty).
1138        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        // Claude stores subagent transcripts in a sibling `<session_id>/` dir;
1144        // remove it too so the clear actually frees the space. Best-effort.
1145        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    /// Bulk-delete all indexed sessions matching the optional provider/project
1156    /// filter (no filter = clear everything). Returns the number removed.
1157    pub fn clear(&self, provider: Option<&str>, project: Option<&str>) -> u32 {
1158        // Snapshot matching ids while holding the lock, then do fs ops without
1159        // it (delete() re-locks per id).
1160        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                // Never bulk-delete the user's personal global transcripts.
1167                .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    /// Adapter that "discovers" caller-supplied files and derives the session id
1188    /// from each file stem. Just enough to populate the index for delete tests.
1189    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        // A sibling subagents dir should be removed too.
1247        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        // Non-matching provider clears nothing; matching clears both.
1293        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        // A session that lives OUTSIDE the isolated roots (i.e. the user's
1305        // personal global home) must never be deletable.
1306        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            // isolated roots deliberately do NOT include `dir`.
1318            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    // docs/specs/SPEC_AGENT_IDENTITY_HISTORY_PERSISTENCE_PROTOCOL_2026_08_16.md
1331    // §4.4: list_for_identity is the actual "fast lookup" this whole step
1332    // exists for — an O(sessions for this identity) HashMap-backed lookup
1333    // instead of list()'s O(total sessions on disk) scan.
1334
1335    #[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    /// Hammers the two conflicting lock orders against each other on the same
1425    /// `Arc<SessionIndex>` a real deployment shares between requests.
1426    ///
1427    /// A deadlock does not *fail* a test, it hangs it — and a hung test hangs
1428    /// CI rather than reporting anything useful. So the workers signal a
1429    /// channel and the assertion is a bounded `recv_timeout`: a deadlock
1430    /// becomes a normal test failure with a readable message, and the threads
1431    /// are deliberately not joined (joining a deadlocked thread would hang
1432    /// exactly as badly as the bug).
1433    ///
1434    /// Against the pre-fix ordering — `refresh()` taking `sessions ->
1435    /// by_working_dir` while `list_for_working_directory()` took
1436    /// `by_working_dir -> sessions` — this wedges. reagentx P1 on PR #3480.
1437    #[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        // A session that's re-discovered under a DIFFERENT identity on a
1496        // second refresh (e.g. its bundle got re-linked) must not leave a
1497        // stale entry under the old identity_id.
1498        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    // ── History search (SPEC_AGENT_HISTORY_SEARCH_2026_09_17.md) ──
1531
1532    /// Adapter serving canned messages, recording which files were actually
1533    /// opened — the recording is what lets a test prove the search never
1534    /// parses a session the caller already excluded.
1535    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        // Claude records an MCP tool with its server prefix, while callers —
1625        // and SearchHistory's own schema — name it bare. "Did I call
1626        // SendMessage" must find the AgentMux tool, not only the built-in one.
1627        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        // An undated message can't be placed outside the window, and dropping
1655        // it could only hide evidence.
1656        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        // What the session's readable records hold is still found; that it
1695        // had records the search couldn't read is reported, so "no hit" for
1696        // anything else isn't taken as proof (Codex P1 on #3693).
1697        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        // The question that motivated this whole feature: "did I call
1739        // SendMessage to Agent4" must be answerable even when no prose in the
1740        // transcript mentions it.
1741        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()); // case-insensitive
1750        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        // And filtering by argument content within that tool.
1756        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        // The single most important property here. A search that silently
1767        // stops early and returns nothing recreates the exact failure this
1768        // feature exists to prevent: an agent concluding "I never did that"
1769        // from an incomplete audit.
1770        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        // What makes the since/until window cheap: excluded candidates are
1792        // never parsed, because the caller filters on indexed metadata first.
1793        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        // This tool must never be the reason a caller blows its own context.
1822        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    // ── Snippet/offset correctness (reagentx P1s on PR #3321) ──
1832    //
1833    // All three of these fail against the original implementation. They are
1834    // about the same underlying mistake in three places: an offset computed
1835    // against one string and then used to slice a different one.
1836
1837    #[test]
1838    fn a_tool_hit_snippet_contains_the_match_even_far_into_a_long_argument() {
1839        // The snippet used to be cut from offset 0 whenever a `tool` filter
1840        // was set, so a match past SNIPPET_MAX_CHARS was reported as a hit
1841        // whose evidence did not contain it. A hit whose snippet omits the
1842        // match is worse than no hit — it looks like verification.
1843        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        // Previously the offset came from `format!("{name} {args}")` but was
1861        // used to slice `args` alone, so the window was shifted by
1862        // name.len()+1 — and for a long name effectively clamped to the end.
1863        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        // Lowercasing is not length-preserving: 'İ' (U+0130, 2 bytes) becomes
1883        // 'i̇' (3 bytes). Finding in a lowercased copy and slicing the
1884        // original therefore drifts by one byte per such character, which can
1885        // slice mid-character and panic. This must neither panic nor
1886        // mis-window.
1887        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        // Direct unit coverage of the helper the three fixes above rely on.
1903        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        // 'İ' is 2 bytes and lowercases to 3, so a naive lowercased-offset
1908        // would report 3 here instead of the correct 2.
1909        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        // Each session takes longer to read than the whole budget, so the first is read and the rest are not.
1926        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    //! Incremental refresh (SPEC_DURABLE_CONVERSATION_MEMORY_2026_09_23.md
1968    //! §4.5): a cold refresh parses every transcript on the machine, so a
1969    //! refresh must only re-parse what changed.
1970    use super::*;
1971    use std::sync::Arc;
1972
1973    /// Files whose mtimes a test can change between refreshes, counting every
1974    /// `extract_meta` call per path.
1975    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    /// Across a restart: a new index over the same saved cache file parses
2053    /// only what changed since the last launch saved it.
2054    #[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        // "Restart": a fresh index, b changed while AgentMux was closed.
2065        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    /// An unwritable cache location is tried once per interval, not on every
2073    /// refresh, and leaves no temporary file behind.
2074    #[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    /// A search must never wait out a cold build behind the MCP's 10 s
2155    /// timeout: while another refresh runs, `try_refresh` returns at once.
2156    #[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    /// Discovery that walks slowly and counts its walks.
2174    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    /// Searches arriving together share refreshes: a refresh that started
2196    /// after a request began already lists everything that existed when it
2197    /// began. Every search running its own full walk, one after another,
2198    /// put the fourth past the MCP's 10 s timeout on a heavy host (Codex P1
2199    /// on #3693).
2200    #[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    /// …but a refresh that finished before the request began may have
2222    /// missed a session written since, so it's never reused.
2223    #[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    /// Discovery that reports what it couldn't look at.
2233    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    /// A directory the walk couldn't read, or a transcript it couldn't index,
2256    /// may hold the very session being searched for. Both are kept with the
2257    /// snapshot so a search over it can't claim to be complete (Codex P1 on
2258    /// #3693).
2259    #[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    /// The first build never waits on, or repeats, another caller's
2277    /// (Codex P2 on #3930).
2278    #[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}