Skip to main content

agentmux_srv_core/backend/history/
claude_adapter.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Claude Code history adapter.
5//! Scans for session JSONL files across both the user's global Claude homes and
6//! the AgentMux-isolated homes that current agents actually write to:
7//!   - ~/.claude/projects/ and ~/.config/claude-*/projects/ (global / legacy)
8//!   - <AGENTMUX_SHARED_DIR>/providers/claude/projects/ (default isolated home)
9//!   - <AGENTMUX_SHARED_DIR>/identities/<account_id>/claude/projects/ (per account, global)
10//!   - <home>/channels/*/identities/*/claude/projects/ and
11//!     <home>/dev/*/(*/)?identities/*/claude/projects/ (per-channel isolated —
12//!     Step 4 of docs/specs/SPEC_AGENT_IDENTITY_HISTORY_PERSISTENCE_PROTOCOL_2026_08_16.md.
13//!     Step 3 links these forward to the global location, but history written
14//!     before that fix landed, or for an account whose link creation failed
15//!     (best-effort, can fail), still has real data only under these
16//!     per-channel paths — scanned here so it stays discoverable rather than
17//!     requiring a manual filesystem search.)
18
19use std::collections::HashSet;
20use std::fs;
21use std::io::{BufRead, BufReader};
22use std::path::{Path, PathBuf};
23use std::time::UNIX_EPOCH;
24
25use super::adapter::*;
26
27/// Where Claude homes live. The homes under them — one per account, and
28/// channels — are listed again on every discovery ([`ClaudeHistoryAdapter::base_dirs`]),
29/// because they are created while srv runs: an account added or switched
30/// after srv started used to stay invisible until the next restart.
31pub struct ClaudeHistoryAdapter {
32    /// The user's home: `~/.claude` and `~/.config/claude-*`.
33    user_home: Option<PathBuf>,
34    /// `<shared>`: `providers/claude` and `identities/*`.
35    shared_dir: Option<PathBuf>,
36    /// AgentMux's home: `channels/*/identities/*` and `dev/…/identities/*`.
37    agentmux_home: Option<PathBuf>,
38}
39
40impl ClaudeHistoryAdapter {
41    /// Push `path` onto `dirs` iff it's a real directory AND its
42    /// canonical (symlink/junction-resolved) form hasn't already been
43    /// pushed — the dedup key, not `path` itself, since two different
44    /// `base_dirs` entries can be different paths to the same physical
45    /// directory (a per-channel isolated `projects/` junction and the
46    /// global location it points at). Falls back to the literal path
47    /// when canonicalization fails (e.g. a dangling/broken link) rather
48    /// than silently dropping it.
49    fn push_deduped_dir(dirs: &mut Vec<PathBuf>, seen: &mut HashSet<PathBuf>, path: PathBuf) {
50        if !path.is_dir() {
51            return;
52        }
53        let key = fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
54        if seen.insert(key) {
55            dirs.push(path);
56        }
57    }
58
59    pub fn new() -> Self {
60        // `AGENTMUX_SHARED_DIR` is exported by the launcher; fall back to
61        // ~/.agentmux/shared so discovery still works in plain/test contexts.
62        let shared_dir = std::env::var_os("AGENTMUX_SHARED_DIR")
63            .map(PathBuf::from)
64            .or_else(|| crate::srv_info::agentmux_root().map(|root| root.join("shared")));
65        // The account-wide root, not `DataPaths::from_env().home_dir`: inside
66        // srv that answers with this version's data directory, which has no
67        // `channels/` or `dev/` to scan.
68        let agentmux_home = crate::srv_info::agentmux_root();
69        Self::with_roots(dirs::home_dir(), shared_dir, agentmux_home)
70    }
71
72    pub fn with_roots(
73        user_home: Option<PathBuf>,
74        shared_dir: Option<PathBuf>,
75        agentmux_home: Option<PathBuf>,
76    ) -> Self {
77        ClaudeHistoryAdapter { user_home, shared_dir, agentmux_home }
78    }
79
80    /// Every Claude `projects/` directory under the roots, as the filesystem
81    /// stands now. Deduplicated by canonical (symlink/junction-resolved) path:
82    /// after Step 3 above, a per-channel isolated `projects/` dir may be a
83    /// junction pointing at the exact same physical location as one of the
84    /// global `<shared>/...` entries, and scanning both would surface every
85    /// session twice.
86    fn base_dirs(&self, problems: &mut Vec<String>) -> Vec<PathBuf> {
87        let mut base_dirs = Vec::new();
88        let mut seen_canonical: HashSet<PathBuf> = HashSet::new();
89
90        if let Some(home) = &self.user_home {
91            // User's personal (non-isolated) Claude sessions
92            Self::push_deduped_dir(&mut base_dirs, &mut seen_canonical, home.join(".claude").join("projects"));
93
94            // Legacy multi-account convention: ~/.config/claude-*/projects/
95            let config_dir = home.join(".config");
96            if config_dir.is_dir() {
97                if let Some(entries) = read_dir_or_note(problems, &config_dir) {
98                    for entry in entries.flatten() {
99                        let name = entry.file_name();
100                        let name_str = name.to_string_lossy();
101                        if name_str.starts_with("claude-") {
102                            Self::push_deduped_dir(&mut base_dirs, &mut seen_canonical, entry.path().join("projects"));
103                        }
104                    }
105                }
106            }
107        }
108
109        // AgentMux-ISOLATED Claude homes — where agents spawned by current builds
110        // actually write (AgentMux sets CLAUDE_CONFIG_DIR here at spawn time).
111        // Without these, the history browse misses every AgentMux agent
112        // conversation. See docs/specs/SPEC_UNIFIED_AGENT_HISTORY_STORE_2026-06-10.md.
113        //   <shared>/providers/claude/projects/              (default, account-wide)
114        //   <shared>/identities/<account_id>/claude/projects/ (per account, global)
115        if let Some(shared) = &self.shared_dir {
116            Self::push_deduped_dir(&mut base_dirs, &mut seen_canonical, shared.join("providers").join("claude").join("projects"));
117            if let Some(entries) = read_dir_or_note(problems, &shared.join("identities")) {
118                for entry in entries.flatten() {
119                    Self::push_deduped_dir(&mut base_dirs, &mut seen_canonical, entry.path().join("claude").join("projects"));
120                }
121            }
122        }
123
124        // Per-channel ISOLATED identity dirs (SPEC_AGENT_IDENTITY_HISTORY_PERSISTENCE_PROTOCOL_2026_08_16.md
125        // §4.4) — `<home>/channels/*/identities/*/claude/projects` and
126        // `<home>/dev/*/identities/*/claude/projects` (or, when a dev clone
127        // id is in play, one level deeper: `<home>/dev/*/*/identities/*/...`).
128        if let Some(agentmux_home) = &self.agentmux_home {
129            for root_name in ["channels", "dev"] {
130                Self::scan_isolated_identities_under(
131                    &agentmux_home.join(root_name),
132                    &mut base_dirs,
133                    &mut seen_canonical,
134                    2,
135                    problems,
136                );
137            }
138        }
139
140        base_dirs
141    }
142
143    /// Find every `identities/` directory up to `max_depth` levels under
144    /// `root`, and for each, every `<account_id>/claude/projects` that
145    /// exists. Bounded, not an unbounded recursive walk — channel/dev
146    /// directory layouts are shallow by construction
147    /// (`channels/<slug>/identities/`, `dev/<branch>/identities/` or
148    /// `dev/<branch>/<clone_id>/identities/`), so depth 2 covers every
149    /// known layout without risking an expensive filesystem walk if
150    /// something unexpected is nested underneath.
151    fn scan_isolated_identities_under(
152        root: &Path,
153        base_dirs: &mut Vec<PathBuf>,
154        seen: &mut HashSet<PathBuf>,
155        max_depth: u8,
156        problems: &mut Vec<String>,
157    ) {
158        let Some(entries) = read_dir_or_note(problems, root) else {
159            return;
160        };
161        for entry in entries.flatten() {
162            let path = entry.path();
163            if !path.is_dir() {
164                continue;
165            }
166            let identities = path.join("identities");
167            if identities.is_dir() {
168                if let Some(id_entries) = read_dir_or_note(problems, &identities) {
169                    for id_entry in id_entries.flatten() {
170                        Self::push_deduped_dir(base_dirs, seen, id_entry.path().join("claude").join("projects"));
171                    }
172                }
173            }
174            if max_depth > 1 {
175                Self::scan_isolated_identities_under(&path, base_dirs, seen, max_depth - 1, problems);
176            }
177        }
178    }
179
180    /// Count subagent JSONL files in a session's subagents/ directory.
181    fn count_subagents(session_dir: &Path) -> u32 {
182        let subagents_dir = session_dir.join("subagents");
183        if !subagents_dir.is_dir() {
184            return 0;
185        }
186        fs::read_dir(&subagents_dir)
187            .map(|entries| {
188                entries
189                    .flatten()
190                    .filter(|e| {
191                        let name = e.file_name();
192                        let s = name.to_string_lossy();
193                        s.starts_with("agent-") && s.ends_with(".jsonl")
194                    })
195                    .count() as u32
196            })
197            .unwrap_or(0)
198    }
199
200    /// Decode a project directory name back to a path.
201    /// e.g., "C--Users-user--claw-agentx-workspace" → "C:/Users/user/.claw/agentx-workspace"
202    /// This is lossy — real hyphens are indistinguishable from path separators.
203    fn decode_project_path(encoded: &str) -> String {
204        // Best-effort: replace leading drive pattern and path separators
205        let mut result = encoded.to_string();
206        // Restore drive letter colon: "C-" at start → "C:"
207        if result.len() >= 2 && result.as_bytes()[1] == b'-' && result.as_bytes()[0].is_ascii_uppercase() {
208            result = format!("{}:{}", &result[..1], &result[2..]);
209        }
210        // Replace remaining hyphens with forward slashes
211        result = result.replace('-', "/");
212        result
213    }
214
215    /// Parse the account id a session's absolute file path was
216    /// discovered under, if any: `.../identities/<account_id>/claude/...`
217    /// (both the always-global `<shared>/identities/...` location and the
218    /// per-channel isolated `<home>/channels/*/identities/...` /
219    /// `<home>/dev/*/(*/)?identities/...` locations share this same
220    /// `identities/<account_id>/claude/` shape — see `new()`'s scan roots).
221    /// Empty string for any other base_dir (personal `~/.claude`, the
222    /// default `<shared>/providers/claude/projects`, legacy
223    /// `~/.config/claude-*`) — those have no account to attribute to.
224    fn identity_id_from_path(path: &Path) -> String {
225        let components: Vec<String> = path
226            .components()
227            .map(|c| c.as_os_str().to_string_lossy().into_owned())
228            .collect();
229        for (i, comp) in components.iter().enumerate() {
230            if comp == "identities" && components.get(i + 2).map(String::as_str) == Some("claude") {
231                if let Some(bundle_id) = components.get(i + 1) {
232                    return bundle_id.clone();
233                }
234            }
235        }
236        String::new()
237    }
238}
239
240/// Record a directory or file discovery couldn't read. A path that no longer
241/// exists isn't one: it was deleted (or never created), so nothing in it was
242/// missed.
243fn note_unreadable(problems: &mut Vec<String>, path: &Path, e: &std::io::Error) {
244    if e.kind() != std::io::ErrorKind::NotFound {
245        problems.push(format!("{}: {e}", path.display()));
246    }
247}
248
249fn read_dir_or_note(problems: &mut Vec<String>, dir: &Path) -> Option<fs::ReadDir> {
250    fs::read_dir(dir).map_err(|e| note_unreadable(problems, dir, &e)).ok()
251}
252
253fn metadata_or_note(problems: &mut Vec<String>, file: &Path) -> Option<fs::Metadata> {
254    file.metadata().map_err(|e| note_unreadable(problems, file, &e)).ok()
255}
256
257/// One conversation message from a Claude record — a transcript line or a
258/// line of the stream-json output AgentMux keeps (`agent:<id>:current`); the
259/// two share the message shape. `None` for anything that isn't a user or
260/// assistant message with something in it (a tool-result frame, thinking only).
261pub(crate) fn message_from_entry(entry: &serde_json::Value, timestamp: i64) -> Option<HistoryMessage> {
262    let entry_type = entry.get("type").and_then(|v| v.as_str()).unwrap_or("");
263    if entry_type == "user" {
264        let content = if let Some(msg) = entry.pointer("/message/content") {
265            if let Some(text) = msg.as_str() {
266                text.to_string()
267            } else if let Some(arr) = msg.as_array() {
268                arr.iter()
269                    .filter_map(|block| {
270                        if block.get("type").and_then(|v| v.as_str()) == Some("text") {
271                            block.get("text").and_then(|v| v.as_str()).map(String::from)
272                        } else {
273                            None
274                        }
275                    })
276                    .collect::<Vec<_>>()
277                    .join("\n")
278            } else {
279                String::new()
280            }
281        } else {
282            String::new()
283        };
284
285        return (!content.is_empty()).then(|| HistoryMessage {
286            role: "user".to_string(),
287            content,
288            timestamp,
289            tool_uses: vec![],
290            origin: None,
291        });
292    } else if entry_type == "assistant" {
293        let mut text_parts = Vec::new();
294        let mut tool_uses = Vec::new();
295
296        if let Some(content_arr) = entry.pointer("/message/content").and_then(|v| v.as_array()) {
297            for block in content_arr {
298                let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
299                match block_type {
300                    "text" => {
301                        if let Some(text) = block.get("text").and_then(|v| v.as_str()) {
302                            text_parts.push(text.to_string());
303                        }
304                    }
305                    "tool_use" => {
306                        let name = block
307                            .get("name")
308                            .and_then(|v| v.as_str())
309                            .unwrap_or("unknown")
310                            .to_string();
311                        // Summarize first argument
312                        let arg_summary = if let Some(input) = block.get("input") {
313                            if let Some(obj) = input.as_object() {
314                                // Take first key-value pair as summary
315                                obj.iter()
316                                    .next()
317                                    .map(|(k, v)| {
318                                        let val_str = if let Some(s) = v.as_str() {
319                                            s.chars().take(100).collect::<String>()
320                                        } else {
321                                            v.to_string().chars().take(100).collect::<String>()
322                                        };
323                                        format!("{}: {}", k, val_str)
324                                    })
325                                    .unwrap_or_default()
326                            } else {
327                                String::new()
328                            }
329                        } else {
330                            String::new()
331                        };
332                        tool_uses.push(ToolUseSummary {
333                            name,
334                            argument_summary: arg_summary,
335                        });
336                    }
337                    // Skip "thinking" blocks — they're internal reasoning
338                    _ => {}
339                }
340            }
341        }
342
343        let content = text_parts.join("\n");
344        return (!content.is_empty() || !tool_uses.is_empty()).then(|| HistoryMessage {
345            role: "assistant".to_string(),
346            content,
347            timestamp,
348            tool_uses,
349            origin: None,
350        });
351    }
352    None
353}
354
355impl HistoryAdapter for ClaudeHistoryAdapter {
356    fn provider(&self) -> &str {
357        "claude"
358    }
359
360    fn discover_files(&self) -> Result<Vec<DiscoveredFile>, HistoryError> {
361        self.discover().map(|found| found.files)
362    }
363
364    fn discover(&self) -> Result<Discovery, HistoryError> {
365        let mut files = Vec::new();
366        let mut problems = Vec::new();
367
368        for base_dir in &self.base_dirs(&mut problems) {
369            let entries = match fs::read_dir(base_dir) {
370                Ok(e) => e,
371                Err(e) => {
372                    note_unreadable(&mut problems, base_dir, &e);
373                    continue;
374                }
375            };
376
377            for project_entry in entries {
378                let project_entry = match project_entry {
379                    Ok(entry) => entry,
380                    Err(e) => {
381                        note_unreadable(&mut problems, base_dir, &e);
382                        continue;
383                    }
384                };
385                let project_path = project_entry.path();
386                if !project_path.is_dir() {
387                    // Top-level .jsonl files (session files at project root level)
388                    if project_path.extension().map_or(false, |e| e == "jsonl") {
389                        if let Some(meta) = metadata_or_note(&mut problems, &project_path) {
390                            let mtime = meta
391                                .modified()
392                                .ok()
393                                .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
394                                .map(|d| d.as_millis() as i64)
395                                .unwrap_or(0);
396                            files.push(DiscoveredFile {
397                                file_path: project_path.to_string_lossy().into(),
398                                mtime_ms: mtime,
399                            });
400                        }
401                    }
402                    continue;
403                }
404
405                // Scan for .jsonl files inside project directories
406                // These are session directories that may also contain subagents/
407                let dir_entries = match fs::read_dir(&project_path) {
408                    Ok(e) => e,
409                    Err(e) => {
410                        note_unreadable(&mut problems, &project_path, &e);
411                        continue;
412                    }
413                };
414                for file_entry in dir_entries {
415                    let file_entry = match file_entry {
416                        Ok(entry) => entry,
417                        Err(e) => {
418                            note_unreadable(&mut problems, &project_path, &e);
419                            continue;
420                        }
421                    };
422                    let file_path = file_entry.path();
423                    if file_path.extension().map_or(false, |e| e == "jsonl") {
424                        // Skip subagent files — those are children of sessions
425                        if file_path
426                            .parent()
427                            .and_then(|p| p.file_name())
428                            .map_or(false, |n| n == "subagents")
429                        {
430                            continue;
431                        }
432                        if let Some(meta) = metadata_or_note(&mut problems, &file_path) {
433                            let mtime = meta
434                                .modified()
435                                .ok()
436                                .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
437                                .map(|d| d.as_millis() as i64)
438                                .unwrap_or(0);
439                            files.push(DiscoveredFile {
440                                file_path: file_path.to_string_lossy().into(),
441                                mtime_ms: mtime,
442                            });
443                        }
444                    }
445                }
446            }
447        }
448
449        files.sort_by(|a, b| b.mtime_ms.cmp(&a.mtime_ms));
450        Ok(Discovery { files, problems })
451    }
452
453    fn extract_meta(&self, file_path: &str) -> Result<Option<SessionMeta>, HistoryError> {
454        let path = Path::new(file_path);
455        let file = fs::File::open(path)?;
456        let file_size = file.metadata()?.len();
457        let reader = BufReader::new(file);
458
459        let mut first_user_msg = String::new();
460        let mut model = "unknown".to_string();
461        let mut slug = String::new();
462        let mut cwd = String::new();
463        let mut git_branch = String::new();
464        let mut entry_count = 0u32;
465        let mut total_tokens: u64 = 0;
466        let mut first_timestamp: i64 = 0;
467        let mut last_timestamp: i64 = 0;
468        let mut starts_undated = false;
469        let mut session_id = String::new();
470
471        // Extract session_id from filename (stem)
472        if let Some(stem) = path.file_stem() {
473            session_id = stem.to_string_lossy().into();
474        }
475
476        let mut lines_iter = reader.lines();
477        let mut found_all_meta = false;
478
479        while let Some(Ok(line)) = lines_iter.next() {
480            if line.trim().is_empty() {
481                continue;
482            }
483
484            let entry: serde_json::Value = match serde_json::from_str(&line) {
485                Ok(v) => v,
486                Err(_) => continue,
487            };
488            entry_count += 1;
489
490            // Extract timestamp
491            if let Some(ts_str) = entry.get("timestamp").and_then(|v| v.as_str()) {
492                if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(ts_str) {
493                    let ts = dt.timestamp_millis();
494                    if first_timestamp == 0 {
495                        first_timestamp = ts;
496                    }
497                    last_timestamp = ts;
498                }
499            }
500
501            // Extract session slug
502            if slug.is_empty() {
503                if let Some(s) = entry.get("slug").and_then(|v| v.as_str()) {
504                    slug = s.to_string();
505                }
506            }
507
508            // Extract session ID from entry if available
509            if session_id.is_empty() {
510                if let Some(s) = entry.get("sessionId").and_then(|v| v.as_str()) {
511                    session_id = s.to_string();
512                }
513            }
514
515            // Extract cwd
516            if cwd.is_empty() {
517                if let Some(c) = entry.get("cwd").and_then(|v| v.as_str()) {
518                    cwd = c.to_string();
519                }
520            }
521
522            // Extract git branch
523            if git_branch.is_empty() {
524                if let Some(b) = entry.get("gitBranch").and_then(|v| v.as_str()) {
525                    git_branch = b.to_string();
526                }
527            }
528
529            let entry_type = entry.get("type").and_then(|v| v.as_str()).unwrap_or("");
530
531            // A conversation record before any dated one, itself undated:
532            // the session started no later than it, and nothing says when.
533            if first_timestamp == 0 && matches!(entry_type, "user" | "assistant") {
534                starts_undated = true;
535            }
536
537            // Extract model from first assistant entry
538            if model == "unknown" && entry_type == "assistant" {
539                if let Some(m) = entry.pointer("/message/model").and_then(|v| v.as_str()) {
540                    model = m.to_string();
541                }
542                // Accumulate tokens
543                if let Some(usage) = entry.pointer("/message/usage") {
544                    if let Some(out) = usage.get("output_tokens").and_then(|v| v.as_u64()) {
545                        total_tokens += out;
546                    }
547                }
548            } else if entry_type == "assistant" {
549                // Still accumulate tokens for non-first assistant entries
550                if let Some(usage) = entry.pointer("/message/usage") {
551                    if let Some(out) = usage.get("output_tokens").and_then(|v| v.as_u64()) {
552                        total_tokens += out;
553                    }
554                }
555            }
556
557            // Extract first user message for preview
558            if first_user_msg.is_empty() && entry_type == "user" {
559                if let Some(content) = entry.pointer("/message/content") {
560                    if let Some(text) = content.as_str() {
561                        first_user_msg = text.chars().take(200).collect();
562                    } else if let Some(arr) = content.as_array() {
563                        // Content can be an array of content blocks
564                        for block in arr {
565                            if block.get("type").and_then(|v| v.as_str()) == Some("text") {
566                                if let Some(text) = block.get("text").and_then(|v| v.as_str()) {
567                                    first_user_msg = text.chars().take(200).collect();
568                                    break;
569                                }
570                            }
571                        }
572                    }
573                }
574            }
575
576            // Early exit: once we have all metadata fields, count remaining lines cheaply
577            if !first_user_msg.is_empty()
578                && model != "unknown"
579                && !cwd.is_empty()
580                && !slug.is_empty()
581            {
582                found_all_meta = true;
583                break;
584            }
585        }
586
587        // Count remaining lines without parsing JSON (fast)
588        if found_all_meta {
589            for remaining_line in lines_iter {
590                if let Ok(line) = remaining_line {
591                    if !line.trim().is_empty() {
592                        entry_count += 1;
593                    }
594                }
595            }
596        }
597
598        if entry_count == 0 {
599            return Ok(None);
600        }
601
602        // Fallback: decode project path from parent directory name
603        if cwd.is_empty() {
604            if let Some(parent_name) = path
605                .parent()
606                .and_then(|p| p.file_name())
607                .map(|n| n.to_string_lossy().to_string())
608            {
609                cwd = Self::decode_project_path(&parent_name);
610            }
611        }
612
613        // Count subagents
614        let subagent_count = if let Some(parent) = path.parent() {
615            let session_dir = parent.join(&session_id);
616            Self::count_subagents(&session_dir)
617        } else {
618            0
619        };
620
621        let file_meta = fs::metadata(file_path)?;
622        let modified_at = file_meta
623            .modified()
624            .ok()
625            .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
626            .map(|d| d.as_millis() as i64)
627            .unwrap_or(last_timestamp);
628
629        Ok(Some(SessionMeta {
630            session_id,
631            file_path: file_path.to_string(),
632            provider: "claude".to_string(),
633            model,
634            slug,
635            working_directory: cwd,
636            created_at: first_timestamp,
637            modified_at,
638            message_count: entry_count,
639            first_user_message: first_user_msg,
640            file_size_bytes: file_size,
641            git_branch,
642            total_tokens,
643            subagent_count,
644            identity_id: Self::identity_id_from_path(path),
645            starts_undated,
646        }))
647    }
648
649    fn parse_file(&self, file_path: &str) -> Result<Option<HistorySession>, HistoryError> {
650        // First extract meta
651        let meta = match self.extract_meta(file_path)? {
652            Some(m) => m,
653            None => return Ok(None),
654        };
655
656        // Read whole, not line by line: a record that can't be read has to be
657        // counted rather than skipped in silence, and only the raw bytes say
658        // whether the last line is finished. The CLI appends while the agent
659        // runs, so an unterminated last line is an append in progress, not a
660        // damaged record.
661        let bytes = fs::read(file_path)?;
662        let ends_with_newline = bytes.last() == Some(&b'\n');
663        let lines: Vec<&[u8]> = bytes.split(|b| *b == b'\n').collect();
664        let last = lines.len() - 1;
665        let mut messages = Vec::new();
666        let mut skipped_records = 0u32;
667
668        for (i, line) in lines.into_iter().enumerate() {
669            if line.iter().all(u8::is_ascii_whitespace) {
670                continue;
671            }
672            let entry: serde_json::Value = match serde_json::from_slice(line) {
673                Ok(v) => v,
674                Err(_) => {
675                    let in_progress = i == last && !ends_with_newline;
676                    if !in_progress {
677                        skipped_records += 1;
678                    }
679                    continue;
680                }
681            };
682
683            // Extract timestamp
684            let timestamp = entry
685                .get("timestamp")
686                .and_then(|v| v.as_str())
687                .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
688                .map(|dt| dt.timestamp_millis())
689                .unwrap_or(0);
690
691            if let Some(message) = message_from_entry(&entry, timestamp) {
692                messages.push(message);
693            }
694        }
695
696        Ok(Some(HistorySession { meta, messages, skipped_records }))
697    }
698}
699
700#[cfg(test)]
701mod tests {
702    use super::*;
703    use std::collections::HashSet;
704
705    const USER_LINE: &str = r#"{"type":"user","message":{"role":"user","content":"deploy the fix"},"timestamp":"2026-09-24T10:00:00Z","cwd":"/work/a"}"#;
706    const ASSISTANT_LINE: &str = r#"{"type":"assistant","message":{"role":"assistant","model":"m","content":[{"type":"text","text":"deployed"}]},"timestamp":"2026-09-24T10:00:05Z","cwd":"/work/a"}"#;
707
708    fn parse(content: &str) -> HistorySession {
709        let tmp = tempfile::TempDir::new().unwrap();
710        let file = tmp.path().join("s.jsonl");
711        fs::write(&file, content).unwrap();
712        ClaudeHistoryAdapter::with_roots(None, None, None)
713            .parse_file(&file.to_string_lossy())
714            .unwrap()
715            .unwrap()
716    }
717
718    /// A record that can't be parsed used to be skipped in silence, so a
719    /// search counted the session as fully read and could call a word that
720    /// appeared only in that record definitively absent (Codex P1 on #3693).
721    #[test]
722    fn a_malformed_record_is_counted_not_silently_skipped() {
723        let session = parse(&format!("{USER_LINE}\n{{\"type\":\"assistant\",\"mess\n{ASSISTANT_LINE}\n"));
724        assert_eq!(session.messages.len(), 2);
725        assert_eq!(session.skipped_records, 1);
726    }
727
728    /// The CLI appends while the agent runs, so a live session's last line
729    /// may be half-written when it's read. That's not corruption — counting
730    /// it would make every search that includes the searcher's own session
731    /// incomplete.
732    #[test]
733    fn an_unterminated_last_line_is_an_append_in_progress_not_corruption() {
734        let session = parse(&format!("{USER_LINE}\n{{\"type\":\"assistant\",\"message\":{{\"con"));
735        assert_eq!(session.messages.len(), 1);
736        assert_eq!(session.skipped_records, 0);
737    }
738
739    /// An account with no Claude home yet, or a root that doesn't exist, is
740    /// nothing missed — only an unreadable directory is.
741    #[test]
742    fn a_missing_directory_is_not_a_discovery_problem() {
743        let tmp = tempfile::TempDir::new().unwrap();
744        let shared = tmp.path().join("shared");
745        fs::create_dir_all(shared.join("identities").join("bundle-without-claude")).unwrap();
746        let adapter = ClaudeHistoryAdapter::with_roots(
747            Some(tmp.path().join("no-such-user-home")),
748            Some(shared),
749            Some(tmp.path().join("no-such-agentmux-home")),
750        );
751        let found = adapter.discover().unwrap();
752        assert!(found.problems.is_empty(), "{:?}", found.problems);
753    }
754
755    /// A directory that exists but can't be read may hold the session being
756    /// searched for, so it's reported rather than skipped (Codex P1 on
757    /// #3693).
758    #[cfg(unix)]
759    #[test]
760    fn an_unreadable_project_directory_is_a_discovery_problem() {
761        use std::os::unix::fs::PermissionsExt;
762        let tmp = tempfile::TempDir::new().unwrap();
763        let shared = tmp.path().join("shared");
764        let project = shared.join("providers").join("claude").join("projects").join("-work-locked");
765        fs::create_dir_all(&project).unwrap();
766        fs::set_permissions(&project, fs::Permissions::from_mode(0o000)).unwrap();
767        let readable_anyway = fs::read_dir(&project).is_ok(); // root ignores modes
768        let found = ClaudeHistoryAdapter::with_roots(None, Some(shared), None).discover().unwrap();
769        fs::set_permissions(&project, fs::Permissions::from_mode(0o755)).unwrap();
770        if readable_anyway {
771            return;
772        }
773        assert!(found.problems.iter().any(|p| p.contains("-work-locked")), "{:?}", found.problems);
774    }
775
776    /// An account's home or a channel created after the adapter is built —
777    /// an account added or switched while srv runs — must still be found.
778    /// The adapter used to list these directories once, when srv started, so
779    /// a session under a later account's home stayed invisible until a restart: on
780    /// 2026-09-24 both of an agent's account homes post-dated srv start and
781    /// SearchHistory answered "no history" with `truncated: false`.
782    #[test]
783    fn a_bundle_created_after_the_adapter_is_built_is_discovered() {
784        let tmp = tempfile::TempDir::new().unwrap();
785        let shared = tmp.path().join("shared");
786        let agentmux_home = tmp.path().join("agentmux");
787        fs::create_dir_all(&shared).unwrap();
788        fs::create_dir_all(agentmux_home.join("channels")).unwrap();
789        let adapter = ClaudeHistoryAdapter::with_roots(
790            None,
791            Some(shared.clone()),
792            Some(agentmux_home.clone()),
793        );
794
795        let global = shared.join("identities").join("late-bundle").join("claude").join("projects").join("-work");
796        let channel = agentmux_home
797            .join("channels")
798            .join("late-channel")
799            .join("identities")
800            .join("channel-bundle")
801            .join("claude")
802            .join("projects")
803            .join("-work");
804        for dir in [&global, &channel] {
805            fs::create_dir_all(dir).unwrap();
806        }
807        fs::write(global.join("in-global-bundle.jsonl"), "{}\n").unwrap();
808        fs::write(channel.join("in-channel-bundle.jsonl"), "{}\n").unwrap();
809
810        let found: Vec<String> = adapter
811            .discover_files()
812            .unwrap()
813            .into_iter()
814            .map(|f| f.file_path)
815            .collect();
816        assert!(found.iter().any(|p| p.ends_with("in-global-bundle.jsonl")), "{found:?}");
817        assert!(found.iter().any(|p| p.ends_with("in-channel-bundle.jsonl")), "{found:?}");
818    }
819
820    #[test]
821    fn push_deduped_dir_skips_a_path_that_is_not_a_real_directory() {
822        let tmp = tempfile::TempDir::new().unwrap();
823        let mut dirs = Vec::new();
824        let mut seen = HashSet::new();
825        ClaudeHistoryAdapter::push_deduped_dir(&mut dirs, &mut seen, tmp.path().join("does-not-exist"));
826        assert!(dirs.is_empty());
827    }
828
829    #[test]
830    fn push_deduped_dir_pushes_a_real_directory_once() {
831        let tmp = tempfile::TempDir::new().unwrap();
832        let dir = tmp.path().join("real");
833        std::fs::create_dir_all(&dir).unwrap();
834        let mut dirs = Vec::new();
835        let mut seen = HashSet::new();
836        ClaudeHistoryAdapter::push_deduped_dir(&mut dirs, &mut seen, dir.clone());
837        ClaudeHistoryAdapter::push_deduped_dir(&mut dirs, &mut seen, dir);
838        assert_eq!(dirs.len(), 1, "calling twice with the identical path must not duplicate it");
839    }
840
841    // The actual motivating case: after Step 3
842    // (SPEC_AGENT_IDENTITY_HISTORY_PERSISTENCE_PROTOCOL_2026_08_16.md §4.1),
843    // an isolated account home's projects/ is a junction pointing at the exact
844    // global path this adapter also scans directly — without dedup by
845    // canonical path, every session under it would appear twice.
846    #[cfg(windows)]
847    #[test]
848    fn push_deduped_dir_treats_a_junction_and_its_target_as_the_same_entry() {
849        let tmp = tempfile::TempDir::new().unwrap();
850        let target = tmp.path().join("global").join("projects");
851        let link = tmp.path().join("isolated").join("projects");
852        agentmux_common::ensure_history_link(&link, &target).unwrap();
853
854        let mut dirs = Vec::new();
855        let mut seen = HashSet::new();
856        ClaudeHistoryAdapter::push_deduped_dir(&mut dirs, &mut seen, target.clone());
857        ClaudeHistoryAdapter::push_deduped_dir(&mut dirs, &mut seen, link);
858        assert_eq!(
859            dirs.len(),
860            1,
861            "the junction and its target must be recognized as the same physical location, not scanned twice"
862        );
863    }
864
865    #[test]
866    fn scan_isolated_identities_finds_a_channel_scoped_projects_dir_at_depth_one() {
867        let tmp = tempfile::TempDir::new().unwrap();
868        let projects = tmp
869            .path()
870            .join("local-main-abc123")
871            .join("identities")
872            .join("bundle-1")
873            .join("claude")
874            .join("projects");
875        std::fs::create_dir_all(&projects).unwrap();
876
877        let mut dirs = Vec::new();
878        let mut seen = HashSet::new();
879        ClaudeHistoryAdapter::scan_isolated_identities_under(tmp.path(), &mut dirs, &mut seen, 2, &mut Vec::new());
880        assert_eq!(dirs, vec![projects]);
881    }
882
883    #[test]
884    fn scan_isolated_identities_finds_a_dev_clone_scoped_projects_dir_at_depth_two() {
885        let tmp = tempfile::TempDir::new().unwrap();
886        let projects = tmp
887            .path()
888            .join("main")
889            .join("a1b2c3d4")
890            .join("identities")
891            .join("bundle-2")
892            .join("claude")
893            .join("projects");
894        std::fs::create_dir_all(&projects).unwrap();
895
896        let mut dirs = Vec::new();
897        let mut seen = HashSet::new();
898        ClaudeHistoryAdapter::scan_isolated_identities_under(tmp.path(), &mut dirs, &mut seen, 2, &mut Vec::new());
899        assert_eq!(dirs, vec![projects]);
900    }
901
902    #[test]
903    fn scan_isolated_identities_does_not_descend_past_max_depth() {
904        let tmp = tempfile::TempDir::new().unwrap();
905        // Three levels deep -- depth 2 must not find this.
906        let projects = tmp
907            .path()
908            .join("main")
909            .join("a1b2c3d4")
910            .join("extra-nesting")
911            .join("identities")
912            .join("bundle-3")
913            .join("claude")
914            .join("projects");
915        std::fs::create_dir_all(&projects).unwrap();
916
917        let mut dirs = Vec::new();
918        let mut seen = HashSet::new();
919        ClaudeHistoryAdapter::scan_isolated_identities_under(tmp.path(), &mut dirs, &mut seen, 2, &mut Vec::new());
920        assert!(dirs.is_empty(), "must not walk past the bounded depth");
921    }
922
923    #[test]
924    fn scan_isolated_identities_ignores_directories_with_no_identities_subdir() {
925        let tmp = tempfile::TempDir::new().unwrap();
926        std::fs::create_dir_all(tmp.path().join("some-channel").join("data")).unwrap();
927
928        let mut dirs = Vec::new();
929        let mut seen = HashSet::new();
930        ClaudeHistoryAdapter::scan_isolated_identities_under(tmp.path(), &mut dirs, &mut seen, 2, &mut Vec::new());
931        assert!(dirs.is_empty());
932    }
933}