Skip to main content

agentmux_srv_core/backend/history/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! History module — discovers and indexes past CLI agent conversations from disk.
5
6pub mod adapter;
7pub mod claude_adapter;
8pub mod index;
9pub mod agent_sessions;
10pub mod record;
11pub mod typed;
12
13use std::sync::Arc;
14
15use adapter::*;
16use claude_adapter::ClaudeHistoryAdapter;
17use index::SessionIndex;
18
19/// The global named-agent registry record for `agent_id`, for agents that have
20/// no `db_agents` row — launching an agent does not create one, so a live agent
21/// commonly exists only here.
22///
23/// Fetched at most once per `sessions_for_agent` call and used for BOTH
24/// fallbacks the record can answer (definition id and working directory).
25/// It used to return just the working directory, which meant the record's
26/// `definition_id` — sitting right there — went unread, and identity-link
27/// resolution fell back to the raw slug instead (reagentx P1 on PR #3480,
28/// re-review).
29///
30/// The lookup itself comes from `backend::agent_registry_lookup`, which owns
31/// the only copy of the slug-matching and path-reconstruction rules; this
32/// function previously re-implemented both inline, which reagentx P2 on the
33/// same PR flagged against `native_memory_handlers`' copy, since a later fix
34/// to either one would silently miss the other.
35fn registry_record(agent_id: &str) -> Option<crate::registry::NamedAgentRecord> {
36    crate::backend::agent_registry_lookup::find_active_record_by_slug(agent_id)
37}
38
39/// Whose history a lookup is about: the definition id its identity links
40/// are keyed by, and the working directory its transcripts record.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct HistoryOwner {
43    pub definition_id: String,
44    pub working_directory: Option<String>,
45}
46
47impl HistoryOwner {
48    /// Resolve a MuxAPI slug (the pre-M4c-2 path, and the one an
49    /// Unattributed caller keeps).
50    pub fn from_slug(store: &crate::backend::storage::store::Store, agent_id: &str) -> Self {
51        // `agent_id` arrives as the SLUG (`AGENTMUX_AGENT_ID`) from every App
52        // API caller, but `db_agent_identity_links.agent_id` stores the
53        // DEFINITION id — so querying that table with the slug matched zero
54        // rows every time, and the early return on "no links" then reported a
55        // confident, empty history for agents whose transcripts were sitting
56        // on disk. A caller that already holds a definition id passes through
57        // unchanged. Same resolution `app_api::resolve_agent_definition_id`
58        // already documents ("listing links by slug always returns empty").
59        let instance = store.instance_get_by_slug(agent_id).ok().flatten();
60        let definition_from_db = instance.as_ref().map(|i| {
61            if i.definition_id.is_empty() { i.id.clone() } else { i.definition_id.clone() }
62        });
63        let working_dir_from_db = instance
64            .as_ref()
65            .map(|i| i.working_directory.clone())
66            .filter(|w| !w.is_empty());
67
68        // One registry read, shared by both fallbacks below, and skipped
69        // entirely when the `db_agents` row already answered both questions.
70        let record = if definition_from_db.is_none() || working_dir_from_db.is_none() {
71            registry_record(agent_id)
72        } else {
73            None
74        };
75
76        // Without the registry step, a registry-only agent (no `db_agents`
77        // row — the common case) fell through to the raw slug here, and the
78        // link table is keyed by definition id, so the link query matched
79        // nothing and the agent's identity-bound sessions silently vanished.
80        // Same third fallback `app_api::resolve_agent_definition_id` already
81        // has, for the same reason. The raw slug remains the last resort: a
82        // caller that already holds a definition id passes through unchanged.
83        let definition_id = definition_from_db
84            .or_else(|| {
85                record
86                    .as_ref()
87                    .map(|r| r.data.definition_id.clone())
88                    .filter(|d| !d.is_empty())
89            })
90            .unwrap_or_else(|| agent_id.to_string());
91
92        // The ambient-credentials fallback below (`sessions_for_owner`) needs
93        // the working directory: the row's, else the registry record's.
94        let working_directory = working_dir_from_db.or_else(|| {
95            record
96                .as_ref()
97                .and_then(crate::backend::agent_registry_lookup::working_dir_from_record)
98        });
99        Self { definition_id, working_directory }
100    }
101
102    /// An agent's own row — identity M4c-2c, an attributed caller. Its
103    /// working directory is the row's, else its registry record's found by
104    /// the row's slug **and** id, never by slug alone.
105    pub fn of_row(row: &crate::backend::storage::AgentDefinition) -> Self {
106        let working_directory = Some(row.working_directory.clone())
107            .filter(|w| !w.is_empty())
108            .or_else(|| {
109                crate::backend::agent_registry_lookup::find_active_record_by_slug_and_definition(
110                    &row.slug, &row.id,
111                )
112                .as_ref()
113                .and_then(crate::backend::agent_registry_lookup::working_dir_from_record)
114            });
115        Self { definition_id: row.id.clone(), working_directory }
116    }
117}
118
119/// Account ids linked to more than one agent (`db_agent_identity_links`).
120fn accounts_linked_to_several_agents(
121    store: &crate::backend::storage::store::Store,
122) -> Result<std::collections::HashSet<String>, String> {
123    let mut agents_by_account: std::collections::HashMap<String, std::collections::HashSet<String>> =
124        std::collections::HashMap::new();
125    for link in store
126        .agent_identity_list_all()
127        .map_err(|e| format!("failed to read identity links: {e}"))?
128    {
129        agents_by_account.entry(link.account_id).or_default().insert(link.agent_id);
130    }
131    Ok(agents_by_account
132        .into_iter()
133        .filter(|(_, agents)| agents.len() > 1)
134        .map(|(account, _)| account)
135        .collect())
136}
137
138/// A search's answer while the first index build after srv start is running.
139pub const HISTORY_INDEX_BUILDING: &str = "history index is still being built after AgentMux started \
140     (it reads every transcript once) — this is not an empty history; retry in a minute";
141
142/// Why a history search could not answer.
143#[derive(Debug)]
144pub enum HistorySearchError {
145    /// The first index build after srv start is still running. Retryable,
146    /// and never to be read as "no history".
147    IndexBuilding,
148    /// Anything else, e.g. the store failing to list the owner's accounts.
149    Failed(String),
150}
151
152impl std::fmt::Display for HistorySearchError {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        match self {
155            HistorySearchError::IndexBuilding => f.write_str(HISTORY_INDEX_BUILDING),
156            HistorySearchError::Failed(e) => f.write_str(e),
157        }
158    }
159}
160
161/// What a search knows about a session only AgentMux's record holds.
162fn record_meta(session: &record::RecordSession) -> SessionMeta {
163    SessionMeta {
164        session_id: session.session_id.clone(),
165        file_path: session
166            .ranges
167            .first()
168            .map(|(zone, _, _)| format!("agentmux-record:{zone}"))
169            .unwrap_or_default(),
170        provider: "claude".to_string(),
171        model: String::new(),
172        slug: String::new(),
173        working_directory: session.cwd.clone().unwrap_or_default(),
174        created_at: session.first_ms,
175        modified_at: session.last_ms,
176        message_count: 0,
177        first_user_message: String::new(),
178        file_size_bytes: session.ranges.iter().map(|(_, start, end)| (end - start).max(0) as u64).sum(),
179        git_branch: String::new(),
180        total_tokens: 0,
181        subagent_count: 0,
182        identity_id: String::new(),
183        starts_undated: session.first_ms == 0,
184    }
185}
186
187/// SearchHistory's `since`/`until` in milliseconds. They're documented as
188/// Unix seconds, but a hit's own `timestamp` is in milliseconds and is the
189/// natural value to pass back; a value this large is already milliseconds
190/// (as seconds it would be the year 5138).
191pub fn unix_time_to_ms(value: i64) -> i64 {
192    const ALREADY_MS: i64 = 100_000_000_000;
193    if value.abs() >= ALREADY_MS {
194        value
195    } else {
196        value.saturating_mul(1000)
197    }
198}
199
200/// How long after srv start the first index build waits
201/// ([`HistoryService::warm_in_background`]): past the window in which the user
202/// opens their first agents. The spec protects the first 30 s
203/// (SPEC_AGENT_OPEN_LATENCY_2026_09_27.md §5), and a cold build can take 25 s
204/// on its own, so a start inside that window would still overlap it (Codex P2
205/// on #3930). A search before then starts the build early
206/// ([`HistoryService::refresh_for_search`]).
207pub const WARM_DELAY: std::time::Duration = std::time::Duration::from_secs(60);
208
209/// Lower the calling thread's scheduling priority for background work. On
210/// Windows, `THREAD_MODE_BACKGROUND_BEGIN` also lowers its I/O and memory
211/// priority — the index build is mostly file reads. On Linux, a nice of 10
212/// for this thread only. Best-effort: a failure leaves normal priority.
213fn lower_current_thread_priority() {
214    #[cfg(windows)]
215    unsafe {
216        use windows_sys::Win32::System::Threading::{
217            GetCurrentThread, SetThreadPriority, THREAD_MODE_BACKGROUND_BEGIN,
218        };
219        let _ = SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);
220    }
221    #[cfg(target_os = "linux")]
222    unsafe {
223        let tid = libc::syscall(libc::SYS_gettid) as libc::id_t;
224        let _ = libc::setpriority(libc::PRIO_PROCESS, tid, 10);
225    }
226}
227
228/// Run the index's first build unless another caller has finished it or is
229/// running it now — never a second full pass right after theirs (Codex P2s on
230/// #3930) — then clear `pending`.
231fn build_first_index(
232    index: &SessionIndex,
233    pending: &std::sync::atomic::AtomicBool,
234    trigger: &'static str,
235) {
236    let started = std::time::Instant::now();
237    match index.try_first_build() {
238        index::FirstBuild::Built { discovered } => tracing::info!(
239            discovered,
240            duration_ms = started.elapsed().as_millis() as u64,
241            trigger,
242            "history: index built"
243        ),
244        index::FirstBuild::AlreadyBuilt => {
245            tracing::info!(trigger, "history: index already built; first build skipped")
246        }
247        index::FirstBuild::Busy => {
248            tracing::info!(
249                trigger,
250                "history: index build already running; first build skipped"
251            )
252        }
253    }
254    pending.store(false, std::sync::atomic::Ordering::SeqCst);
255}
256
257/// The history service exposed to the RPC layer.
258pub struct HistoryService {
259    index: Arc<SessionIndex>,
260    /// AgentMux's own record of each agent's conversations — which sessions
261    /// are whose, and the content of those whose transcript is gone.
262    records: record::AgentRecords,
263    /// A deferred first build is scheduled and hasn't finished yet.
264    warm_pending: Arc<std::sync::atomic::AtomicBool>,
265    /// A search already started the pending first build early.
266    warm_started_early: Arc<std::sync::atomic::AtomicBool>,
267}
268
269impl HistoryService {
270    pub fn new() -> Self {
271        let adapters: Vec<Box<dyn HistoryAdapter>> =
272            vec![Box::new(ClaudeHistoryAdapter::new())];
273
274        // Saved beside the shared agent registry, so every channel and build
275        // on the machine reuses one cache; entries are only trusted while the
276        // transcript's mtime is unchanged.
277        let mut index = SessionIndex::new(adapters);
278        if let Some(shared) = crate::registry::resolve_global_shared_root() {
279            index = index.with_cache_file(shared.join("history").join("session-meta-cache.json"));
280        }
281        HistoryService {
282            index: Arc::new(index),
283            records: record::AgentRecords::global(),
284            warm_pending: Arc::new(std::sync::atomic::AtomicBool::new(false)),
285            warm_started_early: Arc::new(std::sync::atomic::AtomicBool::new(false)),
286        }
287    }
288
289    /// Construct directly from a `SessionIndex` — used by tests that need
290    /// to inject a mock adapter instead of `ClaudeHistoryAdapter::new()`'s
291    /// real filesystem scan. `pub(crate)` (not private) so tests in other
292    /// modules (e.g. `app_api::bundle`'s `bundle.export_for_agent_with_history`
293    /// tests) can build an isolated `HistoryService` too, instead of
294    /// depending on `AppState::history_service`'s real filesystem scan.
295    #[cfg(any(test, feature = "test-support"))]
296    pub fn from_index(index: SessionIndex) -> Self {
297        Self::from_index_and_records(index, record::AgentRecords::new(None))
298    }
299
300    #[cfg(any(test, feature = "test-support"))]
301    pub(crate) fn from_index_and_records(index: SessionIndex, records: record::AgentRecords) -> Self {
302        HistoryService {
303            index: Arc::new(index),
304            records,
305            warm_pending: Arc::new(std::sync::atomic::AtomicBool::new(false)),
306            warm_started_early: Arc::new(std::sync::atomic::AtomicBool::new(false)),
307        }
308    }
309
310    /// Build the index off-thread at srv start, so the first search doesn't
311    /// pay for parsing every transcript on the machine inside the MCP's 10 s
312    /// timeout (SPEC_DURABLE_CONVERSATION_MEMORY_2026_09_23.md §4.5).
313    ///
314    /// Deferred by [`WARM_DELAY`] and run at background priority: the first
315    /// build reads every transcript on the machine (61,066 sessions in 23.5 s
316    /// on one host) and used to start the moment srv did — exactly when the
317    /// user opens their first agents, competing with them for CPU and disk
318    /// (SPEC_AGENT_OPEN_LATENCY_2026_09_27.md F2). A search in the meantime
319    /// answers "index building", as it does during the build itself, and
320    /// starts the build now; the History tab's `list`/`get` still build on
321    /// demand.
322    pub fn warm_in_background(&self) -> std::thread::JoinHandle<()> {
323        self.warm_in_background_after(WARM_DELAY)
324    }
325
326    /// [`Self::warm_in_background`] with an explicit delay (tests use zero).
327    pub fn warm_in_background_after(
328        &self,
329        delay: std::time::Duration,
330    ) -> std::thread::JoinHandle<()> {
331        let index = self.index.clone();
332        let pending = self.warm_pending.clone();
333        pending.store(true, std::sync::atomic::Ordering::SeqCst);
334        std::thread::Builder::new()
335            .name("history-index-warm".into())
336            .spawn(move || {
337                lower_current_thread_priority();
338                if !delay.is_zero() {
339                    std::thread::sleep(delay);
340                }
341                build_first_index(&index, &pending, "startup");
342            })
343            .expect("spawn history-index-warm thread")
344    }
345
346    /// A search arrived while the deferred first build is still waiting out
347    /// [`WARM_DELAY`]: someone wants the index now, so build it now, off the
348    /// search's thread. Once.
349    fn start_pending_build_early(&self) {
350        if self
351            .warm_started_early
352            .swap(true, std::sync::atomic::Ordering::SeqCst)
353        {
354            return;
355        }
356        let index = self.index.clone();
357        let pending = self.warm_pending.clone();
358        let _ = std::thread::Builder::new()
359            .name("history-index-first".into())
360            .spawn(move || build_first_index(&index, &pending, "search"));
361    }
362
363    /// Build the index if it never has been. Blocking; for callers without a
364    /// tight deadline.
365    fn ensure_built(&self) {
366        if self.index.refreshed_at_ms() == 0 {
367            self.index.refresh();
368        }
369    }
370
371    /// Bring the index up to date before a search, so that "no hits, complete"
372    /// can mean nothing was there: every session on disk when the search began
373    /// is in the snapshot it reads. Reusing a recent snapshot (it used to be
374    /// reused for 30 s, or whenever another refresh was running) let a session
375    /// written in that window go unseen while the answer claimed to be
376    /// complete (Codex P1 on #3693).
377    ///
378    /// An incremental refresh re-lists the transcript directories and
379    /// re-parses only files whose mtime moved: 51,671 files stat'd in 2.7 s on
380    /// one heavy host (2026-09-24), far less on most. A refresh already
381    /// running is waited for and then followed by this search's own (unless
382    /// another search's refresh began after this one did), since it may have
383    /// started before this search's sessions were written. Only the
384    /// very first build answers "still building" instead of waiting: it reads
385    /// every transcript once and would outlast the MCP's 10 s timeout.
386    /// Concurrent searches share refreshes ([`SessionIndex::refresh_covering_now`]).
387    fn refresh_for_search(&self) -> Result<(), HistorySearchError> {
388        if self.index.refreshed_at_ms() == 0 {
389            // The deferred first build is scheduled but hasn't finished (or
390            // started): answer "building" rather than running that whole
391            // first scan inside this search — same as while it runs.
392            if self.warm_pending.load(std::sync::atomic::Ordering::SeqCst) {
393                self.start_pending_build_early();
394                return Err(HistorySearchError::IndexBuilding);
395            }
396            return match self.index.try_refresh() {
397                Some(_) => Ok(()),
398                None => Err(HistorySearchError::IndexBuilding),
399            };
400        }
401        self.index.refresh_covering_now();
402        Ok(())
403    }
404
405    /// List sessions with pagination and filters.
406    /// Lazy-initializes the index on first call.
407    pub fn list(
408        &self,
409        provider: Option<&str>,
410        project: Option<&str>,
411        offset: usize,
412        limit: usize,
413        sort_by: &str,
414        sort_dir: &str,
415    ) -> serde_json::Value {
416        // Lazy init: scan on first request
417        self.ensure_built();
418
419        let (sessions, total, has_more) =
420            self.index.list(provider, project, offset, limit, sort_by, sort_dir);
421
422        serde_json::json!({
423            "sessions": sessions,
424            "total": total,
425            "has_more": has_more,
426        })
427    }
428
429    /// Typed core of `list_for_agent` — the JSON-returning method wraps
430    /// this. Exists as its own function so other backend code (e.g.
431    /// `bundle.rs`'s `bundle.export_for_agent_with_history`) can get this
432    /// agent's `SessionMeta` list directly, without a JSON
433    /// serialize/deserialize round-trip through the RPC-facing shape.
434    ///
435    /// `force_refresh`: reagentx P1 on PR #2613 — the lazy
436    /// refresh-only-if-empty behavior (shared with `list`/`get`, fine for
437    /// an interactive browse where slight staleness is an acceptable
438    /// trade for speed) is wrong for a caller claiming completeness, like
439    /// `bundle.export_for_agent_with_history`: once the index has been
440    /// populated once (by ANY prior call, interactive or otherwise), a
441    /// session created since then would silently be missing from an
442    /// export that reports itself as the full record. `list_for_agent`
443    /// (the interactive RPC) passes `false`, preserving its existing
444    /// speed/freshness trade-off; the export path passes `true`.
445    pub fn sessions_for_agent(
446        &self,
447        store: &crate::backend::storage::store::Store,
448        agent_id: &str,
449        offset: usize,
450        limit: usize,
451        sort_by: &str,
452        sort_dir: &str,
453        force_refresh: bool,
454    ) -> Result<(Vec<SessionMeta>, u32, bool), String> {
455        let owner = HistoryOwner::from_slug(store, agent_id);
456        self.sessions_for_owner(store, &owner, offset, limit, sort_by, sort_dir, force_refresh)
457    }
458
459    /// [`Self::sessions_for_agent`] for an owner already resolved — identity
460    /// M4c-2c: an attributed caller's own row (`HistoryOwner::of_row`),
461    /// never a slug another agent may share.
462    pub fn sessions_for_owner(
463        &self,
464        store: &crate::backend::storage::store::Store,
465        owner: &HistoryOwner,
466        offset: usize,
467        limit: usize,
468        sort_by: &str,
469        sort_dir: &str,
470        force_refresh: bool,
471    ) -> Result<(Vec<SessionMeta>, u32, bool), String> {
472        if force_refresh {
473            self.index.refresh();
474        } else {
475            self.ensure_built();
476        }
477
478        let links = store
479            .agent_identity_list_for_agent(&owner.definition_id)
480            .map_err(|e| format!("failed to resolve agent's linked identities: {e}"))?;
481
482        // An account linked to several agents holds all of their transcripts
483        // under one account's home, so its sessions are not all this
484        // owner's: `SearchHistory` would return another agent's conversation,
485        // the ungoverned disclosure `search_for_agent`'s doc rules out. From
486        // such an account keep only sessions in the owner's own working
487        // directory; with no known directory, keep none (counted) rather than
488        // guess. An account only this owner uses keeps every session, so an
489        // agent whose working directory moved keeps its older history.
490        let shared_accounts = accounts_linked_to_several_agents(store)?;
491        let own_dir = owner
492            .working_directory
493            .as_deref()
494            .map(index::normalize_working_dir);
495        let mut merged: Vec<SessionMeta> = Vec::new();
496        for link in &links {
497            let (sessions, _total, _has_more) =
498                self.index.list_for_identity(&link.account_id, 0, usize::MAX, sort_by, sort_dir);
499            if !shared_accounts.contains(&link.account_id) {
500                merged.extend(sessions);
501                continue;
502            }
503            match &own_dir {
504                Some(dir) => merged.extend(
505                    sessions
506                        .into_iter()
507                        .filter(|s| &index::normalize_working_dir(&s.working_directory) == dir),
508                ),
509                None => crate::backend::agent_resolve::record_uid_fallback(
510                    "history.shared_account_without_working_dir",
511                ),
512            }
513        }
514
515        // An agent with no bound account has no link row at all — its
516        // registry record's `identity_id` reads "default" while its
517        // transcripts are written under a channel's default home nothing
518        // points at — so the identity lookup above finds nothing for the
519        // common case. The working directory is recorded inside the
520        // transcript (`cwd`) and on the agent's own row, so it resolves the
521        // sessions the account lookup cannot.
522        if let Some(dir) = &owner.working_directory {
523            merged.extend(self.index.list_for_working_directory(dir));
524        }
525
526        // The two sources legitimately overlap for an agent that is both
527        // identity-bound and running in its own directory.
528        let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
529        merged.retain(|s| seen.insert(s.session_id.clone()));
530
531        let mut refs: Vec<&SessionMeta> = merged.iter().collect();
532        index::SessionIndex::sort_sessions(&mut refs, sort_by, sort_dir);
533
534        let total = refs.len() as u32;
535        let has_more = offset + limit < refs.len();
536        let page: Vec<SessionMeta> = refs.into_iter().skip(offset).take(limit).cloned().collect();
537        Ok((page, total, has_more))
538    }
539
540    /// Search this agent's OWN conversation history.
541    ///
542    /// `SPEC_AGENT_HISTORY_SEARCH_2026_09_17.md`. Closes the gap where an
543    /// agent's memory of what it did is bounded by its current context window
544    /// while its actual actions are not — so a compaction or session reset
545    /// leaves it confidently misreporting its own past, with nothing marking
546    /// the boundary. Questions like "did I already send that message" are
547    /// answerable from disk; before this they were not answerable by the agent
548    /// being asked.
549    ///
550    /// **Own history only.** Searching another agent's transcript is already a
551    /// governed act — `conversation_visibility` plus the `transcript_request`
552    /// tier rules decide whether one agent may read another's content. A
553    /// search verb that read other agents' sessions directly would be a
554    /// second, ungoverned disclosure path around that machinery, and a more
555    /// dangerous one for looking like an ordinary read tool. Cross-agent
556    /// search must route *through* `transcript_request`, as its own phase.
557    ///
558    /// `opts.since_ms`/`until_ms` drop whole sessions on indexed metadata
559    /// **before** any file is opened, so a narrow time window costs nothing on
560    /// irrelevant sessions, and then filter the messages of the sessions that
561    /// remain. `opts.max_sessions` bounds how many of those are parsed, newest
562    /// first; the rest are counted, not dropped.
563    pub fn search_for_agent(
564        &self,
565        store: &crate::backend::storage::store::Store,
566        owner: &HistoryOwner,
567        opts: &index::HistorySearchOptions,
568    ) -> Result<index::HistorySearchOutcome, HistorySearchError> {
569        self.refresh_for_search()?;
570
571        // Whose sessions these are comes from AgentMux's own record, keyed by
572        // the agent's UID (`owner.definition_id` is the caller's row id): the
573        // same in every channel and version and across account switches. A
574        // session there is searched in its provider transcript when that
575        // still exists, and in the record when it doesn't.
576        let (ledger, record_problems) = self.records.sessions_of(&owner.definition_id);
577        let in_ledger: std::collections::HashSet<String> =
578            ledger.iter().map(|s| s.session_id.clone()).collect();
579        let mut candidates: Vec<index::SearchCandidate> = Vec::with_capacity(ledger.len());
580        let mut record_only = 0u32;
581        for session in ledger {
582            let candidate = match self.index.get_meta(&session.session_id) {
583                Some(meta) => index::SearchCandidate {
584                    meta,
585                    source: index::Source::Transcript,
586                    attribution: index::Attribution::AgentRecord,
587                },
588                None => {
589                    record_only += 1;
590                    index::SearchCandidate {
591                        meta: record_meta(&session),
592                        source: index::Source::Record(session),
593                        attribution: index::Attribution::AgentRecord,
594                    }
595                }
596            };
597            candidates.push(candidate);
598        }
599
600        // Sessions found only by working directory or account. When the agent
601        // has a record they're left out (counted): none of them is in it, so
602        // they're another agent's in a shared folder or account, or older
603        // than the record (none on the host measured, 2026-09-24). An agent
604        // with no record at all has nothing better, so it keeps them.
605        let (by_folder, _total, _has_more) = self
606            .sessions_for_owner(store, owner, 0, usize::MAX, "modified_at", "desc", false)
607            .map_err(HistorySearchError::Failed)?;
608        let inferred: Vec<SessionMeta> =
609            by_folder.into_iter().filter(|s| !in_ledger.contains(&s.session_id)).collect();
610        let mut inferred_excluded = 0u32;
611        if in_ledger.is_empty() || opts.include_inferred {
612            candidates.extend(inferred.into_iter().map(|meta| index::SearchCandidate {
613                meta,
614                source: index::Source::Transcript,
615                attribution: index::Attribution::Inferred,
616            }));
617        } else {
618            inferred_excluded = inferred.len() as u32;
619        }
620
621        // A session last written before `since` holds nothing after it, and
622        // one started after `until` holds nothing before it. An unknown time
623        // — no timestamp at all, or an undated record before the first dated
624        // one — can't rule a session out.
625        let mut in_window: Vec<index::SearchCandidate> = candidates
626            .into_iter()
627            .filter(|c| opts.since_ms.is_none_or(|since| c.meta.modified_at == 0 || c.meta.modified_at >= since))
628            .filter(|c| {
629                opts.until_ms.is_none_or(|until| {
630                    c.meta.created_at == 0 || c.meta.starts_undated || c.meta.created_at <= until
631                })
632            })
633            .collect();
634        in_window.sort_by(|a, b| b.meta.modified_at.cmp(&a.meta.modified_at));
635
636        let mut outcome = index::search_candidates(&in_window, opts, &|c| self.load(c));
637        outcome.ledger_sessions = in_ledger.len() as u32;
638        outcome.record_only_sessions = record_only;
639        outcome.inferred_sessions_excluded = inferred_excluded;
640        let mut problems = self.index.discovery_problems();
641        problems.extend(record_problems);
642        outcome.add_discovery_errors(problems);
643        Ok(outcome)
644    }
645
646    /// A candidate's conversation, from wherever it lives.
647    fn load(&self, candidate: &index::SearchCandidate) -> Result<Option<HistorySession>, HistoryError> {
648        match &candidate.source {
649            index::Source::Transcript => self.index.get_full(&candidate.meta.session_id),
650            index::Source::Record(session) if session.ranges.is_empty() => Err(HistoryError::Other(
651                "in the agent's segment log, but neither a provider transcript nor AgentMux's record holds it"
652                    .into(),
653            )),
654            index::Source::Record(session) => {
655                let (messages, skipped_records) = self.records.read(session)?;
656                Ok(Some(HistorySession { meta: candidate.meta.clone(), messages, skipped_records }))
657            }
658        }
659    }
660
661    /// This agent's own sessions — the actual "fast Conversation History
662    /// lookup" protocol §4.4 asks for, resolving `agent_id` to its bound
663    /// account(s) (`Store::agent_identity_list_for_agent`, the
664    /// same `db_agent_identity_links` table `identity/auth_dirs.rs`
665    /// already keys off) and querying `SessionIndex::list_for_identity`'s
666    /// O(sessions for this identity) HashMap-backed path instead of
667    /// `list()`'s O(total sessions on disk) scan. An agent normally has
668    /// at most one linked account per provider, but this merges across
669    /// however many exist rather than assuming exactly one.
670    pub fn list_for_agent(
671        &self,
672        store: &crate::backend::storage::store::Store,
673        agent_id: &str,
674        offset: usize,
675        limit: usize,
676        sort_by: &str,
677        sort_dir: &str,
678    ) -> serde_json::Value {
679        let (page, total, has_more) = match self.sessions_for_agent(store, agent_id, offset, limit, sort_by, sort_dir, false) {
680            Ok(r) => r,
681            Err(e) => return serde_json::json!({ "error": e }),
682        };
683
684        serde_json::json!({
685            "sessions": page,
686            "total": total,
687            "has_more": has_more,
688        })
689    }
690
691    /// Get full conversation for a session.
692    pub fn get(&self, session_id: &str) -> serde_json::Value {
693        // Lazy init
694        self.ensure_built();
695
696        match self.index.get_full(session_id) {
697            Ok(Some(session)) => serde_json::json!({ "session": session }),
698            Ok(None) => serde_json::json!({ "error": "session not found" }),
699            Err(e) => serde_json::json!({ "error": format!("{}", e) }),
700        }
701    }
702
703    /// Re-scan disk and update the index.
704    pub fn refresh(&self) -> serde_json::Value {
705        let (discovered, updated, new_count) = self.index.refresh();
706        serde_json::json!({
707            "discovered": discovered,
708            "updated": updated,
709            "new": new_count,
710        })
711    }
712
713    /// Delete a single session's on-disk transcript and drop it from the index.
714    pub fn delete(&self, session_id: &str) -> serde_json::Value {
715        self.ensure_built();
716        match self.index.delete(session_id) {
717            Ok(true) => serde_json::json!({ "deleted": true }),
718            Ok(false) => serde_json::json!({ "deleted": false, "error": "session not found" }),
719            Err(e) => serde_json::json!({ "deleted": false, "error": format!("{}", e) }),
720        }
721    }
722
723    /// Bulk-clear sessions matching the optional provider/project filter.
724    pub fn clear(&self, provider: Option<&str>, project: Option<&str>) -> serde_json::Value {
725        self.ensure_built();
726        let deleted = self.index.clear(provider, project);
727        serde_json::json!({ "deleted": deleted })
728    }
729}
730
731/// Whose sessions a search reads, from AgentMux's own record (PR 2 of the
732/// history-robustness plan).
733#[cfg(test)]
734mod agent_record_search_tests {
735    use super::record::fixtures::{append, assistant, init, store, zone, UID};
736    use super::*;
737
738    const CWD: &str = "/work/agent-a";
739
740    /// A service over a real Claude adapter rooted at `shared`, and the
741    /// agent's record in `records`.
742    fn service(shared: &std::path::Path, records: &Arc<crate::backend::storage::filestore::FileStore>) -> HistoryService {
743        HistoryService::from_index_and_records(
744            SessionIndex::with_isolated_roots(
745                vec![Box::new(ClaudeHistoryAdapter::with_roots(None, Some(shared.to_path_buf()), None))],
746                vec![],
747            ),
748            record::AgentRecords::new(Some(records.clone())),
749        )
750    }
751
752    fn transcript(shared: &std::path::Path, sid: &str, text: &str) {
753        let project = shared.join("providers").join("claude").join("projects").join("-work-agent-a");
754        std::fs::create_dir_all(&project).unwrap();
755        let line = format!(
756            r#"{{"type":"assistant","message":{{"role":"assistant","model":"m","content":[{{"type":"text","text":"{text}"}}]}},"timestamp":"2026-09-24T10:00:00Z","cwd":"{CWD}"}}"#
757        );
758        std::fs::write(project.join(format!("{sid}.jsonl")), format!("{line}\n")).unwrap();
759    }
760
761    fn search(svc: &HistoryService, query: &str, include_inferred: bool) -> index::HistorySearchOutcome {
762        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
763        let owner = HistoryOwner { definition_id: UID.into(), working_directory: Some(CWD.into()) };
764        let opts = index::HistorySearchOptions { query: query.into(), limit: 50, include_inferred, ..Default::default() };
765        svc.search_for_agent(&store, &owner, &opts).unwrap()
766    }
767
768    /// 39% of the sessions on the host measured have no provider transcript
769    /// left (Claude's cleanup, a deleted account folder). They're still in
770    /// AgentMux's record, and found there.
771    #[test]
772    fn a_session_whose_transcript_is_gone_is_found_in_the_agents_record() {
773        let tmp = tempfile::TempDir::new().unwrap();
774        let records = store();
775        append(&records, &zone(), &[init("s-gone", CWD), assistant("s-gone", "only the record remembers this")]);
776        let out = search(&service(tmp.path(), &records), "record remembers", false);
777        assert_eq!(out.hits.len(), 1, "{out:?}");
778        assert_eq!(out.hits[0].source, "agentmux_record");
779        assert_eq!(out.hits[0].attribution, "agent_record");
780        assert_eq!(out.hits[0].session_id, "s-gone");
781        assert_eq!((out.ledger_sessions, out.record_only_sessions), (1, 1));
782        assert!(out.complete, "{out:?}");
783    }
784
785    /// A session whose transcript still exists is read from the transcript,
786    /// once — not again from the record.
787    #[test]
788    fn a_session_with_a_transcript_is_searched_there_once() {
789        let tmp = tempfile::TempDir::new().unwrap();
790        let records = store();
791        append(&records, &zone(), &[init("s1", CWD), assistant("s1", "words in both places")]);
792        transcript(tmp.path(), "s1", "words in both places");
793        let out = search(&service(tmp.path(), &records), "both places", false);
794        assert_eq!(out.hits.len(), 1, "{out:?}");
795        assert_eq!(out.hits[0].source, "provider_transcript");
796        assert_eq!((out.ledger_sessions, out.record_only_sessions), (1, 0));
797    }
798
799    /// Found by folder but not in the agent's record: another agent's session
800    /// in a shared folder, or one older than the record. Left out and counted
801    /// — `include_inferred` searches it, labelled.
802    #[test]
803    fn a_session_found_only_by_folder_is_left_out_when_the_agent_has_a_record() {
804        let tmp = tempfile::TempDir::new().unwrap();
805        let records = store();
806        append(&records, &zone(), &[init("s1", CWD), assistant("s1", "mine")]);
807        transcript(tmp.path(), "s-other", "someone else wrote this");
808        let svc = service(tmp.path(), &records);
809
810        let out = search(&svc, "someone else", false);
811        assert!(out.hits.is_empty(), "{out:?}");
812        assert_eq!(out.inferred_sessions_excluded, 1);
813
814        let out = search(&svc, "someone else", true);
815        assert_eq!(out.hits.len(), 1, "{out:?}");
816        assert_eq!(out.hits[0].attribution, "inferred");
817    }
818
819    /// An agent with no record at all (never ran on a build that keeps one)
820    /// has nothing better than its folder, so it keeps that.
821    #[test]
822    fn an_agent_without_a_record_keeps_the_folder_match() {
823        let tmp = tempfile::TempDir::new().unwrap();
824        transcript(tmp.path(), "s-folder", "found by folder");
825        let out = search(&service(tmp.path(), &store()), "by folder", false);
826        assert_eq!(out.hits.len(), 1, "{out:?}");
827        assert_eq!(out.hits[0].attribution, "inferred");
828        assert_eq!(out.ledger_sessions, 0);
829    }
830
831    /// A session the segment log names but nothing holds any more can't be
832    /// searched, and the answer says so.
833    #[test]
834    fn a_logged_session_with_no_content_anywhere_makes_the_answer_incomplete() {
835        let tmp = tempfile::TempDir::new().unwrap();
836        let records = store();
837        crate::backend::continuity_segments::record_start(
838            &records,
839            crate::backend::continuity_segments::Start {
840                segment_id: String::new(),
841                agent_uid: UID.into(),
842                definition_id: Some(UID.into()),
843                provider: "claude".into(),
844                config_dir: None,
845                provider_session_id: Some("s-lost".into()),
846                cwd: CWD.into(),
847                channel: "test".into(),
848                agentmux_version: "0.0.0".into(),
849                block_id: "b".into(),
850                zone: None,
851                byte_start: None,
852                started_at_ms: 1_000,
853                continuity_rung: crate::backend::continuity_segments::Rung::Fresh,
854                predecessor_segment_id: None,
855                lease_epoch: None,
856                identity_key: None,
857                forked_from: None,
858            },
859        )
860        .unwrap();
861        let out = search(&service(tmp.path(), &records), "anything", false);
862        assert!(!out.complete, "{out:?}");
863        assert_eq!(out.incomplete_reasons, vec!["unreadable_sessions"]);
864        assert_eq!(out.sessions_unreadable[0].session_id, "s-lost");
865    }
866}
867
868#[cfg(test)]
869mod search_freshness_tests {
870    use super::*;
871
872    fn empty_service() -> HistoryService {
873        HistoryService::from_index(SessionIndex::with_isolated_roots(vec![], vec![]))
874    }
875
876    /// The MCP gives a search 10 s; a cold build over every transcript on
877    /// the machine takes far longer. While it runs, a search must answer at
878    /// once — and say the index is building, never "no history".
879    #[test]
880    fn a_search_during_the_first_build_says_so_instead_of_waiting() {
881        let svc = empty_service();
882        let _building = svc.index.refresh_lock.lock().unwrap();
883        let err = svc.refresh_for_search().unwrap_err();
884        assert!(matches!(err, HistorySearchError::IndexBuilding), "{err}");
885        assert!(err.to_string().contains("still being built"), "{err}");
886    }
887
888    #[test]
889    fn since_and_until_accept_seconds_or_milliseconds() {
890        // Documented as seconds …
891        assert_eq!(unix_time_to_ms(1_790_280_000), 1_790_280_000_000);
892        // … but a hit's own timestamp is milliseconds, and passing it back
893        // must not be multiplied into the year 58,000.
894        assert_eq!(unix_time_to_ms(1_790_280_000_123), 1_790_280_000_123);
895        assert_eq!(unix_time_to_ms(0), 0);
896    }
897
898    #[test]
899    fn a_search_on_a_never_built_idle_index_builds_it() {
900        let svc = empty_service();
901        assert!(svc.refresh_for_search().is_ok());
902        assert!(svc.index.refreshed_at_ms() > 0);
903    }
904
905    fn real_service(shared: &std::path::Path) -> HistoryService {
906        HistoryService::from_index(SessionIndex::with_isolated_roots(
907            vec![Box::new(ClaudeHistoryAdapter::with_roots(None, Some(shared.to_path_buf()), None))],
908            vec![],
909        ))
910    }
911
912    fn owner_in(dir: &str) -> HistoryOwner {
913        HistoryOwner { definition_id: "agent-a".into(), working_directory: Some(dir.into()) }
914    }
915
916    /// A transcript whose first message carries no timestamp: its session
917    /// start (the first dated record) is after `until`, but the undated
918    /// message may not be, and the message-level window keeps undated
919    /// messages. Dropping the whole session on its start made the two
920    /// disagree and could answer "complete, no hits" (Codex P2 on #3693).
921    #[test]
922    fn a_session_starting_with_an_undated_message_stays_in_the_until_window() {
923        let tmp = tempfile::TempDir::new().unwrap();
924        let shared = tmp.path().join("shared");
925        let project = shared.join("providers").join("claude").join("projects").join("-work-a");
926        std::fs::create_dir_all(&project).unwrap();
927        let undated = r#"{"type":"user","message":{"role":"user","content":"undated question"},"cwd":"/work/a"}"#;
928        let dated = r#"{"type":"assistant","message":{"role":"assistant","model":"m","content":[{"type":"text","text":"answered"}]},"timestamp":"2026-09-24T12:00:00Z","cwd":"/work/a"}"#;
929        std::fs::write(project.join("s.jsonl"), format!("{undated}\n{dated}\n")).unwrap();
930        let svc = real_service(&shared);
931        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
932        let until = chrono::DateTime::parse_from_rfc3339("2026-09-24T11:00:00Z").unwrap().timestamp_millis();
933        let opts = index::HistorySearchOptions {
934            query: "undated question".into(),
935            limit: 50,
936            until_ms: Some(until),
937            ..Default::default()
938        };
939        let out = svc.search_for_agent(&store, &owner_in("/work/a"), &opts).unwrap();
940        assert_eq!(out.hits.len(), 1, "{out:?}");
941    }
942
943    /// Discovery that couldn't read somewhere may have missed the session
944    /// being searched for, so the answer isn't complete (Codex P1 on #3693).
945    #[test]
946    fn a_search_over_a_snapshot_with_discovery_problems_is_not_complete() {
947        struct Unreadable;
948        impl HistoryAdapter for Unreadable {
949            fn provider(&self) -> &str {
950                "mock"
951            }
952            fn discover_files(&self) -> Result<Vec<DiscoveredFile>, HistoryError> {
953                Ok(Vec::new())
954            }
955            fn discover(&self) -> Result<Discovery, HistoryError> {
956                Ok(Discovery { files: Vec::new(), problems: vec!["/x/projects: Access is denied".into()] })
957            }
958            fn extract_meta(&self, _: &str) -> Result<Option<SessionMeta>, HistoryError> {
959                Ok(None)
960            }
961            fn parse_file(&self, _: &str) -> Result<Option<HistorySession>, HistoryError> {
962                Ok(None)
963            }
964        }
965        let svc = HistoryService::from_index(SessionIndex::with_isolated_roots(vec![Box::new(Unreadable)], vec![]));
966        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
967        let opts = index::HistorySearchOptions { query: "anything".into(), limit: 50, ..Default::default() };
968        let out = svc.search_for_agent(&store, &owner_in("/work/a"), &opts).unwrap();
969        assert!(out.hits.is_empty());
970        assert!(!out.complete, "{out:?}");
971        assert_eq!(out.incomplete_reasons, vec!["discovery_errors"]);
972        assert!(out.discovery_errors.iter().any(|p| p.contains("Access is denied")), "{out:?}");
973    }
974
975    /// A session written moments after one search is found by the next. A
976    /// snapshot reused because it was "fresh enough" (under 30 s old, or
977    /// another refresh running) answered `complete: true` without it — the
978    /// false negative this whole tool exists to prevent (Codex P1 on #3693).
979    #[test]
980    fn a_session_written_right_after_a_search_is_found_by_the_next_search() {
981        let tmp = tempfile::TempDir::new().unwrap();
982        let shared = tmp.path().join("shared");
983        let project = shared.join("providers").join("claude").join("projects").join("-work-a");
984        std::fs::create_dir_all(&project).unwrap();
985        let svc = HistoryService::from_index(SessionIndex::with_isolated_roots(
986            vec![Box::new(ClaudeHistoryAdapter::with_roots(None, Some(shared.clone()), None))],
987            vec![],
988        ));
989        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
990        let owner = HistoryOwner { definition_id: "agent-a".into(), working_directory: Some("/work/a".into()) };
991        let opts = index::HistorySearchOptions { query: "deploy".into(), limit: 50, ..Default::default() };
992
993        let first = svc.search_for_agent(&store, &owner, &opts).unwrap();
994        assert!(first.hits.is_empty() && first.complete, "{first:?}");
995
996        let line = r#"{"type":"user","message":{"role":"user","content":"deploy now"},"timestamp":"2026-09-24T10:00:00Z","cwd":"/work/a"}"#;
997        std::fs::write(project.join("written-after.jsonl"), format!("{line}\n")).unwrap();
998        let second = svc.search_for_agent(&store, &owner, &opts).unwrap();
999        assert_eq!(second.hits.len(), 1, "{second:?}");
1000        assert!(second.complete, "{second:?}");
1001    }
1002
1003    #[test]
1004    fn warm_in_background_builds_the_index() {
1005        let svc = empty_service();
1006        svc.warm_in_background_after(std::time::Duration::ZERO)
1007            .join()
1008            .unwrap();
1009        assert!(svc.index.refreshed_at_ms() > 0);
1010        assert!(!svc.warm_pending.load(std::sync::atomic::Ordering::SeqCst));
1011    }
1012
1013    /// SPEC_AGENT_OPEN_LATENCY_2026_09_27.md F2: the first build is deferred.
1014    /// A search in that window must not run the whole first scan itself (it
1015    /// would outlast the MCP's 10 s) — it answers "building", like during the
1016    /// build — but it starts the build in the background instead of leaving
1017    /// the index unbuilt until the delay ends.
1018    #[test]
1019    fn a_search_while_the_deferred_build_is_pending_starts_it_in_the_background() {
1020        let svc = empty_service();
1021        let _warm = svc.warm_in_background_after(std::time::Duration::from_secs(3600));
1022        let err = svc.refresh_for_search().unwrap_err();
1023        assert!(matches!(err, HistorySearchError::IndexBuilding), "{err}");
1024        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
1025        while svc.index.refreshed_at_ms() == 0 {
1026            assert!(
1027                std::time::Instant::now() < deadline,
1028                "the early build never ran"
1029            );
1030            std::thread::sleep(std::time::Duration::from_millis(10));
1031        }
1032        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
1033        while svc.warm_pending.load(std::sync::atomic::Ordering::SeqCst) {
1034            assert!(
1035                std::time::Instant::now() < deadline,
1036                "pending never cleared"
1037            );
1038            std::thread::sleep(std::time::Duration::from_millis(10));
1039        }
1040        assert!(svc.refresh_for_search().is_ok());
1041    }
1042
1043    /// Codex P2 on #3930: an on-demand build during the delay makes the
1044    /// deferred warm-up a no-op instead of a second full discovery pass.
1045    #[test]
1046    fn an_on_demand_build_during_the_delay_skips_the_deferred_build() {
1047        let svc = empty_service();
1048        let warm = svc.warm_in_background_after(std::time::Duration::from_millis(300));
1049        svc.index.refresh(); // e.g. the History tab's list() during startup
1050        let built_at = svc.index.refreshed_at_ms();
1051        assert!(built_at > 0);
1052        warm.join().unwrap();
1053        assert_eq!(
1054            svc.index.refreshed_at_ms(),
1055            built_at,
1056            "the deferred build must not refresh again"
1057        );
1058        assert!(!svc.warm_pending.load(std::sync::atomic::Ordering::SeqCst));
1059    }
1060
1061    /// The spec's protected window is the first 30 s; a cold build can take
1062    /// ~25 s, so it must not start inside it.
1063    #[test]
1064    fn the_first_build_waits_out_the_startup_window() {
1065        assert!(
1066            WARM_DELAY >= std::time::Duration::from_secs(30),
1067            "{WARM_DELAY:?}"
1068        );
1069    }
1070}
1071
1072#[cfg(test)]
1073mod tests {
1074    use super::*;
1075    use crate::backend::storage::store::Store;
1076
1077    /// Adapter that "discovers" caller-supplied files, tagging each with a
1078    /// fixed identity_id -- just enough to exercise the agent_id ->
1079    /// identity_id -> sessions chain end to end.
1080    struct MockAdapter {
1081        files: Vec<DiscoveredFile>,
1082        identity_id: String,
1083        /// Defaults to "/proj" via [`MockAdapter::new`]; set explicitly by the
1084        /// working-directory resolution tests.
1085        working_directory: String,
1086    }
1087
1088    impl MockAdapter {
1089        fn new(files: Vec<DiscoveredFile>, identity_id: &str) -> Self {
1090            MockAdapter {
1091                files,
1092                identity_id: identity_id.to_string(),
1093                working_directory: "/proj".to_string(),
1094            }
1095        }
1096        fn in_dir(files: Vec<DiscoveredFile>, identity_id: &str, working_directory: &str) -> Self {
1097            MockAdapter {
1098                files,
1099                identity_id: identity_id.to_string(),
1100                working_directory: working_directory.to_string(),
1101            }
1102        }
1103    }
1104    impl HistoryAdapter for MockAdapter {
1105        fn provider(&self) -> &str {
1106            "mock"
1107        }
1108        fn discover_files(&self) -> Result<Vec<DiscoveredFile>, HistoryError> {
1109            Ok(self.files.iter().map(|f| DiscoveredFile { file_path: f.file_path.clone(), mtime_ms: f.mtime_ms }).collect())
1110        }
1111        fn extract_meta(&self, file_path: &str) -> Result<Option<SessionMeta>, HistoryError> {
1112            let id = std::path::Path::new(file_path)
1113                .file_stem()
1114                .map(|s| s.to_string_lossy().into_owned())
1115                .unwrap_or_default();
1116            Ok(Some(SessionMeta {
1117                session_id: id,
1118                file_path: file_path.to_string(),
1119                provider: "mock".to_string(),
1120                model: String::new(),
1121                slug: String::new(),
1122                working_directory: self.working_directory.clone(),
1123                created_at: 0,
1124                modified_at: 0,
1125                message_count: 0,
1126                first_user_message: String::new(),
1127                file_size_bytes: 0,
1128                git_branch: String::new(),
1129                total_tokens: 0,
1130                subagent_count: 0,
1131                identity_id: self.identity_id.clone(),
1132                starts_undated: false,
1133            }))
1134        }
1135        fn parse_file(&self, _: &str) -> Result<Option<HistorySession>, HistoryError> {
1136            Ok(None)
1137        }
1138    }
1139
1140    fn write_session(dir: &std::path::Path, id: &str) -> String {
1141        let f = dir.join(format!("{id}.jsonl"));
1142        std::fs::write(&f, b"{}").unwrap();
1143        f.to_string_lossy().into_owned()
1144    }
1145
1146    // docs/specs/SPEC_AGENT_IDENTITY_HISTORY_PERSISTENCE_PROTOCOL_2026_08_16.md
1147    // §4.4: the actual end-to-end feature -- agent_id resolves through a
1148    // real db_agent_identity_links row (not a mocked lookup) to the
1149    // sessions found under that link's account_id.
1150    #[test]
1151    fn list_for_agent_resolves_through_a_real_identity_link_to_the_right_sessions() {
1152        let dir = std::env::temp_dir().join(format!("amux-hist-svc-{}", std::process::id()));
1153        std::fs::create_dir_all(&dir).unwrap();
1154        let mine = write_session(&dir, "mine");
1155        let someone_elses = write_session(&dir, "someone-elses");
1156
1157        let index = SessionIndex::with_isolated_roots(
1158            vec![
1159                Box::new(MockAdapter::new(
1160                    vec![DiscoveredFile { file_path: mine, mtime_ms: 1 }],
1161                    "acct-mine",
1162                )),
1163                Box::new(MockAdapter::new(
1164                    vec![DiscoveredFile { file_path: someone_elses, mtime_ms: 1 }],
1165                    "acct-someone-else",
1166                )),
1167            ],
1168            vec![dir.clone()],
1169        );
1170        let service = HistoryService::from_index(index);
1171
1172        let store = Store::open_in_memory().unwrap();
1173        let mut def = crate::backend::storage::store::AgentDefinition {
1174            slug: String::new(),
1175            ..crate::backend::storage::agents::test_agent_def("agent-1", "T", "claude", "", 0, "")
1176        };
1177        store.agent_def_insert(&mut def).unwrap();
1178        store
1179            .identity_upsert(&crate::backend::storage::store::IdentityAccount {
1180                id: "acct-mine".to_string(),
1181                name: "claude-acct-mine".to_string(),
1182                provider: "claude".to_string(),
1183                kind: "pat".to_string(),
1184                display_name: String::new(),
1185                secret_ref: crate::backend::storage::store::SecretRef::OAuthConfigDir { dir: String::new() },
1186                context: serde_json::json!({}),
1187                status: "unknown".to_string(),
1188                created_at: 0,
1189                updated_at: 0,
1190            })
1191            .unwrap();
1192        store.agent_identity_link("agent-1", "acct-mine", "claude").unwrap();
1193
1194        let result = service.list_for_agent(&store, "agent-1", 0, 10, "created_at", "desc");
1195        assert_eq!(result["total"], 1);
1196        assert_eq!(result["sessions"][0]["session_id"], "mine");
1197
1198        std::fs::remove_dir_all(&dir).ok();
1199    }
1200
1201    #[test]
1202    fn list_for_agent_returns_empty_when_nothing_on_disk_matches_the_agent() {
1203        let service = HistoryService::from_index(SessionIndex::with_isolated_roots(vec![], vec![]));
1204        let store = Store::open_in_memory().unwrap();
1205        let result = service.list_for_agent(&store, "agent-with-no-links", 0, 10, "created_at", "desc");
1206        assert_eq!(result["total"], 0);
1207        assert_eq!(result["sessions"].as_array().unwrap().len(), 0);
1208    }
1209
1210    // ── Agent → session resolution
1211    // (docs/specs/SPEC_CROSS_CHANNEL_AGENT_HISTORY_RESOLUTION_2026_09_21.md) ──
1212
1213    /// Insert an agent whose slug differs from its id — i.e. every real
1214    /// agent, since the id is a UUID and the slug is human-readable.
1215    fn insert_agent(store: &Store, id: &str, name: &str, slug: &str, working_directory: &str) {
1216        let mut def = crate::backend::storage::store::AgentDefinition {
1217            slug: slug.to_string(),
1218            working_directory: working_directory.to_string(),
1219            ..crate::backend::storage::agents::test_agent_def(id, name, "claude", "", 0, "")
1220        };
1221        store.agent_def_insert(&mut def).unwrap();
1222    }
1223
1224    /// The dominant real-world failure: an agent with no bound account has
1225    /// NO `db_agent_identity_links` row (its registry record's `identity_id`
1226    /// reads "default"), so account resolution finds nothing — while
1227    /// its transcripts sit on disk, recording the directory it ran in. Before
1228    /// the working-directory index this returned a confident, empty history.
1229    #[test]
1230    fn sessions_resolve_by_working_directory_when_the_agent_has_no_identity_link() {
1231        let dir = std::env::temp_dir().join(format!("amux-hist-wd-{}", std::process::id()));
1232        std::fs::create_dir_all(&dir).unwrap();
1233        let mine = write_session(&dir, "mine-wd");
1234        let theirs = write_session(&dir, "theirs-wd");
1235
1236        let index = SessionIndex::with_isolated_roots(
1237            vec![
1238                Box::new(MockAdapter::in_dir(
1239                    vec![DiscoveredFile { file_path: mine, mtime_ms: 1 }],
1240                    "",
1241                    "/agents/agenty-0629j",
1242                )),
1243                Box::new(MockAdapter::in_dir(
1244                    vec![DiscoveredFile { file_path: theirs, mtime_ms: 1 }],
1245                    "",
1246                    "/agents/somebody-else",
1247                )),
1248            ],
1249            vec![dir.clone()],
1250        );
1251        let service = HistoryService::from_index(index);
1252
1253        let store = Store::open_in_memory().unwrap();
1254        insert_agent(&store, "def-uuid-agenty", "AgentY", "agenty", "/agents/agenty-0629j");
1255        // Deliberately NO agent_identity_link: that is the whole point.
1256
1257        let (sessions, total, _) = service
1258            .sessions_for_agent(&store, "agenty", 0, 10, "created_at", "desc", true)
1259            .unwrap();
1260        assert_eq!(total, 1, "the agent's own session must be found without any identity link");
1261        assert_eq!(sessions[0].session_id, "mine-wd");
1262
1263        std::fs::remove_dir_all(&dir).ok();
1264    }
1265
1266    /// One account linked to two agents holds both agents' transcripts. Each
1267    /// agent's history is its own working directory's sessions from it —
1268    /// never the other agent's — while an account only one agent uses keeps
1269    /// every session, including one from an earlier working directory.
1270    #[test]
1271    fn a_shared_account_contributes_only_the_owners_own_directory() {
1272        let dir = std::env::temp_dir().join(format!("amux-hist-shared-{}", std::process::id()));
1273        std::fs::create_dir_all(&dir).unwrap();
1274        let y = write_session(&dir, "shared-y");
1275        let z = write_session(&dir, "shared-z");
1276        let y_old = write_session(&dir, "solo-y-old-dir");
1277
1278        let index = SessionIndex::with_isolated_roots(
1279            vec![
1280                Box::new(MockAdapter::in_dir(vec![DiscoveredFile { file_path: y, mtime_ms: 1 }], "acct-shared", "/agents/y")),
1281                Box::new(MockAdapter::in_dir(vec![DiscoveredFile { file_path: z, mtime_ms: 1 }], "acct-shared", "/agents/z")),
1282                Box::new(MockAdapter::in_dir(vec![DiscoveredFile { file_path: y_old, mtime_ms: 1 }], "acct-solo", "/agents/y-before-move")),
1283            ],
1284            vec![dir.clone()],
1285        );
1286        let service = HistoryService::from_index(index);
1287        let store = Store::open_in_memory().unwrap();
1288        insert_agent(&store, "def-y", "AgentY", "agenty", "/agents/y");
1289        insert_agent(&store, "def-z", "AgentZ", "agentz", "/agents/z");
1290        for acct in ["acct-shared", "acct-solo"] {
1291            store
1292                .identity_upsert(&crate::backend::storage::store::IdentityAccount {
1293                    id: acct.to_string(),
1294                    name: format!("claude-{acct}"),
1295                    provider: "claude".to_string(),
1296                    kind: "oauth".to_string(),
1297                    display_name: String::new(),
1298                    secret_ref: crate::backend::storage::store::SecretRef::OAuthConfigDir { dir: String::new() },
1299                    context: serde_json::json!({}),
1300                    status: "unknown".to_string(),
1301                    created_at: 0,
1302                    updated_at: 0,
1303                })
1304                .unwrap();
1305        }
1306        store.agent_identity_link("def-y", "acct-shared", "claude").unwrap();
1307        store.agent_identity_link("def-z", "acct-shared", "claude").unwrap();
1308        store.agent_identity_link("def-y", "acct-solo", "codex").unwrap();
1309
1310        let ids = |slug: &str| {
1311            let (sessions, _, _) = service
1312                .sessions_for_agent(&store, slug, 0, 10, "created_at", "desc", true)
1313                .unwrap();
1314            let mut ids: Vec<String> = sessions.into_iter().map(|s| s.session_id).collect();
1315            ids.sort();
1316            ids
1317        };
1318        assert_eq!(ids("agenty"), ["shared-y", "solo-y-old-dir"], "never AgentZ's session");
1319        assert_eq!(ids("agentz"), ["shared-z"], "never AgentY's sessions");
1320
1321        std::fs::remove_dir_all(&dir).ok();
1322    }
1323
1324    /// Callers pass the SLUG (`AGENTMUX_AGENT_ID`), but
1325    /// `db_agent_identity_links.agent_id` stores the DEFINITION id — so the
1326    /// link lookup has to resolve the slug first or it matches zero rows.
1327    #[test]
1328    fn identity_links_resolve_from_the_slug_not_only_the_definition_id() {
1329        let dir = std::env::temp_dir().join(format!("amux-hist-slug-{}", std::process::id()));
1330        std::fs::create_dir_all(&dir).unwrap();
1331        let linked = write_session(&dir, "linked-session");
1332
1333        let index = SessionIndex::with_isolated_roots(
1334            vec![Box::new(MockAdapter::in_dir(
1335                vec![DiscoveredFile { file_path: linked, mtime_ms: 1 }],
1336                "acct-mine",
1337                // A directory the agent is NOT in, so only the identity link
1338                // can account for this hit.
1339                "/somewhere/else",
1340            ))],
1341            vec![dir.clone()],
1342        );
1343        let service = HistoryService::from_index(index);
1344
1345        let store = Store::open_in_memory().unwrap();
1346        insert_agent(&store, "def-uuid-agenty", "AgentY", "agenty", "/agents/agenty-0629j");
1347        store
1348            .identity_upsert(&crate::backend::storage::store::IdentityAccount {
1349                id: "acct-mine".to_string(),
1350                name: "claude-acct-mine".to_string(),
1351                provider: "claude".to_string(),
1352                kind: "pat".to_string(),
1353                display_name: String::new(),
1354                secret_ref: crate::backend::storage::store::SecretRef::OAuthConfigDir { dir: String::new() },
1355                context: serde_json::json!({}),
1356                status: "unknown".to_string(),
1357                created_at: 0,
1358                updated_at: 0,
1359            })
1360            .unwrap();
1361        // The link is keyed by DEFINITION id, as production writes it.
1362        store.agent_identity_link("def-uuid-agenty", "acct-mine", "claude").unwrap();
1363
1364        // The caller passes the slug, which is all an agent knows about itself.
1365        let (sessions, total, _) = service
1366            .sessions_for_agent(&store, "agenty", 0, 10, "created_at", "desc", true)
1367            .unwrap();
1368        assert_eq!(total, 1, "the slug must resolve to the definition id the link is stored under");
1369        assert_eq!(sessions[0].session_id, "linked-session");
1370
1371        std::fs::remove_dir_all(&dir).ok();
1372    }
1373
1374    /// `list`'s `project` filter matches on `contains`; working-directory
1375    /// resolution must not, or an agent in `/agents/foo` silently claims
1376    /// every session belonging to `/agents/foo-2`.
1377    #[test]
1378    fn working_directory_matching_is_exact_not_a_prefix() {
1379        let dir = std::env::temp_dir().join(format!("amux-hist-exact-{}", std::process::id()));
1380        std::fs::create_dir_all(&dir).unwrap();
1381        let neighbour = write_session(&dir, "neighbour-session");
1382
1383        let index = SessionIndex::with_isolated_roots(
1384            vec![Box::new(MockAdapter::in_dir(
1385                vec![DiscoveredFile { file_path: neighbour, mtime_ms: 1 }],
1386                "",
1387                "/agents/foo-2",
1388            ))],
1389            vec![dir.clone()],
1390        );
1391        let service = HistoryService::from_index(index);
1392
1393        let store = Store::open_in_memory().unwrap();
1394        insert_agent(&store, "def-uuid-foo", "Foo", "foo", "/agents/foo");
1395
1396        let (_, total, _) = service
1397            .sessions_for_agent(&store, "foo", 0, 10, "created_at", "desc", true)
1398            .unwrap();
1399        assert_eq!(total, 0, "/agents/foo must not claim /agents/foo-2's sessions");
1400
1401        std::fs::remove_dir_all(&dir).ok();
1402    }
1403
1404    /// A trailing separator or different slash style describes the same
1405    /// directory and must resolve to the same sessions.
1406    #[test]
1407    fn working_directory_matching_normalizes_separators_and_trailing_slash() {
1408        let dir = std::env::temp_dir().join(format!("amux-hist-norm-{}", std::process::id()));
1409        std::fs::create_dir_all(&dir).unwrap();
1410        let mine = write_session(&dir, "norm-session");
1411
1412        let index = SessionIndex::with_isolated_roots(
1413            vec![Box::new(MockAdapter::in_dir(
1414                vec![DiscoveredFile { file_path: mine, mtime_ms: 1 }],
1415                "",
1416                r"C:\work\agents\bar",
1417            ))],
1418            vec![dir.clone()],
1419        );
1420        let service = HistoryService::from_index(index);
1421
1422        let store = Store::open_in_memory().unwrap();
1423        insert_agent(&store, "def-uuid-bar", "Bar", "bar", "C:/work/agents/bar/");
1424
1425        let (_, total, _) = service
1426            .sessions_for_agent(&store, "bar", 0, 10, "created_at", "desc", true)
1427            .unwrap();
1428        assert_eq!(total, 1, "the same directory written differently must still match");
1429
1430        std::fs::remove_dir_all(&dir).ok();
1431    }
1432
1433    /// The registry fallback — `registry_record` plus
1434    /// `agent_registry_lookup::working_dir_from_record` — is the path for a
1435    /// live agent with NO `db_agents` row, which is the common case (launching
1436    /// an agent does not create one). Every other test here inserts a real row,
1437    /// so `instance_get_by_slug` always succeeds and this path never runs;
1438    /// a regression in slug derivation or `source_agents_base` handling would
1439    /// ship undetected. reagentx P2 on PR #3480.
1440    #[test]
1441    fn sessions_resolve_via_the_registry_when_the_agent_has_no_db_row() {
1442        let _guard = crate::test_support::ISOLATED_AUTH_ENV_LOCK
1443            .lock()
1444            .unwrap_or_else(|e| e.into_inner());
1445        let prev = std::env::var_os("AGENTMUX_SHARED_DIR");
1446        let tmp = tempfile::tempdir().unwrap();
1447        std::env::set_var("AGENTMUX_SHARED_DIR", tmp.path());
1448
1449        // The registry stores working_dir RELATIVE to source_agents_base.
1450        let base = tmp.path().join("agentsbase");
1451        let resolved_dir = base.join("agenty-0629j").to_string_lossy().to_string();
1452
1453        let registry = crate::registry::Registry::open(tmp.path().join("agents").join("registry")).unwrap();
1454        registry
1455            .upsert(&crate::registry::NamedAgentRecord {
1456                schema_version: 3,
1457                data: crate::registry::NamedAgentRecordV1 {
1458                    instance_id: "inst-agenty".to_string(),
1459                    instance_name: "AgentY".to_string(),
1460                    definition_id: "def-agenty".to_string(),
1461                    identity_id: None,
1462                    memory_id: None,
1463                    session_id: None,
1464                    working_dir: "agenty-0629j".to_string(),
1465                    source_agents_base: Some(base.to_string_lossy().to_string()),
1466                    created_at_ms: 1,
1467                    last_launched_at_ms: 1,
1468                    created_by_version: "test".to_string(),
1469                    last_launched_by_version: "test".to_string(),
1470                },
1471            })
1472            .unwrap();
1473
1474        let dir = std::env::temp_dir().join(format!("amux-hist-reg-{}", std::process::id()));
1475        std::fs::create_dir_all(&dir).unwrap();
1476        let mine = write_session(&dir, "registry-session");
1477        let index = SessionIndex::with_isolated_roots(
1478            vec![Box::new(MockAdapter::in_dir(
1479                vec![DiscoveredFile { file_path: mine, mtime_ms: 1 }],
1480                "",
1481                &resolved_dir,
1482            ))],
1483            vec![dir.clone()],
1484        );
1485        let service = HistoryService::from_index(index);
1486
1487        // Deliberately EMPTY store: no db_agents row, so resolution has to come
1488        // from the registry record above or not at all.
1489        let store = Store::open_in_memory().unwrap();
1490
1491        // The display name is "AgentY"; callers pass the derived slug.
1492        let (sessions, total, _) = service
1493            .sessions_for_agent(&store, "agenty", 0, 10, "created_at", "desc", true)
1494            .unwrap();
1495        assert_eq!(total, 1, "registry fallback must resolve the working directory");
1496        assert_eq!(sessions[0].session_id, "registry-session");
1497
1498        // An unrelated agent must not inherit it by coincidence.
1499        let (_, other_total, _) = service
1500            .sessions_for_agent(&store, "someone-else", 0, 10, "created_at", "desc", true)
1501            .unwrap();
1502        assert_eq!(other_total, 0, "an unrelated slug must not match");
1503
1504        match prev {
1505            Some(v) => std::env::set_var("AGENTMUX_SHARED_DIR", v),
1506            None => std::env::remove_var("AGENTMUX_SHARED_DIR"),
1507        }
1508        std::fs::remove_dir_all(&dir).ok();
1509    }
1510
1511    /// A registry-only agent that ALSO has a real identity link — the gap
1512    /// reagentx P1 flagged on PR #3480 (re-review). The registry test above
1513    /// proves the working-directory fallback, but its record has no identity,
1514    /// so the identity-link half was never exercised without a `db_agents`
1515    /// row.
1516    ///
1517    /// The failure it guards is quiet: with no instance row, `definition_id`
1518    /// fell back to the raw SLUG, and `db_agent_identity_links.agent_id`
1519    /// stores a DEFINITION id — so the link lookup matched zero rows and the
1520    /// agent's identity-bound sessions vanished. That is Bug A, reproduced for
1521    /// exactly the case the PR's own docs call the common one.
1522    ///
1523    /// The session here is deliberately in a directory the registry record
1524    /// does NOT point at, so the working-directory fallback cannot mask a
1525    /// regression by finding it a second way.
1526    #[test]
1527    fn registry_only_agent_still_resolves_its_identity_linked_sessions() {
1528        let _guard = crate::test_support::ISOLATED_AUTH_ENV_LOCK
1529            .lock()
1530            .unwrap_or_else(|e| e.into_inner());
1531        let prev = std::env::var_os("AGENTMUX_SHARED_DIR");
1532        let tmp = tempfile::tempdir().unwrap();
1533        std::env::set_var("AGENTMUX_SHARED_DIR", tmp.path());
1534
1535        let base = tmp.path().join("agentsbase");
1536        let registry =
1537            crate::registry::Registry::open(tmp.path().join("agents").join("registry")).unwrap();
1538        registry
1539            .upsert(&crate::registry::NamedAgentRecord {
1540                schema_version: 3,
1541                data: crate::registry::NamedAgentRecordV1 {
1542                    instance_id: "inst-linked".to_string(),
1543                    instance_name: "AgentY".to_string(),
1544                    definition_id: "def-agenty".to_string(),
1545                    identity_id: None,
1546                    memory_id: None,
1547                    session_id: None,
1548                    working_dir: "agenty-0629j".to_string(),
1549                    source_agents_base: Some(base.to_string_lossy().to_string()),
1550                    created_at_ms: 1,
1551                    last_launched_at_ms: 1,
1552                    created_by_version: "test".to_string(),
1553                    last_launched_by_version: "test".to_string(),
1554                },
1555            })
1556            .unwrap();
1557
1558        let dir = std::env::temp_dir().join(format!("amux-hist-reglink-{}", std::process::id()));
1559        std::fs::create_dir_all(&dir).unwrap();
1560        let mine = write_session(&dir, "identity-linked-session");
1561        let index = SessionIndex::with_isolated_roots(
1562            vec![Box::new(MockAdapter::in_dir(
1563                vec![DiscoveredFile { file_path: mine, mtime_ms: 1 }],
1564                "acct-mine",
1565                "/somewhere/the/registry/does/not/point",
1566            ))],
1567            vec![dir.clone()],
1568        );
1569        let service = HistoryService::from_index(index);
1570
1571        // A definition + identity link, but NO `db_agents` instance row — so
1572        // `instance_get_by_slug("agenty")` finds nothing and the definition id
1573        // can only come from the registry record above.
1574        let store = Store::open_in_memory().unwrap();
1575        insert_test_agent_and_link(&store, "def-agenty", "acct-mine");
1576
1577        let (sessions, total, _) = service
1578            .sessions_for_agent(&store, "agenty", 0, 10, "created_at", "desc", true)
1579            .unwrap();
1580        assert_eq!(
1581            total, 1,
1582            "a registry-only agent's identity-linked sessions must resolve; \
1583             the slug is not a definition id"
1584        );
1585        assert_eq!(sessions[0].session_id, "identity-linked-session");
1586
1587        // The registry record must not hand its definition id to a different
1588        // agent — resolution stays scoped to the matching slug.
1589        let (_, other_total, _) = service
1590            .sessions_for_agent(&store, "someone-else", 0, 10, "created_at", "desc", true)
1591            .unwrap();
1592        assert_eq!(other_total, 0, "an unrelated slug must not inherit the link");
1593
1594        match prev {
1595            Some(v) => std::env::set_var("AGENTMUX_SHARED_DIR", v),
1596            None => std::env::remove_var("AGENTMUX_SHARED_DIR"),
1597        }
1598        std::fs::remove_dir_all(&dir).ok();
1599    }
1600
1601    /// Two live agents whose display names normalize to the SAME slug must not
1602    /// be able to read each other's history. reagentx P1 on PR #3480
1603    /// (third review).
1604    ///
1605    /// Registry records are keyed by `instance_id`, and nothing enforces a
1606    /// unique `instance_name` across them — so `derive_slug("AgentY")` and
1607    /// `derive_slug("AGENTY")` both yield `agenty`. The lookup used to take
1608    /// the *first* match in whatever order the registry happened to list, then
1609    /// hand that record's `definition_id` and `working_dir` to the caller. For
1610    /// this path that means one agent's conversation history silently
1611    /// resolving into another agent's `sessions_for_agent` call.
1612    ///
1613    /// `native_memory_handlers` already guards the same lookup with
1614    /// `.filter(|r| r.data.definition_id == definition_id)`, but that guard is
1615    /// unavailable here: `definition_id` is precisely what this path is trying
1616    /// to resolve. So the lookup itself must refuse to guess.
1617    ///
1618    /// The assertion is deliberately "not the other agent's session" rather
1619    /// than an exact count — failing closed (0 sessions) is the required
1620    /// behaviour, but the bug being prevented is *leakage*, so that is what is
1621    /// asserted.
1622    #[test]
1623    fn colliding_slugs_never_resolve_into_another_agents_history() {
1624        let _guard = crate::test_support::ISOLATED_AUTH_ENV_LOCK
1625            .lock()
1626            .unwrap_or_else(|e| e.into_inner());
1627        let prev = std::env::var_os("AGENTMUX_SHARED_DIR");
1628        let tmp = tempfile::tempdir().unwrap();
1629        std::env::set_var("AGENTMUX_SHARED_DIR", tmp.path());
1630
1631        let base = tmp.path().join("agentsbase");
1632        let registry =
1633            crate::registry::Registry::open(tmp.path().join("agents").join("registry")).unwrap();
1634
1635        let rec = |instance_id: &str, name: &str, def: &str, dir: &str| {
1636            registry
1637                .upsert(&crate::registry::NamedAgentRecord {
1638                    schema_version: 3,
1639                    data: crate::registry::NamedAgentRecordV1 {
1640                        instance_id: instance_id.to_string(),
1641                        instance_name: name.to_string(),
1642                        definition_id: def.to_string(),
1643                        identity_id: None,
1644                        memory_id: None,
1645                        session_id: None,
1646                        working_dir: dir.to_string(),
1647                        source_agents_base: Some(base.to_string_lossy().to_string()),
1648                        created_at_ms: 1,
1649                        last_launched_at_ms: 1,
1650                        created_by_version: "test".to_string(),
1651                        last_launched_by_version: "test".to_string(),
1652                    },
1653                })
1654                .unwrap();
1655        };
1656        // Both normalize to the slug `agenty`.
1657        rec("inst-a", "AgentY", "def-a", "dir-a");
1658        rec("inst-b", "AGENTY", "def-b", "dir-b");
1659
1660        // A session under EACH colliding record, so the assertion does not
1661        // depend on which one `list_active()` happens to return first. Whoever
1662        // the caller really is, at most one of these is theirs — and the slug
1663        // alone cannot say which — so resolving either one is a leak.
1664        let dir = std::env::temp_dir().join(format!("amux-hist-collide-{}", std::process::id()));
1665        std::fs::create_dir_all(&dir).unwrap();
1666        let sess_a = write_session(&dir, "agent-a-private-session");
1667        let sess_b = write_session(&dir, "agent-b-private-session");
1668        let index = SessionIndex::with_isolated_roots(
1669            vec![
1670                Box::new(MockAdapter::in_dir(
1671                    vec![DiscoveredFile { file_path: sess_a, mtime_ms: 1 }],
1672                    "acct-a",
1673                    &base.join("dir-a").to_string_lossy().to_string(),
1674                )),
1675                Box::new(MockAdapter::in_dir(
1676                    vec![DiscoveredFile { file_path: sess_b, mtime_ms: 1 }],
1677                    "acct-b",
1678                    &base.join("dir-b").to_string_lossy().to_string(),
1679                )),
1680            ],
1681            vec![dir.clone()],
1682        );
1683        let service = HistoryService::from_index(index);
1684
1685        let store = Store::open_in_memory().unwrap();
1686        insert_test_agent_and_link(&store, "def-a", "acct-a");
1687        insert_test_agent_and_link(&store, "def-b", "acct-b");
1688
1689        let (sessions, total, _) = service
1690            .sessions_for_agent(&store, "agenty", 0, 10, "created_at", "desc", true)
1691            .unwrap();
1692
1693        assert_eq!(
1694            total,
1695            0,
1696            "an ambiguous slug must resolve to NO history rather than guessing \
1697             an agent; got {:?}",
1698            sessions.iter().map(|s| &s.session_id).collect::<Vec<_>>()
1699        );
1700
1701        match prev {
1702            Some(v) => std::env::set_var("AGENTMUX_SHARED_DIR", v),
1703            None => std::env::remove_var("AGENTMUX_SHARED_DIR"),
1704        }
1705        std::fs::remove_dir_all(&dir).ok();
1706    }
1707
1708    fn insert_test_agent_and_link(store: &Store, agent_id: &str, account_id: &str) {
1709        let mut def = crate::backend::storage::store::AgentDefinition {
1710            slug: String::new(),
1711            ..crate::backend::storage::agents::test_agent_def(agent_id, "T", "claude", "", 0, "")
1712        };
1713        store.agent_def_insert(&mut def).unwrap();
1714        store
1715            .identity_upsert(&crate::backend::storage::store::IdentityAccount {
1716                id: account_id.to_string(),
1717                name: format!("claude-{account_id}"),
1718                provider: "claude".to_string(),
1719                kind: "pat".to_string(),
1720                display_name: String::new(),
1721                secret_ref: crate::backend::storage::store::SecretRef::OAuthConfigDir { dir: String::new() },
1722                context: serde_json::json!({}),
1723                status: "unknown".to_string(),
1724                created_at: 0,
1725                updated_at: 0,
1726            })
1727            .unwrap();
1728        store.agent_identity_link(agent_id, account_id, "claude").unwrap();
1729    }
1730
1731    /// Unlike `MockAdapter` (a fixed file list captured at construction),
1732    /// this re-scans a real directory on every `discover_files()` call --
1733    /// needed to exercise `refresh()`'s actual re-scan behavior, not just
1734    /// the in-memory index it populates.
1735    struct DynamicMockAdapter {
1736        dir: std::path::PathBuf,
1737        identity_id: String,
1738    }
1739    impl HistoryAdapter for DynamicMockAdapter {
1740        fn provider(&self) -> &str {
1741            "mock"
1742        }
1743        fn discover_files(&self) -> Result<Vec<DiscoveredFile>, HistoryError> {
1744            let entries = std::fs::read_dir(&self.dir).map_err(|e| HistoryError::Other(e.to_string()))?;
1745            Ok(entries
1746                .flatten()
1747                .map(|e| DiscoveredFile { file_path: e.path().to_string_lossy().into_owned(), mtime_ms: 0 })
1748                .collect())
1749        }
1750        fn extract_meta(&self, file_path: &str) -> Result<Option<SessionMeta>, HistoryError> {
1751            let id = std::path::Path::new(file_path)
1752                .file_stem()
1753                .map(|s| s.to_string_lossy().into_owned())
1754                .unwrap_or_default();
1755            Ok(Some(SessionMeta {
1756                session_id: id,
1757                file_path: file_path.to_string(),
1758                provider: "mock".to_string(),
1759                model: String::new(),
1760                slug: String::new(),
1761                working_directory: "/proj".to_string(),
1762                created_at: 0,
1763                modified_at: 0,
1764                message_count: 0,
1765                first_user_message: String::new(),
1766                file_size_bytes: 0,
1767                git_branch: String::new(),
1768                total_tokens: 0,
1769                subagent_count: 0,
1770                identity_id: self.identity_id.clone(),
1771                starts_undated: false,
1772            }))
1773        }
1774        fn parse_file(&self, _: &str) -> Result<Option<HistorySession>, HistoryError> {
1775            Ok(None)
1776        }
1777    }
1778
1779    // reagentx P1 on PR #2613: sessions_for_agent's lazy
1780    // refresh-only-if-empty behavior is wrong for a caller claiming
1781    // completeness -- a session created after the index was first
1782    // populated (by ANY prior call) must still show up when
1783    // force_refresh=true, and must NOT show up when force_refresh=false
1784    // (proving the two modes are genuinely different, not that refresh
1785    // just always happens to run).
1786    #[test]
1787    fn force_refresh_true_picks_up_a_session_created_after_first_population_false_does_not() {
1788        let dir = std::env::temp_dir().join(format!("amux-hist-force-refresh-{}", std::process::id()));
1789        std::fs::create_dir_all(&dir).unwrap();
1790        write_session(&dir, "first");
1791
1792        let index = SessionIndex::with_isolated_roots(
1793            vec![Box::new(DynamicMockAdapter { dir: dir.clone(), identity_id: "acct-mine".to_string() })],
1794            vec![dir.clone()],
1795        );
1796        let service = HistoryService::from_index(index);
1797        let store = Store::open_in_memory().unwrap();
1798        insert_test_agent_and_link(&store, "agent-1", "acct-mine");
1799
1800        // First call populates the index (empty -> refresh runs regardless
1801        // of force_refresh).
1802        let (first_pass, total1, _) = service.sessions_for_agent(&store, "agent-1", 0, 10, "created_at", "desc", false).unwrap();
1803        assert_eq!(total1, 1);
1804        assert_eq!(first_pass[0].session_id, "first");
1805
1806        // A new session appears on disk after that first population.
1807        write_session(&dir, "second");
1808
1809        let (_, total_stale, _) =
1810            service.sessions_for_agent(&store, "agent-1", 0, 10, "created_at", "desc", false).unwrap();
1811        assert_eq!(total_stale, 1, "force_refresh=false must NOT see the new session (index already non-empty)");
1812
1813        let (fresh, total_fresh, _) =
1814            service.sessions_for_agent(&store, "agent-1", 0, 10, "created_at", "desc", true).unwrap();
1815        assert_eq!(total_fresh, 2, "force_refresh=true must see the new session");
1816        assert!(fresh.iter().any(|s| s.session_id == "second"));
1817
1818        std::fs::remove_dir_all(&dir).ok();
1819    }
1820}