Skip to main content

atman_runtime/
session.rs

1use std::path::{Path, PathBuf};
2use std::sync::Mutex;
3
4use tokio::sync::{broadcast, watch};
5use tokio_util::sync::CancellationToken;
6use uuid::Uuid;
7
8use crate::event::{Event, EventSink, FlowRunId, TurnId};
9use crate::event_log::reader::{find_last_seq, replay_context_snapshot_from};
10use crate::event_writer::EventWriter;
11use crate::injection::{Injection, InjectionId, InjectionState};
12use crate::message::{Message, MessageRole};
13use crate::projection::message_window::{
14    TranscriptEntry, replay_all_messages_with_seq, replay_messages_from, replay_messages_with_seq,
15    replay_transcript_from,
16};
17use crate::stream::StreamFrame;
18
19#[derive(Debug, Clone, PartialEq, Eq, Hash)]
20pub struct SessionId(pub Uuid);
21
22impl SessionId {
23    pub fn now() -> Self {
24        Self(Uuid::new_v4())
25    }
26
27    pub fn parse(s: &str) -> Result<Self, uuid::Error> {
28        Uuid::parse_str(s).map(Self)
29    }
30}
31
32impl std::fmt::Display for SessionId {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        self.0.fmt(f)
35    }
36}
37
38type WatchKeepalive = (
39    watch::Receiver<ContextSnapshot>,
40    watch::Receiver<Option<String>>,
41    watch::Receiver<usize>,
42    watch::Receiver<Vec<crate::memory::todo::Todo>>,
43    watch::Receiver<Vec<crate::memory::plan::Plan>>,
44);
45
46#[derive(Debug)]
47pub struct TurnState {
48    pub current_turn: Mutex<Option<TurnId>>,
49    pub flow_cancel: Mutex<CancellationToken>,
50    pub streamed: std::sync::atomic::AtomicBool,
51}
52
53impl TurnState {
54    fn new() -> Self {
55        Self {
56            current_turn: Mutex::new(None),
57            flow_cancel: Mutex::new(CancellationToken::new()),
58            streamed: std::sync::atomic::AtomicBool::new(false),
59        }
60    }
61}
62
63pub struct WatchHub {
64    pub stream_tx: broadcast::Sender<StreamFrame>,
65    pub context: watch::Sender<ContextSnapshot>,
66    pub goal: watch::Sender<Option<String>>,
67    pub attach: watch::Sender<usize>,
68    pub todos: watch::Sender<Vec<crate::memory::todo::Todo>>,
69    pub plans: watch::Sender<Vec<crate::memory::plan::Plan>>,
70    _keepalive: WatchKeepalive,
71}
72
73pub struct CompactionState {
74    pub manual_pending: std::sync::atomic::AtomicBool,
75    pub last_input_tokens: std::sync::atomic::AtomicU64,
76    pub review_mode: Mutex<CompactReviewMode>,
77    pub lock: std::sync::Arc<tokio::sync::Mutex<()>>,
78}
79
80impl CompactionState {
81    fn new() -> Self {
82        Self {
83            manual_pending: std::sync::atomic::AtomicBool::new(false),
84            last_input_tokens: std::sync::atomic::AtomicU64::new(0),
85            review_mode: Mutex::new(CompactReviewMode::default()),
86            lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
87        }
88    }
89}
90
91pub struct InteractionServices {
92    pub approval: std::sync::Arc<ApprovalRegistry>,
93    pub compact_reviews: std::sync::Arc<CompactReviewRegistry>,
94    pub forms: std::sync::Arc<FormRegistry>,
95}
96
97impl InteractionServices {
98    fn new() -> Self {
99        Self {
100            approval: std::sync::Arc::new(ApprovalRegistry::new()),
101            compact_reviews: std::sync::Arc::new(CompactReviewRegistry::new()),
102            forms: std::sync::Arc::new(FormRegistry::new()),
103        }
104    }
105}
106
107pub struct Session {
108    id: SessionId,
109    dir: PathBuf,
110    writer: std::sync::Mutex<Option<EventWriter>>,
111    sink: EventSink,
112    message_stream: crate::message_stream::MessageStream,
113    messages: std::sync::Arc<std::sync::Mutex<Vec<Message>>>,
114    pub turn: TurnState,
115    pub watch: WatchHub,
116    pub compaction: CompactionState,
117    pub interactions: InteractionServices,
118    injection_queue: Mutex<Vec<Injection>>,
119    injection_tx: broadcast::Sender<Injection>,
120    last_image_user_msg: Mutex<Option<LastImageUserMsg>>,
121    read_files: std::sync::Arc<std::sync::Mutex<std::collections::HashSet<std::path::PathBuf>>>,
122    fs_access_mode: Mutex<Option<crate::fs_access::FsAccessMode>>,
123    project_index: Option<std::sync::Arc<crate::index::AnchorIndex>>,
124}
125
126#[derive(Debug, Clone)]
127pub struct PendingCompactReview {
128    pub review_id: String,
129    pub summary: String,
130    pub slice_preview: String,
131    pub slice_count: usize,
132    pub range_start: usize,
133    pub range_end: usize,
134    pub tokens_before: u64,
135    pub emitted_at: chrono::DateTime<chrono::Utc>,
136}
137
138#[derive(Debug, Clone)]
139pub enum CompactReviewDecision {
140    AcceptAsIs,
141    AcceptEdited { summary: String },
142    Reject,
143}
144
145pub struct CompactReviewRegistry {
146    entry: std::sync::Mutex<Option<CompactReviewEntry>>,
147    watch_tx: watch::Sender<Option<PendingCompactReview>>,
148}
149
150struct CompactReviewEntry {
151    pending: PendingCompactReview,
152    responder: tokio::sync::oneshot::Sender<CompactReviewDecision>,
153}
154
155impl Default for CompactReviewRegistry {
156    fn default() -> Self {
157        Self::new()
158    }
159}
160
161impl CompactReviewRegistry {
162    pub fn new() -> Self {
163        let (watch_tx, _) = watch::channel(None);
164        Self {
165            entry: std::sync::Mutex::new(None),
166            watch_tx,
167        }
168    }
169
170    pub fn subscribe(&self) -> watch::Receiver<Option<PendingCompactReview>> {
171        self.watch_tx.subscribe()
172    }
173
174    pub fn list_pending(&self) -> Option<PendingCompactReview> {
175        self.entry
176            .lock()
177            .unwrap()
178            .as_ref()
179            .map(|e| e.pending.clone())
180    }
181
182    pub fn subscriber_count(&self) -> usize {
183        self.watch_tx.receiver_count()
184    }
185
186    pub fn request(
187        &self,
188        pending: PendingCompactReview,
189    ) -> tokio::sync::oneshot::Receiver<CompactReviewDecision> {
190        let (tx, rx) = tokio::sync::oneshot::channel();
191        if self.watch_tx.receiver_count() == 0 {
192            let _ = tx.send(CompactReviewDecision::AcceptAsIs);
193            return rx;
194        }
195        {
196            let mut slot = self.entry.lock().unwrap();
197            if let Some(prev) = slot.take() {
198                let _ = prev.responder.send(CompactReviewDecision::Reject);
199            }
200            *slot = Some(CompactReviewEntry {
201                pending: pending.clone(),
202                responder: tx,
203            });
204        }
205        let _ = self.watch_tx.send(Some(pending));
206        rx
207    }
208
209    pub fn decide(&self, review_id: &str, decision: CompactReviewDecision) -> bool {
210        let entry = {
211            let mut slot = self.entry.lock().unwrap();
212            match slot.as_ref() {
213                Some(e) if e.pending.review_id == review_id => slot.take(),
214                _ => None,
215            }
216        };
217        match entry {
218            Some(e) => {
219                let _ = e.responder.send(decision);
220                let _ = self.watch_tx.send(None);
221                true
222            }
223            None => false,
224        }
225    }
226}
227
228#[derive(Debug, Clone)]
229pub struct PendingApproval {
230    pub tool_use_id: String,
231    pub tool_name: String,
232    pub args_preview: String,
233    pub preview: Option<String>,
234    pub level: crate::tool::ApprovalLevel,
235    pub run_id: FlowRunId,
236    pub emitted_at: chrono::DateTime<chrono::Utc>,
237    pub bypass_auto_ceiling: bool,
238}
239
240#[derive(Debug, Clone)]
241pub enum ApprovalDecision {
242    Approve,
243    Deny { reason: String },
244}
245
246pub struct FormRegistry {
247    entries: std::sync::Mutex<Vec<FormEntry>>,
248    watch_tx: watch::Sender<Vec<crate::form::PendingForm>>,
249}
250
251struct FormEntry {
252    pending: crate::form::PendingForm,
253    responder: tokio::sync::oneshot::Sender<crate::form::FormAnswer>,
254}
255
256impl Default for FormRegistry {
257    fn default() -> Self {
258        Self::new()
259    }
260}
261
262impl FormRegistry {
263    pub fn new() -> Self {
264        let (watch_tx, _) = watch::channel(Vec::new());
265        Self {
266            entries: std::sync::Mutex::new(Vec::new()),
267            watch_tx,
268        }
269    }
270
271    pub fn subscribe(&self) -> watch::Receiver<Vec<crate::form::PendingForm>> {
272        self.watch_tx.subscribe()
273    }
274
275    pub fn list_pending(&self) -> Vec<crate::form::PendingForm> {
276        self.entries
277            .lock()
278            .unwrap()
279            .iter()
280            .map(|e| e.pending.clone())
281            .collect()
282    }
283
284    pub fn subscriber_count(&self) -> usize {
285        self.watch_tx.receiver_count()
286    }
287
288    // No TUI attached → auto-cancel so flows don't hang forever. Otherwise
289    // enqueue and hand a receiver back to the caller.
290    pub fn request(
291        &self,
292        pending: crate::form::PendingForm,
293    ) -> tokio::sync::oneshot::Receiver<crate::form::FormAnswer> {
294        let (tx, rx) = tokio::sync::oneshot::channel();
295        if self.watch_tx.receiver_count() == 0 {
296            let _ = tx.send(crate::form::FormAnswer::Cancelled);
297            return rx;
298        }
299        {
300            let mut entries = self.entries.lock().unwrap();
301            entries.push(FormEntry {
302                pending: pending.clone(),
303                responder: tx,
304            });
305        }
306        self.broadcast_snapshot();
307        rx
308    }
309
310    pub fn submit(&self, form_id: &str, answer: crate::form::FormAnswer) -> bool {
311        let entry = {
312            let mut entries = self.entries.lock().unwrap();
313            let pos = entries.iter().position(|e| e.pending.form_id == form_id);
314            pos.map(|p| entries.remove(p))
315        };
316        match entry {
317            Some(e) => {
318                let _ = e.responder.send(answer);
319                self.broadcast_snapshot();
320                true
321            }
322            None => false,
323        }
324    }
325
326    pub fn cancel_all(&self) {
327        let drained: Vec<FormEntry> = {
328            let mut entries = self.entries.lock().unwrap();
329            std::mem::take(&mut *entries)
330        };
331        for e in drained {
332            let _ = e.responder.send(crate::form::FormAnswer::Cancelled);
333        }
334        self.broadcast_snapshot();
335    }
336
337    pub fn promote(&self, form_id: &str) {
338        let mut entries = self.entries.lock().unwrap();
339        if let Some(pos) = entries.iter().position(|e| e.pending.form_id == form_id) {
340            if pos == 0 {
341                return;
342            }
343            let entry = entries.remove(pos);
344            entries.insert(0, entry);
345        }
346        drop(entries);
347        self.broadcast_snapshot();
348    }
349
350    fn broadcast_snapshot(&self) {
351        let snap = self
352            .entries
353            .lock()
354            .unwrap()
355            .iter()
356            .map(|e| e.pending.clone())
357            .collect();
358        let _ = self.watch_tx.send(snap);
359    }
360}
361
362pub struct ApprovalRegistry {
363    entries: std::sync::Mutex<Vec<ApprovalEntry>>,
364    auto_ceiling: std::sync::Mutex<crate::tool::ApprovalLevel>,
365    watch_tx: watch::Sender<Vec<PendingApproval>>,
366}
367
368struct ApprovalEntry {
369    pending: PendingApproval,
370    responder: tokio::sync::oneshot::Sender<ApprovalDecision>,
371}
372
373impl Default for ApprovalRegistry {
374    fn default() -> Self {
375        Self::new()
376    }
377}
378
379impl ApprovalRegistry {
380    pub fn new() -> Self {
381        let (watch_tx, _) = watch::channel(Vec::new());
382        Self {
383            entries: std::sync::Mutex::new(Vec::new()),
384            auto_ceiling: std::sync::Mutex::new(crate::tool::ApprovalLevel::Approve),
385            watch_tx,
386        }
387    }
388
389    pub fn subscribe(&self) -> watch::Receiver<Vec<PendingApproval>> {
390        self.watch_tx.subscribe()
391    }
392
393    pub fn list_pending(&self) -> Vec<PendingApproval> {
394        self.entries
395            .lock()
396            .unwrap()
397            .iter()
398            .map(|e| e.pending.clone())
399            .collect()
400    }
401
402    pub fn set_auto_ceiling(&self, level: crate::tool::ApprovalLevel) {
403        *self.auto_ceiling.lock().unwrap() = level;
404    }
405
406    pub fn request(
407        &self,
408        pending: PendingApproval,
409    ) -> tokio::sync::oneshot::Receiver<ApprovalDecision> {
410        let (tx, rx) = tokio::sync::oneshot::channel();
411        if !pending.bypass_auto_ceiling && pending.level <= *self.auto_ceiling.lock().unwrap() {
412            let _ = tx.send(ApprovalDecision::Approve);
413            return rx;
414        }
415        {
416            let mut entries = self.entries.lock().unwrap();
417            entries.push(ApprovalEntry {
418                pending,
419                responder: tx,
420            });
421        }
422        self.broadcast_snapshot();
423        rx
424    }
425
426    pub fn decide(&self, tool_use_id: &str, decision: ApprovalDecision) -> bool {
427        let mut entries = self.entries.lock().unwrap();
428        if let Some(pos) = entries
429            .iter()
430            .position(|e| e.pending.tool_use_id == tool_use_id)
431        {
432            let entry = entries.remove(pos);
433            let _ = entry.responder.send(decision);
434            drop(entries);
435            self.broadcast_snapshot();
436            true
437        } else {
438            false
439        }
440    }
441
442    pub fn decide_all(&self, decision: ApprovalDecision) -> usize {
443        let mut entries = self.entries.lock().unwrap();
444        let count = entries.len();
445        for entry in entries.drain(..) {
446            let _ = entry.responder.send(decision.clone());
447        }
448        drop(entries);
449        self.broadcast_snapshot();
450        count
451    }
452
453    fn broadcast_snapshot(&self) {
454        let snapshot = self
455            .entries
456            .lock()
457            .unwrap()
458            .iter()
459            .map(|e| e.pending.clone())
460            .collect();
461        let _ = self.watch_tx.send(snapshot);
462    }
463}
464type ImagePart = (usize, String);
465
466#[derive(Debug, Clone)]
467struct LastImageUserMsg {
468    message_seq: u64,
469    images: Vec<ImagePart>,
470}
471
472#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
473pub enum CompactReviewMode {
474    Always,
475    #[default]
476    ManualOnly,
477    Never,
478}
479
480impl CompactReviewMode {
481    pub fn parse(s: &str) -> Option<Self> {
482        match s.trim() {
483            "always" => Some(Self::Always),
484            "manual-only" | "manual_only" => Some(Self::ManualOnly),
485            "never" => Some(Self::Never),
486            _ => None,
487        }
488    }
489
490    pub fn should_review(self, forced: bool) -> bool {
491        match self {
492            Self::Always => true,
493            Self::ManualOnly => forced,
494            Self::Never => false,
495        }
496    }
497}
498
499#[derive(Debug, Clone, PartialEq, Eq)]
500pub struct CompactResult {
501    pub before_tokens: u64,
502    pub after_tokens: u64,
503    pub compacted_start: usize,
504    pub compacted_end: usize,
505}
506
507#[derive(Debug, Clone, Default, PartialEq)]
508pub struct ContextSnapshot {
509    pub model: String,
510    pub tokens_in: u64,
511    pub tokens_out: u64,
512    pub cost_usd: f64,
513    pub mcp_servers: Vec<crate::mcp::McpServerStatus>,
514    pub memory_recent_count: u16,
515    pub window_tokens: u64,
516    pub window_budget: u64,
517    pub cache_read: u64,
518    pub cache_write: u64,
519    pub last_ttft_ms: u64,
520    pub last_tokens_per_sec: f64,
521}
522
523#[derive(Debug, thiserror::Error)]
524pub enum SessionOpenError {
525    #[error("invalid session id `{sid}` (want a UUID)")]
526    InvalidId { sid: String },
527    #[error("session `{sid}` not found at {}", dir.display())]
528    NotFound { sid: String, dir: PathBuf },
529    #[error("session writer init: {0}")]
530    WriterInit(#[source] std::io::Error),
531    #[error("replay {}: {source}", path.display())]
532    Replay {
533        path: PathBuf,
534        #[source]
535        source: std::io::Error,
536    },
537}
538
539fn load_goal(dir: &Path) -> Option<String> {
540    if dir.as_os_str().is_empty() {
541        return None;
542    }
543    let store = crate::memory::goal::GoalStore::at(dir);
544    match store.get() {
545        Ok(s) if !s.is_empty() => Some(s),
546        _ => None,
547    }
548}
549
550fn default_project_index(root: &Path) -> Option<std::sync::Arc<crate::index::AnchorIndex>> {
551    match crate::index::AnchorIndex::open_project(root) {
552        Ok(idx) => Some(std::sync::Arc::new(idx)),
553        Err(e) => {
554            crate::notify!(
555                warn,
556                "project index unavailable at {} — history search disabled: {e}",
557                root.display()
558            );
559            None
560        }
561    }
562}
563
564impl Session {
565    pub fn open(root: impl AsRef<Path>) -> std::io::Result<Self> {
566        Self::open_with_redactor(root, None)
567    }
568
569    pub fn open_with_redactor(
570        root: impl AsRef<Path>,
571        redactor: Option<std::sync::Arc<crate::redact::Redactor>>,
572    ) -> std::io::Result<Self> {
573        let root_ref = root.as_ref();
574        let project_index = default_project_index(root_ref);
575        Self::open_with_context(root_ref, redactor, project_index)
576    }
577
578    pub fn open_with_context(
579        root: impl AsRef<Path>,
580        redactor: Option<std::sync::Arc<crate::redact::Redactor>>,
581        project_index: Option<std::sync::Arc<crate::index::AnchorIndex>>,
582    ) -> std::io::Result<Self> {
583        let id = SessionId::now();
584        let dir = root.as_ref().join("sessions").join(id.to_string());
585        if let Some(ls) = crate::notify::log_sink() {
586            ls.set_session_id(Some(id.to_string()));
587        }
588        let writer = EventWriter::spawn_full(
589            &dir,
590            redactor.clone(),
591            project_index.clone(),
592            Some(id.to_string()),
593        )?;
594        if let Err(e) = crate::session_meta::SessionMeta::from_cwd().save(&dir) {
595            crate::notify!(error, "session meta write failed: {e}");
596        }
597        let mut sink = EventSink::new().with_forwarder(writer.sender());
598        if let Some(r) = redactor {
599            sink = sink.with_redactor(r);
600        }
601        let (injection_tx, _) = broadcast::channel(32);
602        let (stream_tx, _) = broadcast::channel(1024);
603        let (context_watch, context_rx) = watch::channel(ContextSnapshot::default());
604        let (goal_watch, goal_rx) = watch::channel(None);
605        let (attach_watch, attach_rx) = watch::channel(0);
606        let (todos_watch, todos_rx) = watch::channel(Vec::new());
607        let (plans_watch, plans_rx) = watch::channel(Vec::new());
608        let events_handle = sink.events_handle();
609        Ok(Self {
610            id,
611            dir,
612            writer: std::sync::Mutex::new(Some(writer)),
613            sink,
614            message_stream: crate::message_stream::MessageStream::new(events_handle),
615            messages: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
616            turn: TurnState::new(),
617            watch: WatchHub {
618                stream_tx,
619                context: context_watch,
620                goal: goal_watch,
621                attach: attach_watch,
622                todos: todos_watch,
623                plans: plans_watch,
624                _keepalive: (context_rx, goal_rx, attach_rx, todos_rx, plans_rx),
625            },
626            compaction: CompactionState::new(),
627            interactions: InteractionServices::new(),
628            injection_queue: Mutex::new(Vec::new()),
629            injection_tx,
630            last_image_user_msg: Mutex::new(None),
631            read_files: std::sync::Arc::new(
632                std::sync::Mutex::new(std::collections::HashSet::new()),
633            ),
634            fs_access_mode: Mutex::new(None),
635            project_index,
636        })
637    }
638
639    pub fn open_existing(root: impl AsRef<Path>, sid: &str) -> Result<Self, SessionOpenError> {
640        Self::open_existing_with_redactor(root, sid, None)
641    }
642
643    pub fn open_existing_with_redactor(
644        root: impl AsRef<Path>,
645        sid: &str,
646        redactor: Option<std::sync::Arc<crate::redact::Redactor>>,
647    ) -> Result<Self, SessionOpenError> {
648        let project_index = default_project_index(root.as_ref());
649        Self::open_existing_with_context(root, sid, redactor, project_index)
650    }
651
652    pub fn open_existing_with_context(
653        root: impl AsRef<Path>,
654        sid: &str,
655        redactor: Option<std::sync::Arc<crate::redact::Redactor>>,
656        project_index: Option<std::sync::Arc<crate::index::AnchorIndex>>,
657    ) -> Result<Self, SessionOpenError> {
658        let id = SessionId::parse(sid).map_err(|_| SessionOpenError::InvalidId {
659            sid: sid.to_string(),
660        })?;
661        let dir = root.as_ref().join("sessions").join(id.to_string());
662        if let Some(ls) = crate::notify::log_sink() {
663            ls.set_session_id(Some(id.to_string()));
664        }
665        if !dir.exists() {
666            return Err(SessionOpenError::NotFound {
667                sid: sid.to_string(),
668                dir: dir.clone(),
669            });
670        }
671        let writer = EventWriter::spawn_full(
672            &dir,
673            redactor.clone(),
674            project_index.clone(),
675            Some(id.to_string()),
676        )
677        .map_err(SessionOpenError::WriterInit)?;
678        let mut sink = EventSink::new().with_forwarder(writer.sender());
679        if let Some(r) = redactor {
680            sink = sink.with_redactor(r);
681        }
682        let events_path = dir.join("events.jsonl");
683        let messages = replay_messages_from(&events_path)?;
684        let initial_msgs = replay_messages_with_seq(&events_path)?;
685        let all_msgs = replay_all_messages_with_seq(&events_path)?;
686        if let Some(last_seq) = find_last_seq(&events_path)? {
687            sink.restore_seq(last_seq);
688        }
689        let mut initial_context = replay_context_snapshot_from(&events_path);
690        initial_context.window_tokens = crate::compaction::estimate_tokens_for_messages(&messages);
691        initial_context.window_budget =
692            crate::model_registry::model_info(&initial_context.model).context_budget;
693        let initial_goal = load_goal(&dir);
694        let (injection_tx, _) = broadcast::channel(32);
695        let (stream_tx, _) = broadcast::channel(1024);
696        let (context_watch, context_rx) = watch::channel(initial_context);
697        let (goal_watch, goal_rx) = watch::channel(initial_goal);
698        let (attach_watch, attach_rx) = watch::channel(0);
699        let (todos_watch, todos_rx) = watch::channel(Vec::new());
700        let (plans_watch, plans_rx) = watch::channel(Vec::new());
701        let events_handle = sink.events_handle();
702        Ok(Self {
703            id,
704            dir,
705            writer: std::sync::Mutex::new(Some(writer)),
706            sink,
707            message_stream: crate::message_stream::MessageStream::with_initial(
708                events_handle,
709                initial_msgs,
710                all_msgs,
711            ),
712            messages: std::sync::Arc::new(std::sync::Mutex::new(messages)),
713            turn: TurnState::new(),
714            watch: WatchHub {
715                stream_tx,
716                context: context_watch,
717                goal: goal_watch,
718                attach: attach_watch,
719                todos: todos_watch,
720                plans: plans_watch,
721                _keepalive: (context_rx, goal_rx, attach_rx, todos_rx, plans_rx),
722            },
723            compaction: CompactionState::new(),
724            interactions: InteractionServices::new(),
725            injection_queue: Mutex::new(Vec::new()),
726            injection_tx,
727            last_image_user_msg: Mutex::new(None),
728            read_files: std::sync::Arc::new(
729                std::sync::Mutex::new(std::collections::HashSet::new()),
730            ),
731            fs_access_mode: Mutex::new(None),
732            project_index,
733        })
734    }
735
736    pub fn open_ephemeral() -> Self {
737        let (injection_tx, _) = broadcast::channel(32);
738        let (stream_tx, _) = broadcast::channel(1024);
739        let (context_watch, context_rx) = watch::channel(ContextSnapshot::default());
740        let (goal_watch, goal_rx) = watch::channel(None);
741        let (attach_watch, attach_rx) = watch::channel(0);
742        let (todos_watch, todos_rx) = watch::channel(Vec::new());
743        let (plans_watch, plans_rx) = watch::channel(Vec::new());
744        let sink = EventSink::new();
745        let events_handle = sink.events_handle();
746        Self {
747            id: SessionId::now(),
748            dir: PathBuf::new(),
749            writer: std::sync::Mutex::new(None),
750            sink,
751            message_stream: crate::message_stream::MessageStream::new(events_handle),
752            messages: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
753            turn: TurnState::new(),
754            watch: WatchHub {
755                stream_tx,
756                context: context_watch,
757                goal: goal_watch,
758                attach: attach_watch,
759                todos: todos_watch,
760                plans: plans_watch,
761                _keepalive: (context_rx, goal_rx, attach_rx, todos_rx, plans_rx),
762            },
763            compaction: CompactionState::new(),
764            interactions: InteractionServices::new(),
765            injection_queue: Mutex::new(Vec::new()),
766            injection_tx,
767            last_image_user_msg: Mutex::new(None),
768            read_files: std::sync::Arc::new(
769                std::sync::Mutex::new(std::collections::HashSet::new()),
770            ),
771            fs_access_mode: Mutex::new(None),
772            project_index: None,
773        }
774    }
775
776    pub fn project_index(&self) -> Option<std::sync::Arc<crate::index::AnchorIndex>> {
777        self.project_index.clone()
778    }
779
780    pub fn approval(&self) -> std::sync::Arc<ApprovalRegistry> {
781        self.interactions.approval.clone()
782    }
783
784    pub fn compact_reviews(&self) -> std::sync::Arc<CompactReviewRegistry> {
785        self.interactions.compact_reviews.clone()
786    }
787
788    pub fn forms(&self) -> std::sync::Arc<FormRegistry> {
789        self.interactions.forms.clone()
790    }
791
792    pub fn fs_access_mode(&self) -> Option<crate::fs_access::FsAccessMode> {
793        *self.fs_access_mode.lock().unwrap()
794    }
795
796    pub fn set_fs_access_mode(&self, mode: crate::fs_access::FsAccessMode) {
797        *self.fs_access_mode.lock().unwrap() = Some(mode);
798    }
799
800    pub fn compact_review_mode(&self) -> CompactReviewMode {
801        *self.compaction.review_mode.lock().unwrap()
802    }
803
804    pub fn set_compact_review_mode(&self, mode: CompactReviewMode) {
805        *self.compaction.review_mode.lock().unwrap() = mode;
806    }
807
808    pub fn read_files(
809        &self,
810    ) -> std::sync::Arc<std::sync::Mutex<std::collections::HashSet<std::path::PathBuf>>> {
811        self.read_files.clone()
812    }
813
814    pub fn mark_file_read(&self, path: &std::path::Path) {
815        if let Ok(mut set) = self.read_files.lock() {
816            set.insert(path.to_path_buf());
817            if let Ok(canonical) = std::fs::canonicalize(path) {
818                set.insert(canonical);
819            }
820        }
821    }
822
823    pub fn stream_tx(&self) -> broadcast::Sender<StreamFrame> {
824        self.watch.stream_tx.clone()
825    }
826
827    pub fn stream_subscribe(&self) -> broadcast::Receiver<StreamFrame> {
828        self.watch.stream_tx.subscribe()
829    }
830
831    pub fn id(&self) -> &SessionId {
832        &self.id
833    }
834
835    pub fn dir(&self) -> &Path {
836        &self.dir
837    }
838
839    pub fn transcript_replay(&self) -> Vec<TranscriptEntry> {
840        let Some(path) = self.events_path() else {
841            return Vec::new();
842        };
843        replay_transcript_from(&path).unwrap_or_default()
844    }
845
846    pub fn events_path(&self) -> Option<std::path::PathBuf> {
847        self.writer
848            .lock()
849            .unwrap()
850            .as_ref()
851            .map(|w| w.events_path().to_path_buf())
852    }
853
854    pub async fn plan_system_prompt(&self) -> Option<String> {
855        let store = crate::memory::plan::PlanStore::at(&self.dir);
856        let plan = store.latest().await.ok().flatten()?;
857        Some(crate::tools::plan::render_plan(&plan))
858    }
859
860    pub fn goal(&self) -> Option<String> {
861        if let Some(cached) = self.watch.goal.borrow().clone() {
862            return Some(cached);
863        }
864        load_goal(&self.dir)
865    }
866
867    pub fn subscribe_goal(&self) -> watch::Receiver<Option<String>> {
868        self.watch.goal.subscribe()
869    }
870
871    pub fn goal_watch(&self) -> &watch::Sender<Option<String>> {
872        &self.watch.goal
873    }
874
875    pub fn subscribe_context(&self) -> watch::Receiver<ContextSnapshot> {
876        self.watch.context.subscribe()
877    }
878
879    pub fn subscribe_attach(&self) -> watch::Receiver<usize> {
880        self.watch.attach.subscribe()
881    }
882
883    pub fn subscribe_pending_approvals(&self) -> watch::Receiver<Vec<PendingApproval>> {
884        self.interactions.approval.subscribe()
885    }
886
887    pub fn meta(&self) -> Option<crate::session_meta::SessionMeta> {
888        crate::session_meta::SessionMeta::load(&self.dir)
889    }
890
891    pub fn request_manual_compact(&self) {
892        self.compaction
893            .manual_pending
894            .store(true, std::sync::atomic::Ordering::SeqCst);
895    }
896
897    pub fn take_manual_compact_request(&self) -> bool {
898        self.compaction
899            .manual_pending
900            .swap(false, std::sync::atomic::Ordering::SeqCst)
901    }
902
903    pub fn set_goal(&self, goal: Option<String>) {
904        let _ = self.watch.goal.send(goal);
905    }
906
907    pub fn set_attach_count(&self, count: usize) {
908        let _ = self.watch.attach.send(count);
909    }
910
911    #[allow(clippy::too_many_arguments)]
912    pub fn record_llm_call(
913        &self,
914        model: &str,
915        tokens_in: u64,
916        tokens_out: u64,
917        cache_read: u64,
918        cache_write: u64,
919        ttft_ms: Option<u64>,
920        tokens_per_sec: Option<f64>,
921    ) {
922        self.compaction
923            .last_input_tokens
924            .store(tokens_in, std::sync::atomic::Ordering::Relaxed);
925        self.watch.context.send_modify(|snap| {
926            snap.model = model.to_string();
927            snap.tokens_in = snap.tokens_in.saturating_add(tokens_in);
928            snap.tokens_out = snap.tokens_out.saturating_add(tokens_out);
929            snap.cache_read = snap.cache_read.saturating_add(cache_read);
930            snap.cache_write = snap.cache_write.saturating_add(cache_write);
931            snap.last_ttft_ms = ttft_ms.unwrap_or(0);
932            snap.last_tokens_per_sec = tokens_per_sec.unwrap_or(0.0);
933        });
934        self.refresh_window_snapshot();
935    }
936
937    pub fn last_input_tokens(&self) -> u64 {
938        self.compaction
939            .last_input_tokens
940            .load(std::sync::atomic::Ordering::Relaxed)
941    }
942
943    pub async fn acquire_compact_lock(&self) -> tokio::sync::MutexGuard<'_, ()> {
944        self.compaction.lock.lock().await
945    }
946
947    pub async fn acquire_compact_lock_owned(&self) -> tokio::sync::OwnedMutexGuard<()> {
948        self.compaction.lock.clone().lock_owned().await
949    }
950
951    pub fn compact_lock_handle(&self) -> std::sync::Arc<tokio::sync::Mutex<()>> {
952        self.compaction.lock.clone()
953    }
954
955    pub fn refresh_window_snapshot(&self) {
956        let provider_tokens = self.last_input_tokens();
957        let estimated = crate::compaction::estimate_tokens_for_messages(&self.messages());
958        let window = if provider_tokens > 0 {
959            provider_tokens
960        } else {
961            estimated
962        };
963        let budget = crate::model_registry::model_info(&self.last_model()).context_budget;
964        self.watch.context.send_modify(|snap| {
965            snap.window_tokens = window;
966            snap.window_budget = budget;
967        });
968    }
969
970    pub fn cumulative_input_tokens(&self) -> u64 {
971        self.watch.context.borrow().tokens_in
972    }
973
974    pub fn reset_input_tokens_to(&self, tokens: u64) {
975        self.watch.context.send_modify(|snap| {
976            snap.tokens_in = tokens;
977        });
978    }
979
980    pub fn last_model(&self) -> String {
981        self.watch.context.borrow().model.clone()
982    }
983
984    pub fn update_mcp_server(&self, status: crate::mcp::McpServerStatus) {
985        self.watch.context.send_modify(|snap| {
986            if let Some(existing) = snap.mcp_servers.iter_mut().find(|s| s.name == status.name) {
987                *existing = status;
988            } else {
989                snap.mcp_servers.push(status);
990            }
991        });
992    }
993
994    pub fn set_memory_recent_count(&self, count: u16) {
995        self.watch.context.send_modify(|snap| {
996            snap.memory_recent_count = count;
997        });
998    }
999
1000    pub fn subscribe_todos(&self) -> watch::Receiver<Vec<crate::memory::todo::Todo>> {
1001        self.watch.todos.subscribe()
1002    }
1003
1004    pub fn todos_watch(&self) -> &watch::Sender<Vec<crate::memory::todo::Todo>> {
1005        &self.watch.todos
1006    }
1007
1008    pub fn subscribe_plans(&self) -> watch::Receiver<Vec<crate::memory::plan::Plan>> {
1009        self.watch.plans.subscribe()
1010    }
1011
1012    pub fn plans_watch(&self) -> &watch::Sender<Vec<crate::memory::plan::Plan>> {
1013        &self.watch.plans
1014    }
1015
1016    pub async fn refresh_plans_from_store_async(&self) {
1017        if self.dir.as_os_str().is_empty() {
1018            return;
1019        }
1020        let store = crate::memory::plan::PlanStore::at(&self.dir);
1021        match store.list().await {
1022            Ok(list) => {
1023                let _ = self.watch.plans.send(list);
1024            }
1025            Err(e) => {
1026                crate::notify!(
1027                    warn,
1028                    location = Log,
1029                    stack = dedupe("memory.refresh_plans_async", 60_000),
1030                    "refresh_plans_from_store_async: {e}"
1031                );
1032            }
1033        }
1034    }
1035
1036    pub fn refresh_todos_from_store(&self) {
1037        if self.dir.as_os_str().is_empty() {
1038            return;
1039        }
1040        let store = crate::memory::todo::TodoStore::at(&self.dir);
1041        match tokio::task::block_in_place(|| {
1042            tokio::runtime::Handle::try_current()
1043                .ok()
1044                .map(|h| h.block_on(store.list()))
1045        }) {
1046            Some(Ok(list)) => {
1047                let _ = self.watch.todos.send(list);
1048            }
1049            Some(Err(e)) => {
1050                crate::notify!(
1051                    warn,
1052                    location = Log,
1053                    stack = dedupe("memory.refresh_todos", 60_000),
1054                    "refresh_todos_from_store: {e}"
1055                );
1056            }
1057            None => {}
1058        }
1059    }
1060
1061    pub async fn refresh_todos_from_store_async(&self) {
1062        if self.dir.as_os_str().is_empty() {
1063            return;
1064        }
1065        let store = crate::memory::todo::TodoStore::at(&self.dir);
1066        match store.list().await {
1067            Ok(list) => {
1068                let _ = self.watch.todos.send(list);
1069            }
1070            Err(e) => {
1071                crate::notify!(
1072                    warn,
1073                    location = Log,
1074                    stack = dedupe("memory.refresh_todos_async", 60_000),
1075                    "refresh_todos_from_store_async: {e}"
1076                );
1077            }
1078        }
1079    }
1080
1081    pub fn sink(&self) -> &EventSink {
1082        &self.sink
1083    }
1084
1085    /// Single-writer append. Emits the matching event before the in-memory push
1086    /// so events.jsonl remains the authority (§I5).
1087    pub fn append_message(&self, msg: Message, flow_run_id: Option<FlowRunId>) {
1088        AppendMessageCommand { msg, flow_run_id }.execute(self);
1089    }
1090
1091    pub fn emit_attachment_degrade(
1092        &self,
1093        message_seq: u64,
1094        part_index: usize,
1095        file_basename: String,
1096        reason: String,
1097    ) {
1098        self.sink.emit(Event::AttachmentDegraded {
1099            turn_id: None,
1100            flow_run_id: None,
1101            message_seq,
1102            part_index,
1103            file_basename,
1104            reason,
1105        });
1106    }
1107
1108    pub fn record_attachment_degrade(&self, reason: &str) -> usize {
1109        let target = self.last_image_user_msg.lock().unwrap().take();
1110        let Some(entry) = target else {
1111            return 0;
1112        };
1113        let turn_id = self.turn.current_turn.lock().unwrap().clone();
1114        for (part_index, basename) in &entry.images {
1115            self.sink.emit(Event::AttachmentDegraded {
1116                turn_id: turn_id.clone(),
1117                flow_run_id: None,
1118                message_seq: entry.message_seq,
1119                part_index: *part_index,
1120                file_basename: basename.clone(),
1121                reason: reason.into(),
1122            });
1123        }
1124        if let Ok(mut msgs) = self.messages.lock() {
1125            for m in msgs.iter_mut() {
1126                for (part_index, basename) in &entry.images {
1127                    if let Some(part) = m.parts.get_mut(*part_index)
1128                        && matches!(part, crate::message::MessagePart::Image { .. })
1129                    {
1130                        *part = crate::message::MessagePart::Text {
1131                            text: format!("[attachment unavailable: {basename} — {reason}]"),
1132                        };
1133                    }
1134                }
1135            }
1136        }
1137        entry.images.len()
1138    }
1139
1140    pub fn messages(&self) -> crate::message_stream::MessageWindow {
1141        self.message_stream.window()
1142    }
1143
1144    pub fn messages_full(&self) -> std::sync::Arc<Vec<Message>> {
1145        self.message_stream.full_messages()
1146    }
1147
1148    pub fn messages_handle(&self) -> std::sync::Arc<std::sync::Mutex<Vec<Message>>> {
1149        self.messages.clone()
1150    }
1151
1152    pub fn message_count(&self) -> usize {
1153        self.messages().len()
1154    }
1155
1156    pub fn user_message_count(&self) -> usize {
1157        self.messages()
1158            .iter()
1159            .filter(|m| matches!(m.role, MessageRole::User))
1160            .count()
1161    }
1162
1163    pub fn push_system_note(&self, text: String) {
1164        let _ = self
1165            .watch
1166            .stream_tx
1167            .send(crate::stream::StreamFrame::Note(text));
1168    }
1169
1170    pub fn approval_cooldown_ok_for_compact(&self) -> bool {
1171        self.sink.last_compact_ago_seconds().is_none_or(|s| s >= 60)
1172    }
1173
1174    pub fn emit_compact_warning(
1175        &self,
1176        model: &str,
1177        current_tokens: u64,
1178        threshold: u64,
1179        budget: u64,
1180        reason: &str,
1181    ) {
1182        let message = format!(
1183            "context {current_tokens} > threshold {threshold} (budget {budget}, model {model}); skipping compaction: {reason}"
1184        );
1185        self.sink.emit(Event::WatchWarn {
1186            turn_id: self.turn.current_turn.lock().unwrap().clone(),
1187            flow_run_id: None,
1188            target: "context.compaction".into(),
1189            trigger: "auto_compact".into(),
1190            message,
1191        });
1192        self.push_system_note(format!("[warn] compaction skipped: {reason}"));
1193    }
1194
1195    /// Convenience wrapper that computes the compact range and token count
1196    /// from the current message window. Used by tests and internal callers
1197    /// that don't already have a pre-computed range.
1198    pub fn compact_messages_auto(&self, summary: String) -> Option<CompactResult> {
1199        let msgs = self.messages();
1200        let tokens = crate::compaction::estimate_tokens_for_messages(&msgs);
1201        let info = crate::model_registry::model_info(&self.last_model());
1202        let target = info.compaction_target_after();
1203        let range = crate::compaction::find_compact_range(&msgs, target)?;
1204        self.compact_messages(summary, range, tokens)
1205    }
1206
1207    pub fn compact_messages(
1208        &self,
1209        summary: String,
1210        range: crate::compaction::CompactRange,
1211        before_tokens: u64,
1212    ) -> Option<CompactResult> {
1213        use crate::compaction::{estimate_tokens_for_messages, replace_range_with_summary};
1214        let msgs = self.messages();
1215        let turn_id = msgs
1216            .get(range.start)
1217            .map(|m| m.turn_id.clone())
1218            .unwrap_or_else(TurnId::now);
1219        let after = replace_range_with_summary(&msgs, &range, summary.clone(), turn_id.clone());
1220        let after_tokens = estimate_tokens_for_messages(&after);
1221        if after_tokens >= before_tokens {
1222            self.push_system_note(format!(
1223                "compaction skipped: summary would not shrink transcript ({} >= {} tokens)",
1224                after_tokens, before_tokens
1225            ));
1226            return None;
1227        }
1228        let replacement_msg = after.first().cloned().unwrap_or_else(|| {
1229            Message::system_compact_summary(
1230                turn_id.clone(),
1231                summary.clone(),
1232                range.start as u64,
1233                range.end.saturating_sub(1) as u64,
1234                range.end - range.start,
1235            )
1236        });
1237        self.sink.mark_compacted();
1238        let replacement_seq = self.sink.next_seq_peek();
1239        self.sink.emit(Event::SystemMsg {
1240            turn_id: turn_id.clone(),
1241            message: replacement_msg,
1242        });
1243        self.sink.emit(Event::ContextCompact {
1244            session_id: self.id.to_string(),
1245            before_tokens,
1246            after_tokens,
1247            compacted_range_start: range.start as u64,
1248            compacted_range_end: range.end.saturating_sub(1) as u64,
1249            summary_text: Some(summary.clone()),
1250            replacement_msg_seq: Some(replacement_seq),
1251        });
1252        self.sink.emit(Event::CompactionSummary {
1253            session_id: self.id.to_string(),
1254            range_start: range.start as u64,
1255            range_end: range.end.saturating_sub(1) as u64,
1256            compacted_count: range.end - range.start,
1257            before_tokens,
1258            after_tokens,
1259            summary: summary.clone(),
1260        });
1261        let _ = self
1262            .watch
1263            .stream_tx
1264            .send(crate::stream::StreamFrame::CompactionSummary {
1265                phase: crate::stream::CompactionPhase::Finished,
1266                range_start: range.start,
1267                range_end: range.end.saturating_sub(1),
1268                summary,
1269                before_tokens,
1270                after_tokens,
1271                compacted_count: range.end - range.start,
1272            });
1273        let checkpoint_messages = self.messages();
1274        let window_tokens = estimate_tokens_for_messages(&checkpoint_messages);
1275        self.compaction
1276            .last_input_tokens
1277            .store(window_tokens, std::sync::atomic::Ordering::Relaxed);
1278        self.refresh_window_snapshot();
1279        self.sink.emit(Event::Checkpoint {
1280            session_id: self.id.to_string(),
1281            messages: checkpoint_messages.to_vec(),
1282            window_tokens,
1283        });
1284        Some(CompactResult {
1285            before_tokens,
1286            after_tokens,
1287            compacted_start: range.start,
1288            compacted_end: range.end,
1289        })
1290    }
1291
1292    pub fn begin_turn(&self, user_msg: Message) -> TurnId {
1293        BeginTurnCommand { user_msg }.execute(self)
1294    }
1295
1296    pub fn mark_streamed(&self) {
1297        self.turn
1298            .streamed
1299            .store(true, std::sync::atomic::Ordering::Relaxed);
1300    }
1301
1302    pub fn take_streamed_flag(&self) -> bool {
1303        self.turn
1304            .streamed
1305            .swap(false, std::sync::atomic::Ordering::Relaxed)
1306    }
1307
1308    pub fn end_turn(&self) {
1309        self.turn
1310            .streamed
1311            .store(false, std::sync::atomic::Ordering::Relaxed);
1312        let turn_id = self.turn.current_turn.lock().unwrap().take();
1313        if let Some(turn_id) = turn_id {
1314            let mut q = self.injection_queue.lock().unwrap();
1315            for inj in q.iter_mut() {
1316                if inj.state == InjectionState::Pending && inj.turn_id == turn_id {
1317                    inj.state = InjectionState::Cancelled;
1318                    let _ = self.injection_tx.send(inj.clone());
1319                }
1320            }
1321            drop(q);
1322            self.sink.emit(Event::TurnEnd { turn_id });
1323        }
1324    }
1325
1326    pub fn current_turn(&self) -> Option<TurnId> {
1327        self.turn.current_turn.lock().unwrap().clone()
1328    }
1329
1330    pub fn enqueue_injection(&self, text: impl Into<String>) -> Result<InjectionId, EnqueueError> {
1331        self.enqueue_injection_with_level(text, crate::injection::InjectionLevel::L1Nudge, None)
1332    }
1333
1334    pub fn enqueue_injection_with_level(
1335        &self,
1336        text: impl Into<String>,
1337        level: crate::injection::InjectionLevel,
1338        redirect_target: Option<String>,
1339    ) -> Result<InjectionId, EnqueueError> {
1340        let turn_id = self
1341            .turn
1342            .current_turn
1343            .lock()
1344            .unwrap()
1345            .clone()
1346            .ok_or(EnqueueError::NoActiveTurn)?;
1347        let inj = Injection::with_level(turn_id.clone(), text, level, redirect_target);
1348        let id = inj.id.clone();
1349        self.sink.emit(Event::UserInject {
1350            turn_id,
1351            injection: inj.clone(),
1352        });
1353        self.injection_queue.lock().unwrap().push(inj.clone());
1354        let _ = self.injection_tx.send(inj);
1355        Ok(id)
1356    }
1357
1358    pub fn subscribe_injections(&self) -> broadcast::Receiver<Injection> {
1359        self.injection_tx.subscribe()
1360    }
1361
1362    pub fn mark_injection_consumed(&self, id: &InjectionId) {
1363        let mut q = self.injection_queue.lock().unwrap();
1364        for inj in q.iter_mut() {
1365            if inj.id == *id && inj.state == InjectionState::Pending {
1366                inj.state = InjectionState::Injected;
1367                let _ = self.injection_tx.send(inj.clone());
1368                return;
1369            }
1370        }
1371    }
1372
1373    pub fn peek_pending_l2_or_higher(&self, turn_id: &TurnId) -> Option<Injection> {
1374        let q = self.injection_queue.lock().unwrap();
1375        q.iter()
1376            .find(|i| {
1377                i.state == InjectionState::Pending
1378                    && i.turn_id == *turn_id
1379                    && !matches!(i.level, crate::injection::InjectionLevel::L1Nudge)
1380            })
1381            .cloned()
1382    }
1383
1384    /// Drain all Pending injections for `turn_id`. Marks them Injected.
1385    /// Returns them in creation order.
1386    pub fn drain_injections(&self, turn_id: &TurnId) -> Vec<Injection> {
1387        let mut q = self.injection_queue.lock().unwrap();
1388        let mut out = Vec::new();
1389        for inj in q.iter_mut() {
1390            if inj.state == InjectionState::Pending && inj.turn_id == *turn_id {
1391                inj.state = InjectionState::Injected;
1392                let _ = self.injection_tx.send(inj.clone());
1393                out.push(inj.clone());
1394            }
1395        }
1396        out
1397    }
1398
1399    pub fn list_pending_injections(&self) -> Vec<Injection> {
1400        self.injection_queue
1401            .lock()
1402            .unwrap()
1403            .iter()
1404            .filter(|i| i.state == InjectionState::Pending)
1405            .cloned()
1406            .collect()
1407    }
1408
1409    pub fn cancel_flow(&self) {
1410        self.turn.flow_cancel.lock().unwrap().cancel();
1411    }
1412
1413    pub fn flow_cancel_token(&self) -> CancellationToken {
1414        self.turn.flow_cancel.lock().unwrap().clone()
1415    }
1416
1417    pub async fn shutdown(&self) {
1418        let writer = self.writer.lock().unwrap().take();
1419        if let Some(writer) = writer {
1420            writer.shutdown().await;
1421        }
1422    }
1423
1424    // Rides FIFO queue ordering: once flush's own barrier is written,
1425    // every earlier sink.emit is on disk too.
1426    #[allow(clippy::await_holding_lock)]
1427    pub async fn flush_writer(&self) {
1428        let guard = self.writer.lock().unwrap();
1429        let Some(ref writer) = *guard else {
1430            return;
1431        };
1432        writer.flush().await;
1433    }
1434}
1435
1436#[derive(Debug, thiserror::Error)]
1437pub enum EnqueueError {
1438    #[error("enqueue_injection called with no active turn")]
1439    NoActiveTurn,
1440}
1441
1442pub struct AppendMessageCommand {
1443    pub msg: Message,
1444    pub flow_run_id: Option<FlowRunId>,
1445}
1446
1447impl AppendMessageCommand {
1448    pub fn execute(&self, session: &Session) -> u64 {
1449        let flow_run_id_str = self.flow_run_id.as_ref().map(|r| r.0.to_string());
1450        let event = match self.msg.role {
1451            MessageRole::User => Event::UserMsg {
1452                turn_id: self.msg.turn_id.clone(),
1453                message: self.msg.clone(),
1454            },
1455            MessageRole::Assistant => {
1456                let _ = session
1457                    .watch
1458                    .stream_tx
1459                    .send(crate::stream::StreamFrame::AssistantMsg {
1460                        flow_run_id: flow_run_id_str.clone(),
1461                        message: self.msg.clone(),
1462                    });
1463                Event::AssistantMsg {
1464                    turn_id: self.msg.turn_id.clone(),
1465                    flow_run_id: self.flow_run_id.clone(),
1466                    message: self.msg.clone(),
1467                }
1468            }
1469            MessageRole::Tool => {
1470                let _ = session
1471                    .watch
1472                    .stream_tx
1473                    .send(crate::stream::StreamFrame::ToolResultMsg {
1474                        flow_run_id: flow_run_id_str.clone(),
1475                        message: self.msg.clone(),
1476                    });
1477                Event::ToolResultMsg {
1478                    turn_id: self.msg.turn_id.clone(),
1479                    flow_run_id: self.flow_run_id.clone(),
1480                    message: self.msg.clone(),
1481                }
1482            }
1483            MessageRole::System => Event::SystemMsg {
1484                turn_id: self.msg.turn_id.clone(),
1485                message: self.msg.clone(),
1486            },
1487        };
1488        let seq = session.sink.emit_returning_seq(event);
1489        if matches!(self.msg.role, MessageRole::User) {
1490            let images: Vec<(usize, String)> = self
1491                .msg
1492                .parts
1493                .iter()
1494                .enumerate()
1495                .filter_map(|(i, p)| match p {
1496                    crate::message::MessagePart::Image { source } => {
1497                        let basename = match &source.data {
1498                            crate::message::ImageData::Path { path } => path
1499                                .file_name()
1500                                .and_then(|n| n.to_str())
1501                                .unwrap_or("unknown")
1502                                .to_string(),
1503                            crate::message::ImageData::Base64 { .. } => "base64".into(),
1504                        };
1505                        Some((i, basename))
1506                    }
1507                    _ => None,
1508                })
1509                .collect();
1510            if !images.is_empty() {
1511                *session.last_image_user_msg.lock().unwrap() = Some(LastImageUserMsg {
1512                    message_seq: seq,
1513                    images,
1514                });
1515            }
1516        }
1517        session.messages.lock().unwrap().push(self.msg.clone());
1518        seq
1519    }
1520}
1521
1522pub struct BeginTurnCommand {
1523    pub user_msg: Message,
1524}
1525
1526impl BeginTurnCommand {
1527    pub fn execute(&self, session: &Session) -> TurnId {
1528        let turn_id = self.user_msg.turn_id.clone();
1529        *session.turn.current_turn.lock().unwrap() = Some(turn_id.clone());
1530        *session.turn.flow_cancel.lock().unwrap() = tokio_util::sync::CancellationToken::new();
1531        session.sink.emit(Event::TurnStart {
1532            turn_id: turn_id.clone(),
1533        });
1534        AppendMessageCommand {
1535            msg: self.user_msg.clone(),
1536            flow_run_id: None,
1537        }
1538        .execute(session);
1539        turn_id
1540    }
1541}
1542
1543#[cfg(test)]
1544mod tests {
1545    use super::*;
1546    use tempfile::TempDir;
1547
1548    fn write_events(dir: &Path, lines: &[&str]) {
1549        let path = dir.join("events.jsonl");
1550        std::fs::write(&path, lines.join("\n") + "\n").unwrap();
1551    }
1552
1553    #[test]
1554    fn replay_applies_attachment_degraded_patch() {
1555        let dir = TempDir::new().unwrap();
1556        let user_msg = r#"{"type":"user_msg","seq":5,"turn_id":"019f0000-0000-7000-0000-000000000001","message":{"role":"user","parts":[{"type":"image","source":{"media_type":"image/png","data":{"kind":"path","path":"/tmp/photo.png"}}},{"type":"text","text":"describe"}],"turn_id":"019f0000-0000-7000-0000-000000000001"},"ts":"2026-07-07T00:00:00Z"}"#;
1557        let degrade = r#"{"type":"attachment_degraded","seq":6,"turn_id":null,"flow_run_id":null,"message_seq":5,"part_index":0,"file_basename":"photo.png","reason":"image_too_large","ts":"2026-07-07T00:00:01Z"}"#;
1558        write_events(dir.path(), &[user_msg, degrade]);
1559        let entries = replay_transcript_from(&dir.path().join("events.jsonl")).unwrap();
1560        let msg = entries
1561            .into_iter()
1562            .find_map(|e| match e {
1563                TranscriptEntry::Message { message, .. } => Some(message),
1564                _ => None,
1565            })
1566            .unwrap();
1567        assert_eq!(msg.parts.len(), 2);
1568        match &msg.parts[0] {
1569            crate::message::MessagePart::Text { text } => {
1570                assert!(text.contains("photo.png"), "expected basename: {text}");
1571                assert!(text.contains("image_too_large"), "expected reason: {text}");
1572                assert!(text.starts_with("[attachment unavailable"));
1573            }
1574            other => panic!("expected Text stub, got {other:?}"),
1575        }
1576        assert!(matches!(
1577            msg.parts[1],
1578            crate::message::MessagePart::Text { .. }
1579        ));
1580    }
1581
1582    #[test]
1583    fn approval_registry_auto_approves_when_level_leq_ceiling() {
1584        let reg = ApprovalRegistry::new();
1585        reg.set_auto_ceiling(crate::tool::ApprovalLevel::Approve);
1586        let pending = PendingApproval {
1587            tool_use_id: "tu1".into(),
1588            tool_name: "fs.read".into(),
1589            args_preview: "{}".into(),
1590            preview: None,
1591            level: crate::tool::ApprovalLevel::Auto,
1592            run_id: FlowRunId::now(),
1593            emitted_at: chrono::Utc::now(),
1594            bypass_auto_ceiling: false,
1595        };
1596        let rx = reg.request(pending);
1597        let got = rx.blocking_recv().unwrap();
1598        assert!(matches!(got, ApprovalDecision::Approve));
1599        assert!(reg.list_pending().is_empty());
1600    }
1601
1602    #[test]
1603    fn approval_registry_queues_when_level_above_ceiling() {
1604        let reg = std::sync::Arc::new(ApprovalRegistry::new());
1605        reg.set_auto_ceiling(crate::tool::ApprovalLevel::Auto);
1606        let pending = PendingApproval {
1607            tool_use_id: "tu42".into(),
1608            tool_name: "fs.write".into(),
1609            args_preview: "{}".into(),
1610            preview: None,
1611            level: crate::tool::ApprovalLevel::Approve,
1612            run_id: FlowRunId::now(),
1613            emitted_at: chrono::Utc::now(),
1614            bypass_auto_ceiling: false,
1615        };
1616        let mut rx = reg.request(pending);
1617        assert_eq!(reg.list_pending().len(), 1);
1618        assert!(rx.try_recv().is_err(), "should still be queued");
1619        assert!(reg.decide("tu42", ApprovalDecision::Approve));
1620        let got = rx.blocking_recv().unwrap();
1621        assert!(matches!(got, ApprovalDecision::Approve));
1622        assert!(reg.list_pending().is_empty());
1623    }
1624
1625    #[test]
1626    fn approval_registry_decide_all_flushes_queue() {
1627        let reg = ApprovalRegistry::new();
1628        reg.set_auto_ceiling(crate::tool::ApprovalLevel::Auto);
1629        let mut rxs = Vec::new();
1630        for i in 0..3 {
1631            rxs.push(reg.request(PendingApproval {
1632                tool_use_id: format!("tu{i}"),
1633                tool_name: "bash.exec".into(),
1634                args_preview: "{}".into(),
1635                preview: None,
1636                level: crate::tool::ApprovalLevel::Dangerous,
1637                run_id: FlowRunId::now(),
1638                emitted_at: chrono::Utc::now(),
1639                bypass_auto_ceiling: false,
1640            }));
1641        }
1642        assert_eq!(reg.list_pending().len(), 3);
1643        assert_eq!(
1644            reg.decide_all(ApprovalDecision::Deny {
1645                reason: "user cancelled".into()
1646            }),
1647            3
1648        );
1649        assert!(reg.list_pending().is_empty());
1650    }
1651
1652    #[test]
1653    fn compact_review_registry_auto_accepts_when_no_subscriber() {
1654        let reg = CompactReviewRegistry::new();
1655        let pending = PendingCompactReview {
1656            review_id: "r1".into(),
1657            summary: "gist".into(),
1658            slice_preview: String::new(),
1659            slice_count: 0,
1660            range_start: 0,
1661            range_end: 0,
1662            tokens_before: 0,
1663            emitted_at: chrono::Utc::now(),
1664        };
1665        let rx = reg.request(pending);
1666        let got = rx.blocking_recv().unwrap();
1667        assert!(matches!(got, CompactReviewDecision::AcceptAsIs));
1668        assert!(reg.list_pending().is_none());
1669    }
1670
1671    #[test]
1672    fn compact_review_registry_holds_pending_and_decides() {
1673        let reg = std::sync::Arc::new(CompactReviewRegistry::new());
1674        let _sub = reg.subscribe();
1675        let pending = PendingCompactReview {
1676            review_id: "r2".into(),
1677            summary: "old".into(),
1678            slice_preview: "slice".into(),
1679            slice_count: 3,
1680            range_start: 1,
1681            range_end: 4,
1682            tokens_before: 500,
1683            emitted_at: chrono::Utc::now(),
1684        };
1685        let mut rx = reg.request(pending);
1686        assert!(rx.try_recv().is_err(), "should be queued");
1687        assert!(reg.list_pending().is_some());
1688        assert!(reg.decide(
1689            "r2",
1690            CompactReviewDecision::AcceptEdited {
1691                summary: "new".into()
1692            }
1693        ));
1694        let got = rx.blocking_recv().unwrap();
1695        match got {
1696            CompactReviewDecision::AcceptEdited { summary } => assert_eq!(summary, "new"),
1697            other => panic!("unexpected decision: {other:?}"),
1698        }
1699        assert!(reg.list_pending().is_none());
1700    }
1701
1702    #[test]
1703    fn compact_review_registry_reject_flushes() {
1704        let reg = std::sync::Arc::new(CompactReviewRegistry::new());
1705        let _sub = reg.subscribe();
1706        let rx = reg.request(PendingCompactReview {
1707            review_id: "r3".into(),
1708            summary: String::new(),
1709            slice_preview: String::new(),
1710            slice_count: 0,
1711            range_start: 0,
1712            range_end: 0,
1713            tokens_before: 0,
1714            emitted_at: chrono::Utc::now(),
1715        });
1716        assert!(reg.decide("r3", CompactReviewDecision::Reject));
1717        let got = rx.blocking_recv().unwrap();
1718        assert!(matches!(got, CompactReviewDecision::Reject));
1719    }
1720
1721    #[test]
1722    fn replay_context_snapshot_accumulates_llm_call_usage() {
1723        let dir = TempDir::new().unwrap();
1724        let events = [
1725            r#"{"type":"llm_call","seq":1,"model":"anthropic/claude-4","provider":"anthropic","usage":{"input":100,"cached_input":10,"output":50,"cache_write":0},"wallclock_ms":1000,"status":{"kind":"ok"},"ts":"2026-07-08T00:00:00Z"}"#,
1726            r#"{"type":"user_msg","seq":2,"turn_id":"019f0000-0000-7000-0000-000000000002","message":{"role":"user","parts":[{"type":"text","text":"hi"}],"turn_id":"019f0000-0000-7000-0000-000000000002"},"ts":"2026-07-08T00:00:00Z"}"#,
1727            r#"{"type":"llm_call","seq":3,"model":"anthropic/claude-4","provider":"anthropic","usage":{"input":200,"cached_input":0,"output":80,"cache_write":0},"wallclock_ms":1000,"status":{"kind":"ok"},"ts":"2026-07-08T00:00:01Z"}"#,
1728        ];
1729        write_events(dir.path(), &events);
1730        let snap = replay_context_snapshot_from(&dir.path().join("events.jsonl"));
1731        assert_eq!(snap.model, "anthropic/claude-4");
1732        assert_eq!(snap.tokens_in, 310);
1733        assert_eq!(snap.tokens_out, 130);
1734    }
1735
1736    #[test]
1737    fn compact_review_mode_parses_all_variants() {
1738        assert_eq!(
1739            CompactReviewMode::parse("always"),
1740            Some(CompactReviewMode::Always)
1741        );
1742        assert_eq!(
1743            CompactReviewMode::parse("manual-only"),
1744            Some(CompactReviewMode::ManualOnly)
1745        );
1746        assert_eq!(
1747            CompactReviewMode::parse("manual_only"),
1748            Some(CompactReviewMode::ManualOnly)
1749        );
1750        assert_eq!(
1751            CompactReviewMode::parse("never"),
1752            Some(CompactReviewMode::Never)
1753        );
1754        assert_eq!(CompactReviewMode::parse(" bogus "), None);
1755    }
1756
1757    #[test]
1758    fn compact_review_mode_should_review_matrix() {
1759        assert!(CompactReviewMode::Always.should_review(false));
1760        assert!(CompactReviewMode::Always.should_review(true));
1761        assert!(!CompactReviewMode::ManualOnly.should_review(false));
1762        assert!(CompactReviewMode::ManualOnly.should_review(true));
1763        assert!(!CompactReviewMode::Never.should_review(false));
1764        assert!(!CompactReviewMode::Never.should_review(true));
1765    }
1766
1767    #[test]
1768    fn compact_review_registry_new_request_rejects_previous() {
1769        let reg = std::sync::Arc::new(CompactReviewRegistry::new());
1770        let _sub = reg.subscribe();
1771        let rx_a = reg.request(PendingCompactReview {
1772            review_id: "rA".into(),
1773            summary: String::new(),
1774            slice_preview: String::new(),
1775            slice_count: 0,
1776            range_start: 0,
1777            range_end: 0,
1778            tokens_before: 0,
1779            emitted_at: chrono::Utc::now(),
1780        });
1781        let _rx_b = reg.request(PendingCompactReview {
1782            review_id: "rB".into(),
1783            summary: String::new(),
1784            slice_preview: String::new(),
1785            slice_count: 0,
1786            range_start: 0,
1787            range_end: 0,
1788            tokens_before: 0,
1789            emitted_at: chrono::Utc::now(),
1790        });
1791        let got = rx_a.blocking_recv().unwrap();
1792        assert!(matches!(got, CompactReviewDecision::Reject));
1793    }
1794
1795    fn mk_form(form_id: &str, prompt: &str) -> crate::form::PendingForm {
1796        crate::form::PendingForm {
1797            form_id: form_id.into(),
1798            run_id: crate::event::FlowRunId::now(),
1799            tool_use_id: "tu".into(),
1800            kind: crate::form::FormKind::Confirm {
1801                prompt: prompt.into(),
1802            },
1803            emitted_at: chrono::Utc::now(),
1804        }
1805    }
1806
1807    #[test]
1808    fn form_registry_auto_cancels_without_subscriber() {
1809        let reg = FormRegistry::new();
1810        let rx = reg.request(mk_form("f1", "sure?"));
1811        let got = rx.blocking_recv().unwrap();
1812        assert_eq!(got, crate::form::FormAnswer::Cancelled);
1813        assert!(reg.list_pending().is_empty());
1814    }
1815
1816    #[test]
1817    fn form_registry_delivers_answer_by_form_id() {
1818        let reg = std::sync::Arc::new(FormRegistry::new());
1819        let _sub = reg.subscribe();
1820        let rx = reg.request(mk_form("fA", "?"));
1821        assert_eq!(reg.list_pending().len(), 1);
1822        let ok = reg.submit("fA", crate::form::FormAnswer::Confirmed { value: true });
1823        assert!(ok);
1824        let got = rx.blocking_recv().unwrap();
1825        assert_eq!(got, crate::form::FormAnswer::Confirmed { value: true });
1826        assert!(reg.list_pending().is_empty());
1827    }
1828
1829    #[test]
1830    fn form_registry_submit_unknown_id_is_noop() {
1831        let reg = std::sync::Arc::new(FormRegistry::new());
1832        let _sub = reg.subscribe();
1833        let _rx = reg.request(mk_form("real", "?"));
1834        assert!(!reg.submit("ghost", crate::form::FormAnswer::Cancelled));
1835        assert_eq!(reg.list_pending().len(), 1);
1836    }
1837
1838    #[test]
1839    fn form_registry_cancel_all_flushes_pending() {
1840        let reg = std::sync::Arc::new(FormRegistry::new());
1841        let _sub = reg.subscribe();
1842        let rx_a = reg.request(mk_form("a", "?"));
1843        let rx_b = reg.request(mk_form("b", "?"));
1844        reg.cancel_all();
1845        assert_eq!(
1846            rx_a.blocking_recv().unwrap(),
1847            crate::form::FormAnswer::Cancelled
1848        );
1849        assert_eq!(
1850            rx_b.blocking_recv().unwrap(),
1851            crate::form::FormAnswer::Cancelled
1852        );
1853        assert!(reg.list_pending().is_empty());
1854    }
1855
1856    #[test]
1857    fn form_registry_queues_multiple_pending() {
1858        let reg = std::sync::Arc::new(FormRegistry::new());
1859        let _sub = reg.subscribe();
1860        let _rx1 = reg.request(mk_form("1", "?"));
1861        let _rx2 = reg.request(mk_form("2", "?"));
1862        let pending = reg.list_pending();
1863        assert_eq!(pending.len(), 2);
1864        assert_eq!(pending[0].form_id, "1");
1865        assert_eq!(pending[1].form_id, "2");
1866    }
1867
1868    #[test]
1869    fn replay_without_degraded_events_preserves_image_parts() {
1870        let dir = TempDir::new().unwrap();
1871        let user_msg = r#"{"type":"user_msg","seq":1,"turn_id":"019f0000-0000-7000-0000-000000000002","message":{"role":"user","parts":[{"type":"image","source":{"media_type":"image/png","data":{"kind":"path","path":"/tmp/x.png"}}}],"turn_id":"019f0000-0000-7000-0000-000000000002"},"ts":"2026-07-07T00:00:00Z"}"#;
1872        write_events(dir.path(), &[user_msg]);
1873        let entries = replay_transcript_from(&dir.path().join("events.jsonl")).unwrap();
1874        let msg = entries
1875            .into_iter()
1876            .find_map(|e| match e {
1877                TranscriptEntry::Message { message, .. } => Some(message),
1878                _ => None,
1879            })
1880            .unwrap();
1881        assert!(matches!(
1882            msg.parts[0],
1883            crate::message::MessagePart::Image { .. }
1884        ));
1885    }
1886
1887    #[test]
1888    fn replay_messages_from_old_format_no_seq_no_ts() {
1889        let dir = TempDir::new().unwrap();
1890        // Old-style JSONL: no seq, no ts on events
1891        let user_json = r#"{"type":"user_msg","turn_id":"019f0000-0000-7000-0000-000000000001","message":{"role":"user","parts":[{"type":"text","text":"hello"}],"turn_id":"019f0000-0000-7000-0000-000000000001"}}"#;
1892        let asst_json = r#"{"type":"assistant_msg","turn_id":"019f0000-0000-7000-0000-000000000001","message":{"role":"assistant","parts":[{"type":"text","text":"hi there"}],"turn_id":"019f0000-0000-7000-0000-000000000001"},"flow_run_id":null}"#;
1893        write_events(dir.path(), &[user_json, asst_json]);
1894        let msgs = replay_messages_from(&dir.path().join("events.jsonl")).unwrap();
1895        assert_eq!(msgs.len(), 2, "should load both messages from old format");
1896        assert_eq!(msgs[0].text_concat(), "hello");
1897        assert_eq!(msgs[1].text_concat(), "hi there");
1898    }
1899
1900    #[test]
1901    fn replay_messages_from_old_format_with_null_fields() {
1902        let dir = TempDir::new().unwrap();
1903        // Old JSON with null turn_id / flow_run_id (graceful parse)
1904        let sys_json = r#"{"type":"system_msg","turn_id":"019f0000-0000-7000-0000-000000000003","message":{"role":"system","parts":[{"type":"text","text":"note"}],"turn_id":"019f0000-0000-7000-0000-000000000003"}}"#;
1905        write_events(dir.path(), &[sys_json]);
1906        let msgs = replay_messages_from(&dir.path().join("events.jsonl")).unwrap();
1907        assert_eq!(msgs.len(), 1);
1908        assert_eq!(msgs[0].text_concat(), "note");
1909    }
1910
1911    #[test]
1912    fn replay_messages_from_applies_attachment_degrade() {
1913        let dir = TempDir::new().unwrap();
1914        let user_msg = r#"{"type":"user_msg","seq":5,"turn_id":"019f0000-0000-7000-0000-000000000001","message":{"role":"user","parts":[{"type":"image","source":{"media_type":"image/png","data":{"kind":"path","path":"/tmp/photo.png"}}},{"type":"text","text":"describe"}],"turn_id":"019f0000-0000-7000-0000-000000000001"},"ts":"2026-07-07T00:00:00Z"}"#;
1915        let degrade = r#"{"type":"attachment_degraded","seq":6,"turn_id":null,"flow_run_id":null,"message_seq":5,"part_index":0,"file_basename":"photo.png","reason":"image_too_large","ts":"2026-07-07T00:00:01Z"}"#;
1916        write_events(dir.path(), &[user_msg, degrade]);
1917        let msgs = replay_messages_from(&dir.path().join("events.jsonl")).unwrap();
1918        assert_eq!(msgs.len(), 1, "only the user message (patched)");
1919        assert_eq!(msgs[0].parts.len(), 2);
1920        match &msgs[0].parts[0] {
1921            crate::message::MessagePart::Text { text } => {
1922                assert!(text.contains("photo.png"), "expected basename: {text}");
1923                assert!(text.contains("image_too_large"), "expected reason: {text}");
1924                assert!(
1925                    text.starts_with("[attachment unavailable"),
1926                    "expected stub prefix: {text}"
1927                );
1928            }
1929            other => panic!("expected Text stub, got {other:?}"),
1930        }
1931        assert!(
1932            matches!(msgs[0].parts[1], crate::message::MessagePart::Text { .. }),
1933            "second part should remain text"
1934        );
1935    }
1936
1937    #[test]
1938    fn replay_messages_from_degrade_before_message_is_noop() {
1939        let dir = TempDir::new().unwrap();
1940        // Degrade event appears BEFORE the message it references (should not crash)
1941        let degrade = r#"{"type":"attachment_degraded","seq":1,"turn_id":null,"flow_run_id":null,"message_seq":99,"part_index":0,"file_basename":"x.png","reason":"test","ts":"2026-07-07T00:00:00Z"}"#;
1942        let user_msg = r#"{"type":"user_msg","seq":2,"turn_id":"019f0000-0000-7000-0000-000000000001","message":{"role":"user","parts":[{"type":"image","source":{"media_type":"image/png","data":{"kind":"path","path":"/tmp/x.png"}}}],"turn_id":"019f0000-0000-7000-0000-000000000001"},"ts":"2026-07-07T00:00:01Z"}"#;
1943        write_events(dir.path(), &[degrade, user_msg]);
1944        let msgs = replay_messages_from(&dir.path().join("events.jsonl")).unwrap();
1945        assert_eq!(msgs.len(), 1);
1946        // Image part preserved — degrade referenced unknown message_seq
1947        assert!(
1948            matches!(msgs[0].parts[0], crate::message::MessagePart::Image { .. }),
1949            "image should remain when degrade targets unknown seq"
1950        );
1951    }
1952
1953    #[test]
1954    fn replay_messages_from_degrade_wrong_seq_leaves_image() {
1955        let dir = TempDir::new().unwrap();
1956        let user_msg = r#"{"type":"user_msg","seq":1,"turn_id":"019f0000-0000-7000-0000-000000000001","message":{"role":"user","parts":[{"type":"image","source":{"media_type":"image/png","data":{"kind":"path","path":"/tmp/x.png"}}}],"turn_id":"019f0000-0000-7000-0000-000000000001"},"ts":"2026-07-07T00:00:00Z"}"#;
1957        // Degrade references wrong message_seq (2, but message has seq 1)
1958        let degrade = r#"{"type":"attachment_degraded","seq":2,"turn_id":null,"flow_run_id":null,"message_seq":2,"part_index":0,"file_basename":"x.png","reason":"test","ts":"2026-07-07T00:00:01Z"}"#;
1959        write_events(dir.path(), &[user_msg, degrade]);
1960        let msgs = replay_messages_from(&dir.path().join("events.jsonl")).unwrap();
1961        assert_eq!(msgs.len(), 1);
1962        assert!(
1963            matches!(msgs[0].parts[0], crate::message::MessagePart::Image { .. }),
1964            "image should remain when degrade targets wrong seq"
1965        );
1966    }
1967
1968    #[test]
1969    fn replay_messages_from_applies_context_compact() {
1970        let dir = TempDir::new().unwrap();
1971        let user1 = r#"{"type":"user_msg","seq":1,"turn_id":"019f0000-0000-7000-0000-000000000001","message":{"role":"user","parts":[{"type":"text","text":"old u1"}],"turn_id":"019f0000-0000-7000-0000-000000000001"},"ts":"2026-07-07T00:00:00Z"}"#;
1972        let asst1 = r#"{"type":"assistant_msg","seq":2,"turn_id":"019f0000-0000-7000-0000-000000000001","message":{"role":"assistant","parts":[{"type":"text","text":"old a1"}],"turn_id":"019f0000-0000-7000-0000-000000000001"},"flow_run_id":null,"ts":"2026-07-07T00:00:01Z"}"#;
1973        let user2 = r#"{"type":"user_msg","seq":3,"turn_id":"019f0000-0000-7000-0000-000000000002","message":{"role":"user","parts":[{"type":"text","text":"old u2"}],"turn_id":"019f0000-0000-7000-0000-000000000002"},"ts":"2026-07-07T00:00:02Z"}"#;
1974        // replacement message (compact summary)
1975        let summary = r#"{"type":"system_msg","seq":4,"turn_id":"019f0000-0000-7000-0000-000000000002","message":{"role":"system","parts":[{"type":"compact_summary","summary":"two messages compacted","seq_start":0,"seq_end":1,"count":2}],"turn_id":"019f0000-0000-7000-0000-000000000002"},"ts":"2026-07-07T00:00:03Z"}"#;
1976        let compact = r#"{"type":"context_compact","seq":5,"session_id":"sess","before_tokens":200,"after_tokens":50,"compacted_range_start":0,"compacted_range_end":1,"summary_text":"two messages compacted","replacement_msg_seq":4,"ts":"2026-07-07T00:00:04Z"}"#;
1977        let after = r#"{"type":"user_msg","seq":6,"turn_id":"019f0000-0000-7000-0000-000000000003","message":{"role":"user","parts":[{"type":"text","text":"after compact"}],"turn_id":"019f0000-0000-7000-0000-000000000003"},"ts":"2026-07-07T00:00:05Z"}"#;
1978        write_events(dir.path(), &[user1, asst1, user2, summary, compact, after]);
1979        let msgs = replay_messages_from(&dir.path().join("events.jsonl")).unwrap();
1980        // compact range 0-1 removes user1+asst1; user2 (outside range) + summary + after = 3
1981        assert_eq!(msgs.len(), 3, "compact summary + user2 + after compact");
1982        assert!(
1983            matches!(
1984                msgs[0].parts[0],
1985                crate::message::MessagePart::CompactSummary { .. }
1986            ),
1987            "first should be compact summary"
1988        );
1989        if let crate::message::MessagePart::CompactSummary { summary, .. } = &msgs[0].parts[0] {
1990            assert_eq!(summary, "two messages compacted");
1991        }
1992        assert_eq!(msgs[1].text_concat(), "old u2");
1993        assert_eq!(msgs[2].text_concat(), "after compact");
1994    }
1995
1996    #[test]
1997    fn replay_messages_from_no_replacement_seq_ignores_compact() {
1998        let dir = TempDir::new().unwrap();
1999        let user1 = r#"{"type":"user_msg","seq":1,"turn_id":"019f0000-0000-7000-0000-000000000001","message":{"role":"user","parts":[{"type":"text","text":"hello"}],"turn_id":"019f0000-0000-7000-0000-000000000001"},"ts":"2026-07-07T00:00:00Z"}"#;
2000        // context_compact with no replacement_msg_seq → should be ignored
2001        let compact = r#"{"type":"context_compact","seq":2,"session_id":"sess","before_tokens":200,"after_tokens":50,"compacted_range_start":0,"compacted_range_end":0,"summary_text":"ignored","replacement_msg_seq":null,"ts":"2026-07-07T00:00:01Z"}"#;
2002        write_events(dir.path(), &[user1, compact]);
2003        let msgs = replay_messages_from(&dir.path().join("events.jsonl")).unwrap();
2004        assert_eq!(msgs.len(), 1, "compact without replacement seq is ignored");
2005        assert_eq!(msgs[0].text_concat(), "hello");
2006    }
2007
2008    #[test]
2009    fn replay_messages_from_compact_after_no_change_ignored() {
2010        let dir = TempDir::new().unwrap();
2011        let user1 = r#"{"type":"user_msg","seq":1,"turn_id":"019f0000-0000-7000-0000-000000000001","message":{"role":"user","parts":[{"type":"text","text":"hello"}],"turn_id":"019f0000-0000-7000-0000-000000000001"},"ts":"2026-07-07T00:00:00Z"}"#;
2012        let summary = r#"{"type":"system_msg","seq":2,"turn_id":"019f0000-0000-7000-0000-000000000001","message":{"role":"system","parts":[{"type":"compact_summary","summary":"no change","seq_start":0,"seq_end":0,"count":1}],"turn_id":"019f0000-0000-7000-0000-000000000001"},"ts":"2026-07-07T00:00:01Z"}"#;
2013        // after_tokens >= before_tokens → compaction is no-op
2014        let compact = r#"{"type":"context_compact","seq":3,"session_id":"sess","before_tokens":50,"after_tokens":100,"compacted_range_start":0,"compacted_range_end":0,"summary_text":"no change","replacement_msg_seq":2,"ts":"2026-07-07T00:00:02Z"}"#;
2015        write_events(dir.path(), &[user1, summary, compact]);
2016        let msgs = replay_messages_from(&dir.path().join("events.jsonl")).unwrap();
2017        assert_eq!(msgs.len(), 2, "compact with after>=before is ignored");
2018    }
2019
2020    #[test]
2021    fn replay_messages_from_missing_file_returns_empty() {
2022        let dir = TempDir::new().unwrap();
2023        let msgs = replay_messages_from(&dir.path().join("events.jsonl")).unwrap();
2024        assert!(msgs.is_empty());
2025    }
2026
2027    #[test]
2028    fn replay_messages_from_empty_file_returns_empty() {
2029        let dir = TempDir::new().unwrap();
2030        write_events(dir.path(), &[]);
2031        let msgs = replay_messages_from(&dir.path().join("events.jsonl")).unwrap();
2032        assert!(msgs.is_empty());
2033    }
2034
2035    #[test]
2036    fn replay_all_messages_with_seq_includes_compacted() {
2037        let dir = TempDir::new().unwrap();
2038        let user1 = r#"{"type":"user_msg","seq":1,"turn_id":"019f0000-0000-7000-0000-000000000001","message":{"role":"user","parts":[{"type":"text","text":"old"}],"turn_id":"019f0000-0000-7000-0000-000000000001"},"ts":"2026-07-07T00:00:00Z"}"#;
2039        let summary = r#"{"type":"system_msg","seq":4,"turn_id":"019f0000-0000-7000-0000-000000000002","message":{"role":"system","parts":[{"type":"compact_summary","summary":"s","seq_start":0,"seq_end":0,"count":1}],"turn_id":"019f0000-0000-7000-0000-000000000002"},"ts":"2026-07-07T00:00:01Z"}"#;
2040        let compact = r#"{"type":"context_compact","seq":5,"session_id":"sess","before_tokens":200,"after_tokens":50,"compacted_range_start":0,"compacted_range_end":0,"summary_text":"s","replacement_msg_seq":4,"ts":"2026-07-07T00:00:02Z"}"#;
2041        write_events(dir.path(), &[user1, summary, compact]);
2042        let all = replay_all_messages_with_seq(&dir.path().join("events.jsonl")).unwrap();
2043        // all includes both user1 and summary — compaction NOT applied
2044        assert_eq!(all.len(), 2, "all messages preserved (no compaction)");
2045        assert_eq!(all[0].1.text_concat(), "old");
2046    }
2047}