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 "cancelled" | "canceled" => PromptCompletion::Cancelled,
297 "quotalimit" => PromptCompletion::QuotaLimit,
298 _ => PromptCompletion::Error,
299 }
300}
301
302#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
304#[serde(deny_unknown_fields)]
305pub struct MaterializedTurnOutcome {
306 #[serde(default, skip_serializing_if = "Option::is_none")]
307 pub diagnostic: Option<crate::diagnostic::TurnDiagnostic>,
308
309 #[serde(default, skip_serializing_if = "Option::is_none")]
310 pub usage: Option<crate::usage::TokenUsage>,
311 pub command_id: String,
312 #[serde(default, skip_serializing_if = "Option::is_none")]
313 pub accepted_ordinal: Option<u64>,
314 #[serde(default, skip_serializing_if = "Option::is_none")]
315 pub turn_start_position: Option<u64>,
316 pub completed_ordinal: u64,
317 pub completed_at_ms: i64,
318 pub outcome: TurnOutcomeKind,
319}
320
321impl MaterializedTurnOutcome {
322 pub fn interruption_ordinal(&self) -> Option<u64> {
324 (self.turn_start_position.is_some()
325 && matches!(self.outcome, TurnOutcomeKind::Interrupted { .. }))
326 .then_some(self.completed_ordinal)
327 }
328}
329
330#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
332#[serde(deny_unknown_fields)]
333pub struct MaterializedSession {
334 pub session_id: String,
335 pub applied_event_ordinal: u64,
336 pub applied_event_digest: String,
337 pub last_activity_at_ms: Option<i64>,
340 pub execution: MaterializedExecutionState,
341 #[serde(default, skip_serializing_if = "Option::is_none")]
342 pub session_title: Option<String>,
343 #[serde(default, skip_serializing_if = "SessionConfiguration::is_empty")]
344 pub configuration: SessionConfiguration,
345 #[serde(default, skip_serializing_if = "Vec::is_empty")]
346 pub transcript: Vec<Arc<TranscriptItem>>,
349 #[serde(default, skip_serializing_if = "Vec::is_empty")]
350 pub queued_prompts: Vec<MaterializedQueuedPrompt>,
351 #[serde(default, skip_serializing_if = "Vec::is_empty")]
354 pub pending_elicitations: Vec<crate::elicitation::ElicitationRequest>,
355 #[serde(default, skip_serializing_if = "Option::is_none")]
357 pub active_turn: Option<MaterializedTurn>,
358 #[serde(default, skip_serializing_if = "Option::is_none")]
361 pub last_turn_outcome: Option<MaterializedTurnOutcome>,
362}
363
364#[derive(Debug, Clone, PartialEq, Eq)]
367pub struct MaterializedSessionSummary {
368 pub session_id: String,
369 pub applied_event_ordinal: u64,
370 pub last_activity_at_ms: Option<i64>,
371 pub execution: MaterializedExecutionState,
372 pub session_title: Option<String>,
373 pub last_agent_message: Option<String>,
374 pub last_user_message: Option<String>,
375 pub last_agent_message_follows_last_user: bool,
378 pub agent_message_latest_content_ordinals: Vec<u64>,
379 pub interruption_event_ordinals: Vec<u64>,
380}
381
382impl MaterializedSession {
383 pub fn empty(session_id: impl Into<String>) -> Self {
384 Self {
385 session_id: session_id.into(),
386 applied_event_ordinal: 0,
387 applied_event_digest: RELAY_EVENT_GENESIS_DIGEST.into(),
388 last_activity_at_ms: None,
389 execution: MaterializedExecutionState::Idle,
390 session_title: None,
391 configuration: SessionConfiguration::default(),
392 transcript: Vec::new(),
393 queued_prompts: Vec::new(),
394 pending_elicitations: Vec::new(),
395 active_turn: None,
396 last_turn_outcome: None,
397 }
398 }
399
400 pub fn last_activity_at_ms(&self) -> Option<i64> {
401 self.last_activity_at_ms
402 }
403
404 pub fn resolved_title(&self) -> Option<String> {
410 self.session_title
411 .as_deref()
412 .and_then(normalize_session_title)
413 .or_else(|| {
414 self.transcript.iter().find_map(|item| {
415 let TranscriptBody::User { content } = &item.body else {
416 return None;
417 };
418 provisional_session_title(&crate::transcript::materialized_content_text(
419 content,
420 ))
421 })
422 })
423 .or_else(|| {
424 self.queued_prompts
425 .iter()
426 .filter(|prompt| prompt.kind.is_prompt())
427 .find_map(|prompt| {
428 provisional_session_title(&crate::transcript::materialized_content_text(
429 &prompt.content,
430 ))
431 })
432 })
433 }
434
435 pub fn unread_agent_messages_after(&self, viewed_through_event_ordinal: u64) -> u64 {
436 self.transcript
437 .iter()
438 .filter(|item| {
439 item.latest_content_event_ordinal
440 .is_some_and(|ordinal| ordinal > viewed_through_event_ordinal)
441 && item.is_nonempty_agent_message()
442 })
443 .count() as u64
444 }
445
446 pub fn unread_interruptions_after(&self, viewed_through_event_ordinal: u64) -> u64 {
447 self.interruption_event_ordinals()
448 .into_iter()
449 .filter(|ordinal| *ordinal > viewed_through_event_ordinal)
450 .count() as u64
451 }
452
453 pub fn interruption_event_ordinals(&self) -> Vec<u64> {
454 let mut ordinals = self
455 .transcript
456 .iter()
457 .filter(|item| item.is_work_interruption())
458 .map(|item| item.position)
459 .collect::<Vec<_>>();
460 if let Some(ordinal) = self
461 .last_turn_outcome
462 .as_ref()
463 .and_then(MaterializedTurnOutcome::interruption_ordinal)
464 {
465 ordinals.push(ordinal);
466 }
467 ordinals.sort_unstable();
468 ordinals.dedup();
469 ordinals
470 }
471
472 pub fn validate(&self) -> Result<()> {
473 validate_id("session", &self.session_id)?;
474 validate_relay_event_frontier(
475 self.applied_event_ordinal,
476 &self.applied_event_digest,
477 "materialized session event frontier",
478 )?;
479 if self
480 .session_title
481 .as_ref()
482 .is_some_and(|title| title.trim().is_empty())
483 {
484 bail!("materialized session has an empty title");
485 }
486 let mut item_ids = BTreeSet::new();
487 for item in &self.transcript {
488 item.validate(self.applied_event_ordinal)?;
489 if !item_ids.insert(item.stable_id.as_str()) {
490 bail!(
491 "materialized transcript contains duplicate item {:?}",
492 item.stable_id
493 );
494 }
495 }
496 let mut command_ids = BTreeSet::new();
497 for prompt in &self.queued_prompts {
498 if prompt.command_id.trim().is_empty() {
499 bail!("materialized prompt queue has an empty command id");
500 }
501 if !command_ids.insert(prompt.command_id.as_str()) {
502 bail!(
503 "materialized prompt queue contains duplicate command {:?}",
504 prompt.command_id
505 );
506 }
507 if let QueuedCommandKind::SetConfig { key, value } = &prompt.kind
508 && (key.trim().is_empty() || value.trim().is_empty())
509 {
510 bail!(
511 "materialized queued configuration change {:?} is incomplete",
512 prompt.command_id
513 );
514 }
515 }
516 Ok(())
517 }
518}
519
520#[derive(Debug, Clone, PartialEq)]
524pub struct ManagedSessionSnapshot {
525 pub materialized: MaterializedSession,
526 pub window: ProjectionWindow,
529 pub operational: RelayOperationalState,
530 pub latest_credential_sync_signal: Option<CredentialSyncSignal>,
534 pub worker_build: Option<String>,
539 pub subagent_requests: Vec<crate::subagent::SubagentToolRequest>,
541 pub subagent_results: Vec<crate::subagent::SubagentToolResult>,
543}
544
545#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
557pub struct ProjectionWindow {
558 pub omitted_items: usize,
560 pub provisional_title: Option<String>,
562 pub latest_turn_start_position: Option<u64>,
566}
567
568impl ProjectionWindow {
569 pub fn trim(&mut self, session: &mut MaterializedSession, target: usize) {
572 let observed = Self::of(session);
573 if self.provisional_title.is_none() {
574 self.provisional_title = observed.provisional_title;
575 }
576 self.latest_turn_start_position = observed
577 .latest_turn_start_position
578 .or(self.latest_turn_start_position);
579 let mut boundary = session.transcript.len().saturating_sub(target.max(1));
580 for (index, item) in session.transcript.iter().enumerate() {
581 let mutable = match &item.body {
582 TranscriptBody::Agent { streaming, .. }
583 | TranscriptBody::Thought { streaming, .. } => *streaming,
584 TranscriptBody::Tool { call, .. } => matches!(
585 call.get("status").and_then(serde_json::Value::as_str),
586 Some("pending" | "in_progress")
587 ),
588 _ => false,
589 };
590 if mutable || Some(item.position) == self.latest_turn_start_position {
591 boundary = boundary.min(index);
592 }
593 }
594 let cut = session
595 .transcript
596 .iter()
597 .take(boundary + 1)
598 .rposition(|item| item.is_turn_start())
599 .unwrap_or(0);
600 if cut > 0 {
601 session.transcript.drain(..cut);
602 self.omitted_items += cut;
603 }
604 }
605
606 #[must_use]
608 pub fn of(session: &MaterializedSession) -> Self {
609 Self {
610 omitted_items: 0,
611 provisional_title: session.transcript.iter().find_map(|item| {
612 let TranscriptBody::User { content } = &item.body else {
613 return None;
614 };
615 provisional_session_title(&crate::transcript::materialized_content_text(content))
616 }),
617 latest_turn_start_position: session
618 .transcript
619 .iter()
620 .rev()
621 .find(|item| item.is_turn_start())
622 .map(|item| item.position),
623 }
624 }
625}
626
627impl ManagedSessionSnapshot {
628 #[must_use]
633 pub fn resolved_title(&self) -> Option<String> {
634 self.materialized
635 .session_title
636 .as_deref()
637 .and_then(normalize_session_title)
638 .or_else(|| self.window.provisional_title.clone())
639 .or_else(|| {
640 self.materialized
641 .queued_prompts
642 .iter()
643 .filter(|prompt| prompt.kind.is_prompt())
644 .find_map(|prompt| {
645 provisional_session_title(&crate::transcript::materialized_content_text(
646 &prompt.content,
647 ))
648 })
649 })
650 }
651
652 #[must_use]
657 pub fn latest_completed_turn_ordinal(&self) -> Option<u64> {
658 if self.materialized.execution != MaterializedExecutionState::Idle {
659 return None;
660 }
661 self.window.latest_turn_start_position
662 }
663}
664
665#[derive(Debug, Clone)]
667pub struct RecoveryObservation {
668 pub session: SessionRecord,
669 pub config: Config,
670 pub latest_completed_turn_ordinal: Option<u64>,
671 pub checkpoint_wait: Option<crate::activity::CheckpointWait>,
675}
676
677pub fn latest_completed_turn_ordinal(session: &MaterializedSession) -> Option<u64> {
682 if session.execution != MaterializedExecutionState::Idle {
683 return None;
684 }
685 session
686 .transcript
687 .iter()
688 .rev()
689 .find(|item| item.is_turn_start())
690 .map(|item| item.position)
691}
692
693pub fn validate_relay_event_digest(digest: &str, name: &str) -> Result<()> {
694 if digest.len() != 64
695 || !digest
696 .bytes()
697 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
698 {
699 bail!("{name} must be a lowercase SHA-256 digest");
700 }
701 Ok(())
702}
703
704pub fn validate_relay_event_frontier(ordinal: u64, digest: &str, name: &str) -> Result<()> {
705 validate_relay_event_digest(digest, name)?;
706 if (ordinal == 0) != (digest == RELAY_EVENT_GENESIS_DIGEST) {
707 bail!("{name} has inconsistent ordinal {ordinal} and digest {digest}");
708 }
709 Ok(())
710}
711
712fn is_false(value: &bool) -> bool {
713 !*value
714}
715
716impl SessionState {
717 pub const fn as_str(self) -> &'static str {
719 match self {
720 Self::Provisioning => "provisioning",
721 Self::StartupCleanup => "startup-cleanup",
722 Self::Running => "running",
723 Self::Disconnected => "disconnected",
724 Self::Checkpointing => "checkpointing",
725 Self::Closing => "closing",
726 Self::Destroying => "destroying",
727 Self::Stopped => "stopped",
728 Self::Parked => "parked",
729 Self::Lost => "lost",
730 Self::Error => "error",
731 Self::DestroyedWithDataLoss => "destroyed-with-data-loss",
732 }
733 }
734
735 pub fn from_stored(value: &str) -> Option<Self> {
738 Some(match value {
739 "provisioning" => Self::Provisioning,
740 "startup-cleanup" => Self::StartupCleanup,
741 "running" => Self::Running,
742 "disconnected" => Self::Disconnected,
743 "checkpointing" => Self::Checkpointing,
744 "closing" => Self::Closing,
745 "destroying" => Self::Destroying,
746 "stopped" | "archived" => Self::Stopped,
747 "parked" => Self::Parked,
748 "lost" => Self::Lost,
749 "error" => Self::Error,
750 "destroyed-with-data-loss" => Self::DestroyedWithDataLoss,
751 _ => return None,
752 })
753 }
754
755 pub const fn transition_kind(self) -> Option<SessionTransitionKind> {
758 match self {
759 Self::Provisioning => Some(SessionTransitionKind::Starting),
760 Self::StartupCleanup => Some(SessionTransitionKind::Stopping),
761 Self::Closing => Some(SessionTransitionKind::Suspending),
762 Self::Destroying => Some(SessionTransitionKind::Destroying),
763 _ => None,
764 }
765 }
766
767 pub const fn is_active(self) -> bool {
774 matches!(
775 self,
776 Self::Provisioning
777 | Self::StartupCleanup
778 | Self::Running
779 | Self::Disconnected
780 | Self::Checkpointing
781 | Self::Closing
782 | Self::Destroying
783 | Self::Parked
784 | Self::Error
785 )
786 }
787
788 pub const fn has_live_worker(self) -> bool {
792 matches!(
793 self,
794 Self::Provisioning
795 | Self::StartupCleanup
796 | Self::Running
797 | Self::Disconnected
798 | Self::Checkpointing
799 | Self::Closing
800 | Self::Destroying
801 )
802 }
803}
804
805#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
806#[serde(tag = "kind", rename_all = "kebab-case")]
807pub enum PodmanWorkspaceLocator {
808 #[default]
809 ContainerLayer,
810 Volume {
811 name: String,
812 },
813 HostPath {
814 path: PathBuf,
815 helper: Vec<String>,
816 resource: String,
817 },
818}
819
820#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
821#[serde(tag = "kind", rename_all = "kebab-case")]
822pub enum TargetLocator {
823 LocalBare {
824 worker_root: PathBuf,
825 },
826 LocalPodman {
827 container_id: String,
828 #[serde(default)]
829 workspace_storage: PodmanWorkspaceLocator,
830 #[serde(default, skip_serializing_if = "Option::is_none")]
834 borrowed_from: Option<String>,
835 },
836 LocalDocker {
837 container_id: String,
838 #[serde(default, skip_serializing_if = "Option::is_none")]
842 borrowed_from: Option<String>,
843 },
844 AppleContainer {
845 container_id: String,
846 #[serde(default, skip_serializing_if = "Option::is_none")]
850 borrowed_from: Option<String>,
851 },
852 AwsEc2 {
853 instance_id: String,
854 #[serde(default, skip_serializing_if = "Option::is_none")]
855 address: Option<String>,
856 },
857 SshBare {
858 host: String,
859 workspace: PathBuf,
860 #[serde(default, skip_serializing_if = "Option::is_none")]
861 worker_id: Option<String>,
862 },
863 SshPodman {
864 host: String,
865 container_id: String,
866 #[serde(default)]
867 workspace_storage: PodmanWorkspaceLocator,
868 #[serde(default, skip_serializing_if = "Option::is_none")]
872 borrowed_from: Option<String>,
873 },
874 SshDocker {
875 host: String,
876 container_id: String,
877 #[serde(default, skip_serializing_if = "Option::is_none")]
881 borrowed_from: Option<String>,
882 },
883}
884
885impl ManagedWorktreeTarget {
886 pub fn same_location(&self, other: &Self) -> bool {
894 match (self, other) {
895 (Self::Local, Self::Local) => true,
896 (
897 Self::Ssh {
898 destination,
899 ssh_args,
900 },
901 Self::Ssh {
902 destination: other_destination,
903 ssh_args: other_args,
904 },
905 ) => {
906 destination == other_destination
907 && ssh_location_option(ssh_args, 'p', "port")
908 == ssh_location_option(other_args, 'p', "port")
909 && ssh_location_option(ssh_args, 'l', "user")
910 == ssh_location_option(other_args, 'l', "user")
911 }
912 _ => false,
913 }
914 }
915}
916
917fn ssh_location_option(args: &[String], flag: char, option: &str) -> Option<String> {
921 let mut args = args.iter();
922 while let Some(argument) = args.next() {
923 let Some(rest) = argument.strip_prefix('-') else {
924 continue;
925 };
926 let mut chars = rest.chars();
927 let Some(name) = chars.next() else { continue };
928 if name != flag && name != 'o' {
929 continue;
930 }
931 let inline = chars.as_str();
932 let value = if inline.is_empty() {
933 args.next().cloned()
934 } else {
935 Some(inline.to_owned())
936 };
937 if name == flag {
938 return value;
939 }
940 if let Some(setting) = value {
941 let (key, found) = setting
942 .split_once(['=', ' ', '\t'])
943 .unwrap_or((setting.as_str(), ""));
944 if key.trim().eq_ignore_ascii_case(option) {
945 return Some(found.trim().to_owned());
946 }
947 }
948 }
949 None
950}
951
952#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
953#[serde(tag = "kind", rename_all = "kebab-case")]
954pub enum ManagedWorktreeTarget {
955 Local,
956 Ssh {
957 destination: String,
958 #[serde(default, skip_serializing_if = "Vec::is_empty")]
959 ssh_args: Vec<String>,
960 },
961}
962
963#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
965#[serde(deny_unknown_fields)]
966pub struct ManagedWorktreeOptions {
967 pub available: bool,
968 pub default_create: bool,
969}
970
971#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
972#[serde(deny_unknown_fields)]
973pub struct ManagedWorktree {
974 #[serde(default, skip_serializing_if = "ManagedCheckoutKind::is_worktree")]
976 pub kind: ManagedCheckoutKind,
977 pub source_project_directory: PathBuf,
978 pub source_repository: PathBuf,
979 pub worktree_root: PathBuf,
980 pub branch: String,
981 pub target: ManagedWorktreeTarget,
982 #[serde(default, skip_serializing_if = "Option::is_none")]
986 pub base_commit: Option<String>,
987}
988
989#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
990#[serde(rename_all = "snake_case")]
991pub enum ManagedCheckoutKind {
992 #[default]
993 Worktree,
994 Clone,
995}
996
997impl ManagedCheckoutKind {
998 fn is_worktree(&self) -> bool {
999 matches!(self, Self::Worktree)
1000 }
1001}
1002
1003impl ManagedWorktree {
1004 fn validate(&self, session_id: &str, project_directory: Option<&Path>) -> Result<()> {
1005 for (label, path) in [
1006 ("source project directory", &self.source_project_directory),
1007 ("source repository", &self.source_repository),
1008 ("worktree root", &self.worktree_root),
1009 ] {
1010 if !path.is_absolute() || path.components().any(|part| part == Component::ParentDir) {
1011 bail!("managed worktree {label} must be an absolute safe path");
1012 }
1013 }
1014 if !self
1015 .source_project_directory
1016 .starts_with(&self.source_repository)
1017 {
1018 bail!("managed worktree source directory is outside its repository");
1019 }
1020 let expected_root = self
1021 .source_repository
1022 .join(".mj")
1023 .join(match self.kind {
1024 ManagedCheckoutKind::Worktree => "worktrees",
1025 ManagedCheckoutKind::Clone => "clones",
1026 })
1027 .join(session_id);
1028 if self.worktree_root != expected_root {
1029 bail!("managed worktree root does not match the session-owned path");
1030 }
1031 if self.kind == ManagedCheckoutKind::Worktree && self.branch != format!("mj/{session_id}") {
1032 bail!("managed worktree branch does not match the session id");
1033 }
1034 if self.kind == ManagedCheckoutKind::Clone && self.branch.trim().is_empty() {
1035 bail!("managed clone has no starting branch");
1036 }
1037 let relative = self
1038 .source_project_directory
1039 .strip_prefix(&self.source_repository)
1040 .expect("source relationship checked above");
1041 if project_directory != Some(self.worktree_root.join(relative).as_path()) {
1042 bail!("session project directory does not match its managed worktree");
1043 }
1044 match &self.target {
1045 ManagedWorktreeTarget::Local => {}
1046 ManagedWorktreeTarget::Ssh { destination, .. } if destination.trim().is_empty() => {
1047 bail!("managed SSH worktree has an empty destination")
1048 }
1049 ManagedWorktreeTarget::Ssh { .. } => {}
1050 }
1051 Ok(())
1052 }
1053}
1054
1055#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1056#[serde(tag = "kind", rename_all = "kebab-case")]
1057pub enum SessionResourceAllocation {
1058 Container {
1059 cpus: u64,
1060 memory_bytes: u64,
1061 },
1062 AwsEc2 {
1063 instance_type: String,
1064 vcpus: u64,
1065 memory_bytes: u64,
1066 },
1067}
1068
1069#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1071#[serde(rename_all = "kebab-case")]
1072pub enum ResourceAllocationKind {
1073 #[default]
1074 Fixed,
1075 Container,
1076 AwsEc2,
1077}
1078
1079impl SessionResourceAllocation {
1080 pub fn validate(&self) -> Result<()> {
1081 match self {
1082 Self::Container { cpus, memory_bytes } if *cpus == 0 || *memory_bytes == 0 => {
1083 bail!("container resource allocation must have non-zero CPU and memory")
1084 }
1085 Self::AwsEc2 {
1086 instance_type,
1087 vcpus,
1088 memory_bytes,
1089 } if instance_type.trim().is_empty() || *vcpus == 0 || *memory_bytes == 0 => {
1090 bail!("EC2 resource allocation must have an instance type, CPU, and memory")
1091 }
1092 _ => Ok(()),
1093 }
1094 }
1095}
1096
1097pub fn allocation_cpus(allocation: &SessionResourceAllocation) -> u64 {
1099 match allocation {
1100 SessionResourceAllocation::Container { cpus, .. } => *cpus,
1101 SessionResourceAllocation::AwsEc2 { vcpus, .. } => *vcpus,
1102 }
1103}
1104
1105pub fn allocation_memory(allocation: &SessionResourceAllocation) -> u64 {
1107 match allocation {
1108 SessionResourceAllocation::Container { memory_bytes, .. }
1109 | SessionResourceAllocation::AwsEc2 { memory_bytes, .. } => *memory_bytes,
1110 }
1111}
1112
1113impl TargetLocator {
1114 pub const fn skills_scope(&self) -> crate::skills::SkillsScope {
1116 match self {
1117 Self::LocalBare { .. } => crate::skills::SkillsScope::Localhost,
1118 _ => crate::skills::SkillsScope::Isolated,
1119 }
1120 }
1121
1122 fn validate(&self, session_id: &str) -> Result<()> {
1123 match self {
1124 Self::LocalBare { worker_root } => {
1125 if !worker_root.is_absolute()
1126 || worker_root
1127 .components()
1128 .any(|part| part == Component::ParentDir)
1129 || !worker_root.ends_with(session_id)
1130 {
1131 bail!(
1132 "local bare worker root must be an absolute safe path ending in the session id"
1133 );
1134 }
1135 }
1136 Self::LocalPodman { container_id, .. }
1137 | Self::LocalDocker { container_id, .. }
1138 | Self::AppleContainer { container_id, .. }
1139 | Self::SshPodman { container_id, .. }
1140 | Self::SshDocker { container_id, .. }
1141 if container_id.trim().is_empty() =>
1142 {
1143 bail!("target locator has an empty container id")
1144 }
1145 Self::AwsEc2 { instance_id, .. } if instance_id.trim().is_empty() => {
1146 bail!("target locator has an empty AWS instance id")
1147 }
1148 Self::SshBare {
1149 host,
1150 workspace,
1151 worker_id,
1152 } => {
1153 if host.trim().is_empty() {
1154 bail!("bare SSH target locator has an empty host");
1155 }
1156 let unsafe_path = workspace.as_os_str().is_empty()
1157 || workspace
1158 .components()
1159 .any(|part| part == Component::ParentDir);
1160 match worker_id {
1161 Some(worker_id) => {
1164 if worker_id != session_id {
1165 bail!(
1166 "bare SSH target locator's worker identity does not match the session id"
1167 );
1168 }
1169 if unsafe_path {
1170 bail!("bare SSH target locator must have a safe workspace path");
1171 }
1172 }
1173 None => {
1174 if unsafe_path || !workspace.ends_with(session_id) {
1175 bail!(
1176 "bare SSH target locator must be a safe path ending in the session id"
1177 );
1178 }
1179 }
1180 }
1181 }
1182 Self::SshPodman { host, .. } if host.trim().is_empty() => {
1183 bail!("SSH Podman target locator has an empty host")
1184 }
1185 Self::SshDocker { host, .. } if host.trim().is_empty() => {
1186 bail!("SSH Docker target locator has an empty host")
1187 }
1188 _ => {}
1189 }
1190 Ok(())
1191 }
1192}
1193
1194#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1195#[serde(deny_unknown_fields)]
1196pub struct CheckpointMetadata {
1197 pub archive_path: PathBuf,
1198 pub sha256: String,
1200 pub created_at: String,
1201 pub event_frontier: u64,
1202}
1203
1204#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1206#[serde(rename_all = "snake_case")]
1207pub enum PublicationState {
1208 Published,
1209 Unpublished,
1210 Unknown,
1211}
1212
1213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1215pub struct PublicationAssessment {
1216 pub checkpoint_sha256: String,
1217 pub state: PublicationState,
1218 pub dirty: bool,
1219 pub stashed: bool,
1220 pub saved_commits: Vec<String>,
1221 pub destinations: Vec<String>,
1222 pub checked_at: String,
1223 pub reason: Option<String>,
1224}
1225
1226impl CheckpointMetadata {
1227 fn validate(&self) -> Result<()> {
1228 if self.archive_path.as_os_str().is_empty() {
1229 bail!("checkpoint archive path is empty");
1230 }
1231 if self.sha256.len() != 64
1232 || !self
1233 .sha256
1234 .bytes()
1235 .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
1236 {
1237 bail!("checkpoint SHA-256 must be 64 lowercase hexadecimal characters");
1238 }
1239 if self.created_at.trim().is_empty() {
1240 bail!("checkpoint timestamp is empty");
1241 }
1242 Ok(())
1243 }
1244}
1245
1246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1251#[serde(deny_unknown_fields)]
1252pub struct SessionBuildCache {
1253 pub host: String,
1256 pub directory: PathBuf,
1257 #[serde(default, skip_serializing_if = "Option::is_none")]
1260 pub max_size: Option<String>,
1261 #[serde(default, skip_serializing_if = "Option::is_none")]
1264 pub target_root: Option<PathBuf>,
1265}
1266
1267#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1271pub struct ArchiveSpacePreview {
1272 pub sessions: usize,
1274 pub bytes: u64,
1276 pub reclaimable_sessions: usize,
1279 pub reclaimable_bytes: u64,
1280}
1281
1282#[derive(Debug, Clone, PartialEq, Eq)]
1286pub struct BuildCachePreview {
1287 pub native_mbx: Option<String>,
1289 pub mbx_profile_file: Option<String>,
1291 pub mbx_profile_warning: Option<String>,
1293 pub mbx_manual_path_line: Option<String>,
1295 pub directory: Option<PathBuf>,
1297 pub max_total_size: Option<BuildCacheLimit>,
1299 pub user_managed: bool,
1301 pub application: BuildCacheApplication,
1302 pub budget_note: Option<String>,
1304 pub stats: Option<BuildCacheStats>,
1306 pub off_reason: Option<BuildCacheOff>,
1309}
1310
1311#[derive(Debug, Clone, PartialEq, Eq)]
1319pub struct BuildCacheStats {
1320 pub builds: u64,
1322 pub cached_compilations: u64,
1324 pub avoided_compiler_ns: u64,
1326 pub reflinked_bytes: u64,
1328}
1329
1330#[derive(Debug, Clone, PartialEq, Eq)]
1332pub enum BuildCacheOff {
1333 TurnedOff,
1335 Unavailable(String),
1338}
1339
1340impl std::fmt::Display for BuildCacheOff {
1341 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1342 match self {
1343 Self::TurnedOff => formatter.write_str("turned off for this machine"),
1344 Self::Unavailable(reason) => formatter.write_str(reason),
1345 }
1346 }
1347}
1348
1349#[derive(Debug, Clone, PartialEq, Eq)]
1351pub enum BuildCacheLimit {
1352 Size(String),
1354 HostConfiguration(Option<String>),
1357 MjDefault(String),
1359 MbxDefault(Option<String>),
1361}
1362
1363#[derive(Debug, Clone, Default, PartialEq, Eq)]
1364pub enum BuildCacheApplication {
1365 #[default]
1366 Pending,
1367 Applied,
1368 Failed(String),
1369}
1370
1371#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1372#[serde(deny_unknown_fields)]
1373pub struct SessionRecord {
1374 pub id: String,
1375 #[serde(default = "default_session_workspace_id")]
1380 pub workspace_id: String,
1381 pub title: String,
1382 pub harness_kind: HarnessKind,
1383 pub last_profile: String,
1384 pub bundle_id: String,
1385 #[serde(default, skip_serializing_if = "Option::is_none")]
1387 pub project: Option<crate::repository::ProjectBundleSnapshot>,
1388 #[serde(default, skip_serializing_if = "Option::is_none")]
1390 pub project_directory: Option<PathBuf>,
1391 #[serde(default, skip_serializing_if = "Option::is_none")]
1393 pub managed_worktree: Option<ManagedWorktree>,
1394 #[serde(default, skip_serializing_if = "Option::is_none")]
1396 pub create_managed_worktree: Option<bool>,
1397 #[serde(default, skip_serializing_if = "Option::is_none")]
1404 pub launch_base: Option<String>,
1405 #[serde(default, skip_serializing_if = "Option::is_none")]
1409 pub launch_branch: Option<String>,
1410 #[serde(default, skip_serializing_if = "Option::is_none")]
1414 pub checkout: Option<crate::remote_git::ExactCheckout>,
1415 #[serde(default, skip_serializing_if = "Option::is_none")]
1417 pub publication: Option<PublicationAssessment>,
1418 #[serde(
1420 default,
1421 alias = "mjolnir_subagents",
1422 deserialize_with = "crate::subagent::deserialize_optional_policy"
1423 )]
1424 pub subagents: Option<crate::subagent::SubagentPolicy>,
1425 #[serde(default, skip_serializing_if = "Option::is_none")]
1428 pub review: Option<crate::config::SessionReview>,
1429 pub target_template_id: String,
1430 #[serde(default, skip_serializing_if = "Option::is_none")]
1431 pub resource_allocation: Option<SessionResourceAllocation>,
1432 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1433 pub additional_mounts: Vec<AdditionalMount>,
1434 #[serde(default, skip_serializing_if = "Option::is_none")]
1437 pub container_cpus: Option<String>,
1438 #[serde(default, skip_serializing_if = "Option::is_none")]
1441 pub container_memory: Option<String>,
1442 #[serde(default, skip_serializing_if = "Option::is_none")]
1448 pub container_workspace: Option<PathBuf>,
1449 #[serde(default, skip_serializing_if = "Option::is_none")]
1453 pub build_cache: Option<SessionBuildCache>,
1454 pub state: SessionState,
1455 #[serde(default, skip_serializing_if = "is_false")]
1458 pub archived: bool,
1459 #[serde(default, skip_serializing_if = "Option::is_none")]
1460 pub target: Option<TargetLocator>,
1461 #[serde(default, skip_serializing_if = "Option::is_none")]
1463 pub target_runtime: Option<TargetRuntimeSettings>,
1464 #[serde(default, skip_serializing_if = "Option::is_none")]
1465 pub native_session_id: Option<String>,
1466 #[serde(default, skip_serializing_if = "Option::is_none")]
1467 pub acp_session_title: Option<String>,
1468 #[serde(default, skip_serializing_if = "Option::is_none")]
1469 pub session_title_override: Option<String>,
1470 pub created_at: String,
1471 pub updated_at: String,
1472 #[serde(default, alias = "detached_after_event_ordinal")]
1473 pub viewed_through_event_ordinal: u64,
1474 #[serde(default, skip_serializing_if = "String::is_empty")]
1477 pub draft_input: String,
1478 #[serde(default, skip_serializing_if = "Option::is_none")]
1486 pub last_error: Option<String>,
1487 #[serde(default, skip_serializing_if = "Option::is_none")]
1488 pub last_checkpoint_error: Option<String>,
1489 #[serde(default, skip_serializing_if = "Option::is_none")]
1490 pub checkpoint: Option<CheckpointMetadata>,
1491}
1492
1493#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1494#[serde(deny_unknown_fields)]
1495pub struct HostContainerSize {
1496 pub cpus: u64,
1497 pub memory_bytes: u64,
1498}
1499
1500pub const BASELINE_CONTAINER_CPUS: u64 = 8;
1501pub const BASELINE_CONTAINER_MEMORY_BYTES: u64 = 32 * 1024 * 1024 * 1024;
1502
1503pub fn clamp_container_size(
1506 size: HostContainerSize,
1507 limits: Option<HostContainerSize>,
1508) -> HostContainerSize {
1509 let Some(limits) = limits else {
1510 return HostContainerSize {
1511 cpus: size.cpus.max(1),
1512 memory_bytes: size.memory_bytes.max(1),
1513 };
1514 };
1515 HostContainerSize {
1516 cpus: size.cpus.min(limits.cpus.max(1)),
1517 memory_bytes: size.memory_bytes.min(limits.memory_bytes.max(1)),
1518 }
1519}
1520
1521pub fn default_container_size(
1524 remembered: Option<HostContainerSize>,
1525 limits: Option<HostContainerSize>,
1526) -> HostContainerSize {
1527 clamp_container_size(
1528 remembered.unwrap_or(HostContainerSize {
1529 cpus: BASELINE_CONTAINER_CPUS,
1530 memory_bytes: BASELINE_CONTAINER_MEMORY_BYTES,
1531 }),
1532 limits,
1533 )
1534}
1535
1536pub fn preferred_aws_allocation<'a>(
1539 options: &'a [SessionResourceAllocation],
1540 previous: Option<&SessionResourceAllocation>,
1541) -> Option<&'a SessionResourceAllocation> {
1542 if let Some(SessionResourceAllocation::AwsEc2 { instance_type, .. }) = previous
1543 && let Some(option) = options.iter().find(|option| {
1544 matches!(option, SessionResourceAllocation::AwsEc2 { instance_type: candidate, .. } if candidate == instance_type)
1545 })
1546 {
1547 return Some(option);
1548 }
1549 options
1550 .iter()
1551 .find(|option| allocation_cpus(option) == BASELINE_CONTAINER_CPUS)
1552 .or_else(|| options.first())
1553}
1554
1555fn default_session_workspace_id() -> String {
1556 crate::workspace::DEFAULT_WORKSPACE_ID.to_owned()
1557}
1558
1559pub const DESTRUCTION_FAILURE_PREFIX: &str = "the destruction did not finish";
1568
1569pub const CLOSE_FAILURE_PREFIX: &str = "the suspension did not finish";
1570
1571pub const MOVE_FAILURE_PREFIX: &str = "the move did not finish";
1572
1573pub fn is_public_lifecycle_error(error: &str) -> bool {
1575 error.starts_with(CLOSE_FAILURE_PREFIX)
1576 || error.starts_with(MOVE_FAILURE_PREFIX)
1577 || error.starts_with(DESTRUCTION_FAILURE_PREFIX)
1578 || error.starts_with("the close did not finish")
1579}
1580
1581#[must_use]
1594pub fn target_label(config: &Config, target_id: &str, project: Option<&Path>) -> String {
1595 if !matches!(
1596 config.targets.get(target_id),
1597 Some(TargetTemplate::LocalBare | TargetTemplate::SshBare { .. })
1598 ) {
1599 return target_id.to_owned();
1600 }
1601 project.and_then(Path::file_name).map_or_else(
1602 || target_id.to_owned(),
1603 |directory| format!("{target_id}/{}", directory.to_string_lossy()),
1604 )
1605}
1606
1607#[derive(Debug, Clone, Default, PartialEq, Eq)]
1609pub struct StartSelection {
1610 pub at: Option<String>,
1612 pub branch: Option<String>,
1614 pub base: Option<String>,
1616}
1617
1618impl SessionRecord {
1619 #[must_use]
1623 pub fn checkout(&self) -> Checkout<'_> {
1624 derive_record_checkout(self)
1625 }
1626
1627 pub fn start_selection(&self) -> StartSelection {
1631 let at = self
1632 .checkout
1633 .as_ref()
1634 .map(|checkout| checkout.commit.clone());
1635 StartSelection {
1636 branch: self
1637 .checkout
1638 .as_ref()
1639 .and_then(|checkout| checkout.branch.clone())
1640 .or_else(|| self.launch_branch.clone()),
1641 base: self.launch_base.clone().or_else(|| at.clone()),
1642 at,
1643 }
1644 }
1645
1646 pub fn publication_state(&self) -> Option<PublicationState> {
1649 let independent_clone = match self.checkout().effective() {
1650 Checkout::ManagedWorktree { worktree, .. } => {
1651 worktree.kind == ManagedCheckoutKind::Clone
1652 }
1653 Checkout::ManagedWorkspace => true,
1654 Checkout::Attached { .. } | Checkout::Borrowed { .. } => false,
1655 };
1656 if !independent_clone {
1657 return None;
1658 }
1659 if self.state.is_active() {
1660 return Some(PublicationState::Unknown);
1661 }
1662 Some(
1663 self.checkpoint
1664 .as_ref()
1665 .zip(self.publication.as_ref())
1666 .filter(|(checkpoint, assessment)| {
1667 assessment.checkpoint_sha256 == checkpoint.sha256
1668 })
1669 .map_or(PublicationState::Unknown, |(_, assessment)| {
1670 if assessment.dirty || assessment.stashed {
1671 PublicationState::Unpublished
1672 } else {
1673 assessment.state
1674 }
1675 }),
1676 )
1677 }
1678
1679 pub fn target_runtime_settings<'a>(
1684 &'a self,
1685 config: &Config,
1686 ) -> Result<std::borrow::Cow<'a, TargetRuntimeSettings>> {
1687 if let Some(runtime) = &self.target_runtime {
1688 if let Some(refreshed) =
1691 config
1692 .targets
1693 .get(&self.target_template_id)
1694 .and_then(|template| {
1695 runtime.with_current_ssh_options(&TargetRuntimeSettings::from(template))
1696 })
1697 {
1698 return Ok(std::borrow::Cow::Owned(refreshed));
1699 }
1700 return Ok(std::borrow::Cow::Borrowed(runtime));
1701 }
1702 let template = config.targets.get(&self.target_template_id).ok_or_else(|| {
1703 crate::refusal::Refusal::precondition(format!(
1704 "Session {:?} has no recorded target access settings. Restore target {:?} in config.toml once, then retry.",
1705 self.id, self.target_template_id))
1706 })?;
1707 let runtime = TargetRuntimeSettings::from(template);
1708 if let Some(locator) = &self.target {
1709 crate::targets::TargetLocator::try_from(crate::targets::RecordedTarget {
1710 locator, runtime: Some(&runtime), session_id: &self.id,
1711 }).map_err(|error| crate::refusal::Refusal::precondition(format!(
1712 "Session {:?} cannot recover target {:?}: {error}. Restore its original target settings, then retry.", self.id, self.target_template_id)))?;
1713 }
1714 Ok(std::borrow::Cow::Owned(runtime))
1715 }
1716
1717 #[must_use]
1721 pub fn public_error(&self) -> Option<&str> {
1722 self.last_error
1723 .as_deref()
1724 .filter(|error| is_public_lifecycle_error(error))
1725 }
1726
1727 pub fn configuration_issue(&self, config: &Config) -> Option<String> {
1730 if !self.state.is_active() {
1731 return None;
1732 }
1733 let mut issues = Vec::new();
1734 match config.profiles.get(&self.last_profile) {
1735 None => issues.push(format!("missing profile {:?}", self.last_profile)),
1736 Some(profile) if profile.kind != self.harness_kind => issues.push(format!(
1737 "expects {:?}, but profile {:?} is {:?}",
1738 self.harness_kind, self.last_profile, profile.kind
1739 )),
1740 Some(_) => {}
1741 }
1742 if self.checkout().project_directory().is_none() && self.project_bundle(config).is_none() {
1743 issues.push(format!("missing bundle {:?}", self.bundle_id));
1744 }
1745 if self.target_runtime.is_none() && !config.targets.contains_key(&self.target_template_id) {
1746 issues.push(format!(
1747 "missing target template {:?}",
1748 self.target_template_id
1749 ));
1750 }
1751 (!issues.is_empty()).then(|| format!(
1752 "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.",
1753 self.id, issues.join("; ")
1754 ))
1755 }
1756
1757 pub fn validate_configuration(&self, config: &Config) -> Result<()> {
1758 if let Some(issue) = self.configuration_issue(config) {
1759 return Err(crate::refusal::Refusal::precondition(issue).into());
1760 }
1761 Ok(())
1762 }
1763
1764 pub fn display_title(&self) -> &str {
1766 self.session_title_override
1767 .as_deref()
1768 .or(self.acp_session_title.as_deref())
1769 .unwrap_or(&self.id)
1770 }
1771
1772 pub fn listed_title(&self) -> &str {
1777 let named = self.session_title_override.is_some() || self.acp_session_title.is_some();
1778 if !named && !self.title.trim().is_empty() {
1779 return &self.title;
1780 }
1781 self.display_title()
1782 }
1783
1784 pub fn project_name(&self, config: &Config) -> String {
1789 if let Some(project) = &self.project {
1790 return project.name();
1791 }
1792 match self.checkout().effective() {
1793 Checkout::ManagedWorktree { worktree, .. } => path_leaf(&worktree.source_repository),
1794 Checkout::Attached { path } => path_leaf(path),
1795 Checkout::ManagedWorkspace => self.bundle_source_name(config),
1796 Checkout::Borrowed { .. } => unreachable!("effective checkout resolves borrowing"),
1797 }
1798 }
1799
1800 pub fn project_target(&self, config: &Config, target_id: &str) -> String {
1804 let checkout = self.checkout();
1805 let project = match checkout.effective() {
1806 Checkout::ManagedWorktree { worktree, .. } => {
1807 Some(worktree.source_project_directory.as_path())
1808 }
1809 Checkout::Attached { path } => Some(path),
1810 Checkout::ManagedWorkspace => None,
1811 Checkout::Borrowed { .. } => unreachable!("effective checkout resolves borrowing"),
1812 };
1813 target_label(config, target_id, project)
1814 }
1815
1816 pub fn project_source(&self, config: &Config) -> ProjectSourceIdentity {
1821 if let Some(project) = &self.project {
1822 return ProjectSourceIdentity {
1823 key: project
1824 .source_key()
1825 .expect("accepted project has complete identities"),
1826 short: project.name(),
1827 full: project
1828 .identities
1829 .values()
1830 .map(crate::repository::RepositoryIdentity::key)
1831 .collect::<Vec<_>>()
1832 .join(" + "),
1833 };
1834 }
1835 match self.checkout().effective() {
1836 Checkout::ManagedWorktree { worktree, .. } => {
1837 ProjectSourceIdentity::path(&worktree.source_repository, None)
1838 }
1839 Checkout::Attached { path } => {
1840 let remote = match &self.target {
1841 Some(TargetLocator::SshBare { host, .. }) => Some(host.as_str()),
1842 _ => None,
1843 };
1844 ProjectSourceIdentity::path(path, remote)
1845 }
1846 Checkout::ManagedWorkspace => {
1847 self.bundle_source_identity(config)
1848 .unwrap_or_else(|| ProjectSourceIdentity {
1849 key: format!("bundle:{}", self.bundle_id),
1850 short: path_leaf(Path::new(&self.bundle_id)),
1851 full: self.bundle_id.clone(),
1852 })
1853 }
1854 Checkout::Borrowed { .. } => unreachable!("effective checkout resolves borrowing"),
1855 }
1856 }
1857
1858 fn bundle_source_name(&self, config: &Config) -> String {
1861 self.bundle_source_identity(config)
1862 .map(|source| source.short)
1863 .unwrap_or_else(|| path_leaf(Path::new(&self.bundle_id)))
1864 }
1865
1866 fn bundle_source_identity(&self, config: &Config) -> Option<ProjectSourceIdentity> {
1869 let bundle = self.project_bundle(config)?;
1870 let sources = bundle
1871 .repositories
1872 .iter()
1873 .map(repository_source_identity)
1874 .collect::<Option<Vec<_>>>()?;
1875 ProjectSourceIdentity::bundle(sources)
1876 }
1877
1878 pub fn project_bundle<'a>(
1880 &'a self,
1881 config: &'a Config,
1882 ) -> Option<&'a crate::config::ProjectBundle> {
1883 self.project
1884 .as_ref()
1885 .map(|project| &project.bundle)
1886 .or_else(|| config.bundles.get(&self.bundle_id))
1887 }
1888
1889 pub fn compare_by_creation(&self, other: &Self) -> std::cmp::Ordering {
1893 self.creation_order_key().cmp(&other.creation_order_key())
1894 }
1895
1896 pub fn creation_order_key(&self) -> (bool, Option<i64>, &str) {
1898 let timestamp = created_at_seconds(&self.created_at);
1899 (timestamp.is_none(), timestamp, &self.id)
1900 }
1901
1902 fn validate(&self, map_id: &str) -> Result<()> {
1903 validate_id("session", &self.id)?;
1904 if self.id != map_id {
1905 bail!(
1906 "session map key {map_id:?} does not match record id {:?}",
1907 self.id
1908 );
1909 }
1910 if let Some(project) = &self.project {
1911 project.key()?;
1912 }
1913 validate_id("workspace", &self.workspace_id)?;
1914 validate_id("profile", &self.last_profile)?;
1915 validate_id("bundle", &self.bundle_id)?;
1916 if let Some(project_directory) = &self.project_directory
1917 && (!project_directory.is_absolute()
1918 || project_directory
1919 .components()
1920 .any(|part| part == Component::ParentDir))
1921 {
1922 bail!("session {:?} has an unsafe project directory", self.id);
1923 }
1924 if let Some(managed_worktree) = &self.managed_worktree {
1925 managed_worktree.validate(&self.id, self.project_directory.as_deref())?;
1926 }
1927 validate_id("target template", &self.target_template_id)?;
1928 if let Some(allocation) = &self.resource_allocation {
1929 allocation.validate()?;
1930 }
1931 validate_additional_mounts(&self.additional_mounts)?;
1932 if self.title.trim().is_empty() {
1933 bail!("session {:?} has an empty title", self.id);
1934 }
1935 if self
1936 .acp_session_title
1937 .as_ref()
1938 .is_some_and(|title| title.trim().is_empty())
1939 || self
1940 .session_title_override
1941 .as_ref()
1942 .is_some_and(|title| title.trim().is_empty())
1943 {
1944 bail!("session {:?} has an empty display title", self.id);
1945 }
1946 if self.created_at.trim().is_empty() || self.updated_at.trim().is_empty() {
1947 bail!("session {:?} has an empty timestamp", self.id);
1948 }
1949 if let Some(target) = &self.target {
1950 target.validate(&self.id)?;
1951 }
1952 if let Some(checkpoint) = &self.checkpoint {
1953 checkpoint.validate()?;
1954 }
1955 Ok(())
1956 }
1957}
1958
1959fn repository_source_identity(repository: &ProjectRepository) -> Option<ProjectSourceIdentity> {
1960 repository
1961 .github
1962 .as_deref()
1963 .and_then(ProjectSourceIdentity::git_remote)
1964 .or_else(|| {
1965 repository
1966 .local
1967 .as_deref()
1968 .map(|path| ProjectSourceIdentity::path(path, None))
1969 })
1970}
1971
1972#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
1973pub struct ProjectSourceIdentity {
1974 pub key: String,
1975 pub short: String,
1976 pub full: String,
1977}
1978
1979impl ProjectSourceIdentity {
1980 pub fn bundle(mut sources: Vec<Self>) -> Option<Self> {
1982 if sources.is_empty() {
1983 return None;
1984 }
1985 sources.sort_by(|left, right| {
1986 left.key
1987 .cmp(&right.key)
1988 .then_with(|| left.full.cmp(&right.full))
1989 .then_with(|| left.short.cmp(&right.short))
1990 });
1991 sources.dedup_by(|left, right| left.key == right.key);
1992 if sources.len() == 1 {
1993 return sources.pop();
1994 }
1995 let keys = sources
1996 .iter()
1997 .map(|source| source.key.clone())
1998 .collect::<Vec<_>>();
1999 let key = serde_json::to_string(&keys).ok()?;
2000 Some(Self {
2001 key: format!("bundle:{key}"),
2002 short: sources
2003 .iter()
2004 .map(|source| source.short.as_str())
2005 .collect::<Vec<_>>()
2006 .join(" + "),
2007 full: sources
2008 .iter()
2009 .map(|source| source.full.as_str())
2010 .collect::<Vec<_>>()
2011 .join(" + "),
2012 })
2013 }
2014
2015 pub fn git_remote(source: &str) -> Option<Self> {
2018 let identity = crate::repository::RepositoryIdentity::from_remote(source)?;
2019 let full = crate::repository::RepositoryIdentity::remote_label(source)?;
2020 Some(Self {
2021 key: identity.key(),
2022 short: full.rsplit(['/', ':']).next()?.to_owned(),
2023 full,
2024 })
2025 }
2026
2027 pub fn path(path: &Path, remote: Option<&str>) -> Self {
2029 let normalized = path.components().collect::<PathBuf>();
2030 let path_text = normalized.to_string_lossy().into_owned();
2031 let full = remote.map_or_else(|| path_text.clone(), |host| format!("{host}:{path_text}"));
2032 let key = remote.map_or_else(
2033 || format!("path:{path_text}"),
2034 |host| format!("path:{}:{path_text}", host.to_lowercase()),
2035 );
2036 Self {
2037 key,
2038 short: path_leaf(path),
2039 full,
2040 }
2041 }
2042}
2043
2044fn path_leaf(path: &Path) -> String {
2046 path.file_name()
2047 .unwrap_or(path.as_os_str())
2048 .to_string_lossy()
2049 .into_owned()
2050}
2051
2052fn created_at_seconds(timestamp: &str) -> Option<i64> {
2053 chrono::DateTime::parse_from_rfc3339(timestamp)
2054 .ok()
2055 .map(|timestamp| timestamp.timestamp())
2056}
2057
2058#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2059#[serde(deny_unknown_fields)]
2060pub struct State {
2061 #[serde(default)]
2062 pub last_subagent_policy: crate::subagent::SubagentPolicy,
2063 pub version: u32,
2064 #[serde(default, skip_serializing_if = "SnapshotMap::is_empty")]
2065 pub sessions: SnapshotMap<String, SessionRecord>,
2066 #[serde(default, skip_serializing_if = "SnapshotMap::is_empty")]
2069 pub subagents: SnapshotMap<String, SubagentRecord>,
2070 #[serde(default, skip_serializing_if = "SnapshotMap::is_empty")]
2072 pub mount_history: SnapshotMap<String, Vec<PathBuf>>,
2073 #[serde(default, skip_serializing_if = "SnapshotMap::is_empty")]
2075 pub container_sizes: SnapshotMap<String, HostContainerSize>,
2076}
2077
2078impl Default for State {
2079 fn default() -> Self {
2080 Self {
2081 version: STATE_VERSION,
2082 last_subagent_policy: Default::default(),
2083 sessions: SnapshotMap::new(),
2084 subagents: SnapshotMap::new(),
2085 mount_history: SnapshotMap::new(),
2086 container_sizes: SnapshotMap::new(),
2087 }
2088 }
2089}
2090
2091#[derive(Debug, Clone, PartialEq, Eq)]
2098pub enum Checkout<'a> {
2099 Attached { path: &'a Path },
2101 ManagedWorktree {
2108 worktree: &'a ManagedWorktree,
2109 project_directory: Option<&'a Path>,
2110 },
2111 ManagedWorkspace,
2114 Borrowed {
2116 owner: &'a SessionRecord,
2117 checkout: Box<Checkout<'a>>,
2118 },
2119}
2120
2121fn derive_record_checkout(session: &SessionRecord) -> Checkout<'_> {
2123 if let Some(worktree) = &session.managed_worktree {
2124 return Checkout::ManagedWorktree {
2125 worktree,
2126 project_directory: session.project_directory.as_deref(),
2127 };
2128 }
2129 if let Some(path) = session.project_directory.as_deref() {
2130 return Checkout::Attached { path };
2131 }
2132 Checkout::ManagedWorkspace
2133}
2134
2135impl<'a> Checkout<'a> {
2136 #[must_use]
2139 pub fn managed_worktree(&self) -> Option<&'a ManagedWorktree> {
2140 match self {
2141 Self::ManagedWorktree { worktree, .. } => Some(*worktree),
2142 Self::Attached { .. } | Self::ManagedWorkspace | Self::Borrowed { .. } => None,
2143 }
2144 }
2145
2146 #[must_use]
2150 pub fn effective(&self) -> Checkout<'a> {
2151 match self {
2152 Self::Borrowed { checkout, .. } => checkout.effective(),
2153 checkout => checkout.clone(),
2154 }
2155 }
2156
2157 #[must_use]
2160 pub fn project_directory(&self) -> Option<&'a Path> {
2161 match self {
2162 Self::Attached { path } => Some(*path),
2163 Self::ManagedWorktree {
2164 project_directory, ..
2165 } => *project_directory,
2166 Self::ManagedWorkspace => None,
2167 Self::Borrowed { checkout, .. } => checkout.project_directory(),
2168 }
2169 }
2170}
2171
2172pub fn session_is_live(record: &SessionRecord, in_operation: bool, parent_live: bool) -> bool {
2180 record.state != SessionState::Stopped || in_operation || parent_live
2181}
2182
2183pub fn live_session_ids(
2187 sessions: &SnapshotMap<String, SessionRecord>,
2188 subagents: &SnapshotMap<String, SubagentRecord>,
2189 operations: &BTreeSet<String>,
2190) -> BTreeSet<String> {
2191 let mut live = sessions
2192 .iter()
2193 .filter(|(id, record)| session_is_live(record, operations.contains(*id), false))
2194 .map(|(id, _)| id.clone())
2195 .collect::<BTreeSet<_>>();
2196 loop {
2197 let joined = subagents
2198 .iter()
2199 .filter(|(child, relation)| {
2200 !live.contains(*child)
2201 && sessions.contains_key(*child)
2202 && live.contains(&relation.parent_session_id)
2203 })
2204 .map(|(child, _)| child.clone())
2205 .collect::<Vec<_>>();
2206 if joined.is_empty() {
2207 return live;
2208 }
2209 live.extend(joined);
2210 }
2211}
2212
2213impl State {
2214 pub fn checkout(&self, session_id: &str) -> Result<Checkout<'_>> {
2230 let session = self
2231 .sessions
2232 .get(session_id)
2233 .with_context(|| format!("unknown session {session_id}"))?;
2234 self.checkout_for_record(session_id, session)
2235 }
2236
2237 pub fn checkout_for_record<'a>(
2240 &'a self,
2241 session_id: &str,
2242 session: &'a SessionRecord,
2243 ) -> Result<Checkout<'a>> {
2244 self.checkout_for_record_inner(session_id, session, &mut BTreeSet::new())
2245 }
2246
2247 fn checkout_for_record_inner<'a>(
2248 &'a self,
2249 session_id: &str,
2250 session: &'a SessionRecord,
2251 visited: &mut BTreeSet<String>,
2252 ) -> Result<Checkout<'a>> {
2253 if !visited.insert(session_id.to_owned()) {
2254 bail!("sub-agent checkout ownership contains a cycle at {session_id}");
2255 }
2256 if let Some(relation) = self.subagents.get(session_id) {
2257 let Some(owner) = self.sessions.get(&relation.parent_session_id) else {
2258 return Ok(session.checkout());
2259 };
2260 return Ok(Checkout::Borrowed {
2261 owner,
2262 checkout: Box::new(self.checkout_for_record_inner(&owner.id, owner, visited)?),
2263 });
2264 }
2265 Ok(session.checkout())
2266 }
2267
2268 #[must_use]
2273 pub fn session_notice_name(&self, session_id: &str) -> String {
2274 match self.sessions.get(session_id) {
2275 Some(session) if session.listed_title() != session.id => {
2276 session.listed_title().to_owned()
2277 }
2278 _ => short_id(session_id).to_owned(),
2279 }
2280 }
2281
2282 #[must_use]
2291 pub fn project_identity_session<'a>(&'a self, session: &'a SessionRecord) -> &'a SessionRecord {
2292 self.subagents
2293 .get(&session.id)
2294 .and_then(|record| self.sessions.get(&record.parent_session_id))
2295 .unwrap_or(session)
2296 }
2297
2298 #[must_use]
2305 pub fn is_subagent_session(&self, id: &str) -> bool {
2306 self.subagents.contains_key(id) || crate::native_agent::is_view_id(id)
2307 }
2308
2309 pub fn validate(&self) -> Result<()> {
2310 if self.version != STATE_VERSION {
2311 bail!(
2312 "unsupported Mjolnir state version {}; expected {STATE_VERSION}",
2313 self.version
2314 );
2315 }
2316 for (id, session) in &self.sessions {
2317 session.validate(id)?;
2318 }
2319 for child_id in self.subagents.keys() {
2320 self.validate_subagent(child_id)?;
2321 }
2322 for (host, sources) in &self.mount_history {
2323 if host.trim().is_empty() {
2324 bail!("mount history contains an empty host key");
2325 }
2326 if sources.iter().any(|source| !source.is_absolute()) {
2327 bail!("mount history for {host:?} contains a non-absolute source path");
2328 }
2329 }
2330 for (host, size) in &self.container_sizes {
2331 if host.trim().is_empty() {
2332 bail!("container size history contains an empty host key");
2333 }
2334 if size.cpus == 0 || size.memory_bytes == 0 {
2335 bail!("container size history for {host:?} contains a zero value");
2336 }
2337 if size.cpus > i64::MAX as u64 || size.memory_bytes > i64::MAX as u64 {
2338 bail!("container size history for {host:?} exceeds SQLite integer range");
2339 }
2340 }
2341 Ok(())
2342 }
2343
2344 pub fn validate_subagent(&self, child_id: &str) -> Result<()> {
2346 let Some(subagent) = self.subagents.get(child_id) else {
2347 return Ok(());
2348 };
2349 if child_id != subagent.child_session_id {
2350 bail!("sub-agent key {child_id:?} does not match its child session id");
2351 }
2352 if child_id == subagent.parent_session_id {
2353 bail!("sub-agent {child_id:?} cannot be its own parent");
2354 }
2355 if !self.sessions.contains_key(child_id) {
2356 bail!("sub-agent {child_id:?} has no child session");
2357 }
2358 if !self.sessions.contains_key(&subagent.parent_session_id) {
2359 bail!(
2360 "sub-agent {child_id:?} has unknown parent {:?}",
2361 subagent.parent_session_id
2362 );
2363 }
2364 if self.subagents.contains_key(&subagent.parent_session_id) {
2365 bail!("sub-agent {child_id:?} cannot belong to another sub-agent");
2366 }
2367 if subagent.task_name.trim().is_empty()
2368 || subagent.profile_id.trim().is_empty()
2369 || subagent.request_key.trim().is_empty()
2370 {
2371 bail!("sub-agent {child_id:?} has incomplete relationship metadata");
2372 }
2373 Ok(())
2374 }
2375
2376 pub fn remember_mount_sources(&mut self, host: &str, mounts: &[AdditionalMount]) {
2377 if mounts.is_empty() {
2378 return;
2379 }
2380 let sources = self
2381 .mount_history
2382 .entry(host.to_owned())
2383 .or_insert_with(Vec::new);
2384 for mount in mounts.iter().rev() {
2385 sources.retain(|source| source != &mount.source);
2386 sources.insert(0, mount.source.clone());
2387 }
2388 sources.truncate(20);
2389 }
2390
2391 pub fn remember_container_size(&mut self, host: &str, size: HostContainerSize) {
2392 self.container_sizes.insert(host.to_owned(), size);
2393 }
2394
2395 pub fn project_directories(&self, host: &str) -> &[PathBuf] {
2396 self.mount_history
2397 .get(&project_history_key(host))
2398 .map(Vec::as_slice)
2399 .unwrap_or_default()
2400 }
2401
2402 pub fn remember_project_directory(&mut self, host: &str, directory: &Path) {
2403 let key = project_history_key(host);
2404 let directories = self.mount_history.entry(key).or_insert_with(Vec::new);
2405 directories.retain(|existing| existing != directory);
2406 directories.insert(0, directory.to_path_buf());
2407 directories.truncate(20);
2408 }
2409
2410 pub fn destroy_stopped_session(&mut self, session_id: &str) -> Result<SessionRecord> {
2411 let session = self
2412 .sessions
2413 .get(session_id)
2414 .with_context(|| format!("unknown session {session_id}"))?;
2415 if session.state.is_active() {
2416 bail!("refusing to destroy active session {session_id}");
2417 }
2418 Ok(self
2419 .sessions
2420 .remove(session_id)
2421 .expect("session checked above"))
2422 }
2423
2424 pub fn destroy_session_force(&mut self, session_id: &str) -> Result<SessionRecord> {
2430 self.sessions
2431 .get(session_id)
2432 .with_context(|| format!("unknown session {session_id}"))?;
2433 Ok(self
2434 .sessions
2435 .remove(session_id)
2436 .expect("session checked above"))
2437 }
2438
2439 pub fn bundle_users(&self, bundle_id: &str) -> Vec<&SessionRecord> {
2444 self.sessions
2445 .values()
2446 .filter(|session| {
2447 session.bundle_id == bundle_id
2448 && self
2449 .checkout(&session.id)
2450 .is_ok_and(|checkout| checkout.project_directory().is_none())
2451 && session.state != SessionState::DestroyedWithDataLoss
2452 })
2453 .collect()
2454 }
2455
2456 pub fn bundle_removal_refusal(&self, bundle_id: &str) -> Option<String> {
2459 let users = self.bundle_users(bundle_id);
2460 if users.is_empty() {
2461 return None;
2462 }
2463 let mut names = users
2464 .iter()
2465 .take(3)
2466 .map(|session| format!("{:?}", session.listed_title()))
2467 .collect::<Vec<_>>();
2468 if users.len() > 3 {
2469 names.push(format!("{} more", users.len() - 3));
2470 }
2471 Some(format!(
2472 "Project {bundle_id:?} is used by {}: {}. Destroy those sessions before removing it.",
2473 if users.len() == 1 {
2474 "a session"
2475 } else {
2476 "sessions"
2477 },
2478 names.join(", ")
2479 ))
2480 }
2481
2482 pub fn validate_setup_update(&self, before: &Config, after: &Config) -> Result<()> {
2485 for session in self
2486 .sessions
2487 .values()
2488 .filter(|session| session.state.is_active())
2489 {
2490 let protected = if let Some(profile) = before.profiles.get(&session.last_profile) {
2491 let mut comparable = profile.clone();
2492 if let Some(updated) = after.profiles.get(&session.last_profile) {
2493 comparable.enabled = updated.enabled;
2494 comparable.subagents = updated.subagents.clone();
2495 }
2496 profile.kind == session.harness_kind
2498 && after.profiles.get(&session.last_profile) != Some(&comparable)
2499 } else {
2500 false
2501 };
2502 let bundle_changed = self
2503 .checkout(&session.id)
2504 .is_ok_and(|checkout| checkout.project_directory().is_none())
2505 && before
2506 .bundles
2507 .get(&session.bundle_id)
2508 .is_some_and(|bundle| after.bundles.get(&session.bundle_id) != Some(bundle));
2509 let target_changed =
2513 before
2514 .targets
2515 .get(&session.target_template_id)
2516 .is_some_and(|target| {
2517 after
2518 .targets
2519 .get(&session.target_template_id)
2520 .map(TargetTemplate::without_launch_only_settings)
2521 != Some(target.without_launch_only_settings())
2522 });
2523 if protected || bundle_changed || target_changed {
2524 let mut used = Vec::new();
2528 if protected {
2529 used.push(format!("agent profile {:?}", session.last_profile));
2530 }
2531 if bundle_changed {
2532 used.push(format!("project {:?}", session.project_name(before)));
2533 }
2534 if target_changed {
2535 used.push(format!("runtime {:?}", session.target_template_id));
2536 }
2537 let used = match used.as_slice() {
2538 [only] => only.clone(),
2539 [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
2540 [] => unreachable!("something changed"),
2541 };
2542 let title = session.display_title();
2543 let named = if title == session.id {
2544 format!(
2545 "a running session in project {:?}",
2546 session.project_name(before)
2547 )
2548 } else {
2549 format!("the running session {title:?}")
2550 };
2551 bail!(
2552 "Setup would change the {used} that {named} uses. Save the new settings under a new name, or stop the session first."
2553 );
2554 }
2555 }
2556 Ok(())
2557 }
2558
2559 pub fn validate_against_config(&self, config: &Config) -> Result<()> {
2561 self.validate()?;
2562 config.validate()?;
2563 for session in self.sessions.values() {
2564 session.validate_configuration(config)?;
2565 }
2566 Ok(())
2567 }
2568}
2569
2570fn project_history_key(host: &str) -> String {
2571 format!("project:{host}")
2572}
2573
2574pub fn new_session_id() -> Result<String> {
2576 let mut random = [0u8; 16];
2577 getrandom::fill(&mut random)
2578 .map_err(|error| anyhow::anyhow!("generate Mjolnir session id: {error}"))?;
2579 Ok(crate::hex::lower_hex(random))
2580}
2581
2582pub fn harness_session_title(events: &[SequencedEvent]) -> Option<String> {
2584 events.iter().rev().find_map(|event| {
2585 let WorkerEvent::Adapter { payload, .. } = &event.event else {
2586 return None;
2587 };
2588 let crate::acp::RuntimeEvent::SessionUpdate { update } =
2589 serde_json::from_value(payload.clone()).ok()?
2590 else {
2591 return None;
2592 };
2593 let kind = update
2594 .get("sessionUpdate")
2595 .and_then(serde_json::Value::as_str)?;
2596 let title = match kind {
2597 "session_info_update" | "session_title" => {
2598 update.get("title").and_then(serde_json::Value::as_str)
2599 }
2600 _ => None,
2601 }?;
2602 normalize_session_title(title)
2603 })
2604}
2605
2606pub fn default_session_title(
2611 project_directory: Option<&Path>,
2612 bundle_id: &str,
2613 profile_id: &str,
2614) -> String {
2615 let project = project_directory.and_then(Path::file_name).map_or_else(
2616 || bundle_id.to_owned(),
2617 |name| name.to_string_lossy().into_owned(),
2618 );
2619 format!("{project} via {profile_id}")
2620}
2621
2622pub const MAX_SESSION_TITLE_CHARS: usize = 256;
2623
2624pub fn normalize_session_title(title: &str) -> Option<String> {
2626 let normalized = crate::relay::strip_hidden_prompt_context(title)
2627 .split_whitespace()
2628 .collect::<Vec<_>>()
2629 .join(" ");
2630 (!normalized.is_empty()).then(|| truncate_session_title(normalized, MAX_SESSION_TITLE_CHARS))
2631}
2632
2633fn truncate_session_title(title: String, maximum_chars: usize) -> String {
2634 if title.chars().count() <= maximum_chars {
2635 return title;
2636 }
2637
2638 let mut truncated = title.chars().take(maximum_chars - 1).collect::<String>();
2639 if let Some(boundary) = truncated.rfind(char::is_whitespace) {
2640 truncated.truncate(boundary);
2641 }
2642 truncated.push('…');
2643 truncated
2644}
2645
2646pub fn provisional_session_title(prompt: &str) -> Option<String> {
2652 const MAX_TITLE_CHARS: usize = 64;
2653
2654 let normalized = normalize_session_title(prompt)?;
2655 Some(truncate_session_title(normalized, MAX_TITLE_CHARS))
2656}
2657
2658pub fn short_id(id: &str) -> &str {
2659 id.get(..8).unwrap_or(id)
2660}
2661
2662#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
2663pub struct RecoveryCandidate {
2664 pub session_id: String,
2665 pub target_template_id: String,
2666 pub locator: TargetLocator,
2667 pub ownership: Option<crate::worker_launch::WorkerOwnership>,
2668 #[serde(default)]
2671 pub instance_id: Option<String>,
2672 #[serde(default, skip_serializing_if = "Option::is_none")]
2677 pub tracked_session: Option<SessionState>,
2678}
2679
2680#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
2681pub struct RecoveryScan {
2682 pub candidates: Vec<RecoveryCandidate>,
2683 pub warnings: Vec<String>,
2684 #[serde(default)]
2686 pub instance_id: String,
2687 #[serde(default)]
2690 pub hidden_other_instances: usize,
2691}
2692
2693#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2694#[serde(deny_unknown_fields)]
2695pub struct ResumeRepositorySourceReceipt {
2696 pub session_id: String,
2697 pub bundle_id: String,
2698 pub checkpoint_sha256: String,
2699 pub repositories: Vec<crate::config::ProjectRepository>,
2700}
2701
2702#[cfg(test)]
2703mod tests;