1use std::collections::{BTreeMap, BTreeSet};
4use std::path::{Component, Path, PathBuf};
5use std::sync::Arc;
6
7use anyhow::{Context, Result, bail};
8use serde::{Deserialize, Serialize};
9
10use crate::config::{Config, HarnessKind, ProjectRepository, TargetTemplate, validate_id};
11use crate::credentials::CredentialSyncSignal;
12use crate::relay::{
13 RELAY_EVENT_GENESIS_DIGEST, RelayOperationalState, SequencedEvent, WorkerEvent,
14};
15use crate::subagent::SubagentRecord;
16use crate::targets::{AdditionalMount, validate_additional_mounts};
17
18pub const STATE_VERSION: u32 = 1;
19
20mod session_move;
21pub use session_move::*;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "kebab-case")]
25pub enum SessionState {
26 Provisioning,
27 Running,
28 Disconnected,
29 Checkpointing,
30 Closing,
31 Destroying,
32 #[serde(alias = "archived")]
35 Stopped,
36 Lost,
37 Error,
38 DestroyedWithDataLoss,
39}
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44#[serde(rename_all = "kebab-case")]
45pub enum SessionTransitionKind {
46 Starting,
47 Resuming,
48 Moving,
49 Suspending,
50 Destroying,
51}
52
53impl SessionTransitionKind {
54 pub const fn label(self) -> &'static str {
55 match self {
56 Self::Starting => "Starting",
57 Self::Resuming => "Resuming",
58 Self::Moving => "Moving",
59 Self::Suspending => "Suspending",
60 Self::Destroying => "Destroying",
61 }
62 }
63
64 pub fn for_session(state: SessionState, operation: Option<Self>) -> Option<Self> {
65 operation.or_else(|| state.transition_kind())
66 }
67}
68
69#[cfg(test)]
70mod transition_tests {
71 use super::{SessionState, SessionTransitionKind};
72
73 #[test]
74 fn operation_ownership_hides_intermediate_move_states_but_not_ordinary_live_work() {
75 for state in [
76 SessionState::Stopped,
77 SessionState::Running,
78 SessionState::Disconnected,
79 ] {
80 assert_eq!(
81 SessionTransitionKind::for_session(state, Some(SessionTransitionKind::Moving)),
82 Some(SessionTransitionKind::Moving)
83 );
84 assert_eq!(SessionTransitionKind::for_session(state, None), None);
85 }
86 assert_eq!(SessionState::Checkpointing.transition_kind(), None);
87 assert_eq!(
88 SessionState::Closing.transition_kind(),
89 Some(SessionTransitionKind::Suspending)
90 );
91 }
92}
93
94#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(tag = "state", rename_all = "snake_case")]
97pub enum MaterializedExecutionState {
98 #[default]
99 Idle,
100 Running {
101 started_at_ms: i64,
102 },
103 Closing,
104 Closed,
105}
106
107pub use crate::transcript::{TerminalOutputRecord, TranscriptBody, TranscriptItem};
108
109#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(rename_all = "snake_case")]
115pub enum QueuedCommandKind {
116 #[default]
117 Prompt,
118 SetConfig {
119 key: String,
120 value: String,
121 },
122}
123
124impl QueuedCommandKind {
125 pub fn is_prompt(&self) -> bool {
126 matches!(self, Self::Prompt)
127 }
128}
129
130pub fn config_command_text(key: &str, value: &str) -> String {
133 if key == "fast-mode" {
134 "/fast".to_owned()
135 } else {
136 format!("/{key} {value}")
137 }
138}
139
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141#[serde(deny_unknown_fields)]
142pub struct MaterializedQueuedPrompt {
143 pub command_id: String,
144 #[serde(default, skip_serializing_if = "QueuedCommandKind::is_prompt")]
145 pub kind: QueuedCommandKind,
146 pub content: Vec<serde_json::Value>,
147 pub queued_at_ms: i64,
148 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub accepted_ordinal: Option<u64>,
153}
154
155#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158#[serde(deny_unknown_fields)]
159pub struct MaterializedTurn {
160 pub command_id: String,
161 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub accepted_ordinal: Option<u64>,
163 pub turn_start_position: u64,
166 pub started_at_ms: i64,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
171#[serde(tag = "kind", rename_all = "snake_case")]
172pub enum TurnOutcomeKind {
173 Completed { stop_reason: String },
175 Rejected { message: String },
177 Interrupted { message: String },
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub enum PromptCompletion {
183 InputRequired,
184 Finished,
185 Cancelled,
186 QuotaLimit,
187 Error,
188}
189
190pub fn classify_prompt_completion(stop_reason: &str) -> PromptCompletion {
192 let normalized = stop_reason
193 .chars()
194 .filter(|character| *character != '_' && *character != '-')
195 .flat_map(char::to_lowercase)
196 .collect::<String>();
197 match normalized.as_str() {
198 "endturn" => PromptCompletion::Finished,
199 "awaitinginput" => PromptCompletion::InputRequired,
200 "cancelled" | "canceled" => PromptCompletion::Cancelled,
201 "quotalimit" => PromptCompletion::QuotaLimit,
202 _ if crate::relay::is_capacity_stop_reason(stop_reason) => PromptCompletion::QuotaLimit,
203 _ => PromptCompletion::Error,
204 }
205}
206
207#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
209#[serde(deny_unknown_fields)]
210pub struct MaterializedTurnOutcome {
211 #[serde(default, skip_serializing_if = "Option::is_none")]
212 pub diagnostic: Option<crate::diagnostic::TurnDiagnostic>,
213
214 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub usage: Option<crate::usage::TokenUsage>,
216 pub command_id: String,
217 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub accepted_ordinal: Option<u64>,
219 #[serde(default, skip_serializing_if = "Option::is_none")]
220 pub turn_start_position: Option<u64>,
221 pub completed_ordinal: u64,
222 pub completed_at_ms: i64,
223 pub outcome: TurnOutcomeKind,
224}
225
226impl MaterializedTurnOutcome {
227 pub fn interruption_ordinal(&self) -> Option<u64> {
229 (self.turn_start_position.is_some()
230 && matches!(self.outcome, TurnOutcomeKind::Interrupted { .. }))
231 .then_some(self.completed_ordinal)
232 }
233}
234
235#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
237#[serde(deny_unknown_fields)]
238pub struct MaterializedSession {
239 pub session_id: String,
240 pub applied_event_ordinal: u64,
241 pub applied_event_digest: String,
242 pub last_activity_at_ms: Option<i64>,
245 pub execution: MaterializedExecutionState,
246 #[serde(default, skip_serializing_if = "Option::is_none")]
247 pub session_title: Option<String>,
248 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
249 pub configuration: BTreeMap<String, serde_json::Value>,
250 #[serde(default, skip_serializing_if = "Vec::is_empty")]
251 pub transcript: Vec<Arc<TranscriptItem>>,
254 #[serde(default, skip_serializing_if = "Vec::is_empty")]
255 pub queued_prompts: Vec<MaterializedQueuedPrompt>,
256 #[serde(default, skip_serializing_if = "Vec::is_empty")]
259 pub pending_elicitations: Vec<crate::elicitation::ElicitationRequest>,
260 #[serde(default, skip_serializing_if = "Option::is_none")]
262 pub active_turn: Option<MaterializedTurn>,
263 #[serde(default, skip_serializing_if = "Option::is_none")]
266 pub last_turn_outcome: Option<MaterializedTurnOutcome>,
267}
268
269#[derive(Debug, Clone, PartialEq, Eq)]
272pub struct MaterializedSessionSummary {
273 pub session_id: String,
274 pub applied_event_ordinal: u64,
275 pub last_activity_at_ms: Option<i64>,
276 pub execution: MaterializedExecutionState,
277 pub session_title: Option<String>,
278 pub last_agent_message: Option<String>,
279 pub last_user_message: Option<String>,
280 pub last_agent_message_follows_last_user: bool,
283 pub agent_message_latest_content_ordinals: Vec<u64>,
284 pub interruption_event_ordinals: Vec<u64>,
285}
286
287impl MaterializedSession {
288 pub fn empty(session_id: impl Into<String>) -> Self {
289 Self {
290 session_id: session_id.into(),
291 applied_event_ordinal: 0,
292 applied_event_digest: RELAY_EVENT_GENESIS_DIGEST.into(),
293 last_activity_at_ms: None,
294 execution: MaterializedExecutionState::Idle,
295 session_title: None,
296 configuration: BTreeMap::new(),
297 transcript: Vec::new(),
298 queued_prompts: Vec::new(),
299 pending_elicitations: Vec::new(),
300 active_turn: None,
301 last_turn_outcome: None,
302 }
303 }
304
305 pub fn last_activity_at_ms(&self) -> Option<i64> {
306 self.last_activity_at_ms
307 }
308
309 pub fn resolved_title(&self) -> Option<String> {
315 self.session_title
316 .as_deref()
317 .and_then(normalize_session_title)
318 .or_else(|| {
319 self.transcript.iter().find_map(|item| {
320 let TranscriptBody::User { content } = &item.body else {
321 return None;
322 };
323 provisional_session_title(&crate::transcript::materialized_content_text(
324 content,
325 ))
326 })
327 })
328 .or_else(|| {
329 self.queued_prompts
330 .iter()
331 .filter(|prompt| prompt.kind.is_prompt())
332 .find_map(|prompt| {
333 provisional_session_title(&crate::transcript::materialized_content_text(
334 &prompt.content,
335 ))
336 })
337 })
338 }
339
340 pub fn unread_agent_messages_after(&self, viewed_through_event_ordinal: u64) -> u64 {
341 self.transcript
342 .iter()
343 .filter(|item| {
344 item.latest_content_event_ordinal
345 .is_some_and(|ordinal| ordinal > viewed_through_event_ordinal)
346 && item.is_nonempty_agent_message()
347 })
348 .count() as u64
349 }
350
351 pub fn unread_interruptions_after(&self, viewed_through_event_ordinal: u64) -> u64 {
352 self.interruption_event_ordinals()
353 .into_iter()
354 .filter(|ordinal| *ordinal > viewed_through_event_ordinal)
355 .count() as u64
356 }
357
358 pub fn interruption_event_ordinals(&self) -> Vec<u64> {
359 let mut ordinals = self
360 .transcript
361 .iter()
362 .filter(|item| item.is_work_interruption())
363 .map(|item| item.position)
364 .collect::<Vec<_>>();
365 if let Some(ordinal) = self
366 .last_turn_outcome
367 .as_ref()
368 .and_then(MaterializedTurnOutcome::interruption_ordinal)
369 {
370 ordinals.push(ordinal);
371 }
372 ordinals.sort_unstable();
373 ordinals.dedup();
374 ordinals
375 }
376
377 pub fn validate(&self) -> Result<()> {
378 validate_id("session", &self.session_id)?;
379 validate_relay_event_frontier(
380 self.applied_event_ordinal,
381 &self.applied_event_digest,
382 "materialized session event frontier",
383 )?;
384 if self
385 .session_title
386 .as_ref()
387 .is_some_and(|title| title.trim().is_empty())
388 {
389 bail!("materialized session has an empty title");
390 }
391 let mut item_ids = BTreeSet::new();
392 for item in &self.transcript {
393 item.validate(self.applied_event_ordinal)?;
394 if !item_ids.insert(item.stable_id.as_str()) {
395 bail!(
396 "materialized transcript contains duplicate item {:?}",
397 item.stable_id
398 );
399 }
400 }
401 let mut command_ids = BTreeSet::new();
402 for prompt in &self.queued_prompts {
403 if prompt.command_id.trim().is_empty() {
404 bail!("materialized prompt queue has an empty command id");
405 }
406 if !command_ids.insert(prompt.command_id.as_str()) {
407 bail!(
408 "materialized prompt queue contains duplicate command {:?}",
409 prompt.command_id
410 );
411 }
412 if let QueuedCommandKind::SetConfig { key, value } = &prompt.kind
413 && (key.trim().is_empty() || value.trim().is_empty())
414 {
415 bail!(
416 "materialized queued configuration change {:?} is incomplete",
417 prompt.command_id
418 );
419 }
420 }
421 Ok(())
422 }
423}
424
425#[derive(Debug, Clone, PartialEq)]
429pub struct ManagedSessionSnapshot {
430 pub materialized: MaterializedSession,
431 pub window: ProjectionWindow,
434 pub operational: RelayOperationalState,
435 pub latest_credential_sync_signal: Option<CredentialSyncSignal>,
439 pub worker_build: Option<String>,
444 pub subagent_requests: Vec<crate::subagent::SubagentToolRequest>,
446 pub subagent_results: Vec<crate::subagent::SubagentToolResult>,
448}
449
450#[derive(Debug, Clone, PartialEq, Eq)]
462pub struct ProjectionWindow {
463 pub omitted_items: usize,
465 pub provisional_title: Option<String>,
467 pub latest_turn_start_position: Option<u64>,
471}
472
473impl ProjectionWindow {
474 #[must_use]
476 pub fn of(session: &MaterializedSession) -> Self {
477 Self {
478 omitted_items: 0,
479 provisional_title: session.transcript.iter().find_map(|item| {
480 let TranscriptBody::User { content } = &item.body else {
481 return None;
482 };
483 provisional_session_title(&crate::transcript::materialized_content_text(content))
484 }),
485 latest_turn_start_position: session
486 .transcript
487 .iter()
488 .rev()
489 .find(|item| item.is_turn_start())
490 .map(|item| item.position),
491 }
492 }
493}
494
495impl ManagedSessionSnapshot {
496 #[must_use]
501 pub fn resolved_title(&self) -> Option<String> {
502 self.materialized
503 .session_title
504 .as_deref()
505 .and_then(normalize_session_title)
506 .or_else(|| self.window.provisional_title.clone())
507 .or_else(|| {
508 self.materialized
509 .queued_prompts
510 .iter()
511 .filter(|prompt| prompt.kind.is_prompt())
512 .find_map(|prompt| {
513 provisional_session_title(&crate::transcript::materialized_content_text(
514 &prompt.content,
515 ))
516 })
517 })
518 }
519
520 #[must_use]
525 pub fn latest_completed_turn_ordinal(&self) -> Option<u64> {
526 if self.materialized.execution != MaterializedExecutionState::Idle {
527 return None;
528 }
529 self.window.latest_turn_start_position
530 }
531}
532
533#[derive(Debug, Clone)]
535pub struct RecoveryObservation {
536 pub session: SessionRecord,
537 pub config: Config,
538 pub latest_completed_turn_ordinal: Option<u64>,
539 pub execution: MaterializedExecutionState,
540 pub checkpoint_safe: bool,
544}
545
546pub fn latest_completed_turn_ordinal(session: &MaterializedSession) -> Option<u64> {
551 if session.execution != MaterializedExecutionState::Idle {
552 return None;
553 }
554 session
555 .transcript
556 .iter()
557 .rev()
558 .find(|item| item.is_turn_start())
559 .map(|item| item.position)
560}
561
562pub fn validate_relay_event_digest(digest: &str, name: &str) -> Result<()> {
563 if digest.len() != 64
564 || !digest
565 .bytes()
566 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
567 {
568 bail!("{name} must be a lowercase SHA-256 digest");
569 }
570 Ok(())
571}
572
573pub fn validate_relay_event_frontier(ordinal: u64, digest: &str, name: &str) -> Result<()> {
574 validate_relay_event_digest(digest, name)?;
575 if (ordinal == 0) != (digest == RELAY_EVENT_GENESIS_DIGEST) {
576 bail!("{name} has inconsistent ordinal {ordinal} and digest {digest}");
577 }
578 Ok(())
579}
580
581fn is_false(value: &bool) -> bool {
582 !*value
583}
584
585impl SessionState {
586 pub const fn as_str(self) -> &'static str {
588 match self {
589 Self::Provisioning => "provisioning",
590 Self::Running => "running",
591 Self::Disconnected => "disconnected",
592 Self::Checkpointing => "checkpointing",
593 Self::Closing => "closing",
594 Self::Destroying => "destroying",
595 Self::Stopped => "stopped",
596 Self::Lost => "lost",
597 Self::Error => "error",
598 Self::DestroyedWithDataLoss => "destroyed-with-data-loss",
599 }
600 }
601
602 pub fn from_stored(value: &str) -> Option<Self> {
605 Some(match value {
606 "provisioning" => Self::Provisioning,
607 "running" => Self::Running,
608 "disconnected" => Self::Disconnected,
609 "checkpointing" => Self::Checkpointing,
610 "closing" => Self::Closing,
611 "destroying" => Self::Destroying,
612 "stopped" | "archived" => Self::Stopped,
613 "lost" => Self::Lost,
614 "error" => Self::Error,
615 "destroyed-with-data-loss" => Self::DestroyedWithDataLoss,
616 _ => return None,
617 })
618 }
619
620 pub const fn transition_kind(self) -> Option<SessionTransitionKind> {
623 match self {
624 Self::Provisioning => Some(SessionTransitionKind::Starting),
625 Self::Closing => Some(SessionTransitionKind::Suspending),
626 Self::Destroying => Some(SessionTransitionKind::Destroying),
627 _ => None,
628 }
629 }
630
631 pub const fn is_active(self) -> bool {
635 matches!(
636 self,
637 Self::Provisioning
638 | Self::Running
639 | Self::Disconnected
640 | Self::Checkpointing
641 | Self::Closing
642 | Self::Destroying
643 | Self::Error
644 )
645 }
646}
647
648#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
649#[serde(tag = "kind", rename_all = "kebab-case")]
650pub enum PodmanWorkspaceLocator {
651 #[default]
652 ContainerLayer,
653 Volume {
654 name: String,
655 },
656 HostPath {
657 path: PathBuf,
658 helper: Vec<String>,
659 resource: String,
660 },
661}
662
663#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
664#[serde(tag = "kind", rename_all = "kebab-case")]
665pub enum TargetLocator {
666 LocalBare {
667 worker_root: PathBuf,
668 },
669 LocalPodman {
670 container_id: String,
671 #[serde(default)]
672 workspace_storage: PodmanWorkspaceLocator,
673 #[serde(default, skip_serializing_if = "Option::is_none")]
677 borrowed_from: Option<String>,
678 },
679 LocalDocker {
680 container_id: String,
681 #[serde(default, skip_serializing_if = "Option::is_none")]
685 borrowed_from: Option<String>,
686 },
687 AppleContainer {
688 container_id: String,
689 #[serde(default, skip_serializing_if = "Option::is_none")]
693 borrowed_from: Option<String>,
694 },
695 AwsEc2 {
696 instance_id: String,
697 #[serde(default, skip_serializing_if = "Option::is_none")]
698 address: Option<String>,
699 },
700 SshBare {
701 host: String,
702 workspace: PathBuf,
703 #[serde(default, skip_serializing_if = "Option::is_none")]
704 worker_id: Option<String>,
705 },
706 SshPodman {
707 host: String,
708 container_id: String,
709 #[serde(default)]
710 workspace_storage: PodmanWorkspaceLocator,
711 #[serde(default, skip_serializing_if = "Option::is_none")]
715 borrowed_from: Option<String>,
716 },
717 SshDocker {
718 host: String,
719 container_id: String,
720 #[serde(default, skip_serializing_if = "Option::is_none")]
724 borrowed_from: Option<String>,
725 },
726}
727
728#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
729#[serde(tag = "kind", rename_all = "kebab-case")]
730pub enum ManagedWorktreeTarget {
731 Local,
732 Ssh {
733 destination: String,
734 #[serde(default, skip_serializing_if = "Vec::is_empty")]
735 ssh_args: Vec<String>,
736 },
737}
738
739#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
741#[serde(deny_unknown_fields)]
742pub struct ManagedWorktreeOptions {
743 pub available: bool,
744 pub default_create: bool,
745}
746
747#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
748#[serde(deny_unknown_fields)]
749pub struct ManagedWorktree {
750 pub source_project_directory: PathBuf,
751 pub source_repository: PathBuf,
752 pub worktree_root: PathBuf,
753 pub branch: String,
754 pub target: ManagedWorktreeTarget,
755 #[serde(default, skip_serializing_if = "Option::is_none")]
759 pub base_commit: Option<String>,
760}
761
762impl ManagedWorktree {
763 fn validate(&self, session_id: &str, project_directory: Option<&Path>) -> Result<()> {
764 for (label, path) in [
765 ("source project directory", &self.source_project_directory),
766 ("source repository", &self.source_repository),
767 ("worktree root", &self.worktree_root),
768 ] {
769 if !path.is_absolute() || path.components().any(|part| part == Component::ParentDir) {
770 bail!("managed worktree {label} must be an absolute safe path");
771 }
772 }
773 if !self
774 .source_project_directory
775 .starts_with(&self.source_repository)
776 {
777 bail!("managed worktree source directory is outside its repository");
778 }
779 let expected_root = self
780 .source_repository
781 .join(".mj")
782 .join("worktrees")
783 .join(session_id);
784 if self.worktree_root != expected_root {
785 bail!("managed worktree root does not match the session-owned path");
786 }
787 if self.branch != format!("mj/{session_id}") {
788 bail!("managed worktree branch does not match the session id");
789 }
790 let relative = self
791 .source_project_directory
792 .strip_prefix(&self.source_repository)
793 .expect("source relationship checked above");
794 if project_directory != Some(self.worktree_root.join(relative).as_path()) {
795 bail!("session project directory does not match its managed worktree");
796 }
797 match &self.target {
798 ManagedWorktreeTarget::Local => {}
799 ManagedWorktreeTarget::Ssh { destination, .. } if destination.trim().is_empty() => {
800 bail!("managed SSH worktree has an empty destination")
801 }
802 ManagedWorktreeTarget::Ssh { .. } => {}
803 }
804 Ok(())
805 }
806}
807
808#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
809#[serde(tag = "kind", rename_all = "kebab-case")]
810pub enum SessionResourceAllocation {
811 Container {
812 cpus: u64,
813 memory_bytes: u64,
814 },
815 AwsEc2 {
816 instance_type: String,
817 vcpus: u64,
818 memory_bytes: u64,
819 },
820}
821
822impl SessionResourceAllocation {
823 pub fn validate(&self) -> Result<()> {
824 match self {
825 Self::Container { cpus, memory_bytes } if *cpus == 0 || *memory_bytes == 0 => {
826 bail!("container resource allocation must have non-zero CPU and memory")
827 }
828 Self::AwsEc2 {
829 instance_type,
830 vcpus,
831 memory_bytes,
832 } if instance_type.trim().is_empty() || *vcpus == 0 || *memory_bytes == 0 => {
833 bail!("EC2 resource allocation must have an instance type, CPU, and memory")
834 }
835 _ => Ok(()),
836 }
837 }
838}
839
840pub fn allocation_cpus(allocation: &SessionResourceAllocation) -> u64 {
842 match allocation {
843 SessionResourceAllocation::Container { cpus, .. } => *cpus,
844 SessionResourceAllocation::AwsEc2 { vcpus, .. } => *vcpus,
845 }
846}
847
848pub fn allocation_memory(allocation: &SessionResourceAllocation) -> u64 {
850 match allocation {
851 SessionResourceAllocation::Container { memory_bytes, .. }
852 | SessionResourceAllocation::AwsEc2 { memory_bytes, .. } => *memory_bytes,
853 }
854}
855
856impl TargetLocator {
857 fn validate(&self, session_id: &str) -> Result<()> {
858 match self {
859 Self::LocalBare { worker_root } => {
860 if !worker_root.is_absolute()
861 || worker_root
862 .components()
863 .any(|part| part == Component::ParentDir)
864 || !worker_root.ends_with(session_id)
865 {
866 bail!(
867 "local bare worker root must be an absolute safe path ending in the session id"
868 );
869 }
870 }
871 Self::LocalPodman { container_id, .. }
872 | Self::LocalDocker { container_id, .. }
873 | Self::AppleContainer { container_id, .. }
874 | Self::SshPodman { container_id, .. }
875 | Self::SshDocker { container_id, .. }
876 if container_id.trim().is_empty() =>
877 {
878 bail!("target locator has an empty container id")
879 }
880 Self::AwsEc2 { instance_id, .. } if instance_id.trim().is_empty() => {
881 bail!("target locator has an empty AWS instance id")
882 }
883 Self::SshBare {
884 host, workspace, ..
885 } => {
886 if host.trim().is_empty() {
887 bail!("bare SSH target locator has an empty host");
888 }
889 if workspace.as_os_str().is_empty()
890 || workspace
891 .components()
892 .any(|part| part == Component::ParentDir)
893 || !workspace.ends_with(session_id)
894 {
895 bail!("bare SSH target locator must be a safe path ending in the session id");
896 }
897 }
898 Self::SshPodman { host, .. } if host.trim().is_empty() => {
899 bail!("SSH Podman target locator has an empty host")
900 }
901 Self::SshDocker { host, .. } if host.trim().is_empty() => {
902 bail!("SSH Docker target locator has an empty host")
903 }
904 _ => {}
905 }
906 Ok(())
907 }
908}
909
910#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
911#[serde(deny_unknown_fields)]
912pub struct CheckpointMetadata {
913 pub archive_path: PathBuf,
914 pub sha256: String,
916 pub created_at: String,
917 pub event_frontier: u64,
918}
919
920impl CheckpointMetadata {
921 fn validate(&self) -> Result<()> {
922 if self.archive_path.as_os_str().is_empty() {
923 bail!("checkpoint archive path is empty");
924 }
925 if self.sha256.len() != 64
926 || !self
927 .sha256
928 .bytes()
929 .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
930 {
931 bail!("checkpoint SHA-256 must be 64 lowercase hexadecimal characters");
932 }
933 if self.created_at.trim().is_empty() {
934 bail!("checkpoint timestamp is empty");
935 }
936 Ok(())
937 }
938}
939
940#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
944#[serde(deny_unknown_fields)]
945pub struct SessionBuildCache {
946 pub host: String,
949 pub directory: PathBuf,
950 #[serde(default, skip_serializing_if = "Option::is_none")]
953 pub max_size: Option<String>,
954 #[serde(default, skip_serializing_if = "Option::is_none")]
957 pub target_root: Option<PathBuf>,
958}
959
960#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
964pub struct ArchiveSpacePreview {
965 pub sessions: usize,
967 pub bytes: u64,
969 pub reclaimable_sessions: usize,
972 pub reclaimable_bytes: u64,
973}
974
975#[derive(Debug, Clone, PartialEq, Eq)]
979pub struct BuildCachePreview {
980 pub native_mbx: Option<String>,
982 pub directory: Option<PathBuf>,
984 pub max_size: Option<BuildCacheLimit>,
986 pub stats: Option<BuildCacheStats>,
988 pub off_reason: Option<BuildCacheOff>,
991}
992
993#[derive(Debug, Clone, PartialEq, Eq)]
1001pub struct BuildCacheStats {
1002 pub builds: u64,
1004 pub cached_compilations: u64,
1006 pub avoided_compiler_ns: u64,
1008 pub reflinked_bytes: u64,
1010}
1011
1012#[derive(Debug, Clone, PartialEq, Eq)]
1014pub enum BuildCacheOff {
1015 TurnedOff,
1017 Unavailable(String),
1020}
1021
1022impl std::fmt::Display for BuildCacheOff {
1023 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1024 match self {
1025 Self::TurnedOff => formatter.write_str("turned off for this machine"),
1026 Self::Unavailable(reason) => formatter.write_str(reason),
1027 }
1028 }
1029}
1030
1031#[derive(Debug, Clone, PartialEq, Eq)]
1033pub enum BuildCacheLimit {
1034 Size(String),
1036 HostConfiguration(Option<String>),
1039}
1040
1041#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1042#[serde(deny_unknown_fields)]
1043pub struct SessionRecord {
1044 pub id: String,
1045 #[serde(default = "default_session_workspace_id")]
1050 pub workspace_id: String,
1051 pub title: String,
1052 pub harness_kind: HarnessKind,
1053 pub last_profile: String,
1054 pub bundle_id: String,
1055 #[serde(default, skip_serializing_if = "Option::is_none")]
1057 pub project_directory: Option<PathBuf>,
1058 #[serde(default, skip_serializing_if = "Option::is_none")]
1060 pub managed_worktree: Option<ManagedWorktree>,
1061 #[serde(default, skip_serializing_if = "Option::is_none")]
1063 pub create_managed_worktree: Option<bool>,
1064 #[serde(default, skip_serializing_if = "Option::is_none")]
1067 pub mjolnir_subagents: Option<bool>,
1068 pub target_template_id: String,
1069 #[serde(default, skip_serializing_if = "Option::is_none")]
1070 pub resource_allocation: Option<SessionResourceAllocation>,
1071 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1072 pub additional_mounts: Vec<AdditionalMount>,
1073 #[serde(default, skip_serializing_if = "Option::is_none")]
1076 pub container_cpus: Option<String>,
1077 #[serde(default, skip_serializing_if = "Option::is_none")]
1080 pub container_memory: Option<String>,
1081 #[serde(default, skip_serializing_if = "Option::is_none")]
1087 pub container_workspace: Option<PathBuf>,
1088 #[serde(default, skip_serializing_if = "Option::is_none")]
1092 pub build_cache: Option<SessionBuildCache>,
1093 pub state: SessionState,
1094 #[serde(default, skip_serializing_if = "is_false")]
1097 pub archived: bool,
1098 #[serde(default, skip_serializing_if = "Option::is_none")]
1099 pub target: Option<TargetLocator>,
1100 #[serde(default, skip_serializing_if = "Option::is_none")]
1101 pub native_session_id: Option<String>,
1102 #[serde(default, skip_serializing_if = "Option::is_none")]
1103 pub acp_session_title: Option<String>,
1104 #[serde(default, skip_serializing_if = "Option::is_none")]
1105 pub session_title_override: Option<String>,
1106 pub created_at: String,
1107 pub updated_at: String,
1108 #[serde(default, alias = "detached_after_event_ordinal")]
1109 pub viewed_through_event_ordinal: u64,
1110 #[serde(default, skip_serializing_if = "String::is_empty")]
1113 pub draft_input: String,
1114 #[serde(default, skip_serializing_if = "Option::is_none")]
1122 pub last_error: Option<String>,
1123 #[serde(default, skip_serializing_if = "Option::is_none")]
1124 pub last_checkpoint_error: Option<String>,
1125 #[serde(default, skip_serializing_if = "Option::is_none")]
1126 pub checkpoint: Option<CheckpointMetadata>,
1127}
1128
1129#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1130#[serde(deny_unknown_fields)]
1131pub struct HostContainerSize {
1132 pub cpus: u64,
1133 pub memory_bytes: u64,
1134}
1135
1136fn default_session_workspace_id() -> String {
1137 crate::workspace::DEFAULT_WORKSPACE_ID.to_owned()
1138}
1139
1140pub const DESTRUCTION_FAILURE_PREFIX: &str = "the destruction did not finish";
1149
1150pub const CLOSE_FAILURE_PREFIX: &str = "the suspension did not finish";
1151
1152pub fn is_public_lifecycle_error(error: &str) -> bool {
1154 error.starts_with(CLOSE_FAILURE_PREFIX)
1155 || error.starts_with(DESTRUCTION_FAILURE_PREFIX)
1156 || error.starts_with("the close did not finish")
1157}
1158
1159#[must_use]
1172pub fn target_label(config: &Config, target_id: &str, project: Option<&Path>) -> String {
1173 if !matches!(
1174 config.targets.get(target_id),
1175 Some(TargetTemplate::LocalBare | TargetTemplate::SshBare { .. })
1176 ) {
1177 return target_id.to_owned();
1178 }
1179 project.and_then(Path::file_name).map_or_else(
1180 || target_id.to_owned(),
1181 |directory| format!("{target_id}/{}", directory.to_string_lossy()),
1182 )
1183}
1184
1185impl SessionRecord {
1186 #[must_use]
1190 pub fn public_error(&self) -> Option<&str> {
1191 self.last_error
1192 .as_deref()
1193 .filter(|error| is_public_lifecycle_error(error))
1194 }
1195
1196 pub fn configuration_issue(&self, config: &Config) -> Option<String> {
1199 if !self.state.is_active() {
1200 return None;
1201 }
1202 let mut issues = Vec::new();
1203 match config.profiles.get(&self.last_profile) {
1204 None => issues.push(format!("missing profile {:?}", self.last_profile)),
1205 Some(profile) if profile.kind != self.harness_kind => issues.push(format!(
1206 "expects {:?}, but profile {:?} is {:?}",
1207 self.harness_kind, self.last_profile, profile.kind
1208 )),
1209 Some(_) => {}
1210 }
1211 if self.project_directory.is_none() && !config.bundles.contains_key(&self.bundle_id) {
1212 issues.push(format!("missing bundle {:?}", self.bundle_id));
1213 }
1214 if !config.targets.contains_key(&self.target_template_id) {
1215 issues.push(format!(
1216 "missing target template {:?}",
1217 self.target_template_id
1218 ));
1219 }
1220 (!issues.is_empty()).then(|| format!(
1221 "Session {:?} needs configuration repair: {}. Restore these entries in config.toml, then retry. Run mj setup to rediscover installed profiles and targets; existing sessions are preserved.",
1222 self.id, issues.join("; ")
1223 ))
1224 }
1225
1226 pub fn validate_configuration(&self, config: &Config) -> Result<()> {
1227 if let Some(issue) = self.configuration_issue(config) {
1228 bail!("{issue}");
1229 }
1230 Ok(())
1231 }
1232
1233 pub fn display_title(&self) -> &str {
1235 self.session_title_override
1236 .as_deref()
1237 .or(self.acp_session_title.as_deref())
1238 .unwrap_or(&self.id)
1239 }
1240
1241 pub fn project_name(&self, config: &Config) -> String {
1246 if let Some(worktree) = &self.managed_worktree {
1247 return path_leaf(&worktree.source_repository);
1248 }
1249 if let Some(project_directory) = &self.project_directory {
1250 return path_leaf(project_directory);
1251 }
1252 self.bundle_source_name(config)
1253 }
1254
1255 pub fn project_target(&self, config: &Config, target_id: &str) -> String {
1259 let project = self
1260 .managed_worktree
1261 .as_ref()
1262 .map(|worktree| &worktree.source_project_directory)
1263 .or(self.project_directory.as_ref());
1264 target_label(config, target_id, project.map(PathBuf::as_path))
1265 }
1266
1267 pub fn project_source(&self, config: &Config) -> ProjectSourceIdentity {
1272 if let Some(worktree) = &self.managed_worktree {
1273 return ProjectSourceIdentity::path(&worktree.source_repository, None);
1274 }
1275 if let Some(project_directory) = &self.project_directory {
1276 let remote = match &self.target {
1277 Some(TargetLocator::SshBare { host, .. }) => Some(host.as_str()),
1278 _ => None,
1279 };
1280 return ProjectSourceIdentity::path(project_directory, remote);
1281 }
1282 self.bundle_source_identity(config)
1283 .unwrap_or_else(|| ProjectSourceIdentity {
1284 key: format!("bundle:{}", self.bundle_id),
1285 short: path_leaf(Path::new(&self.bundle_id)),
1286 full: self.bundle_id.clone(),
1287 })
1288 }
1289
1290 fn bundle_source_name(&self, config: &Config) -> String {
1293 self.bundle_source_identity(config)
1294 .map(|source| source.short)
1295 .unwrap_or_else(|| path_leaf(Path::new(&self.bundle_id)))
1296 }
1297
1298 fn bundle_source_identity(&self, config: &Config) -> Option<ProjectSourceIdentity> {
1301 let bundle = config.bundles.get(&self.bundle_id)?;
1302 let sources = bundle
1303 .repositories
1304 .iter()
1305 .map(repository_source_identity)
1306 .collect::<Option<Vec<_>>>()?;
1307 ProjectSourceIdentity::bundle(sources)
1308 }
1309
1310 pub fn compare_by_creation(&self, other: &Self) -> std::cmp::Ordering {
1314 self.creation_order_key().cmp(&other.creation_order_key())
1315 }
1316
1317 pub fn creation_order_key(&self) -> (bool, Option<i64>, &str) {
1319 let timestamp = created_at_seconds(&self.created_at);
1320 (timestamp.is_none(), timestamp, &self.id)
1321 }
1322
1323 fn validate(&self, map_id: &str) -> Result<()> {
1324 validate_id("session", &self.id)?;
1325 if self.id != map_id {
1326 bail!(
1327 "session map key {map_id:?} does not match record id {:?}",
1328 self.id
1329 );
1330 }
1331 validate_id("workspace", &self.workspace_id)?;
1332 validate_id("profile", &self.last_profile)?;
1333 validate_id("bundle", &self.bundle_id)?;
1334 if let Some(project_directory) = &self.project_directory
1335 && (!project_directory.is_absolute()
1336 || project_directory
1337 .components()
1338 .any(|part| part == Component::ParentDir))
1339 {
1340 bail!("session {:?} has an unsafe project directory", self.id);
1341 }
1342 if let Some(managed_worktree) = &self.managed_worktree {
1343 managed_worktree.validate(&self.id, self.project_directory.as_deref())?;
1344 }
1345 validate_id("target template", &self.target_template_id)?;
1346 if let Some(allocation) = &self.resource_allocation {
1347 allocation.validate()?;
1348 }
1349 validate_additional_mounts(&self.additional_mounts)?;
1350 if self.title.trim().is_empty() {
1351 bail!("session {:?} has an empty title", self.id);
1352 }
1353 if self
1354 .acp_session_title
1355 .as_ref()
1356 .is_some_and(|title| title.trim().is_empty())
1357 || self
1358 .session_title_override
1359 .as_ref()
1360 .is_some_and(|title| title.trim().is_empty())
1361 {
1362 bail!("session {:?} has an empty display title", self.id);
1363 }
1364 if self.created_at.trim().is_empty() || self.updated_at.trim().is_empty() {
1365 bail!("session {:?} has an empty timestamp", self.id);
1366 }
1367 if let Some(target) = &self.target {
1368 target.validate(&self.id)?;
1369 }
1370 if let Some(checkpoint) = &self.checkpoint {
1371 checkpoint.validate()?;
1372 }
1373 Ok(())
1374 }
1375}
1376
1377fn repository_source_identity(repository: &ProjectRepository) -> Option<ProjectSourceIdentity> {
1378 repository
1379 .github
1380 .as_deref()
1381 .and_then(ProjectSourceIdentity::git_remote)
1382 .or_else(|| {
1383 repository
1384 .local
1385 .as_deref()
1386 .map(|path| ProjectSourceIdentity::path(path, None))
1387 })
1388}
1389
1390#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
1391pub struct ProjectSourceIdentity {
1392 pub key: String,
1393 pub short: String,
1394 pub full: String,
1395}
1396
1397impl ProjectSourceIdentity {
1398 pub fn bundle(mut sources: Vec<Self>) -> Option<Self> {
1400 if sources.is_empty() {
1401 return None;
1402 }
1403 sources.sort_by(|left, right| {
1404 left.key
1405 .cmp(&right.key)
1406 .then_with(|| left.full.cmp(&right.full))
1407 .then_with(|| left.short.cmp(&right.short))
1408 });
1409 sources.dedup_by(|left, right| left.key == right.key);
1410 if sources.len() == 1 {
1411 return sources.pop();
1412 }
1413 let keys = sources
1414 .iter()
1415 .map(|source| source.key.clone())
1416 .collect::<Vec<_>>();
1417 let key = serde_json::to_string(&keys).ok()?;
1418 Some(Self {
1419 key: format!("bundle:{key}"),
1420 short: sources
1421 .iter()
1422 .map(|source| source.short.as_str())
1423 .collect::<Vec<_>>()
1424 .join(" + "),
1425 full: sources
1426 .iter()
1427 .map(|source| source.full.as_str())
1428 .collect::<Vec<_>>()
1429 .join(" + "),
1430 })
1431 }
1432
1433 pub fn git_remote(source: &str) -> Option<Self> {
1436 if let Some(normalized) = normalize_github_source(source) {
1437 let short = normalized
1438 .rsplit_once('/')
1439 .map_or(normalized.as_str(), |(_, repository)| repository)
1440 .to_owned();
1441 return Some(Self {
1442 key: format!("github:{}", normalized.to_lowercase()),
1443 short,
1444 full: normalized,
1445 });
1446 }
1447 let normalized = source.trim().trim_end_matches('/').trim_end_matches(".git");
1448 if normalized.is_empty() {
1449 return None;
1450 }
1451 let short = normalized
1452 .rsplit(['/', ':'])
1453 .find(|part| !part.is_empty())
1454 .unwrap_or(normalized)
1455 .to_owned();
1456 Some(Self {
1457 key: format!("git:{}", normalized.to_lowercase()),
1458 short,
1459 full: normalized.to_owned(),
1460 })
1461 }
1462
1463 pub fn path(path: &Path, remote: Option<&str>) -> Self {
1465 let normalized = path.components().collect::<PathBuf>();
1466 let path_text = normalized.to_string_lossy().into_owned();
1467 let full = remote.map_or_else(|| path_text.clone(), |host| format!("{host}:{path_text}"));
1468 let key = remote.map_or_else(
1469 || format!("path:{path_text}"),
1470 |host| format!("path:{}:{path_text}", host.to_lowercase()),
1471 );
1472 Self {
1473 key,
1474 short: path_leaf(path),
1475 full,
1476 }
1477 }
1478}
1479
1480fn normalize_github_source(source: &str) -> Option<String> {
1481 let source = source.trim();
1482 let path = source
1483 .strip_prefix("https://github.com/")
1484 .or_else(|| source.strip_prefix("http://github.com/"))
1485 .or_else(|| source.strip_prefix("git@github.com:"))
1486 .or_else(|| source.strip_prefix("ssh://git@github.com/"))
1487 .or_else(|| {
1488 (!source.contains("://") && !source.contains('@') && !source.contains(':'))
1489 .then_some(source)
1490 })?
1491 .trim_end_matches(".git");
1492 let mut parts = path.split('/');
1493 let owner = parts.next()?;
1494 let repository = parts.next()?;
1495 (!owner.is_empty() && !repository.is_empty() && parts.next().is_none())
1496 .then(|| format!("{owner}/{repository}"))
1497}
1498
1499fn path_leaf(path: &Path) -> String {
1501 path.file_name()
1502 .unwrap_or(path.as_os_str())
1503 .to_string_lossy()
1504 .into_owned()
1505}
1506
1507fn created_at_seconds(timestamp: &str) -> Option<i64> {
1508 chrono::DateTime::parse_from_rfc3339(timestamp)
1509 .ok()
1510 .map(|timestamp| timestamp.timestamp())
1511}
1512
1513#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1514#[serde(deny_unknown_fields)]
1515pub struct State {
1516 pub version: u32,
1517 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1518 pub sessions: BTreeMap<String, SessionRecord>,
1519 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1522 pub subagents: BTreeMap<String, SubagentRecord>,
1523 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1525 pub mount_history: BTreeMap<String, Vec<PathBuf>>,
1526 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1528 pub container_sizes: BTreeMap<String, HostContainerSize>,
1529}
1530
1531impl Default for State {
1532 fn default() -> Self {
1533 Self {
1534 version: STATE_VERSION,
1535 sessions: BTreeMap::new(),
1536 subagents: BTreeMap::new(),
1537 mount_history: BTreeMap::new(),
1538 container_sizes: BTreeMap::new(),
1539 }
1540 }
1541}
1542
1543impl State {
1544 #[must_use]
1553 pub fn project_identity_session<'a>(&'a self, session: &'a SessionRecord) -> &'a SessionRecord {
1554 self.subagents
1555 .get(&session.id)
1556 .and_then(|record| self.sessions.get(&record.parent_session_id))
1557 .unwrap_or(session)
1558 }
1559
1560 pub fn validate(&self) -> Result<()> {
1561 if self.version != STATE_VERSION {
1562 bail!(
1563 "unsupported Mjolnir state version {}; expected {STATE_VERSION}",
1564 self.version
1565 );
1566 }
1567 for (id, session) in &self.sessions {
1568 session.validate(id)?;
1569 }
1570 for (child_id, subagent) in &self.subagents {
1571 if child_id != &subagent.child_session_id {
1572 bail!("sub-agent key {child_id:?} does not match its child session id");
1573 }
1574 if child_id == &subagent.parent_session_id {
1575 bail!("sub-agent {child_id:?} cannot be its own parent");
1576 }
1577 if !self.sessions.contains_key(child_id) {
1578 bail!("sub-agent {child_id:?} has no child session");
1579 }
1580 if !self.sessions.contains_key(&subagent.parent_session_id) {
1581 bail!(
1582 "sub-agent {child_id:?} has unknown parent {:?}",
1583 subagent.parent_session_id
1584 );
1585 }
1586 if self.subagents.contains_key(&subagent.parent_session_id) {
1587 bail!("sub-agent {child_id:?} cannot belong to another sub-agent");
1588 }
1589 if subagent.task_name.trim().is_empty()
1590 || subagent.profile_id.trim().is_empty()
1591 || subagent.request_key.trim().is_empty()
1592 {
1593 bail!("sub-agent {child_id:?} has incomplete relationship metadata");
1594 }
1595 }
1596 for (host, sources) in &self.mount_history {
1597 if host.trim().is_empty() {
1598 bail!("mount history contains an empty host key");
1599 }
1600 if sources.iter().any(|source| !source.is_absolute()) {
1601 bail!("mount history for {host:?} contains a non-absolute source path");
1602 }
1603 }
1604 for (host, size) in &self.container_sizes {
1605 if host.trim().is_empty() {
1606 bail!("container size history contains an empty host key");
1607 }
1608 if size.cpus == 0 || size.memory_bytes == 0 {
1609 bail!("container size history for {host:?} contains a zero value");
1610 }
1611 if size.cpus > i64::MAX as u64 || size.memory_bytes > i64::MAX as u64 {
1612 bail!("container size history for {host:?} exceeds SQLite integer range");
1613 }
1614 }
1615 Ok(())
1616 }
1617
1618 pub fn remember_mount_sources(&mut self, host: &str, mounts: &[AdditionalMount]) {
1619 if mounts.is_empty() {
1620 return;
1621 }
1622 let sources = self.mount_history.entry(host.to_owned()).or_default();
1623 for mount in mounts.iter().rev() {
1624 sources.retain(|source| source != &mount.source);
1625 sources.insert(0, mount.source.clone());
1626 }
1627 sources.truncate(20);
1628 }
1629
1630 pub fn remember_container_size(&mut self, host: &str, size: HostContainerSize) {
1631 self.container_sizes.insert(host.to_owned(), size);
1632 }
1633
1634 pub fn project_directories(&self, host: &str) -> &[PathBuf] {
1635 self.mount_history
1636 .get(&project_history_key(host))
1637 .map(Vec::as_slice)
1638 .unwrap_or_default()
1639 }
1640
1641 pub fn remember_project_directory(&mut self, host: &str, directory: &Path) {
1642 let key = project_history_key(host);
1643 let directories = self.mount_history.entry(key).or_default();
1644 directories.retain(|existing| existing != directory);
1645 directories.insert(0, directory.to_path_buf());
1646 directories.truncate(20);
1647 }
1648
1649 pub fn destroy_stopped_session(&mut self, session_id: &str) -> Result<SessionRecord> {
1650 let session = self
1651 .sessions
1652 .get(session_id)
1653 .with_context(|| format!("unknown session {session_id}"))?;
1654 if session.state.is_active() {
1655 bail!("refusing to destroy active session {session_id}");
1656 }
1657 Ok(self
1658 .sessions
1659 .remove(session_id)
1660 .expect("session checked above"))
1661 }
1662
1663 pub fn destroy_session_force(&mut self, session_id: &str) -> Result<SessionRecord> {
1669 self.sessions
1670 .get(session_id)
1671 .with_context(|| format!("unknown session {session_id}"))?;
1672 Ok(self
1673 .sessions
1674 .remove(session_id)
1675 .expect("session checked above"))
1676 }
1677
1678 pub fn validate_setup_update(&self, before: &Config, after: &Config) -> Result<()> {
1681 for session in self
1682 .sessions
1683 .values()
1684 .filter(|session| session.state.is_active())
1685 {
1686 let protected = if let Some(profile) = before.profiles.get(&session.last_profile) {
1687 let mut comparable = profile.clone();
1688 if let Some(updated) = after.profiles.get(&session.last_profile) {
1689 comparable.enabled = updated.enabled;
1690 }
1691 profile.kind == session.harness_kind
1693 && after.profiles.get(&session.last_profile) != Some(&comparable)
1694 } else {
1695 false
1696 };
1697 let bundle_changed = session.project_directory.is_none()
1698 && before
1699 .bundles
1700 .get(&session.bundle_id)
1701 .is_some_and(|bundle| after.bundles.get(&session.bundle_id) != Some(bundle));
1702 let target_changed =
1706 before
1707 .targets
1708 .get(&session.target_template_id)
1709 .is_some_and(|target| {
1710 after
1711 .targets
1712 .get(&session.target_template_id)
1713 .map(TargetTemplate::without_launch_only_settings)
1714 != Some(target.without_launch_only_settings())
1715 });
1716 if protected || bundle_changed || target_changed {
1717 bail!(
1718 "Setup would change configuration used by active session {:?}. Keep its profile {:?}, bundle {:?}, and target {:?}; add a separate entry for new settings, or stop the session before editing its configuration.",
1719 session.id,
1720 session.last_profile,
1721 session.bundle_id,
1722 session.target_template_id
1723 );
1724 }
1725 }
1726 Ok(())
1727 }
1728
1729 pub fn validate_against_config(&self, config: &Config) -> Result<()> {
1731 self.validate()?;
1732 config.validate()?;
1733 for session in self.sessions.values() {
1734 session.validate_configuration(config)?;
1735 }
1736 Ok(())
1737 }
1738}
1739
1740fn project_history_key(host: &str) -> String {
1741 format!("project:{host}")
1742}
1743
1744pub fn new_session_id() -> Result<String> {
1746 let mut random = [0u8; 16];
1747 getrandom::fill(&mut random)
1748 .map_err(|error| anyhow::anyhow!("generate Mjolnir session id: {error}"))?;
1749 Ok(crate::hex::lower_hex(random))
1750}
1751
1752pub fn harness_session_title(events: &[SequencedEvent]) -> Option<String> {
1754 events.iter().rev().find_map(|event| {
1755 let WorkerEvent::Adapter { payload, .. } = &event.event else {
1756 return None;
1757 };
1758 let crate::acp::RuntimeEvent::SessionUpdate { update } =
1759 serde_json::from_value(payload.clone()).ok()?
1760 else {
1761 return None;
1762 };
1763 let kind = update
1764 .get("sessionUpdate")
1765 .and_then(serde_json::Value::as_str)?;
1766 let title = match kind {
1767 "session_info_update" | "session_title" => {
1768 update.get("title").and_then(serde_json::Value::as_str)
1769 }
1770 _ => None,
1771 }?;
1772 normalize_session_title(title)
1773 })
1774}
1775
1776pub fn normalize_session_title(title: &str) -> Option<String> {
1777 let normalized = crate::relay::strip_hidden_prompt_context(title)
1778 .split_whitespace()
1779 .collect::<Vec<_>>()
1780 .join(" ");
1781 (!normalized.is_empty()).then_some(normalized)
1782}
1783
1784pub fn provisional_session_title(prompt: &str) -> Option<String> {
1790 const MAX_TITLE_CHARS: usize = 64;
1791
1792 let normalized = normalize_session_title(prompt)?;
1793 if normalized.chars().count() <= MAX_TITLE_CHARS {
1794 return Some(normalized);
1795 }
1796
1797 let mut truncated = normalized
1798 .chars()
1799 .take(MAX_TITLE_CHARS - 1)
1800 .collect::<String>();
1801 if let Some(boundary) = truncated.rfind(char::is_whitespace) {
1802 truncated.truncate(boundary);
1803 }
1804 truncated.push('…');
1805 Some(truncated)
1806}
1807
1808pub fn short_id(id: &str) -> &str {
1809 id.get(..8).unwrap_or(id)
1810}
1811
1812#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
1813pub struct RecoveryCandidate {
1814 pub session_id: String,
1815 pub target_template_id: String,
1816 pub locator: TargetLocator,
1817 pub ownership: Option<crate::worker_launch::WorkerOwnership>,
1818 #[serde(default)]
1821 pub instance_id: Option<String>,
1822 #[serde(default, skip_serializing_if = "Option::is_none")]
1827 pub tracked_session: Option<SessionState>,
1828}
1829
1830#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
1831pub struct RecoveryScan {
1832 pub candidates: Vec<RecoveryCandidate>,
1833 pub warnings: Vec<String>,
1834 #[serde(default)]
1836 pub instance_id: String,
1837 #[serde(default)]
1840 pub hidden_other_instances: usize,
1841}
1842
1843#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1844#[serde(deny_unknown_fields)]
1845pub struct ResumeRepositorySourceReceipt {
1846 pub session_id: String,
1847 pub bundle_id: String,
1848 pub checkpoint_sha256: String,
1849 pub repositories: Vec<crate::config::ProjectRepository>,
1850}
1851
1852#[cfg(test)]
1853mod tests;