1use merry_core::SessionId;
2use std::{
3 env,
4 ffi::OsStr,
5 fs::{File, OpenOptions as StdOpenOptions},
6 path::{Path, PathBuf},
7 sync::Arc,
8};
9use thiserror::Error;
10use tokio::{fs::OpenOptions, io::AsyncWriteExt, sync::Mutex};
11
12#[cfg(unix)]
13use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
14
15const JOURNAL_FILE_NAME: &str = "journal.jsonl";
16
17const LEGACY_STATE_FILE_NAME: &str = "state.json";
18
19const SESSION_LOCK_FILE_NAME: &str = ".session.lock";
20
21const PLANS_DIR_NAME: &str = "plans";
22
23#[cfg(test)]
24use std::sync::atomic::{AtomicBool, Ordering};
25
26#[cfg(test)]
27use tokio::sync::Notify;
28
29#[derive(Debug, Error)]
30pub enum SessionStoreError {
31 #[error("could not resolve XDG state home: neither XDG_STATE_HOME nor HOME is set")]
32 StateHomeUnavailable,
33 #[error("session store path {path} is invalid: {reason}")]
34 InvalidPath { path: PathBuf, reason: &'static str },
35 #[error("session store IO error at {path}: {source}")]
36 Io {
37 path: PathBuf,
38 #[source]
39 source: std::io::Error,
40 },
41 #[error("session state JSON error: {source}")]
42 Json {
43 #[from]
44 source: serde_json::Error,
45 },
46 #[error("session document format version {actual} is not supported")]
47 UnsupportedFormatVersion { actual: u32 },
48 #[error("session document id {actual} does not match requested session {requested}")]
49 SessionIdMismatch {
50 requested: SessionId,
51 actual: SessionId,
52 },
53 #[error("session {session_id} is already reserved by another run")]
54 SessionAlreadyReserved { session_id: SessionId },
55 #[error(
56 "session {session_id} has {pending_count} pending tool calls and cannot be saved at an incomplete tool boundary"
57 )]
58 UnsafePendingToolCalls {
59 session_id: SessionId,
60 pending_count: usize,
61 },
62 #[error("session document is invalid: {reason}")]
63 InvalidDocument { reason: &'static str },
64}
65
66#[derive(Debug, Clone)]
73pub struct FileSessionStore {
74 sessions_dir: PathBuf,
75 write_lock: Arc<Mutex<()>>,
76 #[cfg(test)]
77 stage_pause: Option<SessionStoreStagePause>,
78 #[cfg(test)]
79 commit_pause: Option<SessionStoreCommitPause>,
80 #[cfg(test)]
81 fail_commit: bool,
82 #[cfg(test)]
83 fail_directory_sync: bool,
84}
85
86#[derive(Debug)]
90pub struct SessionReservation {
91 _lock_file: File,
92}
93
94#[derive(Debug)]
100pub(crate) struct StagedSessionBundle {
101 final_path: PathBuf,
102 header_bytes: Vec<u8>,
103 commit_bytes: Vec<u8>,
104 write_lock: Arc<Mutex<()>>,
105 search: Option<search::SessionSearchUpdate>,
106 rotation: Option<crate::session::PreparedJournalRotation>,
107 #[cfg(test)]
108 commit_pause: Option<SessionStoreCommitPause>,
109 #[cfg(test)]
110 fail_commit: bool,
111 #[cfg(test)]
112 fail_directory_sync: bool,
113}
114
115#[derive(Debug)]
116#[must_use = "an appended session commit must be checked for directory durability"]
117pub(crate) enum StagedSessionCommit {
118 Durable,
119 AppendedButNotSynced(SessionStoreError),
120}
121
122impl StagedSessionCommit {
123 pub(crate) fn require_durable(self) -> Result<(), SessionStoreError> {
124 match self {
125 Self::Durable => Ok(()),
126 Self::AppendedButNotSynced(error) => Err(error),
127 }
128 }
129}
130
131impl StagedSessionBundle {
132 pub(crate) async fn commit(self) -> Result<StagedSessionCommit, SessionStoreError> {
133 #[cfg(test)]
134 if self.fail_commit {
135 return Err(io_error(
136 self.final_path,
137 std::io::Error::other("injected session store commit failure"),
138 ));
139 }
140
141 let created = {
142 let _guard = self.write_lock.lock().await;
143 if let Some(rotation) = self.rotation {
144 crate::session::commit_journal_rotation(
145 &self.final_path,
146 &self.header_bytes,
147 &self.commit_bytes,
148 rotation,
149 )
150 .await?;
151 true
152 } else {
153 append_journal_bytes(&self.final_path, &self.header_bytes, &self.commit_bytes)
154 .await?
155 }
156 };
157
158 #[cfg(test)]
159 if let Some(pause) = &self.commit_pause {
160 pause.pause_once().await;
161 }
162
163 if let Some(search) = self.search {
164 search::upsert_user_text(search).await;
165 }
166
167 #[cfg(test)]
168 if self.fail_directory_sync {
169 return Ok(StagedSessionCommit::AppendedButNotSynced(io_error(
170 self.final_path
171 .parent()
172 .unwrap_or(self.final_path.as_path())
173 .to_path_buf(),
174 std::io::Error::other("injected session directory sync failure"),
175 )));
176 }
177
178 if created {
179 match sync_parent_directory(&self.final_path).await {
180 Ok(()) => Ok(StagedSessionCommit::Durable),
181 Err(error) => Ok(StagedSessionCommit::AppendedButNotSynced(error)),
182 }
183 } else {
184 Ok(StagedSessionCommit::Durable)
185 }
186 }
187
188 pub(crate) async fn discard(self) -> Result<(), SessionStoreError> {
189 Ok(())
190 }
191}
192
193#[cfg(test)]
194#[derive(Debug, Clone)]
195pub(crate) struct SessionStoreStagePause {
196 inner: Arc<SessionStoreStagePauseInner>,
197}
198
199#[cfg(test)]
200#[derive(Debug)]
201struct SessionStoreStagePauseInner {
202 claimed: AtomicBool,
203 staged: Notify,
204 resume: Notify,
205}
206
207#[cfg(test)]
208#[derive(Debug, Clone)]
209pub(crate) struct SessionStoreCommitPause {
210 inner: Arc<SessionStoreCommitPauseInner>,
211}
212
213#[cfg(test)]
214#[derive(Debug)]
215struct SessionStoreCommitPauseInner {
216 claimed: AtomicBool,
217 committed: Notify,
218 resume: Notify,
219}
220
221#[cfg(test)]
222impl SessionStoreStagePause {
223 pub(crate) fn new() -> Self {
224 Self {
225 inner: Arc::new(SessionStoreStagePauseInner {
226 claimed: AtomicBool::new(false),
227 staged: Notify::new(),
228 resume: Notify::new(),
229 }),
230 }
231 }
232
233 pub(crate) async fn wait_until_staged(&self) {
234 self.inner.staged.notified().await;
235 }
236
237 pub(crate) fn resume(&self) {
238 self.inner.resume.notify_one();
239 }
240
241 async fn pause_once(&self) {
242 if self.inner.claimed.swap(true, Ordering::AcqRel) {
243 return;
244 }
245 self.inner.staged.notify_one();
246 self.inner.resume.notified().await;
247 }
248}
249
250#[cfg(test)]
251impl SessionStoreCommitPause {
252 pub(crate) fn new() -> Self {
253 Self {
254 inner: Arc::new(SessionStoreCommitPauseInner {
255 claimed: AtomicBool::new(false),
256 committed: Notify::new(),
257 resume: Notify::new(),
258 }),
259 }
260 }
261
262 pub(crate) async fn wait_until_committed(&self) {
263 self.inner.committed.notified().await;
264 }
265
266 pub(crate) fn resume(&self) {
267 self.inner.resume.notify_one();
268 }
269
270 async fn pause_once(&self) {
271 if self.inner.claimed.swap(true, Ordering::AcqRel) {
272 return;
273 }
274 self.inner.committed.notify_one();
275 self.inner.resume.notified().await;
276 }
277}
278
279impl FileSessionStore {
280 pub fn default_sessions_dir() -> Result<PathBuf, SessionStoreError> {
281 let xdg_state_home = env::var_os("XDG_STATE_HOME");
282 if let Some(root) = non_empty_os_str(xdg_state_home.as_deref()) {
283 return Ok(PathBuf::from(root).join("merry").join("sessions"));
284 }
285 let local_appdata = env::var_os("LOCALAPPDATA").map(PathBuf::from);
286 if cfg!(windows)
287 && let Some(local) = local_appdata
288 .as_deref()
289 .filter(|path| !path.as_os_str().is_empty() && path.is_absolute())
290 {
291 return Ok(local.join("merry").join("sessions"));
292 }
293 let Some(home) = merry_core::host_paths::user_home_dir() else {
294 return Err(SessionStoreError::StateHomeUnavailable);
295 };
296 let state_base =
297 merry_core::host_paths::platform_state_base(&home, None, local_appdata.as_deref());
298 Ok(state_base.join("merry").join("sessions"))
299 }
300
301 pub fn default_store() -> Result<Self, SessionStoreError> {
302 Ok(Self::new(Self::default_sessions_dir()?))
303 }
304
305 #[must_use]
309 pub fn new(root: impl AsRef<Path>) -> Self {
310 Self {
311 sessions_dir: root.as_ref().to_path_buf(),
312 write_lock: Arc::new(Mutex::new(())),
313 #[cfg(test)]
314 stage_pause: None,
315 #[cfg(test)]
316 commit_pause: None,
317 #[cfg(test)]
318 fail_commit: false,
319 #[cfg(test)]
320 fail_directory_sync: false,
321 }
322 }
323
324 #[must_use]
325 pub fn sessions_dir(&self) -> &Path {
326 &self.sessions_dir
327 }
328
329 #[must_use]
335 pub fn subagents_store(&self, parent_session_id: &SessionId) -> Self {
336 Self::new(self.session_dir(parent_session_id).join("subagents"))
337 }
338
339 pub async fn reserve_session(
347 &self,
348 session_id: &SessionId,
349 ) -> Result<SessionReservation, SessionStoreError> {
350 let session_dir = self.session_dir(session_id);
351 tokio::fs::create_dir_all(&session_dir)
352 .await
353 .map_err(|source| io_error(session_dir.clone(), source))?;
354 let lock_path = session_dir.join(SESSION_LOCK_FILE_NAME);
355 let session_id = session_id.clone();
356 let lock_file = tokio::task::spawn_blocking({
357 let lock_path = lock_path.clone();
358 move || {
359 let mut options = StdOpenOptions::new();
360 options.read(true).write(true).create(true);
361 #[cfg(unix)]
362 options.mode(0o600);
363 let file = options
364 .open(&lock_path)
365 .map_err(|source| io_error(lock_path.clone(), source))?;
366 #[cfg(unix)]
367 file.set_permissions(std::fs::Permissions::from_mode(0o600))
368 .map_err(|source| io_error(lock_path.clone(), source))?;
369 match file.try_lock() {
370 Ok(()) => Ok(file),
371 Err(std::fs::TryLockError::WouldBlock) => {
372 Err(SessionStoreError::SessionAlreadyReserved {
373 session_id: session_id.clone(),
374 })
375 }
376 Err(std::fs::TryLockError::Error(source)) => Err(io_error(lock_path, source)),
377 }
378 }
379 })
380 .await
381 .map_err(|source| {
382 io_error(
383 lock_path,
384 std::io::Error::other(format!("session reservation task failed: {source}")),
385 )
386 })??;
387 Ok(SessionReservation {
388 _lock_file: lock_file,
389 })
390 }
391
392 pub async fn release_empty_reservation(
396 &self,
397 session_id: &SessionId,
398 reservation: SessionReservation,
399 ) {
400 let session_dir = self.session_dir(session_id);
401 let mut has_other_entries = false;
402 match tokio::fs::read_dir(&session_dir).await {
403 Ok(mut entries) => {
404 while let Ok(Some(entry)) = entries.next_entry().await {
405 if entry.file_name() != OsStr::new(SESSION_LOCK_FILE_NAME) {
406 has_other_entries = true;
407 break;
408 }
409 }
410 }
411 Err(_) => {
412 drop(reservation);
413 return;
414 }
415 }
416 drop(reservation);
417 if has_other_entries {
418 return;
419 }
420 let _ = tokio::fs::remove_file(session_dir.join(SESSION_LOCK_FILE_NAME)).await;
421 let _ = tokio::fs::remove_dir(&session_dir).await;
422 }
423
424 pub async fn contains_session(
431 &self,
432 session_id: &SessionId,
433 ) -> Result<bool, SessionStoreError> {
434 for name in [JOURNAL_FILE_NAME, LEGACY_STATE_FILE_NAME] {
435 let path = self.session_dir(session_id).join(name);
436 if tokio::fs::try_exists(&path)
437 .await
438 .map_err(|source| io_error(path.clone(), source))?
439 {
440 return Ok(true);
441 }
442 }
443 Ok(false)
444 }
445
446 #[must_use]
448 pub fn session_dir(&self, session_id: &SessionId) -> PathBuf {
449 self.sessions_dir.join(session_id.as_str())
450 }
451
452 pub(crate) fn journal_path(&self, session_id: &SessionId) -> PathBuf {
453 self.session_dir(session_id).join(JOURNAL_FILE_NAME)
454 }
455
456 #[cfg(test)]
457 pub(crate) async fn overwrite_journal_bytes(
458 &self,
459 session_id: &SessionId,
460 bytes: &[u8],
461 ) -> Result<(), SessionStoreError> {
462 let session_dir = self.session_dir(session_id);
463 tokio::fs::create_dir_all(&session_dir)
464 .await
465 .map_err(|source| io_error(session_dir.clone(), source))?;
466 let path = self.journal_path(session_id);
467 let _guard = self.write_lock.lock().await;
468 tokio::fs::write(&path, bytes)
469 .await
470 .map_err(|source| io_error(path, source))
471 }
472
473 #[cfg(test)]
474 pub(crate) async fn write_state_bytes(
475 &self,
476 session_id: &SessionId,
477 bytes: &[u8],
478 ) -> Result<(), SessionStoreError> {
479 self.overwrite_journal_bytes(session_id, bytes).await
480 }
481
482 pub(crate) async fn stage_journal_append(
483 &self,
484 session_id: &SessionId,
485 header_bytes: Vec<u8>,
486 commit_bytes: Vec<u8>,
487 images: &[crate::session::JournalImageFile],
488 search_user_text: Option<String>,
489 rotation: Option<crate::session::PreparedJournalRotation>,
490 ) -> Result<StagedSessionBundle, SessionStoreError> {
491 let session_dir = self.session_dir(session_id);
492 tokio::fs::create_dir_all(&session_dir)
493 .await
494 .map_err(|source| io_error(session_dir.clone(), source))?;
495 self.write_journal_images(session_id, images).await?;
496 if let Some(rot) = rotation.as_ref() {
497 self.write_journal_images(session_id, &rot.archive_images)
498 .await?;
499 }
500
501 #[cfg(test)]
502 if let Some(pause) = &self.stage_pause {
503 pause.pause_once().await;
504 }
505
506 Ok(StagedSessionBundle {
507 final_path: session_dir.join(JOURNAL_FILE_NAME),
508 header_bytes,
509 commit_bytes,
510 write_lock: Arc::clone(&self.write_lock),
511 search: search_user_text.map(|user_text| search::SessionSearchUpdate {
512 sessions_dir: self.sessions_dir.clone(),
513 session_id: session_id.clone(),
514 user_text,
515 }),
516 rotation,
517 #[cfg(test)]
518 commit_pause: self.commit_pause.clone(),
519 #[cfg(test)]
520 fail_commit: self.fail_commit,
521 #[cfg(test)]
522 fail_directory_sync: self.fail_directory_sync,
523 })
524 }
525
526 async fn write_journal_images(
527 &self,
528 session_id: &SessionId,
529 images: &[crate::session::JournalImageFile],
530 ) -> Result<(), SessionStoreError> {
531 if images.is_empty() {
532 return Ok(());
533 }
534 let directory = self.session_dir(session_id).join("images");
535 tokio::fs::create_dir_all(&directory)
536 .await
537 .map_err(|source| io_error(directory.clone(), source))?;
538 for image in images {
539 if !crate::session::is_image_id(&image.id) {
540 return Err(SessionStoreError::InvalidDocument {
541 reason: "session journal image id is invalid",
542 });
543 }
544 let path = directory.join(format!("{}.png", image.id));
545 let mut options = OpenOptions::new();
546 options.write(true).create_new(true);
547 #[cfg(unix)]
548 options.mode(0o600);
549 let mut file = match options.open(&path).await {
550 Ok(file) => file,
551 Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => continue,
552 Err(source) => return Err(io_error(path, source)),
553 };
554 file.write_all(&image.bytes)
555 .await
556 .map_err(|source| io_error(path.clone(), source))?;
557 file.sync_all()
558 .await
559 .map_err(|source| io_error(path, source))?;
560 }
561 Ok(())
562 }
563
564 pub(crate) async fn read_journal_bytes(
565 &self,
566 session_id: &SessionId,
567 ) -> Result<Vec<u8>, SessionStoreError> {
568 let path = self.journal_path(session_id);
569 tokio::fs::read(&path)
570 .await
571 .map_err(|source| io_error(path, source))
572 }
573
574 pub(crate) async fn truncate_journal_tail(
577 &self,
578 session_id: &SessionId,
579 valid_len: u64,
580 ) -> Result<(), SessionStoreError> {
581 let path = self.journal_path(session_id);
582 let _guard = self.write_lock.lock().await;
583 let file = OpenOptions::new()
584 .write(true)
585 .open(&path)
586 .await
587 .map_err(|source| io_error(path.clone(), source))?;
588 let current_len = file
589 .metadata()
590 .await
591 .map_err(|source| io_error(path.clone(), source))?
592 .len();
593 if current_len > valid_len {
594 file.set_len(valid_len)
595 .await
596 .map_err(|source| io_error(path.clone(), source))?;
597 file.sync_all()
598 .await
599 .map_err(|source| io_error(path, source))?;
600 }
601 Ok(())
602 }
603
604 #[cfg(test)]
605 pub(crate) async fn read_state_bytes(
606 &self,
607 session_id: &SessionId,
608 ) -> Result<Vec<u8>, SessionStoreError> {
609 self.read_journal_bytes(session_id).await
610 }
611
612 pub(crate) async fn write_plan_file(
614 &self,
615 session_id: &SessionId,
616 file_name: &str,
617 content: &str,
618 ) -> Result<PathBuf, SessionStoreError> {
619 if crate::plan::validate_plan_file_name(file_name).is_err() {
620 return Err(SessionStoreError::InvalidDocument {
621 reason: "plan file name is invalid",
622 });
623 }
624 let directory = self.session_dir(session_id).join(PLANS_DIR_NAME);
625 tokio::fs::create_dir_all(&directory)
626 .await
627 .map_err(|source| io_error(directory.clone(), source))?;
628 let path = directory.join(file_name);
629 let tmp_path = directory.join(format!(".{file_name}.tmp"));
630 let mut options = OpenOptions::new();
631 options.write(true).create(true).truncate(true);
632 #[cfg(unix)]
633 options.mode(0o600);
634 let mut file = options
635 .open(&tmp_path)
636 .await
637 .map_err(|source| io_error(tmp_path.clone(), source))?;
638 file.write_all(content.as_bytes())
639 .await
640 .map_err(|source| io_error(tmp_path.clone(), source))?;
641 file.sync_all()
642 .await
643 .map_err(|source| io_error(tmp_path.clone(), source))?;
644 drop(file);
645 tokio::fs::rename(&tmp_path, &path)
646 .await
647 .map_err(|source| io_error(path.clone(), source))?;
648 Ok(path)
649 }
650
651 pub(crate) async fn read_plan_file(
653 &self,
654 session_id: &SessionId,
655 file_name: &str,
656 ) -> Result<Option<String>, SessionStoreError> {
657 if crate::plan::validate_plan_file_name(file_name).is_err() {
658 return Ok(None);
659 }
660 let path = self
661 .session_dir(session_id)
662 .join(PLANS_DIR_NAME)
663 .join(file_name);
664 match tokio::fs::read_to_string(&path).await {
665 Ok(content) => Ok(Some(content)),
666 Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(None),
667 Err(source) => Err(io_error(path, source)),
668 }
669 }
670
671 pub(crate) async fn read_legacy_bytes(
672 &self,
673 session_id: &SessionId,
674 file_name: &str,
675 ) -> Result<Option<Vec<u8>>, SessionStoreError> {
676 let path = self.session_dir(session_id).join(file_name);
677 match tokio::fs::read(&path).await {
678 Ok(bytes) => Ok(Some(bytes)),
679 Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(None),
680 Err(source) => Err(io_error(path, source)),
681 }
682 }
683
684 #[cfg(test)]
685 pub(crate) fn with_stage_pause_for_tests(mut self, pause: SessionStoreStagePause) -> Self {
686 self.stage_pause = Some(pause);
687 self
688 }
689
690 #[cfg(test)]
691 pub(crate) fn with_commit_pause_for_tests(mut self, pause: SessionStoreCommitPause) -> Self {
692 self.commit_pause = Some(pause);
693 self
694 }
695
696 #[cfg(test)]
697 pub(crate) fn with_commit_failure_for_tests(mut self) -> Self {
698 self.fail_commit = true;
699 self
700 }
701
702 #[cfg(test)]
703 pub(crate) fn with_directory_sync_failure_for_tests(mut self) -> Self {
704 self.fail_directory_sync = true;
705 self
706 }
707}
708
709#[cfg(test)]
710pub(crate) fn sessions_dir_from_env(
711 xdg_state_home: Option<&OsStr>,
712 home: Option<&OsStr>,
713) -> Result<PathBuf, SessionStoreError> {
714 if let Some(root) = non_empty_os_str(xdg_state_home) {
715 return Ok(PathBuf::from(root).join("merry").join("sessions"));
716 }
717
718 if let Some(root) = non_empty_os_str(home) {
719 return Ok(PathBuf::from(root).join(".local/state/merry/sessions"));
720 }
721
722 Err(SessionStoreError::StateHomeUnavailable)
723}
724
725fn non_empty_os_str(value: Option<&OsStr>) -> Option<&OsStr> {
726 value.filter(|value| !value.is_empty())
727}
728
729async fn append_journal_bytes(
733 final_path: &Path,
734 header_bytes: &[u8],
735 commit_bytes: &[u8],
736) -> Result<bool, SessionStoreError> {
737 let mut options = OpenOptions::new();
738 options.create(true).append(true);
739 #[cfg(unix)]
740 options.mode(0o600);
741 let mut file = options
742 .open(final_path)
743 .await
744 .map_err(|source| io_error(final_path.to_path_buf(), source))?;
745 let empty = file
746 .metadata()
747 .await
748 .map_err(|source| io_error(final_path.to_path_buf(), source))?
749 .len()
750 == 0;
751 if empty && !header_bytes.is_empty() {
752 file.write_all(header_bytes)
753 .await
754 .map_err(|source| io_error(final_path.to_path_buf(), source))?;
755 }
756 if !commit_bytes.is_empty() {
757 file.write_all(commit_bytes)
758 .await
759 .map_err(|source| io_error(final_path.to_path_buf(), source))?;
760 }
761 file.sync_all()
762 .await
763 .map_err(|source| io_error(final_path.to_path_buf(), source))?;
764 Ok(empty)
765}
766
767#[cfg(unix)]
768async fn sync_parent_directory(path: &Path) -> Result<(), SessionStoreError> {
769 let parent = path
770 .parent()
771 .ok_or_else(|| SessionStoreError::InvalidPath {
772 path: path.to_path_buf(),
773 reason: "session state path has no parent directory",
774 })?;
775 let directory = tokio::fs::File::open(parent)
776 .await
777 .map_err(|source| io_error(parent.to_path_buf(), source))?;
778 directory
779 .sync_all()
780 .await
781 .map_err(|source| io_error(parent.to_path_buf(), source))
782}
783
784#[cfg(not(unix))]
785async fn sync_parent_directory(_path: &Path) -> Result<(), SessionStoreError> {
786 Ok(())
787}
788
789fn io_error(path: PathBuf, source: std::io::Error) -> SessionStoreError {
790 SessionStoreError::Io { path, source }
791}
792
793mod search;
794
795#[cfg(test)]
796mod tests;