1#[cfg(test)]
4use std::collections::BTreeMap;
5use std::collections::BTreeSet;
6use std::path::{Component, Path, PathBuf};
7use std::sync::Arc;
8
9use anyhow::{Context, Result, bail};
10use serde::{Deserialize, Serialize};
11
12use crate::config::{Config, HarnessKind, ProjectRepository, TargetTemplate, validate_id};
13use crate::credentials::CredentialSyncSignal;
14use crate::relay::{
15 RELAY_EVENT_GENESIS_DIGEST, RelayOperationalState, SequencedEvent, WorkerEvent,
16};
17use crate::snapshot_map::SnapshotMap;
18use crate::subagent::SubagentRecord;
19use crate::targets::{AdditionalMount, validate_additional_mounts};
20
21pub const STATE_VERSION: u32 = 1;
22
23mod target_runtime;
24pub use target_runtime::{TargetConnection, TargetRuntimeSettings};
25
26mod session_configuration;
27pub use session_configuration::SessionConfiguration;
28
29mod session_move;
30pub use session_move::*;
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(rename_all = "kebab-case")]
34pub enum SessionState {
35 Provisioning,
36 StartupCleanup,
38 Running,
39 Disconnected,
40 Checkpointing,
41 Closing,
42 Destroying,
43 #[serde(alias = "archived")]
46 Stopped,
47 Parked,
54 Lost,
55 Error,
56 DestroyedWithDataLoss,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(rename_all = "kebab-case")]
63pub enum SessionTransitionKind {
64 Starting,
65 Resuming,
66 Moving,
67 Suspending,
68 Destroying,
69 Stopping,
71}
72
73impl SessionTransitionKind {
74 pub const fn label(self) -> &'static str {
75 match self {
76 Self::Starting => "Starting",
77 Self::Resuming => "Resuming",
78 Self::Moving => "Moving",
79 Self::Suspending => "Suspending",
80 Self::Destroying => "Destroying",
81 Self::Stopping => "Stopping",
82 }
83 }
84
85 pub fn for_session(state: SessionState, operation: Option<Self>) -> Option<Self> {
86 operation.or_else(|| state.transition_kind())
87 }
88}
89
90#[cfg(test)]
91mod transition_tests {
92 use super::{SessionState, SessionTransitionKind};
93
94 #[test]
95 fn operation_ownership_hides_intermediate_move_states_but_not_ordinary_live_work() {
96 for state in [
97 SessionState::Stopped,
98 SessionState::Running,
99 SessionState::Disconnected,
100 ] {
101 assert_eq!(
102 SessionTransitionKind::for_session(state, Some(SessionTransitionKind::Moving)),
103 Some(SessionTransitionKind::Moving)
104 );
105 assert_eq!(SessionTransitionKind::for_session(state, None), None);
106 }
107 assert_eq!(SessionState::Checkpointing.transition_kind(), None);
108 assert_eq!(
109 SessionState::Closing.transition_kind(),
110 Some(SessionTransitionKind::Suspending)
111 );
112 }
113}
114
115#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(tag = "state", rename_all = "snake_case")]
118pub enum MaterializedExecutionState {
119 #[default]
120 Idle,
121 Running {
122 started_at_ms: i64,
123 },
124 Closing,
125 Closed,
126}
127
128pub use crate::transcript::{TerminalOutputRecord, TranscriptBody, TranscriptItem};
129
130#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
135#[serde(rename_all = "snake_case")]
136pub enum QueuedCommandKind {
137 #[default]
138 Prompt,
139 SetConfig {
140 key: String,
141 value: String,
142 },
143}
144
145impl QueuedCommandKind {
146 pub fn is_prompt(&self) -> bool {
147 matches!(self, Self::Prompt)
148 }
149}
150
151pub fn config_command_text(key: &str, value: &str) -> String {
154 if key == "fast-mode" {
155 "/fast".to_owned()
156 } else {
157 format!("/{key} {value}")
158 }
159}
160
161#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
162#[serde(deny_unknown_fields)]
163pub struct MaterializedQueuedPrompt {
164 pub command_id: String,
165 #[serde(default, skip_serializing_if = "QueuedCommandKind::is_prompt")]
166 pub kind: QueuedCommandKind,
167 pub content: Vec<serde_json::Value>,
168 pub queued_at_ms: i64,
169 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub accepted_ordinal: Option<u64>,
174}
175
176#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
179#[serde(deny_unknown_fields)]
180pub struct MaterializedTurn {
181 pub command_id: String,
182 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub accepted_ordinal: Option<u64>,
184 pub turn_start_position: u64,
187 pub started_at_ms: i64,
188 #[serde(default, skip_serializing_if = "Option::is_none")]
191 pub steered_into: Option<String>,
192}
193
194impl MaterializedTurn {
195 pub fn belongs_to(&self, command_id: &str) -> bool {
197 self.command_id == command_id || self.steered_into.as_deref() == Some(command_id)
198 }
199}
200
201#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(tag = "kind", rename_all = "snake_case")]
204pub enum TurnOutcomeKind {
205 Completed { stop_reason: String },
207 Rejected {
209 message: String,
210 #[serde(default, skip_serializing_if = "Option::is_none")]
211 reason: Option<crate::event_outcome::OutcomeReason>,
212 },
213 Interrupted {
215 message: String,
216 #[serde(default, skip_serializing_if = "Option::is_none")]
217 reason: Option<crate::event_outcome::OutcomeReason>,
218 },
219}
220
221impl std::fmt::Display for TurnOutcomeKind {
224 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
225 use crate::event_outcome::{OutcomeReason, TurnResultKind};
226 let result = self.result();
227 match result.kind {
228 TurnResultKind::Completed => formatter.write_str("completed, end of turn"),
229 TurnResultKind::InputRequired => formatter.write_str("completed, waiting for input"),
230 TurnResultKind::Cancelled | TurnResultKind::Interrupted => {
231 formatter.write_str("interrupted")
232 }
233 TurnResultKind::Failed if result.reason == Some(OutcomeReason::QuotaLimit) => {
234 formatter.write_str("failed: quota limit reached")
235 }
236 TurnResultKind::Failed | TurnResultKind::Rejected => {
237 let message = result.message.as_deref().unwrap_or("unknown failure");
238 if result.stop_reason.is_some() {
239 write!(formatter, "failed: {}", stop_reason_words(message))
240 } else {
241 write!(
242 formatter,
243 "failed: {}",
244 message.lines().next().unwrap_or_default().trim()
245 )
246 }
247 }
248 }
249 }
250}
251
252fn stop_reason_words(stop_reason: &str) -> String {
255 let mut words = String::new();
256 let mut previous_lower = false;
257 for character in stop_reason.trim().chars() {
258 if character == '_' || character == '-' || character.is_whitespace() {
259 if !words.ends_with(' ') && !words.is_empty() {
260 words.push(' ');
261 }
262 previous_lower = false;
263 continue;
264 }
265 if character.is_uppercase() && previous_lower {
266 words.push(' ');
267 }
268 previous_lower = character.is_lowercase() || character.is_ascii_digit();
269 words.extend(character.to_lowercase());
270 }
271 match words.trim_end() {
272 "" => "no reason given".to_owned(),
273 words => words.to_owned(),
274 }
275}
276
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub enum PromptCompletion {
279 InputRequired,
280 Finished,
281 Cancelled,
282 QuotaLimit,
283 Error,
284}
285
286pub fn classify_prompt_completion(stop_reason: &str) -> PromptCompletion {
288 let normalized = stop_reason
289 .chars()
290 .filter(|character| *character != '_' && *character != '-')
291 .flat_map(char::to_lowercase)
292 .collect::<String>();
293 match normalized.as_str() {
294 "endturn" => PromptCompletion::Finished,
295 "awaitinginput" => PromptCompletion::InputRequired,
296 "inferredfinished" => PromptCompletion::Finished,
299 "cancelled" | "canceled" => PromptCompletion::Cancelled,
300 "quotalimit" => PromptCompletion::QuotaLimit,
301 _ => PromptCompletion::Error,
302 }
303}
304
305#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
307#[serde(deny_unknown_fields)]
308pub struct MaterializedTurnOutcome {
309 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub diagnostic: Option<crate::diagnostic::TurnDiagnostic>,
311
312 #[serde(default, skip_serializing_if = "Option::is_none")]
313 pub usage: Option<crate::usage::TokenUsage>,
314 pub command_id: String,
315 #[serde(default, skip_serializing_if = "Option::is_none")]
316 pub accepted_ordinal: Option<u64>,
317 #[serde(default, skip_serializing_if = "Option::is_none")]
318 pub turn_start_position: Option<u64>,
319 pub completed_ordinal: u64,
320 pub completed_at_ms: i64,
321 pub outcome: TurnOutcomeKind,
322}
323
324impl MaterializedTurnOutcome {
325 pub fn interruption_ordinal(&self) -> Option<u64> {
327 (self.turn_start_position.is_some()
328 && matches!(self.outcome, TurnOutcomeKind::Interrupted { .. }))
329 .then_some(self.completed_ordinal)
330 }
331}
332
333#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
335#[serde(deny_unknown_fields)]
336pub struct MaterializedSession {
337 pub session_id: String,
338 pub applied_event_ordinal: u64,
339 pub applied_event_digest: String,
340 pub last_activity_at_ms: Option<i64>,
343 pub execution: MaterializedExecutionState,
344 #[serde(default, skip_serializing_if = "Option::is_none")]
345 pub session_title: Option<String>,
346 #[serde(default, skip_serializing_if = "SessionConfiguration::is_empty")]
347 pub configuration: SessionConfiguration,
348 #[serde(default, skip_serializing_if = "Vec::is_empty")]
349 pub transcript: Vec<Arc<TranscriptItem>>,
352 #[serde(default, skip_serializing_if = "Vec::is_empty")]
353 pub queued_prompts: Vec<MaterializedQueuedPrompt>,
354 #[serde(default, skip_serializing_if = "Vec::is_empty")]
357 pub pending_elicitations: Vec<crate::elicitation::ElicitationRequest>,
358 #[serde(default, skip_serializing_if = "Option::is_none")]
360 pub active_turn: Option<MaterializedTurn>,
361 #[serde(default, skip_serializing_if = "Option::is_none")]
364 pub last_turn_outcome: Option<MaterializedTurnOutcome>,
365}
366
367#[derive(Debug, Clone, PartialEq, Eq)]
370pub struct MaterializedSessionSummary {
371 pub session_id: String,
372 pub applied_event_ordinal: u64,
373 pub last_activity_at_ms: Option<i64>,
374 pub execution: MaterializedExecutionState,
375 pub session_title: Option<String>,
376 pub last_agent_message: Option<String>,
377 pub last_user_message: Option<String>,
378 pub last_agent_message_follows_last_user: bool,
381 pub agent_message_latest_content_ordinals: Vec<u64>,
382 pub interruption_event_ordinals: Vec<u64>,
383}
384
385impl MaterializedSession {
386 pub fn empty(session_id: impl Into<String>) -> Self {
387 Self {
388 session_id: session_id.into(),
389 applied_event_ordinal: 0,
390 applied_event_digest: RELAY_EVENT_GENESIS_DIGEST.into(),
391 last_activity_at_ms: None,
392 execution: MaterializedExecutionState::Idle,
393 session_title: None,
394 configuration: SessionConfiguration::default(),
395 transcript: Vec::new(),
396 queued_prompts: Vec::new(),
397 pending_elicitations: Vec::new(),
398 active_turn: None,
399 last_turn_outcome: None,
400 }
401 }
402
403 pub fn last_activity_at_ms(&self) -> Option<i64> {
404 self.last_activity_at_ms
405 }
406
407 pub fn resolved_title(&self) -> Option<String> {
413 self.session_title
414 .as_deref()
415 .and_then(normalize_session_title)
416 .or_else(|| {
417 self.transcript.iter().find_map(|item| {
418 if !item.is_user_prompt() {
419 return None;
420 }
421 let TranscriptBody::User { content } = &item.body else {
422 return None;
423 };
424 provisional_session_title(&crate::transcript::materialized_content_text(
425 content,
426 ))
427 })
428 })
429 .or_else(|| {
430 self.queued_prompts
431 .iter()
432 .filter(|prompt| prompt.kind.is_prompt())
433 .find_map(|prompt| {
434 provisional_session_title(&crate::transcript::materialized_content_text(
435 &prompt.content,
436 ))
437 })
438 })
439 }
440
441 pub fn unread_agent_messages_after(&self, viewed_through_event_ordinal: u64) -> u64 {
442 self.transcript
443 .iter()
444 .filter(|item| {
445 item.latest_content_event_ordinal
446 .is_some_and(|ordinal| ordinal > viewed_through_event_ordinal)
447 && item.is_nonempty_agent_message()
448 })
449 .count() as u64
450 }
451
452 pub fn unread_interruptions_after(&self, viewed_through_event_ordinal: u64) -> u64 {
453 self.interruption_event_ordinals()
454 .into_iter()
455 .filter(|ordinal| *ordinal > viewed_through_event_ordinal)
456 .count() as u64
457 }
458
459 pub fn interruption_event_ordinals(&self) -> Vec<u64> {
460 let mut ordinals = self
461 .transcript
462 .iter()
463 .filter(|item| item.is_work_interruption())
464 .map(|item| item.position)
465 .collect::<Vec<_>>();
466 if let Some(ordinal) = self
467 .last_turn_outcome
468 .as_ref()
469 .and_then(MaterializedTurnOutcome::interruption_ordinal)
470 {
471 ordinals.push(ordinal);
472 }
473 ordinals.sort_unstable();
474 ordinals.dedup();
475 ordinals
476 }
477
478 pub fn validate(&self) -> Result<()> {
479 validate_id("session", &self.session_id)?;
480 validate_relay_event_frontier(
481 self.applied_event_ordinal,
482 &self.applied_event_digest,
483 "materialized session event frontier",
484 )?;
485 if self
486 .session_title
487 .as_ref()
488 .is_some_and(|title| title.trim().is_empty())
489 {
490 bail!("materialized session has an empty title");
491 }
492 let mut item_ids = BTreeSet::new();
493 for item in &self.transcript {
494 item.validate(self.applied_event_ordinal)?;
495 if !item_ids.insert(item.stable_id.as_str()) {
496 bail!(
497 "materialized transcript contains duplicate item {:?}",
498 item.stable_id
499 );
500 }
501 }
502 let mut command_ids = BTreeSet::new();
503 for prompt in &self.queued_prompts {
504 if prompt.command_id.trim().is_empty() {
505 bail!("materialized prompt queue has an empty command id");
506 }
507 if !command_ids.insert(prompt.command_id.as_str()) {
508 bail!(
509 "materialized prompt queue contains duplicate command {:?}",
510 prompt.command_id
511 );
512 }
513 if let QueuedCommandKind::SetConfig { key, value } = &prompt.kind
514 && (key.trim().is_empty() || value.trim().is_empty())
515 {
516 bail!(
517 "materialized queued configuration change {:?} is incomplete",
518 prompt.command_id
519 );
520 }
521 }
522 Ok(())
523 }
524}
525
526#[derive(Debug, Clone, PartialEq)]
530pub struct ManagedSessionSnapshot {
531 pub materialized: MaterializedSession,
532 pub window: ProjectionWindow,
535 pub operational: RelayOperationalState,
536 pub latest_credential_sync_signal: Option<CredentialSyncSignal>,
540 pub worker_build: Option<String>,
544 pub subagent_requests: Vec<crate::subagent::SubagentToolRequest>,
546 pub subagent_results: Vec<crate::subagent::SubagentToolResult>,
548}
549
550#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
562pub struct ProjectionWindow {
563 pub omitted_items: usize,
565 pub provisional_title: Option<String>,
567 pub latest_turn_start_position: Option<u64>,
571}
572
573impl ProjectionWindow {
574 pub fn trim(&mut self, session: &mut MaterializedSession, target: usize) {
577 let observed = Self::of(session);
578 if self.provisional_title.is_none() {
579 self.provisional_title = observed.provisional_title;
580 }
581 self.latest_turn_start_position = observed
582 .latest_turn_start_position
583 .or(self.latest_turn_start_position);
584 let mut boundary = session.transcript.len().saturating_sub(target.max(1));
585 for (index, item) in session.transcript.iter().enumerate() {
586 let mutable = match &item.body {
587 TranscriptBody::Agent { streaming, .. }
588 | TranscriptBody::Thought { streaming, .. } => *streaming,
589 TranscriptBody::Tool { call, .. } => matches!(
590 call.get("status").and_then(serde_json::Value::as_str),
591 Some("pending" | "in_progress")
592 ),
593 _ => false,
594 };
595 if mutable || Some(item.position) == self.latest_turn_start_position {
596 boundary = boundary.min(index);
597 }
598 }
599 let cut = session
600 .transcript
601 .iter()
602 .take(boundary + 1)
603 .rposition(|item| item.is_turn_start())
604 .unwrap_or(0);
605 if cut > 0 {
606 session.transcript.drain(..cut);
607 self.omitted_items += cut;
608 }
609 }
610
611 #[must_use]
613 pub fn of(session: &MaterializedSession) -> Self {
614 Self {
615 omitted_items: 0,
616 provisional_title: session.transcript.iter().find_map(|item| {
617 if !item.is_user_prompt() {
618 return None;
619 }
620 let TranscriptBody::User { content } = &item.body else {
621 return None;
622 };
623 provisional_session_title(&crate::transcript::materialized_content_text(content))
624 }),
625 latest_turn_start_position: session
626 .transcript
627 .iter()
628 .rev()
629 .find(|item| item.is_turn_start())
630 .map(|item| item.position),
631 }
632 }
633}
634
635impl ManagedSessionSnapshot {
636 #[must_use]
641 pub fn resolved_title(&self) -> Option<String> {
642 self.materialized
643 .session_title
644 .as_deref()
645 .and_then(normalize_session_title)
646 .or_else(|| self.window.provisional_title.clone())
647 .or_else(|| {
648 self.materialized
649 .queued_prompts
650 .iter()
651 .filter(|prompt| prompt.kind.is_prompt())
652 .find_map(|prompt| {
653 provisional_session_title(&crate::transcript::materialized_content_text(
654 &prompt.content,
655 ))
656 })
657 })
658 }
659
660 #[must_use]
665 pub fn latest_completed_turn_ordinal(&self) -> Option<u64> {
666 if self.materialized.execution != MaterializedExecutionState::Idle {
667 return None;
668 }
669 self.window.latest_turn_start_position
670 }
671}
672
673#[derive(Debug, Clone)]
675pub struct RecoveryObservation {
676 pub session: SessionRecord,
677 pub config: Config,
678 pub latest_completed_turn_ordinal: Option<u64>,
679 pub checkpoint_wait: Option<crate::activity::CheckpointWait>,
683}
684
685pub fn latest_completed_turn_ordinal(session: &MaterializedSession) -> Option<u64> {
690 if session.execution != MaterializedExecutionState::Idle {
691 return None;
692 }
693 session
694 .transcript
695 .iter()
696 .rev()
697 .find(|item| item.is_turn_start())
698 .map(|item| item.position)
699}
700
701pub fn validate_relay_event_digest(digest: &str, name: &str) -> Result<()> {
702 if digest.len() != 64
703 || !digest
704 .bytes()
705 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
706 {
707 bail!("{name} must be a lowercase SHA-256 digest");
708 }
709 Ok(())
710}
711
712pub fn validate_relay_event_frontier(ordinal: u64, digest: &str, name: &str) -> Result<()> {
713 validate_relay_event_digest(digest, name)?;
714 if (ordinal == 0) != (digest == RELAY_EVENT_GENESIS_DIGEST) {
715 bail!("{name} has inconsistent ordinal {ordinal} and digest {digest}");
716 }
717 Ok(())
718}
719
720fn is_false(value: &bool) -> bool {
721 !*value
722}
723
724impl SessionState {
725 pub const fn as_str(self) -> &'static str {
727 match self {
728 Self::Provisioning => "provisioning",
729 Self::StartupCleanup => "startup-cleanup",
730 Self::Running => "running",
731 Self::Disconnected => "disconnected",
732 Self::Checkpointing => "checkpointing",
733 Self::Closing => "closing",
734 Self::Destroying => "destroying",
735 Self::Stopped => "stopped",
736 Self::Parked => "parked",
737 Self::Lost => "lost",
738 Self::Error => "error",
739 Self::DestroyedWithDataLoss => "destroyed-with-data-loss",
740 }
741 }
742
743 pub fn from_stored(value: &str) -> Option<Self> {
746 Some(match value {
747 "provisioning" => Self::Provisioning,
748 "startup-cleanup" => Self::StartupCleanup,
749 "running" => Self::Running,
750 "disconnected" => Self::Disconnected,
751 "checkpointing" => Self::Checkpointing,
752 "closing" => Self::Closing,
753 "destroying" => Self::Destroying,
754 "stopped" | "archived" => Self::Stopped,
755 "parked" => Self::Parked,
756 "lost" => Self::Lost,
757 "error" => Self::Error,
758 "destroyed-with-data-loss" => Self::DestroyedWithDataLoss,
759 _ => return None,
760 })
761 }
762
763 pub const fn transition_kind(self) -> Option<SessionTransitionKind> {
766 match self {
767 Self::Provisioning => Some(SessionTransitionKind::Starting),
768 Self::StartupCleanup => Some(SessionTransitionKind::Stopping),
769 Self::Closing => Some(SessionTransitionKind::Suspending),
770 Self::Destroying => Some(SessionTransitionKind::Destroying),
771 _ => None,
772 }
773 }
774
775 pub const fn is_active(self) -> bool {
782 matches!(
783 self,
784 Self::Provisioning
785 | Self::StartupCleanup
786 | Self::Running
787 | Self::Disconnected
788 | Self::Checkpointing
789 | Self::Closing
790 | Self::Destroying
791 | Self::Parked
792 | Self::Error
793 )
794 }
795
796 pub const fn has_live_worker(self) -> bool {
800 matches!(
801 self,
802 Self::Provisioning
803 | Self::StartupCleanup
804 | Self::Running
805 | Self::Disconnected
806 | Self::Checkpointing
807 | Self::Closing
808 | Self::Destroying
809 )
810 }
811}
812
813#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
814#[serde(tag = "kind", rename_all = "kebab-case")]
815pub enum PodmanWorkspaceLocator {
816 #[default]
817 ContainerLayer,
818 Volume {
819 name: String,
820 },
821 HostPath {
822 path: PathBuf,
823 helper: Vec<String>,
824 resource: String,
825 },
826}
827
828#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
829#[serde(tag = "kind", rename_all = "kebab-case")]
830pub enum TargetLocator {
831 LocalBare {
832 worker_root: PathBuf,
833 },
834 LocalPodman {
835 container_id: String,
836 #[serde(default)]
837 workspace_storage: PodmanWorkspaceLocator,
838 #[serde(default, skip_serializing_if = "Option::is_none")]
842 borrowed_from: Option<String>,
843 },
844 LocalDocker {
845 container_id: String,
846 #[serde(default, skip_serializing_if = "Option::is_none")]
850 borrowed_from: Option<String>,
851 },
852 AppleContainer {
853 container_id: String,
854 #[serde(default, skip_serializing_if = "Option::is_none")]
858 borrowed_from: Option<String>,
859 },
860 AwsEc2 {
861 instance_id: String,
862 #[serde(default, skip_serializing_if = "Option::is_none")]
863 address: Option<String>,
864 },
865 SshBare {
866 host: String,
867 workspace: PathBuf,
868 #[serde(default, skip_serializing_if = "Option::is_none")]
869 worker_id: Option<String>,
870 },
871 SshPodman {
872 host: String,
873 container_id: String,
874 #[serde(default)]
875 workspace_storage: PodmanWorkspaceLocator,
876 #[serde(default, skip_serializing_if = "Option::is_none")]
880 borrowed_from: Option<String>,
881 },
882 SshDocker {
883 host: String,
884 container_id: String,
885 #[serde(default, skip_serializing_if = "Option::is_none")]
889 borrowed_from: Option<String>,
890 },
891}
892
893impl ManagedWorktreeTarget {
894 pub fn same_location(&self, other: &Self) -> bool {
902 match (self, other) {
903 (Self::Local, Self::Local) => true,
904 (
905 Self::Ssh {
906 destination,
907 ssh_args,
908 },
909 Self::Ssh {
910 destination: other_destination,
911 ssh_args: other_args,
912 },
913 ) => {
914 destination == other_destination
915 && ssh_location_option(ssh_args, 'p', "port")
916 == ssh_location_option(other_args, 'p', "port")
917 && ssh_location_option(ssh_args, 'l', "user")
918 == ssh_location_option(other_args, 'l', "user")
919 }
920 _ => false,
921 }
922 }
923}
924
925fn ssh_location_option(args: &[String], flag: char, option: &str) -> Option<String> {
929 let mut args = args.iter();
930 while let Some(argument) = args.next() {
931 let Some(rest) = argument.strip_prefix('-') else {
932 continue;
933 };
934 let mut chars = rest.chars();
935 let Some(name) = chars.next() else { continue };
936 if name != flag && name != 'o' {
937 continue;
938 }
939 let inline = chars.as_str();
940 let value = if inline.is_empty() {
941 args.next().cloned()
942 } else {
943 Some(inline.to_owned())
944 };
945 if name == flag {
946 return value;
947 }
948 if let Some(setting) = value {
949 let (key, found) = setting
950 .split_once(['=', ' ', '\t'])
951 .unwrap_or((setting.as_str(), ""));
952 if key.trim().eq_ignore_ascii_case(option) {
953 return Some(found.trim().to_owned());
954 }
955 }
956 }
957 None
958}
959
960#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
961#[serde(tag = "kind", rename_all = "kebab-case")]
962pub enum ManagedWorktreeTarget {
963 Local,
964 Ssh {
965 destination: String,
966 #[serde(default, skip_serializing_if = "Vec::is_empty")]
967 ssh_args: Vec<String>,
968 },
969}
970
971#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
973#[serde(deny_unknown_fields)]
974pub struct ManagedWorktreeOptions {
975 pub available: bool,
976 pub default_create: bool,
977}
978
979#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
980#[serde(deny_unknown_fields)]
981pub struct ManagedWorktree {
982 #[serde(default, skip_serializing_if = "ManagedCheckoutKind::is_worktree")]
984 pub kind: ManagedCheckoutKind,
985 pub source_project_directory: PathBuf,
986 pub source_repository: PathBuf,
987 pub worktree_root: PathBuf,
988 pub branch: String,
989 pub target: ManagedWorktreeTarget,
990 #[serde(default, skip_serializing_if = "Option::is_none")]
994 pub base_commit: Option<String>,
995}
996
997#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
998#[serde(rename_all = "snake_case")]
999pub enum ManagedCheckoutKind {
1000 #[default]
1001 Worktree,
1002 Clone,
1003}
1004
1005impl ManagedCheckoutKind {
1006 fn is_worktree(&self) -> bool {
1007 matches!(self, Self::Worktree)
1008 }
1009}
1010
1011impl ManagedWorktree {
1012 fn validate(&self, session_id: &str, project_directory: Option<&Path>) -> Result<()> {
1013 for (label, path) in [
1014 ("source project directory", &self.source_project_directory),
1015 ("source repository", &self.source_repository),
1016 ("worktree root", &self.worktree_root),
1017 ] {
1018 if !crate::target_path::is_absolute(path)
1019 || path.components().any(|part| part == Component::ParentDir)
1020 {
1021 bail!("managed worktree {label} must be an absolute safe path");
1022 }
1023 }
1024 if !self
1025 .source_project_directory
1026 .starts_with(&self.source_repository)
1027 {
1028 bail!("managed worktree source directory is outside its repository");
1029 }
1030 let expected_root = self
1031 .source_repository
1032 .join(".mj")
1033 .join(match self.kind {
1034 ManagedCheckoutKind::Worktree => "worktrees",
1035 ManagedCheckoutKind::Clone => "clones",
1036 })
1037 .join(session_id);
1038 if self.worktree_root != expected_root {
1039 bail!("managed worktree root does not match the session-owned path");
1040 }
1041 if self.kind == ManagedCheckoutKind::Worktree && self.branch != format!("mj/{session_id}") {
1042 bail!("managed worktree branch does not match the session id");
1043 }
1044 if self.kind == ManagedCheckoutKind::Clone && self.branch.trim().is_empty() {
1045 bail!("managed clone has no starting branch");
1046 }
1047 let relative = self
1048 .source_project_directory
1049 .strip_prefix(&self.source_repository)
1050 .expect("source relationship checked above");
1051 if project_directory != Some(self.worktree_root.join(relative).as_path()) {
1052 bail!("session project directory does not match its managed worktree");
1053 }
1054 match &self.target {
1055 ManagedWorktreeTarget::Local => {}
1056 ManagedWorktreeTarget::Ssh { destination, .. } if destination.trim().is_empty() => {
1057 bail!("managed SSH worktree has an empty destination")
1058 }
1059 ManagedWorktreeTarget::Ssh { .. } => {}
1060 }
1061 Ok(())
1062 }
1063}
1064
1065#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1066#[serde(tag = "kind", rename_all = "kebab-case")]
1067pub enum SessionResourceAllocation {
1068 Container {
1069 cpus: u64,
1070 memory_bytes: u64,
1071 },
1072 AwsEc2 {
1073 instance_type: String,
1074 vcpus: u64,
1075 memory_bytes: u64,
1076 },
1077}
1078
1079#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1081#[serde(rename_all = "kebab-case")]
1082pub enum ResourceAllocationKind {
1083 #[default]
1084 Fixed,
1085 Container,
1086 AwsEc2,
1087}
1088
1089impl SessionResourceAllocation {
1090 pub fn validate(&self) -> Result<()> {
1091 match self {
1092 Self::Container { cpus, memory_bytes } if *cpus == 0 || *memory_bytes == 0 => {
1093 bail!("container resource allocation must have non-zero CPU and memory")
1094 }
1095 Self::AwsEc2 {
1096 instance_type,
1097 vcpus,
1098 memory_bytes,
1099 } if instance_type.trim().is_empty() || *vcpus == 0 || *memory_bytes == 0 => {
1100 bail!("EC2 resource allocation must have an instance type, CPU, and memory")
1101 }
1102 _ => Ok(()),
1103 }
1104 }
1105}
1106
1107pub fn allocation_cpus(allocation: &SessionResourceAllocation) -> u64 {
1109 match allocation {
1110 SessionResourceAllocation::Container { cpus, .. } => *cpus,
1111 SessionResourceAllocation::AwsEc2 { vcpus, .. } => *vcpus,
1112 }
1113}
1114
1115pub fn allocation_memory(allocation: &SessionResourceAllocation) -> u64 {
1117 match allocation {
1118 SessionResourceAllocation::Container { memory_bytes, .. }
1119 | SessionResourceAllocation::AwsEc2 { memory_bytes, .. } => *memory_bytes,
1120 }
1121}
1122
1123impl TargetLocator {
1124 pub const fn skills_scope(&self) -> crate::skills::SkillsScope {
1126 match self {
1127 Self::LocalBare { .. } => crate::skills::SkillsScope::Localhost,
1128 _ => crate::skills::SkillsScope::Isolated,
1129 }
1130 }
1131
1132 fn validate(&self, session_id: &str) -> Result<()> {
1133 match self {
1134 Self::LocalBare { worker_root } => {
1135 if !crate::target_path::is_absolute(worker_root)
1136 || worker_root
1137 .components()
1138 .any(|part| part == Component::ParentDir)
1139 || !worker_root.ends_with(session_id)
1140 {
1141 bail!(
1142 "local bare worker root must be an absolute safe path ending in the session id"
1143 );
1144 }
1145 }
1146 Self::LocalPodman { container_id, .. }
1147 | Self::LocalDocker { container_id, .. }
1148 | Self::AppleContainer { container_id, .. }
1149 | Self::SshPodman { container_id, .. }
1150 | Self::SshDocker { container_id, .. }
1151 if container_id.trim().is_empty() =>
1152 {
1153 bail!("target locator has an empty container id")
1154 }
1155 Self::AwsEc2 { instance_id, .. } if instance_id.trim().is_empty() => {
1156 bail!("target locator has an empty AWS instance id")
1157 }
1158 Self::SshBare {
1159 host,
1160 workspace,
1161 worker_id,
1162 } => {
1163 if host.trim().is_empty() {
1164 bail!("bare SSH target locator has an empty host");
1165 }
1166 let unsafe_path = workspace.as_os_str().is_empty()
1167 || workspace
1168 .components()
1169 .any(|part| part == Component::ParentDir);
1170 match worker_id {
1171 Some(worker_id) => {
1174 if worker_id != session_id {
1175 bail!(
1176 "bare SSH target locator's worker identity does not match the session id"
1177 );
1178 }
1179 if unsafe_path {
1180 bail!("bare SSH target locator must have a safe workspace path");
1181 }
1182 }
1183 None => {
1184 if unsafe_path || !workspace.ends_with(session_id) {
1185 bail!(
1186 "bare SSH target locator must be a safe path ending in the session id"
1187 );
1188 }
1189 }
1190 }
1191 }
1192 Self::SshPodman { host, .. } if host.trim().is_empty() => {
1193 bail!("SSH Podman target locator has an empty host")
1194 }
1195 Self::SshDocker { host, .. } if host.trim().is_empty() => {
1196 bail!("SSH Docker target locator has an empty host")
1197 }
1198 _ => {}
1199 }
1200 Ok(())
1201 }
1202}
1203
1204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1205#[serde(deny_unknown_fields)]
1206pub struct CheckpointMetadata {
1207 pub archive_path: PathBuf,
1208 pub sha256: String,
1210 pub created_at: String,
1211 pub event_frontier: u64,
1212}
1213
1214#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1216#[serde(rename_all = "snake_case")]
1217pub enum PublicationState {
1218 Published,
1219 Unpublished,
1220 Unknown,
1221}
1222
1223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1225pub struct PublicationAssessment {
1226 pub checkpoint_sha256: String,
1227 pub state: PublicationState,
1228 pub dirty: bool,
1229 pub stashed: bool,
1230 pub saved_commits: Vec<String>,
1231 pub destinations: Vec<String>,
1232 pub checked_at: String,
1233 pub reason: Option<String>,
1234}
1235
1236impl CheckpointMetadata {
1237 fn validate(&self) -> Result<()> {
1238 if self.archive_path.as_os_str().is_empty() {
1239 bail!("checkpoint archive path is empty");
1240 }
1241 if self.sha256.len() != 64
1242 || !self
1243 .sha256
1244 .bytes()
1245 .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
1246 {
1247 bail!("checkpoint SHA-256 must be 64 lowercase hexadecimal characters");
1248 }
1249 if self.created_at.trim().is_empty() {
1250 bail!("checkpoint timestamp is empty");
1251 }
1252 Ok(())
1253 }
1254}
1255
1256#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1261#[serde(deny_unknown_fields)]
1262pub struct SessionBuildCache {
1263 pub host: String,
1266 pub directory: PathBuf,
1267 #[serde(default, skip_serializing_if = "Option::is_none")]
1270 pub max_size: Option<String>,
1271 #[serde(default, skip_serializing_if = "Option::is_none")]
1274 pub target_root: Option<PathBuf>,
1275}
1276
1277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1281pub struct ArchiveSpacePreview {
1282 pub sessions: usize,
1284 pub bytes: u64,
1286 pub reclaimable_sessions: usize,
1289 pub reclaimable_bytes: u64,
1290}
1291
1292#[derive(Debug, Clone, PartialEq, Eq)]
1296pub struct BuildCachePreview {
1297 pub native_mbx: Option<String>,
1299 pub mbx_profile_file: Option<String>,
1301 pub mbx_profile_warning: Option<String>,
1303 pub mbx_manual_path_line: Option<String>,
1305 pub directory: Option<PathBuf>,
1307 pub max_total_size: Option<BuildCacheLimit>,
1309 pub user_managed: bool,
1311 pub application: BuildCacheApplication,
1312 pub budget_note: Option<String>,
1314 pub stats: Option<BuildCacheStats>,
1316 pub off_reason: Option<BuildCacheOff>,
1319}
1320
1321#[derive(Debug, Clone, PartialEq, Eq)]
1329pub struct BuildCacheStats {
1330 pub builds: u64,
1332 pub cached_compilations: u64,
1334 pub avoided_compiler_ns: u64,
1336 pub reflinked_bytes: u64,
1338}
1339
1340#[derive(Debug, Clone, PartialEq, Eq)]
1342pub enum BuildCacheOff {
1343 TurnedOff,
1345 Unavailable(String),
1348}
1349
1350impl std::fmt::Display for BuildCacheOff {
1351 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1352 match self {
1353 Self::TurnedOff => formatter.write_str("turned off for this machine"),
1354 Self::Unavailable(reason) => formatter.write_str(reason),
1355 }
1356 }
1357}
1358
1359#[derive(Debug, Clone, PartialEq, Eq)]
1361pub enum BuildCacheLimit {
1362 Size(String),
1364 HostConfiguration(Option<String>),
1367 MjDefault(String),
1369 MbxDefault(Option<String>),
1371}
1372
1373#[derive(Debug, Clone, Default, PartialEq, Eq)]
1374pub enum BuildCacheApplication {
1375 #[default]
1376 Pending,
1377 Applied,
1378 Failed(String),
1379}
1380
1381#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1382#[serde(deny_unknown_fields)]
1383pub struct SessionRecord {
1384 pub id: String,
1385 #[serde(default = "default_session_workspace_id")]
1390 pub workspace_id: String,
1391 pub title: String,
1392 pub harness_kind: HarnessKind,
1393 pub last_profile: String,
1394 pub bundle_id: String,
1395 #[serde(default, skip_serializing_if = "Option::is_none")]
1397 pub project: Option<crate::repository::ProjectBundleSnapshot>,
1398 #[serde(default, skip_serializing_if = "Option::is_none")]
1400 pub project_directory: Option<PathBuf>,
1401 #[serde(default, skip_serializing_if = "Option::is_none")]
1403 pub managed_worktree: Option<ManagedWorktree>,
1404 #[serde(default, skip_serializing_if = "Option::is_none")]
1406 pub create_managed_worktree: Option<bool>,
1407 #[serde(default, skip_serializing_if = "Option::is_none")]
1414 pub launch_base: Option<String>,
1415 #[serde(default, skip_serializing_if = "Option::is_none")]
1419 pub launch_branch: Option<String>,
1420 #[serde(default, skip_serializing_if = "Option::is_none")]
1424 pub checkout: Option<crate::remote_git::ExactCheckout>,
1425 #[serde(default, skip_serializing_if = "Option::is_none")]
1427 pub publication: Option<PublicationAssessment>,
1428 #[serde(
1430 default,
1431 alias = "mjolnir_subagents",
1432 deserialize_with = "crate::subagent::deserialize_optional_policy"
1433 )]
1434 pub subagents: Option<crate::subagent::SubagentPolicy>,
1435 #[serde(default, skip_serializing_if = "Option::is_none")]
1438 pub review: Option<crate::config::SessionReview>,
1439 pub target_template_id: String,
1440 #[serde(default, skip_serializing_if = "Option::is_none")]
1441 pub resource_allocation: Option<SessionResourceAllocation>,
1442 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1443 pub additional_mounts: Vec<AdditionalMount>,
1444 #[serde(default, skip_serializing_if = "Option::is_none")]
1447 pub container_cpus: Option<String>,
1448 #[serde(default, skip_serializing_if = "Option::is_none")]
1451 pub container_memory: Option<String>,
1452 #[serde(default, skip_serializing_if = "Option::is_none")]
1458 pub container_workspace: Option<PathBuf>,
1459 #[serde(default, skip_serializing_if = "Option::is_none")]
1463 pub build_cache: Option<SessionBuildCache>,
1464 pub state: SessionState,
1465 #[serde(default, skip_serializing_if = "is_false")]
1468 pub archived: bool,
1469 #[serde(default, skip_serializing_if = "Option::is_none")]
1470 pub target: Option<TargetLocator>,
1471 #[serde(default, skip_serializing_if = "Option::is_none")]
1473 pub target_runtime: Option<TargetRuntimeSettings>,
1474 #[serde(default, skip_serializing_if = "Option::is_none")]
1475 pub native_session_id: Option<String>,
1476 #[serde(default, skip_serializing_if = "Option::is_none")]
1477 pub acp_session_title: Option<String>,
1478 #[serde(default, skip_serializing_if = "Option::is_none")]
1479 pub session_title_override: Option<String>,
1480 pub created_at: String,
1481 pub updated_at: String,
1482 #[serde(default, alias = "detached_after_event_ordinal")]
1483 pub viewed_through_event_ordinal: u64,
1484 #[serde(default, skip_serializing_if = "String::is_empty")]
1487 pub draft_input: String,
1488 #[serde(default, skip_serializing_if = "Option::is_none")]
1496 pub last_error: Option<String>,
1497 #[serde(default, skip_serializing_if = "Option::is_none")]
1498 pub last_checkpoint_error: Option<String>,
1499 #[serde(default, skip_serializing_if = "Option::is_none")]
1500 pub checkpoint: Option<CheckpointMetadata>,
1501}
1502
1503#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1504#[serde(deny_unknown_fields)]
1505pub struct HostContainerSize {
1506 pub cpus: u64,
1507 pub memory_bytes: u64,
1508}
1509
1510pub const BASELINE_CONTAINER_CPUS: u64 = 8;
1511pub const BASELINE_CONTAINER_MEMORY_BYTES: u64 = 32 * 1024 * 1024 * 1024;
1512
1513pub fn clamp_container_size(
1516 size: HostContainerSize,
1517 limits: Option<HostContainerSize>,
1518) -> HostContainerSize {
1519 let Some(limits) = limits else {
1520 return HostContainerSize {
1521 cpus: size.cpus.max(1),
1522 memory_bytes: size.memory_bytes.max(1),
1523 };
1524 };
1525 HostContainerSize {
1526 cpus: size.cpus.min(limits.cpus.max(1)),
1527 memory_bytes: size.memory_bytes.min(limits.memory_bytes.max(1)),
1528 }
1529}
1530
1531pub fn default_container_size(
1534 remembered: Option<HostContainerSize>,
1535 limits: Option<HostContainerSize>,
1536) -> HostContainerSize {
1537 clamp_container_size(
1538 remembered.unwrap_or(HostContainerSize {
1539 cpus: BASELINE_CONTAINER_CPUS,
1540 memory_bytes: BASELINE_CONTAINER_MEMORY_BYTES,
1541 }),
1542 limits,
1543 )
1544}
1545
1546pub fn preferred_aws_allocation<'a>(
1549 options: &'a [SessionResourceAllocation],
1550 previous: Option<&SessionResourceAllocation>,
1551) -> Option<&'a SessionResourceAllocation> {
1552 if let Some(SessionResourceAllocation::AwsEc2 { instance_type, .. }) = previous
1553 && let Some(option) = options.iter().find(|option| {
1554 matches!(option, SessionResourceAllocation::AwsEc2 { instance_type: candidate, .. } if candidate == instance_type)
1555 })
1556 {
1557 return Some(option);
1558 }
1559 options
1560 .iter()
1561 .find(|option| allocation_cpus(option) == BASELINE_CONTAINER_CPUS)
1562 .or_else(|| options.first())
1563}
1564
1565fn default_session_workspace_id() -> String {
1566 crate::workspace::DEFAULT_WORKSPACE_ID.to_owned()
1567}
1568
1569pub const DESTRUCTION_FAILURE_PREFIX: &str = "the destruction did not finish";
1578
1579pub const CLOSE_FAILURE_PREFIX: &str = "the suspension did not finish";
1580
1581pub const MOVE_FAILURE_PREFIX: &str = "the move did not finish";
1582
1583pub fn is_public_lifecycle_error(error: &str) -> bool {
1585 error.starts_with(CLOSE_FAILURE_PREFIX)
1586 || error.starts_with(MOVE_FAILURE_PREFIX)
1587 || error.starts_with(DESTRUCTION_FAILURE_PREFIX)
1588 || error.starts_with("the close did not finish")
1589}
1590
1591#[must_use]
1604pub fn target_label(config: &Config, target_id: &str, project: Option<&Path>) -> String {
1605 if !matches!(
1606 config.targets.get(target_id),
1607 Some(TargetTemplate::LocalBare | TargetTemplate::SshBare { .. })
1608 ) {
1609 return target_id.to_owned();
1610 }
1611 project.and_then(Path::file_name).map_or_else(
1612 || target_id.to_owned(),
1613 |directory| format!("{target_id}/{}", directory.to_string_lossy()),
1614 )
1615}
1616
1617#[derive(Debug, Clone, Default, PartialEq, Eq)]
1619pub struct StartSelection {
1620 pub at: Option<String>,
1622 pub branch: Option<String>,
1624 pub base: Option<String>,
1626}
1627
1628impl SessionRecord {
1629 #[must_use]
1633 pub fn checkout(&self) -> Checkout<'_> {
1634 derive_record_checkout(self)
1635 }
1636
1637 pub fn start_selection(&self) -> StartSelection {
1641 let at = self
1642 .checkout
1643 .as_ref()
1644 .map(|checkout| checkout.commit.clone());
1645 StartSelection {
1646 branch: self
1647 .checkout
1648 .as_ref()
1649 .and_then(|checkout| checkout.branch.clone())
1650 .or_else(|| self.launch_branch.clone()),
1651 base: self.launch_base.clone().or_else(|| at.clone()),
1652 at,
1653 }
1654 }
1655
1656 pub fn publication_state(&self) -> Option<PublicationState> {
1659 let independent_clone = match self.checkout().effective() {
1660 Checkout::ManagedWorktree { worktree, .. } => {
1661 worktree.kind == ManagedCheckoutKind::Clone
1662 }
1663 Checkout::ManagedWorkspace => true,
1664 Checkout::Attached { .. } | Checkout::Borrowed { .. } => false,
1665 };
1666 if !independent_clone {
1667 return None;
1668 }
1669 if self.state.is_active() {
1670 return Some(PublicationState::Unknown);
1671 }
1672 Some(
1673 self.checkpoint
1674 .as_ref()
1675 .zip(self.publication.as_ref())
1676 .filter(|(checkpoint, assessment)| {
1677 assessment.checkpoint_sha256 == checkpoint.sha256
1678 })
1679 .map_or(PublicationState::Unknown, |(_, assessment)| {
1680 if assessment.dirty || assessment.stashed {
1681 PublicationState::Unpublished
1682 } else {
1683 assessment.state
1684 }
1685 }),
1686 )
1687 }
1688
1689 pub fn target_runtime_settings<'a>(
1694 &'a self,
1695 config: &Config,
1696 ) -> Result<std::borrow::Cow<'a, TargetRuntimeSettings>> {
1697 if let Some(runtime) = &self.target_runtime {
1698 if let Some(refreshed) =
1701 config
1702 .targets
1703 .get(&self.target_template_id)
1704 .and_then(|template| {
1705 runtime.with_current_ssh_options(&TargetRuntimeSettings::from(template))
1706 })
1707 {
1708 return Ok(std::borrow::Cow::Owned(refreshed));
1709 }
1710 return Ok(std::borrow::Cow::Borrowed(runtime));
1711 }
1712 let template = config.targets.get(&self.target_template_id).ok_or_else(|| {
1713 crate::refusal::Refusal::precondition(format!(
1714 "Session {:?} has no recorded target access settings. Restore target {:?} in config.toml once, then retry.",
1715 self.id, self.target_template_id))
1716 })?;
1717 let runtime = TargetRuntimeSettings::from(template);
1718 if let Some(locator) = &self.target {
1719 crate::targets::TargetLocator::try_from(crate::targets::RecordedTarget {
1720 locator, runtime: Some(&runtime), session_id: &self.id,
1721 }).map_err(|error| crate::refusal::Refusal::precondition(format!(
1722 "Session {:?} cannot recover target {:?}: {error}. Restore its original target settings, then retry.", self.id, self.target_template_id)))?;
1723 }
1724 Ok(std::borrow::Cow::Owned(runtime))
1725 }
1726
1727 #[must_use]
1731 pub fn public_error(&self) -> Option<&str> {
1732 self.last_error
1733 .as_deref()
1734 .filter(|error| is_public_lifecycle_error(error))
1735 }
1736
1737 pub fn configuration_issue(&self, config: &Config) -> Option<String> {
1740 if !self.state.is_active() {
1741 return None;
1742 }
1743 let mut issues = Vec::new();
1744 match config.profiles.get(&self.last_profile) {
1745 None => issues.push(format!("missing profile {:?}", self.last_profile)),
1746 Some(profile) if profile.kind != self.harness_kind => issues.push(format!(
1747 "expects {:?}, but profile {:?} is {:?}",
1748 self.harness_kind, self.last_profile, profile.kind
1749 )),
1750 Some(_) => {}
1751 }
1752 if self.checkout().project_directory().is_none() && self.project_bundle(config).is_none() {
1753 issues.push(format!("missing bundle {:?}", self.bundle_id));
1754 }
1755 if self.target_runtime.is_none() && !config.targets.contains_key(&self.target_template_id) {
1756 issues.push(format!(
1757 "missing target template {:?}",
1758 self.target_template_id
1759 ));
1760 }
1761 (!issues.is_empty()).then(|| format!(
1762 "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.",
1763 self.id, issues.join("; ")
1764 ))
1765 }
1766
1767 pub fn validate_configuration(&self, config: &Config) -> Result<()> {
1768 if let Some(issue) = self.configuration_issue(config) {
1769 return Err(crate::refusal::Refusal::precondition(issue).into());
1770 }
1771 Ok(())
1772 }
1773
1774 pub fn display_title(&self) -> &str {
1776 self.session_title_override
1777 .as_deref()
1778 .or(self.acp_session_title.as_deref())
1779 .unwrap_or(&self.id)
1780 }
1781
1782 pub fn listed_title(&self) -> &str {
1787 let named = self.session_title_override.is_some() || self.acp_session_title.is_some();
1788 if !named && !self.title.trim().is_empty() {
1789 return &self.title;
1790 }
1791 self.display_title()
1792 }
1793
1794 pub fn project_name(&self, config: &Config) -> String {
1799 if let Some(project) = &self.project {
1800 return project.name();
1801 }
1802 match self.checkout().effective() {
1803 Checkout::ManagedWorktree { worktree, .. } => path_leaf(&worktree.source_repository),
1804 Checkout::Attached { path } => path_leaf(path),
1805 Checkout::ManagedWorkspace => self.bundle_source_name(config),
1806 Checkout::Borrowed { .. } => unreachable!("effective checkout resolves borrowing"),
1807 }
1808 }
1809
1810 pub fn project_target(&self, config: &Config, target_id: &str) -> String {
1814 let checkout = self.checkout();
1815 let project = match checkout.effective() {
1816 Checkout::ManagedWorktree { worktree, .. } => {
1817 Some(worktree.source_project_directory.as_path())
1818 }
1819 Checkout::Attached { path } => Some(path),
1820 Checkout::ManagedWorkspace => None,
1821 Checkout::Borrowed { .. } => unreachable!("effective checkout resolves borrowing"),
1822 };
1823 target_label(config, target_id, project)
1824 }
1825
1826 pub fn project_source(&self, config: &Config) -> ProjectSourceIdentity {
1831 if let Some(project) = &self.project {
1832 return ProjectSourceIdentity {
1833 key: project
1834 .source_key()
1835 .expect("accepted project has complete identities"),
1836 short: project.name(),
1837 full: project
1838 .identities
1839 .values()
1840 .map(crate::repository::RepositoryIdentity::key)
1841 .collect::<Vec<_>>()
1842 .join(" + "),
1843 };
1844 }
1845 match self.checkout().effective() {
1846 Checkout::ManagedWorktree { worktree, .. } => {
1847 ProjectSourceIdentity::path(&worktree.source_repository, None)
1848 }
1849 Checkout::Attached { path } => {
1850 let remote = match &self.target {
1851 Some(TargetLocator::SshBare { host, .. }) => Some(host.as_str()),
1852 _ => None,
1853 };
1854 ProjectSourceIdentity::path(path, remote)
1855 }
1856 Checkout::ManagedWorkspace => {
1857 self.bundle_source_identity(config)
1858 .unwrap_or_else(|| ProjectSourceIdentity {
1859 key: format!("bundle:{}", self.bundle_id),
1860 short: path_leaf(Path::new(&self.bundle_id)),
1861 full: self.bundle_id.clone(),
1862 })
1863 }
1864 Checkout::Borrowed { .. } => unreachable!("effective checkout resolves borrowing"),
1865 }
1866 }
1867
1868 fn bundle_source_name(&self, config: &Config) -> String {
1871 self.bundle_source_identity(config)
1872 .map(|source| source.short)
1873 .unwrap_or_else(|| path_leaf(Path::new(&self.bundle_id)))
1874 }
1875
1876 fn bundle_source_identity(&self, config: &Config) -> Option<ProjectSourceIdentity> {
1879 let bundle = self.project_bundle(config)?;
1880 let sources = bundle
1881 .repositories
1882 .iter()
1883 .map(repository_source_identity)
1884 .collect::<Option<Vec<_>>>()?;
1885 ProjectSourceIdentity::bundle(sources)
1886 }
1887
1888 pub fn project_bundle<'a>(
1890 &'a self,
1891 config: &'a Config,
1892 ) -> Option<&'a crate::config::ProjectBundle> {
1893 self.project
1894 .as_ref()
1895 .map(|project| &project.bundle)
1896 .or_else(|| config.bundles.get(&self.bundle_id))
1897 }
1898
1899 pub fn compare_by_creation(&self, other: &Self) -> std::cmp::Ordering {
1903 self.creation_order_key().cmp(&other.creation_order_key())
1904 }
1905
1906 pub fn creation_order_key(&self) -> (bool, Option<i64>, &str) {
1908 let timestamp = created_at_seconds(&self.created_at);
1909 (timestamp.is_none(), timestamp, &self.id)
1910 }
1911
1912 fn validate(&self, map_id: &str) -> Result<()> {
1913 validate_id("session", &self.id)?;
1914 if self.id != map_id {
1915 bail!(
1916 "session map key {map_id:?} does not match record id {:?}",
1917 self.id
1918 );
1919 }
1920 if let Some(project) = &self.project {
1921 project.key()?;
1922 }
1923 validate_id("workspace", &self.workspace_id)?;
1924 validate_id("profile", &self.last_profile)?;
1925 validate_id("bundle", &self.bundle_id)?;
1926 if let Some(project_directory) = &self.project_directory
1927 && (!crate::target_path::is_absolute_on_host_or_target(project_directory)
1928 || project_directory
1929 .components()
1930 .any(|part| part == Component::ParentDir))
1931 {
1932 bail!("session {:?} has an unsafe project directory", self.id);
1933 }
1934 if let Some(managed_worktree) = &self.managed_worktree {
1935 managed_worktree.validate(&self.id, self.project_directory.as_deref())?;
1936 }
1937 validate_id("target template", &self.target_template_id)?;
1938 if let Some(allocation) = &self.resource_allocation {
1939 allocation.validate()?;
1940 }
1941 validate_additional_mounts(&self.additional_mounts)?;
1942 if self.title.trim().is_empty() {
1943 bail!("session {:?} has an empty title", self.id);
1944 }
1945 if self
1946 .acp_session_title
1947 .as_ref()
1948 .is_some_and(|title| title.trim().is_empty())
1949 || self
1950 .session_title_override
1951 .as_ref()
1952 .is_some_and(|title| title.trim().is_empty())
1953 {
1954 bail!("session {:?} has an empty display title", self.id);
1955 }
1956 if self.created_at.trim().is_empty() || self.updated_at.trim().is_empty() {
1957 bail!("session {:?} has an empty timestamp", self.id);
1958 }
1959 if let Some(target) = &self.target {
1960 target.validate(&self.id)?;
1961 }
1962 if let Some(checkpoint) = &self.checkpoint {
1963 checkpoint.validate()?;
1964 }
1965 Ok(())
1966 }
1967}
1968
1969fn repository_source_identity(repository: &ProjectRepository) -> Option<ProjectSourceIdentity> {
1970 repository
1971 .github
1972 .as_deref()
1973 .and_then(ProjectSourceIdentity::git_remote)
1974 .or_else(|| {
1975 repository
1976 .local
1977 .as_deref()
1978 .map(|path| ProjectSourceIdentity::path(path, None))
1979 })
1980}
1981
1982#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
1983pub struct ProjectSourceIdentity {
1984 pub key: String,
1985 pub short: String,
1986 pub full: String,
1987}
1988
1989impl ProjectSourceIdentity {
1990 pub fn bundle(mut sources: Vec<Self>) -> Option<Self> {
1992 if sources.is_empty() {
1993 return None;
1994 }
1995 sources.sort_by(|left, right| {
1996 left.key
1997 .cmp(&right.key)
1998 .then_with(|| left.full.cmp(&right.full))
1999 .then_with(|| left.short.cmp(&right.short))
2000 });
2001 sources.dedup_by(|left, right| left.key == right.key);
2002 if sources.len() == 1 {
2003 return sources.pop();
2004 }
2005 let keys = sources
2006 .iter()
2007 .map(|source| source.key.clone())
2008 .collect::<Vec<_>>();
2009 let key = serde_json::to_string(&keys).ok()?;
2010 Some(Self {
2011 key: format!("bundle:{key}"),
2012 short: sources
2013 .iter()
2014 .map(|source| source.short.as_str())
2015 .collect::<Vec<_>>()
2016 .join(" + "),
2017 full: sources
2018 .iter()
2019 .map(|source| source.full.as_str())
2020 .collect::<Vec<_>>()
2021 .join(" + "),
2022 })
2023 }
2024
2025 pub fn git_remote(source: &str) -> Option<Self> {
2028 let identity = crate::repository::RepositoryIdentity::from_remote(source)?;
2029 let full = crate::repository::RepositoryIdentity::remote_label(source)?;
2030 Some(Self {
2031 key: identity.key(),
2032 short: full.rsplit(['/', ':']).next()?.to_owned(),
2033 full,
2034 })
2035 }
2036
2037 pub fn path(path: &Path, remote: Option<&str>) -> Self {
2040 let normalized = path.components().collect::<PathBuf>();
2041 let path_text = crate::target_path::text(&normalized);
2042 let full = remote.map_or_else(|| path_text.clone(), |host| format!("{host}:{path_text}"));
2043 let key = remote.map_or_else(
2044 || format!("path:{path_text}"),
2045 |host| format!("path:{}:{path_text}", host.to_lowercase()),
2046 );
2047 Self {
2048 key,
2049 short: path_leaf(path),
2050 full,
2051 }
2052 }
2053}
2054
2055fn path_leaf(path: &Path) -> String {
2057 path.file_name()
2058 .unwrap_or(path.as_os_str())
2059 .to_string_lossy()
2060 .into_owned()
2061}
2062
2063fn created_at_seconds(timestamp: &str) -> Option<i64> {
2064 chrono::DateTime::parse_from_rfc3339(timestamp)
2065 .ok()
2066 .map(|timestamp| timestamp.timestamp())
2067}
2068
2069#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2070#[serde(deny_unknown_fields)]
2071pub struct State {
2072 #[serde(default)]
2073 pub last_subagent_policy: crate::subagent::SubagentPolicy,
2074 pub version: u32,
2075 #[serde(default, skip_serializing_if = "SnapshotMap::is_empty")]
2076 pub sessions: SnapshotMap<String, SessionRecord>,
2077 #[serde(default, skip_serializing_if = "SnapshotMap::is_empty")]
2080 pub subagents: SnapshotMap<String, SubagentRecord>,
2081 #[serde(default, skip_serializing_if = "SnapshotMap::is_empty")]
2083 pub mount_history: SnapshotMap<String, Vec<PathBuf>>,
2084 #[serde(default, skip_serializing_if = "SnapshotMap::is_empty")]
2086 pub container_sizes: SnapshotMap<String, HostContainerSize>,
2087}
2088
2089impl Default for State {
2090 fn default() -> Self {
2091 Self {
2092 version: STATE_VERSION,
2093 last_subagent_policy: Default::default(),
2094 sessions: SnapshotMap::new(),
2095 subagents: SnapshotMap::new(),
2096 mount_history: SnapshotMap::new(),
2097 container_sizes: SnapshotMap::new(),
2098 }
2099 }
2100}
2101
2102#[derive(Debug, Clone, PartialEq, Eq)]
2109pub enum Checkout<'a> {
2110 Attached { path: &'a Path },
2112 ManagedWorktree {
2119 worktree: &'a ManagedWorktree,
2120 project_directory: Option<&'a Path>,
2121 },
2122 ManagedWorkspace,
2125 Borrowed {
2127 owner: &'a SessionRecord,
2128 checkout: Box<Checkout<'a>>,
2129 },
2130}
2131
2132fn derive_record_checkout(session: &SessionRecord) -> Checkout<'_> {
2134 if let Some(worktree) = &session.managed_worktree {
2135 return Checkout::ManagedWorktree {
2136 worktree,
2137 project_directory: session.project_directory.as_deref(),
2138 };
2139 }
2140 if let Some(path) = session.project_directory.as_deref() {
2141 return Checkout::Attached { path };
2142 }
2143 Checkout::ManagedWorkspace
2144}
2145
2146impl<'a> Checkout<'a> {
2147 #[must_use]
2150 pub fn managed_worktree(&self) -> Option<&'a ManagedWorktree> {
2151 match self {
2152 Self::ManagedWorktree { worktree, .. } => Some(*worktree),
2153 Self::Attached { .. } | Self::ManagedWorkspace | Self::Borrowed { .. } => None,
2154 }
2155 }
2156
2157 #[must_use]
2161 pub fn effective(&self) -> Checkout<'a> {
2162 match self {
2163 Self::Borrowed { checkout, .. } => checkout.effective(),
2164 checkout => checkout.clone(),
2165 }
2166 }
2167
2168 #[must_use]
2171 pub fn project_directory(&self) -> Option<&'a Path> {
2172 match self {
2173 Self::Attached { path } => Some(*path),
2174 Self::ManagedWorktree {
2175 project_directory, ..
2176 } => *project_directory,
2177 Self::ManagedWorkspace => None,
2178 Self::Borrowed { checkout, .. } => checkout.project_directory(),
2179 }
2180 }
2181}
2182
2183pub fn session_is_live(record: &SessionRecord, in_operation: bool, parent_live: bool) -> bool {
2191 record.state != SessionState::Stopped || in_operation || parent_live
2192}
2193
2194pub fn live_session_ids(
2198 sessions: &SnapshotMap<String, SessionRecord>,
2199 subagents: &SnapshotMap<String, SubagentRecord>,
2200 operations: &BTreeSet<String>,
2201) -> BTreeSet<String> {
2202 let mut live = sessions
2203 .iter()
2204 .filter(|(id, record)| session_is_live(record, operations.contains(*id), false))
2205 .map(|(id, _)| id.clone())
2206 .collect::<BTreeSet<_>>();
2207 loop {
2208 let joined = subagents
2209 .iter()
2210 .filter(|(child, relation)| {
2211 !live.contains(*child)
2212 && sessions.contains_key(*child)
2213 && live.contains(&relation.parent_session_id)
2214 })
2215 .map(|(child, _)| child.clone())
2216 .collect::<Vec<_>>();
2217 if joined.is_empty() {
2218 return live;
2219 }
2220 live.extend(joined);
2221 }
2222}
2223
2224impl State {
2225 pub fn checkout(&self, session_id: &str) -> Result<Checkout<'_>> {
2241 let session = self
2242 .sessions
2243 .get(session_id)
2244 .with_context(|| format!("unknown session {session_id}"))?;
2245 self.checkout_for_record(session_id, session)
2246 }
2247
2248 pub fn checkout_for_record<'a>(
2251 &'a self,
2252 session_id: &str,
2253 session: &'a SessionRecord,
2254 ) -> Result<Checkout<'a>> {
2255 self.checkout_for_record_inner(session_id, session, &mut BTreeSet::new())
2256 }
2257
2258 fn checkout_for_record_inner<'a>(
2259 &'a self,
2260 session_id: &str,
2261 session: &'a SessionRecord,
2262 visited: &mut BTreeSet<String>,
2263 ) -> Result<Checkout<'a>> {
2264 if !visited.insert(session_id.to_owned()) {
2265 bail!("sub-agent checkout ownership contains a cycle at {session_id}");
2266 }
2267 if let Some(relation) = self.subagents.get(session_id) {
2268 let Some(owner) = self.sessions.get(&relation.parent_session_id) else {
2269 return Ok(session.checkout());
2270 };
2271 return Ok(Checkout::Borrowed {
2272 owner,
2273 checkout: Box::new(self.checkout_for_record_inner(&owner.id, owner, visited)?),
2274 });
2275 }
2276 Ok(session.checkout())
2277 }
2278
2279 #[must_use]
2284 pub fn session_notice_name(&self, session_id: &str) -> String {
2285 match self.sessions.get(session_id) {
2286 Some(session) if session.listed_title() != session.id => {
2287 session.listed_title().to_owned()
2288 }
2289 _ => short_id(session_id).to_owned(),
2290 }
2291 }
2292
2293 #[must_use]
2302 pub fn project_identity_session<'a>(&'a self, session: &'a SessionRecord) -> &'a SessionRecord {
2303 self.subagents
2304 .get(&session.id)
2305 .and_then(|record| self.sessions.get(&record.parent_session_id))
2306 .unwrap_or(session)
2307 }
2308
2309 #[must_use]
2316 pub fn is_subagent_session(&self, id: &str) -> bool {
2317 self.subagents.contains_key(id) || crate::native_agent::is_view_id(id)
2318 }
2319
2320 pub fn validate(&self) -> Result<()> {
2321 if self.version != STATE_VERSION {
2322 bail!(
2323 "unsupported Mjolnir state version {}; expected {STATE_VERSION}",
2324 self.version
2325 );
2326 }
2327 for (id, session) in &self.sessions {
2328 session.validate(id)?;
2329 }
2330 for child_id in self.subagents.keys() {
2331 self.validate_subagent(child_id)?;
2332 }
2333 for (host, sources) in &self.mount_history {
2334 if host.trim().is_empty() {
2335 bail!("mount history contains an empty host key");
2336 }
2337 if sources
2338 .iter()
2339 .any(|source| !crate::target_path::is_absolute_on_host_or_target(source))
2340 {
2341 bail!("mount history for {host:?} contains a non-absolute source path");
2342 }
2343 }
2344 for (host, size) in &self.container_sizes {
2345 if host.trim().is_empty() {
2346 bail!("container size history contains an empty host key");
2347 }
2348 if size.cpus == 0 || size.memory_bytes == 0 {
2349 bail!("container size history for {host:?} contains a zero value");
2350 }
2351 if size.cpus > i64::MAX as u64 || size.memory_bytes > i64::MAX as u64 {
2352 bail!("container size history for {host:?} exceeds SQLite integer range");
2353 }
2354 }
2355 Ok(())
2356 }
2357
2358 pub fn validate_subagent(&self, child_id: &str) -> Result<()> {
2360 let Some(subagent) = self.subagents.get(child_id) else {
2361 return Ok(());
2362 };
2363 if child_id != subagent.child_session_id {
2364 bail!("sub-agent key {child_id:?} does not match its child session id");
2365 }
2366 if child_id == subagent.parent_session_id {
2367 bail!("sub-agent {child_id:?} cannot be its own parent");
2368 }
2369 if !self.sessions.contains_key(child_id) {
2370 bail!("sub-agent {child_id:?} has no child session");
2371 }
2372 if !self.sessions.contains_key(&subagent.parent_session_id) {
2373 bail!(
2374 "sub-agent {child_id:?} has unknown parent {:?}",
2375 subagent.parent_session_id
2376 );
2377 }
2378 if self.subagents.contains_key(&subagent.parent_session_id) {
2379 bail!("sub-agent {child_id:?} cannot belong to another sub-agent");
2380 }
2381 if subagent.task_name.trim().is_empty()
2382 || subagent.profile_id.trim().is_empty()
2383 || subagent.request_key.trim().is_empty()
2384 {
2385 bail!("sub-agent {child_id:?} has incomplete relationship metadata");
2386 }
2387 Ok(())
2388 }
2389
2390 pub fn remember_mount_sources(&mut self, host: &str, mounts: &[AdditionalMount]) {
2391 if mounts.is_empty() {
2392 return;
2393 }
2394 let sources = self
2395 .mount_history
2396 .entry(host.to_owned())
2397 .or_insert_with(Vec::new);
2398 for mount in mounts.iter().rev() {
2399 sources.retain(|source| source != &mount.source);
2400 sources.insert(0, mount.source.clone());
2401 }
2402 sources.truncate(20);
2403 }
2404
2405 pub fn remember_container_size(&mut self, host: &str, size: HostContainerSize) {
2406 self.container_sizes.insert(host.to_owned(), size);
2407 }
2408
2409 pub fn project_directories(&self, host: &str) -> &[PathBuf] {
2410 self.mount_history
2411 .get(&project_history_key(host))
2412 .map(Vec::as_slice)
2413 .unwrap_or_default()
2414 }
2415
2416 pub fn remember_project_directory(&mut self, host: &str, directory: &Path) {
2417 let key = project_history_key(host);
2418 let directories = self.mount_history.entry(key).or_insert_with(Vec::new);
2419 directories.retain(|existing| existing != directory);
2420 directories.insert(0, directory.to_path_buf());
2421 directories.truncate(20);
2422 }
2423
2424 pub fn destroy_stopped_session(&mut self, session_id: &str) -> Result<SessionRecord> {
2425 let session = self
2426 .sessions
2427 .get(session_id)
2428 .with_context(|| format!("unknown session {session_id}"))?;
2429 if session.state.is_active() {
2430 bail!("refusing to destroy active session {session_id}");
2431 }
2432 Ok(self
2433 .sessions
2434 .remove(session_id)
2435 .expect("session checked above"))
2436 }
2437
2438 pub fn destroy_session_force(&mut self, session_id: &str) -> Result<SessionRecord> {
2444 self.sessions
2445 .get(session_id)
2446 .with_context(|| format!("unknown session {session_id}"))?;
2447 Ok(self
2448 .sessions
2449 .remove(session_id)
2450 .expect("session checked above"))
2451 }
2452
2453 pub fn bundle_users(&self, bundle_id: &str) -> Vec<&SessionRecord> {
2458 self.sessions
2459 .values()
2460 .filter(|session| {
2461 session.bundle_id == bundle_id
2462 && self
2463 .checkout(&session.id)
2464 .is_ok_and(|checkout| checkout.project_directory().is_none())
2465 && session.state != SessionState::DestroyedWithDataLoss
2466 })
2467 .collect()
2468 }
2469
2470 pub fn bundle_removal_refusal(&self, bundle_id: &str) -> Option<String> {
2473 let users = self.bundle_users(bundle_id);
2474 if users.is_empty() {
2475 return None;
2476 }
2477 let mut names = users
2478 .iter()
2479 .take(3)
2480 .map(|session| format!("{:?}", session.listed_title()))
2481 .collect::<Vec<_>>();
2482 if users.len() > 3 {
2483 names.push(format!("{} more", users.len() - 3));
2484 }
2485 Some(format!(
2486 "Project {bundle_id:?} is used by {}: {}. Destroy those sessions before removing it.",
2487 if users.len() == 1 {
2488 "a session"
2489 } else {
2490 "sessions"
2491 },
2492 names.join(", ")
2493 ))
2494 }
2495
2496 pub fn validate_setup_update(&self, before: &Config, after: &Config) -> Result<()> {
2499 for session in self
2500 .sessions
2501 .values()
2502 .filter(|session| session.state.is_active())
2503 {
2504 let protected = if let Some(profile) = before.profiles.get(&session.last_profile) {
2505 let mut comparable = profile.clone();
2506 if let Some(updated) = after.profiles.get(&session.last_profile) {
2507 comparable.enabled = updated.enabled;
2508 comparable.subagents = updated.subagents.clone();
2509 }
2510 profile.kind == session.harness_kind
2512 && after.profiles.get(&session.last_profile) != Some(&comparable)
2513 } else {
2514 false
2515 };
2516 let bundle_changed = self
2517 .checkout(&session.id)
2518 .is_ok_and(|checkout| checkout.project_directory().is_none())
2519 && before
2520 .bundles
2521 .get(&session.bundle_id)
2522 .is_some_and(|bundle| after.bundles.get(&session.bundle_id) != Some(bundle));
2523 let target_changed =
2527 before
2528 .targets
2529 .get(&session.target_template_id)
2530 .is_some_and(|target| {
2531 after
2532 .targets
2533 .get(&session.target_template_id)
2534 .map(TargetTemplate::without_launch_only_settings)
2535 != Some(target.without_launch_only_settings())
2536 });
2537 if protected || bundle_changed || target_changed {
2538 let mut used = Vec::new();
2542 if protected {
2543 used.push(format!("agent profile {:?}", session.last_profile));
2544 }
2545 if bundle_changed {
2546 used.push(format!("project {:?}", session.project_name(before)));
2547 }
2548 if target_changed {
2549 used.push(format!("runtime {:?}", session.target_template_id));
2550 }
2551 let used = match used.as_slice() {
2552 [only] => only.clone(),
2553 [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
2554 [] => unreachable!("something changed"),
2555 };
2556 let title = session.display_title();
2557 let named = if title == session.id {
2558 format!(
2559 "a running session in project {:?}",
2560 session.project_name(before)
2561 )
2562 } else {
2563 format!("the running session {title:?}")
2564 };
2565 bail!(
2566 "Setup would change the {used} that {named} uses. Save the new settings under a new name, or stop the session first."
2567 );
2568 }
2569 }
2570 Ok(())
2571 }
2572
2573 pub fn validate_against_config(&self, config: &Config) -> Result<()> {
2575 self.validate()?;
2576 config.validate()?;
2577 for session in self.sessions.values() {
2578 session.validate_configuration(config)?;
2579 }
2580 Ok(())
2581 }
2582}
2583
2584fn project_history_key(host: &str) -> String {
2585 format!("project:{host}")
2586}
2587
2588pub fn new_session_id() -> Result<String> {
2590 let mut random = [0u8; 16];
2591 getrandom::fill(&mut random)
2592 .map_err(|error| anyhow::anyhow!("generate Mjolnir session id: {error}"))?;
2593 Ok(crate::hex::lower_hex(random))
2594}
2595
2596pub fn harness_session_title(events: &[SequencedEvent]) -> Option<String> {
2598 events.iter().rev().find_map(|event| {
2599 let WorkerEvent::Adapter { payload, .. } = &event.event else {
2600 return None;
2601 };
2602 let crate::acp::RuntimeEvent::SessionUpdate { update } =
2603 serde_json::from_value(payload.clone()).ok()?
2604 else {
2605 return None;
2606 };
2607 let kind = update
2608 .get("sessionUpdate")
2609 .and_then(serde_json::Value::as_str)?;
2610 let title = match kind {
2611 "session_info_update" | "session_title" => {
2612 update.get("title").and_then(serde_json::Value::as_str)
2613 }
2614 _ => None,
2615 }?;
2616 normalize_session_title(title)
2617 })
2618}
2619
2620pub fn default_session_title(
2625 project_directory: Option<&Path>,
2626 bundle_id: &str,
2627 profile_id: &str,
2628) -> String {
2629 let project = project_directory.and_then(Path::file_name).map_or_else(
2630 || bundle_id.to_owned(),
2631 |name| name.to_string_lossy().into_owned(),
2632 );
2633 format!("{project} via {profile_id}")
2634}
2635
2636pub const MAX_SESSION_TITLE_CHARS: usize = 256;
2637
2638pub fn normalize_session_title(title: &str) -> Option<String> {
2640 let normalized = crate::relay::strip_hidden_prompt_context(title)
2641 .split_whitespace()
2642 .collect::<Vec<_>>()
2643 .join(" ");
2644 (!normalized.is_empty()).then(|| truncate_session_title(normalized, MAX_SESSION_TITLE_CHARS))
2645}
2646
2647fn truncate_session_title(title: String, maximum_chars: usize) -> String {
2648 if title.chars().count() <= maximum_chars {
2649 return title;
2650 }
2651
2652 let mut truncated = title.chars().take(maximum_chars - 1).collect::<String>();
2653 if let Some(boundary) = truncated.rfind(char::is_whitespace) {
2654 truncated.truncate(boundary);
2655 }
2656 truncated.push('…');
2657 truncated
2658}
2659
2660pub fn provisional_session_title(prompt: &str) -> Option<String> {
2666 const MAX_TITLE_CHARS: usize = 64;
2667
2668 let normalized = normalize_session_title(prompt)?;
2669 Some(truncate_session_title(normalized, MAX_TITLE_CHARS))
2670}
2671
2672pub fn short_id(id: &str) -> &str {
2673 id.get(..8).unwrap_or(id)
2674}
2675
2676#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
2677pub struct RecoveryCandidate {
2678 pub session_id: String,
2679 pub target_template_id: String,
2680 pub locator: TargetLocator,
2681 pub ownership: Option<crate::worker_launch::WorkerOwnership>,
2682 #[serde(default)]
2685 pub instance_id: Option<String>,
2686 #[serde(default, skip_serializing_if = "Option::is_none")]
2691 pub tracked_session: Option<SessionState>,
2692}
2693
2694#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
2695pub struct RecoveryScan {
2696 pub candidates: Vec<RecoveryCandidate>,
2697 pub warnings: Vec<String>,
2698 #[serde(default)]
2700 pub instance_id: String,
2701 #[serde(default)]
2704 pub hidden_other_instances: usize,
2705}
2706
2707#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2708#[serde(deny_unknown_fields)]
2709pub struct ResumeRepositorySourceReceipt {
2710 pub session_id: String,
2711 pub bundle_id: String,
2712 pub checkpoint_sha256: String,
2713 pub repositories: Vec<crate::config::ProjectRepository>,
2714}
2715
2716#[cfg(test)]
2717mod tests;