返回 CodeWhale
session_manager.rs
根目录 / crates / engine / src / session_manager.rs
1 //! Session management for resuming conversations.
2 //!
3 //! This module provides functionality for:
4 //! - Saving sessions to disk
5 //! - Listing previous sessions
6 //! - Resuming sessions by ID
7 //! - Managing session lifecycle
8
9 use crate::approval_log::{ApprovalReceipt, ApprovalReceiptStore, ApprovalReplay};
10 use crate::model_routing::AutoRouteReceipt;
11 use crate::project_context::find_git_root;
12 use crate::route_runtime::ContextWindowResolution;
13 use crate::tools::goal::{GoalPauseReason, GoalSnapshot};
14 use crate::tools::plan::PlanSnapshot;
15 use crate::tools::todo::TodoListSnapshot;
16 use chrono::{DateTime, Utc};
17 use codewhale_config::ProviderKind;
18 use codewhale_core::ContextReference;
19 #[cfg(test)]
20 use codewhale_core::{ContextReferenceKind, ContextReferenceSource};
21 use codewhale_models::reasoning_effort_tier::ReasoningEffortTier;
22 use codewhale_models::turn_classify::same_recorded_turn;
23 use codewhale_models::{ContentBlock, Message, SystemPrompt};
24 use codewhale_runtime::artifacts::ArtifactRecord;
25 use codewhale_runtime::session_tree::{
26 SessionEntry, SessionEntryKind, SessionImportContainer, SessionJournal,
27 };
28 use codewhale_util::utils::{sync_directory, write_atomic};
29 use serde::{Deserialize, Serialize};
30 use std::collections::{BTreeMap, BTreeSet};
31 use std::fs::{self, OpenOptions};
32 use std::io;
33 use std::path::{Component, Path, PathBuf};
34 use std::sync::atomic::AtomicBool;
35 use std::sync::{Arc, Mutex};
36 use uuid::Uuid;
37
38 /// Maximum active transcripts to retain separately for exec and interactive modes.
39 ///
40 /// A transcript that falls out of this window is archived, never unlinked
41 /// (#6136); archived records sit outside the cap until the user prunes them,
42 /// and empty auto-created stubs are capped separately (#6137).
43 const MAX_SESSIONS: usize = 50;
44 /// Maximum empty auto-created stubs ("New Session", zero messages) to keep.
45 ///
46 /// The product writes one per boot; they are junk that must never occupy a
47 /// transcript's slot in the cap (#6137).
48 const MAX_EMPTY_SESSION_STUBS: usize = 10;
49 /// Maximum session title length, in `char`s. Matches the bound the session
50 /// picker's rename prompt has always enforced.
51 pub const MAX_SESSION_TITLE_CHARS: usize = 100;
52 pub const WORK_GRAPH_IMPORT_ARCHIVE_DIR: &str = ".work-graph-import-archive";
53 /// Per-session JSONL sidecar holding journal entries a bounded save moved out
54 /// of the session document (#6842): `<sessions>/.journal-archive/<id>.jsonl`.
55 pub const JOURNAL_ARCHIVE_DIR: &str = ".journal-archive";
56 const JOURNAL_ARCHIVE_ROTATE_BYTES: u64 = 4 * 1024 * 1024;
57 const JOURNAL_ARCHIVE_XZ_LEVEL: u32 = 1;
58 pub const JOURNAL_ARCHIVE_DOCTOR_WARN_BYTES: u64 = 64 * 1024 * 1024;
59 const JOURNAL_ARCHIVE_SEGMENT_SUFFIX: &str = ".jsonl.xz";
60 pub const DEFAULT_SESSION_TRIM_TARGET_BYTES: u64 = 7 * 1024 * 1024;
61 pub const MIN_SESSION_TRIM_TARGET_BYTES: u64 = 512 * 1024;
62
63 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
64 pub struct JournalArchiveSummary {
65 pub unique_entries: usize,
66 pub duplicate_lines: usize,
67 pub total_bytes: u64,
68 pub raw_bytes: u64,
69 pub compressed_bytes: u64,
70 pub segment_count: usize,
71 }
72
73 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
74 #[serde(rename_all = "snake_case")]
75 pub enum JournalArchiveSessionStatus {
76 Active,
77 Archived,
78 Orphaned,
79 }
80
81 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
82 pub struct JournalArchiveRecord {
83 pub session_id: String,
84 pub status: JournalArchiveSessionStatus,
85 pub segment_count: usize,
86 pub compressed_segments: usize,
87 pub has_hot_tail: bool,
88 pub raw_bytes: u64,
89 pub compressed_bytes: u64,
90 pub total_bytes: u64,
91 pub modified_at: Option<DateTime<Utc>>,
92 }
93
94 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
95 pub struct JournalArchiveInventory {
96 pub archive_dir: PathBuf,
97 pub present: bool,
98 pub sessions: Vec<JournalArchiveRecord>,
99 pub total_bytes: u64,
100 pub raw_bytes: u64,
101 pub compressed_bytes: u64,
102 pub compressed_segments: usize,
103 pub orphaned_sessions: usize,
104 pub orphaned_bytes: u64,
105 pub unreadable: Vec<String>,
106 }
107
108 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
109 pub struct JournalArchiveCompactEntry {
110 pub session_id: String,
111 pub before_bytes: u64,
112 pub after_bytes: u64,
113 pub unique_entries: usize,
114 pub duplicate_lines_removed: usize,
115 pub before_segments: usize,
116 pub after_segments: usize,
117 pub applied: bool,
118 pub session_is_live: bool,
119 }
120
121 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
122 pub struct JournalArchiveCompactReport {
123 pub applied: bool,
124 pub entries: Vec<JournalArchiveCompactEntry>,
125 pub before_bytes: u64,
126 pub after_bytes: u64,
127 pub duplicate_lines_removed: usize,
128 pub skipped_live_sessions: Vec<String>,
129 }
130
131 #[derive(Debug, Clone, Default)]
132 pub struct JournalArchivePruneOptions {
133 pub orphans_only: bool,
134 pub session_id: Option<String>,
135 pub older_than_days: Option<u64>,
136 pub apply: bool,
137 }
138
139 #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
140 pub struct JournalArchivePruneTarget {
141 pub session_id: String,
142 pub status: JournalArchiveSessionStatus,
143 pub bytes: u64,
144 pub segment_count: usize,
145 pub modified_at: Option<DateTime<Utc>>,
146 pub session_is_live: bool,
147 }
148
149 #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
150 pub struct JournalArchivePruneReport {
151 pub applied: bool,
152 pub orphans_only: bool,
153 pub targets: Vec<JournalArchivePruneTarget>,
154 pub removed_bytes: u64,
155 pub removed_files: usize,
156 pub skipped_live_sessions: Vec<String>,
157 }
158
159 #[derive(Debug, Clone, PartialEq, Eq)]
160 pub struct SessionTrimReport {
161 pub session_id: String,
162 pub applied: bool,
163 pub target_bytes: u64,
164 pub before_file_bytes: u64,
165 pub before_carried_bytes: u64,
166 pub after_file_bytes: u64,
167 pub after_carried_bytes: u64,
168 pub before_journal_entries: usize,
169 pub after_journal_entries: usize,
170 pub before_active_entries: usize,
171 pub after_active_entries: usize,
172 pub archived_off_branch_entries: usize,
173 pub archived_active_entries: usize,
174 pub pruned_ended_operations: bool,
175 pub archive_path: Option<PathBuf>,
176 pub session_is_live: bool,
177 }
178
179 struct SessionTrimPlan {
180 candidate: SavedSession,
181 entries_to_archive: Vec<SessionEntry>,
182 before_carried_bytes: u64,
183 after_file_bytes: u64,
184 after_carried_bytes: u64,
185 before_journal_entries: usize,
186 after_journal_entries: usize,
187 before_active_entries: usize,
188 after_active_entries: usize,
189 archived_off_branch_entries: usize,
190 archived_active_entries: usize,
191 pruned_ended_operations: bool,
192 }
193 /// Off-branch entries a session document may carry before an autosave
194 /// archives the excess. Together with [`JOURNAL_RETAINED_DEAD_ENTRIES`] this
195 /// keeps a compacted journal far below `MAX_CANONICAL_HISTORY_ENTRIES`. A
196 /// document whose file is already over `MAX_CANONICAL_HISTORY_BYTES` archives
197 /// every off-branch entry instead.
198 const JOURNAL_PRUNE_DEAD_THRESHOLD: usize = 4_096;
199 /// Recent off-branch entries kept in the document after archiving, so `/tree`
200 /// and `/branch` stay cheap for recent history.
201 const JOURNAL_RETAINED_DEAD_ENTRIES: usize = 1_024;
202 #[derive(Clone, Copy)]
203 enum JournalPrune {
204 Keep,
205 Excess,
206 AllOffBranch,
207 }
208 const SESSION_GOALS_DIR: &str = ".goals";
209 const CURRENT_SESSION_GOAL_SCHEMA_VERSION: u32 = 2;
210 const MAX_SESSION_GOAL_OBJECTIVE_CHARS: usize = 8_192;
211 const MAX_SESSION_GOAL_FILE_BYTES: u64 = 64 * 1_024;
212 pub const CURRENT_SESSION_SCHEMA_VERSION: u32 = 2;
213 pub const SESSION_METADATA_READ_LIMIT: usize = 16 * 1024 * 1024;
214
215 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
216 pub struct SessionObservation {
217 sessions_dir: PathBuf,
218 session_id: String,
219 document_sha256: Option<String>,
220 checkpoint_sha256: Option<String>,
221 }
222
223 impl SessionObservation {
224 pub(crate) fn same_session_target(&self, other: &Self) -> bool {
225 self.sessions_dir == other.sessions_dir && self.session_id == other.session_id
226 }
227
228 pub(crate) fn same_checkpoint(&self, other: &Self) -> bool {
229 self.sessions_dir == other.sessions_dir
230 && self.session_id == other.session_id
231 && self.checkpoint_sha256 == other.checkpoint_sha256
232 }
233 }
234
235 #[derive(Debug, Clone)]
236 pub struct NativeSessionMutation {
237 before: SessionObservation,
238 after: SessionObservation,
239 }
240
241 #[derive(Debug, Clone, PartialEq, Eq)]
242 pub enum SessionWriteOwner {
243 Submission(String),
244 Engine(crate::core::ops::SessionSnapshotSource),
245 Control(crate::core::ops::SessionControlId),
246 }
247
248 impl SessionWriteOwner {
249 pub fn snapshot_source(&self) -> Option<crate::core::ops::SessionSnapshotSource> {
250 match self {
251 Self::Engine(source) => Some(source.clone()),
252 Self::Control(id) => Some(crate::core::ops::SessionSnapshotSource::control(id.clone())),
253 Self::Submission(_) => None,
254 }
255 }
256
257 pub fn matches_source(&self, source: &crate::core::ops::SessionSnapshotSource) -> bool {
258 match self {
259 Self::Submission(id) => source.submission_id.as_deref() == Some(id.as_str()),
260 Self::Engine(own) => own == source,
261 Self::Control(id) => source.control_id.as_ref() == Some(id),
262 }
263 }
264
265 pub fn same_execution(&self, other: &Self) -> bool {
266 match (self, other) {
267 (Self::Engine(a), Self::Engine(b)) => a == b,
268 (Self::Submission(a), Self::Submission(b)) => a == b,
269 (Self::Submission(id), Self::Engine(source))
270 | (Self::Engine(source), Self::Submission(id)) => {
271 source.submission_id.as_ref() == Some(id)
272 }
273 (Self::Control(a), Self::Control(b)) => a == b,
274 _ => false,
275 }
276 }
277
278 pub fn control() -> Self {
279 Self::Control(crate::core::ops::SessionControlId::new())
280 }
281 }
282
283 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
284 pub enum SessionPublicationKind {
285 Checkpoint,
286 Snapshot,
287 Completion,
288 }
289
290 #[derive(Debug, Clone)]
291 struct NativeCheckpointAuthority {
292 sha256: String,
293 owner: SessionWriteOwner,
294 }
295
296 #[derive(Debug, Clone)]
297 struct SessionPublicationBase {
298 observation: SessionObservation,
299 checkpoint: Option<NativeCheckpointAuthority>,
300 }
301
302 #[derive(Debug, Clone)]
303 pub struct SessionPublication {
304 pub path: PathBuf,
305 pub metadata: SessionMetadata,
306 observation: SessionObservation,
307 pub checkpoint_receipt: crate::core::events::SessionCheckpointReceipt,
308 checkpoint: Option<NativeCheckpointAuthority>,
309 }
310
311 impl SessionPublication {
312 pub fn observation(&self) -> &SessionObservation {
313 &self.observation
314 }
315
316 fn base(&self) -> SessionPublicationBase {
317 SessionPublicationBase {
318 observation: self.observation.clone(),
319 checkpoint: self.checkpoint.clone(),
320 }
321 }
322
323 pub fn write_receipt(&self) -> SessionWriteReceipt {
324 SessionWriteReceipt::from_base(self.base())
325 }
326 }
327
328 #[derive(Debug, Clone)]
329 pub struct SessionWriteReceipt(Arc<Mutex<SessionWriteState>>);
330
331 #[derive(Debug)]
332 enum SessionWriteState {
333 Observed(SessionPublicationBase),
334 Pending {
335 predecessor: SessionWriteReceipt,
336 owner: SessionWriteOwner,
337 publication_id: String,
338 checkpoint_predecessor: Option<SessionWriteOwner>,
339 acknowledgement_required: bool,
340 result: Option<Result<Box<SessionPublication>, String>>,
341 closed: bool,
342 },
343 }
344
345 impl SessionWriteReceipt {
346 fn session_scope(&self, require_open: bool) -> io::Result<(PathBuf, String)> {
347 let predecessor = match &*self
348 .0
349 .lock()
350 .unwrap_or_else(std::sync::PoisonError::into_inner)
351 {
352 SessionWriteState::Observed(base) => {
353 return Ok((
354 base.observation.sessions_dir.clone(),
355 base.observation.session_id.clone(),
356 ));
357 }
358 SessionWriteState::Pending { closed: true, .. } if require_open => {
359 return Err(io::Error::new(
360 io::ErrorKind::ResourceBusy,
361 "session producer was refused",
362 ));
363 }
364 SessionWriteState::Pending {
365 result: Some(Err(_)),
366 acknowledgement_required: true,
367 ..
368 } if require_open => {
369 return Err(io::Error::new(
370 io::ErrorKind::ResourceBusy,
371 "session checkpoint acknowledgement failed",
372 ));
373 }
374 SessionWriteState::Pending {
375 result: Some(Ok(publication)),
376 ..
377 } => {
378 return Ok((
379 publication.observation.sessions_dir.clone(),
380 publication.observation.session_id.clone(),
381 ));
382 }
383 SessionWriteState::Pending { predecessor, .. } => predecessor.clone(),
384 };
385 predecessor.session_scope(require_open)
386 }
387
388 pub fn usage_origin(
389 &self,
390 scope: crate::cost_status::CostScopeToken,
391 ) -> io::Result<crate::cost_status::NativeUsageOrigin> {
392 let (store, session) = self.session_scope(true)?;
393 Ok(crate::cost_status::NativeUsageOrigin::session(
394 scope, store, session,
395 ))
396 }
397
398 pub fn project_usage_record(
399 &self,
400 record: &crate::cost_status::RuntimeUsageRecord,
401 cost: &mut SessionCostSnapshot,
402 ) -> io::Result<Option<(u64, u64)>> {
403 let mut candidate = cost.clone();
404 let delta = candidate.project_usage_record(record)?;
405 *cost = candidate;
406 Ok(Some(delta))
407 }
408
409 fn from_base(base: SessionPublicationBase) -> Self {
410 Self(Arc::new(Mutex::new(SessionWriteState::Observed(base))))
411 }
412
413 pub(crate) fn observed(observation: SessionObservation) -> Self {
414 Self::from_base(SessionPublicationBase {
415 observation,
416 checkpoint: None,
417 })
418 }
419
420 pub fn capture(&self, owner: SessionWriteOwner) -> io::Result<Self> {
421 self.capture_with_id(owner, Uuid::new_v4().to_string())
422 }
423
424 pub(crate) fn capture_history_control(
425 &self,
426 operation: &crate::runtime_threads::RuntimeHistoryOperation,
427 ) -> io::Result<Self> {
428 let id = operation
429 .session_publication_id()
430 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error.to_string()))?;
431 self.capture_with_id(
432 SessionWriteOwner::Control(crate::core::ops::SessionControlId::for_admitted_history(
433 id.clone(),
434 )),
435 id,
436 )
437 }
438
439 fn capture_with_id(
440 &self,
441 owner: SessionWriteOwner,
442 publication_id: String,
443 ) -> io::Result<Self> {
444 let (resolved, retry) = match &*self
445 .0
446 .lock()
447 .unwrap_or_else(std::sync::PoisonError::into_inner)
448 {
449 SessionWriteState::Observed(base) => (Some(base.clone()), false),
450 SessionWriteState::Pending {
451 result: Some(Ok(publication)),
452 ..
453 } => (Some(publication.base()), false),
454 SessionWriteState::Pending { closed: true, .. } => {
455 return Err(io::Error::new(
456 io::ErrorKind::ResourceBusy,
457 "session publication was refused or superseded before its write",
458 ));
459 }
460 SessionWriteState::Pending {
461 result: Some(Err(_)),
462 acknowledgement_required: true,
463 ..
464 } => {
465 return Err(io::Error::new(
466 io::ErrorKind::ResourceBusy,
467 "checkpoint acknowledgement failed; recover or retry that captured checkpoint before publishing its successor",
468 ));
469 }
470 SessionWriteState::Pending {
471 result: Some(Err(_)),
472 ..
473 } => (None, true),
474 SessionWriteState::Pending { result: None, .. } => (None, false),
475 };
476 let predecessor = if let Some(base) = resolved {
477 Self::from_base(base)
478 } else if retry {
479 Self::from_base(self.retry_base()?)
480 } else {
481 self.clone()
482 };
483 Ok(Self(Arc::new(Mutex::new(SessionWriteState::Pending {
484 predecessor,
485 owner,
486 publication_id,
487 checkpoint_predecessor: None,
488 acknowledgement_required: false,
489 result: None,
490 closed: false,
491 }))))
492 }
493
494 fn retry_base(&self) -> io::Result<SessionPublicationBase> {
495 let mut current = self.clone();
496 loop {
497 let next = match &*current
498 .0
499 .lock()
500 .unwrap_or_else(std::sync::PoisonError::into_inner)
501 {
502 SessionWriteState::Observed(base) => return Ok(base.clone()),
503 SessionWriteState::Pending {
504 result: Some(Ok(publication)),
505 ..
506 } => return Ok(publication.base()),
507 SessionWriteState::Pending { closed: true, .. } => {
508 return Err(io::Error::new(
509 io::ErrorKind::ResourceBusy,
510 "refused or superseded publication cannot grant retry authority",
511 ));
512 }
513 SessionWriteState::Pending {
514 acknowledgement_required: true,
515 result: Some(Err(_)),
516 ..
517 } => {
518 return Err(io::Error::new(
519 io::ErrorKind::ResourceBusy,
520 "failed checkpoint acknowledgement cannot grant successor publication authority",
521 ));
522 }
523 SessionWriteState::Pending {
524 result: Some(Err(_)),
525 predecessor,
526 ..
527 } => predecessor.clone(),
528 SessionWriteState::Pending { result: None, .. } => {
529 return Err(io::Error::new(
530 io::ErrorKind::ResourceBusy,
531 "retry predecessor still owes its real publication acknowledgement",
532 ));
533 }
534 };
535 current = next;
536 }
537 }
538
539 fn base(&self) -> io::Result<SessionPublicationBase> {
540 match &*self
541 .0
542 .lock()
543 .unwrap_or_else(std::sync::PoisonError::into_inner)
544 {
545 SessionWriteState::Observed(base) => Ok(base.clone()),
546 SessionWriteState::Pending {
547 result: Some(Ok(publication)),
548 ..
549 } => Ok(publication.base()),
550 SessionWriteState::Pending {
551 result: Some(Err(error)),
552 ..
553 } => Err(io::Error::new(io::ErrorKind::ResourceBusy, error.clone())),
554 SessionWriteState::Pending { result: None, .. } => Err(io::Error::new(
555 io::ErrorKind::ResourceBusy,
556 "session publication predecessor has not acknowledged its write",
557 )),
558 }
559 }
560
561 pub fn adopt_mutation(&self, mutation: &NativeSessionMutation) -> io::Result<Self> {
562 let before = &mutation.before;
563 let after = &mutation.after;
564 let mut base = self.base()?;
565 if &base.observation != before
566 || before.sessions_dir != after.sessions_dir
567 || before.session_id != after.session_id
568 || before.checkpoint_sha256 != after.checkpoint_sha256
569 {
570 return Err(io::Error::new(
571 io::ErrorKind::ResourceBusy,
572 "lifecycle mutation did not replace this captured session source",
573 ));
574 }
575 base.observation = after.clone();
576 Ok(Self::from_base(base))
577 }
578
579 pub(crate) fn targets(&self, sessions_dir: &Path, id: &str) -> io::Result<bool> {
580 let base = self.base()?;
581 Ok(base.observation.sessions_dir == sessions_dir && base.observation.session_id == id)
582 }
583
584 pub fn observation(&self) -> io::Result<SessionObservation> {
585 self.base().map(|base| base.observation)
586 }
587
588 fn expected(&self) -> io::Result<SessionPublicationBase> {
589 let predecessor = match &*self
590 .0
591 .lock()
592 .unwrap_or_else(std::sync::PoisonError::into_inner)
593 {
594 SessionWriteState::Pending { closed: true, .. } => {
595 return Err(io::Error::new(
596 io::ErrorKind::ResourceBusy,
597 "session publication was refused or superseded before its write",
598 ));
599 }
600 SessionWriteState::Pending { predecessor, .. } => predecessor.clone(),
601 SessionWriteState::Observed(_) => {
602 return Err(io::Error::new(
603 io::ErrorKind::InvalidInput,
604 "session publication has no captured native producer",
605 ));
606 }
607 };
608 predecessor.base()
609 }
610
611 pub fn require_checkpoint_acknowledgement(&self) {
612 if let SessionWriteState::Pending {
613 acknowledgement_required,
614 ..
615 } = &mut *self
616 .0
617 .lock()
618 .unwrap_or_else(std::sync::PoisonError::into_inner)
619 {
620 *acknowledgement_required = true;
621 }
622 }
623
624 pub fn publication_id(&self) -> Option<String> {
625 match &*self
626 .0
627 .lock()
628 .unwrap_or_else(std::sync::PoisonError::into_inner)
629 {
630 SessionWriteState::Pending { publication_id, .. } => Some(publication_id.clone()),
631 SessionWriteState::Observed(_) => None,
632 }
633 }
634
635 pub fn owner(&self) -> Option<SessionWriteOwner> {
636 match &*self
637 .0
638 .lock()
639 .unwrap_or_else(std::sync::PoisonError::into_inner)
640 {
641 SessionWriteState::Pending { owner, .. } => Some(owner.clone()),
642 SessionWriteState::Observed(_) => None,
643 }
644 }
645
646 fn checkpoint_predecessor(&self) -> Option<SessionWriteOwner> {
647 match &*self
648 .0
649 .lock()
650 .unwrap_or_else(std::sync::PoisonError::into_inner)
651 {
652 SessionWriteState::Pending {
653 checkpoint_predecessor,
654 ..
655 } => checkpoint_predecessor.clone(),
656 SessionWriteState::Observed(_) => None,
657 }
658 }
659
660 pub fn is_successor_of(&self, previous: &Self) -> bool {
661 if Arc::ptr_eq(&self.0, &previous.0) {
662 return false;
663 }
664 match &*self
665 .0
666 .lock()
667 .unwrap_or_else(std::sync::PoisonError::into_inner)
668 {
669 SessionWriteState::Pending {
670 predecessor,
671 result: None,
672 closed: false,
673 ..
674 } => Arc::ptr_eq(&predecessor.0, &previous.0),
675 _ => false,
676 }
677 }
678
679 pub fn coalesce_after(&self, previous: &Self, kind: SessionPublicationKind) -> bool {
680 if Arc::ptr_eq(&self.0, &previous.0) {
681 return false;
682 }
683 let mut current = self
684 .0
685 .lock()
686 .unwrap_or_else(std::sync::PoisonError::into_inner);
687 let SessionWriteState::Pending {
688 predecessor,
689 checkpoint_predecessor: current_checkpoint,
690 result: None,
691 ..
692 } = &mut *current
693 else {
694 return false;
695 };
696 if !Arc::ptr_eq(&predecessor.0, &previous.0) {
697 return false;
698 }
699 let mut prior = previous
700 .0
701 .lock()
702 .unwrap_or_else(std::sync::PoisonError::into_inner);
703 let SessionWriteState::Pending {
704 predecessor: base,
705 owner,
706 checkpoint_predecessor,
707 result,
708 closed,
709 ..
710 } = &mut *prior
711 else {
712 return false;
713 };
714 if result.is_some() || *closed {
715 return false;
716 }
717 *predecessor = base.clone();
718 *current_checkpoint = if kind == SessionPublicationKind::Checkpoint {
719 Some(owner.clone())
720 } else {
721 checkpoint_predecessor.clone()
722 };
723 *closed = true;
724 *result = Some(Err(
725 "session publication coalesced without a durable acknowledgement".into(),
726 ));
727 true
728 }
729
730 fn finish(&self, result: &io::Result<SessionPublication>) {
731 if let SessionWriteState::Pending { result: stored, .. } = &mut *self
732 .0
733 .lock()
734 .unwrap_or_else(std::sync::PoisonError::into_inner)
735 {
736 *stored = Some(
737 result
738 .as_ref()
739 .map(|publication| Box::new(publication.clone()))
740 .map_err(ToString::to_string),
741 );
742 }
743 }
744
745 pub fn refuse(&self, error: impl Into<String>) {
746 if let SessionWriteState::Pending { result, closed, .. } = &mut *self
747 .0
748 .lock()
749 .unwrap_or_else(std::sync::PoisonError::into_inner)
750 && result.is_none()
751 {
752 *closed = true;
753 *result = Some(Err(error.into()));
754 }
755 }
756 }
757
758 struct SessionWriteMetadata {
759 saved: Option<SessionMetadata>,
760 checkpoint: Option<SessionMetadata>,
761 }
762
763 #[derive(Default)]
764 struct SessionCatalog {
765 records: Vec<(PathBuf, SessionMetadata)>,
766 failures: Vec<(PathBuf, io::Error)>,
767 }
768
769 impl SessionCatalog {
770 fn warning(&self) -> Option<String> {
771 self.failures.first().map(|(path, error)| {
772 format!(
773 "{} session record(s) could not be inspected; {}: {error}",
774 self.failures.len(),
775 path.display()
776 )
777 })
778 }
779
780 fn into_complete(self) -> io::Result<Vec<(PathBuf, SessionMetadata)>> {
781 if let Some((path, error)) = self.failures.into_iter().next() {
782 return Err(io::Error::new(
783 error.kind(),
784 format!("session catalog is incomplete; {}: {error}", path.display()),
785 ));
786 }
787 Ok(self.records)
788 }
789 }
790
791 pub(crate) fn read_session_reference_bytes(path: &Path) -> io::Result<Vec<u8>> {
792 use std::io::Read as _;
793 let file = open_private_read_file(path)?;
794 let mut bytes = Vec::new();
795 file.take(SESSION_METADATA_READ_LIMIT as u64)
796 .read_to_end(&mut bytes)?;
797 if bytes.len() == SESSION_METADATA_READ_LIMIT {
798 return Err(io::Error::new(
799 io::ErrorKind::FileTooLarge,
800 "session reference inspection exceeds 16 MiB; source left unchanged",
801 ));
802 }
803 Ok(bytes)
804 }
805
806 const CURRENT_QUEUE_SCHEMA_VERSION: u32 = 1;
807 const LATE_USAGE_DIR: &str = ".late-usage";
808 const CURRENT_LATE_USAGE_SCHEMA_VERSION: u32 = 2;
809 const MAX_LATE_USAGE_UNRESOLVED_RECORDS_PER_SESSION: usize = 64;
810 const MAX_LATE_USAGE_LEDGER_BYTES: u64 = 1024 * 1024;
811 const LATE_USAGE_DELETED: &[u8] = b"codewhale-session-deleted-v1\n";
812 fn serialize_settled_reasons<S>(
813 reasons: &BTreeSet<String>,
814 serializer: S,
815 ) -> Result<S::Ok, S::Error>
816 where
817 S: serde::Serializer,
818 {
819 use serde::Serialize as _;
820 let in_progress = crate::pricing::UnpricedReason::RequestInProgress.label();
821 let unknown = crate::pricing::UnpricedReason::RequestOutcomeUnknown.label();
822 reasons
823 .iter()
824 .map(|reason| {
825 if reason == in_progress {
826 unknown
827 } else {
828 reason.as_str()
829 }
830 })
831 .collect::<BTreeSet<_>>()
832 .serialize(serializer)
833 }
834
835 fn is_false(value: &bool) -> bool {
836 !*value
837 }
838
839 const LATE_USAGE_UNAVAILABLE_REASON: &str = "late_usage_ledger_unavailable";
840
841 #[derive(Clone, Copy)]
842 enum SessionRemoval {
843 Explicit,
844 Retention,
845 }
846
847 #[derive(Debug, Clone, Serialize, Deserialize)]
848 struct LateUsageRecord {
849 source_fingerprint: String,
850 turn_fingerprint: String,
851 route: crate::cost_status::EffectiveRouteEnvelope,
852 #[serde(default, skip_serializing_if = "Option::is_none")]
853 usage: Option<codewhale_models::Usage>,
854 #[serde(
855 default,
856 skip_serializing_if = "crate::cost_status::RuntimeUsageMissingReason::is_success"
857 )]
858 reason: crate::cost_status::RuntimeUsageMissingReason,
859 #[serde(default, skip_serializing_if = "Option::is_none")]
860 decision: Option<crate::cost_status::RuntimeDecisionReceipt>,
861 #[serde(default, skip_serializing_if = "Option::is_none")]
862 settlement: Option<crate::cost_status::UsageSourceRevision>,
863 #[serde(default, skip_serializing_if = "is_false")]
864 diagnostic_only: bool,
865 }
866
867 impl LateUsageRecord {
868 fn runtime_record(&self) -> crate::cost_status::RuntimeUsageRecord {
869 let mut record = crate::cost_status::RuntimeUsageRecord::legacy(
870 self.source_fingerprint.clone(),
871 crate::cost_status::EffectiveRouteUsage {
872 route: self.route.clone(),
873 usage: self.usage.clone().unwrap_or_default(),
874 },
875 );
876 record.settlement = self.settlement.clone();
877 record
878 }
879
880 fn unresolved(&self) -> bool {
881 if self.diagnostic_only {
882 return false;
883 }
884 self.settlement.as_ref().map_or_else(
885 || {
886 self.usage
887 .as_ref()
888 .is_none_or(|usage| *usage == codewhale_models::Usage::default())
889 },
890 |revision| {
891 matches!(
892 revision.coverage,
893 crate::llm_client::ProviderUsageCoverage::Missing
894 | crate::llm_client::ProviderUsageCoverage::Incomplete
895 )
896 },
897 )
898 }
899
900 fn captured(
901 turn_id: &str,
902 source_id: &str,
903 route: &crate::cost_status::EffectiveRouteEnvelope,
904 usage: Option<&codewhale_models::Usage>,
905 decision: Option<&crate::cost_status::RuntimeDecisionReceipt>,
906 reason: crate::cost_status::RuntimeUsageMissingReason,
907 ) -> Self {
908 Self {
909 source_fingerprint: crate::cost_status::usage_source_fingerprint(source_id),
910 turn_fingerprint: crate::cost_status::usage_source_fingerprint(turn_id),
911 route: route.sanitized_for_persistence(),
912 usage: usage
913 .filter(|usage| **usage != codewhale_models::Usage::default())
914 .cloned(),
915 reason,
916 decision: decision.map(crate::cost_status::RuntimeDecisionReceipt::sanitized),
917 settlement: None,
918 diagnostic_only: false,
919 }
920 }
921 }
922
923 #[derive(Debug, Clone, Serialize, Deserialize)]
924 struct LateUsageLedger {
925 schema_version: u32,
926 #[serde(default)]
927 records: Vec<LateUsageRecord>,
928 #[serde(default)]
929 overflowed: bool,
930 }
931
932 impl Default for LateUsageLedger {
933 fn default() -> Self {
934 Self {
935 schema_version: CURRENT_LATE_USAGE_SCHEMA_VERSION,
936 records: Vec::new(),
937 overflowed: false,
938 }
939 }
940 }
941
942 fn is_sha256_fingerprint(value: &str) -> bool {
943 value.len() == 64
944 && value
945 .bytes()
946 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
947 }
948
949 const fn default_session_schema_version() -> u32 {
950 1
951 }
952
953 const fn default_queue_schema_version() -> u32 {
954 CURRENT_QUEUE_SCHEMA_VERSION
955 }
956
957 fn normalize_managed_dir(path: PathBuf) -> std::io::Result<PathBuf> {
958 if path.as_os_str().is_empty() {
959 return Err(std::io::Error::new(
960 std::io::ErrorKind::InvalidInput,
961 "managed directory path cannot be empty",
962 ));
963 }
964 if path.components().any(|component| {
965 matches!(
966 component,
967 Component::ParentDir | Component::Prefix(_) | Component::RootDir
968 )
969 }) && path.is_relative()
970 {
971 return Err(std::io::Error::new(
972 std::io::ErrorKind::InvalidInput,
973 "managed directory path cannot contain traversal components",
974 ));
975 }
976 if path.is_absolute() {
977 return Ok(path);
978 }
979 std::env::current_dir().map(|cwd| cwd.join(path))
980 }
981
982 /// Open (creating if needed) an advisory-lock sidecar that is owner-only
983 /// (0600), one regular link, and never followed through a symlink.
984 pub fn open_private_lock_file(path: &Path) -> io::Result<fs::File> {
985 let mut options = OpenOptions::new();
986 options.create(true).read(true).write(true);
987 #[cfg(unix)]
988 {
989 use std::os::unix::fs::OpenOptionsExt;
990 options
991 .mode(0o600)
992 .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK);
993 let file = options.open(path)?;
994 validate_private_regular_file(&file, path)?;
995 codewhale_config::private_directory::tighten_mode_of(&file, path, 0o600)
996 .map_err(|error| std::io::Error::other(error.to_string()))?;
997 Ok(file)
998 }
999 #[cfg(windows)]
1000 {
1001 use std::os::windows::fs::OpenOptionsExt as _;
1002 use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
1003 options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
1004 let file = options.open(path)?;
1005 validate_private_regular_file(&file, path)?;
1006 Ok(file)
1007 }
1008 #[cfg(all(not(unix), not(windows)))]
1009 {
1010 let file = options.open(path)?;
1011 validate_private_regular_file(&file, path)?;
1012 Ok(file)
1013 }
1014 }
1015
1016 fn open_private_read_file(path: &Path) -> io::Result<fs::File> {
1017 let mut options = OpenOptions::new();
1018 options.read(true);
1019 #[cfg(unix)]
1020 {
1021 use std::os::unix::fs::OpenOptionsExt as _;
1022 options.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK);
1023 }
1024 #[cfg(windows)]
1025 {
1026 use std::os::windows::fs::OpenOptionsExt as _;
1027 use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
1028 options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
1029 }
1030 let file = options.open(path)?;
1031 validate_private_regular_file(&file, path)?;
1032 Ok(file)
1033 }
1034
1035 #[cfg(unix)]
1036 fn validate_private_regular_file(file: &fs::File, path: &Path) -> io::Result<()> {
1037 use std::os::unix::fs::MetadataExt as _;
1038
1039 let metadata = file.metadata()?;
1040 if !metadata.is_file() || metadata.nlink() != 1 {
1041 return Err(io::Error::new(
1042 io::ErrorKind::InvalidData,
1043 format!(
1044 "private sidecar file {} must be one regular filesystem link",
1045 path.display()
1046 ),
1047 ));
1048 }
1049 Ok(())
1050 }
1051
1052 #[cfg(windows)]
1053 fn validate_private_regular_file(file: &fs::File, path: &Path) -> io::Result<()> {
1054 use std::os::windows::fs::MetadataExt as _;
1055 use std::os::windows::io::AsRawHandle as _;
1056 use windows_sys::Win32::Storage::FileSystem::{
1057 BY_HANDLE_FILE_INFORMATION, FILE_ATTRIBUTE_REPARSE_POINT, GetFileInformationByHandle,
1058 };
1059
1060 let metadata = file.metadata()?;
1061 if !metadata.is_file() || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
1062 return Err(io::Error::new(
1063 io::ErrorKind::InvalidData,
1064 format!(
1065 "private sidecar file {} must be a non-reparse regular file",
1066 path.display()
1067 ),
1068 ));
1069 }
1070 let mut info = BY_HANDLE_FILE_INFORMATION::default();
1071 // SAFETY: `file` keeps the handle valid and `info` is writable for the call.
1072 if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 {
1073 return Err(io::Error::last_os_error());
1074 }
1075 if info.nNumberOfLinks != 1 {
1076 return Err(io::Error::new(
1077 io::ErrorKind::InvalidData,
1078 format!(
1079 "private sidecar file {} must have exactly one filesystem link",
1080 path.display()
1081 ),
1082 ));
1083 }
1084 Ok(())
1085 }
1086
1087 #[cfg(all(not(unix), not(windows)))]
1088 fn validate_private_regular_file(file: &fs::File, path: &Path) -> io::Result<()> {
1089 if !file.metadata()?.is_file() {
1090 return Err(io::Error::new(
1091 io::ErrorKind::InvalidData,
1092 format!("private sidecar file {} must be regular", path.display()),
1093 ));
1094 }
1095 Ok(())
1096 }
1097
1098 /// Persisted queued message for offline/degraded mode.
1099 #[derive(Debug, Clone, Serialize, Deserialize)]
1100 pub struct QueuedSessionMessage {
1101 pub display: String,
1102 #[serde(default)]
1103 pub skill_instruction: Option<String>,
1104 #[serde(default)]
1105 pub skill_provenance: Option<codewhale_skills::SkillProvenance>,
1106 }
1107
1108 /// Persisted queue state for recovery after restart/crash.
1109 #[derive(Debug, Clone, Serialize, Deserialize)]
1110 pub struct OfflineQueueState {
1111 #[serde(default = "default_queue_schema_version")]
1112 pub schema_version: u32,
1113 /// Session ID this queue belongs to. Redundant with the per-session file
1114 /// name it is stored under; the UI's restore path still compares it
1115 /// against the live session before adopting the messages.
1116 #[serde(default)]
1117 pub session_id: Option<String>,
1118 #[serde(default)]
1119 pub messages: Vec<QueuedSessionMessage>,
1120 #[serde(default)]
1121 pub draft: Option<QueuedSessionMessage>,
1122 }
1123
1124 /// Result of explicitly repairing a persisted session for process resume.
1125 ///
1126 /// Normal snapshot reads must not infer that an unmatched tool call crashed:
1127 /// an embedding host can persist and inspect a session while that tool is
1128 /// still running. Hosts should use [`SessionManager::load_session_snapshot`]
1129 /// during normal operation and reserve this recovery path for a known process
1130 /// or engine restart.
1131 #[derive(Debug, Clone)]
1132 pub struct SessionRecovery {
1133 pub session: SavedSession,
1134 pub changed: bool,
1135 pub repaired_call_count: usize,
1136 pub duplicate_result_count: usize,
1137 pub orphan_result_count: usize,
1138 }
1139
1140 impl Default for OfflineQueueState {
1141 fn default() -> Self {
1142 Self {
1143 schema_version: CURRENT_QUEUE_SCHEMA_VERSION,
1144 session_id: None,
1145 messages: Vec::new(),
1146 draft: None,
1147 }
1148 }
1149 }
1150
1151 /// Durable context-reference metadata attached to a user message.
1152 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1153 pub struct SessionContextReference {
1154 pub message_index: usize,
1155 pub reference: ContextReference,
1156 }
1157
1158 /// Session metadata stored with each saved session
1159 #[derive(Debug, Clone, Serialize, Deserialize)]
1160 pub struct SessionMetadata {
1161 /// Unique session identifier
1162 pub id: String,
1163 /// Actual host Runtime authority; independent of the conversation id.
1164 /// Legacy/imported conversations have no binding until saved by a host.
1165 #[serde(default, skip_serializing_if = "Option::is_none")]
1166 pub runtime_store: Option<crate::runtime_threads::RuntimeStoreBinding>,
1167 #[serde(default, skip_serializing_if = "Option::is_none")]
1168 pub publication_id: Option<String>,
1169 #[serde(skip)]
1170 pub native_mutation_observation: Option<NativeSessionMutation>,
1171 /// Human-readable title (derived from first message)
1172 pub title: String,
1173 #[serde(default, skip_serializing_if = "is_false")]
1174 pub title_is_custom: bool,
1175 /// When the session was created
1176 pub created_at: DateTime<Utc>,
1177 /// When the session was last updated
1178 pub updated_at: DateTime<Utc>,
1179 /// Number of messages in the session
1180 pub message_count: usize,
1181 /// Total tokens used
1182 pub total_tokens: u64,
1183 /// Model used for the session
1184 pub model: String,
1185 /// Provider used for the session model. Defaults for legacy saved sessions.
1186 #[serde(default = "default_model_provider")]
1187 pub model_provider: String,
1188 /// Exact configured provider key. This is separate from `model_provider`
1189 /// so old consumers can keep treating that field as the built-in provider
1190 /// kind (`custom` for every named custom route).
1191 #[serde(default, skip_serializing_if = "Option::is_none")]
1192 pub model_provider_id: Option<String>,
1193 #[serde(default, skip_serializing_if = "Option::is_none")]
1194 pub exec_route_binding: Option<crate::route_receipt::ExecRouteBinding>,
1195 /// Workspace directory
1196 pub workspace: PathBuf,
1197 /// Optional mode label (agent/plan/etc.)
1198 #[serde(default)]
1199 pub mode: Option<String>,
1200 /// Accumulated cost data for persisted billing and high-water mark.
1201 #[serde(default)]
1202 pub cost: SessionCostSnapshot,
1203 /// Source session id when this session was created with `deepseek fork`.
1204 #[serde(default, skip_serializing_if = "Option::is_none")]
1205 pub parent_session_id: Option<String>,
1206 /// Source message count at fork time. This is intentionally coarse:
1207 /// current saved sessions are linear JSON files, not per-entry trees.
1208 #[serde(default, skip_serializing_if = "Option::is_none")]
1209 pub forked_from_message_count: Option<usize>,
1210 /// Cumulative turn duration in seconds (sum of completed turn elapsed
1211 /// times). Persisted so the footer "worked" chip survives restarts
1212 /// (#2038).
1213 #[serde(default)]
1214 pub cumulative_turn_secs: u64,
1215 /// Durable archive flag (#2934 / #4397). Archived sessions stay on disk
1216 /// and stay loadable; they are hidden from the default browse surfaces
1217 /// and are never chosen by auto-resume.
1218 ///
1219 /// This mirrors `ThreadRecord::archived` in [`crate::runtime_threads`] so
1220 /// the TUI session surfaces and the Runtime API/web dashboard project the
1221 /// same lifecycle field instead of two divergent notions of "put away".
1222 /// Additive and `skip_serializing_if`-guarded: sessions written before
1223 /// v0.9.2 load as `archived = false` and round-trip byte-identically
1224 /// until the flag is actually set.
1225 #[serde(default, skip_serializing_if = "is_not_archived")]
1226 pub archived: bool,
1227 #[serde(default)]
1228 pub spawn_depth: u32,
1229 }
1230
1231 fn is_not_archived(archived: &bool) -> bool {
1232 !*archived
1233 }
1234
1235 /// Sessions currently owned by an in-process interactive surface (the TUI).
1236 ///
1237 /// A saved session is a file, and a running TUI holds the authoritative copy
1238 /// in memory: it autosaves the whole document from `App` state. That makes an
1239 /// out-of-band write to the *same* session unsafe — the next autosave would
1240 /// silently revert it. Rather than let that happen quietly, the owner claims
1241 /// the id here and any external writer is refused.
1242 ///
1243 /// A static registry rather than a field on `RuntimeApiState` because the
1244 /// embedded Runtime API runs inside the TUI process. A standalone
1245 /// `codewhale web` has an empty registry, so external writers consult
1246 /// [`SessionManager::is_session_live_anywhere`], which also sees the
1247 /// cross-process lease a TUI in another process holds.
1248 static LIVE_SESSIONS: std::sync::OnceLock<std::sync::RwLock<std::collections::HashSet<String>>> =
1249 std::sync::OnceLock::new();
1250
1251 fn live_sessions() -> &'static std::sync::RwLock<std::collections::HashSet<String>> {
1252 LIVE_SESSIONS.get_or_init(Default::default)
1253 }
1254
1255 /// Who is asking to mutate a saved session.
1256 ///
1257 /// This is an authority distinction, not a convenience one: the owner may
1258 /// write because it will update its in-memory copy in the same step; anyone
1259 /// else may not, because it cannot.
1260 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1261 pub enum SessionMutator {
1262 /// The in-process surface that currently owns the session (the TUI). It
1263 /// is responsible for updating its cached metadata atomically with the
1264 /// write — see `App::apply_session_mutation`.
1265 Owner,
1266 /// Any other writer: the Runtime API, the web dashboard, a second
1267 /// process. Refused while the session is claimed.
1268 External,
1269 }
1270
1271 /// Set the claimed session to exactly `session_id` (or nothing).
1272 ///
1273 /// The TUI owns at most one session at a time, so switching sessions must
1274 /// release the previous claim in the same step — otherwise a `/new` would
1275 /// leave the old id permanently locked against the dashboard.
1276 pub fn set_live_session(session_id: Option<&str>) {
1277 let session_id = session_id.map(str::trim).filter(|id| !id.is_empty());
1278 if let Ok(mut live) = live_sessions().write() {
1279 live.clear();
1280 if let Some(id) = session_id {
1281 live.insert(id.to_string());
1282 }
1283 }
1284 // A lease for any other session is released with the claim it backed.
1285 if let Ok(mut lease) = LIVE_SESSION_LEASE.lock()
1286 && lease.as_ref().map(|(id, _)| id.as_str()) != session_id
1287 {
1288 *lease = None;
1289 }
1290 }
1291
1292 /// The cross-process half of the live claim (#6144): an exclusive lock on
1293 /// `.late-usage/<id>.live`, held for as long as this process owns the
1294 /// session. The registry above only protects against writers in this
1295 /// process; a standalone `codewhale serve` or a second TUI could still
1296 /// rewrite or delete the document an interactive session is about to
1297 /// autosave over. This lock is separate from the per-write `<id>.lock`, so the
1298 /// owner's own saves never contend with it. It is a liveness signal only —
1299 /// the file carries no data. `None` for the file records a lease that could
1300 /// not be taken (another process holds it), so it is not retried per save.
1301 static LIVE_SESSION_LEASE: std::sync::Mutex<Option<(String, Option<fs::File>)>> =
1302 std::sync::Mutex::new(None);
1303
1304 /// Lock attempts [`SessionManager::reserve_session_for_attach`] makes
1305 /// before it treats contention as a running owner.
1306 const LIVE_LEASE_ATTACH_ATTEMPTS: u32 = 3;
1307
1308 /// The refusal for attaching to a session another process has open.
1309 pub fn session_open_elsewhere(session_id: &str) -> std::io::Error {
1310 std::io::Error::new(
1311 std::io::ErrorKind::ResourceBusy,
1312 format!(
1313 "session {session_id} is open in another Codewhale window. \
1314 Continue it there, or run `codewhale fork {session_id}` to work on a copy"
1315 ),
1316 )
1317 }
1318
1319 /// A reservation of a session's cross-process live lease, taken by
1320 /// [`SessionManager::reserve_session_for_attach`] before a surface attaches.
1321 /// Dropping it releases the reservation; [`Self::commit`] makes the session
1322 /// this process's live session and releases the previous one's lease.
1323 #[must_use = "an uncommitted reservation is released when dropped"]
1324 #[derive(Debug)]
1325 pub struct SessionLease {
1326 id: String,
1327 /// `None` when this process already holds the session's lease.
1328 file: Option<fs::File>,
1329 }
1330
1331 impl SessionLease {
1332 /// Make the reserved session this process's live session. Called after
1333 /// the attach has been validated and applied, so a failed attach never
1334 /// costs the session this process already owns its lease.
1335 pub fn commit(self) {
1336 set_live_session(Some(&self.id));
1337 if let Some(file) = self.file
1338 && let Ok(mut lease) = LIVE_SESSION_LEASE.lock()
1339 {
1340 *lease = Some((self.id, Some(file)));
1341 }
1342 }
1343 }
1344
1345 /// Is this session currently owned by **this process's** interactive surface?
1346 ///
1347 /// The registry is process-local. Reclamation must not treat a missing entry
1348 /// here as proof that no other Codewhale process still owns the directory.
1349 #[must_use]
1350 pub fn is_live_session(session_id: &str) -> bool {
1351 live_sessions()
1352 .read()
1353 .is_ok_and(|live| live.contains(session_id))
1354 }
1355
1356 /// The error an external writer gets when the session is live.
1357 ///
1358 /// `ResourceBusy` so callers can map it to a typed conflict rather than
1359 /// pattern-matching on a message.
1360 pub fn live_session_conflict(session_id: &str) -> std::io::Error {
1361 std::io::Error::new(
1362 std::io::ErrorKind::ResourceBusy,
1363 format!(
1364 "session '{session_id}' is open in an interactive Codewhale session; \
1365 change it there instead — an external write would be reverted by its next autosave"
1366 ),
1367 )
1368 }
1369
1370 /// File-name stem of the sidecar mapping session ids to the session
1371 /// instance (process boot) that created their persisted record. Lives in
1372 /// the sessions directory next to the `<id>.json` records it describes.
1373 const SESSION_BOOT_OWNERS_STEM: &str = "session_boot_owners";
1374
1375 static SESSION_BOOT_ID: std::sync::OnceLock<String> = std::sync::OnceLock::new();
1376
1377 /// Identity of this running session instance (one per process boot).
1378 ///
1379 /// Mirrors the `SubAgentManager` boot id from #405: persisted records are
1380 /// stamped with the instance that created them, so a later Codewhale
1381 /// instance in the same workspace can tell restored rows from its own live
1382 /// work (#4416).
1383 #[must_use]
1384 pub fn current_session_boot_id() -> &'static str {
1385 SESSION_BOOT_ID.get_or_init(|| format!("boot_{}", &Uuid::new_v4().to_string()[..12]))
1386 }
1387
1388 /// Which archive states a session listing includes.
1389 ///
1390 /// Deliberately the same three-way shape as
1391 /// [`crate::runtime_threads::manager::ThreadListFilter`] so `/v1/sessions` and
1392 /// `/v1/threads` answer the same `include_archived` / `archived_only` query
1393 /// pair with the same semantics.
1394 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1395 pub enum SessionListFilter {
1396 /// Only `archived = false` sessions. The browse default.
1397 #[default]
1398 ActiveOnly,
1399 /// Active and archived sessions, newest first.
1400 IncludeArchived,
1401 /// Only `archived = true` sessions.
1402 ArchivedOnly,
1403 }
1404
1405 impl SessionListFilter {
1406 /// Resolve the `include_archived` / `archived_only` query pair the same
1407 /// way the threads routes do.
1408 #[must_use]
1409 pub fn from_query(include_archived: Option<bool>, archived_only: Option<bool>) -> Self {
1410 if archived_only.unwrap_or(false) {
1411 Self::ArchivedOnly
1412 } else if include_archived.unwrap_or(false) {
1413 Self::IncludeArchived
1414 } else {
1415 Self::ActiveOnly
1416 }
1417 }
1418
1419 #[must_use]
1420 pub fn admits(self, archived: bool) -> bool {
1421 match self {
1422 Self::ActiveOnly => !archived,
1423 Self::IncludeArchived => true,
1424 Self::ArchivedOnly => archived,
1425 }
1426 }
1427 }
1428
1429 fn default_model_provider() -> String {
1430 "deepseek".to_string()
1431 }
1432
1433 impl SessionMetadata {
1434 pub fn set_model_provider_route(&mut self, kind: &str, identity: Option<&str>) {
1435 if self.exec_route_binding.is_some()
1436 && (self.model_provider != kind || self.model_provider_id.as_deref() != identity)
1437 {
1438 self.exec_route_binding = Some(crate::route_receipt::ExecRouteBinding::default());
1439 }
1440 self.model_provider = kind.to_string();
1441 self.model_provider_id = identity.map(str::to_string);
1442 }
1443 }
1444
1445 /// Cost and high-water-mark fields persisted with each session.
1446 ///
1447 /// The coverage fields below are persisted **alongside** the money so a restored
1448 /// session can still say what its total covers. Without them a reload produced a
1449 /// dollar figure with no completeness information, which then rendered as "0 of 0
1450 /// turns priced" — a fabricated claim of a complete total. Sessions written
1451 /// before these fields existed deserialize them from `Default`, which is
1452 /// indistinguishable from that same false reading, so the load path detects the
1453 /// legacy shape explicitly (see [`Self::coverage_is_legacy_unknown`]) rather than
1454 /// trusting the defaults (#4318).
1455 #[derive(Debug, Clone, Default, Serialize, Deserialize)]
1456 pub struct SessionCostSnapshot {
1457 /// Accumulated parent-turn session cost in USD.
1458 #[serde(default)]
1459 pub session_cost_usd: f64,
1460 /// Accumulated parent-turn session cost in CNY.
1461 #[serde(default)]
1462 pub session_cost_cny: f64,
1463 /// Accumulated sub-agent/background LLM cost in USD.
1464 #[serde(default)]
1465 pub subagent_cost_usd: f64,
1466 /// Accumulated sub-agent/background LLM cost in CNY.
1467 #[serde(default)]
1468 pub subagent_cost_cny: f64,
1469 /// Max-ever displayed session+subagent cost in USD (preserves #244
1470 /// monotonic guarantee across session restarts).
1471 #[serde(default)]
1472 pub displayed_cost_high_water_usd: f64,
1473 /// Max-ever displayed session+subagent cost in CNY.
1474 #[serde(default)]
1475 pub displayed_cost_high_water_cny: f64,
1476 /// Turns whose route was money-metered and produced an authoritative price.
1477 /// These are exactly the turns the persisted totals contain.
1478 #[serde(default)]
1479 pub priced_turns: u32,
1480 /// Money-metered (or unknown-basis) turns that produced no authoritative
1481 /// price, so their spend is missing from the persisted totals.
1482 #[serde(default)]
1483 pub unpriced_turns: u32,
1484 /// CNY-specific coverage. USD-only routes are unpriced in CNY rather than
1485 /// silently contributing a fabricated zero.
1486 #[serde(default)]
1487 pub cny_priced_turns: u32,
1488 #[serde(default)]
1489 pub cny_unpriced_turns: u32,
1490 /// Stable reason labels for the unpriced turns.
1491 #[serde(
1492 default,
1493 skip_serializing_if = "BTreeSet::is_empty",
1494 serialize_with = "serialize_settled_reasons"
1495 )]
1496 pub unpriced_reasons: BTreeSet<String>,
1497 #[serde(
1498 default,
1499 skip_serializing_if = "BTreeSet::is_empty",
1500 serialize_with = "serialize_settled_reasons"
1501 )]
1502 pub cny_unpriced_reasons: BTreeSet<String>,
1503 /// Token classes used on some route that carry no published price.
1504 #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
1505 pub unpriced_classes: BTreeSet<String>,
1506 /// Provenance labels of the pricing rows the totals were built from.
1507 #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
1508 pub pricing_provenances: BTreeSet<String>,
1509 /// Live-pricing downgrade receipts recorded while building the totals.
1510 #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
1511 pub live_pricing_defects: BTreeSet<String>,
1512 /// Live rows that failed validation and had no usable bundled fallback.
1513 #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
1514 pub live_pricing_unusable_defects: BTreeSet<String>,
1515 /// Redacted per-route receipts: provider, configured identity, wire model,
1516 /// billing surface, endpoint fingerprint, billing mode, currency. Never a URL, a
1517 /// credential, or a filesystem path.
1518 #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
1519 pub route_receipts: BTreeSet<String>,
1520 /// Redacted provider-response identities already settled by their owning
1521 /// parent or routed projection. Worker records persist the same fingerprints.
1522 #[serde(
1523 default,
1524 skip_serializing_if = "crate::cost_status::OrderedFingerprintSet::is_empty"
1525 )]
1526 pub usage_source_fingerprints: crate::cost_status::OrderedFingerprintSet,
1527 #[serde(skip)]
1528 pub pinned_late_usage_fingerprints: std::collections::HashSet<String>,
1529 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1530 pub accounted_usage_sources: BTreeMap<String, crate::cost_status::UsageSourceContribution>,
1531 /// Written by builds that track coverage, so a reader can tell "this session
1532 /// genuinely had zero money-metered turns" apart from "this session predates
1533 /// coverage tracking". Absent on legacy rows.
1534 #[serde(default)]
1535 pub coverage_recorded: bool,
1536 }
1537
1538 impl SessionCostSnapshot {
1539 pub fn project_usage_record(
1540 &mut self,
1541 record: &crate::cost_status::RuntimeUsageRecord,
1542 ) -> io::Result<(u64, u64)> {
1543 let key = crate::cost_status::usage_source_fingerprint(&record.source_id);
1544 self.project_usage_record_by_key(&key, record)
1545 }
1546
1547 pub(crate) fn project_usage_record_by_key(
1548 &mut self,
1549 key: &str,
1550 record: &crate::cost_status::RuntimeUsageRecord,
1551 ) -> io::Result<(u64, u64)> {
1552 let key = key.to_string();
1553 let previous = self.accounted_usage_sources.get(&key);
1554 if let Some(previous) = previous {
1555 previous.validate()?;
1556 }
1557 if previous.is_some_and(|previous| previous.record == *record) {
1558 return Ok((0, 0));
1559 }
1560 if self.usage_source_fingerprints.contains(&key) && previous.is_none() {
1561 return Ok((0, 0));
1562 }
1563 if record.route_conflicts_with(previous.map(|previous| &previous.record)) {
1564 tracing::warn!(
1565 source_id = %record.source_id,
1566 "usage source changed its captured route; recording unknown cost"
1567 );
1568 self.unpriced_reasons
1569 .insert("request_outcome_unknown".to_string());
1570 self.cny_unpriced_reasons
1571 .insert("request_outcome_unknown".to_string());
1572 return Ok((0, 0));
1573 }
1574 if !record.supersedes(previous.map(|previous| &previous.record)) {
1575 return Ok((0, 0));
1576 }
1577 let unknown_fallback;
1578 let record = if let Err(error) = record.validate() {
1579 tracing::warn!(%error, source_id = %record.source_id, "usage record validation failed; continuing with unknown cost");
1580 unknown_fallback = crate::cost_status::unknown_cost_record(
1581 &record.source_id,
1582 &record.usage.route,
1583 record.usage.usage.clone(),
1584 );
1585 &unknown_fallback
1586 } else {
1587 record
1588 };
1589 let next = crate::cost_status::UsageSourceContribution::for_record(record);
1590 let old_tokens =
1591 previous.map_or(0, crate::cost_status::UsageSourceContribution::total_tokens);
1592 let new_tokens = next.total_tokens();
1593 let old_usd = previous.map_or(0.0, |previous| previous.usd);
1594 let old_cny = previous.map_or(0.0, |previous| previous.cny);
1595 let (usd, cny) = if next.owner() == crate::cost_status::UsageSpendOwner::Primary {
1596 (&mut self.session_cost_usd, &mut self.session_cost_cny)
1597 } else {
1598 (&mut self.subagent_cost_usd, &mut self.subagent_cost_cny)
1599 };
1600 if *usd + f64::EPSILON < old_usd || *cny + f64::EPSILON < old_cny {
1601 return Err(io::Error::new(
1602 io::ErrorKind::InvalidData,
1603 "usage projection is missing its prior monetary contribution",
1604 ));
1605 }
1606 if previous.is_some_and(|old| {
1607 self.priced_turns < old.priced
1608 || self.unpriced_turns < old.unpriced
1609 || self.cny_priced_turns < old.cny_priced
1610 || self.cny_unpriced_turns < old.cny_unpriced
1611 }) {
1612 return Err(io::Error::new(
1613 io::ErrorKind::InvalidData,
1614 "usage projection is missing its prior coverage contribution",
1615 ));
1616 }
1617 let updated = crate::pricing::CostEstimate {
1618 usd: (*usd - old_usd).max(0.0),
1619 cny: (*cny - old_cny).max(0.0),
1620 }
1621 .saturating_add(crate::pricing::CostEstimate {
1622 usd: next.usd,
1623 cny: next.cny,
1624 });
1625 *usd = updated.usd;
1626 *cny = updated.cny;
1627 let replace = |total: &mut u32, old: u32, new: u32| {
1628 *total = total.saturating_sub(old).saturating_add(new);
1629 };
1630 replace(
1631 &mut self.priced_turns,
1632 previous.map_or(0, |old| old.priced),
1633 next.priced,
1634 );
1635 replace(
1636 &mut self.unpriced_turns,
1637 previous.map_or(0, |old| old.unpriced),
1638 next.unpriced,
1639 );
1640 replace(
1641 &mut self.cny_priced_turns,
1642 previous.map_or(0, |old| old.cny_priced),
1643 next.cny_priced,
1644 );
1645 replace(
1646 &mut self.cny_unpriced_turns,
1647 previous.map_or(0, |old| old.cny_unpriced),
1648 next.cny_unpriced,
1649 );
1650 let audit = record.usage.route.audit_frozen(&record.usage.usage);
1651 if let Some(provenance) = audit.provenance.as_ref() {
1652 self.pricing_provenances
1653 .insert(provenance.label().to_string());
1654 }
1655 if let Some(defect) = audit.live_pricing_defect.as_ref() {
1656 let defects = if audit.estimate.is_some() {
1657 &mut self.live_pricing_defects
1658 } else {
1659 &mut self.live_pricing_unusable_defects
1660 };
1661 defects.insert(defect.label().to_string());
1662 }
1663 if audit.counts_toward_money_coverage() {
1664 self.unpriced_classes.extend(
1665 audit
1666 .unpriced_classes
1667 .iter()
1668 .map(|class| class.label().to_string()),
1669 );
1670 }
1671 self.route_receipts
1672 .insert(record.usage.route.receipt(&audit));
1673 if let Some(reason) = audit.unpriced_reason {
1674 self.unpriced_reasons.insert(reason.label().to_string());
1675 self.cny_unpriced_reasons.insert(reason.label().to_string());
1676 }
1677 if let Some(revision) = record.settlement.as_ref()
1678 && matches!(
1679 revision.coverage,
1680 crate::llm_client::ProviderUsageCoverage::Missing
1681 | crate::llm_client::ProviderUsageCoverage::Incomplete
1682 )
1683 {
1684 let label = if revision.is_reservation() {
1685 crate::pricing::UnpricedReason::RequestInProgress.label()
1686 } else {
1687 revision.reason.unwrap_or_default().label()
1688 };
1689 self.unpriced_reasons.insert(label.to_string());
1690 self.cny_unpriced_reasons.insert(label.to_string());
1691 }
1692 self.usage_source_fingerprints.insert(key.clone());
1693 self.accounted_usage_sources.insert(key, next);
1694 crate::cost_status::prune_settled_missing_reasons(
1695 &self.accounted_usage_sources,
1696 self.unpriced_turns,
1697 self.cny_unpriced_turns,
1698 &mut self.unpriced_reasons,
1699 &mut self.cny_unpriced_reasons,
1700 );
1701 let total = self.total_estimate();
1702 self.displayed_cost_high_water_usd = self.displayed_cost_high_water_usd.max(total.usd);
1703 self.displayed_cost_high_water_cny = self.displayed_cost_high_water_cny.max(total.cny);
1704 Ok((old_tokens, new_tokens))
1705 }
1706
1707 /// Session + subagent spend as **one** dual-currency accumulator.
1708 ///
1709 /// The persisted USD and CNY columns are projections of per-turn
1710 /// [`crate::pricing::CostEstimate`]s that were accumulated jointly; every
1711 /// display total is derived from this single fold so the two currencies
1712 /// cannot be re-summed by separate code paths that then drift (#4939).
1713 /// CNY is *not* an FX multiple of USD: a turn carries CNY only when its
1714 /// route published an authoritative CNY row (provider-published
1715 /// dual-currency pricing, e.g. DeepSeek's CNY table), and a USD-only turn
1716 /// contributes exactly zero CNY while `cny_unpriced_turns` records the gap.
1717 #[must_use]
1718 pub fn total_estimate(&self) -> crate::pricing::CostEstimate {
1719 crate::pricing::CostEstimate {
1720 usd: self.session_cost_usd,
1721 cny: self.session_cost_cny,
1722 }
1723 .saturating_add(crate::pricing::CostEstimate {
1724 usd: self.subagent_cost_usd,
1725 cny: self.subagent_cost_cny,
1726 })
1727 }
1728
1729 /// Session + subagent cost in USD.
1730 pub fn total_usd(&self) -> f64 {
1731 self.total_estimate()
1732 .amount(codewhale_config::pricing::CostCurrency::Usd)
1733 }
1734
1735 /// Session + subagent cost in CNY.
1736 pub fn total_cny(&self) -> f64 {
1737 self.total_estimate()
1738 .amount(codewhale_config::pricing::CostCurrency::Cny)
1739 }
1740
1741 /// Whether this snapshot's coverage state must be shown as unknown.
1742 ///
1743 /// True when the snapshot has no coverage evidence — the signature of a
1744 /// session written before coverage was persisted. Reporting any such
1745 /// session as "0 of 0 priced" would claim completeness without evidence,
1746 /// including when the saved amount is zero.
1747 #[must_use]
1748 pub fn coverage_is_legacy_unknown(&self) -> bool {
1749 !self.coverage_recorded
1750 }
1751 }
1752
1753 impl SessionMetadata {
1754 /// Copy cost fields from another metadata (used when forking a session).
1755 pub fn copy_cost_from(&mut self, other: &SessionMetadata) {
1756 self.cost = other.cost.clone();
1757 }
1758
1759 /// Record additive lineage metadata for a forked saved session.
1760 pub fn mark_forked_from(&mut self, parent: &SessionMetadata) {
1761 self.parent_session_id = Some(parent.id.clone());
1762 self.forked_from_message_count = Some(parent.message_count);
1763 }
1764 }
1765
1766 /// Durable Work-panel state. Optional on [`SavedSession`] so every session
1767 /// written before v0.8.68 remains loadable without migration.
1768 #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1769 pub struct SessionWorkState {
1770 /// Authoritative Work Graph. Optional so pre-Work-Graph sessions and old
1771 /// binaries continue to exchange fully populated Plan/To-do views.
1772 #[serde(default, skip_serializing_if = "Option::is_none")]
1773 pub graph: Option<crate::work_graph::WorkGraphSnapshot>,
1774 #[serde(default, skip_serializing_if = "TodoListSnapshot::is_empty")]
1775 pub todos: TodoListSnapshot,
1776 #[serde(default, skip_serializing_if = "PlanSnapshot::is_empty")]
1777 pub plan: PlanSnapshot,
1778 }
1779
1780 /// Bounded goal projection persisted beside the owning saved session.
1781 ///
1782 /// This intentionally excludes completion prose, verifier output, transcripts,
1783 /// and filesystem evidence. The saved session already owns conversation
1784 /// history; restart only needs the typed control state that makes the next turn
1785 /// continue the same objective without trusting text reconstructed from it.
1786 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1787 #[serde(deny_unknown_fields)]
1788 pub struct SessionGoalState {
1789 #[serde(default = "current_session_goal_schema_version")]
1790 pub schema_version: u32,
1791 pub objective: String,
1792 pub status: SessionGoalStatus,
1793 #[serde(default, skip_serializing_if = "Option::is_none")]
1794 pub token_budget: Option<u32>,
1795 #[serde(default)]
1796 pub tokens_used: u64,
1797 #[serde(default)]
1798 pub time_used_seconds: u64,
1799 #[serde(default)]
1800 pub continuation_count: u32,
1801 #[serde(default)]
1802 pub elapsed_seconds: u64,
1803 #[serde(default, skip_serializing_if = "Option::is_none")]
1804 pub pause_reason: Option<GoalPauseReason>,
1805 #[serde(default, skip_serializing_if = "Option::is_none")]
1806 pub goal_id: Option<String>,
1807 #[serde(default, skip_serializing_if = "Option::is_none")]
1808 pub last_gap_fingerprint: Option<String>,
1809 #[serde(default)]
1810 pub repeated_gap_count: u32,
1811 #[serde(default, skip_serializing_if = "Option::is_none")]
1812 pub last_gap_pass: Option<u32>,
1813 }
1814
1815 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
1816 #[serde(rename_all = "snake_case")]
1817 pub enum SessionGoalStatus {
1818 Active,
1819 Paused,
1820 Complete,
1821 Blocked,
1822 }
1823
1824 const fn current_session_goal_schema_version() -> u32 {
1825 CURRENT_SESSION_GOAL_SCHEMA_VERSION
1826 }
1827
1828 impl SessionGoalState {
1829 /// Convert a runtime update into the durable, bounded session contract.
1830 /// The canonical empty runtime snapshot removes the sidecar.
1831 pub fn from_runtime(snapshot: &GoalSnapshot) -> io::Result<Option<Self>> {
1832 if snapshot.objective.is_none() && snapshot.status.trim() == "none" {
1833 return Ok(None);
1834 }
1835 let objective = snapshot
1836 .objective
1837 .as_deref()
1838 .map(str::trim)
1839 .filter(|objective| !objective.is_empty())
1840 .ok_or_else(|| {
1841 io::Error::new(io::ErrorKind::InvalidData, "goal snapshot has no objective")
1842 })?;
1843 let status = match snapshot.status.trim() {
1844 "active" => SessionGoalStatus::Active,
1845 "paused" => SessionGoalStatus::Paused,
1846 "complete" => SessionGoalStatus::Complete,
1847 "blocked" => SessionGoalStatus::Blocked,
1848 other => {
1849 return Err(io::Error::new(
1850 io::ErrorKind::InvalidData,
1851 format!("goal snapshot has unsupported status '{other}'"),
1852 ));
1853 }
1854 };
1855 let state = Self {
1856 schema_version: CURRENT_SESSION_GOAL_SCHEMA_VERSION,
1857 objective: objective.to_string(),
1858 status,
1859 token_budget: snapshot.token_budget,
1860 tokens_used: snapshot.tokens_used,
1861 time_used_seconds: snapshot.time_used_seconds,
1862 continuation_count: snapshot.continuation_count,
1863 elapsed_seconds: snapshot.elapsed_seconds.unwrap_or_default(),
1864 pause_reason: snapshot.pause_reason,
1865 goal_id: snapshot.goal_id.clone(),
1866 last_gap_fingerprint: snapshot.last_gap_fingerprint.clone(),
1867 repeated_gap_count: snapshot.repeated_gap_count,
1868 last_gap_pass: snapshot.last_gap_pass,
1869 };
1870 state.validate()?;
1871 Ok(Some(state))
1872 }
1873
1874 pub fn validate(&self) -> io::Result<()> {
1875 if self.schema_version > CURRENT_SESSION_GOAL_SCHEMA_VERSION {
1876 return Err(io::Error::new(
1877 io::ErrorKind::InvalidData,
1878 format!(
1879 "Session goal schema v{} is newer than supported v{}",
1880 self.schema_version, CURRENT_SESSION_GOAL_SCHEMA_VERSION
1881 ),
1882 ));
1883 }
1884 let objective = self.objective.trim();
1885 if objective.is_empty() || objective.chars().count() > MAX_SESSION_GOAL_OBJECTIVE_CHARS {
1886 return Err(io::Error::new(
1887 io::ErrorKind::InvalidData,
1888 format!(
1889 "Session goal objective must contain 1..={MAX_SESSION_GOAL_OBJECTIVE_CHARS} characters"
1890 ),
1891 ));
1892 }
1893 if self
1894 .goal_id
1895 .as_ref()
1896 .is_some_and(|id| id.is_empty() || id.len() > 128)
1897 {
1898 return Err(io::Error::new(
1899 io::ErrorKind::InvalidData,
1900 "invalid session goal revision",
1901 ));
1902 }
1903 codewhale_protocol::validate_goal_stall_state(
1904 self.last_gap_fingerprint.as_deref(),
1905 self.repeated_gap_count,
1906 self.last_gap_pass,
1907 self.continuation_count,
1908 )
1909 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
1910 }
1911
1912 #[must_use]
1913 pub fn to_runtime_snapshot(&self) -> GoalSnapshot {
1914 GoalSnapshot {
1915 goal_id: self.goal_id.clone(),
1916 objective: Some(self.objective.clone()),
1917 status: match self.status {
1918 SessionGoalStatus::Active => "active",
1919 SessionGoalStatus::Paused => "paused",
1920 SessionGoalStatus::Complete => "complete",
1921 SessionGoalStatus::Blocked => "blocked",
1922 }
1923 .to_string(),
1924 token_budget: self.token_budget,
1925 tokens_used: self.tokens_used,
1926 time_used_seconds: self.time_used_seconds,
1927 continuation_count: self.continuation_count,
1928 elapsed_seconds: Some(self.elapsed_seconds),
1929 evidence: None,
1930 blocker: None,
1931 pause_reason: self.pause_reason,
1932 completion_verification: None,
1933 advisories: Vec::new(),
1934 last_gap_fingerprint: self.last_gap_fingerprint.clone(),
1935 repeated_gap_count: self.repeated_gap_count,
1936 last_gap_pass: self.last_gap_pass,
1937 progress: None,
1938 }
1939 }
1940 }
1941
1942 impl SessionWorkState {
1943 #[must_use]
1944 pub fn is_empty(&self) -> bool {
1945 self.graph
1946 .as_ref()
1947 .is_none_or(crate::work_graph::WorkGraphSnapshot::is_empty)
1948 && self.todos.is_empty()
1949 && self.plan.is_empty()
1950 }
1951 }
1952
1953 /// Latest concrete Auto route and the decision receipt that produced it.
1954 ///
1955 /// This is additive, optional session metadata: sessions written before
1956 /// v0.9.1 deserialize with no receipt and keep their legacy restore behavior.
1957 #[derive(Debug, Clone, PartialEq, Eq)]
1958 pub struct SavedAutoRouteReceipt {
1959 pub provider: ProviderKind,
1960 pub provider_identity: String,
1961 pub model: String,
1962 pub receipt: AutoRouteReceipt,
1963 /// Canonical effective reasoning receipt for the selected route, including
1964 /// routes where a concrete tier cannot be proven. Optional so older
1965 /// sessions remain loadable.
1966 pub effective_reasoning_effort: Option<ReasoningEffortTier>,
1967 pub context_window: Option<ContextWindowResolution>,
1968 }
1969
1970 #[derive(Serialize, Deserialize)]
1971 struct SavedAutoRouteReceiptWire {
1972 provider: String,
1973 provider_identity: String,
1974 model: String,
1975 receipt: AutoRouteReceipt,
1976 /// Canonical effective reasoning receipt for the selected route, including
1977 /// routes where a concrete tier cannot be proven. Optional so older
1978 /// sessions remain loadable.
1979 #[serde(default, skip_serializing_if = "Option::is_none")]
1980 effective_reasoning_effort: Option<ReasoningEffortTier>,
1981 #[serde(
1982 default,
1983 skip_serializing_if = "Option::is_none",
1984 deserialize_with = "read_saved_context_window"
1985 )]
1986 context_window: Option<ContextWindowResolution>,
1987 }
1988
1989 fn read_saved_context_window<'de, D: serde::Deserializer<'de>>(
1990 deserializer: D,
1991 ) -> Result<Option<ContextWindowResolution>, D::Error> {
1992 let value = serde_json::Value::deserialize(deserializer)?;
1993 Ok(serde_json::from_value::<ContextWindowResolution>(value)
1994 .ok()
1995 .filter(|window| window.tokens > 0))
1996 }
1997
1998 impl Serialize for SavedAutoRouteReceipt {
1999 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2000 where
2001 S: serde::Serializer,
2002 {
2003 let provider = codewhale_config::descriptors::tui_wire_tag_for_route(
2004 self.provider,
2005 &self.provider_identity,
2006 )
2007 .ok_or_else(|| serde::ser::Error::custom("contradictory saved provider identity"))?;
2008 SavedAutoRouteReceiptWire {
2009 provider: provider.into(),
2010 provider_identity: self.provider_identity.clone(),
2011 model: self.model.clone(),
2012 receipt: self.receipt.clone(),
2013 effective_reasoning_effort: self.effective_reasoning_effort,
2014 context_window: self.context_window,
2015 }
2016 .serialize(serializer)
2017 }
2018 }
2019 impl<'de> Deserialize<'de> for SavedAutoRouteReceipt {
2020 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2021 where
2022 D: serde::Deserializer<'de>,
2023 {
2024 let wire = SavedAutoRouteReceiptWire::deserialize(deserializer)?;
2025 let provider = codewhale_config::descriptors::kind_from_tui_wire_tag(
2026 &wire.provider,
2027 &wire.provider_identity,
2028 )
2029 .ok_or_else(|| serde::de::Error::custom("contradictory saved provider identity"))?;
2030 Ok(Self {
2031 provider,
2032 provider_identity: wire.provider_identity,
2033 model: wire.model,
2034 receipt: wire.receipt,
2035 effective_reasoning_effort: wire.effective_reasoning_effort,
2036 context_window: wire.context_window,
2037 })
2038 }
2039 }
2040
2041 /// Most turn outcomes one session record keeps; the oldest drop first.
2042 pub const MAX_SAVED_TURN_OUTCOMES: usize = 64;
2043 /// Longest error text one saved outcome keeps, in `char`s.
2044 const MAX_SAVED_TURN_OUTCOME_ERROR_CHARS: usize = 4_000;
2045
2046 /// A turn that ended `Failed`, as the person saw it end.
2047 ///
2048 /// The transcript only holds messages, so before this record a failed turn
2049 /// left nothing but the user's prompt behind: once the TUI closed, resume,
2050 /// export, and the app had no way to say why the turn stopped. The error is
2051 /// the text the live transcript showed, passed through the shared secret
2052 /// redactor before it is stored.
2053 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2054 pub struct SavedTurnOutcome {
2055 pub status: crate::core::events::TurnOutcomeStatus,
2056 /// User-facing error text, secrets redacted.
2057 pub error: String,
2058 #[serde(default, skip_serializing_if = "Option::is_none")]
2059 pub code: Option<String>,
2060 #[serde(default, skip_serializing_if = "Option::is_none")]
2061 pub cause: Option<crate::llm_error_envelope::ProviderFailureCause>,
2062 pub ended_at: DateTime<Utc>,
2063 /// Transcript messages that existed when the turn ended. Resume places
2064 /// the notice after that many messages (clamped to the transcript).
2065 pub after_message_count: usize,
2066 }
2067
2068 impl SavedTurnOutcome {
2069 /// Build the persisted record for a failed turn. Redacts before bounding
2070 /// so a cut can never leave half a secret behind.
2071 pub fn failed(error: &str, after_message_count: usize) -> Self {
2072 Self::failed_with_cause(error, None, None, after_message_count)
2073 }
2074
2075 pub fn failed_with_code(error: &str, code: Option<&str>, after_message_count: usize) -> Self {
2076 Self::failed_with_cause(error, code, None, after_message_count)
2077 }
2078
2079 pub fn failed_with_cause(
2080 error: &str,
2081 code: Option<&str>,
2082 cause: Option<crate::llm_error_envelope::ProviderFailureCause>,
2083 after_message_count: usize,
2084 ) -> Self {
2085 let redacted = codewhale_sanitize::redact::redact_secrets(error.trim());
2086 let error = if redacted.chars().count() > MAX_SAVED_TURN_OUTCOME_ERROR_CHARS {
2087 let mut cut: String = redacted
2088 .chars()
2089 .take(MAX_SAVED_TURN_OUTCOME_ERROR_CHARS)
2090 .collect();
2091 cut.push('…');
2092 cut
2093 } else {
2094 redacted
2095 };
2096 let code = code
2097 .map(|value| value.trim().trim_matches(['[', ']']).trim())
2098 .filter(|value| !value.is_empty())
2099 .map(codewhale_sanitize::redact::redact_secrets);
2100 Self {
2101 status: crate::core::events::TurnOutcomeStatus::Failed,
2102 error,
2103 code,
2104 cause,
2105 ended_at: Utc::now(),
2106 after_message_count,
2107 }
2108 }
2109 }
2110
2111 /// Append `outcome`, keeping only the newest [`MAX_SAVED_TURN_OUTCOMES`].
2112 pub fn push_turn_outcome(outcomes: &mut Vec<SavedTurnOutcome>, outcome: SavedTurnOutcome) {
2113 outcomes.push(outcome);
2114 if outcomes.len() > MAX_SAVED_TURN_OUTCOMES {
2115 let excess = outcomes.len() - MAX_SAVED_TURN_OUTCOMES;
2116 outcomes.drain(..excess);
2117 }
2118 }
2119
2120 /// A saved session containing full conversation history
2121 /// Starting with v0.9.5 (#5262) the canonical history is the append-only entry journal (`journal` / `leaf_id`).
2122 #[derive(Debug, Clone, Serialize, Deserialize)]
2123 pub struct SavedSession {
2124 #[serde(skip)]
2125 pub write_receipt: Option<SessionWriteReceipt>,
2126 /// Schema version for migration compatibility
2127 #[serde(default = "default_session_schema_version")]
2128 pub schema_version: u32,
2129 /// Session metadata
2130 pub metadata: SessionMetadata,
2131 /// Conversation messages — derived from the journal's active branch (kept for compat).
2132 pub messages: Vec<Message>,
2133 #[serde(default, skip_serializing_if = "Option::is_none")]
2134 pub journal: Option<SessionJournal>,
2135 #[serde(default, skip_serializing_if = "Option::is_none")]
2136 pub leaf_id: Option<String>,
2137 /// System prompt if any
2138 pub system_prompt: Option<String>,
2139 /// Compact linked context references for user-visible `@path` and
2140 /// `/attach` mentions. Optional for backward-compatible session loads.
2141 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2142 pub context_references: Vec<SessionContextReference>,
2143 /// Metadata registry of large outputs produced during this session.
2144 /// Artifact contents are stored in the session-owned artifact directory.
2145 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2146 pub artifacts: Vec<ArtifactRecord>,
2147 /// Session-owned approval evidence. The append-only sidecar is canonical
2148 /// during a live turn; this projection makes saved snapshots self-
2149 /// describing without putting receipts in the model transcript.
2150 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2151 pub approval_receipts: Vec<ApprovalReceipt>,
2152 /// To-do and plan state shown in the Work sidebar.
2153 #[serde(default, skip_serializing_if = "Option::is_none")]
2154 pub work_state: Option<SessionWorkState>,
2155 /// User-configured tab/window title for this session (`/title`), shown as
2156 /// `[title] …` in front of the terminal window title. Optional for
2157 /// backward-compatible session loads; absent sessions use the `title`
2158 /// config default instead.
2159 #[serde(default, skip_serializing_if = "Option::is_none")]
2160 pub window_title: Option<String>,
2161 #[serde(default, skip_serializing_if = "Option::is_none")]
2162 pub composer_color: Option<String>,
2163 /// Most recent accepted/completed Auto decision, when the saved model mode
2164 /// is `auto`. Optional for backward-compatible session loads.
2165 #[serde(default, skip_serializing_if = "Option::is_none")]
2166 pub last_auto_route: Option<SavedAutoRouteReceipt>,
2167 /// Turns that ended `Failed`, oldest first, bounded to
2168 /// [`MAX_SAVED_TURN_OUTCOMES`]. Not model context: the terminal-outcome
2169 /// record resume, export, and the Runtime API read back.
2170 #[serde(default, skip_serializing_if = "Vec::is_empty")]
2171 pub turn_outcomes: Vec<SavedTurnOutcome>,
2172 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
2173 pub delegated_writes: std::collections::BTreeMap<u64, Vec<String>>,
2174 #[serde(
2175 default,
2176 skip_serializing_if = "Option::is_none",
2177 deserialize_with = "read_saved_agent_preset"
2178 )]
2179 pub agent_preset: Option<String>,
2180 }
2181
2182 fn read_saved_agent_preset<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
2183 where
2184 D: serde::Deserializer<'de>,
2185 {
2186 Ok(
2187 match <Option<serde_json::Value> as serde::Deserialize>::deserialize(deserializer)? {
2188 None | Some(serde_json::Value::Null) => None,
2189 Some(serde_json::Value::String(id)) => Some(id),
2190 Some(other) => Some(other.to_string()),
2191 },
2192 )
2193 }
2194
2195 impl SavedSession {
2196 pub fn capture_publication(
2197 &mut self,
2198 owner: SessionWriteOwner,
2199 ) -> io::Result<SessionWriteReceipt> {
2200 let receipt = self
2201 .write_receipt
2202 .as_ref()
2203 .ok_or_else(|| {
2204 io::Error::new(
2205 io::ErrorKind::ResourceBusy,
2206 "session source was not admitted; reopen it before publishing",
2207 )
2208 })?
2209 .capture(owner)?;
2210 if !self.metadata.cost.accounted_usage_sources.is_empty() {
2211 self.schema_version = self.schema_version.max(CURRENT_SESSION_SCHEMA_VERSION);
2212 }
2213 self.metadata.publication_id = receipt.publication_id();
2214 self.write_receipt = Some(receipt.clone());
2215 Ok(receipt)
2216 }
2217
2218 pub fn adopt_publication(&mut self, publication: &SessionPublication) {
2219 self.metadata = publication.metadata.clone();
2220 self.write_receipt = Some(publication.write_receipt());
2221 }
2222
2223 /// Drop the journal-derived compatibility projection before an async
2224 /// persistence request takes ownership. Disk serialization restores it.
2225 pub fn compact_for_persistence_queue(&mut self) {
2226 if self.journal.is_some() {
2227 self.messages = Vec::new();
2228 }
2229 }
2230
2231 pub fn transport_form(&self) -> Self {
2232 let mut carried = self.clone();
2233 if self
2234 .journal
2235 .as_ref()
2236 .is_some_and(|journal| journal.to_messages() == self.messages)
2237 {
2238 carried.compact_for_persistence_queue();
2239 }
2240 carried
2241 }
2242
2243 /// Bring `messages` and the journal into the shape the on-disk schema
2244 /// expects, in place.
2245 ///
2246 /// This used to be `storage_compatible_copy`, which cloned the whole
2247 /// session to do it. On the debounced persistence path the caller already
2248 /// owns the value and `compact_for_persistence_queue` has already emptied
2249 /// `messages`, so the clone was pure waste — two full deep copies of the
2250 /// history per write (#6214 T3).
2251 ///
2252 /// The no-op cases are load-bearing and must stay no-ops: with no journal,
2253 /// or with `messages` already equal to the journal's active branch, the
2254 /// session serializes exactly as it arrived — including a
2255 /// `metadata.message_count` that disagrees with `messages.len()`. Rewriting
2256 /// that count here would silently edit live data on every save.
2257 pub fn make_storage_compatible(&mut self) {
2258 let Some(journal) = self.journal.as_mut() else {
2259 return;
2260 };
2261 if self.messages.is_empty() {
2262 self.messages = journal.to_messages();
2263 } else {
2264 if self.messages == journal.to_messages() {
2265 return;
2266 }
2267 let report = journal.rebranch_active_messages(&self.messages);
2268 self.leaf_id.clone_from(&journal.leaf_id);
2269 if report.kept_recorded_metadata {
2270 self.messages = journal.to_messages();
2271 }
2272 }
2273 self.metadata.message_count = self.messages.len();
2274 }
2275
2276 pub fn ensure_journal(&mut self) {
2277 if self.journal.is_some() {
2278 if self.leaf_id.is_none() {
2279 self.leaf_id = self.journal.as_ref().and_then(|j| j.leaf_id.clone());
2280 }
2281 let active = self
2282 .journal
2283 .as_ref()
2284 .map(|j| j.to_messages())
2285 .unwrap_or_default();
2286 if !active.is_empty() {
2287 self.messages = active;
2288 self.metadata.message_count = self.messages.len();
2289 }
2290 return;
2291 }
2292 let journal =
2293 SessionJournal::from_messages(self.messages.clone(), self.metadata.spawn_depth);
2294 self.leaf_id = journal.leaf_id.clone();
2295 self.journal = Some(journal);
2296 }
2297 pub fn journal_branch_to(&mut self, entry_id: &str) -> Result<(), String> {
2298 self.ensure_journal();
2299 let journal = self.journal.as_mut().expect("journal ensured");
2300 journal.branch_to(entry_id)?;
2301 self.leaf_id = journal.leaf_id.clone();
2302 let messages = journal.to_messages();
2303 let unchanged = self
2304 .messages
2305 .iter()
2306 .zip(&messages)
2307 .take_while(|(old, new)| same_recorded_turn(old, new))
2308 .count();
2309 self.turn_outcomes
2310 .retain(|outcome| outcome.after_message_count <= unchanged);
2311 self.messages = messages;
2312 self.metadata.message_count = self.messages.len();
2313 self.metadata.updated_at = Utc::now();
2314 Ok(())
2315 }
2316 /// `created_at` of the active branch's message entries, in order — the
2317 /// stamps a resumed session hands back to the live message log so the
2318 /// next save preserves append times instead of rewriting them to resume
2319 /// time.
2320 pub fn journal_message_stamps(&self) -> Vec<DateTime<Utc>> {
2321 self.journal
2322 .as_ref()
2323 .map(|journal| {
2324 journal
2325 .root_to_leaf()
2326 .iter()
2327 .filter(|entry| {
2328 matches!(
2329 *entry.kind,
2330 codewhale_runtime::session_tree::SessionEntryKind::Message { .. }
2331 )
2332 })
2333 .map(|entry| entry.created_at)
2334 .collect()
2335 })
2336 .unwrap_or_default()
2337 }
2338 pub fn export_container(&self, source: &str) -> SessionImportContainer {
2339 let journal = self.journal.clone().unwrap_or_else(|| {
2340 SessionJournal::from_messages(self.messages.clone(), self.metadata.spawn_depth)
2341 });
2342 SessionImportContainer::new(
2343 source.to_string(),
2344 &journal,
2345 serde_json::to_value(&self.metadata).ok(),
2346 )
2347 }
2348 pub fn import_foreign(
2349 container: SessionImportContainer,
2350 workspace: PathBuf,
2351 model: String,
2352 ) -> Result<Self, String> {
2353 let journal = container.into_journal()?;
2354 validate_saved_journal(&journal).map_err(|error| error.to_string())?;
2355 let leaf_id = journal.leaf_id.clone();
2356 let messages = journal.to_messages();
2357 let now = Utc::now();
2358 let spawn_depth = journal.spawn_depth.saturating_add(1);
2359 // Reuse the conversation-derived title so an imported session that
2360 // opens with runtime-owned control traffic (Operate contract, restore
2361 // checkpoint) is named after the real prompt, not the envelope.
2362 let title = conversation_derived_title(&messages)
2363 .unwrap_or_else(|| crate::session_manager::DEFAULT_SESSION_TITLE.to_string());
2364 let metadata = SessionMetadata {
2365 publication_id: None,
2366 native_mutation_observation: None,
2367
2368 id: Uuid::new_v4().to_string(),
2369 title,
2370 title_is_custom: false,
2371 created_at: now,
2372 updated_at: now,
2373 message_count: messages.len(),
2374 total_tokens: 0,
2375 model,
2376 model_provider: default_model_provider(),
2377 model_provider_id: None,
2378 exec_route_binding: None,
2379 workspace,
2380 mode: None,
2381 cost: SessionCostSnapshot::default(),
2382 parent_session_id: None,
2383 forked_from_message_count: None,
2384 runtime_store: None,
2385 cumulative_turn_secs: 0,
2386 archived: false,
2387 spawn_depth,
2388 };
2389 let mut journal = journal;
2390 journal.spawn_depth = spawn_depth;
2391 Ok(Self {
2392 write_receipt: None,
2393 schema_version: CURRENT_SESSION_SCHEMA_VERSION,
2394 metadata,
2395 messages,
2396 journal: Some(journal),
2397 leaf_id,
2398 system_prompt: None,
2399 context_references: Vec::new(),
2400 artifacts: Vec::new(),
2401 approval_receipts: Vec::new(),
2402 work_state: None,
2403 window_title: None,
2404 composer_color: None,
2405 last_auto_route: None,
2406 turn_outcomes: Vec::new(),
2407 delegated_writes: std::collections::BTreeMap::new(),
2408 agent_preset: None,
2409 })
2410 }
2411 }
2412
2413 /// Validate every stored branch before deriving a projection. The journal's
2414 /// traversal safely stops on malformed edges, but persistence must refuse such
2415 /// a document instead of treating a truncated path as the complete conversation.
2416 fn validate_saved_journal(journal: &SessionJournal) -> io::Result<()> {
2417 let invalid = |message| io::Error::new(io::ErrorKind::InvalidData, message);
2418 if journal.schema_version > codewhale_runtime::session_tree::CURRENT_JOURNAL_SCHEMA_VERSION {
2419 return Err(invalid("saved journal schema is newer than supported"));
2420 }
2421 journal
2422 .validate()
2423 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
2424 let mut parents = std::collections::HashMap::with_capacity(journal.entries.len());
2425 for entry in &journal.entries {
2426 if entry.id.is_empty()
2427 || parents
2428 .insert(entry.id.as_str(), entry.parent_id.as_deref())
2429 .is_some()
2430 {
2431 return Err(invalid(
2432 "saved journal contains an empty or duplicate entry id",
2433 ));
2434 }
2435 }
2436 let mut colors = std::collections::HashMap::with_capacity(parents.len());
2437 for id in parents.keys().copied() {
2438 let mut cursor = Some(id);
2439 let mut path = Vec::new();
2440 while let Some(id) = cursor {
2441 match colors.get(id) {
2442 Some(1) => return Err(invalid("saved journal contains a cycle")),
2443 Some(2) => break,
2444 _ => {
2445 colors.insert(id, 1);
2446 path.push(id);
2447 cursor = parents[id];
2448 }
2449 }
2450 }
2451 for id in path {
2452 colors.insert(id, 2);
2453 }
2454 }
2455 Ok(())
2456 }
2457
2458 /// Archived ids per session that the live app has not yet dropped from its
2459 /// in-memory journal. A bounded save records them only after its document
2460 /// write lands; the UI takes them on its next snapshot (no I/O) so RAM
2461 /// matches disk, and a racing save skips re-appending ids still listed here.
2462 fn archived_journal_ids()
2463 -> &'static std::sync::Mutex<std::collections::HashMap<String, std::collections::HashSet<String>>> {
2464 static IDS: std::sync::OnceLock<
2465 std::sync::Mutex<std::collections::HashMap<String, std::collections::HashSet<String>>>,
2466 > = std::sync::OnceLock::new();
2467 IDS.get_or_init(Default::default)
2468 }
2469
2470 /// Take the ids a bounded save archived for `session_id`, for the live
2471 /// journal to drop. Never touches the disk.
2472 pub fn take_archived_journal_ids(session_id: &str) -> std::collections::HashSet<String> {
2473 archived_journal_ids()
2474 .lock()
2475 .unwrap_or_else(std::sync::PoisonError::into_inner)
2476 .remove(session_id)
2477 .unwrap_or_default()
2478 }
2479
2480 #[derive(Deserialize)]
2481 struct ArchiveEntryId {
2482 id: String,
2483 }
2484
2485 fn is_valid_journal_archive_session_id(id: &str) -> bool {
2486 if id.is_empty() || id.starts_with('.') {
2487 return false;
2488 }
2489 let mut components = Path::new(id).components();
2490 matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none()
2491 }
2492
2493 fn journal_archive_path(sessions_dir: &Path, session_id: &str) -> io::Result<PathBuf> {
2494 let id = session_id.trim();
2495 if !is_valid_journal_archive_session_id(id) {
2496 return Err(io::Error::new(
2497 io::ErrorKind::InvalidInput,
2498 "invalid session id for journal archive",
2499 ));
2500 }
2501 Ok(sessions_dir
2502 .join(JOURNAL_ARCHIVE_DIR)
2503 .join(format!("{id}.jsonl")))
2504 }
2505
2506 fn journal_archive_segment_path(
2507 sessions_dir: &Path,
2508 session_id: &str,
2509 seq: u32,
2510 ) -> io::Result<PathBuf> {
2511 let id = session_id.trim();
2512 if !is_valid_journal_archive_session_id(id) || seq == 0 {
2513 return Err(io::Error::new(
2514 io::ErrorKind::InvalidInput,
2515 "invalid session id or segment sequence for journal archive",
2516 ));
2517 }
2518 Ok(sessions_dir
2519 .join(JOURNAL_ARCHIVE_DIR)
2520 .join(format!("{id}.{seq:06}{JOURNAL_ARCHIVE_SEGMENT_SUFFIX}")))
2521 }
2522
2523 fn parse_journal_archive_filename(name: &str) -> Option<(String, Option<u32>)> {
2524 if name.starts_with('.') {
2525 return None;
2526 }
2527 if let Some(stem) = name.strip_suffix(JOURNAL_ARCHIVE_SEGMENT_SUFFIX) {
2528 let (session_id, seq_str) = stem.rsplit_once('.')?;
2529 if !is_valid_journal_archive_session_id(session_id)
2530 || seq_str.is_empty()
2531 || seq_str.len() > 10
2532 || !seq_str.bytes().all(|byte| byte.is_ascii_digit())
2533 {
2534 return None;
2535 }
2536 let seq = seq_str.parse::<u32>().ok().filter(|seq| *seq >= 1)?;
2537 return Some((session_id.to_string(), Some(seq)));
2538 }
2539 if let Some(session_id) = name.strip_suffix(".jsonl")
2540 && is_valid_journal_archive_session_id(session_id)
2541 {
2542 return Some((session_id.to_string(), None));
2543 }
2544 None
2545 }
2546
2547 fn checked_existing_journal_archive_dir(sessions_dir: &Path) -> io::Result<Option<PathBuf>> {
2548 let dir = sessions_dir.join(JOURNAL_ARCHIVE_DIR);
2549 match fs::symlink_metadata(&dir) {
2550 Ok(metadata) => {
2551 if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) {
2552 return Err(io::Error::new(
2553 io::ErrorKind::InvalidInput,
2554 "journal archive directory is a link",
2555 ));
2556 }
2557 if !metadata.is_dir() {
2558 return Err(io::Error::new(
2559 io::ErrorKind::InvalidInput,
2560 "journal archive path is not a directory",
2561 ));
2562 }
2563 Ok(Some(dir))
2564 }
2565 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
2566 Err(error) => Err(error),
2567 }
2568 }
2569
2570 fn list_journal_archive_segments(
2571 sessions_dir: &Path,
2572 session_id: &str,
2573 ) -> io::Result<Vec<(u32, PathBuf)>> {
2574 let id = session_id.trim();
2575 if !is_valid_journal_archive_session_id(id) {
2576 return Err(io::Error::new(
2577 io::ErrorKind::InvalidInput,
2578 "invalid session id for journal archive",
2579 ));
2580 }
2581 let Some(dir) = checked_existing_journal_archive_dir(sessions_dir)? else {
2582 return Ok(Vec::new());
2583 };
2584 let mut segments = Vec::new();
2585 for entry in fs::read_dir(&dir)? {
2586 let entry = entry?;
2587 let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
2588 continue;
2589 };
2590 if let Some((parsed_id, Some(seq))) = parse_journal_archive_filename(&name)
2591 && parsed_id == id
2592 {
2593 segments.push((seq, entry.path()));
2594 }
2595 }
2596 segments.sort_by_key(|(seq, _)| *seq);
2597 Ok(segments)
2598 }
2599
2600 fn read_bounded_line<R: io::BufRead>(
2601 reader: &mut R,
2602 buf: &mut Vec<u8>,
2603 max_line_bytes: usize,
2604 path: &Path,
2605 line_no: usize,
2606 ) -> io::Result<Option<bool>> {
2607 buf.clear();
2608 let mut total = 0usize;
2609 loop {
2610 let available = match reader.fill_buf() {
2611 Ok(available) => available,
2612 Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
2613 Err(error) => return Err(error),
2614 };
2615 if available.is_empty() {
2616 return Ok(if total == 0 { None } else { Some(false) });
2617 }
2618 if let Some(pos) = available.iter().position(|&byte| byte == b'\n') {
2619 let take = pos + 1;
2620 total = total.saturating_add(take);
2621 if total > max_line_bytes {
2622 return Err(io::Error::new(
2623 io::ErrorKind::InvalidData,
2624 format!(
2625 "journal archive {} line {} exceeds {} byte limit",
2626 path.display(),
2627 line_no,
2628 max_line_bytes
2629 ),
2630 ));
2631 }
2632 buf.extend_from_slice(&available[..take]);
2633 reader.consume(take);
2634 return Ok(Some(true));
2635 }
2636 let chunk_len = available.len();
2637 total = total.saturating_add(chunk_len);
2638 if total > max_line_bytes {
2639 return Err(io::Error::new(
2640 io::ErrorKind::InvalidData,
2641 format!(
2642 "journal archive {} line {} exceeds {} byte limit",
2643 path.display(),
2644 line_no,
2645 max_line_bytes
2646 ),
2647 ));
2648 }
2649 buf.extend_from_slice(available);
2650 reader.consume(chunk_len);
2651 }
2652 }
2653
2654 fn stream_journal_archive_lines<R: io::BufRead>(
2655 reader: &mut R,
2656 path: &Path,
2657 allow_torn_eof: bool,
2658 mut on_line: impl FnMut(&str) -> Result<(), serde_json::Error>,
2659 ) -> io::Result<()> {
2660 let mut buf = Vec::new();
2661 let mut line_no = 0usize;
2662 while let Some(ended_with_newline) = read_bounded_line(
2663 reader,
2664 &mut buf,
2665 SESSION_METADATA_READ_LIMIT,
2666 path,
2667 line_no + 1,
2668 )? {
2669 let text = match std::str::from_utf8(&buf) {
2670 Ok(text) => text,
2671 Err(error) if allow_torn_eof && !ended_with_newline => {
2672 tracing::warn!(
2673 path = %path.display(),
2674 %error,
2675 "skipping torn final journal-archive line"
2676 );
2677 break;
2678 }
2679 Err(error) => {
2680 return Err(io::Error::new(
2681 io::ErrorKind::InvalidData,
2682 format!(
2683 "journal archive {} line {}: {error}",
2684 path.display(),
2685 line_no + 1
2686 ),
2687 ));
2688 }
2689 };
2690 let trimmed = text.trim();
2691 if trimmed.is_empty() {
2692 continue;
2693 }
2694 line_no += 1;
2695 match on_line(trimmed) {
2696 Ok(()) => {}
2697 Err(error) if allow_torn_eof && !ended_with_newline => {
2698 tracing::warn!(
2699 path = %path.display(),
2700 %error,
2701 "skipping torn final journal-archive line"
2702 );
2703 break;
2704 }
2705 Err(error) => {
2706 return Err(io::Error::new(
2707 io::ErrorKind::InvalidData,
2708 format!("journal archive {} line {line_no}: {error}", path.display()),
2709 ));
2710 }
2711 }
2712 }
2713 Ok(())
2714 }
2715
2716 fn stream_journal_archive_segment_ids(
2717 segments: &[(u32, PathBuf)],
2718 ) -> io::Result<std::collections::HashSet<String>> {
2719 let mut seen = std::collections::HashSet::new();
2720 for (_, seg_path) in segments {
2721 let file = open_private_read_file(seg_path)?;
2722 let mut reader = io::BufReader::new(liblzma::read::XzDecoder::new(file));
2723 stream_journal_archive_lines(&mut reader, seg_path, false, |line| {
2724 let entry: ArchiveEntryId = serde_json::from_str(line)?;
2725 seen.insert(entry.id);
2726 Ok(())
2727 })?;
2728 }
2729 Ok(seen)
2730 }
2731
2732 /// Every entry archived for `session_id`, oldest first, deduplicated by id
2733 /// (a save that crashed before its document landed re-archives the same
2734 /// entries). A torn final line — a crash mid-append, whose entries are still
2735 /// in the document — is skipped; damage anywhere else is an error.
2736 pub fn load_journal_archive(
2737 sessions_dir: &Path,
2738 session_id: &str,
2739 ) -> io::Result<Vec<SessionEntry>> {
2740 let path = journal_archive_path(sessions_dir, session_id)?;
2741 let segments = list_journal_archive_segments(sessions_dir, session_id)?;
2742 let mut seen = std::collections::HashSet::new();
2743 let mut entries = Vec::new();
2744 for (_, seg_path) in segments {
2745 let file = open_private_read_file(&seg_path)?;
2746 let mut reader = io::BufReader::new(liblzma::read::XzDecoder::new(file));
2747 stream_journal_archive_lines(&mut reader, &seg_path, false, |line| {
2748 let entry: SessionEntry = serde_json::from_str(line)?;
2749 if seen.insert(entry.id.clone()) {
2750 entries.push(entry);
2751 }
2752 Ok(())
2753 })?;
2754 }
2755 let file = match open_private_read_file(&path) {
2756 Ok(file) => file,
2757 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(entries),
2758 Err(error) => return Err(error),
2759 };
2760 let mut reader = io::BufReader::new(file);
2761 stream_journal_archive_lines(&mut reader, &path, true, |line| {
2762 let entry: SessionEntry = serde_json::from_str(line)?;
2763 if seen.insert(entry.id.clone()) {
2764 entries.push(entry);
2765 }
2766 Ok(())
2767 })?;
2768 Ok(entries)
2769 }
2770
2771 pub fn load_journal_archive_ids(
2772 sessions_dir: &Path,
2773 session_id: &str,
2774 ) -> io::Result<std::collections::HashSet<String>> {
2775 let path = journal_archive_path(sessions_dir, session_id)?;
2776 let segments = list_journal_archive_segments(sessions_dir, session_id)?;
2777 let mut seen = stream_journal_archive_segment_ids(&segments)?;
2778 let file = match open_private_read_file(&path) {
2779 Ok(file) => file,
2780 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(seen),
2781 Err(error) => return Err(error),
2782 };
2783 let mut reader = io::BufReader::new(file);
2784 stream_journal_archive_lines(&mut reader, &path, true, |line| {
2785 let entry: ArchiveEntryId = serde_json::from_str(line)?;
2786 seen.insert(entry.id);
2787 Ok(())
2788 })?;
2789 Ok(seen)
2790 }
2791
2792 fn serialize_saved_session(mut session: SavedSession) -> io::Result<String> {
2793 if let Some(journal) = session.journal.as_ref() {
2794 validate_saved_journal(journal)?;
2795 }
2796 session.make_storage_compatible();
2797 serde_json::to_string(&session)
2798 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
2799 }
2800
2801 /// Repair dangling tool-call/result pairs in an already-loaded session and
2802 /// rebranch its journal to the repaired messages. Returns the repair receipt;
2803 /// callers decide whether the result gets persisted (`SessionManager::resume_*`
2804 /// does, foreign `/load` files do not).
2805 pub fn repair_recovered_session(
2806 session: &mut SavedSession,
2807 ) -> codewhale_runtime::tool_history_repair::ToolRepairReceipt {
2808 let repair =
2809 codewhale_runtime::tool_history_repair::repair_tool_call_pairs(&mut session.messages);
2810 if !repair.is_empty() {
2811 if let Some(journal) = session.journal.as_mut() {
2812 journal.rebranch_active_messages(&session.messages);
2813 session.leaf_id = journal.leaf_id.clone();
2814 }
2815 session.metadata.message_count = session.messages.len();
2816 tracing::warn!(
2817 session_id = %session.metadata.id,
2818 repaired_call_ids = ?repair.repaired_call_ids,
2819 duplicate_result_ids = ?repair.duplicate_result_ids,
2820 orphan_result_ids = ?repair.orphan_result_ids,
2821 "repaired persisted tool call/result history"
2822 );
2823 }
2824 repair
2825 }
2826
2827 /// Manager for session persistence operations
2828 #[derive(Debug)]
2829 pub struct SessionManager {
2830 /// Directory where sessions are stored
2831 sessions_dir: PathBuf,
2832 /// Re-entrancy guard: archiving a record saves it, and every save runs
2833 /// retention. Without this, a backlog past the cap would nest one
2834 /// cleanup per archived transcript instead of draining in one pass.
2835 retention_in_progress: AtomicBool,
2836 }
2837
2838 /// One interactive editor owns a session's unsent text until its last queued
2839 /// write finishes. The stable lock file is never unlinked: replacing it would
2840 /// let two processes lock different files for the same session.
2841 #[derive(Debug)]
2842 pub struct OfflineQueueLease {
2843 session_id: String,
2844 _file: fs::File,
2845 }
2846
2847 impl OfflineQueueLease {
2848 pub fn session_id(&self) -> &str {
2849 &self.session_id
2850 }
2851 }
2852
2853 impl Drop for OfflineQueueLease {
2854 fn drop(&mut self) {
2855 // A forked child can briefly retain the same open-file description.
2856 // Release the editor's lock now, rather than waiting for every inherited
2857 // descriptor to close, as RuntimeProcessOwnerLock does on shutdown.
2858 #[cfg(all(unix, not(target_os = "solaris")))]
2859 {
2860 use std::os::fd::AsRawFd as _;
2861 // SAFETY: the lease still owns this descriptor throughout Drop.
2862 unsafe {
2863 libc::flock(self._file.as_raw_fd(), libc::LOCK_UN);
2864 }
2865 }
2866 #[cfg(windows)]
2867 {
2868 use std::os::windows::io::AsRawHandle as _;
2869 use windows_sys::Win32::Storage::FileSystem::UnlockFile;
2870 // SAFETY: the lease owns the handle; fd-lock locks byte 0 only.
2871 unsafe {
2872 UnlockFile(self._file.as_raw_handle() as _, 0, 0, 1, 0);
2873 }
2874 }
2875 // fd-lock uses process-associated fcntl locks on Solaris. They are not
2876 // inherited by fork and closing this descriptor releases the lock.
2877 }
2878 }
2879
2880 /// Origin of a crash-recovery checkpoint file.
2881 #[derive(Debug, Clone, PartialEq, Eq)]
2882 pub enum CheckpointSource {
2883 /// Per-session checkpoint file `checkpoints/<session_id>.json`.
2884 Session(String),
2885 /// Legacy single-slot checkpoint file `checkpoints/latest.json`.
2886 Legacy,
2887 }
2888
2889 /// A crash-recovery checkpoint file discovered on disk (metadata only —
2890 /// callers load the session content separately).
2891 #[derive(Debug, Clone)]
2892 pub struct CheckpointRef {
2893 pub source: CheckpointSource,
2894 pub path: PathBuf,
2895 pub modified: std::time::SystemTime,
2896 }
2897
2898 /// File names in `checkpoints/` that are never per-session checkpoints.
2899 const LEGACY_CHECKPOINT_FILE: &str = "latest.json";
2900 /// Pre-per-session global offline queue, still read once for migration.
2901 const OFFLINE_QUEUE_FILE: &str = "offline_queue.json";
2902 /// Per-session offline queue file: `checkpoints/<session_id>.offline_queue.json`.
2903 const OFFLINE_QUEUE_SUFFIX: &str = ".offline_queue.json";
2904
2905 pub fn is_offline_queue_file(name: &str) -> bool {
2906 name == OFFLINE_QUEUE_FILE || name.ends_with(OFFLINE_QUEUE_SUFFIX)
2907 }
2908
2909 impl SessionManager {
2910 fn approval_receipt_store(&self) -> ApprovalReceiptStore {
2911 ApprovalReceiptStore::new(self.sessions_dir.clone())
2912 }
2913
2914 fn hydrate_approval_receipts(&self, session: &mut SavedSession) -> io::Result<()> {
2915 if let Some(durable) = self
2916 .approval_receipt_store()
2917 .load_if_present(&session.metadata.id)?
2918 {
2919 // Only a missing log permits legacy embedded evidence to stand.
2920 // An empty or torn-first log must not resurrect an old approval.
2921 session.approval_receipts = durable;
2922 }
2923 ApprovalReplay::from_receipts(&session.approval_receipts)
2924 .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
2925 Ok(())
2926 }
2927
2928 /// Reconstruct completed approvals and interrupted unmatched asks for one
2929 /// session without consulting the model transcript.
2930 pub fn replay_approvals(&self, session_id: &str) -> io::Result<ApprovalReplay> {
2931 self.approval_receipt_store().replay(session_id)
2932 }
2933
2934 pub fn validated_session_id<'a>(&self, id: &'a str) -> std::io::Result<&'a str> {
2935 let trimmed = id.trim();
2936 if trimmed.is_empty() {
2937 return Err(std::io::Error::new(
2938 std::io::ErrorKind::InvalidInput,
2939 "Session id cannot be empty",
2940 ));
2941 }
2942 if !trimmed
2943 .chars()
2944 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
2945 {
2946 return Err(std::io::Error::new(
2947 std::io::ErrorKind::InvalidInput,
2948 format!("Invalid session id '{id}'"),
2949 ));
2950 }
2951 if trimmed == SESSION_BOOT_OWNERS_STEM {
2952 return Err(std::io::Error::new(
2953 std::io::ErrorKind::InvalidInput,
2954 format!("Session id '{trimmed}' collides with a reserved sessions file"),
2955 ));
2956 }
2957 Ok(trimmed)
2958 }
2959
2960 /// Metadata of saved session `id`, read without loading its transcript.
2961 pub fn load_session_metadata_by_id(&self, id: &str) -> std::io::Result<SessionMetadata> {
2962 match self.with_session_read_lock(id, Self::late_usage_is_deleted) {
2963 Ok(true) => {
2964 return Err(io::Error::new(
2965 io::ErrorKind::NotFound,
2966 format!("Session '{}' not found", id.trim()),
2967 ));
2968 }
2969 Ok(false) => {}
2970 Err(error) => {
2971 tracing::warn!(session_id = %id, %error, "late usage deletion check failed during metadata read");
2972 }
2973 }
2974 self.load_session_metadata_by_id_raw(id)
2975 }
2976
2977 fn load_session_metadata_by_id_raw(&self, id: &str) -> std::io::Result<SessionMetadata> {
2978 let metadata = Self::load_session_metadata(&self.validated_session_path(id)?)?;
2979 self.validate_metadata_id(id, metadata)
2980 }
2981
2982 fn validate_metadata_id(
2983 &self,
2984 id: &str,
2985 metadata: SessionMetadata,
2986 ) -> io::Result<SessionMetadata> {
2987 if metadata.id != self.validated_session_id(id)? {
2988 return Err(io::Error::new(
2989 io::ErrorKind::InvalidData,
2990 "saved session metadata names a different session id",
2991 ));
2992 }
2993 Ok(metadata)
2994 }
2995
2996 fn validated_session_path(&self, id: &str) -> std::io::Result<PathBuf> {
2997 let trimmed = self.validated_session_id(id)?;
2998 Ok(self.sessions_dir.join(format!("{trimmed}.json")))
2999 }
3000
3001 fn checkpoints_dir(&self) -> PathBuf {
3002 self.sessions_dir.join("checkpoints")
3003 }
3004
3005 fn session_goals_dir(&self) -> PathBuf {
3006 self.sessions_dir.join(SESSION_GOALS_DIR)
3007 }
3008
3009 fn checked_existing_session_goals_dir(&self) -> std::io::Result<Option<PathBuf>> {
3010 let dir = self.session_goals_dir();
3011 let metadata = match fs::symlink_metadata(&dir) {
3012 Ok(metadata) => metadata,
3013 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
3014 Err(error) => return Err(error),
3015 };
3016 if metadata.file_type().is_symlink() || !metadata.is_dir() {
3017 return Err(io::Error::new(
3018 io::ErrorKind::InvalidData,
3019 format!(
3020 "Session goal store {} must be a real directory",
3021 dir.display()
3022 ),
3023 ));
3024 }
3025 Ok(Some(dir))
3026 }
3027
3028 fn ensure_session_goals_dir(&self) -> std::io::Result<PathBuf> {
3029 if let Some(dir) = self.checked_existing_session_goals_dir()? {
3030 return Ok(dir);
3031 }
3032 let dir = self.session_goals_dir();
3033 match fs::create_dir(&dir) {
3034 Ok(()) => {}
3035 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
3036 Err(error) => return Err(error),
3037 }
3038 self.checked_existing_session_goals_dir()?.ok_or_else(|| {
3039 io::Error::new(
3040 io::ErrorKind::NotFound,
3041 format!("Session goal store {} was not created", dir.display()),
3042 )
3043 })
3044 }
3045
3046 fn validated_session_goal_path(&self, session_id: &str) -> std::io::Result<PathBuf> {
3047 let id = self.validated_session_id(session_id)?;
3048 Ok(self.session_goals_dir().join(format!("{id}.json")))
3049 }
3050
3051 fn checked_existing_session_goal_file(path: &Path) -> std::io::Result<bool> {
3052 let metadata = match fs::symlink_metadata(path) {
3053 Ok(metadata) => metadata,
3054 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
3055 Err(error) => return Err(error),
3056 };
3057 if metadata.file_type().is_symlink() || !metadata.is_file() {
3058 return Err(io::Error::new(
3059 io::ErrorKind::InvalidData,
3060 format!("Session goal {} must be a regular file", path.display()),
3061 ));
3062 }
3063 Ok(true)
3064 }
3065
3066 fn validated_checkpoint_path(&self, session_id: &str) -> std::io::Result<PathBuf> {
3067 let trimmed = self.validated_session_id(session_id)?;
3068 // Reserved file names inside `checkpoints/` must never collide with a
3069 // per-session checkpoint file.
3070 if format!("{trimmed}.json") == LEGACY_CHECKPOINT_FILE
3071 || format!("{trimmed}.json") == OFFLINE_QUEUE_FILE
3072 {
3073 return Err(std::io::Error::new(
3074 std::io::ErrorKind::InvalidInput,
3075 format!("Session id '{trimmed}' collides with a reserved checkpoint file"),
3076 ));
3077 }
3078 Ok(self.checkpoints_dir().join(format!("{trimmed}.json")))
3079 }
3080
3081 /// Create a new `SessionManager` with the specified sessions directory
3082 pub fn new(sessions_dir: PathBuf) -> std::io::Result<Self> {
3083 let sessions_dir = normalize_managed_dir(sessions_dir)?;
3084 // Ensure the sessions directory exists
3085 fs::create_dir_all(&sessions_dir)?;
3086 Ok(Self {
3087 sessions_dir,
3088 retention_in_progress: AtomicBool::new(false),
3089 })
3090 }
3091
3092 pub fn open_read_only(sessions_dir: PathBuf) -> io::Result<Option<Self>> {
3093 let sessions_dir = normalize_managed_dir(sessions_dir)?;
3094 match fs::metadata(&sessions_dir) {
3095 Ok(metadata) if metadata.is_dir() => Ok(Some(Self {
3096 sessions_dir,
3097 retention_in_progress: AtomicBool::new(false),
3098 })),
3099 Ok(_) => Err(io::Error::new(
3100 io::ErrorKind::InvalidData,
3101 "sessions root is not a directory",
3102 )),
3103 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
3104 Err(error) => Err(error),
3105 }
3106 }
3107
3108 pub fn load_usage_metadata(&self, id: &str) -> io::Result<SessionMetadata> {
3109 let (mut metadata, ledger) = self.with_session_read_lock(id, |path| {
3110 let deleted = Self::late_usage_is_deleted(path);
3111 if matches!(deleted, Ok(true)) {
3112 return Err(io::Error::new(
3113 io::ErrorKind::NotFound,
3114 format!("Session '{}' not found", id.trim()),
3115 ));
3116 }
3117 let metadata = self.load_session_metadata_by_id_raw(id)?;
3118 if metadata.id != id {
3119 return Err(io::Error::new(
3120 io::ErrorKind::InvalidData,
3121 "session metadata id does not match its record",
3122 ));
3123 }
3124 let ledger = match deleted {
3125 Ok(false) => Self::load_late_usage_unlocked(path),
3126 Ok(true) => unreachable!(),
3127 Err(error) => Err(error),
3128 };
3129 Ok((metadata, ledger))
3130 })?;
3131 Self::apply_late_usage_result(&mut metadata, ledger);
3132 Ok(metadata)
3133 }
3134
3135 /// Create a `SessionManager` using the default location.
3136 pub fn default_location() -> std::io::Result<Self> {
3137 Self::new(default_sessions_dir()?)
3138 }
3139
3140 /// Return the resolved sessions directory path.
3141 pub fn sessions_dir(&self) -> &Path {
3142 &self.sessions_dir
3143 }
3144
3145 pub fn exec_route_binding_key(sessions_dir: &Path, create: bool) -> anyhow::Result<[u8; 32]> {
3146 use ring::rand::SecureRandom as _;
3147 let directory = sessions_dir.join(".exec-route");
3148 let directory = if create {
3149 codewhale_config::private_directory::PrivateDirectory::open(&directory)?
3150 } else {
3151 codewhale_config::private_directory::PrivateDirectory::inspect(&directory)?
3152 };
3153 let name = "key";
3154 let read = || -> anyhow::Result<Option<[u8; 32]>> {
3155 directory
3156 .read_private_receipt(name, 32)?
3157 .map(|(bytes, _)| {
3158 bytes
3159 .try_into()
3160 .map_err(|_| anyhow::anyhow!("invalid exec route binding key"))
3161 })
3162 .transpose()
3163 };
3164 if let Some(key) = read()? {
3165 return Ok(key);
3166 }
3167 anyhow::ensure!(create, "exec route binding key is missing");
3168 let mut key = [0u8; 32];
3169 ring::rand::SystemRandom::new()
3170 .fill(&mut key)
3171 .map_err(|_| anyhow::anyhow!("could not generate an exec route binding key"))?;
3172 if let Err(error) = directory.write_owned_file(name, &key, false) {
3173 return read()?.ok_or(error);
3174 }
3175 Ok(key)
3176 }
3177
3178 /// The live-lease file for `session_id`; see [`set_live_session`].
3179 fn live_lease_path(&self, session_id: &str, create_dir: bool) -> io::Result<PathBuf> {
3180 let (late_path, _) = if create_dir {
3181 self.ensure_late_usage_paths(session_id)?
3182 } else {
3183 self.late_usage_paths(session_id)?
3184 };
3185 Ok(late_path.with_extension("live"))
3186 }
3187
3188 /// Claim `session_id` for this process's interactive surface: the
3189 /// in-process registry ([`set_live_session`]) plus the cross-process
3190 /// lease in this store, so writers in other processes see it too.
3191 ///
3192 /// Known limitation: this claim is best-effort. Attach paths reserve the
3193 /// lease up front ([`Self::reserve_session_for_attach`]), but a session
3194 /// that starts fresh is claimed only at its first snapshot, and a claim
3195 /// that loses the lock to another process's probe or external write, or
3196 /// cannot open the lease file, runs unleased until a later snapshot
3197 /// retries it (an open failure is logged only at debug). In that window
3198 /// another process's external writer can take the lease and write, and
3199 /// this session's next autosave reverts that write.
3200 pub fn claim_live_session(&self, session_id: &str) {
3201 set_live_session(Some(session_id));
3202 let id = session_id.trim();
3203 let Ok(mut lease) = LIVE_SESSION_LEASE.lock() else {
3204 return;
3205 };
3206 // A lease already held is kept. One that could not be taken is tried
3207 // again: another process's liveness probe briefly holds the same lock,
3208 // and a claim that lost that race once must not run unleased for the
3209 // rest of the session.
3210 let retry = match lease.as_ref() {
3211 Some((held, Some(_))) if held == id => return,
3212 Some((held, None)) => held == id,
3213 _ => false,
3214 };
3215 let file = self.live_lease_path(id, true).and_then(|path| {
3216 let file = open_private_lock_file(&path)?;
3217 Ok(codewhale_util::lock::try_lock_file_exclusive(&file)?.then_some(file))
3218 });
3219 match &file {
3220 Ok(Some(_)) => {}
3221 Ok(None) if !retry => tracing::warn!(
3222 session_id = id,
3223 "another Codewhale process already holds this session open"
3224 ),
3225 Ok(None) => {}
3226 Err(error) => {
3227 tracing::debug!(session_id = id, %error, "session live lease unavailable");
3228 }
3229 }
3230 *lease = Some((id.to_string(), file.ok().flatten()));
3231 }
3232
3233 /// Reserve `session_id` before attaching to it (`resume`, `--continue`,
3234 /// `exec --resume`, the session picker, `/load`). Unlike
3235 /// [`Self::claim_live_session`], which records whatever it gets, this
3236 /// refuses with `ResourceBusy` when another process holds the session
3237 /// open: attaching anyway gives the document two autosaving writers, and
3238 /// the last save silently drops the other's turns. Taking the lock is the
3239 /// check, so nothing can claim the session between a check and the attach.
3240 ///
3241 /// The reservation does not touch the session this process owns now: that
3242 /// claim and its lease stay until [`SessionLease::commit`], which the
3243 /// caller runs only once the new session is loaded and applied. Dropping
3244 /// the reservation (a load or apply that failed) releases it and leaves
3245 /// the current session leased.
3246 ///
3247 /// It fails closed: a lease that cannot be opened or locked is an error,
3248 /// not an unguarded attach.
3249 pub fn reserve_session_for_attach(&self, session_id: &str) -> io::Result<SessionLease> {
3250 let id = self.validated_session_id(session_id)?;
3251 if LIVE_SESSION_LEASE
3252 .lock()
3253 .is_ok_and(|lease| matches!(lease.as_ref(), Some((held, Some(_))) if held == id))
3254 {
3255 return Ok(SessionLease {
3256 id: id.to_string(),
3257 file: None,
3258 });
3259 }
3260 let lease_unavailable = |error: io::Error| {
3261 io::Error::new(
3262 error.kind(),
3263 format!("could not take session {id}'s live lease: {error}"),
3264 )
3265 };
3266 let file = self
3267 .live_lease_path(id, true)
3268 .and_then(|path| open_private_lock_file(&path))
3269 .map_err(lease_unavailable)?;
3270 // A liveness probe from another process holds this lock for a moment;
3271 // a few short retries tell that apart from a running owner.
3272 for attempt in 0..LIVE_LEASE_ATTACH_ATTEMPTS {
3273 if codewhale_util::lock::try_lock_file_exclusive(&file).map_err(lease_unavailable)? {
3274 return Ok(SessionLease {
3275 id: id.to_string(),
3276 file: Some(file),
3277 });
3278 }
3279 if attempt + 1 < LIVE_LEASE_ATTACH_ATTEMPTS {
3280 std::thread::sleep(std::time::Duration::from_millis(10));
3281 }
3282 }
3283 Err(session_open_elsewhere(id))
3284 }
3285
3286 /// Hold the existing live lease throughout an external mutation. A
3287 /// liveness probe releases its lock before returning and cannot protect
3288 /// the subsequent read/write from another surface attaching meanwhile.
3289 ///
3290 /// Refuses with `ResourceBusy` when an interactive session in this or
3291 /// another process holds the session, and with `InvalidInput` for a
3292 /// malformed id. It may sleep briefly between lock attempts (see
3293 /// [`Self::reserve_session_for_attach`]), so async callers run it under
3294 /// `spawn_blocking`. Keep the returned lease alive until the write lands.
3295 pub fn reserve_session_for_external_write(&self, id: &str) -> io::Result<SessionLease> {
3296 let live = live_sessions()
3297 .read()
3298 .map_err(|_| io::Error::other("session ownership registry unavailable"))?;
3299 if live.contains(id.trim()) {
3300 return Err(live_session_conflict(id));
3301 }
3302 drop(live);
3303 let lease = self.reserve_session_for_attach(id)?;
3304 // A same-process attach may have committed after the registry read.
3305 // Its already-held lease is borrowed, never ours to mutate through.
3306 if lease.file.is_none() {
3307 return Err(live_session_conflict(id));
3308 }
3309 Ok(lease)
3310 }
3311
3312 /// Is `session_id` open in an interactive session in this process *or any
3313 /// other*? A read-only hint for listings and recovery candidates (the
3314 /// session picker, interrupted-work discovery, retention's candidate
3315 /// scan). It never authorizes a write: the probe releases its lock before
3316 /// returning, so every mutation — rename, archive, delete, the Runtime
3317 /// API's export and save, `scrub-secrets` — holds
3318 /// [`Self::reserve_session_for_external_write`] across its load and save
3319 /// instead (#6144).
3320 ///
3321 /// Fails closed: a malformed id, or a lease that cannot be opened, reads
3322 /// as live, so a caller skips it rather than acting on it. Callers that
3323 /// must tell a malformed id apart (a 400, not a 409) validate first or
3324 /// reserve the lease, which reports `InvalidInput`.
3325 ///
3326 #[must_use]
3327 pub fn is_session_live_anywhere(&self, session_id: &str) -> bool {
3328 if is_live_session(session_id) {
3329 return true;
3330 }
3331 let Ok(path) = self.live_lease_path(session_id, false) else {
3332 return true;
3333 };
3334 let file = match open_private_read_file(&path) {
3335 Ok(file) => file,
3336 Err(error) if error.kind() == io::ErrorKind::NotFound => return false,
3337 Err(_) => return true,
3338 };
3339 // Contention means a live holder; acquiring proves none, and the
3340 // probe's lock is released when `file` drops here.
3341 !matches!(
3342 codewhale_util::lock::try_lock_file_exclusive(&file),
3343 Ok(true)
3344 )
3345 }
3346
3347 /// Hold `session_id`'s live lease the way another running Codewhale
3348 /// process does: an OS lock on its own open file description.
3349 #[cfg(any(test, feature = "test-support"))]
3350 pub fn hold_live_lease_elsewhere(&self, session_id: &str) -> fs::File {
3351 let path = self.live_lease_path(session_id, true).expect("lease path");
3352 let lease = open_private_lock_file(&path).expect("open lease");
3353 assert!(codewhale_util::lock::try_lock_file_exclusive(&lease).expect("lock lease"));
3354 lease
3355 }
3356
3357 /// Whether a saved document exists for `session_id`.
3358 #[must_use]
3359 pub fn session_document_exists(&self, session_id: &str) -> bool {
3360 self.validated_session_path(session_id)
3361 .is_ok_and(|path| path.is_file())
3362 }
3363
3364 fn late_usage_paths(&self, session_id: &str) -> io::Result<(PathBuf, PathBuf)> {
3365 let session_id = self.validated_session_id(session_id)?;
3366 let dir = self.sessions_dir.join(LATE_USAGE_DIR);
3367 match fs::symlink_metadata(&dir) {
3368 Ok(metadata) => {
3369 #[cfg(windows)]
3370 let linked = {
3371 use std::os::windows::fs::MetadataExt as _;
3372 metadata.file_attributes()
3373 & windows_sys::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT
3374 != 0
3375 };
3376 #[cfg(not(windows))]
3377 let linked = metadata.file_type().is_symlink();
3378 if linked || !metadata.is_dir() {
3379 return Err(io::Error::new(
3380 io::ErrorKind::InvalidData,
3381 "late usage store must be a real directory",
3382 ));
3383 }
3384 }
3385 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
3386 Err(error) => return Err(error),
3387 }
3388 Ok((
3389 dir.join(format!("{session_id}.json")),
3390 dir.join(format!("{session_id}.lock")),
3391 ))
3392 }
3393
3394 fn ensure_late_usage_paths(&self, session_id: &str) -> io::Result<(PathBuf, PathBuf)> {
3395 self.late_usage_paths(session_id)?;
3396 let dir = self.sessions_dir.join(LATE_USAGE_DIR);
3397 match fs::create_dir(&dir) {
3398 Ok(()) => {}
3399 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
3400 Err(error) => return Err(error),
3401 }
3402 let paths = self.late_usage_paths(session_id)?;
3403 #[cfg(unix)]
3404 {
3405 use std::os::unix::fs::OpenOptionsExt as _;
3406 let handle = OpenOptions::new()
3407 .read(true)
3408 .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
3409 .open(&dir)?;
3410 codewhale_config::private_directory::tighten_mode_of(&handle, &dir, 0o700)
3411 .map_err(|error| std::io::Error::other(error.to_string()))?;
3412 }
3413 Ok(paths)
3414 }
3415
3416 /// A deletion marker and its stable lock survive deletion, without any
3417 /// route or usage data. A captured callback must never recreate the ledger.
3418 fn late_usage_is_deleted(path: &Path) -> io::Result<bool> {
3419 use std::io::Read as _;
3420 let tombstone = match open_private_read_file(&path.with_extension("deleted")) {
3421 Ok(file) => file,
3422 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
3423 Err(error) => return Err(error),
3424 };
3425 let mut marker = Vec::with_capacity(LATE_USAGE_DELETED.len());
3426 tombstone
3427 .take(u64::try_from(LATE_USAGE_DELETED.len()).unwrap_or(u64::MAX) + 1)
3428 .read_to_end(&mut marker)?;
3429 if marker != LATE_USAGE_DELETED {
3430 return Err(io::Error::new(
3431 io::ErrorKind::InvalidData,
3432 "invalid late usage deletion marker",
3433 ));
3434 }
3435 Ok(true)
3436 }
3437
3438 fn write_late_usage_ledger(path: &Path, ledger: &LateUsageLedger) -> io::Result<()> {
3439 let mut bytes = serde_json::to_vec(ledger)
3440 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
3441 let limit = usize::try_from(MAX_LATE_USAGE_LEDGER_BYTES).unwrap_or(usize::MAX);
3442 if bytes.len() > limit {
3443 let mut remaining_bytes = bytes.len();
3444 let mut pruned = 0;
3445 for record in ledger
3446 .records
3447 .iter()
3448 .filter(|record| record.diagnostic_only)
3449 {
3450 let record_len = serde_json::to_vec(record)
3451 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?
3452 .len();
3453 pruned += 1;
3454 let comma = usize::from(pruned < ledger.records.len());
3455 remaining_bytes -= record_len + comma;
3456 if remaining_bytes <= limit {
3457 break;
3458 }
3459 }
3460 if remaining_bytes > limit {
3461 return Err(io::Error::new(
3462 io::ErrorKind::InvalidData,
3463 "late usage ledger exceeds its size bound",
3464 ));
3465 }
3466 let mut compacted = ledger.clone();
3467 let mut remaining = pruned;
3468 compacted.records.retain(|record| {
3469 if record.diagnostic_only && remaining > 0 {
3470 remaining -= 1;
3471 return false;
3472 }
3473 true
3474 });
3475 bytes = serde_json::to_vec(&compacted)
3476 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
3477 tracing::warn!(
3478 pruned,
3479 "compacted late usage diagnostic receipts to fit the ledger bound"
3480 );
3481 }
3482 let parent = path.parent().ok_or_else(|| {
3483 io::Error::new(io::ErrorKind::InvalidInput, "usage ledger has no parent")
3484 })?;
3485 let name = path.file_name().ok_or_else(|| {
3486 io::Error::new(io::ErrorKind::InvalidInput, "usage ledger has no basename")
3487 })?;
3488 codewhale_util::files::WorkspaceFile::open_resolved_root(parent, Path::new(name), false)?
3489 .replace(&bytes)?;
3490 Self::sync_late_usage_ledger(path)
3491 }
3492
3493 fn sync_late_usage_ledger(path: &Path) -> io::Result<()> {
3494 let parent = path.parent().ok_or_else(|| {
3495 io::Error::new(io::ErrorKind::InvalidInput, "usage ledger has no parent")
3496 })?;
3497 let name = path.file_name().ok_or_else(|| {
3498 io::Error::new(io::ErrorKind::InvalidInput, "usage ledger has no basename")
3499 })?;
3500 let ledger = codewhale_util::files::WorkspaceFile::open_resolved_root(
3501 parent,
3502 Path::new(name),
3503 false,
3504 )?;
3505 ledger.open_update(false, false)?.sync_all()?;
3506 ledger.sync_parent()?;
3507 #[cfg(unix)]
3508 for directory in [parent, parent.parent().unwrap_or(parent)] {
3509 if let (Some(ancestor), Some(name)) = (directory.parent(), directory.file_name()) {
3510 codewhale_util::files::WorkspaceFile::open_resolved_root(
3511 ancestor,
3512 Path::new(name),
3513 false,
3514 )?
3515 .sync_parent()?;
3516 }
3517 }
3518 Ok(())
3519 }
3520
3521 fn load_late_usage_unlocked(path: &Path) -> io::Result<LateUsageLedger> {
3522 let file = match open_private_read_file(path) {
3523 Ok(file) => file,
3524 Err(error) if error.kind() == io::ErrorKind::NotFound => {
3525 return Ok(LateUsageLedger::default());
3526 }
3527 Err(error) => return Err(error),
3528 };
3529 let metadata = file.metadata()?;
3530 if metadata.len() > MAX_LATE_USAGE_LEDGER_BYTES {
3531 return Err(io::Error::new(
3532 io::ErrorKind::InvalidData,
3533 format!(
3534 "late usage ledger {} exceeds its size bound",
3535 path.display()
3536 ),
3537 ));
3538 }
3539 use std::io::Read as _;
3540 let mut raw = Vec::with_capacity(
3541 usize::try_from(metadata.len().min(MAX_LATE_USAGE_LEDGER_BYTES)).unwrap_or(0),
3542 );
3543 file.take(MAX_LATE_USAGE_LEDGER_BYTES.saturating_add(1))
3544 .read_to_end(&mut raw)?;
3545 if u64::try_from(raw.len()).unwrap_or(u64::MAX) > MAX_LATE_USAGE_LEDGER_BYTES {
3546 return Err(io::Error::new(
3547 io::ErrorKind::InvalidData,
3548 format!(
3549 "late usage ledger {} exceeds its size bound",
3550 path.display()
3551 ),
3552 ));
3553 }
3554 let ledger: LateUsageLedger = serde_json::from_slice(&raw)
3555 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
3556 if !(1..=CURRENT_LATE_USAGE_SCHEMA_VERSION).contains(&ledger.schema_version)
3557 || (ledger.schema_version < 2
3558 && ledger
3559 .records
3560 .iter()
3561 .any(|record| record.settlement.is_some()))
3562 || ledger
3563 .records
3564 .iter()
3565 .filter(|record| record.unresolved())
3566 .count()
3567 > MAX_LATE_USAGE_UNRESOLVED_RECORDS_PER_SESSION
3568 || ledger.records.iter().any(|record| {
3569 record.runtime_record().validate().is_err()
3570 || !is_sha256_fingerprint(&record.source_fingerprint)
3571 || !is_sha256_fingerprint(&record.turn_fingerprint)
3572 || record.decision.as_ref().is_some_and(|r| !r.is_bounded())
3573 })
3574 {
3575 return Err(io::Error::new(
3576 io::ErrorKind::InvalidData,
3577 "late usage ledger has an unsupported or unbounded shape",
3578 ));
3579 }
3580 Ok(ledger)
3581 }
3582
3583 fn with_session_write_admission<T>(
3584 &self,
3585 session_id: &str,
3586 write: impl FnOnce() -> io::Result<T>,
3587 ) -> io::Result<Option<T>> {
3588 let (path, lock_path) = self.ensure_late_usage_paths(session_id)?;
3589 let lock_file = open_private_lock_file(&lock_path)?;
3590 let mut lock = fd_lock::RwLock::new(lock_file);
3591 let _guard = lock.write()?;
3592 if Self::late_usage_is_deleted(&path)? {
3593 Self::sync_late_usage_ledger(&path.with_extension("deleted"))?;
3594 return Ok(None);
3595 }
3596 write().map(Some)
3597 }
3598
3599 fn with_session_observation<T>(
3600 &self,
3601 session_id: &str,
3602 observe: impl FnOnce() -> io::Result<T>,
3603 ) -> io::Result<Option<T>> {
3604 self.with_session_read_lock(session_id, |path| {
3605 if Self::late_usage_is_deleted(path)? {
3606 return Ok(None);
3607 }
3608 observe().map(Some)
3609 })
3610 }
3611
3612 /// Run an out-of-band rewrite of a session's files (`scrub-secrets`)
3613 /// under the same per-session lock every save takes, so it cannot
3614 /// interleave with a save, and while holding the session's live lease, so
3615 /// no interactive session holds the conversation in memory to put the old
3616 /// content back on its next autosave. `None` when the session was
3617 /// deleted; an invalid id is an `InvalidInput` error, and a session open
3618 /// in an interactive surface is `ResourceBusy`, left untouched.
3619 ///
3620 /// The lease is taken inside the save lock with non-blocking attempts, so
3621 /// the reverse order elsewhere (lease, then a save) cannot deadlock: one
3622 /// side reports busy instead.
3623 pub fn with_session_file_lock<T>(
3624 &self,
3625 session_id: &str,
3626 rewrite: impl FnOnce() -> io::Result<T>,
3627 ) -> io::Result<Option<T>> {
3628 let session_id = self.validated_session_id(session_id)?;
3629 self.with_session_write_admission(session_id, || {
3630 let _lease = self.reserve_session_for_external_write(session_id)?;
3631 rewrite()
3632 })
3633 }
3634
3635 /// Serialize active accounting admission with deletion of its origin.
3636 /// A retired origin is handled without running the callback. Callers must
3637 /// release this boundary before attempting a late-usage append, which
3638 /// independently checks retirement under the same stable lock.
3639 pub fn with_live_session_origin(
3640 &self,
3641 session_id: &str,
3642 accept: impl FnOnce() -> bool,
3643 ) -> io::Result<Option<bool>> {
3644 self.with_session_write_admission(session_id, || Ok(accept()))
3645 }
3646
3647 fn retired_session_write_error() -> io::Error {
3648 io::Error::new(io::ErrorKind::NotFound, "session was deleted")
3649 }
3650
3651 fn persist_late_usage_record(
3652 &self,
3653 session_id: &str,
3654 incoming: LateUsageRecord,
3655 ) -> io::Result<bool> {
3656 let (path, lock_path) = self.ensure_late_usage_paths(session_id)?;
3657 let lock_file = open_private_lock_file(&lock_path)?;
3658 let mut lock = fd_lock::RwLock::new(lock_file);
3659 let _guard = lock.write()?;
3660 if Self::late_usage_is_deleted(&path)? {
3661 // Handled, rather than a failed sink that should queue a retry.
3662 Self::sync_late_usage_ledger(&path.with_extension("deleted"))?;
3663 return Ok(true);
3664 }
3665 self.persist_late_usage_record_admitted(&path, incoming)
3666 }
3667
3668 fn persist_late_usage_record_admitted(
3669 &self,
3670 path: &Path,
3671 incoming: LateUsageRecord,
3672 ) -> io::Result<bool> {
3673 let mut ledger = Self::load_late_usage_unlocked(path)?;
3674 let original = ledger.clone();
3675 let source_fingerprint = incoming.source_fingerprint.clone();
3676 if let Some(record) = ledger
3677 .records
3678 .iter_mut()
3679 .find(|record| record.source_fingerprint == source_fingerprint)
3680 {
3681 if record.turn_fingerprint != incoming.turn_fingerprint
3682 || record.route != incoming.route
3683 {
3684 return Err(io::Error::new(
3685 io::ErrorKind::InvalidData,
3686 "late usage source changed its captured origin or route",
3687 ));
3688 }
3689 if record.settlement.is_some()
3690 && record.usage != incoming.usage
3691 && incoming.decision.is_none()
3692 {
3693 return Err(io::Error::new(
3694 io::ErrorKind::PermissionDenied,
3695 "serialized usage cannot replace a native source revision",
3696 ));
3697 }
3698 let mut changed = false;
3699 if record.settlement.is_none()
3700 && record
3701 .usage
3702 .as_ref()
3703 .is_none_or(|usage| *usage == codewhale_models::Usage::default())
3704 && let Some(usage) = incoming.usage.as_ref()
3705 {
3706 record.usage = Some(usage.clone());
3707 if !incoming.diagnostic_only {
3708 record.diagnostic_only = false;
3709 }
3710 changed = true;
3711 }
3712 if let Some(decision) = incoming.decision.as_ref() {
3713 if !decision.is_bounded() {
3714 return Err(io::Error::new(
3715 io::ErrorKind::InvalidData,
3716 "decision receipt exceeds its bound",
3717 ));
3718 }
3719 record.decision = Some(decision.sanitized());
3720 changed = true;
3721 }
3722 if changed {
3723 Self::write_late_usage_candidate(path, &original, &ledger)?;
3724 }
3725 return Ok(true);
3726 }
3727 let known_usage = incoming.usage.as_ref();
3728 if known_usage.is_none()
3729 && ledger
3730 .records
3731 .iter()
3732 .filter(|record| record.unresolved())
3733 .count()
3734 == MAX_LATE_USAGE_UNRESOLVED_RECORDS_PER_SESSION
3735 {
3736 if !ledger.overflowed {
3737 ledger.overflowed = true;
3738 Self::write_late_usage_ledger(path, &ledger)?;
3739 }
3740 return Ok(true);
3741 }
3742 ledger.records.push(incoming);
3743 Self::write_late_usage_candidate(path, &original, &ledger)?;
3744 Ok(true)
3745 }
3746
3747 /// Preserve the last complete ledger on a failed known-receipt append.
3748 /// Its existing overflow flag records settlement incompleteness; the error
3749 /// is returned, never treated as handled or a reason to repeat a provider.
3750 fn write_late_usage_candidate(
3751 path: &Path,
3752 original: &LateUsageLedger,
3753 candidate: &LateUsageLedger,
3754 ) -> io::Result<()> {
3755 match Self::write_late_usage_ledger(path, candidate) {
3756 Ok(()) => Ok(()),
3757 Err(error) => {
3758 if !original.overflowed {
3759 let mut retained = original.clone();
3760 retained.overflowed = true;
3761 if let Err(gap_error) = Self::write_late_usage_ledger(path, &retained) {
3762 tracing::warn!(%gap_error, "late usage settlement gap could not be persisted");
3763 }
3764 }
3765 Err(error)
3766 }
3767 }
3768 }
3769
3770 pub fn persist_late_decision_receipt(
3771 &self,
3772 session_id: &str,
3773 turn_id: &str,
3774 receipt: &crate::cost_status::RuntimeDecisionReceipt,
3775 ) -> io::Result<bool> {
3776 if !receipt.is_bounded() {
3777 return Err(io::Error::new(
3778 io::ErrorKind::InvalidData,
3779 "decision receipt exceeds its bound",
3780 ));
3781 }
3782 let mut incoming = LateUsageRecord::captured(
3783 turn_id,
3784 &receipt.source_id,
3785 &receipt.route,
3786 None,
3787 Some(receipt),
3788 crate::cost_status::RuntimeUsageMissingReason::SuccessWithoutUsage,
3789 );
3790 incoming.diagnostic_only = true;
3791 self.persist_late_usage_record(session_id, incoming)
3792 }
3793
3794 /// Read the bounded provider decision evidence from the existing origin ledger.
3795 #[cfg(any(test, feature = "test-support"))]
3796 pub fn decision_receipts_for_session(
3797 &self,
3798 session_id: &str,
3799 ) -> io::Result<Vec<crate::cost_status::RuntimeDecisionReceipt>> {
3800 Ok(self
3801 .load_late_usage(session_id)?
3802 .records
3803 .into_iter()
3804 .filter_map(|record| record.decision)
3805 .collect())
3806 }
3807
3808 pub fn persist_runtime_usage_record(
3809 &self,
3810 session_id: &str,
3811 record: &crate::cost_status::RuntimeUsageRecord,
3812 ) -> io::Result<bool> {
3813 self.with_session_write_admission(session_id, || {
3814 self.persist_runtime_usage_record_admitted(session_id, session_id, record)
3815 })
3816 .map(|handled| handled.unwrap_or(true))
3817 }
3818
3819 pub(crate) fn persist_runtime_usage_record_admitted(
3820 &self,
3821 session_id: &str,
3822 turn_id: &str,
3823 record: &crate::cost_status::RuntimeUsageRecord,
3824 ) -> io::Result<bool> {
3825 let (path, _) = self.late_usage_paths(session_id)?;
3826 let mut ledger = Self::load_late_usage_unlocked(&path)?;
3827 let original = ledger.clone();
3828 let key = crate::cost_status::usage_source_fingerprint(&record.source_id);
3829 let index = ledger
3830 .records
3831 .iter()
3832 .position(|old| old.source_fingerprint == key);
3833 let previous = index.map(|index| &ledger.records[index]);
3834 if previous.is_some_and(|old| {
3835 old.turn_fingerprint != crate::cost_status::usage_source_fingerprint(turn_id)
3836 || old.route != record.usage.route.sanitized_for_persistence()
3837 }) {
3838 return Err(io::Error::new(
3839 io::ErrorKind::InvalidData,
3840 "usage source changed its captured origin or route",
3841 ));
3842 }
3843 let previous_record = previous.filter(|old| !old.diagnostic_only).map(|old| {
3844 let mut record = crate::cost_status::RuntimeUsageRecord::legacy(
3845 old.source_fingerprint.clone(),
3846 crate::cost_status::EffectiveRouteUsage {
3847 route: old.route.clone(),
3848 usage: old.usage.clone().unwrap_or_default(),
3849 },
3850 );
3851 record.settlement = old.settlement.clone();
3852 record
3853 });
3854 if !record.supersedes(previous_record.as_ref()) {
3855 Self::sync_late_usage_ledger(&path)?;
3856 return Ok(true);
3857 }
3858 let unresolved = record.settlement.as_ref().is_some_and(|revision| {
3859 matches!(
3860 revision.coverage,
3861 crate::llm_client::ProviderUsageCoverage::Missing
3862 | crate::llm_client::ProviderUsageCoverage::Incomplete
3863 )
3864 });
3865 if index.is_none()
3866 && unresolved
3867 && ledger.records.iter().filter(|old| old.unresolved()).count()
3868 >= MAX_LATE_USAGE_UNRESOLVED_RECORDS_PER_SESSION
3869 {
3870 return Err(io::Error::new(
3871 io::ErrorKind::StorageFull,
3872 "late usage unresolved-source capacity reached; exact receipt retained",
3873 ));
3874 }
3875 let mut incoming = LateUsageRecord::captured(
3876 turn_id,
3877 &record.source_id,
3878 &record.usage.route,
3879 Some(&record.usage.usage),
3880 None,
3881 record
3882 .settlement
3883 .as_ref()
3884 .and_then(|revision| revision.reason)
3885 .unwrap_or_default(),
3886 );
3887 incoming.usage = Some(record.usage.usage.clone());
3888 incoming.settlement = record.settlement.clone();
3889 ledger.schema_version = CURRENT_LATE_USAGE_SCHEMA_VERSION;
3890 if let Some(index) = index {
3891 incoming.decision = ledger.records[index].decision.clone();
3892 ledger.records[index] = incoming;
3893 } else {
3894 ledger.records.push(incoming);
3895 }
3896 Self::write_late_usage_candidate(&path, &original, &ledger)?;
3897 Ok(true)
3898 }
3899
3900 pub fn has_native_usage_records(&self, session_id: &str) -> io::Result<bool> {
3901 self.with_session_write_admission(session_id, || {
3902 let (path, _) = self.late_usage_paths(session_id)?;
3903 Ok(Self::load_late_usage_unlocked(&path)?
3904 .records
3905 .iter()
3906 .any(|record| record.settlement.is_some() && !record.diagnostic_only))
3907 })?
3908 .ok_or_else(Self::retired_session_write_error)
3909 }
3910
3911 pub(crate) fn persist_legacy_usage_admitted(
3912 &self,
3913 session_id: &str,
3914 turn_id: &str,
3915 record: &crate::cost_status::RuntimeUsageRecord,
3916 ) -> io::Result<bool> {
3917 let (path, _) = self.late_usage_paths(session_id)?;
3918 self.persist_late_usage_record_admitted(
3919 &path,
3920 LateUsageRecord::captured(
3921 turn_id,
3922 &record.source_id,
3923 &record.usage.route,
3924 Some(&record.usage.usage),
3925 None,
3926 crate::cost_status::RuntimeUsageMissingReason::SuccessWithoutUsage,
3927 ),
3928 )
3929 }
3930
3931 pub fn persist_late_runtime_usage(
3932 &self,
3933 session_id: &str,
3934 turn_id: &str,
3935 record: &crate::cost_status::RuntimeUsageRecord,
3936 ) -> io::Result<bool> {
3937 self.persist_late_usage_record(
3938 session_id,
3939 LateUsageRecord::captured(
3940 turn_id,
3941 &record.source_id,
3942 &record.usage.route,
3943 Some(&record.usage.usage),
3944 None,
3945 crate::cost_status::RuntimeUsageMissingReason::SuccessWithoutUsage,
3946 ),
3947 )
3948 }
3949
3950 pub fn persist_late_runtime_drop(
3951 &self,
3952 session_id: &str,
3953 turn_id: &str,
3954 record: &crate::cost_status::RuntimeUsageDropRecord,
3955 ) -> io::Result<bool> {
3956 self.persist_late_usage_record(
3957 session_id,
3958 LateUsageRecord::captured(
3959 turn_id,
3960 &record.source_id,
3961 &record.route,
3962 None,
3963 None,
3964 record.reason,
3965 ),
3966 )
3967 }
3968
3969 fn with_session_read_lock<T>(
3970 &self,
3971 session_id: &str,
3972 read: impl FnOnce(&Path) -> io::Result<T>,
3973 ) -> io::Result<T> {
3974 let (path, lock_path) = self.late_usage_paths(session_id)?;
3975 let lock_file = match open_private_read_file(&lock_path) {
3976 Ok(file) => file,
3977 Err(error) if error.kind() == io::ErrorKind::NotFound => {
3978 // Atomic replacement makes a copied ledger readable without
3979 // creating a lock. No writer can have published a tombstone
3980 // without first creating the stable lock.
3981 return read(&path);
3982 }
3983 Err(error) => return Err(error),
3984 };
3985 let lock = fd_lock::RwLock::new(lock_file);
3986 let _guard = lock.read()?;
3987 read(&path)
3988 }
3989
3990 fn load_late_usage(&self, session_id: &str) -> io::Result<LateUsageLedger> {
3991 self.with_session_read_lock(session_id, |path| {
3992 if Self::late_usage_is_deleted(path)? {
3993 return Err(io::Error::new(
3994 io::ErrorKind::NotFound,
3995 "session accounting was deleted",
3996 ));
3997 }
3998 Self::load_late_usage_unlocked(path)
3999 })
4000 }
4001
4002 fn apply_late_usage_to_metadata(&self, metadata: &mut SessionMetadata) {
4003 let ledger = self.load_late_usage(&metadata.id);
4004 Self::apply_late_usage_result(metadata, ledger);
4005 }
4006
4007 fn late_usage_unavailable_fingerprint(session_id: &str) -> String {
4008 crate::cost_status::usage_source_fingerprint(&format!(
4009 "late-usage-unavailable:{}",
4010 crate::cost_status::usage_source_fingerprint(session_id)
4011 ))
4012 }
4013
4014 fn late_usage_overflow_fingerprint(session_id: &str) -> String {
4015 crate::cost_status::usage_source_fingerprint(&format!(
4016 "late-usage-overflow:{}",
4017 crate::cost_status::usage_source_fingerprint(session_id)
4018 ))
4019 }
4020
4021 fn compact_usage_source_fingerprints_admitted(&self, metadata: &mut SessionMetadata) {
4022 if metadata.cost.usage_source_fingerprints.len()
4023 <= crate::cost_status::MAX_USAGE_SOURCE_FINGERPRINTS
4024 {
4025 return;
4026 }
4027 let late_path = match self.late_usage_paths(&metadata.id) {
4028 Ok((path, _)) => path,
4029 Err(_) => return,
4030 };
4031 let ledger = match Self::load_late_usage_unlocked(&late_path) {
4032 Ok(ledger) => ledger,
4033 Err(_) => return,
4034 };
4035 let mut pinned = std::collections::HashSet::with_capacity(
4036 ledger.records.len() + metadata.cost.accounted_usage_sources.len() + 2,
4037 );
4038 pinned.insert(Self::late_usage_unavailable_fingerprint(&metadata.id));
4039 pinned.insert(Self::late_usage_overflow_fingerprint(&metadata.id));
4040 for record in &ledger.records {
4041 pinned.insert(record.source_fingerprint.clone());
4042 }
4043 for key in metadata.cost.accounted_usage_sources.keys() {
4044 pinned.insert(key.clone());
4045 }
4046 metadata
4047 .cost
4048 .usage_source_fingerprints
4049 .compact_keeping_pinned(crate::cost_status::MAX_USAGE_SOURCE_FINGERPRINTS, |fp| {
4050 pinned.contains(fp)
4051 });
4052 metadata.cost.pinned_late_usage_fingerprints = pinned;
4053 }
4054
4055 fn apply_late_usage_result(
4056 metadata: &mut SessionMetadata,
4057 ledger: io::Result<LateUsageLedger>,
4058 ) {
4059 let unavailable_fp = Self::late_usage_unavailable_fingerprint(&metadata.id);
4060 let overflow_fp = Self::late_usage_overflow_fingerprint(&metadata.id);
4061 metadata.cost.pinned_late_usage_fingerprints.clear();
4062 metadata
4063 .cost
4064 .pinned_late_usage_fingerprints
4065 .insert(unavailable_fp.clone());
4066 metadata
4067 .cost
4068 .pinned_late_usage_fingerprints
4069 .insert(overflow_fp.clone());
4070 let ledger = match ledger {
4071 Ok(ledger) => ledger,
4072 Err(_) => {
4073 // The transcript is independent of optional accounting data.
4074 // Keep a stable gap receipt even when this projection is later
4075 // saved; loading it again must not invent another missing call.
4076 if metadata
4077 .cost
4078 .usage_source_fingerprints
4079 .insert(unavailable_fp)
4080 {
4081 metadata.cost.unpriced_turns = metadata.cost.unpriced_turns.saturating_add(1);
4082 metadata.cost.cny_unpriced_turns =
4083 metadata.cost.cny_unpriced_turns.saturating_add(1);
4084 }
4085 metadata
4086 .cost
4087 .unpriced_reasons
4088 .insert(LATE_USAGE_UNAVAILABLE_REASON.to_string());
4089 metadata
4090 .cost
4091 .cny_unpriced_reasons
4092 .insert(LATE_USAGE_UNAVAILABLE_REASON.to_string());
4093 return;
4094 }
4095 };
4096 for mut record in ledger.records {
4097 metadata
4098 .cost
4099 .pinned_late_usage_fingerprints
4100 .insert(record.source_fingerprint.clone());
4101 if let Some(receipt) = record
4102 .decision
4103 .as_ref()
4104 .filter(|receipt| receipt.is_bounded())
4105 {
4106 metadata
4107 .cost
4108 .route_receipts
4109 .insert(receipt.diagnostic_receipt());
4110 }
4111 if record.diagnostic_only {
4112 continue;
4113 }
4114 if record.settlement.is_some() {
4115 let mut source = crate::cost_status::RuntimeUsageRecord::legacy(
4116 record.source_fingerprint.clone(),
4117 crate::cost_status::EffectiveRouteUsage {
4118 route: record.route.clone(),
4119 usage: record.usage.clone().unwrap_or_default(),
4120 },
4121 );
4122 source.settlement = record.settlement.clone();
4123 match metadata
4124 .cost
4125 .project_usage_record_by_key(&record.source_fingerprint, &source)
4126 {
4127 Ok((old, new)) => {
4128 metadata.total_tokens = metadata
4129 .total_tokens
4130 .saturating_sub(old)
4131 .saturating_add(new)
4132 }
4133 Err(error) => {
4134 tracing::warn!(%error, "saved usage projection skipped invalid entry");
4135 metadata
4136 .cost
4137 .unpriced_reasons
4138 .insert("usage_correction_unverified".into());
4139 metadata
4140 .cost
4141 .cny_unpriced_reasons
4142 .insert("usage_correction_unverified".into());
4143 }
4144 }
4145 continue;
4146 }
4147 if record.usage.as_ref() == Some(&codewhale_models::Usage::default()) {
4148 record.usage = None;
4149 }
4150 let source_fingerprint = record.source_fingerprint.clone();
4151 let source = if let Some(usage) = record.usage.clone() {
4152 crate::cost_status::NativeUsageSource::capture(
4153 source_fingerprint.clone(),
4154 crate::cost_status::UsageSpendOwner::Auxiliary,
4155 )
4156 .prepare(
4157 &record.route,
4158 &usage,
4159 crate::llm_client::ProviderUsageCoverage::Reported,
4160 record.reason,
4161 )
4162 } else {
4163 crate::cost_status::RuntimeUsageDropRecord {
4164 reason: record.reason,
4165 source_id: source_fingerprint.clone(),
4166 route: record.route.clone(),
4167 }
4168 .as_usage_record()
4169 };
4170 match metadata
4171 .cost
4172 .project_usage_record_by_key(&source_fingerprint, &source)
4173 {
4174 Ok((old, new)) => {
4175 metadata.total_tokens = metadata
4176 .total_tokens
4177 .saturating_sub(old)
4178 .saturating_add(new);
4179 }
4180 Err(error) => {
4181 tracing::warn!(%error, "saved late usage projection skipped invalid entry");
4182 }
4183 }
4184 }
4185 if ledger.overflowed && metadata.cost.usage_source_fingerprints.insert(overflow_fp) {
4186 metadata.cost.unpriced_turns = metadata.cost.unpriced_turns.saturating_add(1);
4187 metadata.cost.cny_unpriced_turns = metadata.cost.cny_unpriced_turns.saturating_add(1);
4188 metadata
4189 .cost
4190 .unpriced_reasons
4191 .insert("late_usage_ledger_overflow".to_string());
4192 metadata
4193 .cost
4194 .cny_unpriced_reasons
4195 .insert("late_usage_ledger_overflow".to_string());
4196 }
4197 }
4198
4199 /// Persist the bounded goal control state for one saved session.
4200 /// `None` is the canonical clear operation and is idempotent.
4201 pub fn save_session_goal(
4202 &self,
4203 session_id: &str,
4204 goal: Option<&SessionGoalState>,
4205 ) -> std::io::Result<()> {
4206 let path = self.validated_session_goal_path(session_id)?;
4207 let Some(goal) = goal else {
4208 if self.checked_existing_session_goals_dir()?.is_some() && path.exists() {
4209 fs::remove_file(&path)?;
4210 if let Some(parent) = path.parent() {
4211 sync_directory(parent);
4212 }
4213 }
4214 return Ok(());
4215 };
4216 goal.validate()?;
4217 self.ensure_session_goals_dir()?;
4218 Self::checked_existing_session_goal_file(&path)?;
4219 let content = serde_json::to_string_pretty(goal)
4220 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
4221 write_atomic(&path, content.as_bytes())
4222 }
4223
4224 /// Load a saved session's durable goal, rejecting malformed or future
4225 /// records instead of silently starting a different objective.
4226 pub fn load_session_goal(&self, session_id: &str) -> std::io::Result<Option<SessionGoalState>> {
4227 let path = self.validated_session_goal_path(session_id)?;
4228 if self.checked_existing_session_goals_dir()?.is_none()
4229 || !Self::checked_existing_session_goal_file(&path)?
4230 {
4231 return Ok(None);
4232 }
4233 let file_len = fs::metadata(&path)?.len();
4234 if file_len > MAX_SESSION_GOAL_FILE_BYTES {
4235 return Err(io::Error::new(
4236 io::ErrorKind::InvalidData,
4237 format!(
4238 "Session goal {} is {file_len} bytes; maximum is {MAX_SESSION_GOAL_FILE_BYTES}",
4239 path.display()
4240 ),
4241 ));
4242 }
4243 let raw = fs::read_to_string(path)?;
4244 let goal: SessionGoalState = serde_json::from_str(&raw)
4245 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
4246 goal.validate()?;
4247 Ok(Some(goal))
4248 }
4249
4250 fn hydrate_recovered_runtime_binding(&self, session: &mut SavedSession) -> io::Result<()> {
4251 let persisted = self.load_session_write_metadata(&session.metadata.id)?;
4252 Self::prepare_session_write(session, &persisted, false)
4253 }
4254
4255 fn resolve_runtime_binding(
4256 session: &mut SavedSession,
4257 persisted: Option<&SessionMetadata>,
4258 ) -> io::Result<()> {
4259 let Some(binding) = persisted.and_then(|metadata| metadata.runtime_store.as_ref()) else {
4260 return Ok(());
4261 };
4262 let Some(incoming) = session.metadata.runtime_store.as_ref() else {
4263 session.metadata.runtime_store = Some(binding.clone());
4264 return Ok(());
4265 };
4266 if incoming == binding {
4267 return Ok(());
4268 }
4269 let incoming_abandonable = incoming.is_missing_session_store().unwrap_or(false)
4270 || incoming.is_adoptable_empty_store().unwrap_or(false);
4271 if incoming_abandonable && binding.validate_existing_store().is_ok() {
4272 session.metadata.runtime_store = Some(binding.clone());
4273 return Ok(());
4274 }
4275 let persisted_abandonable = binding.is_missing_session_store().unwrap_or(false)
4276 || binding.is_adoptable_empty_store().unwrap_or(false);
4277 if !persisted_abandonable {
4278 return Err(io::Error::new(
4279 io::ErrorKind::PermissionDenied,
4280 "Session Runtime ownership changed; reopen the session before saving",
4281 ));
4282 }
4283 Ok(())
4284 }
4285
4286 fn load_session_write_metadata(&self, id: &str) -> io::Result<SessionWriteMetadata> {
4287 let saved = match self.load_session_metadata_by_id_raw(id) {
4288 Ok(metadata) => Some(metadata),
4289 Err(error) if error.kind() == io::ErrorKind::NotFound => None,
4290 Err(error) => return Err(error),
4291 };
4292 let checkpoint = match Self::load_checkpoint_metadata(&self.validated_checkpoint_path(id)?)
4293 {
4294 Ok(metadata) => Some(self.validate_metadata_id(id, metadata)?),
4295 Err(error) if error.kind() == io::ErrorKind::NotFound => None,
4296 Err(error) => return Err(error),
4297 };
4298 Ok(SessionWriteMetadata { saved, checkpoint })
4299 }
4300
4301 fn prepare_session_write(
4302 session: &mut SavedSession,
4303 persisted: &SessionWriteMetadata,
4304 preserve_lifecycle: bool,
4305 ) -> io::Result<()> {
4306 if !session.metadata.cost.accounted_usage_sources.is_empty() {
4307 session.schema_version = session.schema_version.max(CURRENT_SESSION_SCHEMA_VERSION);
4308 }
4309 for metadata in persisted.saved.iter().chain(persisted.checkpoint.iter()) {
4310 Self::resolve_runtime_binding(session, Some(metadata))?;
4311 }
4312 if preserve_lifecycle
4313 && let Some(metadata) = persisted.saved.as_ref().or(persisted.checkpoint.as_ref())
4314 {
4315 Self::preserve_lifecycle(&mut session.metadata, metadata);
4316 }
4317 Ok(())
4318 }
4319
4320 fn preserve_lifecycle(metadata: &mut SessionMetadata, persisted: &SessionMetadata) {
4321 if persisted.title_is_custom
4322 || persisted.title != DEFAULT_SESSION_TITLE
4323 || persisted.message_count != 0
4324 {
4325 metadata.title.clone_from(&persisted.title);
4326 }
4327 metadata.title_is_custom = persisted.title_is_custom;
4328 metadata.archived = persisted.archived;
4329 metadata.created_at = persisted.created_at;
4330 if metadata.exec_route_binding.is_none()
4331 && let Some(binding) = persisted.exec_route_binding.as_ref()
4332 {
4333 metadata.exec_route_binding = Some(
4334 if metadata.model_provider == persisted.model_provider
4335 && metadata.model_provider_id == persisted.model_provider_id
4336 {
4337 binding.clone()
4338 } else {
4339 crate::route_receipt::ExecRouteBinding::default()
4340 },
4341 );
4342 }
4343 metadata
4344 .parent_session_id
4345 .clone_from(&persisted.parent_session_id);
4346 metadata.forked_from_message_count = persisted.forked_from_message_count;
4347 }
4348
4349 pub(crate) fn capture_session_write_source(&self, id: &str) -> io::Result<SessionWriteReceipt> {
4350 self.with_session_write_admission(id, || self.observe_session_admitted(id))?
4351 .map(SessionWriteReceipt::observed)
4352 .ok_or_else(Self::retired_session_write_error)
4353 }
4354
4355 pub fn expect_absent_session(&self, id: &str) -> io::Result<SessionWriteReceipt> {
4356 let id = self.validated_session_id(id)?.to_string();
4357 Ok(SessionWriteReceipt::observed(SessionObservation {
4358 sessions_dir: self.sessions_dir.clone(),
4359 session_id: id,
4360 document_sha256: None,
4361 checkpoint_sha256: None,
4362 }))
4363 }
4364
4365 fn hash_session_record(path: &Path) -> io::Result<Option<String>> {
4366 use sha2::{Digest, Sha256};
4367 use std::io::Read;
4368 let mut file = match open_private_read_file(path) {
4369 Ok(file) => file,
4370 Err(error) if error.kind() == io::ErrorKind::NotFound => {
4371 if path
4372 .parent()
4373 .is_some_and(|parent| parent.exists() && !parent.is_dir())
4374 {
4375 return Err(io::Error::new(
4376 io::ErrorKind::NotADirectory,
4377 format!(
4378 "private sidecar parent {} is not a directory",
4379 path.parent().unwrap_or(path).display()
4380 ),
4381 ));
4382 }
4383 return Ok(None);
4384 }
4385 Err(error) => return Err(error),
4386 };
4387 let mut digest = Sha256::new();
4388 let mut buffer = [0_u8; 64 * 1024];
4389 loop {
4390 let count = file.read(&mut buffer)?;
4391 if count == 0 {
4392 break;
4393 }
4394 digest.update(&buffer[..count]);
4395 }
4396 Ok(Some(codewhale_runtime::hashing::hex_bytes(
4397 digest.finalize(),
4398 )))
4399 }
4400
4401 fn observe_session_admitted(&self, id: &str) -> io::Result<SessionObservation> {
4402 self.load_session_write_metadata(id)?;
4403 Ok(SessionObservation {
4404 sessions_dir: self.sessions_dir.clone(),
4405 session_id: self.validated_session_id(id)?.to_string(),
4406 document_sha256: Self::hash_session_record(&self.validated_session_path(id)?)?,
4407 checkpoint_sha256: Self::hash_session_record(&self.validated_checkpoint_path(id)?)?,
4408 })
4409 }
4410
4411 fn validate_unadmitted_read(
4412 &self,
4413 id: &str,
4414 path: &Path,
4415 expected_sha256: &str,
4416 admission_held: bool,
4417 ) -> io::Result<bool> {
4418 let verify = || {
4419 if Self::hash_session_record(path)?.as_deref() != Some(expected_sha256) {
4420 return Err(io::Error::new(
4421 io::ErrorKind::ResourceBusy,
4422 "session record changed during recovery read; reopen it",
4423 ));
4424 }
4425 Ok(true)
4426 };
4427 if admission_held {
4428 return verify();
4429 }
4430 let mut entered = false;
4431 let observed = self.with_session_read_lock(id, |late_path| {
4432 entered = true;
4433 if Self::late_usage_is_deleted(late_path).unwrap_or(false) {
4434 return Ok(false);
4435 }
4436 verify()
4437 });
4438 match observed {
4439 Err(_) if !entered => {
4440 if self
4441 .late_usage_paths(id)
4442 .ok()
4443 .and_then(|(late_path, _)| Self::late_usage_is_deleted(&late_path).ok())
4444 == Some(true)
4445 {
4446 return Ok(false);
4447 }
4448 verify()
4449 }
4450 result => result,
4451 }
4452 }
4453
4454 fn validate_publication_admitted(
4455 &self,
4456 session: &SavedSession,
4457 receipt: &SessionWriteReceipt,
4458 ) -> io::Result<SessionPublicationBase> {
4459 let expected = receipt.expected()?;
4460 if expected.observation.sessions_dir != self.sessions_dir
4461 || expected.observation.session_id != session.metadata.id
4462 || expected.observation != self.observe_session_admitted(&session.metadata.id)?
4463 {
4464 return Err(io::Error::new(
4465 io::ErrorKind::ResourceBusy,
4466 "session document or checkpoint changed after its captured source; source retained",
4467 ));
4468 }
4469 Ok(expected)
4470 }
4471
4472 fn validate_checkpoint_authority(base: &SessionPublicationBase) -> io::Result<()> {
4473 if let Some(hash) = base.observation.checkpoint_sha256.as_ref()
4474 && base
4475 .checkpoint
4476 .as_ref()
4477 .is_none_or(|checkpoint| &checkpoint.sha256 != hash)
4478 {
4479 return Err(io::Error::new(
4480 io::ErrorKind::ResourceBusy,
4481 "checkpoint has no native owning publication receipt; recover it explicitly before automatic publication",
4482 ));
4483 }
4484 Ok(())
4485 }
4486
4487 fn publication_receipt(
4488 session: &SavedSession,
4489 ) -> io::Result<crate::core::events::SessionCheckpointReceipt> {
4490 Ok(crate::core::events::SessionCheckpointReceipt {
4491 persisted_sha256: crate::core::events::SessionCheckpointRequest::prefix_hash(
4492 &session.messages,
4493 )
4494 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?,
4495 messages_len: session.messages.len(),
4496 projection: crate::core::events::SessionCheckpointProjection::Exact,
4497 })
4498 }
4499
4500 pub fn publish_session(&self, session: &SavedSession) -> io::Result<SessionPublication> {
4501 self.publish_session_inner(session.clone(), JournalPrune::Keep, false)
4502 }
4503
4504 pub fn publish_session_preserving_lifecycle(
4505 &self,
4506 session: &SavedSession,
4507 ) -> io::Result<SessionPublication> {
4508 self.publish_session_inner(session.clone(), JournalPrune::Keep, true)
4509 }
4510
4511 pub fn publish_session_bounded(&self, session: SavedSession) -> io::Result<SessionPublication> {
4512 self.publish_session_inner(session, JournalPrune::Excess, true)
4513 }
4514
4515 fn publish_session_inner(
4516 &self,
4517 mut session: SavedSession,
4518 prune: JournalPrune,
4519 preserve_lifecycle: bool,
4520 ) -> io::Result<SessionPublication> {
4521 let receipt = session
4522 .write_receipt
4523 .clone()
4524 .filter(|receipt| receipt.owner().is_some())
4525 .ok_or_else(|| {
4526 io::Error::new(
4527 io::ErrorKind::InvalidInput,
4528 "session publication lacks a captured native producer",
4529 )
4530 })?;
4531 let id = session.metadata.id.clone();
4532 let exec_mode = session.metadata.mode.as_deref() == Some("exec");
4533 let result = self
4534 .with_session_write_admission(&id, || {
4535 let base = self.validate_publication_admitted(&session, &receipt)?;
4536 let persisted = self.load_session_write_metadata(&id)?;
4537 session.make_storage_compatible();
4538 let checkpoint_receipt = Self::publication_receipt(&session)?;
4539 let metadata =
4540 self.write_session_admitted(session, prune, preserve_lifecycle, &persisted)?;
4541 Ok(SessionPublication {
4542 path: self.validated_session_path(&id)?,
4543 metadata,
4544 observation: self.observe_session_admitted(&id)?,
4545 checkpoint_receipt,
4546 checkpoint: base.checkpoint,
4547 })
4548 })
4549 .and_then(|result| result.ok_or_else(Self::retired_session_write_error));
4550 receipt.finish(&result);
4551 if result.is_ok()
4552 && let Err(error) = self.cleanup_old_sessions_for_mode(None, Some(exec_mode))
4553 {
4554 tracing::warn!(session_id = %id, %error, "session published but retention could not be inspected");
4555 }
4556 result
4557 }
4558
4559 pub fn publish_checkpoint_owned(
4560 &self,
4561 mut session: SavedSession,
4562 ) -> io::Result<SessionPublication> {
4563 let receipt = session
4564 .write_receipt
4565 .clone()
4566 .filter(|receipt| receipt.owner().is_some())
4567 .ok_or_else(|| {
4568 io::Error::new(
4569 io::ErrorKind::InvalidInput,
4570 "checkpoint lacks a captured native producer",
4571 )
4572 })?;
4573 let id = session.metadata.id.clone();
4574 let result = self
4575 .with_session_write_admission(&id, || {
4576 let base = self.validate_publication_admitted(&session, &receipt)?;
4577 Self::validate_checkpoint_authority(&base)?;
4578 let persisted = self.load_session_write_metadata(&id)?;
4579 Self::prepare_session_write(&mut session, &persisted, true)?;
4580 let session_path = self.validated_session_path(&id)?;
4581 self.archive_before_first_graph_write(&session, &session_path)?;
4582 fs::create_dir_all(self.checkpoints_dir())?;
4583 let path = self.validated_checkpoint_path(&id)?;
4584 let already_persisted = path.exists() || session_path.exists();
4585 self.hydrate_approval_receipts(&mut session)?;
4586 session.make_storage_compatible();
4587 self.compact_usage_source_fingerprints_admitted(&mut session.metadata);
4588 session.metadata.publication_id = receipt.publication_id();
4589 let checkpoint_receipt = Self::publication_receipt(&session)?;
4590 let metadata = session.metadata.clone();
4591 let content = serialize_saved_session(session)?;
4592 write_atomic(&path, content.as_bytes())?;
4593 self.stamp_session_boot_owner_for_new_record(&id, already_persisted);
4594 let observation = self.observe_session_admitted(&id)?;
4595 let checkpoint =
4596 observation
4597 .checkpoint_sha256
4598 .clone()
4599 .map(|sha256| NativeCheckpointAuthority {
4600 sha256,
4601 owner: receipt
4602 .owner()
4603 .expect("validated native checkpoint producer"),
4604 });
4605 Ok(SessionPublication {
4606 path,
4607 metadata,
4608 observation,
4609 checkpoint_receipt,
4610 checkpoint,
4611 })
4612 })
4613 .and_then(|result| result.ok_or_else(Self::retired_session_write_error));
4614 receipt.finish(&result);
4615 result
4616 }
4617
4618 pub fn publish_completed_session(
4619 &self,
4620 mut session: SavedSession,
4621 ) -> io::Result<(SessionPublication, io::Result<()>)> {
4622 let receipt = session
4623 .write_receipt
4624 .clone()
4625 .filter(|receipt| {
4626 matches!(
4627 receipt.owner(),
4628 Some(SessionWriteOwner::Engine(_) | SessionWriteOwner::Control(_))
4629 )
4630 })
4631 .ok_or_else(|| {
4632 io::Error::new(
4633 io::ErrorKind::InvalidInput,
4634 "completion lacks a captured terminal or control owner",
4635 )
4636 })?;
4637 let id = session.metadata.id.clone();
4638 let exec_mode = session.metadata.mode.as_deref() == Some("exec");
4639 let result = self
4640 .with_session_write_admission(&id, || {
4641 let base = self.validate_publication_admitted(&session, &receipt)?;
4642 Self::validate_checkpoint_authority(&base)?;
4643 if let Some(checkpoint) = base.checkpoint.as_ref() {
4644 let owner = receipt
4645 .owner()
4646 .expect("validated native completion producer");
4647 if !matches!(owner, SessionWriteOwner::Control(_))
4648 && !owner.same_execution(&checkpoint.owner)
4649 && receipt
4650 .checkpoint_predecessor()
4651 .as_ref()
4652 .is_none_or(|predecessor| !owner.same_execution(predecessor))
4653 {
4654 return Err(io::Error::new(
4655 io::ErrorKind::ResourceBusy,
4656 "completion does not own its captured checkpoint predecessor",
4657 ));
4658 }
4659 }
4660 let persisted = self.load_session_write_metadata(&id)?;
4661 session.make_storage_compatible();
4662 let checkpoint_receipt = Self::publication_receipt(&session)?;
4663 let metadata =
4664 self.write_session_admitted(session, JournalPrune::Excess, true, &persisted)?;
4665 let mut observation = self.observe_session_admitted(&id)?;
4666 let clear = self.clear_session_checkpoint_admitted(&id);
4667 if clear.is_ok() {
4668 observation.checkpoint_sha256 = None;
4669 }
4670 Ok((
4671 SessionPublication {
4672 path: self.validated_session_path(&id)?,
4673 metadata,
4674 observation,
4675 checkpoint_receipt,
4676 checkpoint: if clear.is_ok() { None } else { base.checkpoint },
4677 },
4678 clear,
4679 ))
4680 })
4681 .and_then(|result| result.ok_or_else(Self::retired_session_write_error));
4682 receipt.finish(
4683 &result
4684 .as_ref()
4685 .map(|(publication, _)| publication.clone())
4686 .map_err(|error| io::Error::new(error.kind(), error.to_string())),
4687 );
4688 if result.is_ok()
4689 && let Err(error) = self.cleanup_old_sessions_for_mode(None, Some(exec_mode))
4690 {
4691 tracing::warn!(session_id = %id, %error, "completion published but retention could not be inspected");
4692 }
4693 result
4694 }
4695
4696 #[cfg(any(test, feature = "test-support"))]
4697 pub fn save_session(&self, session: &SavedSession) -> std::io::Result<PathBuf> {
4698 self.save_session_owned(session.clone())
4699 }
4700
4701 /// Save a session to disk, consuming it.
4702 #[cfg(any(test, feature = "test-support"))]
4703 pub fn save_session_owned(&self, session: SavedSession) -> std::io::Result<PathBuf> {
4704 self.save_session_inner(session, JournalPrune::Keep, false)
4705 }
4706
4707 #[cfg(any(test, feature = "test-support"))]
4708 pub fn save_session_bounded(&self, session: SavedSession) -> std::io::Result<PathBuf> {
4709 self.save_session_inner(session, JournalPrune::Excess, true)
4710 }
4711
4712 /// Make a saved document whose file exceeds the full-history transport
4713 /// bound readable under it. The bound counts what a canonical handoff
4714 /// carries: compact JSON without the journal-derived `messages` copy
4715 /// ([`SavedSession::transport_form`]). Every off-branch journal entry is
4716 /// projected into the journal archive sidecar (the same durable step the
4717 /// autosave prune uses) and, only when the whole projected document is
4718 /// still over `limit`, ended non-durable unpinned Work Graph operations
4719 /// beyond the newest `ENDED_OPERATION_CAP` are dropped too. Then, in
4720 /// order: when the whole projected document fits, it is written; when the
4721 /// carried form already fits as loaded, nothing is written; when the
4722 /// projected carried form fits, the projection is written; otherwise
4723 /// nothing is archived or rewritten and the projected carried size is
4724 /// returned with whether that projection pruned ended operations. The
4725 /// active branch and durable or pinned operations are never touched.
4726 /// Known limits: a file left over `limit` is parsed whole on every bounded
4727 /// read, and readers that bound the whole document (Runtime API history,
4728 /// native fork, import merge) can see that write and still refuse.
4729 fn compact_oversized_session(&self, id: &str, limit: u64) -> io::Result<Option<(u64, bool)>> {
4730 let size = |session: &SavedSession| -> io::Result<u64> {
4731 serde_json::to_vec(session)
4732 .map(|bytes| bytes.len() as u64)
4733 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
4734 };
4735 let project = |session: &SavedSession| -> io::Result<(u64, u64)> {
4736 let mut projected = session.clone();
4737 if let Some(journal) = projected.journal.as_mut() {
4738 let off_branch: std::collections::HashSet<String> =
4739 journal.prune_plan(0, 0).into_iter().collect();
4740 journal
4741 .remove_entries(&off_branch)
4742 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
4743 projected.leaf_id = journal.leaf_id.clone();
4744 }
4745 self.hydrate_recovered_runtime_binding(&mut projected)?;
4746 self.hydrate_approval_receipts(&mut projected)?;
4747 if let Some(journal) = projected.journal.as_ref() {
4748 validate_saved_journal(journal)?;
4749 }
4750 projected.make_storage_compatible();
4751 Ok((size(&projected)?, size(&projected.transport_form())?))
4752 };
4753 let mut session = self.load_session_snapshot_with_limit(id, None, false)?;
4754 session.capture_publication(SessionWriteOwner::control())?;
4755 let loaded = size(&session.transport_form())?;
4756 let (mut whole, mut carried) = project(&session)?;
4757 let mut pruned_operations = false;
4758 let session_id = session.metadata.id.clone();
4759 if whole > limit
4760 && let Some(graph) = session
4761 .work_state
4762 .as_mut()
4763 .and_then(|state| state.graph.as_mut())
4764 && crate::work_graph::evictable_operations(graph).len()
4765 > crate::work_graph::ENDED_OPERATION_CAP
4766 {
4767 match crate::work_graph::apply(
4768 graph,
4769 crate::work_graph::WorkGraphChange::PruneEndedOperations {
4770 keep: crate::work_graph::ENDED_OPERATION_CAP,
4771 },
4772 crate::work_graph::ChangeCtx {
4773 session_id: session_id.clone(),
4774 now: Utc::now().timestamp_millis(),
4775 idempotency_key: None,
4776 },
4777 ) {
4778 Ok((next, _)) => {
4779 *graph = next;
4780 pruned_operations = true;
4781 (whole, carried) = project(&session)?;
4782 }
4783 Err(report) => tracing::warn!(
4784 %session_id,
4785 %report,
4786 "ended-operation prune refused; keeping the full Work Graph"
4787 ),
4788 }
4789 }
4790 if whole > limit && loaded <= limit {
4791 return Ok(None);
4792 }
4793 if whole > limit && carried > limit {
4794 return Ok(Some((carried, pruned_operations)));
4795 }
4796 self.publish_session_inner(session, JournalPrune::AllOffBranch, true)?;
4797 Ok(None)
4798 }
4799
4800 pub fn trim_session_for_transport(
4801 &self,
4802 id_or_prefix: &str,
4803 target_bytes: u64,
4804 apply: bool,
4805 ) -> io::Result<SessionTrimReport> {
4806 let max_bytes = codewhale_protocol::MAX_CANONICAL_HISTORY_BYTES as u64;
4807 if !(MIN_SESSION_TRIM_TARGET_BYTES..=max_bytes).contains(&target_bytes) {
4808 return Err(io::Error::new(
4809 io::ErrorKind::InvalidInput,
4810 format!(
4811 "trim target must be between {:.1} MiB and {:.1} MiB",
4812 MIN_SESSION_TRIM_TARGET_BYTES as f64 / 1_048_576.0,
4813 max_bytes as f64 / 1_048_576.0,
4814 ),
4815 ));
4816 }
4817 let session_id = self.resolve_trim_session_id(id_or_prefix)?;
4818 let path = self.validated_session_path(&session_id)?;
4819
4820 if !apply {
4821 let file_bytes = open_private_read_file(&path)?.metadata()?.len();
4822 let session = self.load_session_snapshot_with_limit(&session_id, None, false)?;
4823 let plan = self.plan_session_trim(&session, file_bytes, target_bytes)?;
4824 let session_is_live = self.is_session_live_anywhere(&session_id);
4825 return Ok(SessionTrimReport {
4826 session_id,
4827 applied: false,
4828 target_bytes,
4829 before_file_bytes: file_bytes,
4830 before_carried_bytes: plan.before_carried_bytes,
4831 after_file_bytes: plan.after_file_bytes,
4832 after_carried_bytes: plan.after_carried_bytes,
4833 before_journal_entries: plan.before_journal_entries,
4834 after_journal_entries: plan.after_journal_entries,
4835 before_active_entries: plan.before_active_entries,
4836 after_active_entries: plan.after_active_entries,
4837 archived_off_branch_entries: plan.archived_off_branch_entries,
4838 archived_active_entries: plan.archived_active_entries,
4839 pruned_ended_operations: plan.pruned_ended_operations,
4840 archive_path: None,
4841 session_is_live,
4842 });
4843 }
4844
4845 let _lease = self.reserve_session_for_external_write(&session_id)?;
4846 self.promote_interrupted_checkpoint(&session_id, None)?;
4847 let report = self
4848 .with_session_write_admission(&session_id, || {
4849 let file_bytes = open_private_read_file(&path)?.metadata()?.len();
4850 let session = self.load_session_snapshot_with_limit(&session_id, None, true)?;
4851 let plan = self.plan_session_trim(&session, file_bytes, target_bytes)?;
4852 if plan.entries_to_archive.is_empty() && !plan.pruned_ended_operations {
4853 return Ok(SessionTrimReport {
4854 session_id: session_id.clone(),
4855 applied: false,
4856 target_bytes,
4857 before_file_bytes: file_bytes,
4858 before_carried_bytes: plan.before_carried_bytes,
4859 after_file_bytes: file_bytes,
4860 after_carried_bytes: plan.before_carried_bytes,
4861 before_journal_entries: plan.before_journal_entries,
4862 after_journal_entries: plan.before_journal_entries,
4863 before_active_entries: plan.before_active_entries,
4864 after_active_entries: plan.before_active_entries,
4865 archived_off_branch_entries: 0,
4866 archived_active_entries: 0,
4867 pruned_ended_operations: false,
4868 archive_path: None,
4869 session_is_live: false,
4870 });
4871 }
4872 let archive_path = if !plan.entries_to_archive.is_empty() {
4873 let already = self.load_journal_archive_ids(&session_id)?;
4874 let fresh: Vec<&SessionEntry> = plan
4875 .entries_to_archive
4876 .iter()
4877 .filter(|entry| !already.contains(&entry.id))
4878 .collect();
4879 self.append_journal_archive(&session_id, &fresh)?;
4880 let hot_path = journal_archive_path(&self.sessions_dir, &session_id)?;
4881 let reported_path = if hot_path.exists() {
4882 hot_path
4883 } else {
4884 list_journal_archive_segments(&self.sessions_dir, &session_id)?
4885 .into_iter()
4886 .last()
4887 .map_or(hot_path, |(_, segment)| segment)
4888 };
4889 Some(reported_path)
4890 } else {
4891 None
4892 };
4893 let persisted = self.load_session_write_metadata(&session_id)?;
4894 self.write_session_admitted(plan.candidate, JournalPrune::Keep, true, &persisted)?;
4895 let after_file_bytes = open_private_read_file(&path)?.metadata()?.len();
4896 Ok(SessionTrimReport {
4897 session_id: session_id.clone(),
4898 applied: true,
4899 target_bytes,
4900 before_file_bytes: file_bytes,
4901 before_carried_bytes: plan.before_carried_bytes,
4902 after_file_bytes,
4903 after_carried_bytes: plan.after_carried_bytes,
4904 before_journal_entries: plan.before_journal_entries,
4905 after_journal_entries: plan.after_journal_entries,
4906 before_active_entries: plan.before_active_entries,
4907 after_active_entries: plan.after_active_entries,
4908 archived_off_branch_entries: plan.archived_off_branch_entries,
4909 archived_active_entries: plan.archived_active_entries,
4910 pruned_ended_operations: plan.pruned_ended_operations,
4911 archive_path,
4912 session_is_live: false,
4913 })
4914 })?
4915 .ok_or_else(Self::retired_session_write_error)?;
4916 if report.applied {
4917 self.load_session_snapshot_bounded(
4918 &session_id,
4919 codewhale_protocol::MAX_CANONICAL_HISTORY_BYTES,
4920 )?;
4921 }
4922 Ok(report)
4923 }
4924
4925 fn resolve_trim_session_id(&self, id_or_prefix: &str) -> io::Result<String> {
4926 let trimmed = id_or_prefix.trim();
4927 if trimmed.is_empty() {
4928 return Err(io::Error::new(
4929 io::ErrorKind::InvalidInput,
4930 "session id must not be empty",
4931 ));
4932 }
4933 if let Ok(path) = self.validated_session_path(trimmed) {
4934 match open_private_read_file(&path) {
4935 Ok(_) => return Ok(trimmed.to_string()),
4936 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
4937 Err(error) => return Err(error),
4938 }
4939 }
4940 self.resolve_session_id_prefix(trimmed)
4941 }
4942
4943 fn plan_session_trim(
4944 &self,
4945 session: &SavedSession,
4946 file_bytes: u64,
4947 target_bytes: u64,
4948 ) -> io::Result<SessionTrimPlan> {
4949 let size = |doc: &SavedSession| -> io::Result<u64> {
4950 serde_json::to_vec(doc)
4951 .map(|bytes| bytes.len() as u64)
4952 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
4953 };
4954 let session_id = session.metadata.id.clone();
4955 let before_carried_bytes = size(&session.transport_form())?;
4956 let mut candidate = session.clone();
4957 candidate.ensure_journal();
4958 candidate.make_storage_compatible();
4959 self.hydrate_recovered_runtime_binding(&mut candidate)?;
4960 self.hydrate_approval_receipts(&mut candidate)?;
4961 candidate.metadata.publication_id = Some(Uuid::new_v4().to_string());
4962
4963 let before_journal_entries = candidate.journal.as_ref().map_or(0, SessionJournal::len);
4964 let before_active_entries = candidate
4965 .journal
4966 .as_ref()
4967 .map_or(0, |journal| journal.root_to_leaf().len());
4968
4969 if before_carried_bytes <= target_bytes {
4970 return Ok(SessionTrimPlan {
4971 candidate,
4972 entries_to_archive: Vec::new(),
4973 before_carried_bytes,
4974 after_file_bytes: file_bytes,
4975 after_carried_bytes: before_carried_bytes,
4976 before_journal_entries,
4977 after_journal_entries: before_journal_entries,
4978 before_active_entries,
4979 after_active_entries: before_active_entries,
4980 archived_off_branch_entries: 0,
4981 archived_active_entries: 0,
4982 pruned_ended_operations: false,
4983 });
4984 }
4985
4986 let mut entries_to_archive = Vec::new();
4987 let mut archived_off_branch_entries = 0usize;
4988 if let Some(journal) = candidate.journal.as_mut() {
4989 let off_branch_ids: std::collections::HashSet<String> =
4990 journal.prune_plan(0, 0).into_iter().collect();
4991 if !off_branch_ids.is_empty() {
4992 for entry in &journal.entries {
4993 if off_branch_ids.contains(&entry.id) {
4994 entries_to_archive.push(entry.clone());
4995 }
4996 }
4997 archived_off_branch_entries = journal
4998 .remove_entries(&off_branch_ids)
4999 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
5000 candidate.leaf_id = journal.leaf_id.clone();
5001 }
5002 }
5003
5004 let mut pruned_ended_operations = false;
5005 let mut carried = size(&candidate.transport_form())?;
5006 if carried > target_bytes
5007 && let Some(graph) = candidate
5008 .work_state
5009 .as_mut()
5010 .and_then(|state| state.graph.as_mut())
5011 && crate::work_graph::evictable_operations(graph).len()
5012 > crate::work_graph::ENDED_OPERATION_CAP
5013 {
5014 match crate::work_graph::apply(
5015 graph,
5016 crate::work_graph::WorkGraphChange::PruneEndedOperations {
5017 keep: crate::work_graph::ENDED_OPERATION_CAP,
5018 },
5019 crate::work_graph::ChangeCtx {
5020 session_id: session_id.clone(),
5021 now: Utc::now().timestamp_millis(),
5022 idempotency_key: None,
5023 },
5024 ) {
5025 Ok((next, _)) => {
5026 *graph = next;
5027 pruned_ended_operations = true;
5028 carried = size(&candidate.transport_form())?;
5029 }
5030 Err(report) => tracing::warn!(
5031 %session_id,
5032 %report,
5033 "ended-operation prune refused during trim; keeping the full Work Graph"
5034 ),
5035 }
5036 }
5037
5038 let mut archived_active_entries = 0usize;
5039 if carried > target_bytes {
5040 let active_ids: Vec<String> = candidate
5041 .journal
5042 .as_ref()
5043 .map(|journal| {
5044 journal
5045 .root_to_leaf()
5046 .into_iter()
5047 .map(|entry| entry.id.clone())
5048 .collect()
5049 })
5050 .unwrap_or_default();
5051 let active_len = active_ids.len();
5052 if active_len <= 1 {
5053 let mib = |bytes: u64| bytes as f64 / 1_048_576.0;
5054 return Err(io::Error::new(
5055 io::ErrorKind::InvalidData,
5056 format!(
5057 "cannot trim session {session_id} to {:.1} MiB: the session has {active_len} active entries and still carries {:.1} MiB. Run `codewhale sessions export {session_id}` to preserve a full archive",
5058 mib(target_bytes),
5059 mib(carried),
5060 ),
5061 ));
5062 }
5063 let (min_tail, _) =
5064 Self::apply_active_trim_cut(&candidate, &active_ids, active_len - 1)?;
5065 let min_tail_carried = size(&min_tail.transport_form())?;
5066 if min_tail_carried > target_bytes {
5067 let mib = |bytes: u64| bytes as f64 / 1_048_576.0;
5068 return Err(io::Error::new(
5069 io::ErrorKind::InvalidData,
5070 format!(
5071 "cannot trim session {session_id} to {:.1} MiB: even keeping only the final entry still carries {:.1} MiB (metadata and work state cannot be dropped). Run `codewhale sessions export {session_id}` to preserve a full archive",
5072 mib(target_bytes),
5073 mib(min_tail_carried),
5074 ),
5075 ));
5076 }
5077
5078 let mut lo = 1usize;
5079 let mut hi = active_len - 1;
5080 while lo < hi {
5081 let mid = lo + (hi - lo) / 2;
5082 let (probe, _) = Self::apply_active_trim_cut(&candidate, &active_ids, mid)?;
5083 if size(&probe.transport_form())? <= target_bytes {
5084 hi = mid;
5085 } else {
5086 lo = mid + 1;
5087 }
5088 }
5089 let min_k = lo;
5090 let remaining = active_len - min_k;
5091 let max_turn_align = (min_k + remaining / 2).min(active_len - 1);
5092 let cut_k = {
5093 let journal = candidate.journal.as_ref().expect("journal ensured");
5094 let by_id = journal.index();
5095 (min_k..=max_turn_align)
5096 .find(|&idx| {
5097 by_id
5098 .get(active_ids[idx].as_str())
5099 .is_some_and(|entry| Self::is_turn_start_entry(entry))
5100 })
5101 .or_else(|| {
5102 (min_k..active_len).find(|&idx| {
5103 by_id
5104 .get(active_ids[idx].as_str())
5105 .is_some_and(|entry| !Self::is_tool_result_entry(entry))
5106 })
5107 })
5108 .unwrap_or(min_k)
5109 };
5110
5111 let (trimmed, archived_active) =
5112 Self::apply_active_trim_cut(&candidate, &active_ids, cut_k)?;
5113 archived_active_entries = archived_active.len();
5114 entries_to_archive.extend(archived_active);
5115 candidate = trimmed;
5116 carried = size(&candidate.transport_form())?;
5117 }
5118
5119 if let Some(journal) = candidate.journal.as_ref() {
5120 validate_saved_journal(journal)?;
5121 }
5122 let after_journal_entries = candidate.journal.as_ref().map_or(0, SessionJournal::len);
5123 let after_active_entries = candidate
5124 .journal
5125 .as_ref()
5126 .map_or(0, |journal| journal.root_to_leaf().len());
5127 let after_file_bytes = size(&candidate)?;
5128
5129 Ok(SessionTrimPlan {
5130 candidate,
5131 entries_to_archive,
5132 before_carried_bytes,
5133 after_file_bytes,
5134 after_carried_bytes: carried,
5135 before_journal_entries,
5136 after_journal_entries,
5137 before_active_entries,
5138 after_active_entries,
5139 archived_off_branch_entries,
5140 archived_active_entries,
5141 pruned_ended_operations,
5142 })
5143 }
5144
5145 fn apply_active_trim_cut(
5146 base: &SavedSession,
5147 active_ids: &[String],
5148 cut_k: usize,
5149 ) -> io::Result<(SavedSession, Vec<SessionEntry>)> {
5150 let mut candidate = base.clone();
5151 let journal = candidate
5152 .journal
5153 .as_mut()
5154 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "session journal missing"))?;
5155 let drop_ids: std::collections::HashSet<&str> =
5156 active_ids[..cut_k].iter().map(String::as_str).collect();
5157 let new_root_id = active_ids[cut_k].as_str();
5158 let mut archived = Vec::with_capacity(cut_k);
5159 let mut kept = Vec::with_capacity(journal.entries.len().saturating_sub(cut_k));
5160 for mut entry in std::mem::take(&mut journal.entries) {
5161 if drop_ids.contains(entry.id.as_str()) {
5162 archived.push(entry);
5163 } else {
5164 if entry.id == new_root_id {
5165 entry.parent_id = None;
5166 }
5167 kept.push(entry);
5168 }
5169 }
5170 journal.entries = kept;
5171 validate_saved_journal(journal)?;
5172 let before_messages = base.messages.len();
5173 candidate.leaf_id = journal.leaf_id.clone();
5174 candidate.messages = journal.to_messages();
5175 let dropped_messages = before_messages.saturating_sub(candidate.messages.len());
5176 candidate.turn_outcomes.retain_mut(|outcome| {
5177 if outcome.after_message_count < dropped_messages {
5178 false
5179 } else {
5180 outcome.after_message_count -= dropped_messages;
5181 true
5182 }
5183 });
5184 candidate.metadata.message_count = candidate.messages.len();
5185 Ok((candidate, archived))
5186 }
5187
5188 fn is_tool_result_entry(entry: &SessionEntry) -> bool {
5189 matches!(
5190 entry.kind.as_ref(),
5191 SessionEntryKind::Message { message }
5192 if message.content.iter().any(|block| {
5193 matches!(
5194 block,
5195 ContentBlock::ToolResult { .. }
5196 | ContentBlock::ToolSearchToolResult { .. }
5197 | ContentBlock::CodeExecutionToolResult { .. }
5198 | ContentBlock::WebSearchToolResult { .. }
5199 | ContentBlock::WebFetchToolResult { .. }
5200 )
5201 })
5202 )
5203 }
5204
5205 fn is_turn_start_entry(entry: &SessionEntry) -> bool {
5206 match entry.kind.as_ref() {
5207 SessionEntryKind::User { .. }
5208 | SessionEntryKind::Compaction { .. }
5209 | SessionEntryKind::BranchSummary { .. }
5210 | SessionEntryKind::System { .. } => true,
5211 SessionEntryKind::Message { message } => {
5212 message.role == codewhale_models::Role::User && !Self::is_tool_result_entry(entry)
5213 }
5214 SessionEntryKind::Assistant { .. } => false,
5215 }
5216 }
5217
5218 #[cfg(any(test, feature = "test-support"))]
5219 fn save_session_inner(
5220 &self,
5221 session: SavedSession,
5222 prune: JournalPrune,
5223 preserve_lifecycle: bool,
5224 ) -> io::Result<PathBuf> {
5225 let session_id = session.metadata.id.clone();
5226 let exec_mode = session.metadata.mode.as_deref() == Some("exec");
5227 let path = self.validated_session_path(&session_id)?;
5228 self.with_session_write_admission(&session_id, || {
5229 let persisted = self.load_session_write_metadata(&session_id)?;
5230 self.write_session_admitted(session, prune, preserve_lifecycle, &persisted)
5231 })?
5232 .ok_or_else(Self::retired_session_write_error)?;
5233 self.cleanup_old_sessions_for_mode(None, Some(exec_mode))?;
5234 Ok(path)
5235 }
5236
5237 fn write_session_admitted(
5238 &self,
5239 mut session: SavedSession,
5240 prune: JournalPrune,
5241 preserve_lifecycle: bool,
5242 persisted: &SessionWriteMetadata,
5243 ) -> io::Result<SessionMetadata> {
5244 let session_id = session.metadata.id.clone();
5245 let path = self.validated_session_path(&session_id)?;
5246 Self::prepare_session_write(&mut session, persisted, preserve_lifecycle)?;
5247 let already_persisted =
5248 path.exists() || self.validated_checkpoint_path(&session_id)?.exists();
5249 self.archive_before_first_graph_write(&session, &path)?;
5250 let archived = match prune {
5251 JournalPrune::Keep => Vec::new(),
5252 JournalPrune::Excess => {
5253 let (threshold, retained) = if fs::symlink_metadata(&path).is_ok_and(|meta| {
5254 meta.len() > codewhale_protocol::MAX_CANONICAL_HISTORY_BYTES as u64
5255 }) {
5256 (0, 0)
5257 } else {
5258 (JOURNAL_PRUNE_DEAD_THRESHOLD, JOURNAL_RETAINED_DEAD_ENTRIES)
5259 };
5260 self.archive_dead_journal_entries(&mut session, threshold, retained)
5261 .unwrap_or_else(|error| {
5262 tracing::warn!(%session_id, %error, "journal archive step failed; keeping the full journal");
5263 Vec::new()
5264 })
5265 }
5266 JournalPrune::AllOffBranch => self.archive_dead_journal_entries(&mut session, 0, 0)?,
5267 };
5268 self.hydrate_approval_receipts(&mut session)?;
5269 self.compact_usage_source_fingerprints_admitted(&mut session.metadata);
5270 session.metadata.publication_id = Some(
5271 session
5272 .write_receipt
5273 .as_ref()
5274 .and_then(SessionWriteReceipt::publication_id)
5275 .unwrap_or_else(|| Uuid::new_v4().to_string()),
5276 );
5277 let metadata = session.metadata.clone();
5278 let content = serialize_saved_session(session)?;
5279 write_atomic(&path, content.as_bytes())?;
5280 self.stamp_session_boot_owner_for_new_record(&session_id, already_persisted);
5281 if !archived.is_empty() {
5282 archived_journal_ids()
5283 .lock()
5284 .unwrap_or_else(std::sync::PoisonError::into_inner)
5285 .entry(session_id)
5286 .or_default()
5287 .extend(archived);
5288 }
5289 Ok(metadata)
5290 }
5291
5292 fn mutate_session_lifecycle(
5293 &self,
5294 id: &str,
5295 mutator: SessionMutator,
5296 mutate: impl FnOnce(&mut SessionMetadata) -> bool,
5297 ) -> io::Result<SessionMetadata> {
5298 let _lease = (mutator == SessionMutator::External)
5299 .then(|| self.reserve_session_for_external_write(id))
5300 .transpose()?;
5301 let (metadata, changed) = self
5302 .with_session_write_admission(id, || {
5303 let persisted = self.load_session_write_metadata(id)?;
5304 let before = self.observe_session_admitted(id)?;
5305 let mut session = self.load_session_snapshot_with_limit(id, None, true)?;
5306 repair_recovered_session(&mut session);
5307 if !mutate(&mut session.metadata) {
5308 session.metadata.native_mutation_observation = Some(NativeSessionMutation {
5309 before: before.clone(),
5310 after: before,
5311 });
5312 return Ok((session.metadata, false));
5313 }
5314 let mut metadata =
5315 self.write_session_admitted(session, JournalPrune::Keep, false, &persisted)?;
5316 metadata.native_mutation_observation = Some(NativeSessionMutation {
5317 before,
5318 after: self.observe_session_admitted(id)?,
5319 });
5320 Ok((metadata, true))
5321 })?
5322 .ok_or_else(Self::retired_session_write_error)?;
5323 if changed {
5324 self.cleanup_old_sessions_for_mode(
5325 None,
5326 Some(metadata.mode.as_deref() == Some("exec")),
5327 )?;
5328 }
5329 Ok(metadata)
5330 }
5331
5332 /// Save a crash-recovery checkpoint for in-flight turns.
5333 ///
5334 /// Checkpoints are keyed per session (`checkpoints/<session_id>.json`) so
5335 /// concurrent sessions never overwrite each other's crash-recovery state.
5336 #[cfg(any(test, feature = "test-support"))]
5337 pub fn save_checkpoint(&self, session: &SavedSession) -> std::io::Result<PathBuf> {
5338 self.save_checkpoint_owned(session.clone())
5339 }
5340
5341 /// Save a crash-recovery checkpoint, consuming the session.
5342 #[cfg(any(test, feature = "test-support"))]
5343 pub fn save_checkpoint_owned(&self, session: SavedSession) -> std::io::Result<PathBuf> {
5344 let session_id = session.metadata.id.clone();
5345 let path = self.validated_checkpoint_path(&session_id)?;
5346 self.with_session_write_admission(&session_id, || {
5347 let persisted = self.load_session_write_metadata(&session_id)?;
5348 let mut durable_session = session;
5349 Self::prepare_session_write(&mut durable_session, &persisted, true)?;
5350 let session_path = self.validated_session_path(&session_id)?;
5351 self.archive_before_first_graph_write(&durable_session, &session_path)?;
5352 fs::create_dir_all(self.checkpoints_dir())?;
5353 let already_persisted = path.exists() || session_path.exists();
5354 self.hydrate_approval_receipts(&mut durable_session)?;
5355 durable_session.metadata.publication_id = Some(Uuid::new_v4().to_string());
5356 let content = serialize_saved_session(durable_session)?;
5357 write_atomic(&path, content.as_bytes())?;
5358 self.stamp_session_boot_owner_for_new_record(&session_id, already_persisted);
5359 Ok(())
5360 })?
5361 .ok_or_else(Self::retired_session_write_error)?;
5362 Ok(path)
5363 }
5364
5365 fn session_boot_owners_path(&self) -> PathBuf {
5366 self.sessions_dir
5367 .join(format!("{SESSION_BOOT_OWNERS_STEM}.json"))
5368 }
5369
5370 fn load_session_boot_owners(&self) -> BTreeMap<String, String> {
5371 fs::read_to_string(self.session_boot_owners_path())
5372 .ok()
5373 .and_then(|content| serde_json::from_str(&content).ok())
5374 .unwrap_or_default()
5375 }
5376
5377 /// Does any durable record (session file or crash checkpoint) exist for
5378 /// this session id?
5379 fn session_record_exists(&self, session_id: &str) -> bool {
5380 self.validated_session_path(session_id)
5381 .is_ok_and(|path| path.exists())
5382 || self
5383 .validated_checkpoint_path(session_id)
5384 .is_ok_and(|path| path.exists())
5385 }
5386
5387 /// Record which session instance owns `session_id`'s persisted record.
5388 ///
5389 /// Entries whose durable record no longer exists are pruned on the same
5390 /// write, so the sidecar cannot grow without bound.
5391 pub fn record_session_boot_owner(
5392 &self,
5393 session_id: &str,
5394 boot_id: &str,
5395 ) -> std::io::Result<()> {
5396 let id = self.validated_session_id(session_id)?.to_string();
5397 self.with_boot_owners_lock(|| {
5398 let mut owners = self.load_session_boot_owners();
5399 owners.retain(|owned, _| owned == &id || self.session_record_exists(owned));
5400 owners.insert(id, boot_id.to_string());
5401 let content = serde_json::to_string_pretty(&owners)
5402 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
5403 write_atomic(&self.session_boot_owners_path(), content.as_bytes())
5404 })
5405 }
5406
5407 /// Serialize the sidecar's read-modify-write across processes. Two
5408 /// processes stamping at once each read the old map and the second rename
5409 /// dropped the first one's entry (#6144 P8).
5410 fn with_boot_owners_lock<T>(&self, update: impl FnOnce() -> io::Result<T>) -> io::Result<T> {
5411 let lock_file = open_private_lock_file(
5412 &self
5413 .sessions_dir
5414 .join(format!("{SESSION_BOOT_OWNERS_STEM}.lock")),
5415 )?;
5416 let mut lock = fd_lock::RwLock::new(lock_file);
5417 let _guard = lock.write()?;
5418 update()
5419 }
5420
5421 /// The session-instance boot id stamped on this session's persisted
5422 /// record, when one was recorded.
5423 #[must_use]
5424 pub fn session_boot_owner(&self, session_id: &str) -> Option<String> {
5425 let id = self.validated_session_id(session_id).ok()?;
5426 self.load_session_boot_owners().get(id).cloned()
5427 }
5428
5429 /// Was this session's persisted record created by a different session
5430 /// instance (an earlier or sibling Codewhale process)?
5431 ///
5432 /// Mirrors `SubAgentManager::is_from_prior_session` (#405): a durable
5433 /// record with no stamped owner predates the marker and is classified as
5434 /// prior-instance work, while an id with no durable record at all is
5435 /// this instance's own not-yet-persisted session.
5436 #[must_use]
5437 pub fn session_from_prior_instance(&self, session_id: &str) -> bool {
5438 match self.session_boot_owner(session_id) {
5439 Some(owner) => owner != current_session_boot_id(),
5440 None => self.session_record_exists(session_id),
5441 }
5442 }
5443
5444 /// Stamp this instance as creator when a save writes the first durable
5445 /// record for `session_id`. A record that already existed keeps its
5446 /// original owner: re-serializing another instance's work (crash
5447 /// recovery, external mutation) must not re-badge it as ours.
5448 fn stamp_session_boot_owner_for_new_record(&self, session_id: &str, already_persisted: bool) {
5449 if already_persisted || self.session_boot_owner(session_id).is_some() {
5450 return;
5451 }
5452 if let Err(error) = self.record_session_boot_owner(session_id, current_session_boot_id()) {
5453 tracing::warn!(session_id, %error, "could not stamp session boot owner");
5454 }
5455 }
5456
5457 fn clear_session_boot_owner(&self, session_id: &str) {
5458 let Ok(id) = self.validated_session_id(session_id) else {
5459 return;
5460 };
5461 let _ = self.with_boot_owners_lock(|| {
5462 let mut owners = self.load_session_boot_owners();
5463 if owners.remove(id).is_none() {
5464 return Ok(());
5465 }
5466 if let Ok(content) = serde_json::to_string_pretty(&owners) {
5467 write_atomic(&self.session_boot_owners_path(), content.as_bytes())?;
5468 }
5469 Ok(())
5470 });
5471 }
5472
5473 /// Move the journal's excess off-branch entries into the archive sidecar.
5474 /// Order is the data-loss guard: plan on the unchanged journal, append and
5475 /// fsync the planned entries, and only then remove them from the document
5476 /// about to be written. Any failure leaves the journal whole. Returns the
5477 /// removed ids.
5478 fn archive_dead_journal_entries(
5479 &self,
5480 session: &mut SavedSession,
5481 dead_threshold: usize,
5482 dead_budget: usize,
5483 ) -> io::Result<Vec<String>> {
5484 let session_id = session.metadata.id.clone();
5485 let Some(journal) = session.journal.as_mut() else {
5486 return Ok(Vec::new());
5487 };
5488 let plan = journal.prune_plan(dead_threshold, dead_budget);
5489 if plan.is_empty() {
5490 return Ok(Vec::new());
5491 }
5492 let ids: std::collections::HashSet<String> = plan.into_iter().collect();
5493 // Ids a previous save archived but the live journal still carries
5494 // are already durable; append only the rest.
5495 let already = archived_journal_ids()
5496 .lock()
5497 .unwrap_or_else(std::sync::PoisonError::into_inner)
5498 .get(&session_id)
5499 .cloned()
5500 .unwrap_or_default();
5501 let fresh: Vec<&SessionEntry> = journal
5502 .entries
5503 .iter()
5504 .filter(|entry| ids.contains(&entry.id) && !already.contains(&entry.id))
5505 .collect();
5506 self.append_journal_archive(&session_id, &fresh)?;
5507 journal
5508 .remove_entries(&ids)
5509 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
5510 session.leaf_id = journal.leaf_id.clone();
5511 Ok(ids.into_iter().collect())
5512 }
5513
5514 /// Append `entries` to the session's journal archive, one JSON object per
5515 /// line, and fsync before returning. The sidecar is owner-only and never
5516 /// followed through a link.
5517 fn append_journal_archive(
5518 &self,
5519 session_id: &str,
5520 entries: &[&SessionEntry],
5521 ) -> io::Result<()> {
5522 use std::io::{Read as _, Seek as _, SeekFrom, Write as _};
5523 if entries.is_empty() {
5524 return Ok(());
5525 }
5526 let path = journal_archive_path(&self.sessions_dir, session_id)?;
5527 let dir = self.sessions_dir.join(JOURNAL_ARCHIVE_DIR);
5528 if let Ok(metadata) = fs::symlink_metadata(&dir)
5529 && codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata)
5530 {
5531 return Err(io::Error::new(
5532 io::ErrorKind::InvalidInput,
5533 "journal archive directory is a link",
5534 ));
5535 }
5536 let created_dir = !dir.exists();
5537 fs::create_dir_all(&dir)?;
5538 let mut buf = Vec::new();
5539 for entry in entries {
5540 serde_json::to_writer(&mut buf, entry)
5541 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
5542 buf.push(b'\n');
5543 }
5544 let created_file = !path.exists();
5545 {
5546 let mut file = open_private_lock_file(&path)?;
5547 let mut start = file.seek(SeekFrom::End(0))?;
5548 if start > 0 {
5549 let mut last = [0u8; 1];
5550 file.seek(SeekFrom::End(-1))?;
5551 file.read_exact(&mut last)?;
5552 if last[0] != b'\n' {
5553 let mut raw = Vec::new();
5554 file.seek(SeekFrom::Start(0))?;
5555 file.read_to_end(&mut raw)?;
5556 start = raw
5557 .iter()
5558 .rposition(|byte| *byte == b'\n')
5559 .map_or(0, |index| index as u64 + 1);
5560 file.set_len(start)?;
5561 }
5562 file.seek(SeekFrom::Start(start))?;
5563 }
5564 if let Err(error) = file.write_all(&buf).and_then(|()| file.sync_all()) {
5565 let _ = file.set_len(start).and_then(|()| file.sync_all());
5566 return Err(error);
5567 }
5568 }
5569 #[cfg(unix)]
5570 if created_file || created_dir {
5571 // Make the new directory entries durable, not only the bytes.
5572 fs::File::open(&dir)?.sync_all()?;
5573 if created_dir {
5574 fs::File::open(&self.sessions_dir)?.sync_all()?;
5575 }
5576 }
5577 #[cfg(not(unix))]
5578 let _ = (created_file, created_dir);
5579 self.rotate_journal_archive_at_threshold(session_id, JOURNAL_ARCHIVE_ROTATE_BYTES)?;
5580 Ok(())
5581 }
5582
5583 fn rotate_journal_archive_at_threshold(
5584 &self,
5585 session_id: &str,
5586 threshold_bytes: u64,
5587 ) -> io::Result<bool> {
5588 use std::io::Write as _;
5589 let hot_path = journal_archive_path(&self.sessions_dir, session_id)?;
5590 let hot_len = match open_private_read_file(&hot_path) {
5591 Ok(file) => file.metadata()?.len(),
5592 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(false),
5593 Err(error) => return Err(error),
5594 };
5595 if hot_len < threshold_bytes {
5596 return Ok(false);
5597 }
5598 let segments = list_journal_archive_segments(&self.sessions_dir, session_id)?;
5599 let next_seq = match segments.last() {
5600 Some((seq, _)) => seq.checked_add(1).ok_or_else(|| {
5601 io::Error::new(
5602 io::ErrorKind::InvalidData,
5603 "journal archive segment sequence exhausted",
5604 )
5605 })?,
5606 None => 1,
5607 };
5608 let mut seen = stream_journal_archive_segment_ids(&segments)?;
5609 let mut encoder = liblzma::write::XzEncoder::new(Vec::new(), JOURNAL_ARCHIVE_XZ_LEVEL);
5610 let mut fresh_count = 0usize;
5611 let mut write_error: Option<io::Error> = None;
5612 {
5613 let file = open_private_read_file(&hot_path)?;
5614 let mut reader = io::BufReader::new(file);
5615 stream_journal_archive_lines(&mut reader, &hot_path, true, |line| {
5616 let entry: SessionEntry = serde_json::from_str(line)?;
5617 if seen.insert(entry.id) {
5618 fresh_count += 1;
5619 if write_error.is_none()
5620 && let Err(error) = encoder
5621 .write_all(line.as_bytes())
5622 .and_then(|()| encoder.write_all(b"\n"))
5623 {
5624 write_error = Some(error);
5625 }
5626 }
5627 Ok(())
5628 })?;
5629 }
5630 if let Some(error) = write_error {
5631 return Err(error);
5632 }
5633 if fresh_count > 0 {
5634 let compressed = encoder.finish()?;
5635 let segment_path =
5636 journal_archive_segment_path(&self.sessions_dir, session_id, next_seq)?;
5637 write_atomic(&segment_path, &compressed)?;
5638 }
5639 let dir = self.sessions_dir.join(JOURNAL_ARCHIVE_DIR);
5640 match fs::remove_file(&hot_path) {
5641 Ok(()) => sync_directory(&dir),
5642 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
5643 Err(error) => return Err(error),
5644 }
5645 Ok(true)
5646 }
5647
5648 /// Entries archived out of `session_id`'s journal by bounded saves.
5649 pub fn load_journal_archive(&self, session_id: &str) -> io::Result<Vec<SessionEntry>> {
5650 load_journal_archive(&self.sessions_dir, self.validated_session_id(session_id)?)
5651 }
5652
5653 pub fn load_journal_archive_ids(
5654 &self,
5655 session_id: &str,
5656 ) -> io::Result<std::collections::HashSet<String>> {
5657 load_journal_archive_ids(&self.sessions_dir, self.validated_session_id(session_id)?)
5658 }
5659
5660 pub fn journal_archive_summary(
5661 &self,
5662 session_id: &str,
5663 ) -> io::Result<Option<JournalArchiveSummary>> {
5664 let id = self.validated_session_id(session_id)?;
5665 let hot_path = journal_archive_path(&self.sessions_dir, id)?;
5666 let segments = list_journal_archive_segments(&self.sessions_dir, id)?;
5667 let mut seen = std::collections::HashSet::new();
5668 let mut unique_entries = 0usize;
5669 let mut duplicate_lines = 0usize;
5670 let mut compressed_bytes = 0u64;
5671 for (_, seg_path) in &segments {
5672 let file = open_private_read_file(seg_path)?;
5673 compressed_bytes = compressed_bytes.saturating_add(file.metadata()?.len());
5674 let mut reader = io::BufReader::new(liblzma::read::XzDecoder::new(file));
5675 stream_journal_archive_lines(&mut reader, seg_path, false, |line| {
5676 let entry: ArchiveEntryId = serde_json::from_str(line)?;
5677 if seen.insert(entry.id) {
5678 unique_entries += 1;
5679 } else {
5680 duplicate_lines += 1;
5681 }
5682 Ok(())
5683 })?;
5684 }
5685 let (has_hot, raw_bytes) = match open_private_read_file(&hot_path) {
5686 Ok(file) => {
5687 let len = file.metadata()?.len();
5688 let mut reader = io::BufReader::new(file);
5689 stream_journal_archive_lines(&mut reader, &hot_path, true, |line| {
5690 let entry: ArchiveEntryId = serde_json::from_str(line)?;
5691 if seen.insert(entry.id) {
5692 unique_entries += 1;
5693 } else {
5694 duplicate_lines += 1;
5695 }
5696 Ok(())
5697 })?;
5698 (true, len)
5699 }
5700 Err(error) if error.kind() == io::ErrorKind::NotFound => (false, 0),
5701 Err(error) => return Err(error),
5702 };
5703 if segments.is_empty() && !has_hot {
5704 return Ok(None);
5705 }
5706 Ok(Some(JournalArchiveSummary {
5707 unique_entries,
5708 duplicate_lines,
5709 total_bytes: raw_bytes.saturating_add(compressed_bytes),
5710 raw_bytes,
5711 compressed_bytes,
5712 segment_count: segments.len().saturating_add(usize::from(has_hot)),
5713 }))
5714 }
5715
5716 fn classify_journal_archive_session_read_only(
5717 sessions_dir: &Path,
5718 session_id: &str,
5719 ) -> JournalArchiveSessionStatus {
5720 let session_path = sessions_dir.join(format!("{session_id}.json"));
5721 let checkpoint_path = sessions_dir
5722 .join("checkpoints")
5723 .join(format!("{session_id}.json"));
5724 for candidate in [&session_path, &checkpoint_path] {
5725 match fs::symlink_metadata(candidate) {
5726 Ok(metadata) => {
5727 if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata)
5728 || !metadata.is_file()
5729 {
5730 return JournalArchiveSessionStatus::Active;
5731 }
5732 return match Self::load_session_metadata(candidate) {
5733 Ok(meta) if meta.archived => JournalArchiveSessionStatus::Archived,
5734 _ => JournalArchiveSessionStatus::Active,
5735 };
5736 }
5737 Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
5738 Err(_) => return JournalArchiveSessionStatus::Active,
5739 }
5740 }
5741 JournalArchiveSessionStatus::Orphaned
5742 }
5743
5744 pub fn inspect_journal_archives_read_only(
5745 sessions_dir: &Path,
5746 ) -> io::Result<JournalArchiveInventory> {
5747 let mut inventory = JournalArchiveInventory {
5748 archive_dir: sessions_dir.join(JOURNAL_ARCHIVE_DIR),
5749 ..JournalArchiveInventory::default()
5750 };
5751 let Some(dir) = checked_existing_journal_archive_dir(sessions_dir)? else {
5752 return Ok(inventory);
5753 };
5754 inventory.present = true;
5755
5756 #[derive(Default)]
5757 struct GroupedArchive {
5758 compressed_segments: usize,
5759 has_hot_tail: bool,
5760 raw_bytes: u64,
5761 compressed_bytes: u64,
5762 modified_at: Option<DateTime<Utc>>,
5763 }
5764
5765 let mut grouped: BTreeMap<String, GroupedArchive> = BTreeMap::new();
5766 for entry in fs::read_dir(&dir)? {
5767 let entry = match entry {
5768 Ok(entry) => entry,
5769 Err(error) => {
5770 inventory.unreadable.push(error.to_string());
5771 continue;
5772 }
5773 };
5774 let path = entry.path();
5775 let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
5776 inventory.unreadable.push(path.display().to_string());
5777 continue;
5778 };
5779 if name.starts_with('.') {
5780 continue;
5781 }
5782 let metadata = match fs::symlink_metadata(&path) {
5783 Ok(metadata) => metadata,
5784 Err(error) => {
5785 inventory
5786 .unreadable
5787 .push(format!("{}: {error}", path.display()));
5788 continue;
5789 }
5790 };
5791 if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata)
5792 || !metadata.is_file()
5793 {
5794 inventory
5795 .unreadable
5796 .push(format!("{} (unexpected link or non-file)", path.display()));
5797 continue;
5798 }
5799 let Some((session_id, seq)) = parse_journal_archive_filename(&name) else {
5800 continue;
5801 };
5802 let bucket = grouped.entry(session_id).or_default();
5803 let len = metadata.len();
5804 if seq.is_some() {
5805 bucket.compressed_segments = bucket.compressed_segments.saturating_add(1);
5806 bucket.compressed_bytes = bucket.compressed_bytes.saturating_add(len);
5807 } else {
5808 bucket.has_hot_tail = true;
5809 bucket.raw_bytes = bucket.raw_bytes.saturating_add(len);
5810 }
5811 if let Some(modified) = metadata.modified().ok().map(DateTime::<Utc>::from) {
5812 bucket.modified_at = Some(match bucket.modified_at {
5813 Some(prev) if prev > modified => prev,
5814 _ => modified,
5815 });
5816 }
5817 }
5818
5819 for (session_id, bucket) in grouped {
5820 let status =
5821 Self::classify_journal_archive_session_read_only(sessions_dir, &session_id);
5822 let total_bytes = bucket.raw_bytes.saturating_add(bucket.compressed_bytes);
5823 let segment_count = bucket
5824 .compressed_segments
5825 .saturating_add(usize::from(bucket.has_hot_tail));
5826 inventory.total_bytes = inventory.total_bytes.saturating_add(total_bytes);
5827 inventory.raw_bytes = inventory.raw_bytes.saturating_add(bucket.raw_bytes);
5828 inventory.compressed_bytes = inventory
5829 .compressed_bytes
5830 .saturating_add(bucket.compressed_bytes);
5831 inventory.compressed_segments = inventory
5832 .compressed_segments
5833 .saturating_add(bucket.compressed_segments);
5834 if status == JournalArchiveSessionStatus::Orphaned {
5835 inventory.orphaned_sessions = inventory.orphaned_sessions.saturating_add(1);
5836 inventory.orphaned_bytes = inventory.orphaned_bytes.saturating_add(total_bytes);
5837 }
5838 inventory.sessions.push(JournalArchiveRecord {
5839 session_id,
5840 status,
5841 segment_count,
5842 compressed_segments: bucket.compressed_segments,
5843 has_hot_tail: bucket.has_hot_tail,
5844 raw_bytes: bucket.raw_bytes,
5845 compressed_bytes: bucket.compressed_bytes,
5846 total_bytes,
5847 modified_at: bucket.modified_at,
5848 });
5849 }
5850 inventory.sessions.sort_by(|a, b| {
5851 b.total_bytes
5852 .cmp(&a.total_bytes)
5853 .then_with(|| a.session_id.cmp(&b.session_id))
5854 });
5855 Ok(inventory)
5856 }
5857
5858 fn with_journal_archive_write_lock<T>(
5859 &self,
5860 session_id: &str,
5861 allow_deleted_session: bool,
5862 write: impl FnOnce() -> io::Result<T>,
5863 ) -> io::Result<Option<T>> {
5864 if !allow_deleted_session {
5865 return self.with_session_write_admission(session_id, write);
5866 }
5867 let (_, lock_path) = self.ensure_late_usage_paths(session_id)?;
5868 let lock_file = open_private_lock_file(&lock_path)?;
5869 let mut lock = fd_lock::RwLock::new(lock_file);
5870 let _guard = lock.write()?;
5871 write().map(Some)
5872 }
5873
5874 fn resolve_archive_session_id(
5875 &self,
5876 id_or_prefix: &str,
5877 inventory: &JournalArchiveInventory,
5878 ) -> io::Result<String> {
5879 let trimmed = id_or_prefix.trim();
5880 if trimmed.is_empty() {
5881 return Err(io::Error::new(
5882 io::ErrorKind::InvalidInput,
5883 "session id must not be empty",
5884 ));
5885 }
5886 if inventory
5887 .sessions
5888 .iter()
5889 .any(|record| record.session_id == trimmed)
5890 {
5891 return Ok(trimmed.to_string());
5892 }
5893 let matches: Vec<&str> = inventory
5894 .sessions
5895 .iter()
5896 .filter(|record| record.session_id.starts_with(trimmed))
5897 .map(|record| record.session_id.as_str())
5898 .collect();
5899 match matches.len() {
5900 1 => Ok(matches[0].to_string()),
5901 n if n > 1 => Err(io::Error::new(
5902 io::ErrorKind::InvalidInput,
5903 format!("session id prefix '{trimmed}' matches {n} journal archives"),
5904 )),
5905 _ => self.resolve_trim_session_id(trimmed),
5906 }
5907 }
5908
5909 fn compress_journal_archive_stream(
5910 segments: &[(u32, PathBuf)],
5911 hot_path: &Path,
5912 ) -> io::Result<(Vec<u8>, usize, usize)> {
5913 use std::io::Write as _;
5914 let mut encoder = liblzma::write::XzEncoder::new(Vec::new(), JOURNAL_ARCHIVE_XZ_LEVEL);
5915 let mut seen = std::collections::HashSet::new();
5916 let mut unique_entries = 0usize;
5917 let mut duplicate_lines = 0usize;
5918 let mut write_error: Option<io::Error> = None;
5919
5920 for (_, seg_path) in segments {
5921 let file = open_private_read_file(seg_path)?;
5922 let mut reader = io::BufReader::new(liblzma::read::XzDecoder::new(file));
5923 stream_journal_archive_lines(&mut reader, seg_path, false, |line| {
5924 let entry: SessionEntry = serde_json::from_str(line)?;
5925 if seen.insert(entry.id) {
5926 unique_entries += 1;
5927 if write_error.is_none()
5928 && let Err(error) = encoder
5929 .write_all(line.as_bytes())
5930 .and_then(|()| encoder.write_all(b"\n"))
5931 {
5932 write_error = Some(error);
5933 }
5934 } else {
5935 duplicate_lines += 1;
5936 }
5937 Ok(())
5938 })?;
5939 if let Some(error) = write_error.take() {
5940 return Err(error);
5941 }
5942 }
5943 match open_private_read_file(hot_path) {
5944 Ok(file) => {
5945 let mut reader = io::BufReader::new(file);
5946 stream_journal_archive_lines(&mut reader, hot_path, true, |line| {
5947 let entry: SessionEntry = serde_json::from_str(line)?;
5948 if seen.insert(entry.id) {
5949 unique_entries += 1;
5950 if write_error.is_none()
5951 && let Err(error) = encoder
5952 .write_all(line.as_bytes())
5953 .and_then(|()| encoder.write_all(b"\n"))
5954 {
5955 write_error = Some(error);
5956 }
5957 } else {
5958 duplicate_lines += 1;
5959 }
5960 Ok(())
5961 })?;
5962 if let Some(error) = write_error.take() {
5963 return Err(error);
5964 }
5965 }
5966 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
5967 Err(error) => return Err(error),
5968 }
5969 let bytes = if unique_entries > 0 {
5970 encoder.finish()?
5971 } else {
5972 Vec::new()
5973 };
5974 Ok((bytes, unique_entries, duplicate_lines))
5975 }
5976
5977 pub fn compact_journal_archives(
5978 &self,
5979 session_filter: Option<&str>,
5980 apply: bool,
5981 ) -> io::Result<JournalArchiveCompactReport> {
5982 let inventory = Self::inspect_journal_archives_read_only(&self.sessions_dir)?;
5983 let selected_id = match session_filter {
5984 Some(filter) => Some(self.resolve_archive_session_id(filter, &inventory)?),
5985 None => None,
5986 };
5987 let targets: Vec<&JournalArchiveRecord> = inventory
5988 .sessions
5989 .iter()
5990 .filter(|record| {
5991 selected_id
5992 .as_deref()
5993 .is_none_or(|id| record.session_id == id)
5994 })
5995 .collect();
5996
5997 let mut report = JournalArchiveCompactReport {
5998 applied: apply,
5999 ..JournalArchiveCompactReport::default()
6000 };
6001 let dir = self.sessions_dir.join(JOURNAL_ARCHIVE_DIR);
6002
6003 for record in targets {
6004 let session_id = &record.session_id;
6005 let hot_path = journal_archive_path(&self.sessions_dir, session_id)?;
6006 if !apply {
6007 let segments = list_journal_archive_segments(&self.sessions_dir, session_id)?;
6008 let has_hot = match fs::symlink_metadata(&hot_path) {
6009 Ok(_) => true,
6010 Err(error) if error.kind() == io::ErrorKind::NotFound => false,
6011 Err(error) => return Err(error),
6012 };
6013 let (compressed, unique_entries, duplicate_lines) =
6014 Self::compress_journal_archive_stream(&segments, &hot_path)?;
6015 let needs_work = has_hot || segments.len() > 1 || duplicate_lines > 0;
6016 if !needs_work && selected_id.is_none() {
6017 continue;
6018 }
6019 let after_bytes = if needs_work {
6020 compressed.len() as u64
6021 } else {
6022 record.total_bytes
6023 };
6024 let after_segments = if needs_work {
6025 usize::from(unique_entries > 0)
6026 } else {
6027 record.segment_count
6028 };
6029 let entry = JournalArchiveCompactEntry {
6030 session_id: session_id.clone(),
6031 before_bytes: record.total_bytes,
6032 after_bytes,
6033 unique_entries,
6034 duplicate_lines_removed: duplicate_lines,
6035 before_segments: record.segment_count,
6036 after_segments,
6037 applied: false,
6038 session_is_live: self.is_session_live_anywhere(session_id),
6039 };
6040 report.before_bytes = report.before_bytes.saturating_add(entry.before_bytes);
6041 report.after_bytes = report.after_bytes.saturating_add(entry.after_bytes);
6042 report.duplicate_lines_removed = report
6043 .duplicate_lines_removed
6044 .saturating_add(entry.duplicate_lines_removed);
6045 report.entries.push(entry);
6046 continue;
6047 }
6048
6049 let allow_deleted = record.status == JournalArchiveSessionStatus::Orphaned;
6050 let outcome =
6051 match self.with_journal_archive_write_lock(session_id, allow_deleted, || {
6052 let _lease = self.reserve_session_for_external_write(session_id)?;
6053 let segments = list_journal_archive_segments(&self.sessions_dir, session_id)?;
6054 let mut before_bytes = 0u64;
6055 for (_, seg_path) in &segments {
6056 before_bytes = before_bytes
6057 .saturating_add(open_private_read_file(seg_path)?.metadata()?.len());
6058 }
6059 let has_hot = match open_private_read_file(&hot_path) {
6060 Ok(file) => {
6061 before_bytes = before_bytes.saturating_add(file.metadata()?.len());
6062 true
6063 }
6064 Err(error) if error.kind() == io::ErrorKind::NotFound => false,
6065 Err(error) => return Err(error),
6066 };
6067 let before_segments = segments.len().saturating_add(usize::from(has_hot));
6068 if before_segments == 0 {
6069 return Ok(None);
6070 }
6071 let (compressed, unique_entries, duplicate_lines) =
6072 Self::compress_journal_archive_stream(&segments, &hot_path)?;
6073 let needs_work = has_hot || segments.len() > 1 || duplicate_lines > 0;
6074 if !needs_work {
6075 if selected_id.is_none() {
6076 return Ok(None);
6077 }
6078 return Ok(Some(JournalArchiveCompactEntry {
6079 session_id: session_id.clone(),
6080 before_bytes,
6081 after_bytes: before_bytes,
6082 unique_entries,
6083 duplicate_lines_removed: 0,
6084 before_segments,
6085 after_segments: before_segments,
6086 applied: false,
6087 session_is_live: false,
6088 }));
6089 }
6090 if unique_entries > 0 {
6091 let next_seq = match segments.last() {
6092 Some((seq, _)) => seq.checked_add(1).ok_or_else(|| {
6093 io::Error::new(
6094 io::ErrorKind::InvalidData,
6095 "journal archive segment sequence exhausted",
6096 )
6097 })?,
6098 None => 1,
6099 };
6100 let new_segment =
6101 journal_archive_segment_path(&self.sessions_dir, session_id, next_seq)?;
6102 write_atomic(&new_segment, &compressed)?;
6103 }
6104 let mut removed_any = false;
6105 for (_, seg_path) in &segments {
6106 match fs::remove_file(seg_path) {
6107 Ok(()) => removed_any = true,
6108 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
6109 Err(error) => return Err(error),
6110 }
6111 }
6112 if has_hot {
6113 match fs::remove_file(&hot_path) {
6114 Ok(()) => removed_any = true,
6115 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
6116 Err(error) => return Err(error),
6117 }
6118 }
6119 if removed_any {
6120 sync_directory(&dir);
6121 }
6122 Ok(Some(JournalArchiveCompactEntry {
6123 session_id: session_id.clone(),
6124 before_bytes,
6125 after_bytes: compressed.len() as u64,
6126 unique_entries,
6127 duplicate_lines_removed: duplicate_lines,
6128 before_segments,
6129 after_segments: usize::from(unique_entries > 0),
6130 applied: true,
6131 session_is_live: false,
6132 }))
6133 }) {
6134 Ok(outcome) => outcome,
6135 Err(error)
6136 if error.kind() == io::ErrorKind::ResourceBusy && selected_id.is_none() =>
6137 {
6138 report.skipped_live_sessions.push(session_id.clone());
6139 continue;
6140 }
6141 Err(error) => return Err(error),
6142 };
6143 if let Some(Some(entry)) = outcome {
6144 report.before_bytes = report.before_bytes.saturating_add(entry.before_bytes);
6145 report.after_bytes = report.after_bytes.saturating_add(entry.after_bytes);
6146 report.duplicate_lines_removed = report
6147 .duplicate_lines_removed
6148 .saturating_add(entry.duplicate_lines_removed);
6149 report.entries.push(entry);
6150 }
6151 }
6152 Ok(report)
6153 }
6154
6155 fn latest_journal_archive_modified_at(
6156 &self,
6157 session_id: &str,
6158 ) -> io::Result<Option<DateTime<Utc>>> {
6159 let mut latest: Option<DateTime<Utc>> = None;
6160 let mut paths: Vec<PathBuf> =
6161 list_journal_archive_segments(&self.sessions_dir, session_id)?
6162 .into_iter()
6163 .map(|(_, path)| path)
6164 .collect();
6165 paths.push(journal_archive_path(&self.sessions_dir, session_id)?);
6166 for path in paths {
6167 let metadata = match fs::symlink_metadata(&path) {
6168 Ok(metadata) => metadata,
6169 Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
6170 Err(error) => return Err(error),
6171 };
6172 if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata)
6173 || !metadata.is_file()
6174 {
6175 continue;
6176 }
6177 if let Some(modified) = metadata.modified().ok().map(DateTime::<Utc>::from) {
6178 latest = Some(match latest {
6179 Some(prev) if prev > modified => prev,
6180 _ => modified,
6181 });
6182 }
6183 }
6184 Ok(latest)
6185 }
6186
6187 pub fn prune_journal_archives(
6188 &self,
6189 options: &JournalArchivePruneOptions,
6190 ) -> io::Result<JournalArchivePruneReport> {
6191 if !options.orphans_only
6192 && options.session_id.is_none()
6193 && options.older_than_days.is_none()
6194 {
6195 return Err(io::Error::new(
6196 io::ErrorKind::InvalidInput,
6197 "specify --orphans-only, --session <ID>, or --older-than-days <DAYS> to select which journal archives to prune",
6198 ));
6199 }
6200 let inventory = Self::inspect_journal_archives_read_only(&self.sessions_dir)?;
6201 let selected_id = match options.session_id.as_deref() {
6202 Some(filter) => Some(self.resolve_archive_session_id(filter, &inventory)?),
6203 None => None,
6204 };
6205 let cutoff = match options.older_than_days {
6206 Some(days) => {
6207 let Some(cutoff) = days
6208 .checked_mul(86_400)
6209 .map(std::time::Duration::from_secs)
6210 .and_then(|age| chrono::Duration::from_std(age).ok())
6211 .and_then(|age| Utc::now().checked_sub_signed(age))
6212 else {
6213 return Ok(JournalArchivePruneReport {
6214 applied: options.apply,
6215 orphans_only: options.orphans_only,
6216 ..JournalArchivePruneReport::default()
6217 });
6218 };
6219 Some(cutoff)
6220 }
6221 None => None,
6222 };
6223
6224 let selected: Vec<&JournalArchiveRecord> = inventory
6225 .sessions
6226 .iter()
6227 .filter(|record| {
6228 if let Some(id) = selected_id.as_deref()
6229 && record.session_id != id
6230 {
6231 return false;
6232 }
6233 if options.orphans_only && record.status != JournalArchiveSessionStatus::Orphaned {
6234 return false;
6235 }
6236 if let Some(cutoff) = cutoff
6237 && !record.modified_at.is_some_and(|ts| ts <= cutoff)
6238 {
6239 return false;
6240 }
6241 true
6242 })
6243 .collect();
6244
6245 let mut report = JournalArchivePruneReport {
6246 applied: options.apply,
6247 orphans_only: options.orphans_only,
6248 ..JournalArchivePruneReport::default()
6249 };
6250
6251 for record in selected {
6252 let session_id = &record.session_id;
6253 if !options.apply {
6254 report.targets.push(JournalArchivePruneTarget {
6255 session_id: session_id.clone(),
6256 status: record.status,
6257 bytes: record.total_bytes,
6258 segment_count: record.segment_count,
6259 modified_at: record.modified_at,
6260 session_is_live: self.is_session_live_anywhere(session_id),
6261 });
6262 continue;
6263 }
6264 let allow_deleted = record.status == JournalArchiveSessionStatus::Orphaned;
6265 let outcome =
6266 match self.with_journal_archive_write_lock(session_id, allow_deleted, || {
6267 let _lease = self.reserve_session_for_external_write(session_id)?;
6268 if options.orphans_only
6269 && Self::classify_journal_archive_session_read_only(
6270 &self.sessions_dir,
6271 session_id,
6272 ) != JournalArchiveSessionStatus::Orphaned
6273 {
6274 return Ok((0usize, 0u64));
6275 }
6276 if let Some(cutoff) = cutoff
6277 && !self
6278 .latest_journal_archive_modified_at(session_id)?
6279 .is_some_and(|ts| ts <= cutoff)
6280 {
6281 return Ok((0usize, 0u64));
6282 }
6283 self.remove_journal_archive_counted(session_id)
6284 }) {
6285 Ok(outcome) => outcome,
6286 Err(error)
6287 if error.kind() == io::ErrorKind::ResourceBusy && selected_id.is_none() =>
6288 {
6289 report.skipped_live_sessions.push(session_id.clone());
6290 continue;
6291 }
6292 Err(error) => return Err(error),
6293 };
6294 if let Some((files, bytes)) = outcome
6295 && files > 0
6296 {
6297 report.removed_files = report.removed_files.saturating_add(files);
6298 report.removed_bytes = report.removed_bytes.saturating_add(bytes);
6299 report.targets.push(JournalArchivePruneTarget {
6300 session_id: session_id.clone(),
6301 status: record.status,
6302 bytes,
6303 segment_count: files,
6304 modified_at: record.modified_at,
6305 session_is_live: false,
6306 });
6307 }
6308 }
6309 Ok(report)
6310 }
6311
6312 /// Bring an archived entry, and every ancestor the journal no longer
6313 /// holds, back into `session`'s journal so `/branch` can select it.
6314 /// `Ok(false)` when `entry_id` is in neither the journal nor the archive.
6315 pub fn restore_archived_journal_chain(
6316 &self,
6317 session: &mut SavedSession,
6318 entry_id: &str,
6319 ) -> io::Result<bool> {
6320 session.ensure_journal();
6321 let session_id = session.metadata.id.clone();
6322 let journal = session.journal.as_mut().expect("journal ensured");
6323 if journal.contains(entry_id) {
6324 return Ok(true);
6325 }
6326 let archive = self.load_journal_archive(&session_id)?;
6327 let by_id: std::collections::HashMap<&str, &SessionEntry> = archive
6328 .iter()
6329 .map(|entry| (entry.id.as_str(), entry))
6330 .collect();
6331 let mut chain = Vec::new();
6332 let mut cursor = Some(entry_id);
6333 while let Some(id) = cursor {
6334 if journal.contains(id) {
6335 break;
6336 }
6337 let Some(entry) = by_id.get(id) else {
6338 if chain.is_empty() {
6339 return Ok(false);
6340 }
6341 return Err(io::Error::new(
6342 io::ErrorKind::InvalidData,
6343 format!("archived entry {entry_id} is missing ancestor {id}"),
6344 ));
6345 };
6346 if chain.len() > by_id.len() {
6347 return Err(io::Error::new(
6348 io::ErrorKind::InvalidData,
6349 "journal archive contains a cycle",
6350 ));
6351 }
6352 chain.push((*entry).clone());
6353 cursor = entry.parent_id.as_deref();
6354 }
6355 let restored: Vec<String> = chain.iter().map(|entry| entry.id.clone()).collect();
6356 journal.entries.extend(chain.into_iter().rev());
6357 validate_saved_journal(journal)?;
6358 // The live app must not later drop what was just brought back.
6359 if let Some(pending) = archived_journal_ids()
6360 .lock()
6361 .unwrap_or_else(std::sync::PoisonError::into_inner)
6362 .get_mut(&session_id)
6363 {
6364 for id in &restored {
6365 pending.remove(id);
6366 }
6367 }
6368 Ok(true)
6369 }
6370
6371 /// Remove the session's journal archive with the session itself. A
6372 /// linked archive directory is not followed.
6373 fn remove_journal_archive(&self, id: &str) -> io::Result<()> {
6374 let _ = self.remove_journal_archive_counted(id)?;
6375 Ok(())
6376 }
6377
6378 fn remove_journal_archive_counted(&self, id: &str) -> io::Result<(usize, u64)> {
6379 let dir = self.sessions_dir.join(JOURNAL_ARCHIVE_DIR);
6380 match fs::symlink_metadata(&dir) {
6381 Ok(metadata)
6382 if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) =>
6383 {
6384 tracing::warn!(
6385 path = %dir.display(),
6386 "journal archive directory is a link; its copies were not removed"
6387 );
6388 return Ok((0, 0));
6389 }
6390 Ok(metadata) if !metadata.is_dir() => return Ok((0, 0)),
6391 Ok(_) => {}
6392 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok((0, 0)),
6393 Err(error) => return Err(error),
6394 }
6395 let mut paths: Vec<PathBuf> = list_journal_archive_segments(&self.sessions_dir, id)?
6396 .into_iter()
6397 .map(|(_, path)| path)
6398 .collect();
6399 paths.push(journal_archive_path(&self.sessions_dir, id)?);
6400 let mut removed_files = 0usize;
6401 let mut removed_bytes = 0u64;
6402 for path in paths {
6403 let bytes = match fs::symlink_metadata(&path) {
6404 Ok(metadata) => {
6405 if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata)
6406 || !metadata.is_file()
6407 {
6408 tracing::warn!(
6409 path = %path.display(),
6410 "journal archive entry is a link or non-file; skipping removal"
6411 );
6412 continue;
6413 }
6414 metadata.len()
6415 }
6416 Err(error) if error.kind() == io::ErrorKind::NotFound => continue,
6417 Err(error) => return Err(error),
6418 };
6419 match fs::remove_file(&path) {
6420 Ok(()) => {
6421 removed_files = removed_files.saturating_add(1);
6422 removed_bytes = removed_bytes.saturating_add(bytes);
6423 }
6424 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
6425 Err(error) => return Err(error),
6426 }
6427 }
6428 if removed_files > 0 {
6429 sync_directory(&dir);
6430 }
6431 archived_journal_ids()
6432 .lock()
6433 .unwrap_or_else(std::sync::PoisonError::into_inner)
6434 .remove(id.trim());
6435 Ok((removed_files, removed_bytes))
6436 }
6437
6438 /// Preserve the exact pre-import session once, before the first graph-
6439 /// bearing session or checkpoint write can replace it.
6440 fn archive_before_first_graph_write(
6441 &self,
6442 session: &SavedSession,
6443 source: &Path,
6444 ) -> std::io::Result<()> {
6445 let writes_graph = session
6446 .work_state
6447 .as_ref()
6448 .and_then(|state| state.graph.as_ref())
6449 .is_some_and(|graph| !graph.is_empty());
6450 if !writes_graph || !source.exists() {
6451 return Ok(());
6452 }
6453 let bytes = fs::read(source)?;
6454 let already_graph_backed = serde_json::from_slice::<SavedSession>(&bytes)
6455 .ok()
6456 .and_then(|saved| saved.work_state)
6457 .and_then(|state| state.graph)
6458 .is_some_and(|graph| !graph.is_empty());
6459 if already_graph_backed {
6460 return Ok(());
6461 }
6462 let archive_dir = self.sessions_dir.join(WORK_GRAPH_IMPORT_ARCHIVE_DIR);
6463 fs::create_dir_all(&archive_dir)?;
6464 let archive =
6465 archive_dir.join(source.file_name().ok_or_else(|| {
6466 io::Error::new(io::ErrorKind::InvalidInput, "invalid session path")
6467 })?);
6468 if !archive.exists() {
6469 write_atomic(&archive, &bytes)?;
6470 }
6471 Ok(())
6472 }
6473
6474 fn read_checkpoint_file(
6475 &self,
6476 path: &Path,
6477 expected_id: Option<&str>,
6478 admission_held: bool,
6479 ) -> io::Result<Option<SavedSession>> {
6480 use std::io::Read as _;
6481 let mut file = match open_private_read_file(path) {
6482 Ok(file) => file,
6483 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
6484 Err(error) => return Err(error),
6485 };
6486 let mut content = String::new();
6487 file.read_to_string(&mut content)?;
6488 let mut session: SavedSession = serde_json::from_str(&content)
6489 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
6490 if session.schema_version > CURRENT_SESSION_SCHEMA_VERSION {
6491 return Err(std::io::Error::new(
6492 std::io::ErrorKind::InvalidData,
6493 format!(
6494 "Checkpoint schema v{} is newer than supported v{}",
6495 session.schema_version, CURRENT_SESSION_SCHEMA_VERSION
6496 ),
6497 ));
6498 }
6499 if expected_id.is_some_and(|id| session.metadata.id != id.trim()) {
6500 return Err(io::Error::new(
6501 io::ErrorKind::InvalidData,
6502 "checkpoint identity mismatch",
6503 ));
6504 }
6505 if let Some(journal) = &session.journal {
6506 validate_saved_journal(journal)?;
6507 }
6508 // A crash after retirement but before checkpoint removal must not
6509 // offer the deleted origin for recovery. Optional accounting damage
6510 // still permits recovery and is projected as incomplete below.
6511 let retired = if admission_held {
6512 let (late_path, _) = self.late_usage_paths(&session.metadata.id)?;
6513 Self::late_usage_is_deleted(&late_path)
6514 } else {
6515 self.with_session_read_lock(&session.metadata.id, Self::late_usage_is_deleted)
6516 };
6517 if retired.unwrap_or(false) {
6518 return Ok(None);
6519 }
6520 session.system_prompt = strip_legacy_truncation_note(session.system_prompt);
6521 self.hydrate_approval_receipts(&mut session)?;
6522 if admission_held {
6523 let (late_path, _) = self.late_usage_paths(&session.metadata.id)?;
6524 Self::apply_late_usage_result(
6525 &mut session.metadata,
6526 Self::load_late_usage_unlocked(&late_path),
6527 );
6528 } else {
6529 self.apply_late_usage_to_metadata(&mut session.metadata);
6530 }
6531 if let Some(id) = expected_id {
6532 let mut admission_entered = false;
6533 let mut capture = || -> io::Result<SessionObservation> {
6534 admission_entered = true;
6535 let observation = self.observe_session_admitted(id)?;
6536 if observation.checkpoint_sha256.as_deref()
6537 != Some(codewhale_runtime::hashing::sha256_hex(content.as_bytes()).as_str())
6538 {
6539 return Err(io::Error::new(
6540 io::ErrorKind::ResourceBusy,
6541 "checkpoint changed during its admitted load",
6542 ));
6543 }
6544 Ok(observation)
6545 };
6546 let observation = if admission_held {
6547 capture()
6548 } else {
6549 self.with_session_observation(id, capture)
6550 .and_then(|observation| {
6551 observation.ok_or_else(Self::retired_session_write_error)
6552 })
6553 };
6554 match observation {
6555 Ok(observation) => {
6556 session.write_receipt = Some(SessionWriteReceipt::observed(observation))
6557 }
6558 Err(error)
6559 if error.kind() == io::ErrorKind::FileTooLarge
6560 || (!admission_entered
6561 && error.kind() != io::ErrorKind::NotFound
6562 && session
6563 .metadata
6564 .cost
6565 .unpriced_reasons
6566 .contains(LATE_USAGE_UNAVAILABLE_REASON)) =>
6567 {
6568 if !self.validate_unadmitted_read(
6569 id,
6570 path,
6571 &codewhale_runtime::hashing::sha256_hex(content.as_bytes()),
6572 admission_held,
6573 )? {
6574 return Ok(None);
6575 }
6576 session.write_receipt = None;
6577 tracing::warn!(session_id = %id, %error, "checkpoint loaded without publication authority");
6578 }
6579 Err(error) => return Err(error),
6580 }
6581 }
6582 Ok(Some(session))
6583 }
6584
6585 /// Load a specific session's crash-recovery checkpoint if present.
6586 pub fn load_session_checkpoint(&self, session_id: &str) -> io::Result<Option<SavedSession>> {
6587 self.load_session_checkpoint_inner(session_id, false)
6588 }
6589
6590 fn load_session_checkpoint_inner(
6591 &self,
6592 session_id: &str,
6593 admission_held: bool,
6594 ) -> io::Result<Option<SavedSession>> {
6595 let path = self.validated_checkpoint_path(session_id)?;
6596 self.read_checkpoint_file(&path, Some(session_id), admission_held)
6597 }
6598
6599 pub fn load_recovery_checkpoint(
6600 &self,
6601 session_id: &str,
6602 ) -> std::io::Result<Option<SavedSession>> {
6603 Ok(self
6604 .recovery_checkpoint_with_source(session_id, true, false)?
6605 .map(|(session, _)| session))
6606 }
6607
6608 fn recovery_checkpoint_with_source(
6609 &self,
6610 session_id: &str,
6611 allow_damaged_current: bool,
6612 admission_held: bool,
6613 ) -> std::io::Result<Option<(SavedSession, bool)>> {
6614 self.validated_checkpoint_path(session_id)?;
6615 let current = self.load_session_checkpoint_inner(session_id, admission_held);
6616 let legacy = match self.legacy_checkpoint_origin() {
6617 Ok(Some(origin)) if origin == session_id => self
6618 .read_checkpoint_file(
6619 &self.checkpoints_dir().join(LEGACY_CHECKPOINT_FILE),
6620 None,
6621 admission_held,
6622 )
6623 .unwrap_or_else(|error| {
6624 tracing::warn!(%error, "legacy checkpoint could not be read; preserving it");
6625 None
6626 })
6627 .filter(|session| session.metadata.id == session_id),
6628 Ok(_) => None,
6629 Err(error) => {
6630 tracing::warn!(%error, "legacy checkpoint could not be read; preserving it");
6631 None
6632 }
6633 };
6634 let current = match current {
6635 Ok(current) => current,
6636 Err(_) if allow_damaged_current && legacy.is_some() => None,
6637 Err(error) => {
6638 return Err(io::Error::new(
6639 error.kind(),
6640 format!(
6641 "checkpoint {} is unreadable and has been preserved. Review the available conversation preview and preserve this recovery file before resuming: {error}",
6642 self.validated_checkpoint_path(session_id)?.display()
6643 ),
6644 ));
6645 }
6646 };
6647 Ok(match (current, legacy) {
6648 (Some(current), Some(legacy))
6649 if legacy.metadata.updated_at > current.metadata.updated_at =>
6650 {
6651 Some((legacy, true))
6652 }
6653 (Some(current), _) => Some((current, false)),
6654 (None, legacy) => legacy.map(|session| (session, true)),
6655 })
6656 }
6657
6658 /// Load the legacy single-slot checkpoint (`checkpoints/latest.json`) if
6659 /// present. Compatibility read only — this release no longer writes it.
6660 pub fn load_legacy_checkpoint(&self) -> std::io::Result<Option<SavedSession>> {
6661 let path = self.checkpoints_dir().join(LEGACY_CHECKPOINT_FILE);
6662 self.read_checkpoint_file(&path, None, false)
6663 }
6664
6665 pub fn legacy_checkpoint_origin(&self) -> io::Result<Option<String>> {
6666 let path = self.checkpoints_dir().join(LEGACY_CHECKPOINT_FILE);
6667 match Self::load_checkpoint_metadata(&path) {
6668 Ok(metadata) => Ok(Some(metadata.id)),
6669 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
6670 Err(error) => Err(error),
6671 }
6672 }
6673
6674 /// Clear one session's crash-recovery checkpoint. Scoped: this can never
6675 /// remove another session's checkpoint file or the legacy slot.
6676 #[cfg(any(test, feature = "test-support"))]
6677 pub fn clear_session_checkpoint(&self, session_id: &str) -> io::Result<()> {
6678 self.with_session_write_admission(session_id, || {
6679 self.clear_session_checkpoint_admitted(session_id)
6680 })
6681 .map(|_| ())
6682 }
6683
6684 fn clear_session_checkpoint_admitted(&self, session_id: &str) -> io::Result<()> {
6685 match fs::remove_file(self.validated_checkpoint_path(session_id)?) {
6686 Ok(()) => Ok(()),
6687 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
6688 Err(error) => Err(error),
6689 }
6690 }
6691
6692 /// Enumerate all crash-recovery checkpoint files (per-session files plus
6693 /// the legacy single slot), sorted most recently modified first. Only
6694 /// file metadata is read here; callers load content per candidate.
6695 pub fn list_checkpoints(&self) -> std::io::Result<Vec<CheckpointRef>> {
6696 let dir = self.checkpoints_dir();
6697 let mut refs = Vec::new();
6698 let entries = match fs::read_dir(&dir) {
6699 Ok(entries) => entries,
6700 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(refs),
6701 Err(err) => return Err(err),
6702 };
6703 for entry in entries {
6704 let entry = entry?;
6705 let path = entry.path();
6706 if path.extension().is_none_or(|ext| ext != "json") {
6707 continue;
6708 }
6709 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
6710 continue;
6711 };
6712 let source = if name == LEGACY_CHECKPOINT_FILE {
6713 CheckpointSource::Legacy
6714 } else if is_offline_queue_file(name) {
6715 // Parked offline queues live in this directory but are not
6716 // crash-recovery checkpoints.
6717 continue;
6718 } else {
6719 let session_id = name.trim_end_matches(".json").to_string();
6720 if self.validated_checkpoint_path(&session_id).is_err() {
6721 continue;
6722 }
6723 CheckpointSource::Session(session_id)
6724 };
6725 let modified = fs::symlink_metadata(&path)?.modified()?;
6726 refs.push(CheckpointRef {
6727 source,
6728 path,
6729 modified,
6730 });
6731 }
6732 refs.sort_by_key(|r| std::cmp::Reverse(r.modified));
6733 Ok(refs)
6734 }
6735
6736 /// Does `session_id` still hold a crash-recovery checkpoint — the
6737 /// durable sign the session ended mid-turn (#5715)?
6738 #[must_use]
6739 pub fn session_has_checkpoint(&self, session_id: &str) -> bool {
6740 self.validated_checkpoint_path(session_id)
6741 .is_ok_and(|path| path.exists())
6742 }
6743
6744 /// The most recent workspace-scoped session that still holds a
6745 /// crash-recovery checkpoint — durable evidence a prior session in this
6746 /// workspace ended mid-turn (#5715). Metadata only; the transcript is
6747 /// never read. `exclude` is the live session's own id: its in-flight
6748 /// checkpoint is current work, not prior work, and engine respawns
6749 /// inside one session must not report the session's own checkpoint.
6750 /// Sessions this process instance created are likewise excluded.
6751 pub fn interrupted_workspace_session(
6752 &self,
6753 workspace: &Path,
6754 exclude: Option<&str>,
6755 ) -> Option<SessionMetadata> {
6756 // Newest-first already; a checkpoint file only survives a session
6757 // that never reached a settled save.
6758 for checkpoint in self.list_checkpoints().ok()? {
6759 let CheckpointSource::Session(id) = &checkpoint.source else {
6760 continue;
6761 };
6762 // A checkpoint another running session is still refreshing is
6763 // that session's in-flight work, not a prior crash.
6764 if Some(id.as_str()) == exclude
6765 || !self.session_from_prior_instance(id)
6766 || self.is_session_live_anywhere(id)
6767 {
6768 continue;
6769 }
6770 // One malformed id or unreadable record must not hide a later
6771 // valid checkpoint — skip and keep scanning.
6772 let metadata = match self.load_session_metadata_by_id(id) {
6773 Ok(metadata) => Ok(metadata),
6774 Err(error) if error.kind() == io::ErrorKind::NotFound => self
6775 .checkpoint_metadata(&checkpoint)
6776 .and_then(|checkpoint| checkpoint.ok_or(error)),
6777 Err(error) => Err(error),
6778 };
6779 match metadata {
6780 Ok(meta) if workspace_scope_matches(&meta.workspace, workspace) => {
6781 return Some(meta);
6782 }
6783 Ok(_) => {}
6784 Err(error) => {
6785 tracing::warn!(session_id = %id, %error, "interrupted session could not be inspected; source retained")
6786 }
6787 }
6788 }
6789 None
6790 }
6791
6792 /// Acquire before loading or editing a queue, including on in-process
6793 /// resume. A per-write lock is insufficient: the second editor's stale
6794 /// snapshot would overwrite the first as soon as its write completed.
6795 pub fn acquire_offline_queue_lease(
6796 &self,
6797 session_id: &str,
6798 ) -> io::Result<std::sync::Arc<OfflineQueueLease>> {
6799 let session_id = self.validated_session_id(session_id)?.to_string();
6800 let directory = self.checkpoints_dir();
6801 fs::create_dir_all(&directory)?;
6802 let path = directory.join(format!("{session_id}.offline_queue.lock"));
6803 let file = fs::OpenOptions::new()
6804 .create(true)
6805 .truncate(false)
6806 .read(true)
6807 .write(true)
6808 .open(path)?;
6809 let mut lock = fd_lock::RwLock::new(file);
6810 let guard = lock.try_write().map_err(|error| {
6811 io::Error::new(
6812 error.kind(),
6813 format!("Cannot open session {session_id}: its queued input is already open in another window, or its previous writes are still finishing ({error})"),
6814 )
6815 })?;
6816 // fd-lock's guard borrows its owner. Retain the underlying descriptor
6817 // instead so this lease can travel with asynchronous writes. Forgetting
6818 // this non-owning guard keeps the OS lock held; the final Arc explicitly
6819 // unlocks in Drop. The OS also releases it when the process crashes.
6820 std::mem::forget(guard);
6821 Ok(std::sync::Arc::new(OfflineQueueLease {
6822 session_id,
6823 _file: lock.into_inner(),
6824 }))
6825 }
6826
6827 /// Park this session's offline queue (queued + draft messages).
6828 ///
6829 /// Queues are keyed per session (`checkpoints/<session_id>.offline_queue.json`)
6830 /// for exactly the reason checkpoints are: concurrent Codewhale instances
6831 /// must never overwrite — or delete — each other's unsent user text.
6832 ///
6833 /// A queue with no session id has no owner to restore it to, so parking is
6834 /// refused rather than written to a shared file where the next boot would
6835 /// destroy it.
6836 pub fn save_offline_queue_state(
6837 &self,
6838 state: &OfflineQueueState,
6839 session_id: Option<&str>,
6840 ) -> std::io::Result<PathBuf> {
6841 let session_id = session_id.ok_or_else(|| {
6842 std::io::Error::new(
6843 std::io::ErrorKind::InvalidInput,
6844 "Offline queue cannot be parked without a session id",
6845 )
6846 })?;
6847 let path = self.validated_offline_queue_path(session_id)?;
6848 fs::create_dir_all(self.checkpoints_dir())?;
6849 let mut owned = state.clone();
6850 // The stamp is redundant with the file name; it stays because the UI's
6851 // restore path still compares it against the live session id.
6852 owned.session_id = Some(self.validated_session_id(session_id)?.to_string());
6853 let content = serde_json::to_string_pretty(&owned)
6854 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
6855 write_atomic(&path, content.as_bytes())?;
6856 Ok(path)
6857 }
6858
6859 /// Load one session's parked offline queue if present.
6860 pub fn load_offline_queue_state(
6861 &self,
6862 session_id: &str,
6863 ) -> std::io::Result<Option<OfflineQueueState>> {
6864 let path = self.validated_offline_queue_path(session_id)?;
6865 Ok(match Self::read_offline_queue_file(&path)? {
6866 Some(state) => Some(state),
6867 None => self.adopt_legacy_offline_queue(session_id, &path)?,
6868 })
6869 }
6870
6871 /// Remove one named session's parked offline queue.
6872 pub fn clear_offline_queue_state_for(&self, session_id: &str) -> std::io::Result<()> {
6873 let path = self.validated_offline_queue_path(session_id)?;
6874 match fs::remove_file(&path) {
6875 Ok(()) => {}
6876 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
6877 Err(error) => return Err(error),
6878 }
6879 Ok(())
6880 }
6881
6882 fn validated_offline_queue_path(&self, session_id: &str) -> std::io::Result<PathBuf> {
6883 let trimmed = self.validated_session_id(session_id)?;
6884 Ok(self
6885 .checkpoints_dir()
6886 .join(format!("{trimmed}{OFFLINE_QUEUE_SUFFIX}")))
6887 }
6888
6889 fn read_offline_queue_file(path: &Path) -> std::io::Result<Option<OfflineQueueState>> {
6890 let content = match fs::read_to_string(path) {
6891 Ok(content) => content,
6892 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
6893 Err(error) => return Err(error),
6894 };
6895 let state: OfflineQueueState = serde_json::from_str(&content)
6896 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
6897 if state.schema_version > CURRENT_QUEUE_SCHEMA_VERSION {
6898 return Err(std::io::Error::new(
6899 std::io::ErrorKind::InvalidData,
6900 format!(
6901 "Offline queue schema v{} is newer than supported v{}",
6902 state.schema_version, CURRENT_QUEUE_SCHEMA_VERSION
6903 ),
6904 ));
6905 }
6906 Ok(Some(state))
6907 }
6908
6909 /// Migrate the pre-per-session global queue (`checkpoints/offline_queue.json`).
6910 ///
6911 /// It holds user-authored text, so it is adopted only by the session it was
6912 /// stamped for, and it is removed only once this session's copy is durably
6913 /// written. A queue stamped for someone else — or for nobody — is left
6914 /// exactly where it is, still readable, for its owner to claim.
6915 fn adopt_legacy_offline_queue(
6916 &self,
6917 session_id: &str,
6918 path: &Path,
6919 ) -> std::io::Result<Option<OfflineQueueState>> {
6920 let legacy = self.checkpoints_dir().join(OFFLINE_QUEUE_FILE);
6921 // A corrupt or future-schema legacy file must not fail this session's
6922 // boot: leave it on disk untouched and start with an empty queue.
6923 let Ok(Some(state)) = Self::read_offline_queue_file(&legacy) else {
6924 return Ok(None);
6925 };
6926 if state.session_id.as_deref() != Some(self.validated_session_id(session_id)?) {
6927 return Ok(None);
6928 }
6929 let content = serde_json::to_string_pretty(&state)
6930 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
6931 fs::create_dir_all(self.checkpoints_dir())?;
6932 write_atomic(path, content.as_bytes())?;
6933 match fs::remove_file(&legacy) {
6934 Ok(()) => {}
6935 // A second instance of the same session can win the adoption
6936 // race: both read the legacy file, both write this session's
6937 // per-session copy, and the twin's remove already retired the
6938 // legacy one. The queue is durably adopted either way, so a
6939 // vanished legacy file is success here, not a boot error.
6940 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
6941 Err(error) => return Err(error),
6942 }
6943 Ok(Some(state))
6944 }
6945
6946 /// Read a session snapshot without repairing tool call/result pairs.
6947 ///
6948 /// This is the correct API for embedding hosts that inspect or update a
6949 /// durable session while an engine may still be executing a tool call.
6950 /// A dangling `tool_use` is not proof of a crashed process in that state.
6951 pub fn load_session_snapshot(&self, id: &str) -> std::io::Result<SavedSession> {
6952 self.load_session_snapshot_with_limit(id, None, false)
6953 }
6954
6955 /// The same protected session parser with an explicit transport byte ceiling.
6956 /// A file within the ceiling is read capped before allocating or parsing its
6957 /// document; a larger one is parsed whole and accepted only when its
6958 /// carried form ([`SavedSession::transport_form`]) is within the ceiling.
6959 pub fn load_session_snapshot_bounded(
6960 &self,
6961 id: &str,
6962 limit: usize,
6963 ) -> io::Result<SavedSession> {
6964 self.load_session_snapshot_with_limit(id, Some(limit), false)
6965 }
6966
6967 pub fn inspect_session_snapshot_bounded(
6968 &self,
6969 id: &str,
6970 limit: usize,
6971 ) -> io::Result<SavedSession> {
6972 use std::io::Read as _;
6973 let path = self.validated_session_path(id)?;
6974 let mut content = Vec::new();
6975 open_private_read_file(&path)?
6976 .take((limit as u64).saturating_add(1))
6977 .read_to_end(&mut content)?;
6978 if content.len() > limit {
6979 return Err(io::Error::new(
6980 io::ErrorKind::InvalidData,
6981 "Saved session exceeds the inspection limit",
6982 ));
6983 }
6984 let mut session = Self::decode_inspected_session(id, &path, &content)?;
6985 session.ensure_journal();
6986 Ok(session)
6987 }
6988
6989 fn decode_inspected_session(id: &str, path: &Path, content: &[u8]) -> io::Result<SavedSession> {
6990 let mut session: SavedSession = serde_json::from_slice(content)
6991 .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
6992 if session.schema_version > CURRENT_SESSION_SCHEMA_VERSION {
6993 return Err(std::io::Error::new(
6994 std::io::ErrorKind::InvalidData,
6995 format!(
6996 "Session schema v{} is newer than supported v{}",
6997 session.schema_version, CURRENT_SESSION_SCHEMA_VERSION
6998 ),
6999 ));
7000 }
7001
7002 if session.metadata.id != id.trim() {
7003 return Err(std::io::Error::new(
7004 std::io::ErrorKind::InvalidData,
7005 format!(
7006 "Session file {} records a different session id",
7007 path.display()
7008 ),
7009 ));
7010 }
7011
7012 session.system_prompt = strip_legacy_truncation_note(session.system_prompt);
7013 if let Some(journal) = session.journal.as_ref() {
7014 validate_saved_journal(journal)?;
7015 }
7016 Ok(session)
7017 }
7018
7019 fn load_session_snapshot_with_limit(
7020 &self,
7021 id: &str,
7022 limit: Option<usize>,
7023 admission_held: bool,
7024 ) -> io::Result<SavedSession> {
7025 use std::io::Read;
7026 let path = self.validated_session_path(id)?;
7027 let mut oversized = false;
7028 let content = match limit {
7029 None => {
7030 let mut content = String::new();
7031 open_private_read_file(&path)?.read_to_string(&mut content)?;
7032 content
7033 }
7034 Some(limit) => {
7035 let mut file = open_private_read_file(&path)?;
7036 if file.metadata()?.len() > limit as u64 {
7037 let before = file.metadata()?.len();
7038 let mib = |bytes: u64| bytes as f64 / 1_048_576.0;
7039 let projected = self
7040 .compact_oversized_session(id, limit as u64)
7041 .map_err(|error| {
7042 io::Error::new(
7043 error.kind(),
7044 format!(
7045 "session exceeds its full-history transport limit and compaction failed: {error}; source retained"
7046 ),
7047 )
7048 })?;
7049 if let Some((projected, pruned_operations)) = projected {
7050 let compaction = if pruned_operations {
7051 "archiving its off-branch history and pruning ended operations"
7052 } else {
7053 "archiving its off-branch history"
7054 };
7055 let session_id = id.trim();
7056 return Err(io::Error::new(
7057 io::ErrorKind::InvalidData,
7058 format!(
7059 "session is {:.1} MiB and the full-history transport limit is {:.1} MiB; {compaction} would still hand over {:.1} MiB, counting the conversation once, so nothing was changed. Run `codewhale sessions export {session_id}` to preserve a full archive (then `/load` the extracted `session.json`), or `codewhale sessions trim {session_id} --apply` to archive the oldest entries and bring this session under the limit",
7060 mib(before),
7061 mib(limit as u64),
7062 mib(projected),
7063 ),
7064 ));
7065 }
7066 file = open_private_read_file(&path)?;
7067 oversized = file.metadata()?.len() > limit as u64;
7068 }
7069 let mut bytes = Vec::new();
7070 if oversized {
7071 file.read_to_end(&mut bytes)?;
7072 } else {
7073 file.take((limit as u64).saturating_add(1))
7074 .read_to_end(&mut bytes)?;
7075 }
7076 if !oversized && bytes.len() > limit {
7077 return Err(io::Error::new(
7078 io::ErrorKind::InvalidData,
7079 "session grew beyond full-history transport bound; source retained",
7080 ));
7081 }
7082 String::from_utf8(bytes)
7083 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?
7084 }
7085 };
7086 let mut session = Self::decode_inspected_session(id, &path, content.as_bytes())?;
7087 session.ensure_journal();
7088 self.hydrate_approval_receipts(&mut session)?;
7089 if admission_held {
7090 let (late_path, _) = self.late_usage_paths(id)?;
7091 Self::apply_late_usage_result(
7092 &mut session.metadata,
7093 Self::load_late_usage_unlocked(&late_path),
7094 );
7095 } else {
7096 self.apply_late_usage_to_metadata(&mut session.metadata);
7097 }
7098 if let Some(limit) = limit.filter(|_| oversized)
7099 && serde_json::to_vec(&session.transport_form())
7100 .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?
7101 .len()
7102 > limit
7103 {
7104 return Err(io::Error::new(
7105 io::ErrorKind::InvalidData,
7106 "session grew beyond full-history transport bound; source retained",
7107 ));
7108 }
7109
7110 let mut admission_entered = false;
7111 let mut capture = || -> io::Result<SessionObservation> {
7112 admission_entered = true;
7113 let observation = self.observe_session_admitted(id)?;
7114 if observation.document_sha256.as_deref()
7115 != Some(codewhale_runtime::hashing::sha256_hex(content.as_bytes()).as_str())
7116 {
7117 return Err(io::Error::new(
7118 io::ErrorKind::ResourceBusy,
7119 "session changed during its admitted load; reopen it",
7120 ));
7121 }
7122 Ok(observation)
7123 };
7124 let observation = if admission_held {
7125 capture()
7126 } else {
7127 self.with_session_observation(id, capture)
7128 .and_then(|observation| observation.ok_or_else(Self::retired_session_write_error))
7129 };
7130 match observation {
7131 Ok(observation) => {
7132 session.write_receipt = Some(SessionWriteReceipt::observed(observation))
7133 }
7134 Err(error)
7135 if error.kind() == io::ErrorKind::FileTooLarge
7136 || (!admission_entered
7137 && error.kind() != io::ErrorKind::NotFound
7138 && session
7139 .metadata
7140 .cost
7141 .unpriced_reasons
7142 .contains(LATE_USAGE_UNAVAILABLE_REASON)) =>
7143 {
7144 if !self.validate_unadmitted_read(
7145 id,
7146 &path,
7147 &codewhale_runtime::hashing::sha256_hex(content.as_bytes()),
7148 admission_held,
7149 )? {
7150 return Err(Self::retired_session_write_error());
7151 }
7152 session.write_receipt = None;
7153 tracing::warn!(session_id = %id, %error, "history loaded without publication authority");
7154 }
7155 Err(error) => return Err(error),
7156 }
7157 Ok(session)
7158 }
7159
7160 /// Load and repair a session after a known process or engine restart.
7161 ///
7162 /// The returned repair remains in memory until the caller persists
7163 /// `recovery.session`. Keeping persistence explicit lets embedding hosts
7164 /// serialize recovery with their own transcript mutation lock.
7165 pub fn recover_session_for_resume(&self, id: &str) -> io::Result<SessionRecovery> {
7166 self.load_session_snapshot(id)
7167 .map(Self::repair_resume_snapshot)
7168 }
7169
7170 fn repair_resume_snapshot(mut session: SavedSession) -> SessionRecovery {
7171 let repair = repair_recovered_session(&mut session);
7172 SessionRecovery {
7173 session,
7174 changed: !repair.is_empty(),
7175 repaired_call_count: repair.repaired_call_ids.len(),
7176 duplicate_result_count: repair.duplicate_result_ids.len(),
7177 orphan_result_count: repair.orphan_result_ids.len(),
7178 }
7179 }
7180
7181 /// Load, repair, and durably persist a session being resumed.
7182 ///
7183 /// Resume is where a crash-repaired history becomes durable: the repaired
7184 /// record replaces the interrupted one so the same repair does not re-run
7185 /// on every later load. A persist failure is logged and the repaired
7186 /// in-memory session is still returned — a failed write-back must not
7187 /// strand the resume.
7188 pub fn resume_session(&self, id: &str) -> std::io::Result<SessionRecovery> {
7189 let recovery = self.resume_session_inner(id, None)?;
7190 // A resume is where a repaired history becomes durable, so the repair
7191 // counts are the dated record of what the conversation lost or had put
7192 // back. They name counts, never message bodies.
7193 codewhale_runtime::audit::log_sensitive_event(
7194 "session.resumed",
7195 serde_json::json!({
7196 "session_id": recovery.session.metadata.id,
7197 "repaired": recovery.changed,
7198 "repaired_call_count": recovery.repaired_call_count,
7199 "duplicate_result_count": recovery.duplicate_result_count,
7200 "orphan_result_count": recovery.orphan_result_count,
7201 "messages": recovery.session.messages.len(),
7202 }),
7203 );
7204 Ok(recovery)
7205 }
7206
7207 fn resume_session_inner(
7208 &self,
7209 id: &str,
7210 workspace: Option<&Path>,
7211 ) -> io::Result<SessionRecovery> {
7212 let check_workspace = |session: &SavedSession| -> io::Result<()> {
7213 if workspace.is_some_and(|workspace| {
7214 !workspace_scope_matches(&session.metadata.workspace, workspace)
7215 }) {
7216 return Err(io::Error::new(
7217 io::ErrorKind::PermissionDenied,
7218 "session belongs to another workspace",
7219 ));
7220 }
7221 Ok(())
7222 };
7223 let mut recovered = None;
7224 let mut admission_entered = false;
7225 let publication = self.with_session_write_admission(id, || {
7226 admission_entered = true;
7227 let session = self.load_session_snapshot_with_limit(id, None, true)?;
7228 check_workspace(&session)?;
7229 let recovery = Self::repair_resume_snapshot(session);
7230 let candidate = recovery.changed.then(|| recovery.session.clone());
7231 recovered = Some(recovery);
7232 let Some(candidate) = candidate else {
7233 return Ok(None);
7234 };
7235 let persisted = self.load_session_write_metadata(id)?;
7236 let metadata =
7237 self.write_session_admitted(candidate, JournalPrune::Keep, true, &persisted)?;
7238 let observation = self.observe_session_admitted(id)?;
7239 if let Some(recovery) = recovered.as_mut() {
7240 recovery.session.metadata = metadata.clone();
7241 recovery.session.write_receipt = Some(SessionWriteReceipt::observed(observation));
7242 }
7243 Ok(Some(metadata.mode.as_deref() == Some("exec")))
7244 });
7245 match publication {
7246 Ok(Some(Some(exec_mode))) => {
7247 if let Err(error) = self.cleanup_old_sessions_for_mode(None, Some(exec_mode)) {
7248 tracing::warn!(session_id = %id, %error, "repaired session was committed but retention could not be inspected");
7249 }
7250 }
7251 Ok(Some(None)) => {}
7252 Ok(None) => return Err(Self::retired_session_write_error()),
7253 Err(error) if recovered.is_some() => {
7254 tracing::warn!(session_id = %id, error_kind = ?error.kind(), %error, "repaired session history could not be persisted; the repair will re-run on the next load");
7255 }
7256 Err(error) if !admission_entered => {
7257 let mut recovery = self.recover_session_for_resume(id)?;
7258 recovery.session.write_receipt = None;
7259 check_workspace(&recovery.session)?;
7260 tracing::warn!(session_id = %id, error_kind = ?error.kind(), %error, "session write admission failed; recovered history was left in memory without publication");
7261 return Ok(recovery);
7262 }
7263 Err(error) => return Err(error),
7264 }
7265 recovered.ok_or_else(|| {
7266 io::Error::other("session recovery completed without a captured history")
7267 })
7268 }
7269
7270 /// [`Self::resume_session`] for a surface that will own and autosave the
7271 /// session: it first reserves the session's live lease, and refuses with
7272 /// `ResourceBusy` when another process has it open
7273 /// ([`Self::reserve_session_for_attach`]). The caller commits the
7274 /// returned lease once the session is applied.
7275 ///
7276 /// A session that was interrupted mid-turn is attached in its interrupted
7277 /// state: its crash checkpoint, when newer than the saved document, is
7278 /// promoted first. Attaching the older document instead dropped the
7279 /// in-flight turn, and the next autosave then cleared the only record of
7280 /// it while the turn's file edits stayed on disk.
7281 pub fn attach_session(&self, id: &str) -> std::io::Result<(SessionRecovery, SessionLease)> {
7282 self.attach_session_in_workspace(id, None)
7283 }
7284
7285 pub fn attach_session_in_workspace(
7286 &self,
7287 id: &str,
7288 workspace: Option<&Path>,
7289 ) -> std::io::Result<(SessionRecovery, SessionLease)> {
7290 let lease = self.reserve_session_for_attach(id)?;
7291 self.promote_interrupted_checkpoint(id, workspace)?;
7292 let recovery = self.resume_session_inner(id, workspace)?;
7293 Ok((recovery, lease))
7294 }
7295
7296 /// Persist `id`'s crash checkpoint as its saved document when the
7297 /// checkpoint is the newer of the two (or there is no document yet), then
7298 /// consume it. Callers hold the session's attach lease. A stale checkpoint
7299 /// never replaces a newer document; an unreadable document and a failed
7300 /// save leave both files as they were. The saved document is verified in
7301 /// full before its checkpoint is consumed under the same write admission.
7302 pub fn promote_interrupted_checkpoint(
7303 &self,
7304 id: &str,
7305 workspace: Option<&Path>,
7306 ) -> io::Result<()> {
7307 let published_mode = self.with_session_write_admission(id, || {
7308 let Some((mut checkpoint, legacy)) = self.recovery_checkpoint_with_source(id, false, true)? else {
7309 return Ok(None);
7310 };
7311 let persisted = self.load_session_write_metadata(id)?;
7312 if workspace.is_some_and(|workspace| !workspace_scope_matches(&checkpoint.metadata.workspace, workspace)) {
7313 return Err(io::Error::new(io::ErrorKind::PermissionDenied, "checkpoint belongs to another workspace"));
7314 }
7315 if let (Some(workspace), Some(saved)) = (workspace, persisted.saved.as_ref())
7316 && !workspace_scope_matches(&saved.workspace, workspace)
7317 {
7318 return Err(io::Error::new(io::ErrorKind::PermissionDenied, "saved session belongs to another workspace"));
7319 }
7320 Self::prepare_session_write(&mut checkpoint, &persisted, true)?;
7321 let published = if let Some(saved) = persisted.saved.as_ref() {
7322 let mut saved_session = self.load_session_snapshot_with_limit(id, None, true)?;
7323 if saved.updated_at >= checkpoint.metadata.updated_at {
7324 let previous_binding = saved_session.metadata.runtime_store.clone();
7325 Self::prepare_session_write(&mut saved_session, &persisted, true)?;
7326 if saved_session.metadata.runtime_store != previous_binding {
7327 Some(self.write_session_admitted(saved_session, JournalPrune::Keep, true, &persisted)?)
7328 } else {
7329 None
7330 }
7331 } else {
7332 Some(self.write_session_admitted(checkpoint, JournalPrune::Keep, true, &persisted)?)
7333 }
7334 } else {
7335 let path = self.validated_session_path(id)?;
7336 if !matches!(fs::symlink_metadata(path), Err(error) if error.kind() == io::ErrorKind::NotFound) {
7337 return Err(io::Error::new(io::ErrorKind::AlreadyExists, "session destination is not vacant"));
7338 }
7339 Some(self.write_session_admitted(checkpoint, JournalPrune::Keep, true, &persisted)?)
7340 };
7341 if !legacy {
7342 self.clear_session_checkpoint_admitted(id)?;
7343 }
7344 Ok(published.map(|metadata| metadata.mode.as_deref() == Some("exec")))
7345 })?.ok_or_else(Self::retired_session_write_error)?;
7346 if let Some(exec_mode) = published_mode {
7347 self.cleanup_old_sessions_for_mode(None, Some(exec_mode))?;
7348 }
7349 Ok(())
7350 }
7351
7352 /// [`Self::attach_session`] with a partial-ID prefix.
7353 pub fn attach_session_by_prefix(
7354 &self,
7355 prefix: &str,
7356 ) -> std::io::Result<(SessionRecovery, SessionLease)> {
7357 self.attach_session(&self.resolve_recoverable_session_id_prefix(prefix)?)
7358 }
7359
7360 /// [`Self::attach_session`] for a session file `/load` has already read.
7361 /// Either way the surface becomes the writer of the id the file names, so
7362 /// a managed record and a foreign file take the same contract: the id's
7363 /// live lease is reserved first and refused while another window has it
7364 /// open. A managed record then resumes through the manager so its repair
7365 /// is persisted in place; a foreign file is not ours to rewrite, so its
7366 /// journal projection and repair stay in memory.
7367 pub fn attach_session_file(
7368 &self,
7369 parsed: SavedSession,
7370 path: &Path,
7371 ) -> std::io::Result<(SavedSession, SessionLease)> {
7372 if self.owns_session_path(&parsed.metadata.id, path) {
7373 return self
7374 .attach_session(&parsed.metadata.id)
7375 .map(|(recovery, lease)| (recovery.session, lease));
7376 }
7377 let lease = self.reserve_session_for_attach(&parsed.metadata.id)?;
7378 match self.load_session_metadata_by_id(&parsed.metadata.id) {
7379 Ok(saved) if saved.updated_at > parsed.metadata.updated_at => {
7380 return Err(std::io::Error::new(
7381 std::io::ErrorKind::AlreadyExists,
7382 format!(
7383 "session {} has a newer saved record than {}; continue it with `/resume {}`, or move that record aside before loading this older copy",
7384 parsed.metadata.id,
7385 path.display(),
7386 parsed.metadata.id
7387 ),
7388 ));
7389 }
7390 Ok(_) => {}
7391 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
7392 Err(error) => return Err(error),
7393 }
7394 let mut session = parsed;
7395 session.write_receipt = None;
7396 if let Some(journal) = session.journal.as_ref() {
7397 validate_saved_journal(journal)?;
7398 }
7399 session.ensure_journal();
7400 repair_recovered_session(&mut session);
7401 Ok((session, lease))
7402 }
7403
7404 /// [`Self::resume_session`] with a partial-ID prefix.
7405 pub fn resume_session_by_prefix(&self, prefix: &str) -> std::io::Result<SessionRecovery> {
7406 self.resume_session(&self.resolve_session_id_prefix(prefix)?)
7407 }
7408
7409 /// True when `path` is this store's durable record for `id`. File-based
7410 /// session loads use it to decide whether a repair may be written back in
7411 /// place or must stay in memory (a foreign file is not ours to rewrite).
7412 pub fn owns_session_path(&self, id: &str, path: &Path) -> bool {
7413 let Ok(managed) = self.validated_session_path(id) else {
7414 return false;
7415 };
7416 managed == path
7417 || managed
7418 .canonicalize()
7419 .is_ok_and(|managed| path.canonicalize().is_ok_and(|path| managed == path))
7420 }
7421
7422 /// Load a session by ID for the standalone CodeWhale resume flow.
7423 ///
7424 /// This preserves the historical recovery behavior for existing callers.
7425 /// Embedding hosts performing ordinary runtime reads should use
7426 /// [`Self::load_session_snapshot`] instead.
7427 pub fn load_session(&self, id: &str) -> std::io::Result<SavedSession> {
7428 self.recover_session_for_resume(id)
7429 .map(|recovery| recovery.session)
7430 }
7431
7432 /// Load a session by partial ID prefix
7433 pub fn load_session_by_prefix(&self, prefix: &str) -> std::io::Result<SavedSession> {
7434 self.load_session(&self.resolve_session_id_prefix(prefix)?)
7435 }
7436
7437 /// Resolve a unique ID without applying resume-time repair to its record.
7438 pub fn resolve_session_id_prefix(&self, prefix: &str) -> std::io::Result<String> {
7439 self.resolve_session_id_prefix_inner(prefix, false)
7440 }
7441
7442 pub fn resolve_recoverable_session_id_prefix(&self, prefix: &str) -> std::io::Result<String> {
7443 self.resolve_session_id_prefix_inner(prefix, true)
7444 }
7445
7446 fn resolve_session_id_prefix_inner(
7447 &self,
7448 prefix: &str,
7449 include_recovery: bool,
7450 ) -> std::io::Result<String> {
7451 let mut matches: Vec<_> = self
7452 .list_sessions()?
7453 .into_iter()
7454 .map(|session| session.id)
7455 .filter(|id| id.starts_with(prefix))
7456 .collect();
7457 for checkpoint in if include_recovery {
7458 self.list_checkpoints()?
7459 } else {
7460 Vec::new()
7461 } {
7462 let id = match &checkpoint.source {
7463 CheckpointSource::Session(id) => Some(id.clone()),
7464 CheckpointSource::Legacy => self
7465 .checkpoint_metadata(&checkpoint)?
7466 .map(|metadata| metadata.id),
7467 };
7468 if let Some(id) = id.filter(|id| id.starts_with(prefix)) {
7469 matches.push(id);
7470 }
7471 }
7472 matches.sort();
7473 matches.dedup();
7474
7475 match matches.len() {
7476 0 => Err(std::io::Error::new(
7477 std::io::ErrorKind::NotFound,
7478 format!("No session found with prefix: {prefix}"),
7479 )),
7480 1 => Ok(matches[0].clone()),
7481 _ => Err(std::io::Error::new(
7482 std::io::ErrorKind::InvalidInput,
7483 format!(
7484 "Ambiguous prefix '{}' matches {} sessions",
7485 prefix,
7486 matches.len()
7487 ),
7488 )),
7489 }
7490 }
7491
7492 /// List all saved sessions, sorted by most recently updated
7493 pub fn list_sessions(&self) -> std::io::Result<Vec<SessionMetadata>> {
7494 Ok(self
7495 .list_session_records()?
7496 .into_iter()
7497 .map(|(_, mut metadata)| {
7498 self.apply_late_usage_to_metadata(&mut metadata);
7499 metadata
7500 })
7501 .collect())
7502 }
7503
7504 pub fn list_sessions_lenient(&self) -> Vec<SessionMetadata> {
7505 let catalog = match self.scan_session_records() {
7506 Ok(catalog) => catalog,
7507 Err(error) => {
7508 tracing::warn!(%error, "session listing failed; showing no sessions");
7509 return Vec::new();
7510 }
7511 };
7512 if let Some(warning) = catalog.warning() {
7513 tracing::warn!(%warning, "session listing is incomplete; showing the readable ones");
7514 }
7515 let mut sessions: Vec<_> = catalog
7516 .records
7517 .into_iter()
7518 .map(|(_, mut metadata)| {
7519 self.apply_late_usage_to_metadata(&mut metadata);
7520 metadata
7521 })
7522 .collect();
7523 sessions.sort_by_key(|session| std::cmp::Reverse(session.updated_at));
7524 sessions
7525 }
7526
7527 pub fn list_sessions_with_recovery(
7528 &self,
7529 ) -> std::io::Result<(
7530 Vec<SessionMetadata>,
7531 std::collections::HashSet<String>,
7532 Option<String>,
7533 )> {
7534 let catalog = self.scan_session_records()?;
7535 let mut warning = catalog.warning();
7536 let mut sessions: Vec<_> = catalog
7537 .records
7538 .into_iter()
7539 .map(|(_, mut metadata)| {
7540 self.apply_late_usage_to_metadata(&mut metadata);
7541 metadata
7542 })
7543 .collect();
7544 let mut positions: std::collections::HashMap<String, usize> = sessions
7545 .iter()
7546 .enumerate()
7547 .map(|(index, session)| (session.id.clone(), index))
7548 .collect();
7549 let saved: std::collections::HashSet<String> = positions.keys().cloned().collect();
7550 let mut recovery = std::collections::HashSet::new();
7551 let checkpoints = match self.list_checkpoints() {
7552 Ok(checkpoints) => checkpoints,
7553 Err(error) => {
7554 warning.get_or_insert_with(|| error.to_string());
7555 Vec::new()
7556 }
7557 };
7558 for checkpoint in checkpoints {
7559 if let CheckpointSource::Session(id) = &checkpoint.source
7560 && self.is_session_live_anywhere(id)
7561 {
7562 continue;
7563 }
7564 let metadata = match self.checkpoint_metadata(&checkpoint) {
7565 Ok(Some(metadata)) => metadata,
7566 Ok(None) => continue,
7567 Err(error) => {
7568 warning.get_or_insert_with(|| error.to_string());
7569 continue;
7570 }
7571 };
7572 let id = &metadata.id;
7573 if self.is_session_live_anywhere(id) {
7574 continue;
7575 }
7576 if let Some(index) = positions.get(id).copied() {
7577 let existing = &mut sessions[index];
7578 if saved.contains(id) && metadata.updated_at > existing.updated_at {
7579 if !workspace_scope_matches(&metadata.workspace, &existing.workspace) {
7580 warning.get_or_insert_with(|| "recovery checkpoint and saved session belong to different workspaces".to_string());
7581 continue;
7582 }
7583 recovery.insert(id.clone());
7584 let mut metadata = metadata;
7585 metadata.title = existing.title.clone();
7586 metadata.title_is_custom = existing.title_is_custom;
7587 metadata.archived = existing.archived;
7588 metadata.created_at = existing.created_at;
7589 metadata.parent_session_id = existing.parent_session_id.clone();
7590 metadata.forked_from_message_count = existing.forked_from_message_count;
7591 metadata.runtime_store = existing.runtime_store.clone();
7592 *existing = metadata;
7593 } else if recovery.contains(id)
7594 && !saved.contains(id)
7595 && metadata.updated_at > existing.updated_at
7596 {
7597 *existing = metadata;
7598 }
7599 continue;
7600 }
7601 let Ok(path) = self.validated_session_path(id) else {
7602 continue;
7603 };
7604 if !matches!(fs::symlink_metadata(path), Err(error) if error.kind() == io::ErrorKind::NotFound)
7605 {
7606 continue;
7607 }
7608 recovery.insert(id.clone());
7609 positions.insert(id.clone(), sessions.len());
7610 sessions.push(metadata);
7611 }
7612 sessions.sort_by_key(|session| std::cmp::Reverse(session.updated_at));
7613 Ok((sessions, recovery, warning))
7614 }
7615
7616 pub fn checkpoint_metadata(
7617 &self,
7618 checkpoint: &CheckpointRef,
7619 ) -> io::Result<Option<SessionMetadata>> {
7620 let metadata = Self::load_checkpoint_metadata(&checkpoint.path)?;
7621 let id = &metadata.id;
7622 self.validated_checkpoint_path(id)?;
7623 if matches!(&checkpoint.source, CheckpointSource::Session(name) if name != id) {
7624 return Err(io::Error::new(
7625 io::ErrorKind::InvalidData,
7626 "checkpoint identity mismatch",
7627 ));
7628 }
7629 if self.with_session_read_lock(id, Self::late_usage_is_deleted)? {
7630 return Ok(None);
7631 }
7632 Ok(Some(metadata))
7633 }
7634
7635 fn load_checkpoint_metadata(path: &Path) -> io::Result<SessionMetadata> {
7636 Self::load_session_metadata(path)
7637 }
7638
7639 /// [`Self::list_sessions`] without the late-usage cost overlay, keeping
7640 /// the file each record was read from.
7641 /// A record's file is not always `<id>.json`: early builds wrote
7642 /// `session_<timestamp>.json`, and retention must address those by path.
7643 fn list_session_records(&self) -> io::Result<Vec<(PathBuf, SessionMetadata)>> {
7644 self.scan_session_records()?.into_complete()
7645 }
7646
7647 fn is_session_document(path: &Path) -> bool {
7648 path.extension().is_some_and(|ext| ext == "json")
7649 && path
7650 .file_stem()
7651 .and_then(|stem| stem.to_str())
7652 .is_some_and(|stem| {
7653 stem != SESSION_BOOT_OWNERS_STEM
7654 && codewhale_runtime::artifacts::is_valid_session_id(stem)
7655 })
7656 }
7657
7658 pub fn saved_session_count(&self) -> io::Result<usize> {
7659 let mut count = 0;
7660 for entry in fs::read_dir(&self.sessions_dir)? {
7661 let path = entry?.path();
7662 if !Self::is_session_document(&path) {
7663 continue;
7664 }
7665 if let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) {
7666 match self.with_session_read_lock(stem, Self::late_usage_is_deleted) {
7667 Ok(true) => continue,
7668 Ok(false) => {}
7669 Err(error) => {
7670 tracing::warn!(session_id = %stem, %error, "late usage deletion check failed during session count");
7671 }
7672 }
7673 }
7674 count += 1;
7675 }
7676 Ok(count)
7677 }
7678
7679 fn scan_session_records(&self) -> io::Result<SessionCatalog> {
7680 let mut catalog = SessionCatalog::default();
7681 for entry in fs::read_dir(&self.sessions_dir)? {
7682 let entry = match entry {
7683 Ok(entry) => entry,
7684 Err(error) => {
7685 catalog.failures.push((self.sessions_dir.clone(), error));
7686 continue;
7687 }
7688 };
7689 let path = entry.path();
7690 if !Self::is_session_document(&path) {
7691 continue;
7692 }
7693 match Self::load_session_metadata(&path) {
7694 Ok(metadata) => {
7695 match self.with_session_read_lock(&metadata.id, Self::late_usage_is_deleted) {
7696 Ok(true) => continue,
7697 Ok(false) => catalog.records.push((path, metadata)),
7698 Err(error) => {
7699 tracing::warn!(session_id = %metadata.id, %error, "late usage deletion check failed during catalog scan");
7700 catalog.records.push((path, metadata));
7701 }
7702 }
7703 }
7704 Err(error) => catalog.failures.push((path, error)),
7705 }
7706 }
7707 catalog
7708 .records
7709 .sort_by_key(|(_, metadata)| std::cmp::Reverse(metadata.updated_at));
7710 Ok(catalog)
7711 }
7712
7713 /// Set the durable archive flag on a saved session and return the
7714 /// resulting metadata.
7715 ///
7716 /// This is the single writer for the flag: the picker, the `/sessions`
7717 /// command, and `PATCH /v1/sessions/{id}` all route through it so the TUI
7718 /// and the web dashboard cannot drift into two archive notions. A no-op
7719 /// call (already in the requested state) still returns the metadata and
7720 /// does not rewrite the file.
7721 pub fn set_session_archived(
7722 &self,
7723 id: &str,
7724 archived: bool,
7725 mutator: SessionMutator,
7726 ) -> std::io::Result<SessionMetadata> {
7727 self.mutate_session_lifecycle(id, mutator, |metadata| {
7728 if metadata.archived == archived {
7729 return false;
7730 }
7731 metadata.archived = archived;
7732 true
7733 })
7734 }
7735
7736 /// Rename a saved session and return the resulting metadata.
7737 ///
7738 /// Titles are trimmed and bounded to [`MAX_SESSION_TITLE_CHARS`]
7739 /// characters (counted in `char`s, not bytes, so a CJK or emoji title is
7740 /// not truncated mid-scalar). Created-at and fork lineage are untouched.
7741 pub fn rename_session(
7742 &self,
7743 id: &str,
7744 title: &str,
7745 mutator: SessionMutator,
7746 ) -> std::io::Result<SessionMetadata> {
7747 let title = normalize_session_title(title)?;
7748 self.mutate_session_lifecycle(id, mutator, |metadata| {
7749 if metadata.title == title && metadata.title_is_custom {
7750 return false;
7751 }
7752 metadata.title = title;
7753 metadata.title_is_custom = true;
7754 true
7755 })
7756 }
7757
7758 /// Load only the metadata from a session file within a bounded prefix.
7759 pub fn load_session_metadata(path: &Path) -> io::Result<SessionMetadata> {
7760 use std::io::Read as _;
7761
7762 const PREFIX_BYTES: usize = 64 * 1024;
7763 let mut file = open_private_read_file(path)?;
7764 let mut bytes = Vec::with_capacity(PREFIX_BYTES);
7765 let mut target = PREFIX_BYTES;
7766 loop {
7767 let requested = target - bytes.len();
7768 let count = file
7769 .by_ref()
7770 .take(requested as u64)
7771 .read_to_end(&mut bytes)?;
7772 let text = utf8_prefix(&bytes);
7773 const SCHEMA_KEY: &[u8] = b"\"schema_version\"";
7774 if let Some(offset) = find_json_key(text.as_bytes(), SCHEMA_KEY)
7775 && let Some(value) = text[offset + SCHEMA_KEY.len()..]
7776 .trim_start()
7777 .strip_prefix(':')
7778 && let Some(Ok(version)) = serde_json::Deserializer::from_str(value)
7779 .into_iter::<u64>()
7780 .next()
7781 && version > u64::from(CURRENT_SESSION_SCHEMA_VERSION)
7782 {
7783 return Err(io::Error::new(
7784 io::ErrorKind::InvalidData,
7785 format!(
7786 "Session schema v{version} is newer than supported v{CURRENT_SESSION_SCHEMA_VERSION}; source retained"
7787 ),
7788 ));
7789 }
7790 if let Some(mut metadata) = extract_top_level_metadata(&bytes) {
7791 apply_legacy_title_recovery(&mut metadata, &bytes);
7792 return Ok(metadata);
7793 }
7794 if count < requested {
7795 return Err(io::Error::new(
7796 io::ErrorKind::InvalidData,
7797 "session file missing parseable `metadata` block",
7798 ));
7799 }
7800 if target == SESSION_METADATA_READ_LIMIT {
7801 return Err(io::Error::new(
7802 io::ErrorKind::FileTooLarge,
7803 "session metadata could not be read within the 16 MiB inspection limit; the file was left unchanged",
7804 ));
7805 }
7806 target = (target * 2).min(SESSION_METADATA_READ_LIMIT);
7807 }
7808 }
7809
7810 /// Whether `remove_session` has anything of `id`'s to act on: its
7811 /// document, a recovery checkpoint (its own, or the legacy slot it
7812 /// originated), or a deletion marker whose cleanup a retry finishes. The
7813 /// same test `remove_session` repeats under the session's lock, made
7814 /// before any lease or lock file is created for the id.
7815 fn session_may_have_records(&self, id: &str, path: &Path) -> io::Result<bool> {
7816 match fs::symlink_metadata(path) {
7817 Ok(_) => return Ok(true),
7818 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
7819 Err(error) => return Err(error),
7820 }
7821 if let Ok(checkpoint) = self.validated_checkpoint_path(id)
7822 && checkpoint.try_exists()?
7823 {
7824 return Ok(true);
7825 }
7826 if matches!(self.legacy_checkpoint_origin(), Ok(Some(origin)) if origin == id.trim()) {
7827 return Ok(true);
7828 }
7829 let (late_path, _) = self.late_usage_paths(id)?;
7830 Self::late_usage_is_deleted(&late_path)
7831 }
7832
7833 /// Delete a session and its recovery checkpoints, retiring its origin.
7834 pub fn delete_session(&self, id: &str) -> std::io::Result<()> {
7835 self.remove_session(id, SessionRemoval::Explicit)
7836 }
7837
7838 /// Remove the pre-import copy of `session_path` that the first
7839 /// graph-bearing write kept (see `archive_before_first_graph_write`): it is
7840 /// the same transcript, so a deleted session must not survive in it.
7841 ///
7842 /// A linked archive directory is not followed, as the late-usage store
7843 /// refuses one: deletion must not reach a same-named file elsewhere.
7844 fn remove_import_archive_copy(&self, session_path: &Path) -> io::Result<()> {
7845 let Some(name) = session_path.file_name() else {
7846 return Ok(());
7847 };
7848 let dir = self.sessions_dir.join(WORK_GRAPH_IMPORT_ARCHIVE_DIR);
7849 match fs::symlink_metadata(&dir) {
7850 Ok(metadata)
7851 if codewhale_util::path_identity::metadata_is_link_or_reparse(&metadata) =>
7852 {
7853 tracing::warn!(
7854 path = %dir.display(),
7855 "work-graph import archive is a link; its copies were not removed"
7856 );
7857 return Ok(());
7858 }
7859 Ok(_) => {}
7860 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
7861 Err(error) => return Err(error),
7862 }
7863 match fs::remove_file(dir.join(name)) {
7864 Ok(()) => {
7865 sync_directory(&dir);
7866 Ok(())
7867 }
7868 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
7869 Err(error) => Err(error),
7870 }
7871 }
7872
7873 fn remove_session(&self, id: &str, removal: SessionRemoval) -> std::io::Result<()> {
7874 let path = self.validated_session_path(id)?;
7875 // Reserving the lease creates `.late-usage/<id>.live`; an id with
7876 // nothing to remove must not leave one behind. The authoritative
7877 // check below repeats this under the session's lock.
7878 if !self.session_may_have_records(id, &path)? {
7879 return Err(io::Error::new(
7880 io::ErrorKind::NotFound,
7881 format!("Session '{}' not found", id.trim()),
7882 ));
7883 }
7884 let _lease = self.reserve_session_for_external_write(id)?;
7885 // Older ordinary snapshots may use a name reserved by the checkpoint
7886 // directory. Such a name must never address its shared legacy files.
7887 let checkpoint = self.validated_checkpoint_path(id).ok();
7888 let (late_path, lock_path) = self.ensure_late_usage_paths(id)?;
7889 let lock_file = open_private_lock_file(&lock_path)?;
7890 let mut lock = fd_lock::RwLock::new(lock_file);
7891 let _guard = lock.write()?;
7892 let already_deleted = Self::late_usage_is_deleted(&late_path)?;
7893 let legacy_origin = self.legacy_checkpoint_origin();
7894 if matches!(removal, SessionRemoval::Explicit)
7895 && let Err(error) = &legacy_origin
7896 {
7897 return Err(io::Error::new(
7898 error.kind(),
7899 format!(
7900 "cannot verify the shared legacy checkpoint before deleting this session: {error}"
7901 ),
7902 ));
7903 }
7904 let owns_legacy_checkpoint =
7905 matches!(&legacy_origin, Ok(Some(origin)) if origin == id.trim());
7906 if matches!(removal, SessionRemoval::Explicit) && owns_legacy_checkpoint && !already_deleted
7907 {
7908 return Err(io::Error::other(
7909 "this session has a shared legacy checkpoint; remove that checkpoint separately before deleting the session",
7910 ));
7911 }
7912 let has_recovery = match checkpoint.as_ref() {
7913 Some(path) => path.try_exists()?,
7914 None => false,
7915 } || owns_legacy_checkpoint;
7916 if !already_deleted {
7917 // An unknown id must not acquire a deletion marker. A prior
7918 // tombstone, however, lets a retry finish interrupted cleanup.
7919 match fs::symlink_metadata(&path) {
7920 Ok(_) => {}
7921 Err(error) if error.kind() == io::ErrorKind::NotFound && has_recovery => {}
7922 Err(error) => return Err(error),
7923 }
7924 }
7925 if matches!(removal, SessionRemoval::Retention) && !already_deleted {
7926 // Retention never acts on an uncertain origin. An unreadable
7927 // legacy checkpoint may be this id's crash recovery, and a
7928 // damaged recovery leaves the ordinary snapshot as the only
7929 // readable copy of the conversation. Fail closed: keep every byte
7930 // and let the caller skip this record.
7931 if let Err(error) = &legacy_origin {
7932 return Err(io::Error::new(
7933 error.kind(),
7934 format!(
7935 "retention left session '{}' untouched: the legacy checkpoint's origin is unreadable ({error})",
7936 id.trim()
7937 ),
7938 ));
7939 }
7940 }
7941 if matches!(removal, SessionRemoval::Retention) && has_recovery && !already_deleted {
7942 // Retention owns the ordinary snapshot, not crash recovery. Keep
7943 // the origin and its accounting/evidence writable for resume.
7944 match fs::remove_file(&path) {
7945 Ok(()) => {}
7946 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
7947 Err(error) => return Err(error),
7948 }
7949 // The pre-import copy is an older ordinary snapshot, not recovery.
7950 let result = self.remove_import_archive_copy(&path);
7951 sync_directory(&self.sessions_dir);
7952 return result;
7953 }
7954 // The store this document is bound to is named by its binding, not by
7955 // its id: a host store usually sits under another conversation's
7956 // directory. Read it before the document is gone (#6144 P2).
7957 let bound_store = match self.load_session_metadata_by_id_raw(id) {
7958 Ok(metadata) => metadata.runtime_store,
7959 Err(error) if error.kind() == io::ErrorKind::NotFound => None,
7960 Err(error) => return Err(error),
7961 };
7962 self.save_session_goal(id, None)?;
7963 // Publish the tombstone before removing data. A crash or a delayed
7964 // callback can no longer re-create this session's accounting. The
7965 // stable lock inode must never be removed or atomically replaced.
7966 if !already_deleted {
7967 write_atomic(&late_path.with_extension("deleted"), LATE_USAGE_DELETED)?;
7968 }
7969 match fs::remove_file(&path) {
7970 Ok(()) => {}
7971 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
7972 Err(error) => return Err(error),
7973 }
7974 match fs::remove_file(&late_path) {
7975 Ok(()) => {
7976 if let Some(parent) = late_path.parent()
7977 && parent != self.sessions_dir.as_path()
7978 {
7979 sync_directory(parent);
7980 }
7981 }
7982 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
7983 Err(error) => return Err(error),
7984 }
7985 if let Some(checkpoint) = checkpoint {
7986 match fs::remove_file(&checkpoint) {
7987 Ok(()) => {
7988 if let Some(parent) = checkpoint.parent()
7989 && parent != self.sessions_dir.as_path()
7990 {
7991 sync_directory(parent);
7992 }
7993 }
7994 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
7995 Err(error) => return Err(error),
7996 }
7997 }
7998 self.remove_import_archive_copy(&path)?;
7999 self.remove_journal_archive(id)?;
8000 self.clear_session_boot_owner(id);
8001 let session_dir = self.sessions_dir.join(id.trim());
8002 let mut removed_in_session_dir = false;
8003 if session_dir.exists() {
8004 if codewhale_util::path_identity::metadata_is_link_or_reparse(&fs::symlink_metadata(
8005 &session_dir,
8006 )?) {
8007 // Preserve remove_dir_all's existing no-follow behavior.
8008 fs::remove_dir_all(&session_dir)?;
8009 sync_directory(&self.sessions_dir);
8010 return Ok(());
8011 }
8012 // Other conversations and automations can share this host's Runtime
8013 // authority. Deleting a transcript must never delete that store —
8014 // including a `runtime-recovered-*` sibling, which another
8015 // document may be bound to.
8016 for entry in fs::read_dir(&session_dir)? {
8017 let entry = entry?;
8018 if is_runtime_store_dir_name(&entry.file_name()) {
8019 continue;
8020 }
8021 if entry.file_type()?.is_dir() {
8022 fs::remove_dir_all(entry.path())?;
8023 } else {
8024 fs::remove_file(entry.path())?;
8025 }
8026 removed_in_session_dir = true;
8027 }
8028 }
8029 self.retire_released_stores(id, bound_store);
8030 if session_dir.is_dir() && fs::read_dir(&session_dir)?.next().is_none() {
8031 fs::remove_dir(&session_dir)?;
8032 } else if removed_in_session_dir && session_dir.is_dir() {
8033 sync_directory(&session_dir);
8034 }
8035 sync_directory(&self.sessions_dir);
8036 Ok(())
8037 }
8038
8039 /// Set aside the stores a deleted document released — the one its
8040 /// binding names, and any left under its own directory — when nothing
8041 /// else binds them and they hold no work. Never unlinks; a store in use,
8042 /// holding work, or bound elsewhere stays exactly where it is (#6144 P2).
8043 fn retire_released_stores(
8044 &self,
8045 id: &str,
8046 bound_store: Option<crate::runtime_threads::RuntimeStoreBinding>,
8047 ) {
8048 let mut candidates: Vec<PathBuf> = bound_store
8049 .map(|binding| binding.data_dir)
8050 .into_iter()
8051 .collect();
8052 if let Ok(entries) = fs::read_dir(self.sessions_dir.join(id.trim())) {
8053 candidates.extend(
8054 entries
8055 .flatten()
8056 .filter(|entry| is_runtime_store_dir_name(&entry.file_name()))
8057 .map(|entry| entry.path()),
8058 );
8059 }
8060 for store in candidates {
8061 crate::session_reconcile::retire_unbound_store(self, &store, "session deleted");
8062 }
8063 }
8064
8065 /// Clean up old sessions to stay within each mode's active cap.
8066 #[cfg(any(test, feature = "test-support"))]
8067 pub fn cleanup_old_sessions(&self) -> std::io::Result<()> {
8068 self.cleanup_old_sessions_keeping(None)
8069 }
8070
8071 /// As `Self::cleanup_old_sessions`, but never touches `keep` — the
8072 /// session being resumed at boot. Without this, a background cleanup that
8073 /// races session restore can retire the just-resumed session when 50+
8074 /// newer records exist (its `updated_at` is not bumped until first save).
8075 ///
8076 /// The cap counts *active* transcripts separately for exec and interactive
8077 /// modes: archived records sit outside it until the user prunes them, and
8078 /// empty auto-created stubs get their own small cap per mode so they can
8079 /// never push a real transcript out (#6136, #6137).
8080 /// A transcript past the cap is archived, never unlinked; the store's
8081 /// destructive paths stay the explicit user actions.
8082 pub fn cleanup_old_sessions_keeping(&self, keep: Option<&str>) -> std::io::Result<()> {
8083 self.cleanup_old_sessions_for_mode(keep, None)
8084 }
8085
8086 fn cleanup_old_sessions_for_mode(
8087 &self,
8088 keep: Option<&str>,
8089 exec_mode: Option<bool>,
8090 ) -> std::io::Result<()> {
8091 // Archiving saves the record, and every save runs retention again.
8092 // Drain a backlog in one pass here instead of nesting one cleanup per
8093 // archived transcript.
8094 if self
8095 .retention_in_progress
8096 .swap(true, std::sync::atomic::Ordering::SeqCst)
8097 {
8098 return Ok(());
8099 }
8100 let result = self.cleanup_old_sessions_inner(keep, exec_mode);
8101 self.retention_in_progress
8102 .store(false, std::sync::atomic::Ordering::SeqCst);
8103 result
8104 }
8105
8106 fn cleanup_old_sessions_inner(
8107 &self,
8108 keep: Option<&str>,
8109 exec_mode: Option<bool>,
8110 ) -> std::io::Result<()> {
8111 let catalog = self.scan_session_records()?;
8112 if let Some(warning) = catalog.warning() {
8113 tracing::warn!(target: "session", %warning, "retention left sessions untouched because the catalog is incomplete");
8114 return Ok(());
8115 }
8116 let records = catalog.records;
8117
8118 // What retention owes each class (#6136/#6137): archived records are
8119 // already outside the cap; empty auto-created stubs are junk the
8120 // product writes on every boot and are capped apart so they can never
8121 // occupy a transcript's slot; exec and interactive sessions carry
8122 // independent MAX_SESSIONS windows.
8123 let mut active: [Vec<&SessionMetadata>; 2] = Default::default();
8124 let mut stubs: [Vec<(&Path, &SessionMetadata)>; 2] = Default::default();
8125 for (path, session) in &records {
8126 let is_exec = session.mode.as_deref() == Some("exec");
8127 if session.archived || exec_mode.is_some_and(|expected| expected != is_exec) {
8128 continue;
8129 }
8130 let mode = usize::from(is_exec);
8131 if is_empty_auto_created_session(session) {
8132 stubs[mode].push((path, session));
8133 } else {
8134 active[mode].push(session);
8135 }
8136 }
8137
8138 for session in active
8139 .iter()
8140 .flat_map(|sessions| sessions.iter().skip(MAX_SESSIONS))
8141 {
8142 if keep.is_some_and(|id| id == session.id) {
8143 continue;
8144 }
8145 // `External` keeps the live-session guard honest: a record
8146 // another process is driving is not ours to retire.
8147 if let Err(err) = self.set_session_archived(&session.id, true, SessionMutator::External)
8148 {
8149 tracing::warn!(
8150 target: "session",
8151 session = session.id,
8152 ?err,
8153 "retention could not archive a transcript past the cap; it stays active"
8154 );
8155 }
8156 }
8157
8158 for (listed_path, session) in stubs
8159 .iter()
8160 .flat_map(|sessions| sessions.iter().skip(MAX_EMPTY_SESSION_STUBS))
8161 {
8162 if keep.is_some_and(|id| id == session.id) {
8163 continue;
8164 }
8165 if let Err(err) = self.retire_empty_stub(listed_path, &session.id) {
8166 tracing::warn!(
8167 target: "session",
8168 session = session.id,
8169 ?err,
8170 "retention could not remove an empty session stub"
8171 );
8172 }
8173 }
8174
8175 // A directory without a top-level session snapshot is not proof of an
8176 // orphan: runtime threads and automations own independent durable stores,
8177 // including in other processes and before their first snapshot. Retention
8178 // only retires records it listed above; never infer authority to delete
8179 // other directories from an absent transcript or process-local claim.
8180
8181 Ok(())
8182 }
8183
8184 /// Retire one empty auto-created stub that retention listed at
8185 /// `listed_path`.
8186 ///
8187 /// Early builds wrote records as `session_<timestamp>.json`, so the file
8188 /// retention listed is not always `<id>.json`. Removing such a stub by id
8189 /// could never find it: it was listed again, failed with `NotFound`, and
8190 /// warned on every launch forever. That record has no id-addressed
8191 /// accounting, checkpoint, or directory (nothing could reach it by id), so
8192 /// retiring it is removing exactly the file that was listed. A stub that
8193 /// is already gone when removal runs (another process's retention got
8194 /// there first) is already removed, not an error.
8195 fn retire_empty_stub(&self, listed_path: &Path, id: &str) -> std::io::Result<()> {
8196 let canonical = self.validated_session_path(id)?;
8197 let result = if listed_path == canonical {
8198 self.remove_session(id, SessionRemoval::Retention)
8199 } else {
8200 let _lease = self.reserve_session_for_external_write(id)?;
8201 fs::remove_file(listed_path)
8202 };
8203 match result {
8204 Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()),
8205 other => other,
8206 }
8207 }
8208
8209 /// Remove session files whose `updated_at` is older than `max_age`
8210 /// from the persisted-sessions directory. Returns the number of
8211 /// records pruned. Building block for #406's phase-2 auto-archive
8212 /// on boot; today the user-facing entry point is the
8213 /// `/sessions prune <days>` slash command.
8214 ///
8215 /// Crash-recovery safety: skips the per-session checkpoint files
8216 /// (`checkpoints/<session_id>.json`), the legacy single-slot
8217 /// checkpoint (`checkpoints/latest.json`), and any file under `checkpoints/`
8218 /// — those are owned by the checkpoint subsystem and live with
8219 /// stricter durability rules. Only top-level `<session_id>.json`
8220 /// files are candidates.
8221 ///
8222 /// `max_age` is checked against the metadata's `updated_at`
8223 /// timestamp embedded in the JSON, not the filesystem mtime — the
8224 /// user may have rsynced their `~/.deepseek` between machines and
8225 /// fs mtimes can lie.
8226 pub fn prune_sessions_older_than(
8227 &self,
8228 max_age: std::time::Duration,
8229 ) -> std::io::Result<usize> {
8230 self.prune_sessions_older_than_keeping(max_age, None)
8231 }
8232
8233 /// As [`Self::prune_sessions_older_than`], but never deletes `keep` — the
8234 /// active session. A just-resumed session's `updated_at` is stale until
8235 /// its first post-resume save, so an age prune could otherwise delete the
8236 /// live session out from under the TUI.
8237 pub fn prune_sessions_older_than_keeping(
8238 &self,
8239 max_age: std::time::Duration,
8240 keep: Option<&str>,
8241 ) -> std::io::Result<usize> {
8242 // A max_age too large to represent (or to subtract from now) means
8243 // nothing can be old enough to prune — keep everything instead of
8244 // panicking on DateTime underflow or inventing a fallback horizon.
8245 let Some(cutoff) = chrono::Duration::from_std(max_age)
8246 .ok()
8247 .and_then(|age| Utc::now().checked_sub_signed(age))
8248 else {
8249 return Ok(0);
8250 };
8251 let sessions = self.list_sessions()?;
8252 let mut pruned = 0usize;
8253 for session in sessions {
8254 if keep.is_some_and(|id| id == session.id) {
8255 continue;
8256 }
8257 if session.updated_at < cutoff {
8258 if let Err(err) = self.remove_session(&session.id, SessionRemoval::Retention) {
8259 tracing::warn!(
8260 target: "session",
8261 session = session.id,
8262 ?err,
8263 "session prune skipped a record",
8264 );
8265 continue;
8266 }
8267 pruned += 1;
8268 }
8269 }
8270 Ok(pruned)
8271 }
8272
8273 /// Get the most recent session scoped to the current workspace.
8274 ///
8275 /// Archived sessions are skipped: archiving is the user saying "not this
8276 /// one", and `--continue` / auto-resume must honour that rather than
8277 /// dragging a put-away session back.
8278 pub fn get_latest_session_for_workspace(
8279 &self,
8280 workspace: &Path,
8281 ) -> std::io::Result<Option<SessionMetadata>> {
8282 let sessions = self.list_sessions()?;
8283 Ok(sessions.into_iter().find(|session| {
8284 !session.archived
8285 && workspace_scope_matches(&session.workspace, workspace)
8286 && !is_empty_auto_created_session(session)
8287 }))
8288 }
8289
8290 /// Search sessions by title
8291 pub fn search_sessions(&self, query: &str) -> std::io::Result<Vec<SessionMetadata>> {
8292 let query_lower = query.to_lowercase();
8293 let sessions = self.list_sessions()?;
8294
8295 Ok(sessions
8296 .into_iter()
8297 .filter(|s| s.title.to_lowercase().contains(&query_lower))
8298 .collect())
8299 }
8300
8301 pub fn missing_workspace_session_hint(&self, current_workspace: &Path) -> Option<PathBuf> {
8302 let catalog = self.scan_session_records().ok()?;
8303 let current_abs = make_absolute_lexical(current_workspace).ok();
8304 let current_parent = current_abs
8305 .as_deref()
8306 .and_then(Path::parent)
8307 .or_else(|| current_workspace.parent())
8308 .map(canonicalize_existing_prefix);
8309 let current_name = current_workspace.file_name();
8310 catalog.records.into_iter().find_map(|(_, session)| {
8311 if session.archived
8312 || is_empty_auto_created_session(&session)
8313 || workspace_scope_matches(&session.workspace, current_workspace)
8314 || session.workspace.exists()
8315 {
8316 return None;
8317 }
8318 let same_parent = session
8319 .workspace
8320 .parent()
8321 .map(canonicalize_existing_prefix)
8322 .zip(current_parent.as_ref())
8323 .is_some_and(|(lhs, rhs)| lhs == *rhs);
8324 let same_leaf = session
8325 .workspace
8326 .file_name()
8327 .zip(current_name)
8328 .is_some_and(|(lhs, rhs)| lhs == rhs);
8329 (same_parent || same_leaf).then_some(session.workspace)
8330 })
8331 }
8332
8333 pub fn migrate_workspace(
8334 &self,
8335 options: &WorkspaceMigrationOptions,
8336 ) -> std::io::Result<WorkspaceMigrationReport> {
8337 struct MigrationCheckpointEntry {
8338 path: PathBuf,
8339 legacy: bool,
8340 metadata: Option<SessionMetadata>,
8341 error: Option<String>,
8342 }
8343
8344 let old_abs = make_absolute_lexical(&options.old_path)?;
8345 let new_abs = make_absolute_lexical(&options.new_path)?;
8346 let old_is_symlink =
8347 fs::symlink_metadata(&old_abs).is_ok_and(|meta| meta.file_type().is_symlink());
8348 let resolved_old = if old_is_symlink {
8349 old_abs
8350 .parent()
8351 .zip(old_abs.file_name())
8352 .map(|(parent, name)| canonicalize_existing_prefix(parent).join(name))
8353 .unwrap_or_else(|| old_abs.clone())
8354 } else {
8355 canonicalize_existing_prefix(&old_abs)
8356 };
8357 let resolved_new = if new_abs.exists() {
8358 if !new_abs.is_dir() {
8359 return Err(io::Error::new(
8360 io::ErrorKind::InvalidInput,
8361 format!(
8362 "New workspace path {} is not a directory",
8363 options.new_path.display()
8364 ),
8365 ));
8366 }
8367 fs::canonicalize(&new_abs)?
8368 } else if options.dry_run {
8369 canonicalize_existing_prefix(&new_abs)
8370 } else {
8371 return Err(io::Error::new(
8372 io::ErrorKind::NotFound,
8373 format!(
8374 "New workspace directory {} does not exist",
8375 options.new_path.display()
8376 ),
8377 ));
8378 };
8379 let old_norm = normalize_workspace_path_for_compare(&old_abs);
8380 let new_norm = normalize_workspace_path_for_compare(&resolved_new);
8381 if old_norm == new_norm {
8382 return Err(io::Error::new(
8383 io::ErrorKind::InvalidInput,
8384 "Old and new workspace paths are identical",
8385 ));
8386 }
8387 let resolved_old_cmp = normalize_workspace_path_for_compare(&resolved_old);
8388 if resolved_old_cmp == new_norm
8389 || strip_workspace_prefix(&old_abs, &new_abs).is_some()
8390 || strip_workspace_prefix(&new_abs, &old_abs).is_some()
8391 || strip_workspace_prefix(&old_abs, &resolved_new).is_some()
8392 || strip_workspace_prefix(&resolved_new, &old_abs).is_some()
8393 || strip_workspace_prefix(&resolved_old, &resolved_new).is_some()
8394 || strip_workspace_prefix(&resolved_new, &resolved_old).is_some()
8395 {
8396 return Err(io::Error::new(
8397 io::ErrorKind::InvalidInput,
8398 "Old and new workspace paths cannot overlap",
8399 ));
8400 }
8401
8402 let remap = |workspace: &Path| {
8403 let mapped =
8404 remap_workspace_path(workspace, &old_abs, &resolved_new).or_else(|| {
8405 (!old_is_symlink
8406 && normalize_workspace_path_for_compare(&resolved_old)
8407 != normalize_workspace_path_for_compare(&resolved_new))
8408 .then(|| remap_workspace_path(workspace, &resolved_old, &resolved_new))
8409 .flatten()
8410 })?;
8411 (normalize_workspace_path_for_compare(workspace)
8412 != normalize_workspace_path_for_compare(&mapped))
8413 .then_some(mapped)
8414 };
8415 let matches_old = |workspace: &Path| remap(workspace).is_some();
8416 let is_under_new = |workspace: &Path| {
8417 let abs =
8418 make_absolute_lexical(workspace).unwrap_or_else(|_| clean_lexical_path(workspace));
8419 let canonical_abs = canonicalize_existing_prefix(&abs);
8420 paths_equivalent(workspace, &resolved_new)
8421 || strip_workspace_prefix(&abs, &new_abs).is_some()
8422 || strip_workspace_prefix(&abs, &resolved_new).is_some()
8423 || strip_workspace_prefix(&canonical_abs, &resolved_new).is_some()
8424 };
8425
8426 let mut report = WorkspaceMigrationReport {
8427 old_path: old_abs.clone(),
8428 new_path: resolved_new.clone(),
8429 ..Default::default()
8430 };
8431
8432 let catalog = self.scan_session_records()?;
8433 if let Some(warning) = catalog.warning() {
8434 report.unreadable.push(warning);
8435 }
8436 let mut docs_by_id: BTreeMap<String, SessionMetadata> = BTreeMap::new();
8437 for (path, metadata) in catalog.records {
8438 if path.file_stem().and_then(|s| s.to_str()) != Some(metadata.id.as_str()) {
8439 report.unreadable.push(format!(
8440 "{}: session id {} does not match filename",
8441 path.display(),
8442 metadata.id
8443 ));
8444 continue;
8445 }
8446 docs_by_id.insert(metadata.id.clone(), metadata);
8447 }
8448 let mut ckpts_by_id: BTreeMap<String, Vec<MigrationCheckpointEntry>> = BTreeMap::new();
8449 match self.list_checkpoints() {
8450 Ok(checkpoints) => {
8451 for checkpoint in checkpoints {
8452 let is_legacy = matches!(checkpoint.source, CheckpointSource::Legacy);
8453 match self.checkpoint_metadata(&checkpoint) {
8454 Ok(Some(metadata)) => {
8455 let id = metadata.id.clone();
8456 ckpts_by_id
8457 .entry(id)
8458 .or_default()
8459 .push(MigrationCheckpointEntry {
8460 path: checkpoint.path,
8461 legacy: is_legacy,
8462 metadata: Some(metadata),
8463 error: None,
8464 });
8465 }
8466 Ok(None) => {}
8467 Err(error) => {
8468 if let CheckpointSource::Session(ref id) = checkpoint.source {
8469 ckpts_by_id.entry(id.clone()).or_default().push(
8470 MigrationCheckpointEntry {
8471 path: checkpoint.path.clone(),
8472 legacy: false,
8473 metadata: None,
8474 error: Some(format!(
8475 "{}: {error}",
8476 checkpoint.path.display()
8477 )),
8478 },
8479 );
8480 } else {
8481 report
8482 .unreadable
8483 .push(format!("{}: {error}", checkpoint.path.display()));
8484 }
8485 }
8486 }
8487 }
8488 }
8489 Err(error) => {
8490 report
8491 .unreadable
8492 .push(format!("checkpoints listing: {error}"));
8493 }
8494 }
8495
8496 let mut all_ids: std::collections::BTreeSet<String> = docs_by_id.keys().cloned().collect();
8497 all_ids.extend(ckpts_by_id.keys().cloned());
8498
8499 let target_ids: Vec<String> = if let Some(selector) = options.session_id.as_deref() {
8500 let resolved_id = match self.resolve_recoverable_session_id_prefix(selector) {
8501 Ok(id) => id,
8502 Err(_err) if all_ids.contains(selector) => selector.to_string(),
8503 Err(err) => return Err(err),
8504 };
8505 vec![resolved_id]
8506 } else {
8507 all_ids.into_iter().collect()
8508 };
8509
8510 let tasks_runtime_dir = (self.sessions_dir.file_name().and_then(|n| n.to_str())
8511 == Some("sessions"))
8512 .then(|| {
8513 self.sessions_dir
8514 .parent()
8515 .map(|root| root.join("tasks").join("runtime"))
8516 })
8517 .flatten()
8518 .filter(|dir| dir.join("threads").is_dir())
8519 .or_else(|| {
8520 let dir = crate::task_manager::default_tasks_dir().join("runtime");
8521 dir.join("threads").is_dir().then_some(dir)
8522 });
8523
8524 for id in target_ids {
8525 let doc_meta = docs_by_id.get(&id);
8526 let ckpt_entries = ckpts_by_id.get(&id).map(Vec::as_slice).unwrap_or(&[]);
8527 let doc_matches_old = doc_meta.is_some_and(|meta| matches_old(&meta.workspace));
8528 let ckpt_matches_old = ckpt_entries.iter().any(|entry| {
8529 entry
8530 .metadata
8531 .as_ref()
8532 .is_some_and(|meta| matches_old(&meta.workspace))
8533 });
8534 let doc_already_new = doc_meta.is_some_and(|meta| is_under_new(&meta.workspace));
8535 let ckpt_already_new = ckpt_entries.iter().any(|entry| {
8536 entry
8537 .metadata
8538 .as_ref()
8539 .is_some_and(|meta| is_under_new(&meta.workspace))
8540 });
8541
8542 if options.session_id.is_some()
8543 && !doc_matches_old
8544 && !ckpt_matches_old
8545 && !doc_already_new
8546 && !ckpt_already_new
8547 {
8548 let actual = doc_meta
8549 .or_else(|| {
8550 ckpt_entries
8551 .iter()
8552 .find_map(|entry| entry.metadata.as_ref())
8553 })
8554 .map(|m| m.workspace.display().to_string())
8555 .unwrap_or_else(|| "unknown".to_string());
8556 return Err(io::Error::new(
8557 io::ErrorKind::InvalidInput,
8558 format!(
8559 "Session {id} belongs to workspace {actual}, not {}",
8560 old_abs.display()
8561 ),
8562 ));
8563 }
8564 if !doc_matches_old && !ckpt_matches_old && !doc_already_new && !ckpt_already_new {
8565 if doc_meta.is_none() && ckpt_entries.iter().all(|entry| entry.metadata.is_none()) {
8566 report
8567 .unreadable
8568 .extend(ckpt_entries.iter().filter_map(|entry| entry.error.clone()));
8569 }
8570 continue;
8571 }
8572
8573 let mut candidate_bindings = Vec::new();
8574 let mut seen_store_dirs = std::collections::HashSet::new();
8575 let mut push_binding = |binding: crate::runtime_threads::RuntimeStoreBinding| {
8576 if seen_store_dirs.insert(binding.data_dir.clone()) {
8577 candidate_bindings.push(binding);
8578 }
8579 };
8580 if let Some(binding) = doc_meta.and_then(|meta| meta.runtime_store.clone()) {
8581 push_binding(binding);
8582 }
8583 for entry in ckpt_entries {
8584 if let Some(binding) = entry
8585 .metadata
8586 .as_ref()
8587 .and_then(|meta| meta.runtime_store.clone())
8588 {
8589 push_binding(binding);
8590 }
8591 }
8592 let session_dir = self.sessions_dir.join(&id);
8593 if fs::symlink_metadata(&session_dir).is_ok_and(|meta| meta.file_type().is_symlink()) {
8594 push_binding(crate::runtime_threads::RuntimeStoreBinding {
8595 data_dir: session_dir.join("runtime"),
8596 execution_scope: String::new(),
8597 });
8598 } else if let Ok(entries) = fs::read_dir(&session_dir) {
8599 for entry in entries.flatten() {
8600 if !is_runtime_store_dir_name(&entry.file_name()) {
8601 continue;
8602 }
8603 let path = entry.path();
8604 if fs::symlink_metadata(&path).is_ok_and(|meta| meta.file_type().is_symlink()) {
8605 push_binding(crate::runtime_threads::RuntimeStoreBinding {
8606 data_dir: path,
8607 execution_scope: String::new(),
8608 });
8609 } else if path.is_dir()
8610 && let Ok(binding) =
8611 crate::runtime_threads::RuntimeStoreBinding::for_store_dir(&path)
8612 {
8613 push_binding(binding);
8614 }
8615 }
8616 }
8617 drop(push_binding);
8618 if candidate_bindings.is_empty()
8619 && let Some(tasks_dir) = tasks_runtime_dir.as_ref()
8620 {
8621 let tasks_has_symlink = tasks_dir
8622 .parent()
8623 .into_iter()
8624 .chain(std::iter::once(tasks_dir.as_path()))
8625 .any(|p| {
8626 fs::symlink_metadata(p).is_ok_and(|meta| meta.file_type().is_symlink())
8627 });
8628 if tasks_has_symlink {
8629 candidate_bindings.push(crate::runtime_threads::RuntimeStoreBinding {
8630 data_dir: tasks_dir.clone(),
8631 execution_scope: String::new(),
8632 });
8633 } else if let Ok(binding) =
8634 crate::runtime_threads::RuntimeStoreBinding::for_store_dir(tasks_dir)
8635 {
8636 candidate_bindings.push(binding);
8637 }
8638 }
8639
8640 if options.dry_run {
8641 if self.is_session_live_anywhere(&id) {
8642 report.busy_sessions.push(id);
8643 continue;
8644 }
8645 let mut thread_ids = Vec::new();
8646 let mut hold_failed = false;
8647 let mut store_busy = false;
8648 let mut session_filter = std::collections::HashSet::new();
8649 session_filter.insert(id.clone());
8650 for binding in &candidate_bindings {
8651 if !binding.data_dir.is_dir() {
8652 continue;
8653 }
8654 match binding.preview_migrate_session_workspace(
8655 &self.sessions_dir,
8656 Some(&session_filter),
8657 &old_abs,
8658 &resolved_new,
8659 ) {
8660 Ok(Some((mut found, skipped))) => {
8661 if found.is_empty()
8662 && !old_is_symlink
8663 && resolved_old != old_abs
8664 && let Ok(Some((alt_found, _))) = binding
8665 .preview_migrate_session_workspace(
8666 &self.sessions_dir,
8667 Some(&session_filter),
8668 &resolved_old,
8669 &resolved_new,
8670 )
8671 {
8672 found = alt_found;
8673 }
8674 thread_ids.extend(found);
8675 report.unreadable.extend(skipped);
8676 }
8677 Ok(None) => {
8678 store_busy = true;
8679 break;
8680 }
8681 Err(error) => {
8682 report
8683 .unreadable
8684 .push(format!("{id} runtime store: {error}"));
8685 hold_failed = true;
8686 break;
8687 }
8688 }
8689 }
8690 if store_busy {
8691 report.busy_sessions.push(id);
8692 continue;
8693 }
8694 if hold_failed || (!doc_matches_old && !ckpt_matches_old && thread_ids.is_empty()) {
8695 continue;
8696 }
8697 if resolved_new.is_dir() {
8698 let missing_target = doc_meta
8699 .filter(|_| doc_matches_old)
8700 .into_iter()
8701 .chain(
8702 ckpt_entries
8703 .iter()
8704 .filter_map(|entry| entry.metadata.as_ref()),
8705 )
8706 .filter_map(|meta| remap(&meta.workspace))
8707 .find(|next_ws| !next_ws.is_dir());
8708 if let Some(next_ws) = missing_target {
8709 report.unreadable.push(format!(
8710 "{id}: target workspace directory {} does not exist",
8711 next_ws.display()
8712 ));
8713 continue;
8714 }
8715 }
8716 for entry in ckpt_entries {
8717 if let Some(error) = entry.error.as_ref() {
8718 report.unreadable.push(error.clone());
8719 }
8720 }
8721 if doc_matches_old {
8722 report.migrated_sessions.push(id.clone());
8723 }
8724 if ckpt_matches_old {
8725 report.migrated_checkpoints.push(id.clone());
8726 }
8727 report.migrated_threads.extend(thread_ids);
8728 continue;
8729 }
8730
8731 let _lease = match self.reserve_session_for_external_write(&id) {
8732 Ok(lease) => lease,
8733 Err(error) if error.kind() == io::ErrorKind::ResourceBusy => {
8734 report.busy_sessions.push(id);
8735 continue;
8736 }
8737 Err(error) => {
8738 report.unreadable.push(format!("{id}: {error}"));
8739 continue;
8740 }
8741 };
8742
8743 let mut held_stores = Vec::new();
8744 let mut hold_failed = false;
8745 let mut store_busy = false;
8746 for binding in candidate_bindings {
8747 if !binding.data_dir.is_dir() {
8748 continue;
8749 }
8750 match binding.try_hold_for_sessions_dir(&self.sessions_dir) {
8751 Ok(Some(held)) => held_stores.push(held),
8752 Ok(None) => {
8753 store_busy = true;
8754 break;
8755 }
8756 Err(error) => {
8757 report
8758 .unreadable
8759 .push(format!("{id} runtime store: {error}"));
8760 hold_failed = true;
8761 break;
8762 }
8763 }
8764 }
8765 if store_busy {
8766 report.busy_sessions.push(id);
8767 continue;
8768 }
8769 if hold_failed {
8770 continue;
8771 }
8772
8773 let mut session_filter = std::collections::HashSet::new();
8774 session_filter.insert(id.clone());
8775 let mut thread_ids = Vec::new();
8776 let mut thread_probe_failed = false;
8777 for held in &held_stores {
8778 match held.migrate_session_workspace(
8779 Some(&session_filter),
8780 &old_abs,
8781 &resolved_new,
8782 true,
8783 None,
8784 ) {
8785 Ok((mut found, skipped)) => {
8786 if found.is_empty()
8787 && !old_is_symlink
8788 && resolved_old != old_abs
8789 && let Ok((alt_found, _)) = held.migrate_session_workspace(
8790 Some(&session_filter),
8791 &resolved_old,
8792 &resolved_new,
8793 true,
8794 None,
8795 )
8796 {
8797 found = alt_found;
8798 }
8799 thread_ids.extend(found);
8800 report.unreadable.extend(skipped);
8801 }
8802 Err(error) => {
8803 report.unreadable.push(format!("{id} threads: {error}"));
8804 thread_probe_failed = true;
8805 break;
8806 }
8807 }
8808 }
8809 if thread_probe_failed {
8810 continue;
8811 }
8812
8813 if !doc_matches_old && !ckpt_matches_old && thread_ids.is_empty() {
8814 continue;
8815 }
8816
8817 let doc_target_ws = doc_matches_old
8818 .then(|| doc_meta.and_then(|meta| remap(&meta.workspace)))
8819 .flatten();
8820 let mut ckpt_targets = Vec::new();
8821 for entry in ckpt_entries {
8822 if let Some(ref error) = entry.error {
8823 if !options.dry_run {
8824 report.unreadable.push(error.clone());
8825 }
8826 continue;
8827 }
8828 if let Some(ref meta) = entry.metadata
8829 && let Some(next_ws) = remap(&meta.workspace)
8830 {
8831 ckpt_targets.push((entry.path.clone(), entry.legacy, next_ws));
8832 }
8833 }
8834
8835 let mut target_missing = false;
8836 if let Some(ref next_ws) = doc_target_ws
8837 && !next_ws.is_dir()
8838 {
8839 report.unreadable.push(format!(
8840 "{id}: target workspace directory {} does not exist",
8841 next_ws.display()
8842 ));
8843 target_missing = true;
8844 }
8845 for (_, _, next_ws) in &ckpt_targets {
8846 if !next_ws.is_dir() {
8847 report.unreadable.push(format!(
8848 "{id}: target workspace directory {} does not exist",
8849 next_ws.display()
8850 ));
8851 target_missing = true;
8852 }
8853 }
8854 if target_missing {
8855 continue;
8856 }
8857
8858 let pre_observation = if doc_meta.is_some()
8859 && (doc_target_ws.is_some() || !ckpt_targets.is_empty() || !thread_ids.is_empty())
8860 {
8861 self.with_session_write_admission(&id, || self.observe_session_admitted(&id))
8862 .ok()
8863 .flatten()
8864 } else {
8865 None
8866 };
8867
8868 if doc_target_ws.is_some() {
8869 let doc_write = self.with_session_write_admission(&id, || {
8870 let persisted = self.load_session_write_metadata(&id)?;
8871 let mut session = self.load_session_snapshot_with_limit(&id, None, true)?;
8872 repair_recovered_session(&mut session);
8873 if let Some(next_ws) = remap(&session.metadata.workspace) {
8874 session.metadata.workspace = next_ws;
8875 self.write_session_admitted(
8876 session,
8877 JournalPrune::Keep,
8878 false,
8879 &persisted,
8880 )?;
8881 Ok(true)
8882 } else {
8883 Ok(false)
8884 }
8885 });
8886 match doc_write {
8887 Ok(Some(true)) => report.migrated_sessions.push(id.clone()),
8888 Ok(Some(false)) => {}
8889 Ok(None) => {
8890 report.unreadable.push(format!("{id}: session retired"));
8891 continue;
8892 }
8893 Err(error) => {
8894 report.unreadable.push(format!("{id}: {error}"));
8895 continue;
8896 }
8897 }
8898 }
8899
8900 let mut migrated_any_ckpt = false;
8901 for (ckpt_path, legacy, _next_ws) in ckpt_targets {
8902 let expected_id = (!legacy).then_some(id.as_str());
8903 let ckpt_result = self.with_session_write_admission(&id, || {
8904 let Some(mut checkpoint) =
8905 self.read_checkpoint_file(&ckpt_path, expected_id, true)?
8906 else {
8907 return Ok(false);
8908 };
8909 if checkpoint.metadata.id != id {
8910 return Ok(false);
8911 }
8912 let Some(next_ws) = remap(&checkpoint.metadata.workspace) else {
8913 return Ok(false);
8914 };
8915 let persisted = self.load_session_write_metadata(&id)?;
8916 Self::prepare_session_write(&mut checkpoint, &persisted, true)?;
8917 checkpoint.metadata.workspace = next_ws;
8918 self.hydrate_approval_receipts(&mut checkpoint)?;
8919 checkpoint.make_storage_compatible();
8920 checkpoint.metadata.publication_id = Some(Uuid::new_v4().to_string());
8921 let content = serialize_saved_session(checkpoint)?;
8922 write_atomic(&ckpt_path, content.as_bytes())?;
8923 Ok(true)
8924 });
8925 match ckpt_result {
8926 Ok(Some(true)) => migrated_any_ckpt = true,
8927 Ok(Some(false)) => {}
8928 Ok(None) => {
8929 report
8930 .unreadable
8931 .push(format!("{}: session retired", ckpt_path.display()));
8932 }
8933 Err(error) => {
8934 report
8935 .unreadable
8936 .push(format!("{}: {error}", ckpt_path.display()));
8937 }
8938 }
8939 }
8940 if migrated_any_ckpt {
8941 report.migrated_checkpoints.push(id.clone());
8942 }
8943
8944 let post_observation = if doc_meta.is_some() {
8945 self.with_session_write_admission(&id, || self.observe_session_admitted(&id))
8946 .ok()
8947 .flatten()
8948 } else {
8949 None
8950 };
8951
8952 if !held_stores.is_empty() && (!thread_ids.is_empty() || post_observation.is_some()) {
8953 let publication_update = post_observation
8954 .as_ref()
8955 .map(|post| (id.as_str(), pre_observation.as_ref(), post));
8956 for held in &held_stores {
8957 match held.migrate_session_workspace(
8958 Some(&session_filter),
8959 &old_abs,
8960 &resolved_new,
8961 false,
8962 publication_update,
8963 ) {
8964 Ok((mut updated, skipped)) => {
8965 if updated.is_empty()
8966 && !old_is_symlink
8967 && resolved_old != old_abs
8968 && let Ok((alt_updated, _)) = held.migrate_session_workspace(
8969 Some(&session_filter),
8970 &resolved_old,
8971 &resolved_new,
8972 false,
8973 publication_update,
8974 )
8975 {
8976 updated = alt_updated;
8977 }
8978 report.migrated_threads.extend(updated);
8979 report.unreadable.extend(skipped);
8980 }
8981 Err(error) => {
8982 report
8983 .unreadable
8984 .push(format!("{id} thread update: {error}"));
8985 }
8986 }
8987 }
8988 }
8989 }
8990
8991 Ok(report)
8992 }
8993 }
8994
8995 #[derive(Debug, Clone)]
8996 pub struct WorkspaceMigrationOptions {
8997 pub old_path: PathBuf,
8998 pub new_path: PathBuf,
8999 pub session_id: Option<String>,
9000 pub dry_run: bool,
9001 }
9002
9003 #[derive(Debug, Clone, Default, PartialEq, Eq)]
9004 pub struct WorkspaceMigrationReport {
9005 pub old_path: PathBuf,
9006 pub new_path: PathBuf,
9007 pub migrated_sessions: Vec<String>,
9008 pub migrated_checkpoints: Vec<String>,
9009 pub migrated_threads: Vec<String>,
9010 pub busy_sessions: Vec<String>,
9011 pub unreadable: Vec<String>,
9012 }
9013
9014 /// A Runtime store directory inside a session directory: `runtime`, or a
9015 /// `runtime-recovered-*` sibling opened for a conversation whose store was
9016 /// missing.
9017 pub fn is_runtime_store_dir_name(name: &std::ffi::OsStr) -> bool {
9018 name.to_str()
9019 .is_some_and(|name| name == "runtime" || name.starts_with("runtime-recovered-"))
9020 }
9021
9022 /// Unicode format characters that never belong in a session title: bidi
9023 /// embeddings/overrides/isolates and marks, zero-width joiners/spaces, the
9024 /// soft hyphen, BOM, and line/paragraph separators. Together with
9025 /// `char::is_control` (C0, DEL, C1 — so ESC, BEL, ST, and OSC introducers)
9026 /// this is the one character policy for the persisted title, the terminal
9027 /// tab title, and every plain-text listing that echoes a title.
9028 pub fn is_title_format_char(ch: char) -> bool {
9029 matches!(
9030 ch,
9031 '\u{00ad}'
9032 | '\u{061c}'
9033 | '\u{200b}'..='\u{200f}'
9034 | '\u{2028}'..='\u{202e}'
9035 | '\u{2060}'..='\u{2064}'
9036 | '\u{2066}'..='\u{2069}'
9037 | '\u{feff}'
9038 )
9039 }
9040
9041 /// One-line notice that a prior session in `workspace` ended mid-turn
9042 /// (#5715), for the session-pinned prompt prefix. `current_session_id` is
9043 /// excluded: an in-flight checkpoint of the live session is current work,
9044 /// not prior work. Returns `None` when no interrupted session exists.
9045 pub fn session_recovery_hint(workspace: &Path, current_session_id: Option<&str>) -> Option<String> {
9046 let manager = SessionManager::default_location().ok()?;
9047 let meta = manager.interrupted_workspace_session(workspace, current_session_id)?;
9048 Some(format!(
9049 "A previous Codewhale session in this workspace (\"{}\", id {}, last active {}) has a recovery checkpoint — it likely ended mid-task. To inspect it, call session_search with session_id \"{}\", then offer to summarize or continue the work; resuming is the user's decision (e.g. /resume).",
9050 meta.title,
9051 truncate_id(&meta.id),
9052 meta.updated_at.format("%Y-%m-%d %H:%M UTC"),
9053 meta.id,
9054 ))
9055 }
9056
9057 /// Drop control and bidi/zero-width format characters from a title.
9058 ///
9059 /// A session title is user- or content-derived text that later reaches an
9060 /// OSC 0 terminal title, `codewhale sessions` stdout, and the picker, so the
9061 /// persisted value must not be able to carry a raw escape sequence. Ordinary
9062 /// text, punctuation, CJK, and emoji pass through untouched.
9063 pub fn sanitize_session_title(raw: &str) -> String {
9064 raw.chars()
9065 .filter(|ch| !ch.is_control() && !is_title_format_char(*ch))
9066 .collect()
9067 }
9068
9069 /// Sanitize, trim, and bound a user-supplied session title.
9070 ///
9071 /// Returns `InvalidInput` for an empty title or one longer than
9072 /// [`MAX_SESSION_TITLE_CHARS`] so every rename surface (picker, `/rename`,
9073 /// `PATCH /v1/sessions/{id}`) rejects the same inputs with the same reason.
9074 pub fn normalize_session_title(title: &str) -> std::io::Result<String> {
9075 let sanitized = sanitize_session_title(title);
9076 let trimmed = sanitized.trim();
9077 if trimmed.is_empty() {
9078 return Err(std::io::Error::new(
9079 std::io::ErrorKind::InvalidInput,
9080 "Session title cannot be empty",
9081 ));
9082 }
9083 if trimmed.chars().count() > MAX_SESSION_TITLE_CHARS {
9084 return Err(std::io::Error::new(
9085 std::io::ErrorKind::InvalidInput,
9086 format!("Session title cannot exceed {MAX_SESSION_TITLE_CHARS} characters"),
9087 ));
9088 }
9089 Ok(trimmed.to_string())
9090 }
9091
9092 pub fn workspace_scope_matches(saved_workspace: &Path, current_workspace: &Path) -> bool {
9093 if paths_equivalent(saved_workspace, current_workspace) {
9094 return true;
9095 }
9096
9097 // Repository identity comes from the containing checkout itself (Git
9098 // dir/worktree traversal shared with project-context scope resolution),
9099 // never from branch names or paths mentioned in conversation.
9100 let canonical = |path: &Path| fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
9101 match (
9102 find_git_root(&canonical(saved_workspace)),
9103 find_git_root(&canonical(current_workspace)),
9104 ) {
9105 (Some(saved_root), Some(current_root)) => paths_equivalent(&saved_root, &current_root),
9106 _ => false,
9107 }
9108 }
9109
9110 pub fn is_empty_auto_created_session(session: &SessionMetadata) -> bool {
9111 !session.title_is_custom
9112 && session.message_count == 0
9113 && session
9114 .title
9115 .trim()
9116 .eq_ignore_ascii_case(DEFAULT_SESSION_TITLE)
9117 }
9118
9119 pub fn paths_equivalent(lhs: &Path, rhs: &Path) -> bool {
9120 let lhs_canonical = fs::canonicalize(lhs).ok();
9121 let rhs_canonical = fs::canonicalize(rhs).ok();
9122 match (lhs_canonical, rhs_canonical) {
9123 (Some(lhs), Some(rhs)) => {
9124 normalize_workspace_path_for_compare(&lhs) == normalize_workspace_path_for_compare(&rhs)
9125 }
9126 _ => {
9127 normalize_workspace_path_for_compare(&canonicalize_existing_prefix(lhs))
9128 == normalize_workspace_path_for_compare(&canonicalize_existing_prefix(rhs))
9129 }
9130 }
9131 }
9132
9133 fn make_absolute_lexical(path: &Path) -> std::io::Result<PathBuf> {
9134 let joined = if path.is_absolute() {
9135 path.to_path_buf()
9136 } else {
9137 std::env::current_dir()?.join(path)
9138 };
9139 Ok(clean_lexical_path(&joined))
9140 }
9141
9142 fn clean_lexical_path(path: &Path) -> PathBuf {
9143 let mut out = PathBuf::new();
9144 for component in path.components() {
9145 match component {
9146 Component::CurDir => {}
9147 Component::ParentDir => match out.components().next_back() {
9148 Some(Component::Normal(_)) => {
9149 out.pop();
9150 }
9151 None | Some(Component::ParentDir) => {
9152 out.push(Component::ParentDir);
9153 }
9154 Some(Component::RootDir | Component::Prefix(_)) => {}
9155 Some(Component::CurDir) => unreachable!(),
9156 },
9157 other => out.push(other.as_os_str()),
9158 }
9159 }
9160 if out.as_os_str().is_empty() {
9161 PathBuf::from(".")
9162 } else {
9163 out
9164 }
9165 }
9166
9167 fn canonicalize_existing_prefix(path: &Path) -> PathBuf {
9168 let joined = if path.is_absolute() {
9169 path.to_path_buf()
9170 } else if let Ok(cwd) = std::env::current_dir() {
9171 cwd.join(path)
9172 } else {
9173 return clean_lexical_path(path);
9174 };
9175 let mut resolved = PathBuf::new();
9176 let mut missing = Vec::<std::ffi::OsString>::new();
9177 let mut prefix_open = true;
9178
9179 for component in joined.components() {
9180 match component {
9181 Component::Prefix(prefix) => resolved.push(prefix.as_os_str()),
9182 Component::RootDir => resolved.push(component.as_os_str()),
9183 Component::CurDir => {}
9184 Component::Normal(part) => {
9185 if prefix_open {
9186 let next = resolved.join(part);
9187 match fs::canonicalize(&next) {
9188 Ok(canon) => {
9189 resolved = canon;
9190 }
9191 Err(_) => {
9192 prefix_open = false;
9193 missing.push(part.to_os_string());
9194 }
9195 }
9196 } else {
9197 missing.push(part.to_os_string());
9198 }
9199 }
9200 Component::ParentDir => {
9201 if missing.pop().is_some() {
9202 prefix_open = missing.is_empty();
9203 } else if let Some(parent) = resolved.parent() {
9204 resolved = parent.to_path_buf();
9205 }
9206 }
9207 }
9208 }
9209
9210 for part in missing {
9211 resolved.push(part);
9212 }
9213 if resolved.as_os_str().is_empty() {
9214 clean_lexical_path(&joined)
9215 } else {
9216 resolved
9217 }
9218 }
9219
9220 #[cfg(windows)]
9221 fn normalize_workspace_path_for_compare(path: &Path) -> String {
9222 let mut normalized = clean_lexical_path(path)
9223 .to_string_lossy()
9224 .replace('/', "\\");
9225 if let Some(rest) = normalized.strip_prefix(r"\\?\UNC\") {
9226 normalized = format!("\\\\{rest}");
9227 } else if let Some(rest) = normalized.strip_prefix(r"\\?\") {
9228 normalized = rest.to_string();
9229 }
9230 while normalized.len() > 3 && normalized.ends_with('\\') {
9231 normalized.pop();
9232 }
9233 normalized.to_ascii_lowercase()
9234 }
9235
9236 #[cfg(not(windows))]
9237 fn normalize_workspace_path_for_compare(path: &Path) -> PathBuf {
9238 clean_lexical_path(path)
9239 }
9240
9241 pub fn shell_quote_path(path: &Path) -> String {
9242 let raw = path.display().to_string();
9243 if !raw.is_empty()
9244 && raw.bytes().all(|byte| {
9245 byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'\\' | b'.' | b'_' | b'-' | b':')
9246 })
9247 {
9248 return raw;
9249 }
9250 let escaped = raw.replace('\'', "'\\''");
9251 format!("'{escaped}'")
9252 }
9253
9254 pub fn remap_workspace_path(stored: &Path, old_base: &Path, new_base: &Path) -> Option<PathBuf> {
9255 let stored_clean = canonicalize_existing_prefix(stored);
9256 let stored_raw = clean_lexical_path(stored);
9257 let old_clean = canonicalize_existing_prefix(old_base);
9258 let old_raw = clean_lexical_path(old_base);
9259
9260 for (candidate_stored, candidate_old) in [(&stored_raw, &old_raw), (&stored_clean, &old_clean)]
9261 {
9262 if let Some(suffix) = strip_workspace_prefix(candidate_stored, candidate_old) {
9263 let mapped = if suffix.as_os_str().is_empty() {
9264 new_base.to_path_buf()
9265 } else {
9266 new_base.join(suffix)
9267 };
9268 let mapped = clean_lexical_path(&mapped);
9269 if normalize_workspace_path_for_compare(stored)
9270 != normalize_workspace_path_for_compare(&mapped)
9271 {
9272 return Some(mapped);
9273 }
9274 }
9275 }
9276 None
9277 }
9278
9279 fn strip_workspace_prefix(path: &Path, base: &Path) -> Option<PathBuf> {
9280 #[cfg(windows)]
9281 {
9282 let norm_path = normalize_workspace_path_for_compare(path);
9283 let norm_base = normalize_workspace_path_for_compare(base);
9284 if norm_path == norm_base {
9285 return Some(PathBuf::new());
9286 }
9287 let prefix = if norm_base.ends_with('\\') {
9288 norm_base
9289 } else {
9290 format!("{norm_base}\\")
9291 };
9292 if norm_path.starts_with(&prefix) {
9293 let base_count = clean_lexical_path(base).components().count();
9294 let suffix: PathBuf = clean_lexical_path(path)
9295 .components()
9296 .skip(base_count)
9297 .collect();
9298 return Some(suffix);
9299 }
9300 None
9301 }
9302 #[cfg(not(windows))]
9303 {
9304 path.strip_prefix(base).ok().map(Path::to_path_buf)
9305 }
9306 }
9307
9308 /// Resolve the default session directory path.
9309 ///
9310 /// v0.8.44: prefers `~/.codewhale/sessions`, falls back to
9311 /// `~/.deepseek/sessions` for existing installs. Uses the write-path resolver
9312 /// so the first access relocates any legacy `~/.deepseek/sessions` into
9313 /// `~/.codewhale/sessions` when the primary directory is missing (#3240).
9314 /// If an older build already created an empty primary sessions directory, copy
9315 /// missing legacy entries into it without overwriting newer CodeWhale data.
9316 pub fn default_sessions_dir() -> std::io::Result<PathBuf> {
9317 if let Some(dir) = unsealed_sessions_dir() {
9318 return Ok(dir);
9319 }
9320 let dir = codewhale_config::ensure_state_dir("sessions")
9321 .map_err(|e| std::io::Error::new(std::io::ErrorKind::NotFound, e.to_string()))?;
9322 match merge_missing_legacy_session_entries(&dir) {
9323 Ok(0) => {}
9324 Ok(count) => {
9325 tracing::info!(
9326 target: "session::migration",
9327 "Copied {count} missing legacy session entries into {}",
9328 dir.display()
9329 );
9330 }
9331 Err(err) => {
9332 tracing::warn!(
9333 target: "session::migration",
9334 "Could not copy legacy sessions into {}: {err}",
9335 dir.display()
9336 );
9337 }
9338 }
9339 Ok(dir)
9340 }
9341
9342 /// `App::new` lists recent sessions, so merely building a fixture reaches the
9343 /// sessions directory — including the legacy relocation `ensure_state_dir`
9344 /// performs, which would move a developer's real `~/.deepseek/sessions`.
9345 /// An unsealed test gets a private directory (and no migration); a sealed one
9346 /// follows its own environment.
9347 #[cfg(any(test, feature = "test-support"))]
9348 fn unsealed_sessions_dir() -> Option<PathBuf> {
9349 crate::test_support::unsealed_state_dir("sessions")
9350 }
9351
9352 #[cfg(not(any(test, feature = "test-support")))]
9353 fn unsealed_sessions_dir() -> Option<PathBuf> {
9354 None
9355 }
9356
9357 fn merge_missing_legacy_session_entries(primary: &Path) -> io::Result<usize> {
9358 if codewhale_paths::codewhale_home_is_explicit() {
9359 return Ok(0);
9360 }
9361
9362 let legacy = codewhale_config::legacy_deepseek_home()
9363 .map_err(|e| io::Error::new(io::ErrorKind::NotFound, e.to_string()))?
9364 .join("sessions");
9365 if !legacy.is_dir() || paths_equivalent(primary, &legacy) {
9366 return Ok(0);
9367 }
9368
9369 copy_missing_dir_entries(&legacy, primary)
9370 }
9371
9372 fn copy_missing_dir_entries(src: &Path, dst: &Path) -> io::Result<usize> {
9373 fs::create_dir_all(dst)?;
9374 let mut copied = 0;
9375 for entry in fs::read_dir(src)? {
9376 let entry = entry?;
9377 let source = entry.path();
9378 let target = dst.join(entry.file_name());
9379
9380 let file_type = entry.file_type()?;
9381 if file_type.is_dir() {
9382 if entry.file_name() == std::ffi::OsStr::new("checkpoints") || target.exists() {
9383 continue;
9384 }
9385 copied += copy_missing_dir_entries(&source, &target)?;
9386 } else if file_type.is_file() {
9387 copied += usize::from(copy_file_create_new(&source, &target)?);
9388 }
9389 }
9390 Ok(copied)
9391 }
9392
9393 fn copy_file_create_new(src: &Path, dst: &Path) -> io::Result<bool> {
9394 let mut source = fs::File::open(src)?;
9395 let mut target = match fs::OpenOptions::new()
9396 .write(true)
9397 .create_new(true)
9398 .open(dst)
9399 {
9400 Ok(file) => file,
9401 Err(err) if err.kind() == io::ErrorKind::AlreadyExists => return Ok(false),
9402 Err(err) => return Err(err),
9403 };
9404 if let Err(err) = io::copy(&mut source, &mut target) {
9405 let _ = fs::remove_file(dst);
9406 return Err(err);
9407 }
9408 Ok(true)
9409 }
9410
9411 /// Prune snapshots older than `max_age` for `workspace`.
9412 ///
9413 /// Always non-fatal. Returns silently — callers don't need the count
9414 /// (the underlying repo logs at WARN if anything blew up).
9415 pub fn prune_workspace_snapshots(workspace: &Path, max_age: std::time::Duration) {
9416 match codewhale_snapshot::prune_older_than(workspace, max_age) {
9417 Ok(0) => {}
9418 Ok(n) => {
9419 tracing::debug!(target: "snapshot", "boot prune removed {n} snapshot(s)");
9420 }
9421 Err(e) => {
9422 tracing::warn!(target: "snapshot", "boot prune failed: {e}");
9423 }
9424 }
9425 }
9426
9427 /// Create a new `SavedSession` from conversation state
9428 #[cfg(any(test, feature = "test-support"))]
9429 pub fn create_saved_session(
9430 messages: &[Message],
9431 model: &str,
9432 workspace: &Path,
9433 total_tokens: u64,
9434 system_prompt: Option<&SystemPrompt>,
9435 ) -> SavedSession {
9436 create_saved_session_with_mode(
9437 messages,
9438 model,
9439 workspace,
9440 total_tokens,
9441 system_prompt,
9442 None,
9443 )
9444 }
9445
9446 /// Placeholder title used for a session that has no first user message yet.
9447 /// `build_session_snapshot` (tui/ui/frame.rs) treats a title equal to this
9448 /// constant as an auto-generated placeholder and lets the conversation-derived
9449 /// title win once a user message exists. Keep this string stable on purpose.
9450 pub const DEFAULT_SESSION_TITLE: &str = "New Session";
9451
9452 /// Create a new `SavedSession` from conversation state with optional mode label
9453 pub fn create_saved_session_with_mode(
9454 messages: &[Message],
9455 model: &str,
9456 workspace: &Path,
9457 total_tokens: u64,
9458 system_prompt: Option<&SystemPrompt>,
9459 mode: Option<&str>,
9460 ) -> SavedSession {
9461 create_saved_session_with_id_and_mode(
9462 Uuid::new_v4().to_string(),
9463 messages,
9464 model,
9465 workspace,
9466 total_tokens,
9467 system_prompt,
9468 mode,
9469 )
9470 }
9471
9472 /// Create a new `SavedSession` using a caller-owned session id.
9473 pub fn create_saved_session_with_id_and_mode(
9474 id: String,
9475 messages: &[Message],
9476 model: &str,
9477 workspace: &Path,
9478 total_tokens: u64,
9479 system_prompt: Option<&SystemPrompt>,
9480 mode: Option<&str>,
9481 ) -> SavedSession {
9482 create_saved_session_with_id_mode_and_stamps(
9483 id,
9484 messages,
9485 &[],
9486 model,
9487 workspace,
9488 total_tokens,
9489 system_prompt,
9490 mode,
9491 )
9492 }
9493
9494 /// Create a new `SavedSession` whose journal entries keep the time each
9495 /// message actually landed. `message_stamps[i]` is the append time of
9496 /// `messages[i]`; a missing stamp falls back to now. Callers without a
9497 /// live stamp log pass `&[]` and get the historical save-time behavior.
9498 pub fn create_saved_session_with_id_mode_and_stamps(
9499 id: String,
9500 messages: &[Message],
9501 message_stamps: &[DateTime<Utc>],
9502 model: &str,
9503 workspace: &Path,
9504 total_tokens: u64,
9505 system_prompt: Option<&SystemPrompt>,
9506 mode: Option<&str>,
9507 ) -> SavedSession {
9508 create_saved_session_inner(
9509 id,
9510 messages,
9511 SessionJournal::from_messages_stamped(messages.to_vec(), message_stamps, 0),
9512 model,
9513 workspace,
9514 total_tokens,
9515 system_prompt,
9516 mode,
9517 true,
9518 )
9519 }
9520
9521 /// Create a snapshot whose `messages` projection is left empty (#6214 T3).
9522 ///
9523 /// The journal still carries every message, and every serialization path
9524 /// rehydrates the projection (`serialize_saved_session` runs
9525 /// `make_storage_compatible`), so the on-disk bytes are identical to the
9526 /// filled form. The persistence queue drops the projection anyway
9527 /// (`compact_for_persistence_queue`), so building it first is one full
9528 /// history copy per debounced flush for nothing. Callers that serialize a
9529 /// journal-only snapshot directly must run `make_storage_compatible` first.
9530 pub fn create_saved_session_journal_only(
9531 id: String,
9532 messages: &[Message],
9533 journal: SessionJournal,
9534 model: &str,
9535 workspace: &Path,
9536 total_tokens: u64,
9537 system_prompt: Option<&SystemPrompt>,
9538 mode: Option<&str>,
9539 ) -> SavedSession {
9540 create_saved_session_inner(
9541 id,
9542 messages,
9543 journal,
9544 model,
9545 workspace,
9546 total_tokens,
9547 system_prompt,
9548 mode,
9549 false,
9550 )
9551 }
9552
9553 fn create_saved_session_inner(
9554 id: String,
9555 messages: &[Message],
9556 journal: SessionJournal,
9557 model: &str,
9558 workspace: &Path,
9559 total_tokens: u64,
9560 system_prompt: Option<&SystemPrompt>,
9561 mode: Option<&str>,
9562 fill_messages: bool,
9563 ) -> SavedSession {
9564 let now = Utc::now();
9565
9566 // Generate title from the first real user message (runtime-owned control
9567 // traffic is skipped by `conversation_derived_title`). Fall back to the
9568 // placeholder when no user-authored prompt exists yet.
9569 let title =
9570 conversation_derived_title(messages).unwrap_or_else(|| DEFAULT_SESSION_TITLE.to_string());
9571
9572 let leaf_id = journal.leaf_id.clone();
9573 SavedSession {
9574 write_receipt: None,
9575
9576 schema_version: CURRENT_SESSION_SCHEMA_VERSION,
9577 metadata: SessionMetadata {
9578 publication_id: None,
9579 native_mutation_observation: None,
9580
9581 id,
9582 title,
9583 title_is_custom: false,
9584 created_at: now,
9585 updated_at: now,
9586 message_count: messages.len(),
9587 total_tokens,
9588 model: model.to_string(),
9589 model_provider: default_model_provider(),
9590 model_provider_id: None,
9591 exec_route_binding: None,
9592 workspace: workspace.to_path_buf(),
9593 mode: mode.map(str::to_string),
9594 cost: SessionCostSnapshot::default(),
9595 parent_session_id: None,
9596 forked_from_message_count: None,
9597 runtime_store: None,
9598 cumulative_turn_secs: 0,
9599 archived: false,
9600 spawn_depth: journal.spawn_depth,
9601 },
9602 messages: if fill_messages {
9603 messages.to_vec()
9604 } else {
9605 Vec::new()
9606 },
9607 journal: Some(journal),
9608 leaf_id,
9609 system_prompt: system_prompt_to_string(system_prompt),
9610 context_references: Vec::new(),
9611 artifacts: Vec::new(),
9612 approval_receipts: Vec::new(),
9613 work_state: None,
9614 window_title: None,
9615 composer_color: None,
9616 last_auto_route: None,
9617 turn_outcomes: Vec::new(),
9618 delegated_writes: std::collections::BTreeMap::new(),
9619 agent_preset: None,
9620 }
9621 }
9622
9623 /// Update an existing session with new messages
9624 pub fn update_session(
9625 mut session: SavedSession,
9626 messages: &[Message],
9627 total_tokens: u64,
9628 system_prompt: Option<&SystemPrompt>,
9629 ) -> SavedSession {
9630 session.schema_version = CURRENT_SESSION_SCHEMA_VERSION;
9631 session.ensure_journal();
9632 let old_len = session.messages.len();
9633 let new_len = messages.len();
9634 let common = messages
9635 .iter()
9636 .zip(session.messages.iter())
9637 .take_while(|(a, b)| same_recorded_turn(a, b))
9638 .count();
9639 let mut kept_recorded_metadata = false;
9640 if new_len >= old_len && messages[..old_len] == session.messages[..] {
9641 if let Some(journal) = session.journal.as_mut() {
9642 for msg in &messages[old_len..] {
9643 journal.append_message(msg.clone());
9644 }
9645 session.leaf_id = journal.leaf_id.clone();
9646 }
9647 } else if (new_len != old_len || messages != session.messages.as_slice())
9648 && let Some(journal) = session.journal.as_mut()
9649 {
9650 kept_recorded_metadata = journal
9651 .rebranch_active_messages(messages)
9652 .kept_recorded_metadata;
9653 session.leaf_id = journal.leaf_id.clone();
9654 }
9655 if kept_recorded_metadata && let Some(journal) = &session.journal {
9656 session.messages = journal.to_messages();
9657 } else {
9658 session.messages.clear();
9659 session.messages.extend_from_slice(messages);
9660 }
9661 session
9662 .turn_outcomes
9663 .retain(|outcome| outcome.after_message_count <= common);
9664 session.metadata.updated_at = Utc::now();
9665 session.metadata.message_count = messages.len();
9666 session.metadata.total_tokens = total_tokens;
9667 session.system_prompt = system_prompt_to_string(system_prompt);
9668 session
9669 }
9670
9671 /// Strip a stale `[Session note]` block that was written by the old
9672 /// 500-message cap. Only removes notes that contain the specific
9673 /// "older messages were dropped" phrase — ordinary user-added
9674 /// `[Session note]` prompts are left untouched.
9675 fn strip_legacy_truncation_note(system_prompt: Option<String>) -> Option<String> {
9676 let sp = system_prompt?;
9677 let Some(trimmed) = sp.strip_prefix("[Session note]\n") else {
9678 return Some(sp);
9679 };
9680 // Only strip if this is the known cap_messages note.
9681 if !trimmed.contains("older messages were dropped") {
9682 return Some(sp);
9683 }
9684 // The note block ends with "\n\n---\n\n" (7 chars) followed by the real prompt.
9685 trimmed
9686 .find("\n\n---\n\n")
9687 .map(|pos| trimmed[pos + 7..].to_string())
9688 }
9689
9690 /// Byte offset of `key` (a quoted JSON key such as `"metadata"`) outside any
9691 /// string literal. Brace/string-aware so a key name quoted inside an earlier
9692 /// message body is never matched.
9693 fn find_json_key(bytes: &[u8], key: &[u8]) -> Option<usize> {
9694 if bytes
9695 .iter()
9696 .copied()
9697 .find(|byte| !byte.is_ascii_whitespace())
9698 != Some(b'{')
9699 {
9700 return None;
9701 }
9702 let mut idx = 0usize;
9703 let mut depth = 0usize;
9704 let mut in_string = false;
9705 let mut escape = false;
9706 while idx < bytes.len() {
9707 let c = bytes[idx];
9708 if in_string {
9709 if escape {
9710 escape = false;
9711 } else if c == b'\\' {
9712 escape = true;
9713 } else if c == b'"' {
9714 in_string = false;
9715 }
9716 } else {
9717 match c {
9718 b'{' | b'[' => depth += 1,
9719 b'}' | b']' => {
9720 depth = depth.checked_sub(1)?;
9721 if depth == 0 {
9722 return None;
9723 }
9724 }
9725 b'"' => {
9726 if depth == 1 && bytes[idx..].starts_with(key) {
9727 let mut after = idx + key.len();
9728 while after < bytes.len() && bytes[after].is_ascii_whitespace() {
9729 after += 1;
9730 }
9731 if bytes.get(after) == Some(&b':') {
9732 return Some(idx);
9733 }
9734 }
9735 in_string = true;
9736 }
9737 _ => {}
9738 }
9739 }
9740 idx += 1;
9741 }
9742 None
9743 }
9744
9745 /// Offset of the value opening with `open` that follows the key at
9746 /// `key_offset`.
9747 fn json_value_start(bytes: &[u8], key_offset: usize, key_len: usize, open: u8) -> Option<usize> {
9748 let mut idx = key_offset + key_len;
9749 while idx < bytes.len() && (bytes[idx] as char).is_whitespace() {
9750 idx += 1;
9751 }
9752 if idx >= bytes.len() || bytes[idx] != b':' {
9753 return None;
9754 }
9755 idx += 1;
9756 while idx < bytes.len() && (bytes[idx] as char).is_whitespace() {
9757 idx += 1;
9758 }
9759 (idx < bytes.len() && bytes[idx] == open).then_some(idx)
9760 }
9761
9762 /// Exclusive end of the balanced `{...}` starting at `start`, or `None` when
9763 /// the buffer is truncated before it closes.
9764 fn json_object_end(bytes: &[u8], start: usize) -> Option<usize> {
9765 let mut depth = 0i32;
9766 let mut in_string = false;
9767 let mut escape = false;
9768 for (offset, &c) in bytes[start..].iter().enumerate() {
9769 if escape {
9770 escape = false;
9771 continue;
9772 }
9773 match c {
9774 b'\\' => escape = true,
9775 b'"' => in_string = !in_string,
9776 b'{' if !in_string => depth += 1,
9777 b'}' if !in_string => {
9778 depth -= 1;
9779 if depth == 0 {
9780 return Some(start + offset + 1);
9781 }
9782 }
9783 _ => {}
9784 }
9785 }
9786 None
9787 }
9788
9789 /// The longest valid UTF-8 prefix of `buf`. A fixed-size read prefix can end
9790 /// inside a multi-byte character (routine for CJK or emoji transcripts, which
9791 /// serde writes unescaped); rejecting the whole buffer then forced a full-file
9792 /// read of every such session on each listing.
9793 ///
9794 /// Only a character cut at the very end is trimmed. An invalid byte anywhere
9795 /// else means a damaged file, and an empty prefix sends it down the full read,
9796 /// which reports it.
9797 fn utf8_prefix(buf: &[u8]) -> &str {
9798 match std::str::from_utf8(buf) {
9799 Ok(s) => s,
9800 // `valid_up_to` marks a char boundary, so this slice is valid.
9801 Err(error) if error.error_len().is_none() => {
9802 std::str::from_utf8(&buf[..error.valid_up_to()]).unwrap_or_default()
9803 }
9804 Err(_) => "",
9805 }
9806 }
9807
9808 /// String-scan a JSON byte buffer for the top-level `"metadata":{...}`
9809 /// block and return it parsed. Returns `None` if no balanced metadata
9810 /// object is present in the buffer.
9811 ///
9812 /// Supports the optimisation in `SessionManager::load_session_metadata`
9813 /// (#337). The scanner is brace-balanced and string-aware so a `{` or
9814 /// `}` appearing inside a string literal doesn't perturb the depth
9815 /// count.
9816 fn extract_top_level_metadata(buf: &[u8]) -> Option<SessionMetadata> {
9817 let s = utf8_prefix(buf);
9818 let bytes = s.as_bytes();
9819 const KEY: &[u8] = b"\"metadata\"";
9820 let start = json_value_start(bytes, find_json_key(bytes, KEY)?, KEY.len(), b'{')?;
9821 let end = json_object_end(bytes, start)?;
9822 serde_json::from_str::<SessionMetadata>(&s[start..end]).ok()
9823 }
9824
9825 /// Complete message objects from the front of the `messages` array, plus
9826 /// whether the array was seen to end. A message the prefix cut in half is
9827 /// simply absent; nothing is reconstructed.
9828 fn extract_leading_messages(buf: &[u8], max: usize) -> (Vec<Message>, bool) {
9829 let s = utf8_prefix(buf);
9830 let bytes = s.as_bytes();
9831 const KEY: &[u8] = b"\"messages\"";
9832 let Some(key_offset) = find_json_key(bytes, KEY) else {
9833 return (Vec::new(), false);
9834 };
9835 let Some(array_start) = json_value_start(bytes, key_offset, KEY.len(), b'[') else {
9836 return (Vec::new(), false);
9837 };
9838 let mut cursor = array_start + 1;
9839 let mut out = Vec::new();
9840 loop {
9841 while cursor < bytes.len() && matches!(bytes[cursor], b' ' | b'\t' | b'\r' | b'\n' | b',') {
9842 cursor += 1;
9843 }
9844 if cursor < bytes.len() && bytes[cursor] == b']' {
9845 return (out, true);
9846 }
9847 if out.len() >= max || cursor >= bytes.len() || bytes[cursor] != b'{' {
9848 return (out, false);
9849 }
9850 let Some(end) = json_object_end(bytes, cursor) else {
9851 return (out, false);
9852 };
9853 let Ok(message) = serde_json::from_str::<Message>(&s[cursor..end]) else {
9854 return (out, false);
9855 };
9856 out.push(message);
9857 cursor = end;
9858 }
9859 }
9860
9861 /// How many leading messages the legacy-title recovery will parse. The
9862 /// enclosing read is already bounded to a 64 KB prefix (#337); this bounds
9863 /// the parse inside it.
9864 const LEGACY_TITLE_SCAN_MESSAGES: usize = 24;
9865
9866 /// Recover a title that a superseded derivation took from runtime control
9867 /// traffic, using the session's own first real user prompt.
9868 ///
9869 /// Provenance is proven, never guessed: the stored title has to be exactly
9870 /// what the old rule produced — [`truncate_title`] of a message the current
9871 /// classifier rejects as not a user turn. A renamed session, and a person who
9872 /// literally typed an envelope as their first message, never match, so their
9873 /// text is kept. Returns `None` when there is nothing proven to recover.
9874 fn recovered_legacy_title(
9875 stored: &str,
9876 messages: &[Message],
9877 array_complete: bool,
9878 ) -> Option<String> {
9879 let stale = messages.iter().any(|message| {
9880 codewhale_models::turn_classify::classify_user_turn_prompt(message)
9881 == codewhale_models::turn_classify::UserTurnPromptKind::NotPrompt
9882 && message.content.iter().any(|block| match block {
9883 ContentBlock::Text { text, .. } => {
9884 truncate_title(text, 50) == stored
9885 || truncate_title(extract_user_prompt(text), 50) == stored
9886 }
9887 _ => false,
9888 })
9889 });
9890 if !stale {
9891 return None;
9892 }
9893 match conversation_derived_title(messages) {
9894 Some(title) => Some(title),
9895 // No user turn in what we read. Only claim the conversation has none
9896 // when the array actually ended inside the prefix; a truncated read
9897 // keeps the stored title rather than inventing a neutral one.
9898 None if array_complete => Some(DEFAULT_SESSION_TITLE.to_string()),
9899 None => None,
9900 }
9901 }
9902
9903 /// Apply [`recovered_legacy_title`] to freshly loaded metadata. In memory
9904 /// only — the session file is never rewritten, so the stored title (and any
9905 /// rename) survives on disk.
9906 fn apply_legacy_title_recovery(metadata: &mut SessionMetadata, buf: &[u8]) {
9907 // Cost gate, never the rename decision: an envelope title always opens
9908 // with `<`, so this keeps #337's bounded-parse win for ordinary titles.
9909 // Whether to rewrite is `recovered_legacy_title`'s proven provenance.
9910 if metadata.title_is_custom || !metadata.title.starts_with('<') {
9911 return;
9912 }
9913 let (messages, complete) = extract_leading_messages(buf, LEGACY_TITLE_SCAN_MESSAGES);
9914 if messages.is_empty() {
9915 return;
9916 }
9917 if let Some(title) = recovered_legacy_title(&metadata.title, &messages, complete) {
9918 metadata.title = title;
9919 }
9920 }
9921
9922 fn system_prompt_to_string(system_prompt: Option<&SystemPrompt>) -> Option<String> {
9923 match system_prompt {
9924 Some(SystemPrompt::Text(text)) => Some(text.clone()),
9925 Some(SystemPrompt::Blocks(blocks)) => Some(
9926 blocks
9927 .iter()
9928 .map(|b| b.text.clone())
9929 .collect::<Vec<_>>()
9930 .join("\n\n---\n\n"),
9931 ),
9932 None => None,
9933 }
9934 }
9935
9936 /// Truncate a session ID to 8 characters for compact display.
9937 /// Returns a `&str` borrowing from the input — no allocation.
9938 pub fn truncate_id(id: &str) -> &str {
9939 id.get(..8).unwrap_or(id)
9940 }
9941
9942 /// Strip a leading `<turn_meta>...</turn_meta>` block from saved user text.
9943 ///
9944 /// Older sessions can have turn metadata prefixed to the first user message.
9945 /// The session picker and generated session titles should show the user's
9946 /// prompt, not the cache/debug envelope.
9947 pub fn extract_user_prompt(raw: &str) -> &str {
9948 let trimmed = raw.trim_start();
9949 let Some(after_open) = trimmed.strip_prefix("<turn_meta>") else {
9950 return trimmed;
9951 };
9952 if let Some(close_pos) = after_open.find("</turn_meta>") {
9953 return after_open[close_pos + "</turn_meta>".len()..].trim_start();
9954 }
9955 after_open.trim_start()
9956 }
9957
9958 /// Clean a stored title for display, falling back to a neutral label.
9959 pub fn extract_title(raw: &str) -> &str {
9960 let title = extract_user_prompt(raw);
9961 if title.is_empty() { "Session" } else { title }
9962 }
9963
9964 /// Strip common inline thinking/reasoning XML sections from saved assistant
9965 /// text before it is shown in session previews.
9966 pub fn strip_thinking_tags(text: &str) -> String {
9967 let tags = ["think", "thinking", "reasoning", "analysis"];
9968 let mut result = text.to_string();
9969 for tag in tags {
9970 let open = format!("<{tag}>");
9971 let close = format!("</{tag}>");
9972 loop {
9973 let lower = result.to_ascii_lowercase();
9974 match (lower.find(&open), lower.find(&close)) {
9975 (Some(start), Some(end)) if start < end => {
9976 result.replace_range(start..end + close.len(), "");
9977 }
9978 (_, Some(end)) => {
9979 result.replace_range(..end + close.len(), "");
9980 }
9981 (Some(start), None) => {
9982 result.truncate(start);
9983 break;
9984 }
9985 (None, None) => break,
9986 }
9987 }
9988 }
9989 result
9990 }
9991
9992 /// Truncate a string to create a title (character-safe for UTF-8)
9993 pub(crate) fn truncate_title(s: &str, max_len: usize) -> String {
9994 let s = s.trim();
9995 // Older sessions may carry a title saved before sanitization existed;
9996 // never echo raw controls into stdout or the picker. Take the first
9997 // line before sanitizing so a legacy multi-line title still shows only
9998 // its first line.
9999 let first_line = sanitize_session_title(s.lines().next().unwrap_or(s));
10000 let first_line = first_line.trim();
10001
10002 let char_count = first_line.chars().count();
10003 if char_count <= max_len {
10004 first_line.to_string()
10005 } else {
10006 let truncated: String = first_line.chars().take(max_len - 3).collect();
10007 format!("{truncated}...")
10008 }
10009 }
10010
10011 /// Derive the auto-title from the first real user message of a conversation.
10012 ///
10013 /// Returns `None` when no user-authored message exists to name the session
10014 /// after (an empty transcript, or one holding only runtime-owned control
10015 /// traffic); callers fall back to [`DEFAULT_SESSION_TITLE`].
10016 ///
10017 /// Chat-template compatibility forces runtime-owned control traffic
10018 /// (sub-agent handoffs, the Operate contract, restore checkpoints) through
10019 /// `role = "user"`, but an internal envelope is not what the person typed.
10020 /// Prompt eligibility comes from the existing user-turn classifier; the live
10021 /// title fallback shares the same selection through `conversation_title_prompt`.
10022 fn conversation_derived_title(messages: &[Message]) -> Option<String> {
10023 conversation_title_prompt(messages).map(|prompt| truncate_title(prompt, 50))
10024 }
10025
10026 /// Select the first real user turn's text for persisted and live titles.
10027 /// Keep an image-only turn as the first user boundary, and strip historical
10028 /// leading turn metadata without introducing another provenance classifier.
10029 pub fn conversation_title_prompt(messages: &[Message]) -> Option<&str> {
10030 messages
10031 .iter()
10032 .find(|message| {
10033 codewhale_models::turn_classify::classify_user_turn_prompt(message)
10034 != codewhale_models::turn_classify::UserTurnPromptKind::NotPrompt
10035 })
10036 .and_then(|m| {
10037 m.content.iter().find_map(|block| match block {
10038 ContentBlock::Text { text, .. } => {
10039 let prompt = extract_user_prompt(text);
10040 if prompt.is_empty() {
10041 None
10042 } else {
10043 Some(prompt)
10044 }
10045 }
10046 _ => None,
10047 })
10048 })
10049 }
10050
10051 /// Format a session for display in a picker
10052 pub fn format_session_line(meta: &SessionMetadata) -> String {
10053 let age = format_age(&meta.updated_at);
10054 let updated = format_session_updated_at(&meta.updated_at, &age);
10055 let truncated_title = truncate_title(extract_title(&meta.title), 40);
10056 let fork_label = if meta.parent_session_id.is_some() {
10057 " | fork"
10058 } else {
10059 ""
10060 };
10061
10062 format!(
10063 "{} | {} | {} msgs{} | {}",
10064 truncate_id(&meta.id),
10065 truncated_title,
10066 meta.message_count,
10067 fork_label,
10068 updated
10069 )
10070 }
10071
10072 pub fn format_session_updated_at(dt: &DateTime<Utc>, age: &str) -> String {
10073 format!("{} ({age})", dt.format("%Y-%m-%d %H:%M UTC"))
10074 }
10075
10076 /// Format a datetime as relative age
10077 fn format_age(dt: &DateTime<Utc>) -> String {
10078 let now = Utc::now();
10079 let duration = now.signed_duration_since(*dt);
10080
10081 if duration.num_minutes() < 1 {
10082 "just now".to_string()
10083 } else if duration.num_hours() < 1 {
10084 format!("{}m ago", duration.num_minutes())
10085 } else if duration.num_days() < 1 {
10086 format!("{}h ago", duration.num_hours())
10087 } else if duration.num_weeks() < 1 {
10088 format!("{}d ago", duration.num_days())
10089 } else {
10090 format!("{}w ago", duration.num_weeks())
10091 }
10092 }
10093
10094 // === Unit Tests ===
10095
10096 #[cfg(test)]
10097 mod tests {
10098 include!("session_manager/test_cases_01.rs");
10099
10100 include!("session_manager/test_cases_02.rs");
10101
10102 include!("session_manager/test_cases_03.rs");
10103
10104 include!("session_manager/test_cases_04.rs");
10105 }
10106
10107 #[cfg(test)]
10108 mod storage_compatible_tests {
10109 use super::*;
10110
10111 fn user(text: &str) -> Message {
10112 Message {
10113 role: codewhale_models::Role::from("user"),
10114 content: vec![codewhale_models::ContentBlock::Text {
10115 text: text.to_string(),
10116 cache_control: None,
10117 }],
10118 }
10119 }
10120
10121 /// Journal-only snapshots (#6214 T3) skip building the `messages`
10122 /// projection, but a save still lands full history: serialization
10123 /// rehydrates the projection from the journal, so a reload is whole.
10124 #[test]
10125 fn journal_only_snapshot_saves_and_reloads_full_history() {
10126 let tmp = tempfile::tempdir().expect("tempdir");
10127 let messages = vec![user("first"), user("answer")];
10128 let sparse = create_saved_session_journal_only(
10129 "roundtrip".to_string(),
10130 &messages,
10131 SessionJournal::from_messages(messages.clone(), 0),
10132 "test-model",
10133 tmp.path(),
10134 7,
10135 None,
10136 None,
10137 );
10138 assert!(
10139 sparse.messages.is_empty(),
10140 "journal-only snapshots carry no messages projection"
10141 );
10142 assert_eq!(
10143 sparse.journal.as_ref().expect("journal").to_messages(),
10144 messages,
10145 "the journal still carries every message"
10146 );
10147 let manager = SessionManager::new(tmp.path().join("sessions")).expect("manager");
10148 manager.save_session_owned(sparse).expect("save sparse");
10149 let reloaded = manager.load_session("roundtrip").expect("reload");
10150 assert_eq!(reloaded.messages, messages);
10151 }
10152
10153 /// The no-op cases must stay no-ops, byte for byte.
10154 ///
10155 /// `make_storage_compatible` replaced a clone-and-return-`Option` helper
10156 /// (#6214 T3). Two of that helper's paths returned `None`, and the caller
10157 /// then serialized the *original* — so a `metadata.message_count` that
10158 /// disagrees with `messages.len()` survived untouched. Rewriting it in
10159 /// place would silently edit live data on every save, and nothing else in
10160 /// the suite catches that.
10161 #[test]
10162 fn make_storage_compatible_leaves_the_no_op_cases_byte_identical() {
10163 let workspace = std::env::temp_dir();
10164 let messages = vec![user("one"), user("two")];
10165
10166 // 1. No journal at all (legacy, pre-journal files): untouched.
10167 let mut legacy = create_saved_session(&messages, "test-model", &workspace, 0, None);
10168 legacy.journal = None;
10169 legacy.metadata.message_count = 99; // deliberately disagrees
10170 let before = serde_json::to_string_pretty(&legacy).expect("legacy json");
10171 let mut after_session = legacy.clone();
10172 after_session.make_storage_compatible();
10173 assert_eq!(
10174 serde_json::to_string_pretty(&after_session).expect("legacy json"),
10175 before,
10176 "a session with no journal must serialize exactly as it arrived"
10177 );
10178 assert_eq!(after_session.metadata.message_count, 99);
10179
10180 // 2. Journal present and `messages` already equals its active branch:
10181 // still untouched, including the disagreeing count.
10182 let mut settled = create_saved_session(&messages, "test-model", &workspace, 0, None);
10183 assert!(settled.journal.is_some(), "fixture must carry a journal");
10184 settled.messages = settled
10185 .journal
10186 .as_ref()
10187 .expect("journal present")
10188 .to_messages();
10189 settled.metadata.message_count = 99;
10190 let before = serde_json::to_string_pretty(&settled).expect("settled json");
10191 let mut after_session = settled.clone();
10192 after_session.make_storage_compatible();
10193 assert_eq!(
10194 serde_json::to_string_pretty(&after_session).expect("settled json"),
10195 before,
10196 "an already-consistent session must not be rewritten"
10197 );
10198 assert_eq!(
10199 after_session.metadata.message_count, 99,
10200 "the early return must happen before message_count is recomputed"
10201 );
10202 }
10203
10204 /// The queued (journal-only) path is what the debounced flush actually
10205 /// writes: `compact_for_persistence_queue` empties `messages` first.
10206 #[test]
10207 fn make_storage_compatible_rehydrates_a_compacted_queue_snapshot() {
10208 let workspace = std::env::temp_dir();
10209 let messages = vec![user("one"), user("two"), user("three")];
10210 let mut session = create_saved_session(&messages, "test-model", &workspace, 0, None);
10211 let expected = session
10212 .journal
10213 .as_ref()
10214 .expect("journal present")
10215 .to_messages();
10216
10217 session.compact_for_persistence_queue();
10218 assert!(
10219 session.messages.is_empty(),
10220 "the queued snapshot is journal-only"
10221 );
10222
10223 session.make_storage_compatible();
10224 assert_eq!(
10225 session.messages, expected,
10226 "the compat projection is rebuilt from the journal"
10227 );
10228 assert_eq!(session.metadata.message_count, expected.len());
10229 }
10230 }
10231
10232 #[cfg(test)]
10233 mod canonical_journal_admission_tests {
10234 use super::*;
10235 #[test]
10236 fn corrupted_saved_branch_refuses_read_and_write_without_truncating_source() {
10237 let tmp = tempfile::tempdir().unwrap();
10238 let manager = SessionManager::new(tmp.path().join("sessions")).unwrap();
10239 let message = Message {
10240 role: codewhale_models::Role::User,
10241 content: vec![ContentBlock::Text {
10242 text: "retained".into(),
10243 cache_control: None,
10244 }],
10245 };
10246 let mut session = create_saved_session_with_id_and_mode(
10247 "corrupt-graph".into(),
10248 &[message],
10249 "test-model",
10250 tmp.path(),
10251 0,
10252 None,
10253 None,
10254 );
10255 let mut empty_root = session.clone();
10256 empty_root.metadata.id = "empty-root-graph".into();
10257 let mut alternative = session.messages.clone();
10258 alternative[0].role = codewhale_models::Role::Assistant;
10259 let graph = empty_root.journal.as_mut().unwrap();
10260 graph.rebranch_active_messages(&alternative);
10261 let retained_entries = graph.entries.clone();
10262 assert_eq!(retained_entries.len(), 2);
10263 graph.rebranch_active_messages(&[]);
10264 empty_root.leaf_id = None;
10265 empty_root.messages.clear();
10266 empty_root.metadata.message_count = 0;
10267 manager.save_session(&empty_root).unwrap();
10268 let observed = manager
10269 .load_session_snapshot_bounded(
10270 "empty-root-graph",
10271 codewhale_protocol::MAX_CANONICAL_HISTORY_BYTES,
10272 )
10273 .unwrap();
10274 assert!(observed.messages.is_empty());
10275 assert_eq!(observed.leaf_id, None);
10276 assert_eq!(observed.journal.as_ref().unwrap().leaf_id, None);
10277 assert_eq!(observed.journal.as_ref().unwrap().entries, retained_entries);
10278 let graph = session.journal.as_mut().unwrap();
10279 graph.entries[0].parent_id = Some(graph.entries[0].id.clone());
10280 let bytes = serde_json::to_vec(&session).unwrap();
10281 let path = manager.validated_session_path("corrupt-graph").unwrap();
10282 fs::write(&path, &bytes).unwrap();
10283 assert_eq!(
10284 manager
10285 .load_session_snapshot("corrupt-graph")
10286 .unwrap_err()
10287 .kind(),
10288 io::ErrorKind::InvalidData
10289 );
10290 assert!(manager.save_session(&session).is_err());
10291 assert_eq!(fs::read(&path).unwrap(), bytes);
10292 assert!(
10293 SavedSession::import_foreign(
10294 session.export_container("fixture"),
10295 tmp.path().into(),
10296 "test-model".into()
10297 )
10298 .is_err()
10299 );
10300 }
10301 }
10302
10303 #[cfg(test)]
10304 mod journal_bound_tests {
10305 //! #6842: bounded autosaves archive superseded journal entries before
10306 //! dropping them from the session document.
10307 use super::*;
10308 use std::collections::HashSet;
10309
10310 fn text(text: &str) -> Message {
10311 Message {
10312 role: codewhale_models::Role::User,
10313 content: vec![ContentBlock::Text {
10314 text: text.into(),
10315 cache_control: None,
10316 }],
10317 }
10318 }
10319
10320 /// A session whose journal holds `rounds` superseded copies of a
10321 /// 10-message tail, as repeated compaction leaves it.
10322 fn compacted_session(id: &str, workspace: &Path, rounds: usize) -> SavedSession {
10323 let mut session = create_saved_session_with_id_and_mode(
10324 id.into(),
10325 &[text("start")],
10326 "test-model",
10327 workspace,
10328 0,
10329 None,
10330 None,
10331 );
10332 let journal = session.journal.as_mut().unwrap();
10333 for round in 0..rounds {
10334 let tail: Vec<Message> = (0..10)
10335 .map(|i| text(&format!("round {round} message {i}")))
10336 .collect();
10337 journal.rebranch_active_messages(&tail);
10338 }
10339 session.leaf_id = journal.leaf_id.clone();
10340 session.messages = journal.to_messages();
10341 session.metadata.message_count = session.messages.len();
10342 session
10343 }
10344
10345 fn all_ids(entries: &[SessionEntry]) -> HashSet<String> {
10346 entries.iter().map(|e| e.id.clone()).collect()
10347 }
10348
10349 #[test]
10350 fn bounded_save_archives_then_prunes_and_live_journal_follows() {
10351 let tmp = tempfile::tempdir().unwrap();
10352 let manager = SessionManager::new(tmp.path().join("sessions")).unwrap();
10353 let session = compacted_session("bounded-a", tmp.path(), 460);
10354 let original = session.journal.clone().unwrap();
10355 let active = original.to_messages();
10356
10357 manager.save_session_bounded(session).unwrap();
10358
10359 let saved = manager.load_session("bounded-a").unwrap();
10360 let journal = saved.journal.as_ref().unwrap();
10361 assert!(
10362 journal.len() <= 10 + JOURNAL_RETAINED_DEAD_ENTRIES,
10363 "{}",
10364 journal.len()
10365 );
10366 assert_eq!(journal.to_messages(), active);
10367 assert_eq!(saved.leaf_id, original.leaf_id);
10368 let archive = manager.load_journal_archive("bounded-a").unwrap();
10369 // Nothing lost: document + archive is exactly the original journal.
10370 let mut union = all_ids(&journal.entries);
10371 union.extend(all_ids(&archive));
10372 assert_eq!(union, all_ids(&original.entries));
10373 assert_eq!(archive.len() + journal.len(), original.len());
10374
10375 // The live journal drops exactly what the save archived.
10376 let mut live = original.clone();
10377 let archived = take_archived_journal_ids("bounded-a");
10378 assert_eq!(archived, all_ids(&archive));
10379 live.remove_entries(&archived).unwrap();
10380 assert_eq!(all_ids(&live.entries), all_ids(&journal.entries));
10381 assert!(take_archived_journal_ids("bounded-a").is_empty());
10382
10383 // A plain save never prunes.
10384 let small = compacted_session("bounded-plain", tmp.path(), 460);
10385 let len = small.journal.as_ref().unwrap().len();
10386 manager.save_session(&small).unwrap();
10387 let reloaded = manager.load_session("bounded-plain").unwrap();
10388 assert_eq!(reloaded.journal.unwrap().len(), len);
10389 }
10390
10391 #[test]
10392 fn archive_failure_prunes_nothing() {
10393 let tmp = tempfile::tempdir().unwrap();
10394 let sessions = tmp.path().join("sessions");
10395 let manager = SessionManager::new(sessions.clone()).unwrap();
10396 // A regular file where the archive directory belongs.
10397 fs::write(sessions.join(JOURNAL_ARCHIVE_DIR), b"not a dir").unwrap();
10398 let session = compacted_session("bounded-b", tmp.path(), 460);
10399 let len = session.journal.as_ref().unwrap().len();
10400 manager.save_session_bounded(session).unwrap();
10401 let saved = manager.load_session("bounded-b").unwrap();
10402 assert_eq!(saved.journal.unwrap().len(), len);
10403 assert!(take_archived_journal_ids("bounded-b").is_empty());
10404 }
10405
10406 #[cfg(unix)]
10407 #[test]
10408 fn archive_written_then_document_write_fails_loses_nothing() {
10409 use std::os::unix::fs::PermissionsExt as _;
10410 let tmp = tempfile::tempdir().unwrap();
10411 let sessions = tmp.path().join("sessions");
10412 let manager = SessionManager::new(sessions.clone()).unwrap();
10413 let session = compacted_session("bounded-c", tmp.path(), 460);
10414 let original = session.journal.clone().unwrap();
10415 manager.save_session(&session).unwrap();
10416 fs::create_dir_all(sessions.join(JOURNAL_ARCHIVE_DIR)).unwrap();
10417 // The archive can be appended, but the document's temp file cannot
10418 // be created: the crash window between the two writes.
10419 fs::set_permissions(&sessions, fs::Permissions::from_mode(0o500)).unwrap();
10420 let failed = manager.save_session_bounded(session.clone());
10421 fs::set_permissions(&sessions, fs::Permissions::from_mode(0o700)).unwrap();
10422 assert!(failed.is_err(), "document write must fail in this setup");
10423 let on_disk = manager.load_session("bounded-c").unwrap();
10424 assert_eq!(on_disk.journal.as_ref().unwrap(), &original);
10425 assert!(
10426 !manager
10427 .load_journal_archive("bounded-c")
10428 .unwrap()
10429 .is_empty()
10430 );
10431 assert!(take_archived_journal_ids("bounded-c").is_empty());
10432
10433 // Retrying archives the same entries again; the reader dedupes and
10434 // the union is still the whole journal.
10435 manager.save_session_bounded(session).unwrap();
10436 let saved = manager.load_session("bounded-c").unwrap();
10437 let archive = manager.load_journal_archive("bounded-c").unwrap();
10438 let mut union = all_ids(&saved.journal.unwrap().entries);
10439 union.extend(all_ids(&archive));
10440 assert_eq!(union, all_ids(&original.entries));
10441 let _ = take_archived_journal_ids("bounded-c");
10442 }
10443
10444 #[test]
10445 fn branch_to_an_archived_entry_restores_its_chain() {
10446 let tmp = tempfile::tempdir().unwrap();
10447 let manager = SessionManager::new(tmp.path().join("sessions")).unwrap();
10448 let session = compacted_session("bounded-d", tmp.path(), 460);
10449 let original = session.journal.clone().unwrap();
10450 manager.save_session_bounded(session).unwrap();
10451 let archived = take_archived_journal_ids("bounded-d");
10452 // The deepest archived entry of the oldest round.
10453 let target = original
10454 .entries
10455 .iter()
10456 .filter(|e| archived.contains(&e.id))
10457 .find(|e| {
10458 e.kind
10459 .as_message()
10460 .is_some_and(|m| m.content == text("round 0 message 9").content)
10461 })
10462 .unwrap()
10463 .id
10464 .clone();
10465
10466 let mut session = manager.load_session("bounded-d").unwrap();
10467 assert!(session.journal_branch_to(&target).is_err());
10468 assert!(
10469 manager
10470 .restore_archived_journal_chain(&mut session, &target)
10471 .unwrap()
10472 );
10473 session.journal_branch_to(&target).unwrap();
10474 manager.save_session(&session).unwrap();
10475 let reloaded = manager.load_session("bounded-d").unwrap();
10476 assert_eq!(reloaded.leaf_id.as_deref(), Some(target.as_str()));
10477 // Each round replaced the whole tail, so round 0 is its own root chain.
10478 let expected: Vec<Message> = (0..10)
10479 .map(|i| text(&format!("round 0 message {i}")))
10480 .collect();
10481 assert_eq!(reloaded.messages, expected);
10482
10483 let mut missing = manager.load_session("bounded-d").unwrap();
10484 assert!(
10485 !manager
10486 .restore_archived_journal_chain(&mut missing, "no-such-entry")
10487 .unwrap()
10488 );
10489 }
10490
10491 #[test]
10492 fn deleting_a_session_removes_its_journal_archive() {
10493 let tmp = tempfile::tempdir().unwrap();
10494 let sessions = tmp.path().join("sessions");
10495 let manager = SessionManager::new(sessions.clone()).unwrap();
10496 manager
10497 .save_session_bounded(compacted_session("bounded-e", tmp.path(), 460))
10498 .unwrap();
10499 let _ = take_archived_journal_ids("bounded-e");
10500 let path = journal_archive_path(&sessions, "bounded-e").unwrap();
10501 assert!(path.exists());
10502 manager.delete_session("bounded-e").unwrap();
10503 assert!(!path.exists());
10504 }
10505
10506 #[test]
10507 fn metadata_larger_than_the_prefix_is_read_without_the_transcript() {
10508 let tmp = tempfile::tempdir().unwrap();
10509 let manager = SessionManager::new(tmp.path().join("sessions")).unwrap();
10510 let mut session = compacted_session("bounded-f", tmp.path(), 10);
10511 for i in 0..9_000 {
10512 session.metadata.cost.usage_source_fingerprints.insert(
10513 crate::cost_status::usage_source_fingerprint(&format!("call-{i}")),
10514 );
10515 }
10516 let path = manager.save_session(&session).unwrap();
10517 // Replace the transcript with 1 MB of non-JSON: listing must still
10518 // find the >64 KB metadata block (the grown read stops once it
10519 // closes; this checks correctness, not how many bytes were read).
10520 let bytes = fs::read(&path).unwrap();
10521 let start = find_json_key(&bytes, b"\"metadata\"").unwrap();
10522 let open = json_value_start(&bytes, start, 10, b'{').unwrap();
10523 let end = json_object_end(&bytes, open).unwrap();
10524 assert!(
10525 end > 64 * 1024,
10526 "metadata must exceed the old prefix: {end}"
10527 );
10528 let mut damaged = bytes[..end].to_vec();
10529 damaged.extend(std::iter::repeat_n(b'x', 1 << 20));
10530 fs::write(&path, &damaged).unwrap();
10531 let metadata = SessionManager::load_session_metadata(&path).unwrap();
10532 assert_eq!(metadata.id, "bounded-f");
10533 assert_eq!(
10534 metadata.cost.usage_source_fingerprints.len(),
10535 crate::cost_status::MAX_USAGE_SOURCE_FINGERPRINTS
10536 );
10537 assert!(
10538 !metadata
10539 .cost
10540 .usage_source_fingerprints
10541 .contains(&crate::cost_status::usage_source_fingerprint("call-0"))
10542 );
10543 assert!(
10544 metadata
10545 .cost
10546 .usage_source_fingerprints
10547 .contains(&crate::cost_status::usage_source_fingerprint("call-8999"))
10548 );
10549 }
10550
10551 #[test]
10552 fn oversized_linear_session_refusal_names_export_and_trim_and_trim_recovers_it() {
10553 let tmp = tempfile::tempdir().unwrap();
10554 let manager = SessionManager::new(tmp.path().join("sessions")).unwrap();
10555 let payload = "a".repeat(220 * 1024);
10556 let mut messages = Vec::new();
10557 for turn in 0..42 {
10558 messages.push(Message {
10559 role: codewhale_models::Role::User,
10560 content: vec![ContentBlock::Text {
10561 text: format!("turn-{turn}-user-{payload}"),
10562 cache_control: None,
10563 }],
10564 });
10565 messages.push(Message {
10566 role: codewhale_models::Role::Assistant,
10567 content: vec![ContentBlock::Text {
10568 text: format!("turn-{turn}-assistant"),
10569 cache_control: None,
10570 }],
10571 });
10572 }
10573 let session = create_saved_session_with_id_and_mode(
10574 "linear-oversized".into(),
10575 &messages,
10576 "test-model",
10577 tmp.path(),
10578 0,
10579 None,
10580 None,
10581 );
10582 let original_entries = session.journal.as_ref().unwrap().entries.clone();
10583 let original_leaf = session.leaf_id.clone();
10584 let path = manager.save_session(&session).unwrap();
10585 let before_bytes = fs::read(&path).unwrap();
10586
10587 let err = manager
10588 .load_session_snapshot_bounded(
10589 "linear-oversized",
10590 codewhale_protocol::MAX_CANONICAL_HISTORY_BYTES,
10591 )
10592 .expect_err("oversized linear trunk must refuse");
10593 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
10594 let msg = err.to_string();
10595 assert!(
10596 msg.contains("codewhale sessions export linear-oversized"),
10597 "{msg}"
10598 );
10599 assert!(
10600 msg.contains("codewhale sessions trim linear-oversized --apply"),
10601 "{msg}"
10602 );
10603 assert_eq!(fs::read(&path).unwrap(), before_bytes);
10604
10605 let dry = manager
10606 .trim_session_for_transport("linear-overs", DEFAULT_SESSION_TRIM_TARGET_BYTES, false)
10607 .unwrap();
10608 assert_eq!(dry.session_id, "linear-oversized");
10609 assert!(!dry.applied);
10610 assert!(dry.archived_active_entries > 0);
10611 assert!(dry.after_carried_bytes <= DEFAULT_SESSION_TRIM_TARGET_BYTES);
10612 assert!(dry.archive_path.is_none());
10613 assert_eq!(fs::read(&path).unwrap(), before_bytes);
10614 assert!(
10615 manager
10616 .load_journal_archive("linear-oversized")
10617 .unwrap()
10618 .is_empty()
10619 );
10620
10621 let applied = manager
10622 .trim_session_for_transport("linear-overs", DEFAULT_SESSION_TRIM_TARGET_BYTES, true)
10623 .unwrap();
10624 assert!(applied.applied);
10625 assert_eq!(applied.archived_active_entries, dry.archived_active_entries);
10626 assert!(applied.after_carried_bytes <= DEFAULT_SESSION_TRIM_TARGET_BYTES);
10627 assert!(applied.archive_path.is_some());
10628
10629 let reopened = manager
10630 .load_session_snapshot_bounded(
10631 "linear-oversized",
10632 codewhale_protocol::MAX_CANONICAL_HISTORY_BYTES,
10633 )
10634 .unwrap();
10635 let kept_journal = reopened.journal.as_ref().unwrap();
10636 assert_eq!(reopened.leaf_id, original_leaf);
10637 assert_eq!(reopened.messages.len(), reopened.metadata.message_count);
10638 assert!(kept_journal.root_to_leaf()[0].parent_id.is_none());
10639 let archived = manager.load_journal_archive("linear-oversized").unwrap();
10640 let mut union = all_ids(&kept_journal.entries);
10641 union.extend(all_ids(&archived));
10642 assert_eq!(union, all_ids(&original_entries));
10643 assert_eq!(
10644 kept_journal.entries.len() + archived.len(),
10645 original_entries.len()
10646 );
10647
10648 let second = manager
10649 .trim_session_for_transport("linear-oversized", DEFAULT_SESSION_TRIM_TARGET_BYTES, true)
10650 .unwrap();
10651 assert!(!second.applied);
10652 assert_eq!(second.archived_active_entries, 0);
10653 }
10654
10655 #[test]
10656 fn trim_aligns_away_from_orphaned_tool_result_and_refuses_live_session() {
10657 let tmp = tempfile::tempdir().unwrap();
10658 let manager = SessionManager::new(tmp.path().join("sessions")).unwrap();
10659 let big_output = "x".repeat(90 * 1024);
10660 let mut messages = Vec::new();
10661 for turn in 0..9 {
10662 messages.push(Message {
10663 role: codewhale_models::Role::User,
10664 content: vec![ContentBlock::Text {
10665 text: format!("prompt-{turn}"),
10666 cache_control: None,
10667 }],
10668 });
10669 messages.push(Message {
10670 role: codewhale_models::Role::Assistant,
10671 content: vec![ContentBlock::ToolUse {
10672 id: format!("call-{turn}"),
10673 name: "read_file".into(),
10674 input: serde_json::json!({ "path": format!("file-{turn}.rs") }),
10675 execution_id: None,
10676 caller: None,
10677 thought_signature: None,
10678 }],
10679 });
10680 messages.push(Message {
10681 role: codewhale_models::Role::User,
10682 content: vec![ContentBlock::ToolResult {
10683 tool_use_id: format!("call-{turn}"),
10684 content: format!("result-{turn}-{big_output}"),
10685 execution_id: None,
10686 is_error: Some(false),
10687 content_blocks: None,
10688 }],
10689 });
10690 }
10691 let session = create_saved_session_with_id_and_mode(
10692 "tool-boundary-trim".into(),
10693 &messages,
10694 "test-model",
10695 tmp.path(),
10696 0,
10697 None,
10698 None,
10699 );
10700 let original_entries = session.journal.as_ref().unwrap().entries.clone();
10701 manager.save_session(&session).unwrap();
10702
10703 let lease = manager
10704 .reserve_session_for_external_write("tool-boundary-trim")
10705 .unwrap();
10706 let dry_live = manager
10707 .trim_session_for_transport("tool-boundary-trim", MIN_SESSION_TRIM_TARGET_BYTES, false)
10708 .unwrap();
10709 assert!(dry_live.session_is_live);
10710 let busy = manager
10711 .trim_session_for_transport("tool-boundary-trim", MIN_SESSION_TRIM_TARGET_BYTES, true)
10712 .expect_err("live session must refuse trim apply");
10713 assert_eq!(busy.kind(), io::ErrorKind::ResourceBusy);
10714 drop(lease);
10715
10716 let report = manager
10717 .trim_session_for_transport("tool-boundary-trim", MIN_SESSION_TRIM_TARGET_BYTES, true)
10718 .unwrap();
10719 assert!(report.applied);
10720 assert!(report.after_carried_bytes <= MIN_SESSION_TRIM_TARGET_BYTES);
10721 let mut reloaded = manager.load_session_snapshot("tool-boundary-trim").unwrap();
10722 let first = &reloaded.messages[0];
10723 assert_eq!(first.role, codewhale_models::Role::User);
10724 assert!(
10725 !first
10726 .content
10727 .iter()
10728 .any(|block| matches!(block, ContentBlock::ToolResult { .. })),
10729 "trimmed session must not start with an orphaned ToolResult"
10730 );
10731 let repair = repair_recovered_session(&mut reloaded);
10732 assert!(repair.is_empty(), "trimmed tail must need zero tool repair");
10733 let archived = manager.load_journal_archive("tool-boundary-trim").unwrap();
10734 let mut union = all_ids(&reloaded.journal.as_ref().unwrap().entries);
10735 union.extend(all_ids(&archived));
10736 assert_eq!(union, all_ids(&original_entries));
10737 }
10738
10739 #[test]
10740 fn journal_archive_rotates_to_xz_segment_losslessly_and_deduplicates_without_losing_branch_or_export()
10741 {
10742 use std::io::Read as _;
10743
10744 let tmp = tempfile::tempdir().unwrap();
10745 let sessions = tmp.path().join("sessions");
10746 let manager = SessionManager::new(sessions.clone()).unwrap();
10747 let session = compacted_session("rotate-xz", tmp.path(), 460);
10748 let original = session.journal.clone().unwrap();
10749 manager.save_session_bounded(session).unwrap();
10750 let archived_ids = take_archived_journal_ids("rotate-xz");
10751 assert!(!archived_ids.is_empty());
10752
10753 let hot_path = journal_archive_path(&sessions, "rotate-xz").unwrap();
10754 assert!(hot_path.exists());
10755 let first_pass = manager.load_journal_archive("rotate-xz").unwrap();
10756 let duplicate_refs: Vec<&SessionEntry> = first_pass.iter().take(5).collect();
10757 manager
10758 .append_journal_archive("rotate-xz", &duplicate_refs)
10759 .unwrap();
10760 assert!(
10761 manager
10762 .rotate_journal_archive_at_threshold("rotate-xz", 1)
10763 .unwrap()
10764 );
10765 let seg_path = journal_archive_segment_path(&sessions, "rotate-xz", 1).unwrap();
10766 assert!(seg_path.exists());
10767 assert!(!hot_path.exists());
10768 #[cfg(unix)]
10769 {
10770 use std::os::unix::fs::PermissionsExt as _;
10771 let mode = fs::metadata(&seg_path).unwrap().permissions().mode() & 0o777;
10772 assert_eq!(mode, 0o600);
10773 }
10774
10775 let after_rotate = manager.load_journal_archive("rotate-xz").unwrap();
10776 assert_eq!(after_rotate.len(), first_pass.len());
10777 assert_eq!(
10778 after_rotate
10779 .iter()
10780 .map(|entry| entry.id.as_str())
10781 .collect::<Vec<_>>(),
10782 first_pass
10783 .iter()
10784 .map(|entry| entry.id.as_str())
10785 .collect::<Vec<_>>()
10786 );
10787
10788 let target = original
10789 .entries
10790 .iter()
10791 .filter(|entry| archived_ids.contains(&entry.id))
10792 .find(|entry| {
10793 entry
10794 .kind
10795 .as_message()
10796 .is_some_and(|msg| msg.content == text("round 0 message 9").content)
10797 })
10798 .unwrap()
10799 .id
10800 .clone();
10801 let mut restored_session = manager.load_session("rotate-xz").unwrap();
10802 assert!(
10803 manager
10804 .restore_archived_journal_chain(&mut restored_session, &target)
10805 .unwrap()
10806 );
10807 restored_session.journal_branch_to(&target).unwrap();
10808
10809 let snapshot = manager.load_session_snapshot("rotate-xz").unwrap();
10810 let export_path = tmp.path().join("rotate-xz.tar.xz");
10811 crate::session_export::write_session_archive(
10812 &snapshot,
10813 Some(&sessions),
10814 &export_path,
10815 crate::session_export::SessionArchiveOptions {
10816 include_artifacts: false,
10817 compression_level: 0,
10818 overwrite: true,
10819 },
10820 )
10821 .unwrap();
10822 let mut tar = tar::Archive::new(liblzma::read::XzDecoder::new(
10823 fs::File::open(&export_path).unwrap(),
10824 ));
10825 let mut container_raw = String::new();
10826 for entry in tar.entries().unwrap() {
10827 let mut entry = entry.unwrap();
10828 if entry.path().unwrap() == Path::new("container.json") {
10829 entry.read_to_string(&mut container_raw).unwrap();
10830 }
10831 }
10832 let container: SessionImportContainer = serde_json::from_str(&container_raw).unwrap();
10833 assert!(container.entries.iter().any(|entry| entry.id == target));
10834 assert_eq!(all_ids(&container.entries), all_ids(&original.entries));
10835
10836 manager.delete_session("rotate-xz").unwrap();
10837 assert!(!seg_path.exists());
10838 assert!(!hot_path.exists());
10839 }
10840
10841 #[test]
10842 fn journal_archive_summary_and_id_scan_stream_without_loading_full_entries() {
10843 use std::io::Write as _;
10844
10845 let tmp = tempfile::tempdir().unwrap();
10846 let sessions = tmp.path().join("sessions");
10847 let manager = SessionManager::new(sessions.clone()).unwrap();
10848 let session = compacted_session("stream-summary", tmp.path(), 460);
10849 manager.save_session_bounded(session).unwrap();
10850 let _ = take_archived_journal_ids("stream-summary");
10851
10852 let original = manager.load_journal_archive("stream-summary").unwrap();
10853 assert!(original.len() >= 3);
10854 let split = original.len() / 2;
10855 let first_half: Vec<&SessionEntry> = original[..split].iter().collect();
10856 let second_half: Vec<&SessionEntry> = original[split..].iter().collect();
10857 manager.remove_journal_archive("stream-summary").unwrap();
10858
10859 manager
10860 .append_journal_archive("stream-summary", &first_half)
10861 .unwrap();
10862 assert!(
10863 manager
10864 .rotate_journal_archive_at_threshold("stream-summary", 1)
10865 .unwrap()
10866 );
10867 let mut hot_batch = vec![first_half[0]];
10868 hot_batch.extend(second_half);
10869 manager
10870 .append_journal_archive("stream-summary", &hot_batch)
10871 .unwrap();
10872
10873 let hot_path = journal_archive_path(&sessions, "stream-summary").unwrap();
10874 let mut hot_file = OpenOptions::new().append(true).open(&hot_path).unwrap();
10875 hot_file.write_all(b"{\"id\":\"torn-entry\"").unwrap();
10876 hot_file.sync_all().unwrap();
10877 drop(hot_file);
10878
10879 let summary = manager
10880 .journal_archive_summary("stream-summary")
10881 .unwrap()
10882 .expect("summary present");
10883 assert_eq!(summary.unique_entries, original.len());
10884 assert_eq!(summary.duplicate_lines, 1);
10885 assert_eq!(summary.segment_count, 2);
10886 assert!(summary.raw_bytes > 0);
10887 assert!(summary.compressed_bytes > 0);
10888 assert_eq!(
10889 summary.total_bytes,
10890 summary.raw_bytes + summary.compressed_bytes
10891 );
10892
10893 let scanned_ids = manager.load_journal_archive_ids("stream-summary").unwrap();
10894 let loaded = manager.load_journal_archive("stream-summary").unwrap();
10895 assert_eq!(scanned_ids, all_ids(&loaded));
10896 assert_eq!(loaded.len(), original.len());
10897 }
10898
10899 #[test]
10900 fn sessions_archive_inspect_compact_and_prune_respect_dry_run_orphans_and_live_lease() {
10901 let tmp = tempfile::tempdir().unwrap();
10902 let sessions = tmp.path().join("sessions");
10903 let manager = SessionManager::new(sessions.clone()).unwrap();
10904
10905 let empty_dir = tmp.path().join("fresh-sessions");
10906 let empty_inv = SessionManager::inspect_journal_archives_read_only(&empty_dir).unwrap();
10907 assert!(!empty_inv.present);
10908 assert!(empty_inv.sessions.is_empty());
10909 assert!(!empty_dir.exists());
10910
10911 let active = compacted_session("active-arch", tmp.path(), 460);
10912 manager.save_session_bounded(active).unwrap();
10913 let _ = take_archived_journal_ids("active-arch");
10914 let active_entries = manager.load_journal_archive("active-arch").unwrap();
10915 let dup_slice: Vec<&SessionEntry> = active_entries.iter().take(4).collect();
10916 manager
10917 .append_journal_archive("active-arch", &dup_slice)
10918 .unwrap();
10919
10920 let mut archived = compacted_session("archived-arch", tmp.path(), 460);
10921 archived.metadata.archived = true;
10922 manager.save_session_bounded(archived).unwrap();
10923 let _ = take_archived_journal_ids("archived-arch");
10924
10925 let orphan_source = compacted_session("orphan-arch", tmp.path(), 460);
10926 manager.save_session_bounded(orphan_source).unwrap();
10927 let _ = take_archived_journal_ids("orphan-arch");
10928 fs::remove_file(sessions.join("orphan-arch.json")).unwrap();
10929
10930 let inventory = SessionManager::inspect_journal_archives_read_only(&sessions).unwrap();
10931 assert!(inventory.present);
10932 assert_eq!(inventory.sessions.len(), 3);
10933 assert_eq!(inventory.orphaned_sessions, 1);
10934 assert!(inventory.orphaned_bytes > 0);
10935 let status_for = |id: &str| {
10936 inventory
10937 .sessions
10938 .iter()
10939 .find(|record| record.session_id == id)
10940 .map(|record| record.status)
10941 };
10942 assert_eq!(
10943 status_for("active-arch"),
10944 Some(JournalArchiveSessionStatus::Active)
10945 );
10946 assert_eq!(
10947 status_for("archived-arch"),
10948 Some(JournalArchiveSessionStatus::Archived)
10949 );
10950 assert_eq!(
10951 status_for("orphan-arch"),
10952 Some(JournalArchiveSessionStatus::Orphaned)
10953 );
10954
10955 let active_hot = journal_archive_path(&sessions, "active-arch").unwrap();
10956 let active_before_bytes = fs::read(&active_hot).unwrap();
10957 let dry_compact = manager
10958 .compact_journal_archives(Some("active-arch"), false)
10959 .unwrap();
10960 assert!(!dry_compact.applied);
10961 assert_eq!(dry_compact.entries.len(), 1);
10962 assert_eq!(dry_compact.duplicate_lines_removed, 4);
10963 assert_eq!(fs::read(&active_hot).unwrap(), active_before_bytes);
10964
10965 let lease = manager
10966 .reserve_session_for_external_write("active-arch")
10967 .unwrap();
10968 let busy_compact = manager
10969 .compact_journal_archives(Some("active-arch"), true)
10970 .expect_err("live session must refuse compact --apply");
10971 assert_eq!(busy_compact.kind(), io::ErrorKind::ResourceBusy);
10972 let busy_prune = manager
10973 .prune_journal_archives(&JournalArchivePruneOptions {
10974 session_id: Some("active-arch".to_string()),
10975 apply: true,
10976 ..JournalArchivePruneOptions::default()
10977 })
10978 .expect_err("live session must refuse prune --apply");
10979 assert_eq!(busy_prune.kind(), io::ErrorKind::ResourceBusy);
10980 drop(lease);
10981
10982 let applied_compact = manager
10983 .compact_journal_archives(Some("active-arch"), true)
10984 .unwrap();
10985 assert!(applied_compact.applied);
10986 assert_eq!(applied_compact.entries.len(), 1);
10987 assert_eq!(applied_compact.entries[0].duplicate_lines_removed, 4);
10988 assert!(applied_compact.after_bytes < applied_compact.before_bytes);
10989 assert!(!active_hot.exists());
10990 assert_eq!(
10991 manager.load_journal_archive("active-arch").unwrap().len(),
10992 active_entries.len()
10993 );
10994
10995 let selector_err = manager
10996 .prune_journal_archives(&JournalArchivePruneOptions {
10997 apply: true,
10998 ..JournalArchivePruneOptions::default()
10999 })
11000 .expect_err("prune without selector must fail closed");
11001 assert_eq!(selector_err.kind(), io::ErrorKind::InvalidInput);
11002
11003 let dry_orphans = manager
11004 .prune_journal_archives(&JournalArchivePruneOptions {
11005 orphans_only: true,
11006 apply: false,
11007 ..JournalArchivePruneOptions::default()
11008 })
11009 .unwrap();
11010 assert!(!dry_orphans.applied);
11011 assert_eq!(dry_orphans.targets.len(), 1);
11012 assert_eq!(dry_orphans.targets[0].session_id, "orphan-arch");
11013 assert!(
11014 journal_archive_path(&sessions, "orphan-arch")
11015 .unwrap()
11016 .exists()
11017 );
11018
11019 let applied_orphans = manager
11020 .prune_journal_archives(&JournalArchivePruneOptions {
11021 orphans_only: true,
11022 apply: true,
11023 ..JournalArchivePruneOptions::default()
11024 })
11025 .unwrap();
11026 assert!(applied_orphans.applied);
11027 assert_eq!(applied_orphans.removed_files, 1);
11028 assert!(
11029 !journal_archive_path(&sessions, "orphan-arch")
11030 .unwrap()
11031 .exists()
11032 );
11033 assert!(
11034 !manager
11035 .load_journal_archive("active-arch")
11036 .unwrap()
11037 .is_empty()
11038 );
11039 assert!(
11040 !manager
11041 .load_journal_archive("archived-arch")
11042 .unwrap()
11043 .is_empty()
11044 );
11045
11046 let applied_session_prune = manager
11047 .prune_journal_archives(&JournalArchivePruneOptions {
11048 session_id: Some("archived-arch".to_string()),
11049 apply: true,
11050 ..JournalArchivePruneOptions::default()
11051 })
11052 .unwrap();
11053 assert!(applied_session_prune.applied);
11054 assert_eq!(applied_session_prune.removed_files, 1);
11055 assert!(
11056 manager
11057 .load_journal_archive("archived-arch")
11058 .unwrap()
11059 .is_empty()
11060 );
11061 let intact = manager.load_session("archived-arch").unwrap();
11062 assert_eq!(intact.metadata.id, "archived-arch");
11063
11064 #[cfg(unix)]
11065 {
11066 let link_root = tmp.path().join("linked-sessions");
11067 let outside = tmp.path().join("outside-archive");
11068 fs::create_dir_all(&link_root).unwrap();
11069 fs::create_dir_all(&outside).unwrap();
11070 std::os::unix::fs::symlink(&outside, link_root.join(JOURNAL_ARCHIVE_DIR)).unwrap();
11071 let err = SessionManager::inspect_journal_archives_read_only(&link_root)
11072 .expect_err("symlinked .journal-archive must be rejected");
11073 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
11074 }
11075 }
11076
11077 #[test]
11078 fn sessions_archive_prune_older_than_days_and_multi_session_skip_live() {
11079 let tmp = tempfile::tempdir().unwrap();
11080 let sessions = tmp.path().join("sessions");
11081 let manager = SessionManager::new(sessions.clone()).unwrap();
11082
11083 let aged = compacted_session("aged-arch", tmp.path(), 460);
11084 manager.save_session_bounded(aged).unwrap();
11085 let _ = take_archived_journal_ids("aged-arch");
11086
11087 let fresh = compacted_session("fresh-arch", tmp.path(), 460);
11088 manager.save_session_bounded(fresh).unwrap();
11089 let _ = take_archived_journal_ids("fresh-arch");
11090
11091 let dry_fresh_only = manager
11092 .prune_journal_archives(&JournalArchivePruneOptions {
11093 older_than_days: Some(30),
11094 apply: false,
11095 ..JournalArchivePruneOptions::default()
11096 })
11097 .unwrap();
11098 assert!(dry_fresh_only.targets.is_empty());
11099
11100 let aged_hot = journal_archive_path(&sessions, "aged-arch").unwrap();
11101 let old_time = std::time::SystemTime::now() - std::time::Duration::from_secs(45 * 86_400);
11102 fs::File::options()
11103 .write(true)
11104 .open(&aged_hot)
11105 .unwrap()
11106 .set_times(fs::FileTimes::new().set_modified(old_time))
11107 .unwrap();
11108
11109 let dry_30d = manager
11110 .prune_journal_archives(&JournalArchivePruneOptions {
11111 older_than_days: Some(30),
11112 apply: false,
11113 ..JournalArchivePruneOptions::default()
11114 })
11115 .unwrap();
11116 assert_eq!(dry_30d.targets.len(), 1);
11117 assert_eq!(dry_30d.targets[0].session_id, "aged-arch");
11118
11119 let dry_0d = manager
11120 .prune_journal_archives(&JournalArchivePruneOptions {
11121 older_than_days: Some(0),
11122 apply: false,
11123 ..JournalArchivePruneOptions::default()
11124 })
11125 .unwrap();
11126 assert_eq!(dry_0d.targets.len(), 2);
11127
11128 let (_, lock_path) = manager.ensure_late_usage_paths("aged-arch").unwrap();
11129 let (locked_tx, locked_rx) = std::sync::mpsc::channel();
11130 let aged_hot_for_touch = aged_hot.clone();
11131 let holder = std::thread::spawn(move || {
11132 let lock_file = open_private_lock_file(&lock_path).unwrap();
11133 let mut lock = fd_lock::RwLock::new(lock_file);
11134 let _guard = lock.write().unwrap();
11135 locked_tx.send(()).unwrap();
11136 std::thread::sleep(std::time::Duration::from_millis(50));
11137 fs::File::options()
11138 .write(true)
11139 .open(&aged_hot_for_touch)
11140 .unwrap()
11141 .set_times(fs::FileTimes::new().set_modified(std::time::SystemTime::now()))
11142 .unwrap();
11143 });
11144 locked_rx.recv().unwrap();
11145 let raced_prune = manager
11146 .prune_journal_archives(&JournalArchivePruneOptions {
11147 older_than_days: Some(30),
11148 apply: true,
11149 ..JournalArchivePruneOptions::default()
11150 })
11151 .unwrap();
11152 holder.join().unwrap();
11153 assert_eq!(raced_prune.removed_files, 0);
11154 assert!(raced_prune.targets.is_empty());
11155 assert!(aged_hot.exists());
11156 let latest = manager
11157 .latest_journal_archive_modified_at("aged-arch")
11158 .unwrap()
11159 .expect("modified timestamp");
11160 assert!(latest > Utc::now() - chrono::Duration::days(1));
11161
11162 let lease = manager
11163 .reserve_session_for_external_write("fresh-arch")
11164 .unwrap();
11165 let compact_all = manager.compact_journal_archives(None, true).unwrap();
11166 assert!(compact_all.applied);
11167 assert_eq!(compact_all.entries.len(), 1);
11168 assert_eq!(compact_all.entries[0].session_id, "aged-arch");
11169 assert_eq!(compact_all.skipped_live_sessions, vec!["fresh-arch"]);
11170 assert!(
11171 journal_archive_path(&sessions, "fresh-arch")
11172 .unwrap()
11173 .exists()
11174 );
11175 assert_eq!(
11176 manager
11177 .compact_journal_archives(Some("fresh-arch"), true)
11178 .unwrap_err()
11179 .kind(),
11180 io::ErrorKind::ResourceBusy
11181 );
11182
11183 let prune_all = manager
11184 .prune_journal_archives(&JournalArchivePruneOptions {
11185 older_than_days: Some(0),
11186 apply: true,
11187 ..JournalArchivePruneOptions::default()
11188 })
11189 .unwrap();
11190 assert!(prune_all.applied);
11191 assert_eq!(prune_all.targets.len(), 1);
11192 assert_eq!(prune_all.targets[0].session_id, "aged-arch");
11193 assert_eq!(prune_all.skipped_live_sessions, vec!["fresh-arch"]);
11194 assert!(
11195 journal_archive_path(&sessions, "fresh-arch")
11196 .unwrap()
11197 .exists()
11198 );
11199 assert!(
11200 manager
11201 .load_journal_archive("aged-arch")
11202 .unwrap()
11203 .is_empty()
11204 );
11205 assert_eq!(
11206 manager
11207 .prune_journal_archives(&JournalArchivePruneOptions {
11208 session_id: Some("fresh-arch".to_string()),
11209 apply: true,
11210 ..JournalArchivePruneOptions::default()
11211 })
11212 .unwrap_err()
11213 .kind(),
11214 io::ErrorKind::ResourceBusy
11215 );
11216 drop(lease);
11217 }
11218 }
11219
11219 lines RUST