mermaid-cli 0.14.1

Open-source AI pair programmer with agentic capabilities. Local-first with Ollama, native tool calling, and beautiful TUI.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
use crate::domain::CompactionArchive;
use crate::models::{ChatMessage, MessageRole};
use anyhow::Result;
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, VecDeque};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;

/// Reject a conversation id that doesn't match the generated shape
/// (`%Y%m%d_%H%M%S_%3f` => `YYYYMMDD_HHMMSS_mmm`). Without this, a
/// user-typed `/load <id>` (or `delete`) joins arbitrary text into a
/// filesystem path — `../../secret` would read/delete files outside the
/// project. Digits-and-underscores can't contain `/`, `\`, `..`, or a drive
/// prefix, so the format check alone closes the traversal.
fn validate_conversation_id(id: &str) -> Result<()> {
    let valid = id.len() == 19
        && id.as_bytes().iter().enumerate().all(|(i, b)| match i {
            8 | 15 => *b == b'_',
            _ => b.is_ascii_digit(),
        });
    anyhow::ensure!(valid, "invalid conversation id: {id:?}");
    Ok(())
}

/// Upper bound on a conversation file we'll read into memory (#129). A giant or
/// hostile `.mermaid/conversations/*.json` (or one with an enormous `content`)
/// would otherwise OOM the process — `--continue` walks every file. 64 MiB is
/// far above any real transcript yet bounds the worst case.
const MAX_CONVERSATION_BYTES: u64 = 64 * 1024 * 1024;

/// Read a conversation file with the [`MAX_CONVERSATION_BYTES`] cap enforced
/// *before* the bytes are pulled into RAM.
fn read_conversation_capped(path: &Path) -> std::io::Result<String> {
    let len = fs::metadata(path)?.len();
    if len > MAX_CONVERSATION_BYTES {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!(
                "conversation file {} is {len} bytes, over the {} MiB cap",
                path.display(),
                MAX_CONVERSATION_BYTES / (1024 * 1024)
            ),
        ));
    }
    fs::read_to_string(path)
}

/// Marker left in a message's text when its screenshot bytes are dropped on save.
const SCREENSHOT_ELIDED_MARKER: &str = "\n[screenshot not persisted]";

/// Return a sanitized copy of `messages` with computer-use screenshot bytes
/// removed before they reach durable storage (#99). Screenshots — which can
/// capture on-screen secrets — attach to **non-User** messages (the assistant
/// message the capture is routed onto, or a tool outcome); user-supplied
/// multimodal images attach to **User** messages and are intentional content,
/// so they're preserved. The live in-memory conversation is untouched (this
/// runs on a copy at the save chokepoint), so the chat and model context still
/// see the screenshot for the session — only the on-disk copy is scrubbed.
///
/// Returns `None` when nothing needed stripping, so the hot save path avoids a
/// clone in the common (no-screenshot) case.
fn strip_persisted_screenshots(messages: &[ChatMessage]) -> Option<Vec<ChatMessage>> {
    let needs = messages
        .iter()
        .any(|m| m.role != MessageRole::User && m.images.is_some());
    if !needs {
        return None;
    }
    let mut out = messages.to_vec();
    for m in out.iter_mut() {
        if m.role != MessageRole::User && m.images.is_some() {
            m.images = None;
            if !m.content.ends_with(SCREENSHOT_ELIDED_MARKER) {
                m.content.push_str(SCREENSHOT_ELIDED_MARKER);
            }
        }
    }
    Some(out)
}

/// A complete conversation history
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConversationHistory {
    pub id: String,
    pub title: String,
    pub messages: Vec<ChatMessage>,
    pub model_name: String,
    pub project_path: String,
    pub created_at: DateTime<Local>,
    pub updated_at: DateTime<Local>,
    pub total_tokens: Option<usize>,
    /// Metadata for context compactions performed in this conversation.
    #[serde(default)]
    pub compactions: Vec<crate::domain::CompactionRecord>,
    /// History of user input prompts for navigation (up/down arrows)
    #[serde(default)]
    pub input_history: VecDeque<String>,
}

impl ConversationHistory {
    /// Create a new conversation history.
    ///
    /// `now` is injected rather than read from the wall clock because this
    /// runs inside the pure reducer (`/clear` mints a fresh conversation, and
    /// `State::new` mints the initial one): the id and title are a
    /// deterministic function of the caller's clock, so `--replay` reproduces
    /// them exactly.
    pub fn new(project_path: String, model_name: String, now: DateTime<Local>) -> Self {
        // Include subsecond precision to avoid ID collisions within the same second
        let id = format!("{}", now.format("%Y%m%d_%H%M%S_%3f"));
        Self {
            id: id.clone(),
            title: format!("Session {}", now.format("%Y-%m-%d %H:%M")),
            messages: Vec::new(),
            model_name,
            project_path,
            created_at: now,
            updated_at: now,
            total_tokens: None,
            compactions: Vec::new(),
            input_history: VecDeque::new(),
        }
    }

    /// Add messages to the conversation. `now` is the caller's injected
    /// clock (`state.now` inside the reducer) — mutation methods never read
    /// the wall clock themselves so `update()` stays a pure function.
    pub fn add_messages(&mut self, messages: &[ChatMessage], now: DateTime<Local>) {
        self.messages.extend_from_slice(messages);
        self.updated_at = now;
        self.update_title();
    }

    /// Replace the model-visible message log without deriving a new title.
    /// Used by context compaction: the original title still describes the
    /// session better than the generated checkpoint. The messages keep their
    /// own timestamps (they rode in on the `Msg` payload); only `updated_at`
    /// is stamped, from the injected clock.
    pub fn replace_messages(&mut self, messages: Vec<ChatMessage>, now: DateTime<Local>) {
        self.messages = messages;
        self.updated_at = now;
    }

    /// Record a completed context compaction. `now` injected — see
    /// [`Self::add_messages`].
    pub fn add_compaction(
        &mut self,
        record: crate::domain::CompactionRecord,
        now: DateTime<Local>,
    ) {
        self.compactions.push(record);
        self.updated_at = now;
    }

    /// Add input to history (with deduplication of consecutive identical inputs)
    pub fn add_to_input_history(&mut self, input: String) {
        // Skip empty inputs
        if input.trim().is_empty() {
            return;
        }

        // Don't add if it's identical to the last entry
        if let Some(last) = self.input_history.back()
            && last == &input
        {
            return;
        }

        // Cap history at 100 entries to prevent unbounded growth
        if self.input_history.len() >= 100 {
            self.input_history.pop_front(); // O(1) instead of O(n)
        }

        self.input_history.push_back(input);
    }

    /// Update the title based on the first user message.
    /// Short-circuits if the title was already derived from a user message.
    fn update_title(&mut self) {
        // Only set title once — it comes from the first user message
        if !self.title.starts_with("Session ") {
            return;
        }
        if let Some(first_user_msg) = self.messages.iter().find(|m| m.role == MessageRole::User) {
            let preview = if first_user_msg.content.len() > 60 {
                let end = first_user_msg.content.floor_char_boundary(60);
                format!("{}...", &first_user_msg.content[..end])
            } else {
                first_user_msg.content.clone()
            };
            self.title = preview;
        }
    }

    /// Get a summary for display
    pub fn summary(&self) -> String {
        let message_count = self.messages.len();
        let duration = self.updated_at.signed_duration_since(self.created_at);
        let hours = duration.num_hours();
        let minutes = duration.num_minutes() % 60;

        format!(
            "{} | {} messages | {}h {}m | {}",
            self.updated_at.format("%Y-%m-%d %H:%M"),
            message_count,
            hours,
            minutes,
            self.title
        )
    }
}

/// Cheap fingerprint of a file on disk used for optimistic-concurrency
/// detection (F73): an `(mtime, len)` pair. A concurrent writer that rewrites a
/// conversation almost always changes the length (different message count) and
/// the mtime, so a mismatch against the value captured at load/last-save flags
/// the clobber without parsing the file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct FileStamp {
    mtime: SystemTime,
    len: u64,
}

/// Stat `path` into a [`FileStamp`]. `None` when the file is absent/unreadable.
fn file_stamp(path: &Path) -> Option<FileStamp> {
    let meta = fs::metadata(path).ok()?;
    let mtime = meta.modified().ok()?;
    Some(FileStamp {
        mtime,
        len: meta.len(),
    })
}

/// Process-unique counter for `.conflict` sibling filenames so two conflicts on
/// the same id within one process don't collide.
static CONFLICT_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Manages conversation persistence for a project
#[derive(Clone)]
pub struct ConversationManager {
    conversations_dir: PathBuf,
    compactions_dir: PathBuf,
    /// Per-id `(mtime, len)` of the conversation file as THIS process last
    /// observed it — recorded at load and after each of our own saves. Used to
    /// detect a concurrent writer before `save_conversation` overwrites (F73).
    /// Shared across clones of the manager (same process) via the `Arc`, so a
    /// cloned manager sees the same baselines; separate processes have separate
    /// maps, which is exactly the cross-process clobber we want to catch.
    seen: Arc<Mutex<HashMap<String, FileStamp>>>,
}

impl ConversationManager {
    /// Create a new conversation manager for a project directory
    pub fn new(project_dir: impl AsRef<Path>) -> Result<Self> {
        let mermaid_dir = project_dir.as_ref().join(".mermaid");
        let conversations_dir = mermaid_dir.join("conversations");
        let compactions_dir = mermaid_dir.join("compactions");

        // Create conversations directory if it doesn't exist
        fs::create_dir_all(&conversations_dir)?;
        fs::create_dir_all(&compactions_dir)?;

        Ok(Self {
            conversations_dir,
            compactions_dir,
            seen: Arc::new(Mutex::new(HashMap::new())),
        })
    }

    /// Record the on-disk `(mtime, len)` of `path` as the baseline for `id`, so a
    /// later `save_conversation` can tell whether a concurrent writer touched the
    /// file since we read or wrote it (F73). Called on load and after our own
    /// saves. Best-effort: an unreadable file simply leaves no baseline.
    fn record_stamp(&self, id: &str, path: &Path) {
        if let Some(stamp) = file_stamp(path) {
            self.seen
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .insert(id.to_string(), stamp);
        }
    }

    /// Path of a `.conflict` sibling for `id`. Deliberately ends in `.conflict`
    /// (not `.json`) so it never shows up in `list_conversations` /
    /// `load_last_conversation`, which only consider `*.json`. `id` is validated
    /// by the caller before this runs, so the filename can't traverse.
    fn conflict_sibling_path(&self, id: &str) -> PathBuf {
        let n = CONFLICT_COUNTER.fetch_add(1, Ordering::Relaxed);
        self.conversations_dir
            .join(format!("{}.{}.{}.conflict", id, std::process::id(), n))
    }

    /// Save a conversation to disk
    pub fn save_conversation(&self, conversation: &ConversationHistory) -> Result<()> {
        // The id field is persisted and round-trips through (potentially
        // tampered) on-disk state; validate it before it drives the write path,
        // so a loaded conversation can't escape the conversations dir on save.
        validate_conversation_id(&conversation.id)?;
        let filename = format!("{}.json", conversation.id);
        let path = self.conversations_dir.join(filename);

        // Strip computer-use screenshot bytes before they hit disk (#99). Only
        // clones the conversation when there is actually something to scrub.
        let json = match strip_persisted_screenshots(&conversation.messages) {
            Some(sanitized) => {
                let mut redacted = conversation.clone();
                redacted.messages = sanitized;
                serde_json::to_string_pretty(&redacted)?
            },
            None => serde_json::to_string_pretty(conversation)?,
        };

        // Optimistic-concurrency guard (F73). Without this, two processes (e.g. a
        // daemon `run` and an interactive session) saving the same id do blind
        // last-writer-wins and silently clobber each other. If the file on disk
        // changed since we last read or wrote it — a concurrent writer — don't
        // overwrite: preserve our copy in a `.conflict` sibling and warn. The
        // baseline is per-process (`seen`), recorded at load and after our own
        // saves, so our OWN repeated saves don't false-positive.
        let baseline = self
            .seen
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .get(&conversation.id)
            .copied();
        if let (Some(current), Some(base)) = (file_stamp(&path), baseline)
            && current != base
        {
            let sibling = self.conflict_sibling_path(&conversation.id);
            // Keep the existing atomic-write for the preserved copy too.
            crate::runtime::write_atomic(&sibling, json.as_bytes())?;
            tracing::warn!(
                id = %conversation.id,
                main = %path.display(),
                conflict = %sibling.display(),
                "conversation changed on disk since load (concurrent writer); wrote our copy to a .conflict sibling instead of overwriting"
            );
            return Ok(());
        }

        // Atomic write: a crash mid-save must not empty/corrupt the session
        // file (this is the hot path, rewritten after nearly every message).
        crate::runtime::write_atomic(&path, json.as_bytes())?;
        // Refresh our baseline to the file we just wrote so the NEXT save by this
        // process compares against our own write, not the pre-save state.
        self.record_stamp(&conversation.id, &path);

        Ok(())
    }

    /// Save the raw messages removed by a compaction. Archives live
    /// outside the hot conversation JSON so `/load` and `/list` don't
    /// parse old transcripts on every startup.
    pub fn save_compaction_archive(&self, archive: &CompactionArchive) -> Result<PathBuf> {
        // Both the conversation id (a directory component) and the archive id
        // (a file component) come from persisted state and must not traverse.
        validate_conversation_id(&archive.conversation_id)?;
        anyhow::ensure!(
            !archive.id.is_empty()
                && !archive.id.contains(['/', '\\'])
                && !archive.id.contains(".."),
            "invalid compaction archive id: {:?}",
            archive.id
        );
        let dir = self.compactions_dir.join(&archive.conversation_id);
        fs::create_dir_all(&dir)?;
        let path = dir.join(format!("{}.json", archive.id));
        // The archive is the only durable copy of compacted-out messages; scrub
        // screenshot bytes here too so they don't survive in compaction archives
        // (#99). Clones only when a screenshot is actually present.
        let json = match strip_persisted_screenshots(&archive.messages) {
            Some(sanitized) => {
                let mut redacted = archive.clone();
                redacted.messages = sanitized;
                serde_json::to_string_pretty(&redacted)?
            },
            None => serde_json::to_string_pretty(archive)?,
        };
        // Atomic write: the archive is the ONLY durable copy of messages
        // dropped by a compaction — a partial write would lose them.
        crate::runtime::write_atomic(&path, json.as_bytes())?;
        Ok(path)
    }

    /// Load a specific conversation by ID
    pub fn load_conversation(&self, id: &str) -> Result<ConversationHistory> {
        validate_conversation_id(id)?;
        let filename = format!("{}.json", id);
        let path = self.conversations_dir.join(filename);

        let json = read_conversation_capped(&path)?;
        let conversation: ConversationHistory = serde_json::from_str(&json)?;
        // The file name was validated, but the deserialized `id` (which drives
        // later saves) is independent on-disk state — validate it too.
        validate_conversation_id(&conversation.id)?;

        // Capture the load-time baseline so a later save can detect a concurrent
        // writer that touched this file in between (F73).
        self.record_stamp(&conversation.id, &path);

        Ok(conversation)
    }

    /// Load the most recent *valid* conversation.
    ///
    /// Iterates files newest-first by mtime and returns the first that reads,
    /// parses, and has a valid id — skipping (with a warning) any unreadable,
    /// unparseable, or traversing-id file. Mirrors `list_conversations`'s
    /// tolerance so one corrupt/partial file (e.g. a crash mid-write) can't make
    /// `--continue` hard-fail; it falls back to the next-newest valid conversation.
    pub fn load_last_conversation(&self) -> Result<Option<ConversationHistory>> {
        let Ok(entries) = fs::read_dir(&self.conversations_dir) else {
            return Ok(None);
        };

        let mut candidates: Vec<(std::time::SystemTime, PathBuf)> = entries
            .flatten()
            .filter(|e| e.path().extension().is_some_and(|x| x == "json"))
            .filter_map(|e| {
                let mtime = e.metadata().ok()?.modified().ok()?;
                Some((mtime, e.path()))
            })
            .collect();
        candidates.sort_by_key(|(mtime, _)| std::cmp::Reverse(*mtime));

        for (_, path) in candidates {
            let Ok(json) = read_conversation_capped(&path) else {
                tracing::warn!(path = %path.display(), "skipping unreadable or oversized conversation file");
                continue;
            };
            let Ok(conv) = serde_json::from_str::<ConversationHistory>(&json) else {
                tracing::warn!(path = %path.display(), "skipping unparseable conversation file");
                continue;
            };
            // A planted session file with a traversing `id` must not become the
            // resumed conversation (its id would later drive an out-of-dir save).
            if validate_conversation_id(&conv.id).is_err() {
                tracing::warn!(path = %path.display(), id = %conv.id, "skipping conversation with invalid id");
                continue;
            }
            // Capture the load-time baseline for the optimistic-concurrency
            // guard so a later save can detect a concurrent writer (F73).
            self.record_stamp(&conv.id, &path);
            return Ok(Some(conv));
        }
        Ok(None)
    }

    /// List all conversations in the project
    pub fn list_conversations(&self) -> Result<Vec<ConversationHistory>> {
        let mut conversations = Vec::new();

        // Read all JSON files in the conversations directory
        if let Ok(entries) = fs::read_dir(&self.conversations_dir) {
            for entry in entries.flatten() {
                if let Some(ext) = entry.path().extension()
                    && ext == "json"
                    && let Ok(json) = read_conversation_capped(&entry.path())
                    && let Ok(conv) = serde_json::from_str::<ConversationHistory>(&json)
                {
                    conversations.push(conv);
                }
            }
        }

        // Sort by updated_at (newest first)
        conversations.sort_by_key(|c| std::cmp::Reverse(c.updated_at));

        Ok(conversations)
    }

    /// Delete a conversation
    pub fn delete_conversation(&self, id: &str) -> Result<()> {
        validate_conversation_id(id)?;
        let filename = format!("{}.json", id);
        let path = self.conversations_dir.join(filename);

        if path.exists() {
            fs::remove_file(path)?;
        }

        Ok(())
    }

    /// Get the conversations directory path
    pub fn conversations_dir(&self) -> &Path {
        &self.conversations_dir
    }

    pub fn compactions_dir(&self) -> &Path {
        &self.compactions_dir
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn validate_conversation_id_rejects_traversal() {
        assert!(validate_conversation_id("20260101_120000_001").is_ok());
        assert!(validate_conversation_id("../secret").is_err());
        assert!(validate_conversation_id("..\\secret").is_err());
        assert!(validate_conversation_id("/etc/passwd").is_err());
        assert!(validate_conversation_id("20260101_120000").is_err()); // too short
        assert!(validate_conversation_id("abcdefgh_120000_001").is_err()); // non-digits
    }

    #[test]
    fn strip_persisted_screenshots_drops_assistant_images_keeps_user_images() {
        let messages = vec![
            ChatMessage::user("look at this").with_images(vec!["USER_PASTED_B64".to_string()]),
            ChatMessage::assistant("here is the screen")
                .with_images(vec!["SCREENSHOT_B64".to_string()]),
            ChatMessage::assistant("no image here"),
        ];
        let sanitized = strip_persisted_screenshots(&messages).expect("had a screenshot to strip");
        // User-supplied image preserved.
        assert_eq!(
            sanitized[0].images.as_deref(),
            Some(["USER_PASTED_B64".to_string()].as_slice())
        );
        // Assistant screenshot dropped + marker added.
        assert!(sanitized[1].images.is_none());
        assert!(sanitized[1].content.ends_with(SCREENSHOT_ELIDED_MARKER));
        // Untouched assistant message is unchanged (no spurious marker).
        assert!(!sanitized[2].content.ends_with(SCREENSHOT_ELIDED_MARKER));
    }

    #[test]
    fn strip_persisted_screenshots_is_none_without_assistant_images() {
        let messages = vec![
            ChatMessage::user("hi").with_images(vec!["USER_B64".to_string()]),
            ChatMessage::assistant("no images"),
        ];
        assert!(strip_persisted_screenshots(&messages).is_none());
    }

    #[test]
    fn saved_conversation_json_has_no_screenshot_bytes() {
        let dir = std::env::temp_dir().join("mermaid_strip_test");
        let _ = fs::create_dir_all(&dir);
        let mut conv = ConversationHistory::new("/tmp/p".into(), "m".into(), Local::now());
        conv.messages = vec![
            ChatMessage::user("u").with_images(vec!["USERIMG".to_string()]),
            ChatMessage::assistant("a").with_images(vec!["SHOTBYTES".to_string()]),
        ];
        let store = ConversationManager {
            conversations_dir: dir.clone(),
            compactions_dir: dir.clone(),
            seen: Arc::new(Mutex::new(HashMap::new())),
        };
        store.save_conversation(&conv).expect("save");
        let raw = fs::read_to_string(dir.join(format!("{}.json", conv.id))).expect("read");
        assert!(
            !raw.contains("SHOTBYTES"),
            "screenshot leaked to disk: {raw}"
        );
        assert!(raw.contains("USERIMG"), "user image should persist");
        // Live conversation untouched — still carries the screenshot in-session.
        assert_eq!(
            conv.messages[1].images.as_deref(),
            Some(["SHOTBYTES".to_string()].as_slice())
        );
        let _ = fs::remove_file(dir.join(format!("{}.json", conv.id)));
    }

    #[test]
    fn test_new_conversation_has_session_title() {
        let conv =
            ConversationHistory::new("/tmp/project".into(), "test-model".into(), Local::now());
        assert!(conv.title.starts_with("Session "));
        assert_eq!(conv.model_name, "test-model");
        assert_eq!(conv.project_path, "/tmp/project");
        assert!(conv.messages.is_empty());
    }

    #[test]
    fn test_title_updates_from_first_user_message() {
        let mut conv = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        conv.add_messages(&[ChatMessage::user("Fix the login bug")], Local::now());
        assert_eq!(conv.title, "Fix the login bug");
    }

    #[test]
    fn test_title_truncated_at_60_chars() {
        let mut conv = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        let long_msg = "a".repeat(100);
        conv.add_messages(&[ChatMessage::user(long_msg)], Local::now());
        assert!(conv.title.ends_with("..."));
        assert!(conv.title.len() <= 64); // 60 chars + "..."
    }

    #[test]
    fn test_title_set_only_once() {
        let mut conv = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        conv.add_messages(&[ChatMessage::user("First message")], Local::now());
        conv.add_messages(&[ChatMessage::user("Second message")], Local::now());
        assert_eq!(conv.title, "First message");
    }

    #[test]
    fn test_input_history_deduplication() {
        let mut conv = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        conv.add_to_input_history("hello".into());
        conv.add_to_input_history("hello".into()); // duplicate
        conv.add_to_input_history("world".into());
        assert_eq!(conv.input_history.len(), 2);
    }

    #[test]
    fn test_input_history_skips_empty() {
        let mut conv = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        conv.add_to_input_history("".into());
        conv.add_to_input_history("   ".into());
        assert_eq!(conv.input_history.len(), 0);
    }

    #[test]
    fn test_input_history_capped_at_100() {
        let mut conv = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        for i in 0..110 {
            conv.add_to_input_history(format!("msg{}", i));
        }
        assert_eq!(conv.input_history.len(), 100);
        assert_eq!(conv.input_history.front().unwrap(), "msg10");
    }

    #[test]
    fn test_save_load_roundtrip() {
        let dir = std::env::temp_dir().join("mermaid_test_conv_roundtrip");
        let _ = fs::remove_dir_all(&dir);
        let manager = ConversationManager::new(&dir).unwrap();

        let mut conv = ConversationHistory::new("/tmp".into(), "model".into(), Local::now());
        conv.add_messages(&[ChatMessage::user("test message")], Local::now());
        conv.add_to_input_history("test message".into());

        manager.save_conversation(&conv).unwrap();
        let loaded = manager.load_conversation(&conv.id).unwrap();

        assert_eq!(loaded.id, conv.id);
        assert_eq!(loaded.title, conv.title);
        assert_eq!(loaded.messages.len(), 1);
        assert_eq!(loaded.input_history.len(), 1);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_list_conversations_ordered_by_updated_at() {
        let dir = std::env::temp_dir().join("mermaid_test_conv_list");
        let _ = fs::remove_dir_all(&dir);
        let manager = ConversationManager::new(&dir).unwrap();

        let conv1 = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        std::thread::sleep(std::time::Duration::from_millis(10));
        let conv2 = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());

        manager.save_conversation(&conv1).unwrap();
        manager.save_conversation(&conv2).unwrap();

        let list = manager.list_conversations().unwrap();
        assert_eq!(list.len(), 2);
        // Newest first
        assert_eq!(list[0].id, conv2.id);
        assert_eq!(list[1].id, conv1.id);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_load_last_conversation() {
        let dir = std::env::temp_dir().join("mermaid_test_conv_last");
        let _ = fs::remove_dir_all(&dir);
        let manager = ConversationManager::new(&dir).unwrap();

        assert!(manager.load_last_conversation().unwrap().is_none());

        let conv = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        manager.save_conversation(&conv).unwrap();

        let last = manager.load_last_conversation().unwrap().unwrap();
        assert_eq!(last.id, conv.id);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_load_last_conversation_picks_newest_by_mtime() {
        // Writes three conversations with staggered mtimes (via sleeps
        // between saves) and asserts the mtime-based picker returns the
        // last one written — even though filename-alphabetical ordering
        // would pick a different file.
        let dir = std::env::temp_dir().join("mermaid_test_conv_mtime");
        let _ = fs::remove_dir_all(&dir);
        let manager = ConversationManager::new(&dir).unwrap();

        let conv1 = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        manager.save_conversation(&conv1).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));

        let conv2 = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        manager.save_conversation(&conv2).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));

        let conv3 = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        manager.save_conversation(&conv3).unwrap();

        let last = manager.load_last_conversation().unwrap().unwrap();
        assert_eq!(
            last.id, conv3.id,
            "should return the most-recently-written file"
        );

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_last_conversation_skips_corrupt_newest_falls_back_to_valid() {
        let dir = std::env::temp_dir().join("mermaid_test_conv_corrupt");
        let _ = fs::remove_dir_all(&dir);
        let manager = ConversationManager::new(&dir).unwrap();

        let good = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        manager.save_conversation(&good).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(10));

        // Plant a NEWER, corrupt file (well-formed name, garbage contents): the
        // newest-by-mtime entry is unparseable, so #68 must skip it.
        let corrupt = manager.conversations_dir().join("20991231_235959_999.json");
        fs::write(&corrupt, b"{ not valid json").unwrap();

        let last = manager.load_last_conversation().unwrap().unwrap();
        assert_eq!(
            last.id, good.id,
            "must fall back to the newest VALID conversation"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_last_conversation_none_when_only_corrupt() {
        let dir = std::env::temp_dir().join("mermaid_test_conv_only_corrupt");
        let _ = fs::remove_dir_all(&dir);
        let manager = ConversationManager::new(&dir).unwrap();
        fs::write(
            manager.conversations_dir().join("20991231_235959_998.json"),
            b"nope",
        )
        .unwrap();
        assert!(manager.load_last_conversation().unwrap().is_none());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_conversation_tolerates_unknown_message_role() {
        // F74: a conversation written by a NEWER build may carry a MessageRole
        // this build doesn't model. It must still load — the unknown role maps to
        // a neutral System message — so `--continue` doesn't silently skip the
        // newest session (the prior behavior, when the whole parse hard-failed).
        let dir =
            std::env::temp_dir().join(format!("mermaid_conv_role_skew_{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        let manager = ConversationManager::new(&dir).unwrap();

        let id = "20260101_120000_001";
        let json = format!(
            r#"{{
                "id": "{id}",
                "title": "skew",
                "messages": [
                    {{
                        "role": "Developer",
                        "content": "from a newer build",
                        "timestamp": "2026-01-01T12:00:00-04:00"
                    }}
                ],
                "model_name": "m",
                "project_path": "/tmp",
                "created_at": "2026-01-01T12:00:00-04:00",
                "updated_at": "2026-01-01T12:00:00-04:00",
                "total_tokens": null
            }}"#
        );
        fs::write(manager.conversations_dir().join(format!("{id}.json")), json).unwrap();

        let loaded = manager
            .load_conversation(id)
            .expect("must load despite an unknown role");
        assert_eq!(loaded.messages.len(), 1);
        assert_eq!(
            loaded.messages[0].role,
            MessageRole::System,
            "an unknown role becomes a neutral System message"
        );

        // And `--continue`'s newest-valid picker returns it instead of skipping.
        let last = manager
            .load_last_conversation()
            .unwrap()
            .expect("the newest session must load");
        assert_eq!(last.id, id);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_delete_conversation() {
        let dir = std::env::temp_dir().join("mermaid_test_conv_delete");
        let _ = fs::remove_dir_all(&dir);
        let manager = ConversationManager::new(&dir).unwrap();

        let conv = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        manager.save_conversation(&conv).unwrap();
        assert_eq!(manager.list_conversations().unwrap().len(), 1);

        manager.delete_conversation(&conv.id).unwrap();
        assert_eq!(manager.list_conversations().unwrap().len(), 0);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn read_conversation_capped_refuses_oversized_file() {
        // #129: a file over the cap is refused before it's read into RAM. Use a
        // sparse file so the test stays fast and doesn't actually write 64 MiB.
        let dir = std::env::temp_dir().join(format!("mermaid_conv_cap_{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();

        let small = dir.join("small.json");
        fs::write(&small, b"{}").unwrap();
        assert!(read_conversation_capped(&small).is_ok());

        let big = dir.join("big.json");
        let f = fs::File::create(&big).unwrap();
        f.set_len(MAX_CONVERSATION_BYTES + 1).unwrap();
        assert!(
            read_conversation_capped(&big).is_err(),
            "a file over the cap must be refused, not slurped into memory"
        );

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn save_conversation_detects_concurrent_writer_and_writes_conflict_sibling() {
        // F73: a daemon `run` and an interactive session can both hold the same
        // conversation id. Blind last-writer-wins silently drops one side's
        // edits. The optimistic-concurrency guard must detect the concurrent
        // write and preserve our copy in a `.conflict` sibling instead of
        // clobbering the other writer's file.
        let dir =
            std::env::temp_dir().join(format!("mermaid_conv_conflict_{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        let manager = ConversationManager::new(&dir).unwrap();

        let mut conv = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        conv.add_messages(&[ChatMessage::user("ours")], Local::now());
        manager.save_conversation(&conv).unwrap();
        let main = manager
            .conversations_dir()
            .join(format!("{}.json", conv.id));

        // A SEPARATE process (its own baseline map) loads the same conversation,
        // appends, and saves — growing the file. This is the concurrent writer.
        let other = ConversationManager::new(&dir).unwrap();
        let mut their_conv = other.load_conversation(&conv.id).unwrap();
        their_conv.add_messages(
            &[ChatMessage::user("theirs - extra content here")],
            Local::now(),
        );
        other.save_conversation(&their_conv).unwrap();

        // Our next save still holds the pre-concurrent baseline, so it must NOT
        // overwrite the other writer's file.
        manager.save_conversation(&conv).unwrap();
        let on_disk: ConversationHistory =
            serde_json::from_str(&fs::read_to_string(&main).unwrap()).unwrap();
        assert_eq!(
            on_disk.messages.len(),
            2,
            "the concurrent writer's file must be left intact"
        );

        // Our copy is preserved in exactly one `.conflict` sibling.
        let mut conflicts = fs::read_dir(manager.conversations_dir())
            .unwrap()
            .flatten()
            .filter(|e| e.file_name().to_string_lossy().ends_with(".conflict"))
            .map(|e| e.path())
            .collect::<Vec<_>>();
        assert_eq!(conflicts.len(), 1, "exactly one .conflict sibling expected");
        let sibling = fs::read_to_string(conflicts.pop().unwrap()).unwrap();
        assert!(
            sibling.contains("ours") && !sibling.contains("theirs"),
            "the .conflict sibling holds OUR copy, not the concurrent writer's"
        );

        // The `.conflict` sibling must not pollute the conversation listing
        // (it isn't a `*.json` file).
        let listed = manager.list_conversations().unwrap();
        assert_eq!(
            listed.len(),
            1,
            ".conflict sibling must not appear as a conversation"
        );
        assert_eq!(listed[0].id, conv.id);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn save_conversation_repeated_self_saves_do_not_conflict() {
        // The guard must not false-positive on a single process's OWN repeated
        // saves (the hot path rewrites the file after nearly every message).
        let dir =
            std::env::temp_dir().join(format!("mermaid_conv_self_save_{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        let manager = ConversationManager::new(&dir).unwrap();

        let mut conv = ConversationHistory::new("/tmp".into(), "m".into(), Local::now());
        conv.add_messages(&[ChatMessage::user("first")], Local::now());
        manager.save_conversation(&conv).unwrap();
        conv.add_messages(&[ChatMessage::user("second")], Local::now());
        manager.save_conversation(&conv).unwrap();

        let conflicts = fs::read_dir(manager.conversations_dir())
            .unwrap()
            .flatten()
            .filter(|e| e.file_name().to_string_lossy().ends_with(".conflict"))
            .count();
        assert_eq!(
            conflicts, 0,
            "our own repeated saves must not be flagged as conflicts"
        );
        let loaded = manager.load_conversation(&conv.id).unwrap();
        assert_eq!(loaded.messages.len(), 2, "latest save must win for us");

        let _ = fs::remove_dir_all(&dir);
    }
}