Skip to main content

mj_core/
state.rs

1//! Durable controller-side state for Hel-managed sessions.
2
3#[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    /// Startup failed; teardown owns the target until termination is confirmed.
37    StartupCleanup,
38    Running,
39    Disconnected,
40    Checkpointing,
41    Closing,
42    Destroying,
43    /// Checkpointed and torn down. Persisted as `"archived"` before the verb
44    /// was renamed, so the alias keeps those records loading.
45    #[serde(alias = "archived")]
46    Stopped,
47    /// A Mjolnir sub-agent whose turn ended and whose parent was told: its
48    /// worker process tree is stopped so it holds no processes in the
49    /// parent's container, while its record, relation, target locator and
50    /// worker root (relay journal, native session id) stay. Only a parent's
51    /// `send_message` starts it again. Nothing that connects to, reconnects,
52    /// recovers or upgrades live sessions acts on it.
53    Parked,
54    Lost,
55    Error,
56    DestroyedWithDataLoss,
57}
58
59/// A lifecycle transition temporarily replaces the conversation in control surfaces.
60/// Operation ownership takes precedence over intermediate durable session states.
61#[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    /// A sub-agent stopped because its parent is being suspended.
70    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/// Controller-owned execution state derived from the relay event stream.
116#[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/// What a durable queue entry does when its turn comes.
131///
132/// Serialized without a tag for prompts so entries written before configuration
133/// changes could be queued keep loading unchanged.
134#[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
151/// The composer form of a configuration change, used both as the queue entry's
152/// display text and as the text peeled back into the composer for editing.
153pub 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    /// Relay acceptance ordinal of the `CommandQueued` event that created this
170    /// entry. It is the turn identity the API hands back to callers, so wait
171    /// can tell one queued prompt's outcome from another's.
172    #[serde(default, skip_serializing_if = "Option::is_none")]
173    pub accepted_ordinal: Option<u64>,
174}
175
176/// The prompt currently executing, recorded when its `CommandStarted` event is
177/// projected and cleared when the command completes.
178#[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    /// Ordinal of the `CommandStarted` event, which is also the transcript
185    /// position of the turn's first item.
186    pub turn_start_position: u64,
187    pub started_at_ms: i64,
188    /// The relay prompt still executing this turn after a steer moved the
189    /// turn to a queued prompt. That prompt's completion ends this turn.
190    #[serde(default, skip_serializing_if = "Option::is_none")]
191    pub steered_into: Option<String>,
192}
193
194impl MaterializedTurn {
195    /// Whether the ending of relay prompt `command_id` ends this turn.
196    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/// How a prompt ended.
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203#[serde(tag = "kind", rename_all = "snake_case")]
204pub enum TurnOutcomeKind {
205    /// The harness finished the turn and reported this stop reason.
206    Completed { stop_reason: String },
207    /// The relay refused the command before it ran.
208    Rejected {
209        message: String,
210        #[serde(default, skip_serializing_if = "Option::is_none")]
211        reason: Option<crate::event_outcome::OutcomeReason>,
212    },
213    /// The command was interrupted after being accepted.
214    Interrupted {
215        message: String,
216        #[serde(default, skip_serializing_if = "Option::is_none")]
217        reason: Option<crate::event_outcome::OutcomeReason>,
218    },
219}
220
221/// How a turn ended, in words a person reads: "completed, end of turn",
222/// "interrupted", or "failed: <reason>".
223impl 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
252/// A stop reason as the harness spells it (`MaxTokens`, `max_turn_requests`)
253/// as lower-case words.
254fn 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
286/// Shared interpretation for wait responses and durable completion events.
287pub 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/// The most recent finished prompt on a session.
303#[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    /// Only work that actually started can have been interrupted.
323    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/// Canonical controller projection for one logical ACP session.
331#[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    /// Monotonic controller projection watermark derived from relay event
338    /// receipt times. It is deliberately independent of retained rows.
339    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    /// Transcript items are shared by pointer so cloning a snapshot copies
347    /// handles rather than the whole conversation.
348    pub transcript: Vec<Arc<TranscriptItem>>,
349    #[serde(default, skip_serializing_if = "Vec::is_empty")]
350    pub queued_prompts: Vec<MaterializedQueuedPrompt>,
351    /// In-flight form requests are projected durably, but their answers are
352    /// connection-only and never enter this state.
353    #[serde(default, skip_serializing_if = "Vec::is_empty")]
354    pub pending_elicitations: Vec<crate::elicitation::ElicitationRequest>,
355    /// The prompt running right now, if any.
356    #[serde(default, skip_serializing_if = "Option::is_none")]
357    pub active_turn: Option<MaterializedTurn>,
358    /// The most recently finished prompt, kept after the session stops so a
359    /// caller can still read how the last turn ended.
360    #[serde(default, skip_serializing_if = "Option::is_none")]
361    pub last_turn_outcome: Option<MaterializedTurnOutcome>,
362}
363
364/// The small portion of a durable projection needed to populate dashboard
365/// rows before the live session delivers its full transcript snapshot.
366#[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    /// Whether the last nonempty agent message appears after the last
376    /// nonempty user message in transcript order.
377    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    /// Resolve the title exposed by a live materialized session.
405    ///
406    /// Sessions created before provisional titles were projected can still
407    /// have an untitled transcript. Derive the same bounded fallback from
408    /// their first visible user prompt when reading them.
409    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                    if !item.is_user_prompt() {
416                        return None;
417                    }
418                    let TranscriptBody::User { content } = &item.body else {
419                        return None;
420                    };
421                    provisional_session_title(&crate::transcript::materialized_content_text(
422                        content,
423                    ))
424                })
425            })
426            .or_else(|| {
427                self.queued_prompts
428                    .iter()
429                    .filter(|prompt| prompt.kind.is_prompt())
430                    .find_map(|prompt| {
431                        provisional_session_title(&crate::transcript::materialized_content_text(
432                            &prompt.content,
433                        ))
434                    })
435            })
436    }
437
438    pub fn unread_agent_messages_after(&self, viewed_through_event_ordinal: u64) -> u64 {
439        self.transcript
440            .iter()
441            .filter(|item| {
442                item.latest_content_event_ordinal
443                    .is_some_and(|ordinal| ordinal > viewed_through_event_ordinal)
444                    && item.is_nonempty_agent_message()
445            })
446            .count() as u64
447    }
448
449    pub fn unread_interruptions_after(&self, viewed_through_event_ordinal: u64) -> u64 {
450        self.interruption_event_ordinals()
451            .into_iter()
452            .filter(|ordinal| *ordinal > viewed_through_event_ordinal)
453            .count() as u64
454    }
455
456    pub fn interruption_event_ordinals(&self) -> Vec<u64> {
457        let mut ordinals = self
458            .transcript
459            .iter()
460            .filter(|item| item.is_work_interruption())
461            .map(|item| item.position)
462            .collect::<Vec<_>>();
463        if let Some(ordinal) = self
464            .last_turn_outcome
465            .as_ref()
466            .and_then(MaterializedTurnOutcome::interruption_ordinal)
467        {
468            ordinals.push(ordinal);
469        }
470        ordinals.sort_unstable();
471        ordinals.dedup();
472        ordinals
473    }
474
475    pub fn validate(&self) -> Result<()> {
476        validate_id("session", &self.session_id)?;
477        validate_relay_event_frontier(
478            self.applied_event_ordinal,
479            &self.applied_event_digest,
480            "materialized session event frontier",
481        )?;
482        if self
483            .session_title
484            .as_ref()
485            .is_some_and(|title| title.trim().is_empty())
486        {
487            bail!("materialized session has an empty title");
488        }
489        let mut item_ids = BTreeSet::new();
490        for item in &self.transcript {
491            item.validate(self.applied_event_ordinal)?;
492            if !item_ids.insert(item.stable_id.as_str()) {
493                bail!(
494                    "materialized transcript contains duplicate item {:?}",
495                    item.stable_id
496                );
497            }
498        }
499        let mut command_ids = BTreeSet::new();
500        for prompt in &self.queued_prompts {
501            if prompt.command_id.trim().is_empty() {
502                bail!("materialized prompt queue has an empty command id");
503            }
504            if !command_ids.insert(prompt.command_id.as_str()) {
505                bail!(
506                    "materialized prompt queue contains duplicate command {:?}",
507                    prompt.command_id
508                );
509            }
510            if let QueuedCommandKind::SetConfig { key, value } = &prompt.kind
511                && (key.trim().is_empty() || value.trim().is_empty())
512            {
513                bail!(
514                    "materialized queued configuration change {:?} is incomplete",
515                    prompt.command_id
516                );
517            }
518        }
519        Ok(())
520    }
521}
522
523/// A materialized session paired with the live worker's relay state. The
524/// session manager hands this to every reader that needs both the durable
525/// projection and the connection's operational status.
526#[derive(Debug, Clone, PartialEq)]
527pub struct ManagedSessionSnapshot {
528    pub materialized: MaterializedSession,
529    /// What `materialized.transcript` leaves out, and the facts that live
530    /// there. See [`ProjectionWindow`].
531    pub window: ProjectionWindow,
532    pub operational: RelayOperationalState,
533    /// Newest relay event observed by this live actor that asks for immediate
534    /// credential reconciliation. This is intentionally ephemeral: it avoids
535    /// retaining raw replay pages or rescanning projected history.
536    pub latest_credential_sync_signal: Option<CredentialSyncSignal>,
537    /// Content address of the executable the connected worker is running, as
538    /// it reported in hello. `None` when the connection did not come from a
539    /// live worker or the worker predates the field; either way the worker is
540    /// not known to be the build this controller would install.
541    pub worker_build: Option<String>,
542    /// Pending parent-tool work fetched from the target worker.
543    pub subagent_requests: Vec<crate::subagent::SubagentToolRequest>,
544    /// Recently completed tool work cached by the worker for idempotent calls.
545    pub subagent_results: Vec<crate::subagent::SubagentToolResult>,
546}
547
548/// What a projection's transcript window leaves out.
549///
550/// A polled projection carries only the end of the transcript, because that is
551/// all any viewer shows and loading the rest is work proportional to history.
552/// Two facts a reader needs live outside that window: the provisional title
553/// comes from the *first* user message, and the newest turn start is outside
554/// it whenever a single turn is longer than the window. Both are read
555/// separately, with one indexed query each, rather than found by scanning.
556///
557/// A complete projection answers both by scanning what it already holds, which
558/// is what [`ProjectionWindow::of`] does.
559#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
560pub struct ProjectionWindow {
561    /// Transcript items before the window. Zero when the projection is whole.
562    pub omitted_items: usize,
563    /// The title derived from the first user message.
564    pub provisional_title: Option<String>,
565    /// Position of the newest turn start — a user message or the marker for a
566    /// turn the harness began on its own — whether or not it is in the
567    /// window. `None` when the session has none.
568    pub latest_turn_start_position: Option<u64>,
569}
570
571impl ProjectionWindow {
572    /// Keep complete turns around the tail target. Unsettled content can still
573    /// change after a newer turn starts, so retain its turn as well.
574    pub fn trim(&mut self, session: &mut MaterializedSession, target: usize) {
575        let observed = Self::of(session);
576        if self.provisional_title.is_none() {
577            self.provisional_title = observed.provisional_title;
578        }
579        self.latest_turn_start_position = observed
580            .latest_turn_start_position
581            .or(self.latest_turn_start_position);
582        let mut boundary = session.transcript.len().saturating_sub(target.max(1));
583        for (index, item) in session.transcript.iter().enumerate() {
584            let mutable = match &item.body {
585                TranscriptBody::Agent { streaming, .. }
586                | TranscriptBody::Thought { streaming, .. } => *streaming,
587                TranscriptBody::Tool { call, .. } => matches!(
588                    call.get("status").and_then(serde_json::Value::as_str),
589                    Some("pending" | "in_progress")
590                ),
591                _ => false,
592            };
593            if mutable || Some(item.position) == self.latest_turn_start_position {
594                boundary = boundary.min(index);
595            }
596        }
597        let cut = session
598            .transcript
599            .iter()
600            .take(boundary + 1)
601            .rposition(|item| item.is_turn_start())
602            .unwrap_or(0);
603        if cut > 0 {
604            session.transcript.drain(..cut);
605            self.omitted_items += cut;
606        }
607    }
608
609    /// The window of a projection that omits nothing.
610    #[must_use]
611    pub fn of(session: &MaterializedSession) -> Self {
612        Self {
613            omitted_items: 0,
614            provisional_title: session.transcript.iter().find_map(|item| {
615                if !item.is_user_prompt() {
616                    return None;
617                }
618                let TranscriptBody::User { content } = &item.body else {
619                    return None;
620                };
621                provisional_session_title(&crate::transcript::materialized_content_text(content))
622            }),
623            latest_turn_start_position: session
624                .transcript
625                .iter()
626                .rev()
627                .find(|item| item.is_turn_start())
628                .map(|item| item.position),
629        }
630    }
631}
632
633impl ManagedSessionSnapshot {
634    /// The session's title, using the same precedence as
635    /// [`MaterializedSession::resolved_title`] but taking the provisional
636    /// title from the window rather than from a transcript head that a polled
637    /// projection does not carry.
638    #[must_use]
639    pub fn resolved_title(&self) -> Option<String> {
640        self.materialized
641            .session_title
642            .as_deref()
643            .and_then(normalize_session_title)
644            .or_else(|| self.window.provisional_title.clone())
645            .or_else(|| {
646                self.materialized
647                    .queued_prompts
648                    .iter()
649                    .filter(|prompt| prompt.kind.is_prompt())
650                    .find_map(|prompt| {
651                        provisional_session_title(&crate::transcript::materialized_content_text(
652                            &prompt.content,
653                        ))
654                    })
655            })
656    }
657
658    /// The position of the turn this session most recently finished, or `None`
659    /// while it is still working. Same answer as
660    /// [`latest_completed_turn_ordinal`], from a position the window carries
661    /// rather than a scan back through the transcript.
662    #[must_use]
663    pub fn latest_completed_turn_ordinal(&self) -> Option<u64> {
664        if self.materialized.execution != MaterializedExecutionState::Idle {
665            return None;
666        }
667        self.window.latest_turn_start_position
668    }
669}
670
671/// One session's activity, reported to the recovery coordinator.
672#[derive(Debug, Clone)]
673pub struct RecoveryObservation {
674    pub session: SessionRecord,
675    pub config: Config,
676    pub latest_completed_turn_ordinal: Option<u64>,
677    /// Why a routine checkpoint has to wait, or `None` when one may start now:
678    /// [`crate::activity::routine_checkpoint_wait`] on the worker's
679    /// operational state, the same answer checkpoint admission gives.
680    pub checkpoint_wait: Option<crate::activity::CheckpointWait>,
681}
682
683/// The position where the session's most recent finished turn began, or
684/// `None` while it is still working. A turn starts at a user message or at the
685/// marker for a turn the harness began on its own, so autonomous work is
686/// covered once it settles.
687pub fn latest_completed_turn_ordinal(session: &MaterializedSession) -> Option<u64> {
688    if session.execution != MaterializedExecutionState::Idle {
689        return None;
690    }
691    session
692        .transcript
693        .iter()
694        .rev()
695        .find(|item| item.is_turn_start())
696        .map(|item| item.position)
697}
698
699pub fn validate_relay_event_digest(digest: &str, name: &str) -> Result<()> {
700    if digest.len() != 64
701        || !digest
702            .bytes()
703            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
704    {
705        bail!("{name} must be a lowercase SHA-256 digest");
706    }
707    Ok(())
708}
709
710pub fn validate_relay_event_frontier(ordinal: u64, digest: &str, name: &str) -> Result<()> {
711    validate_relay_event_digest(digest, name)?;
712    if (ordinal == 0) != (digest == RELAY_EVENT_GENESIS_DIGEST) {
713        bail!("{name} has inconsistent ordinal {ordinal} and digest {digest}");
714    }
715    Ok(())
716}
717
718fn is_false(value: &bool) -> bool {
719    !*value
720}
721
722impl SessionState {
723    /// The persisted and wire spelling, matching the serde encoding.
724    pub const fn as_str(self) -> &'static str {
725        match self {
726            Self::Provisioning => "provisioning",
727            Self::StartupCleanup => "startup-cleanup",
728            Self::Running => "running",
729            Self::Disconnected => "disconnected",
730            Self::Checkpointing => "checkpointing",
731            Self::Closing => "closing",
732            Self::Destroying => "destroying",
733            Self::Stopped => "stopped",
734            Self::Parked => "parked",
735            Self::Lost => "lost",
736            Self::Error => "error",
737            Self::DestroyedWithDataLoss => "destroyed-with-data-loss",
738        }
739    }
740
741    /// Read a stored spelling. Rows written before the verb was renamed still
742    /// say `"archived"`.
743    pub fn from_stored(value: &str) -> Option<Self> {
744        Some(match value {
745            "provisioning" => Self::Provisioning,
746            "startup-cleanup" => Self::StartupCleanup,
747            "running" => Self::Running,
748            "disconnected" => Self::Disconnected,
749            "checkpointing" => Self::Checkpointing,
750            "closing" => Self::Closing,
751            "destroying" => Self::Destroying,
752            "stopped" | "archived" => Self::Stopped,
753            "parked" => Self::Parked,
754            "lost" => Self::Lost,
755            "error" => Self::Error,
756            "destroyed-with-data-loss" => Self::DestroyedWithDataLoss,
757            _ => return None,
758        })
759    }
760
761    /// Recovery without a live operation still hides an unfinished target transition.
762    /// Ordinary checkpoints and reconnects deliberately keep their conversation visible.
763    pub const fn transition_kind(self) -> Option<SessionTransitionKind> {
764        match self {
765            Self::Provisioning => Some(SessionTransitionKind::Starting),
766            Self::StartupCleanup => Some(SessionTransitionKind::Stopping),
767            Self::Closing => Some(SessionTransitionKind::Suspending),
768            Self::Destroying => Some(SessionTransitionKind::Destroying),
769            _ => None,
770        }
771    }
772
773    /// True while the session still belongs on the dashboard. `Closing` and
774    /// `Checkpointing` stay active on purpose: a stop that has not produced a
775    /// verified checkpoint must not make its row disappear. A `Parked`
776    /// sub-agent is active too: it is still its parent's child, still listed,
777    /// and its parent's suspend, destroy or workspace close must still end
778    /// it. Code that needs a live worker must ask [`Self::has_live_worker`].
779    pub const fn is_active(self) -> bool {
780        matches!(
781            self,
782            Self::Provisioning
783                | Self::StartupCleanup
784                | Self::Running
785                | Self::Disconnected
786                | Self::Checkpointing
787                | Self::Closing
788                | Self::Destroying
789                | Self::Parked
790                | Self::Error
791        )
792    }
793
794    /// True while the session may have a worker process tree on its target,
795    /// including one still being started or torn down: the states in which a
796    /// sub-agent counts against its parent's cap.
797    pub const fn has_live_worker(self) -> bool {
798        matches!(
799            self,
800            Self::Provisioning
801                | Self::StartupCleanup
802                | Self::Running
803                | Self::Disconnected
804                | Self::Checkpointing
805                | Self::Closing
806                | Self::Destroying
807        )
808    }
809}
810
811#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
812#[serde(tag = "kind", rename_all = "kebab-case")]
813pub enum PodmanWorkspaceLocator {
814    #[default]
815    ContainerLayer,
816    Volume {
817        name: String,
818    },
819    HostPath {
820        path: PathBuf,
821        helper: Vec<String>,
822        resource: String,
823    },
824}
825
826#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
827#[serde(tag = "kind", rename_all = "kebab-case")]
828pub enum TargetLocator {
829    LocalBare {
830        worker_root: PathBuf,
831    },
832    LocalPodman {
833        container_id: String,
834        #[serde(default)]
835        workspace_storage: PodmanWorkspaceLocator,
836        /// The session that owns the container when this locator is a
837        /// sub-agent child borrowing its parent's container; `None` when the
838        /// session owns the container itself.
839        #[serde(default, skip_serializing_if = "Option::is_none")]
840        borrowed_from: Option<String>,
841    },
842    LocalDocker {
843        container_id: String,
844        /// The session that owns the container when this locator is a
845        /// sub-agent child borrowing its parent's container; `None` when the
846        /// session owns the container itself.
847        #[serde(default, skip_serializing_if = "Option::is_none")]
848        borrowed_from: Option<String>,
849    },
850    AppleContainer {
851        container_id: String,
852        /// The session that owns the container when this locator is a
853        /// sub-agent child borrowing its parent's container; `None` when the
854        /// session owns the container itself.
855        #[serde(default, skip_serializing_if = "Option::is_none")]
856        borrowed_from: Option<String>,
857    },
858    AwsEc2 {
859        instance_id: String,
860        #[serde(default, skip_serializing_if = "Option::is_none")]
861        address: Option<String>,
862    },
863    SshBare {
864        host: String,
865        workspace: PathBuf,
866        #[serde(default, skip_serializing_if = "Option::is_none")]
867        worker_id: Option<String>,
868    },
869    SshPodman {
870        host: String,
871        container_id: String,
872        #[serde(default)]
873        workspace_storage: PodmanWorkspaceLocator,
874        /// The session that owns the container when this locator is a
875        /// sub-agent child borrowing its parent's container; `None` when the
876        /// session owns the container itself.
877        #[serde(default, skip_serializing_if = "Option::is_none")]
878        borrowed_from: Option<String>,
879    },
880    SshDocker {
881        host: String,
882        container_id: String,
883        /// The session that owns the container when this locator is a
884        /// sub-agent child borrowing its parent's container; `None` when the
885        /// session owns the container itself.
886        #[serde(default, skip_serializing_if = "Option::is_none")]
887        borrowed_from: Option<String>,
888    },
889}
890
891impl ManagedWorktreeTarget {
892    /// Whether `other` reaches the same checkout: the same kind and, over
893    /// SSH, the same destination, port, and login user.
894    ///
895    /// The other `ssh` options (keys, `ControlPath`, keepalives, host-key
896    /// policy) say how to connect, not where the worktree lives, so they
897    /// follow the machine's current configuration and never make a
898    /// suspended session unable to resume.
899    pub fn same_location(&self, other: &Self) -> bool {
900        match (self, other) {
901            (Self::Local, Self::Local) => true,
902            (
903                Self::Ssh {
904                    destination,
905                    ssh_args,
906                },
907                Self::Ssh {
908                    destination: other_destination,
909                    ssh_args: other_args,
910                },
911            ) => {
912                destination == other_destination
913                    && ssh_location_option(ssh_args, 'p', "port")
914                        == ssh_location_option(other_args, 'p', "port")
915                    && ssh_location_option(ssh_args, 'l', "user")
916                        == ssh_location_option(other_args, 'l', "user")
917            }
918            _ => false,
919        }
920    }
921}
922
923/// The value `ssh` would use for an option that has both a short flag
924/// (`-p 22`, `-p22`) and an `-o` spelling (`-o Port=22`, `-oPort 22`). OpenSSH
925/// keeps the first value it sees.
926fn ssh_location_option(args: &[String], flag: char, option: &str) -> Option<String> {
927    let mut args = args.iter();
928    while let Some(argument) = args.next() {
929        let Some(rest) = argument.strip_prefix('-') else {
930            continue;
931        };
932        let mut chars = rest.chars();
933        let Some(name) = chars.next() else { continue };
934        if name != flag && name != 'o' {
935            continue;
936        }
937        let inline = chars.as_str();
938        let value = if inline.is_empty() {
939            args.next().cloned()
940        } else {
941            Some(inline.to_owned())
942        };
943        if name == flag {
944            return value;
945        }
946        if let Some(setting) = value {
947            let (key, found) = setting
948                .split_once(['=', ' ', '\t'])
949                .unwrap_or((setting.as_str(), ""));
950            if key.trim().eq_ignore_ascii_case(option) {
951                return Some(found.trim().to_owned());
952            }
953        }
954    }
955    None
956}
957
958#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
959#[serde(tag = "kind", rename_all = "kebab-case")]
960pub enum ManagedWorktreeTarget {
961    Local,
962    Ssh {
963        destination: String,
964        #[serde(default, skip_serializing_if = "Vec::is_empty")]
965        ssh_args: Vec<String>,
966    },
967}
968
969/// Whether a selected project can create a session-owned Git checkout.
970#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
971#[serde(deny_unknown_fields)]
972pub struct ManagedWorktreeOptions {
973    pub available: bool,
974    pub default_create: bool,
975}
976
977#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
978#[serde(deny_unknown_fields)]
979pub struct ManagedWorktree {
980    /// Old records are linked worktrees. New isolated raw sessions own a clone.
981    #[serde(default, skip_serializing_if = "ManagedCheckoutKind::is_worktree")]
982    pub kind: ManagedCheckoutKind,
983    pub source_project_directory: PathBuf,
984    pub source_repository: PathBuf,
985    pub worktree_root: PathBuf,
986    pub branch: String,
987    pub target: ManagedWorktreeTarget,
988    /// The commit the session branch was created at. Recorded so an export can
989    /// diff against it in one read; sessions created before this field existed
990    /// fall back to the branch reflog, which expires.
991    #[serde(default, skip_serializing_if = "Option::is_none")]
992    pub base_commit: Option<String>,
993}
994
995#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
996#[serde(rename_all = "snake_case")]
997pub enum ManagedCheckoutKind {
998    #[default]
999    Worktree,
1000    Clone,
1001}
1002
1003impl ManagedCheckoutKind {
1004    fn is_worktree(&self) -> bool {
1005        matches!(self, Self::Worktree)
1006    }
1007}
1008
1009impl ManagedWorktree {
1010    fn validate(&self, session_id: &str, project_directory: Option<&Path>) -> Result<()> {
1011        for (label, path) in [
1012            ("source project directory", &self.source_project_directory),
1013            ("source repository", &self.source_repository),
1014            ("worktree root", &self.worktree_root),
1015        ] {
1016            if !crate::target_path::is_absolute(path)
1017                || path.components().any(|part| part == Component::ParentDir)
1018            {
1019                bail!("managed worktree {label} must be an absolute safe path");
1020            }
1021        }
1022        if !self
1023            .source_project_directory
1024            .starts_with(&self.source_repository)
1025        {
1026            bail!("managed worktree source directory is outside its repository");
1027        }
1028        let expected_root = self
1029            .source_repository
1030            .join(".mj")
1031            .join(match self.kind {
1032                ManagedCheckoutKind::Worktree => "worktrees",
1033                ManagedCheckoutKind::Clone => "clones",
1034            })
1035            .join(session_id);
1036        if self.worktree_root != expected_root {
1037            bail!("managed worktree root does not match the session-owned path");
1038        }
1039        if self.kind == ManagedCheckoutKind::Worktree && self.branch != format!("mj/{session_id}") {
1040            bail!("managed worktree branch does not match the session id");
1041        }
1042        if self.kind == ManagedCheckoutKind::Clone && self.branch.trim().is_empty() {
1043            bail!("managed clone has no starting branch");
1044        }
1045        let relative = self
1046            .source_project_directory
1047            .strip_prefix(&self.source_repository)
1048            .expect("source relationship checked above");
1049        if project_directory != Some(self.worktree_root.join(relative).as_path()) {
1050            bail!("session project directory does not match its managed worktree");
1051        }
1052        match &self.target {
1053            ManagedWorktreeTarget::Local => {}
1054            ManagedWorktreeTarget::Ssh { destination, .. } if destination.trim().is_empty() => {
1055                bail!("managed SSH worktree has an empty destination")
1056            }
1057            ManagedWorktreeTarget::Ssh { .. } => {}
1058        }
1059        Ok(())
1060    }
1061}
1062
1063#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1064#[serde(tag = "kind", rename_all = "kebab-case")]
1065pub enum SessionResourceAllocation {
1066    Container {
1067        cpus: u64,
1068        memory_bytes: u64,
1069    },
1070    AwsEc2 {
1071        instance_type: String,
1072        vcpus: u64,
1073        memory_bytes: u64,
1074    },
1075}
1076
1077/// Resource sizing supported by a target template.
1078#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
1079#[serde(rename_all = "kebab-case")]
1080pub enum ResourceAllocationKind {
1081    #[default]
1082    Fixed,
1083    Container,
1084    AwsEc2,
1085}
1086
1087impl SessionResourceAllocation {
1088    pub fn validate(&self) -> Result<()> {
1089        match self {
1090            Self::Container { cpus, memory_bytes } if *cpus == 0 || *memory_bytes == 0 => {
1091                bail!("container resource allocation must have non-zero CPU and memory")
1092            }
1093            Self::AwsEc2 {
1094                instance_type,
1095                vcpus,
1096                memory_bytes,
1097            } if instance_type.trim().is_empty() || *vcpus == 0 || *memory_bytes == 0 => {
1098                bail!("EC2 resource allocation must have an instance type, CPU, and memory")
1099            }
1100            _ => Ok(()),
1101        }
1102    }
1103}
1104
1105/// The CPU count an allocation grants, regardless of target kind.
1106pub fn allocation_cpus(allocation: &SessionResourceAllocation) -> u64 {
1107    match allocation {
1108        SessionResourceAllocation::Container { cpus, .. } => *cpus,
1109        SessionResourceAllocation::AwsEc2 { vcpus, .. } => *vcpus,
1110    }
1111}
1112
1113/// The memory, in bytes, an allocation grants, regardless of target kind.
1114pub fn allocation_memory(allocation: &SessionResourceAllocation) -> u64 {
1115    match allocation {
1116        SessionResourceAllocation::Container { memory_bytes, .. }
1117        | SessionResourceAllocation::AwsEc2 { memory_bytes, .. } => *memory_bytes,
1118    }
1119}
1120
1121impl TargetLocator {
1122    /// Only raw localhost sessions can use the daemon host's CLI and config.
1123    pub const fn skills_scope(&self) -> crate::skills::SkillsScope {
1124        match self {
1125            Self::LocalBare { .. } => crate::skills::SkillsScope::Localhost,
1126            _ => crate::skills::SkillsScope::Isolated,
1127        }
1128    }
1129
1130    fn validate(&self, session_id: &str) -> Result<()> {
1131        match self {
1132            Self::LocalBare { worker_root } => {
1133                if !crate::target_path::is_absolute(worker_root)
1134                    || worker_root
1135                        .components()
1136                        .any(|part| part == Component::ParentDir)
1137                    || !worker_root.ends_with(session_id)
1138                {
1139                    bail!(
1140                        "local bare worker root must be an absolute safe path ending in the session id"
1141                    );
1142                }
1143            }
1144            Self::LocalPodman { container_id, .. }
1145            | Self::LocalDocker { container_id, .. }
1146            | Self::AppleContainer { container_id, .. }
1147            | Self::SshPodman { container_id, .. }
1148            | Self::SshDocker { container_id, .. }
1149                if container_id.trim().is_empty() =>
1150            {
1151                bail!("target locator has an empty container id")
1152            }
1153            Self::AwsEc2 { instance_id, .. } if instance_id.trim().is_empty() => {
1154                bail!("target locator has an empty AWS instance id")
1155            }
1156            Self::SshBare {
1157                host,
1158                workspace,
1159                worker_id,
1160            } => {
1161                if host.trim().is_empty() {
1162                    bail!("bare SSH target locator has an empty host");
1163                }
1164                let unsafe_path = workspace.as_os_str().is_empty()
1165                    || workspace
1166                        .components()
1167                        .any(|part| part == Component::ParentDir);
1168                match worker_id {
1169                    // A sub-agent child works in its parent's workspace under
1170                    // its own worker identity, as cleanup also requires.
1171                    Some(worker_id) => {
1172                        if worker_id != session_id {
1173                            bail!(
1174                                "bare SSH target locator's worker identity does not match the session id"
1175                            );
1176                        }
1177                        if unsafe_path {
1178                            bail!("bare SSH target locator must have a safe workspace path");
1179                        }
1180                    }
1181                    None => {
1182                        if unsafe_path || !workspace.ends_with(session_id) {
1183                            bail!(
1184                                "bare SSH target locator must be a safe path ending in the session id"
1185                            );
1186                        }
1187                    }
1188                }
1189            }
1190            Self::SshPodman { host, .. } if host.trim().is_empty() => {
1191                bail!("SSH Podman target locator has an empty host")
1192            }
1193            Self::SshDocker { host, .. } if host.trim().is_empty() => {
1194                bail!("SSH Docker target locator has an empty host")
1195            }
1196            _ => {}
1197        }
1198        Ok(())
1199    }
1200}
1201
1202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1203#[serde(deny_unknown_fields)]
1204pub struct CheckpointMetadata {
1205    pub archive_path: PathBuf,
1206    /// Lowercase SHA-256 digest of the verified archive.
1207    pub sha256: String,
1208    pub created_at: String,
1209    pub event_frontier: u64,
1210}
1211
1212/// Whether every saved Git change has a verified durable copy outside mj.
1213#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1214#[serde(rename_all = "snake_case")]
1215pub enum PublicationState {
1216    Published,
1217    Unpublished,
1218    Unknown,
1219}
1220
1221/// Evidence for one exact checkpoint. A newer checkpoint invalidates it.
1222#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1223pub struct PublicationAssessment {
1224    pub checkpoint_sha256: String,
1225    pub state: PublicationState,
1226    pub dirty: bool,
1227    pub stashed: bool,
1228    pub saved_commits: Vec<String>,
1229    pub destinations: Vec<String>,
1230    pub checked_at: String,
1231    pub reason: Option<String>,
1232}
1233
1234impl CheckpointMetadata {
1235    fn validate(&self) -> Result<()> {
1236        if self.archive_path.as_os_str().is_empty() {
1237            bail!("checkpoint archive path is empty");
1238        }
1239        if self.sha256.len() != 64
1240            || !self
1241                .sha256
1242                .bytes()
1243                .all(|byte| byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase())
1244        {
1245            bail!("checkpoint SHA-256 must be 64 lowercase hexadecimal characters");
1246        }
1247        if self.created_at.trim().is_empty() {
1248            bail!("checkpoint timestamp is empty");
1249        }
1250        Ok(())
1251    }
1252}
1253
1254/// The mbx build cache a container session was provisioned with. The
1255/// directory is a host path mounted read-write at the same absolute path
1256/// inside the container. Older containers retain their private binaries until
1257/// recreated; the worker's `bin/mbx` contents identify that legacy scheme.
1258#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1259#[serde(deny_unknown_fields)]
1260pub struct SessionBuildCache {
1261    /// The container host this cache was resolved on. A session moved to a
1262    /// different host cannot reuse it, so the decision is made again there.
1263    pub host: String,
1264    pub directory: PathBuf,
1265    /// Read compatibility for old records only. Launch never uses this value;
1266    /// budgets belong to the shared machine configuration.
1267    #[serde(default, skip_serializing_if = "Option::is_none")]
1268    pub max_size: Option<String>,
1269    /// A `[target] root` the host's mbx configuration relocates outside the
1270    /// cache directory, mounted read-write at the same path as well.
1271    #[serde(default, skip_serializing_if = "Option::is_none")]
1272    pub target_root: Option<PathBuf>,
1273}
1274
1275/// How much disk Mjolnir's own copies of sessions use, and how much an
1276/// `archive_after_days` value would free. Settings shows this on the
1277/// SessionWiki page so the effect of a value is visible before it is saved.
1278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1279pub struct ArchiveSpacePreview {
1280    /// Every session record Mjolnir holds, archived or not.
1281    pub sessions: usize,
1282    /// What those sessions' checkpoints and attachments occupy.
1283    pub bytes: u64,
1284    /// The sessions an `archive_after_days` value would catch, and their
1285    /// share of `bytes`. Both are zero when no value is set.
1286    pub reclaimable_sessions: usize,
1287    pub reclaimable_bytes: u64,
1288}
1289
1290/// What a container target's host resolves for its blank build cache
1291/// settings right now. Settings shows this beside each "automatic" field so
1292/// the values a session would actually run with are visible before one starts.
1293#[derive(Debug, Clone, PartialEq, Eq)]
1294pub struct BuildCachePreview {
1295    /// The host's own mbx version, or `None` when it has none on `PATH`.
1296    pub native_mbx: Option<String>,
1297    /// The login profile the host would update when mbx is installed.
1298    pub mbx_profile_file: Option<String>,
1299    /// Why an unrecognized login shell may not read the selected profile.
1300    pub mbx_profile_warning: Option<String>,
1301    /// A literal POSIX PATH line for users whose shell does not read the selected profile.
1302    pub mbx_manual_path_line: Option<String>,
1303    /// The cache directory sessions would mount, once known.
1304    pub directory: Option<PathBuf>,
1305    /// The budget sessions would run with, once known.
1306    pub max_total_size: Option<BuildCacheLimit>,
1307    /// True when a general-purpose host installation owns the configuration.
1308    pub user_managed: bool,
1309    pub application: BuildCacheApplication,
1310    /// Explanation of the shared storage budget.
1311    pub budget_note: Option<String>,
1312    /// What the cache on that host has done so far, when it has a tally.
1313    pub stats: Option<BuildCacheStats>,
1314    /// Why sessions on this target run without a cache, or `None` when they
1315    /// share one.
1316    pub off_reason: Option<BuildCacheOff>,
1317}
1318
1319/// mbx's own running totals for one host's cache, read from the tally beside
1320/// the store.
1321///
1322/// These are machine-wide and cumulative: every session on that host and any
1323/// native builds the user ran themselves are counted together, since they
1324/// share one cache. They answer whether the cache is being used at all, not
1325/// what one session got out of it.
1326#[derive(Debug, Clone, PartialEq, Eq)]
1327pub struct BuildCacheStats {
1328    /// Builds that went through mbx. Zero means nothing has used the shim.
1329    pub builds: u64,
1330    /// Compilations answered from the cache instead of run.
1331    pub cached_compilations: u64,
1332    /// Compiler time those answers avoided, as mbx estimates it.
1333    pub avoided_compiler_ns: u64,
1334    /// Restored output bytes that were cloned rather than copied.
1335    pub reflinked_bytes: u64,
1336}
1337
1338/// Why a target's sessions run without the build cache.
1339#[derive(Debug, Clone, PartialEq, Eq)]
1340pub enum BuildCacheOff {
1341    /// This machine's own `enabled = false`.
1342    TurnedOff,
1343    /// Nothing on the machine's settings page can turn it on: the global
1344    /// switch, the host's mbx, or its filesystem. The text says which.
1345    Unavailable(String),
1346}
1347
1348impl std::fmt::Display for BuildCacheOff {
1349    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1350        match self {
1351            Self::TurnedOff => formatter.write_str("turned off for this machine"),
1352            Self::Unavailable(reason) => formatter.write_str(reason),
1353        }
1354    }
1355}
1356
1357/// Where a machine build cache budget comes from.
1358#[derive(Debug, Clone, PartialEq, Eq)]
1359pub enum BuildCacheLimit {
1360    /// An explicit mj machine setting written to shared mbx configuration.
1361    Size(String),
1362    /// The host's own `~/.config/mbx/config.toml` carries the budget. The
1363    /// total it sets, when it sets one.
1364    HostConfiguration(Option<String>),
1365    /// An automatic total initialized by mj, independent of later disk growth.
1366    MjDefault(String),
1367    /// The host's native mbx default, or no combined limit.
1368    MbxDefault(Option<String>),
1369}
1370
1371#[derive(Debug, Clone, Default, PartialEq, Eq)]
1372pub enum BuildCacheApplication {
1373    #[default]
1374    Pending,
1375    Applied,
1376    Failed(String),
1377}
1378
1379#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1380#[serde(deny_unknown_fields)]
1381pub struct SessionRecord {
1382    pub id: String,
1383    /// Owning workspace while active, or the most recent workspace while inactive.
1384    ///
1385    /// Inactive histories are globally resumable, so this id may refer to a
1386    /// workspace that has since been deleted.
1387    #[serde(default = "default_session_workspace_id")]
1388    pub workspace_id: String,
1389    pub title: String,
1390    pub harness_kind: HarnessKind,
1391    pub last_profile: String,
1392    pub bundle_id: String,
1393    /// Accepted bundle for every target, including a raw directory's bundle of one.
1394    #[serde(default, skip_serializing_if = "Option::is_none")]
1395    pub project: Option<crate::repository::ProjectBundleSnapshot>,
1396    /// Existing project directory used directly by a local or SSH bare target.
1397    #[serde(default, skip_serializing_if = "Option::is_none")]
1398    pub project_directory: Option<PathBuf>,
1399    /// Git worktree created and owned by Hel for this raw-project session.
1400    #[serde(default, skip_serializing_if = "Option::is_none")]
1401    pub managed_worktree: Option<ManagedWorktree>,
1402    /// None preserves automatic selection; false uses the selected directory.
1403    #[serde(default, skip_serializing_if = "Option::is_none")]
1404    pub create_managed_worktree: Option<bool>,
1405    /// Diff baseline as supplied by the caller (the API's `base`). A raw
1406    /// managed worktree also starts here; a bundle checkout keeps its selected
1407    /// remote branch tip. With `checkout`, it applies to the checked-out
1408    /// repository only, and when absent that repository's base is the
1409    /// checkout commit. The resolved baseline lands in
1410    /// `managed_worktree.base_commit` or the clone's `mj.baseCommit`.
1411    #[serde(default, skip_serializing_if = "Option::is_none")]
1412    pub launch_base: Option<String>,
1413    /// Existing branch to check out in a new isolated workspace (the API's
1414    /// `branch` without `at`). Never set together with `checkout`, which
1415    /// carries its own branch.
1416    #[serde(default, skip_serializing_if = "Option::is_none")]
1417    pub launch_branch: Option<String>,
1418    /// Immutable exact starting selection for one bundle repository, built
1419    /// from the API's `at` and `branch`. Resume preserves checkpointed work
1420    /// rather than applying this selection again.
1421    #[serde(default, skip_serializing_if = "Option::is_none")]
1422    pub checkout: Option<crate::remote_git::ExactCheckout>,
1423    /// Last verified publication verdict, tied to its checkpoint digest.
1424    #[serde(default, skip_serializing_if = "Option::is_none")]
1425    pub publication: Option<PublicationAssessment>,
1426    /// Stored delegation policy. Historical records without a choice use native delegation.
1427    #[serde(
1428        default,
1429        alias = "mjolnir_subagents",
1430        deserialize_with = "crate::subagent::deserialize_optional_policy"
1431    )]
1432    pub subagents: Option<crate::subagent::SubagentPolicy>,
1433    /// Turn review chosen for this session when it was created. `None`
1434    /// follows the global `[review]` section.
1435    #[serde(default, skip_serializing_if = "Option::is_none")]
1436    pub review: Option<crate::config::SessionReview>,
1437    pub target_template_id: String,
1438    #[serde(default, skip_serializing_if = "Option::is_none")]
1439    pub resource_allocation: Option<SessionResourceAllocation>,
1440    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1441    pub additional_mounts: Vec<AdditionalMount>,
1442    /// Per-session container CPU limit that overrides the target template's
1443    /// value. It is applied the next time the container is created.
1444    #[serde(default, skip_serializing_if = "Option::is_none")]
1445    pub container_cpus: Option<String>,
1446    /// Per-session container memory limit that overrides the target
1447    /// template's value. It is applied the next time the container is created.
1448    #[serde(default, skip_serializing_if = "Option::is_none")]
1449    pub container_memory: Option<String>,
1450    /// In-container workspace root this session's repositories live under.
1451    /// `None` is a session whose container predates per-session workspaces and
1452    /// therefore keeps the shared legacy `/workspace`; every session created
1453    /// since records `/workspace/<session id>`, so two checkouts of one project
1454    /// on a host never share an absolute path.
1455    #[serde(default, skip_serializing_if = "Option::is_none")]
1456    pub container_workspace: Option<PathBuf>,
1457    /// The mbx build cache this session's container runs with, decided once at
1458    /// provisioning. `None` means the session runs without a build cache;
1459    /// resume, move, and sub-agent children reuse the recorded value.
1460    #[serde(default, skip_serializing_if = "Option::is_none")]
1461    pub build_cache: Option<SessionBuildCache>,
1462    pub state: SessionState,
1463    /// Legacy visibility preference, retained for record compatibility.
1464    /// Current surfaces do not hide sessions based on this flag.
1465    #[serde(default, skip_serializing_if = "is_false")]
1466    pub archived: bool,
1467    #[serde(default, skip_serializing_if = "Option::is_none")]
1468    pub target: Option<TargetLocator>,
1469    /// Connection and worker settings captured when this target was selected.
1470    #[serde(default, skip_serializing_if = "Option::is_none")]
1471    pub target_runtime: Option<TargetRuntimeSettings>,
1472    #[serde(default, skip_serializing_if = "Option::is_none")]
1473    pub native_session_id: Option<String>,
1474    #[serde(default, skip_serializing_if = "Option::is_none")]
1475    pub acp_session_title: Option<String>,
1476    #[serde(default, skip_serializing_if = "Option::is_none")]
1477    pub session_title_override: Option<String>,
1478    pub created_at: String,
1479    pub updated_at: String,
1480    #[serde(default, alias = "detached_after_event_ordinal")]
1481    pub viewed_through_event_ordinal: u64,
1482    /// Unsent chat input carried across a detach, so returning to a session
1483    /// restores what the user was typing. Empty means no draft.
1484    #[serde(default, skip_serializing_if = "String::is_empty")]
1485    pub draft_input: String,
1486    /// Why the last operation on this session failed.
1487    ///
1488    /// This is usually a raw controller error chain, which names profile
1489    /// homes, project paths and SSH hosts, so a public projection publishes it
1490    /// only for a session that is stopped or failed. The one exception is a
1491    /// sentence the controller composed for the person; see
1492    /// [`CLOSE_FAILURE_PREFIX`].
1493    #[serde(default, skip_serializing_if = "Option::is_none")]
1494    pub last_error: Option<String>,
1495    #[serde(default, skip_serializing_if = "Option::is_none")]
1496    pub last_checkpoint_error: Option<String>,
1497    #[serde(default, skip_serializing_if = "Option::is_none")]
1498    pub checkpoint: Option<CheckpointMetadata>,
1499}
1500
1501#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1502#[serde(deny_unknown_fields)]
1503pub struct HostContainerSize {
1504    pub cpus: u64,
1505    pub memory_bytes: u64,
1506}
1507
1508pub const BASELINE_CONTAINER_CPUS: u64 = 8;
1509pub const BASELINE_CONTAINER_MEMORY_BYTES: u64 = 32 * 1024 * 1024 * 1024;
1510
1511/// Clamp a container size to a host reading, preserving the TUI's minimum of
1512/// one CPU and one byte when a host reports zero totals.
1513pub fn clamp_container_size(
1514    size: HostContainerSize,
1515    limits: Option<HostContainerSize>,
1516) -> HostContainerSize {
1517    let Some(limits) = limits else {
1518        return HostContainerSize {
1519            cpus: size.cpus.max(1),
1520            memory_bytes: size.memory_bytes.max(1),
1521        };
1522    };
1523    HostContainerSize {
1524        cpus: size.cpus.min(limits.cpus.max(1)),
1525        memory_bytes: size.memory_bytes.min(limits.memory_bytes.max(1)),
1526    }
1527}
1528
1529/// The default selected for a new container target: its remembered host size,
1530/// or 8 CPUs / 32 GiB, clamped to the latest host totals when available.
1531pub fn default_container_size(
1532    remembered: Option<HostContainerSize>,
1533    limits: Option<HostContainerSize>,
1534) -> HostContainerSize {
1535    clamp_container_size(
1536        remembered.unwrap_or(HostContainerSize {
1537            cpus: BASELINE_CONTAINER_CPUS,
1538            memory_bytes: BASELINE_CONTAINER_MEMORY_BYTES,
1539        }),
1540        limits,
1541    )
1542}
1543
1544/// The TUI's preferred EC2 size: retain the same instance type if offered,
1545/// else choose 8 vCPUs, else the first offered option.
1546pub fn preferred_aws_allocation<'a>(
1547    options: &'a [SessionResourceAllocation],
1548    previous: Option<&SessionResourceAllocation>,
1549) -> Option<&'a SessionResourceAllocation> {
1550    if let Some(SessionResourceAllocation::AwsEc2 { instance_type, .. }) = previous
1551        && let Some(option) = options.iter().find(|option| {
1552            matches!(option, SessionResourceAllocation::AwsEc2 { instance_type: candidate, .. } if candidate == instance_type)
1553        })
1554    {
1555        return Some(option);
1556    }
1557    options
1558        .iter()
1559        .find(|option| allocation_cpus(option) == BASELINE_CONTAINER_CPUS)
1560        .or_else(|| options.first())
1561}
1562
1563fn default_session_workspace_id() -> String {
1564    crate::workspace::DEFAULT_WORKSPACE_ID.to_owned()
1565}
1566
1567/// How a failed close's reason begins in [`SessionRecord::last_error`].
1568///
1569/// A close that fails is non-destructive: the session goes back to the state
1570/// it was running in. Its reason therefore has to be published for a live
1571/// session, which the raw error chains in the same field never are. The
1572/// controller composes a sentence for the person and tags it with this prefix,
1573/// and the projection reads the tag to tell the two apart. Written in one
1574/// place and read in one place, so the tag cannot drift.
1575pub const DESTRUCTION_FAILURE_PREFIX: &str = "the destruction did not finish";
1576
1577pub const CLOSE_FAILURE_PREFIX: &str = "the suspension did not finish";
1578
1579pub const MOVE_FAILURE_PREFIX: &str = "the move did not finish";
1580
1581/// Recognize safe lifecycle outcomes, including records saved before the rename.
1582pub fn is_public_lifecycle_error(error: &str) -> bool {
1583    error.starts_with(CLOSE_FAILURE_PREFIX)
1584        || error.starts_with(MOVE_FAILURE_PREFIX)
1585        || error.starts_with(DESTRUCTION_FAILURE_PREFIX)
1586        || error.starts_with("the close did not finish")
1587}
1588
1589/// How a target is named beside a session, wherever a surface shows one.
1590///
1591/// A bare target (`local-bare`, `ssh-bare`) opens a project directory directly,
1592/// so the target alone does not say what the session was working on and the
1593/// project's own folder name is appended. Every other kind names a provisioned
1594/// environment that already identifies itself, so the target id stands alone.
1595/// A target id the configuration no longer holds is shown verbatim, because its
1596/// kind is no longer known.
1597///
1598/// Shared so the live session summary and the Resume dialog's archived rows
1599/// cannot drift apart: [`SessionRecord::project_target`] calls this, and so
1600/// does the archived row built from the SessionWiki index.
1601#[must_use]
1602pub fn target_label(config: &Config, target_id: &str, project: Option<&Path>) -> String {
1603    if !matches!(
1604        config.targets.get(target_id),
1605        Some(TargetTemplate::LocalBare | TargetTemplate::SshBare { .. })
1606    ) {
1607        return target_id.to_owned();
1608    }
1609    project.and_then(Path::file_name).map_or_else(
1610        || target_id.to_owned(),
1611        |directory| format!("{target_id}/{}", directory.to_string_lossy()),
1612    )
1613}
1614
1615/// A session's starting selection in the terms the API and CLI use.
1616#[derive(Debug, Clone, Default, PartialEq, Eq)]
1617pub struct StartSelection {
1618    /// Commit the workspace started checked out at.
1619    pub at: Option<String>,
1620    /// Branch created at `at`, or the existing branch checked out without it.
1621    pub branch: Option<String>,
1622    /// Diff base; `at` unless the caller named another.
1623    pub base: Option<String>,
1624}
1625
1626impl SessionRecord {
1627    /// Checkout shape recorded by this session, before State applies any
1628    /// sub-agent borrowing relationship. Call [`State::checkout`] whenever
1629    /// State is available so a child resolves to its parent's owner.
1630    #[must_use]
1631    pub fn checkout(&self) -> Checkout<'_> {
1632        derive_record_checkout(self)
1633    }
1634
1635    /// The starting selection this record stores, as `at`, `branch` and
1636    /// `base`. The record keeps the older field layout, so this is the one
1637    /// place that maps it to the public names.
1638    pub fn start_selection(&self) -> StartSelection {
1639        let at = self
1640            .checkout
1641            .as_ref()
1642            .map(|checkout| checkout.commit.clone());
1643        StartSelection {
1644            branch: self
1645                .checkout
1646                .as_ref()
1647                .and_then(|checkout| checkout.branch.clone())
1648                .or_else(|| self.launch_branch.clone()),
1649            base: self.launch_base.clone().or_else(|| at.clone()),
1650            at,
1651        }
1652    }
1653
1654    /// Cached verdict for an independent clone. Active checkouts are unknown
1655    /// until a new checkpoint binds an assessment to their exact contents.
1656    pub fn publication_state(&self) -> Option<PublicationState> {
1657        let independent_clone = match self.checkout().effective() {
1658            Checkout::ManagedWorktree { worktree, .. } => {
1659                worktree.kind == ManagedCheckoutKind::Clone
1660            }
1661            Checkout::ManagedWorkspace => true,
1662            Checkout::Attached { .. } | Checkout::Borrowed { .. } => false,
1663        };
1664        if !independent_clone {
1665            return None;
1666        }
1667        if self.state.is_active() {
1668            return Some(PublicationState::Unknown);
1669        }
1670        Some(
1671            self.checkpoint
1672                .as_ref()
1673                .zip(self.publication.as_ref())
1674                .filter(|(checkpoint, assessment)| {
1675                    assessment.checkpoint_sha256 == checkpoint.sha256
1676                })
1677                .map_or(PublicationState::Unknown, |(_, assessment)| {
1678                    if assessment.dirty || assessment.stashed {
1679                        PublicationState::Unpublished
1680                    } else {
1681                        assessment.state
1682                    }
1683                }),
1684        )
1685    }
1686
1687    /// The target access settings this session's commands use: the ones
1688    /// recorded when its target was selected, with the machine's current ssh
1689    /// options while they still reach the same host, user, and port, or the
1690    /// configured target's when nothing was recorded.
1691    pub fn target_runtime_settings<'a>(
1692        &'a self,
1693        config: &Config,
1694    ) -> Result<std::borrow::Cow<'a, TargetRuntimeSettings>> {
1695        if let Some(runtime) = &self.target_runtime {
1696            // How to reach the target follows the machine's current ssh
1697            // options; where it is stays as recorded (launch finding R3-7).
1698            if let Some(refreshed) =
1699                config
1700                    .targets
1701                    .get(&self.target_template_id)
1702                    .and_then(|template| {
1703                        runtime.with_current_ssh_options(&TargetRuntimeSettings::from(template))
1704                    })
1705            {
1706                return Ok(std::borrow::Cow::Owned(refreshed));
1707            }
1708            return Ok(std::borrow::Cow::Borrowed(runtime));
1709        }
1710        let template = config.targets.get(&self.target_template_id).ok_or_else(|| {
1711            crate::refusal::Refusal::precondition(format!(
1712                "Session {:?} has no recorded target access settings. Restore target {:?} in config.toml once, then retry.",
1713                self.id, self.target_template_id))
1714        })?;
1715        let runtime = TargetRuntimeSettings::from(template);
1716        if let Some(locator) = &self.target {
1717            crate::targets::TargetLocator::try_from(crate::targets::RecordedTarget {
1718                locator, runtime: Some(&runtime), session_id: &self.id,
1719            }).map_err(|error| crate::refusal::Refusal::precondition(format!(
1720                "Session {:?} cannot recover target {:?}: {error}. Restore its original target settings, then retry.", self.id, self.target_template_id)))?;
1721        }
1722        Ok(std::borrow::Cow::Owned(runtime))
1723    }
1724
1725    /// The recorded failure that is safe to publish whatever state this
1726    /// session is in, because the controller wrote it for the person rather
1727    /// than copying an error chain into it.
1728    #[must_use]
1729    pub fn public_error(&self) -> Option<&str> {
1730        self.last_error
1731            .as_deref()
1732            .filter(|error| is_public_lifecycle_error(error))
1733    }
1734
1735    /// Configuration drift belongs to this session, not the entire controller.
1736    /// The diagnostic contains only public identifiers, so both UIs can show it.
1737    pub fn configuration_issue(&self, config: &Config) -> Option<String> {
1738        if !self.state.is_active() {
1739            return None;
1740        }
1741        let mut issues = Vec::new();
1742        match config.profiles.get(&self.last_profile) {
1743            None => issues.push(format!("missing profile {:?}", self.last_profile)),
1744            Some(profile) if profile.kind != self.harness_kind => issues.push(format!(
1745                "expects {:?}, but profile {:?} is {:?}",
1746                self.harness_kind, self.last_profile, profile.kind
1747            )),
1748            Some(_) => {}
1749        }
1750        if self.checkout().project_directory().is_none() && self.project_bundle(config).is_none() {
1751            issues.push(format!("missing bundle {:?}", self.bundle_id));
1752        }
1753        if self.target_runtime.is_none() && !config.targets.contains_key(&self.target_template_id) {
1754            issues.push(format!(
1755                "missing target template {:?}",
1756                self.target_template_id
1757            ));
1758        }
1759        (!issues.is_empty()).then(|| format!(
1760            "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.",
1761            self.id, issues.join("; ")
1762        ))
1763    }
1764
1765    pub fn validate_configuration(&self, config: &Config) -> Result<()> {
1766        if let Some(issue) = self.configuration_issue(config) {
1767            return Err(crate::refusal::Refusal::precondition(issue).into());
1768        }
1769        Ok(())
1770    }
1771
1772    /// User-visible session name, independent of the initial prompt stored in `title`.
1773    pub fn display_title(&self) -> &str {
1774        self.session_title_override
1775            .as_deref()
1776            .or(self.acp_session_title.as_deref())
1777            .unwrap_or(&self.id)
1778    }
1779
1780    /// The name a listing shows: the display title, except that a session
1781    /// the harness has not named yet and nobody renamed would otherwise be
1782    /// named by its id, which every listing already prints beside it. The
1783    /// title it was created with says more (launch findings F-12 and R2-8).
1784    pub fn listed_title(&self) -> &str {
1785        let named = self.session_title_override.is_some() || self.acp_session_title.is_some();
1786        if !named && !self.title.trim().is_empty() {
1787            return &self.title;
1788        }
1789        self.display_title()
1790    }
1791
1792    /// Project this session works in, as the session list and the chat header
1793    /// both name it: the source repository of a managed worktree, else the
1794    /// project directory, else the bundle's primary repository, else the
1795    /// bundle id.
1796    pub fn project_name(&self, config: &Config) -> String {
1797        if let Some(project) = &self.project {
1798            return project.name();
1799        }
1800        match self.checkout().effective() {
1801            Checkout::ManagedWorktree { worktree, .. } => path_leaf(&worktree.source_repository),
1802            Checkout::Attached { path } => path_leaf(path),
1803            Checkout::ManagedWorkspace => self.bundle_source_name(config),
1804            Checkout::Borrowed { .. } => unreachable!("effective checkout resolves borrowing"),
1805        }
1806    }
1807
1808    /// Target label used by the live session summary. Bare targets identify
1809    /// the project directory they open directly; workspace targets already
1810    /// identify the provisioned environment on their own.
1811    pub fn project_target(&self, config: &Config, target_id: &str) -> String {
1812        let checkout = self.checkout();
1813        let project = match checkout.effective() {
1814            Checkout::ManagedWorktree { worktree, .. } => {
1815                Some(worktree.source_project_directory.as_path())
1816            }
1817            Checkout::Attached { path } => Some(path),
1818            Checkout::ManagedWorkspace => None,
1819            Checkout::Borrowed { .. } => unreachable!("effective checkout resolves borrowing"),
1820        };
1821        target_label(config, target_id, project)
1822    }
1823
1824    /// Stable source identity used to group sessions. Managed worktrees point
1825    /// back at their source repository, raw sessions use their project
1826    /// directory until their Git origin is resolved, and bundle sessions use
1827    /// their complete canonical repository set when configured.
1828    pub fn project_source(&self, config: &Config) -> ProjectSourceIdentity {
1829        if let Some(project) = &self.project {
1830            return ProjectSourceIdentity {
1831                key: project
1832                    .source_key()
1833                    .expect("accepted project has complete identities"),
1834                short: project.name(),
1835                full: project
1836                    .identities
1837                    .values()
1838                    .map(crate::repository::RepositoryIdentity::key)
1839                    .collect::<Vec<_>>()
1840                    .join(" + "),
1841            };
1842        }
1843        match self.checkout().effective() {
1844            Checkout::ManagedWorktree { worktree, .. } => {
1845                ProjectSourceIdentity::path(&worktree.source_repository, None)
1846            }
1847            Checkout::Attached { path } => {
1848                let remote = match &self.target {
1849                    Some(TargetLocator::SshBare { host, .. }) => Some(host.as_str()),
1850                    _ => None,
1851                };
1852                ProjectSourceIdentity::path(path, remote)
1853            }
1854            Checkout::ManagedWorkspace => {
1855                self.bundle_source_identity(config)
1856                    .unwrap_or_else(|| ProjectSourceIdentity {
1857                        key: format!("bundle:{}", self.bundle_id),
1858                        short: path_leaf(Path::new(&self.bundle_id)),
1859                        full: self.bundle_id.clone(),
1860                    })
1861            }
1862            Checkout::Borrowed { .. } => unreachable!("effective checkout resolves borrowing"),
1863        }
1864    }
1865
1866    /// Resolve the display name shared by session headings, chat headers, and
1867    /// resume details for a bundle-backed session.
1868    fn bundle_source_name(&self, config: &Config) -> String {
1869        self.bundle_source_identity(config)
1870            .map(|source| source.short)
1871            .unwrap_or_else(|| path_leaf(Path::new(&self.bundle_id)))
1872    }
1873
1874    /// Resolve the canonical identity of every repository in a bundle for
1875    /// grouping and display naming.
1876    fn bundle_source_identity(&self, config: &Config) -> Option<ProjectSourceIdentity> {
1877        let bundle = self.project_bundle(config)?;
1878        let sources = bundle
1879            .repositories
1880            .iter()
1881            .map(repository_source_identity)
1882            .collect::<Option<Vec<_>>>()?;
1883        ProjectSourceIdentity::bundle(sources)
1884    }
1885
1886    /// The accepted definition survives saved-project merges and config edits.
1887    pub fn project_bundle<'a>(
1888        &'a self,
1889        config: &'a Config,
1890    ) -> Option<&'a crate::config::ProjectBundle> {
1891        self.project
1892            .as_ref()
1893            .map(|project| &project.bundle)
1894            .or_else(|| config.bundles.get(&self.bundle_id))
1895    }
1896
1897    /// Orders two sessions the way the session list's sequence view does:
1898    /// oldest first by creation time, with the id as a stable tiebreak. A
1899    /// session whose timestamp does not parse sorts last.
1900    pub fn compare_by_creation(&self, other: &Self) -> std::cmp::Ordering {
1901        self.creation_order_key().cmp(&other.creation_order_key())
1902    }
1903
1904    /// Parse once per session when used with `sort_by_cached_key`.
1905    pub fn creation_order_key(&self) -> (bool, Option<i64>, &str) {
1906        let timestamp = created_at_seconds(&self.created_at);
1907        (timestamp.is_none(), timestamp, &self.id)
1908    }
1909
1910    fn validate(&self, map_id: &str) -> Result<()> {
1911        validate_id("session", &self.id)?;
1912        if self.id != map_id {
1913            bail!(
1914                "session map key {map_id:?} does not match record id {:?}",
1915                self.id
1916            );
1917        }
1918        if let Some(project) = &self.project {
1919            project.key()?;
1920        }
1921        validate_id("workspace", &self.workspace_id)?;
1922        validate_id("profile", &self.last_profile)?;
1923        validate_id("bundle", &self.bundle_id)?;
1924        if let Some(project_directory) = &self.project_directory
1925            && (!crate::target_path::is_absolute_on_host_or_target(project_directory)
1926                || project_directory
1927                    .components()
1928                    .any(|part| part == Component::ParentDir))
1929        {
1930            bail!("session {:?} has an unsafe project directory", self.id);
1931        }
1932        if let Some(managed_worktree) = &self.managed_worktree {
1933            managed_worktree.validate(&self.id, self.project_directory.as_deref())?;
1934        }
1935        validate_id("target template", &self.target_template_id)?;
1936        if let Some(allocation) = &self.resource_allocation {
1937            allocation.validate()?;
1938        }
1939        validate_additional_mounts(&self.additional_mounts)?;
1940        if self.title.trim().is_empty() {
1941            bail!("session {:?} has an empty title", self.id);
1942        }
1943        if self
1944            .acp_session_title
1945            .as_ref()
1946            .is_some_and(|title| title.trim().is_empty())
1947            || self
1948                .session_title_override
1949                .as_ref()
1950                .is_some_and(|title| title.trim().is_empty())
1951        {
1952            bail!("session {:?} has an empty display title", self.id);
1953        }
1954        if self.created_at.trim().is_empty() || self.updated_at.trim().is_empty() {
1955            bail!("session {:?} has an empty timestamp", self.id);
1956        }
1957        if let Some(target) = &self.target {
1958            target.validate(&self.id)?;
1959        }
1960        if let Some(checkpoint) = &self.checkpoint {
1961            checkpoint.validate()?;
1962        }
1963        Ok(())
1964    }
1965}
1966
1967fn repository_source_identity(repository: &ProjectRepository) -> Option<ProjectSourceIdentity> {
1968    repository
1969        .github
1970        .as_deref()
1971        .and_then(ProjectSourceIdentity::git_remote)
1972        .or_else(|| {
1973            repository
1974                .local
1975                .as_deref()
1976                .map(|path| ProjectSourceIdentity::path(path, None))
1977        })
1978}
1979
1980#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
1981pub struct ProjectSourceIdentity {
1982    pub key: String,
1983    pub short: String,
1984    pub full: String,
1985}
1986
1987impl ProjectSourceIdentity {
1988    /// Combine repository identities into one stable bundle identity.
1989    pub fn bundle(mut sources: Vec<Self>) -> Option<Self> {
1990        if sources.is_empty() {
1991            return None;
1992        }
1993        sources.sort_by(|left, right| {
1994            left.key
1995                .cmp(&right.key)
1996                .then_with(|| left.full.cmp(&right.full))
1997                .then_with(|| left.short.cmp(&right.short))
1998        });
1999        sources.dedup_by(|left, right| left.key == right.key);
2000        if sources.len() == 1 {
2001            return sources.pop();
2002        }
2003        let keys = sources
2004            .iter()
2005            .map(|source| source.key.clone())
2006            .collect::<Vec<_>>();
2007        let key = serde_json::to_string(&keys).ok()?;
2008        Some(Self {
2009            key: format!("bundle:{key}"),
2010            short: sources
2011                .iter()
2012                .map(|source| source.short.as_str())
2013                .collect::<Vec<_>>()
2014                .join(" + "),
2015            full: sources
2016                .iter()
2017                .map(|source| source.full.as_str())
2018                .collect::<Vec<_>>()
2019                .join(" + "),
2020        })
2021    }
2022
2023    /// Canonicalizes a Git remote so raw checkouts group as the same project
2024    /// even when their worktree paths differ.
2025    pub fn git_remote(source: &str) -> Option<Self> {
2026        let identity = crate::repository::RepositoryIdentity::from_remote(source)?;
2027        let full = crate::repository::RepositoryIdentity::remote_label(source)?;
2028        Some(Self {
2029            key: identity.key(),
2030            short: full.rsplit(['/', ':']).next()?.to_owned(),
2031            full,
2032        })
2033    }
2034
2035    /// Build a local-root identity, qualified by host for remote directories.
2036    /// The directory is the session target's, so its text is POSIX.
2037    pub fn path(path: &Path, remote: Option<&str>) -> Self {
2038        let normalized = path.components().collect::<PathBuf>();
2039        let path_text = crate::target_path::text(&normalized);
2040        let full = remote.map_or_else(|| path_text.clone(), |host| format!("{host}:{path_text}"));
2041        let key = remote.map_or_else(
2042            || format!("path:{path_text}"),
2043            |host| format!("path:{}:{path_text}", host.to_lowercase()),
2044        );
2045        Self {
2046            key,
2047            short: path_leaf(path),
2048            full,
2049        }
2050    }
2051}
2052
2053/// Last component of a path, falling back to the whole path when it has none.
2054fn path_leaf(path: &Path) -> String {
2055    path.file_name()
2056        .unwrap_or(path.as_os_str())
2057        .to_string_lossy()
2058        .into_owned()
2059}
2060
2061fn created_at_seconds(timestamp: &str) -> Option<i64> {
2062    chrono::DateTime::parse_from_rfc3339(timestamp)
2063        .ok()
2064        .map(|timestamp| timestamp.timestamp())
2065}
2066
2067#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2068#[serde(deny_unknown_fields)]
2069pub struct State {
2070    #[serde(default)]
2071    pub last_subagent_policy: crate::subagent::SubagentPolicy,
2072    pub version: u32,
2073    #[serde(default, skip_serializing_if = "SnapshotMap::is_empty")]
2074    pub sessions: SnapshotMap<String, SessionRecord>,
2075    /// Child sessions keyed by their session id. The relationship lives in
2076    /// controller state so every control surface sees the same session family.
2077    #[serde(default, skip_serializing_if = "SnapshotMap::is_empty")]
2078    pub subagents: SnapshotMap<String, SubagentRecord>,
2079    /// Recently used source directories, keyed by `local` or SSH host name.
2080    #[serde(default, skip_serializing_if = "SnapshotMap::is_empty")]
2081    pub mount_history: SnapshotMap<String, Vec<PathBuf>>,
2082    /// Most recently launched container size on each physical target host.
2083    #[serde(default, skip_serializing_if = "SnapshotMap::is_empty")]
2084    pub container_sizes: SnapshotMap<String, HostContainerSize>,
2085}
2086
2087impl Default for State {
2088    fn default() -> Self {
2089        Self {
2090            version: STATE_VERSION,
2091            last_subagent_policy: Default::default(),
2092            sessions: SnapshotMap::new(),
2093            subagents: SnapshotMap::new(),
2094            mount_history: SnapshotMap::new(),
2095            container_sizes: SnapshotMap::new(),
2096        }
2097    }
2098}
2099
2100/// The effective code checkout for one session, including who owns it.
2101///
2102/// These variants are derived from the durable session record and the
2103/// `State::subagents` relationship. They are not serialized. In particular,
2104/// the creation-time `create_managed_worktree` choice is not evidence of
2105/// current checkout ownership.
2106#[derive(Debug, Clone, PartialEq, Eq)]
2107pub enum Checkout<'a> {
2108    /// A user-selected raw directory. Mjolnir never creates or removes it.
2109    Attached { path: &'a Path },
2110    /// A raw project worktree or clone created and retired by Mjolnir.
2111    ///
2112    /// `project_directory` can be absent only on an incomplete legacy record;
2113    /// ownership still follows the managed-worktree descriptor. For valid
2114    /// records it can be below `worktree_root` when the project is a
2115    /// subdirectory of its repository.
2116    ManagedWorktree {
2117        worktree: &'a ManagedWorktree,
2118        project_directory: Option<&'a Path>,
2119    },
2120    /// A bundle workspace cloned on the target and retired with its target.
2121    /// Its target path is platform-specific and is derived by provisioning.
2122    ManagedWorkspace,
2123    /// A child session uses the parent's checkout and never owns its lifetime.
2124    Borrowed {
2125        owner: &'a SessionRecord,
2126        checkout: Box<Checkout<'a>>,
2127    },
2128}
2129
2130/// The only conversion from persisted checkout fields to an ownership kind.
2131fn derive_record_checkout(session: &SessionRecord) -> Checkout<'_> {
2132    if let Some(worktree) = &session.managed_worktree {
2133        return Checkout::ManagedWorktree {
2134            worktree,
2135            project_directory: session.project_directory.as_deref(),
2136        };
2137    }
2138    if let Some(path) = session.project_directory.as_deref() {
2139        return Checkout::Attached { path };
2140    }
2141    Checkout::ManagedWorkspace
2142}
2143
2144impl<'a> Checkout<'a> {
2145    /// The managed worktree owned by this session, if any. A borrowed child
2146    /// intentionally gets `None` even when its owner uses a managed checkout.
2147    #[must_use]
2148    pub fn managed_worktree(&self) -> Option<&'a ManagedWorktree> {
2149        match self {
2150            Self::ManagedWorktree { worktree, .. } => Some(*worktree),
2151            Self::Attached { .. } | Self::ManagedWorkspace | Self::Borrowed { .. } => None,
2152        }
2153    }
2154
2155    /// Resolve a borrowed checkout to the value that describes its location.
2156    /// The outer [`Checkout::Borrowed`] variant still controls cleanup: a
2157    /// child must never retire the managed checkout it borrows.
2158    #[must_use]
2159    pub fn effective(&self) -> Checkout<'a> {
2160        match self {
2161            Self::Borrowed { checkout, .. } => checkout.effective(),
2162            checkout => checkout.clone(),
2163        }
2164    }
2165
2166    /// The concrete repository directory when the record stores one.
2167    /// Bundle workspace paths are target-specific and are not in the record.
2168    #[must_use]
2169    pub fn project_directory(&self) -> Option<&'a Path> {
2170        match self {
2171            Self::Attached { path } => Some(*path),
2172            Self::ManagedWorktree {
2173                project_directory, ..
2174            } => *project_directory,
2175            Self::ManagedWorkspace => None,
2176            Self::Borrowed { checkout, .. } => checkout.project_directory(),
2177        }
2178    }
2179}
2180
2181/// Whether a terminal dashboard follows `record` live through the runtime
2182/// feed. Stopped is the one settled state that accumulates, so a stopped
2183/// session is left to the resume dialog unless something still holds it:
2184/// a lifecycle operation or move in flight (`in_operation`), or a live
2185/// parent whose Sub-agents view shows it (`parent_live`). Lost and
2186/// data-loss sessions stay live: they are unsettled failures that need
2187/// attention.
2188pub fn session_is_live(record: &SessionRecord, in_operation: bool, parent_live: bool) -> bool {
2189    record.state != SessionState::Stopped || in_operation || parent_live
2190}
2191
2192/// Every session [`session_is_live`] keeps, given the ids that have an
2193/// operation in flight. A stopped sub-agent follows its parent, so
2194/// membership settles parent before child.
2195pub fn live_session_ids(
2196    sessions: &SnapshotMap<String, SessionRecord>,
2197    subagents: &SnapshotMap<String, SubagentRecord>,
2198    operations: &BTreeSet<String>,
2199) -> BTreeSet<String> {
2200    let mut live = sessions
2201        .iter()
2202        .filter(|(id, record)| session_is_live(record, operations.contains(*id), false))
2203        .map(|(id, _)| id.clone())
2204        .collect::<BTreeSet<_>>();
2205    loop {
2206        let joined = subagents
2207            .iter()
2208            .filter(|(child, relation)| {
2209                !live.contains(*child)
2210                    && sessions.contains_key(*child)
2211                    && live.contains(&relation.parent_session_id)
2212            })
2213            .map(|(child, _)| child.clone())
2214            .collect::<Vec<_>>();
2215        if joined.is_empty() {
2216            return live;
2217        }
2218        live.extend(joined);
2219    }
2220}
2221
2222impl State {
2223    /// Derive the checkout location and its owner for a session.
2224    ///
2225    /// Raw directory sessions with no managed-worktree descriptor are
2226    /// attached even when they have no Git project snapshot (the supported
2227    /// non-Git bare-target case). A descriptor takes precedence if both raw
2228    /// fields are present, because it is the cleanup authority; the stored
2229    /// project path is retained as the checkout directory, even if an invalid
2230    /// legacy record disagrees with the descriptor's root. Record validation
2231    /// rejects that mismatch. With neither field present, old bundle-backed
2232    /// records map to a managed workspace whether their bundle came from config
2233    /// or a saved project snapshot. A managed sub-agent is resolved through its
2234    /// durable parent relation first, so its copied `project_directory` never
2235    /// changes ownership. Nested children keep the chain of borrowed owners.
2236    /// An orphan child whose parent record has already been removed falls
2237    /// back to its stored checkout fields, preserving the older cleanup path.
2238    pub fn checkout(&self, session_id: &str) -> Result<Checkout<'_>> {
2239        let session = self
2240            .sessions
2241            .get(session_id)
2242            .with_context(|| format!("unknown session {session_id}"))?;
2243        self.checkout_for_record(session_id, session)
2244    }
2245
2246    /// Derive checkout ownership for a projected record while retaining the
2247    /// durable sub-agent relationship from this state snapshot.
2248    pub fn checkout_for_record<'a>(
2249        &'a self,
2250        session_id: &str,
2251        session: &'a SessionRecord,
2252    ) -> Result<Checkout<'a>> {
2253        self.checkout_for_record_inner(session_id, session, &mut BTreeSet::new())
2254    }
2255
2256    fn checkout_for_record_inner<'a>(
2257        &'a self,
2258        session_id: &str,
2259        session: &'a SessionRecord,
2260        visited: &mut BTreeSet<String>,
2261    ) -> Result<Checkout<'a>> {
2262        if !visited.insert(session_id.to_owned()) {
2263            bail!("sub-agent checkout ownership contains a cycle at {session_id}");
2264        }
2265        if let Some(relation) = self.subagents.get(session_id) {
2266            let Some(owner) = self.sessions.get(&relation.parent_session_id) else {
2267                return Ok(session.checkout());
2268            };
2269            return Ok(Checkout::Borrowed {
2270                owner,
2271                checkout: Box::new(self.checkout_for_record_inner(&owner.id, owner, visited)?),
2272            });
2273        }
2274        Ok(session.checkout())
2275    }
2276
2277    /// How a notice names a session: the title the session list shows
2278    /// (`listed_title`, which includes the title it was created with), or its
2279    /// short id when it has no title or its record is gone (launch findings
2280    /// B-3, R5-5 and R8-3).
2281    #[must_use]
2282    pub fn session_notice_name(&self, session_id: &str) -> String {
2283        match self.sessions.get(session_id) {
2284            Some(session) if session.listed_title() != session.id => {
2285                session.listed_title().to_owned()
2286            }
2287            _ => short_id(session_id).to_owned(),
2288        }
2289    }
2290
2291    /// The session whose project identity names a row.
2292    ///
2293    /// A sub-agent child runs inside its parent's workspace and owns no
2294    /// managed worktree, so its own `project_directory` is the parent's
2295    /// worktree checkout, whose directory is named after the parent session
2296    /// id. Reading the project identity from the parent instead keeps a child
2297    /// under the same project heading and target label as the session it
2298    /// belongs to.
2299    #[must_use]
2300    pub fn project_identity_session<'a>(&'a self, session: &'a SessionRecord) -> &'a SessionRecord {
2301        self.subagents
2302            .get(&session.id)
2303            .and_then(|record| self.sessions.get(&record.parent_session_id))
2304            .unwrap_or(session)
2305    }
2306
2307    /// Whether `id` names a sub-agent rather than a session the user started:
2308    /// a Mjolnir-managed child, or the record a client builds to show a
2309    /// harness-owned child (see [`crate::native_agent::view_id`]).
2310    ///
2311    /// Every list of top-level sessions filters with this, so the lists
2312    /// cannot disagree about what a sub-agent is.
2313    #[must_use]
2314    pub fn is_subagent_session(&self, id: &str) -> bool {
2315        self.subagents.contains_key(id) || crate::native_agent::is_view_id(id)
2316    }
2317
2318    pub fn validate(&self) -> Result<()> {
2319        if self.version != STATE_VERSION {
2320            bail!(
2321                "unsupported Mjolnir state version {}; expected {STATE_VERSION}",
2322                self.version
2323            );
2324        }
2325        for (id, session) in &self.sessions {
2326            session.validate(id)?;
2327        }
2328        for child_id in self.subagents.keys() {
2329            self.validate_subagent(child_id)?;
2330        }
2331        for (host, sources) in &self.mount_history {
2332            if host.trim().is_empty() {
2333                bail!("mount history contains an empty host key");
2334            }
2335            if sources
2336                .iter()
2337                .any(|source| !crate::target_path::is_absolute_on_host_or_target(source))
2338            {
2339                bail!("mount history for {host:?} contains a non-absolute source path");
2340            }
2341        }
2342        for (host, size) in &self.container_sizes {
2343            if host.trim().is_empty() {
2344                bail!("container size history contains an empty host key");
2345            }
2346            if size.cpus == 0 || size.memory_bytes == 0 {
2347                bail!("container size history for {host:?} contains a zero value");
2348            }
2349            if size.cpus > i64::MAX as u64 || size.memory_bytes > i64::MAX as u64 {
2350                bail!("container size history for {host:?} exceeds SQLite integer range");
2351            }
2352        }
2353        Ok(())
2354    }
2355
2356    /// Validate one relationship after an incremental committed update.
2357    pub fn validate_subagent(&self, child_id: &str) -> Result<()> {
2358        let Some(subagent) = self.subagents.get(child_id) else {
2359            return Ok(());
2360        };
2361        if child_id != subagent.child_session_id {
2362            bail!("sub-agent key {child_id:?} does not match its child session id");
2363        }
2364        if child_id == subagent.parent_session_id {
2365            bail!("sub-agent {child_id:?} cannot be its own parent");
2366        }
2367        if !self.sessions.contains_key(child_id) {
2368            bail!("sub-agent {child_id:?} has no child session");
2369        }
2370        if !self.sessions.contains_key(&subagent.parent_session_id) {
2371            bail!(
2372                "sub-agent {child_id:?} has unknown parent {:?}",
2373                subagent.parent_session_id
2374            );
2375        }
2376        if self.subagents.contains_key(&subagent.parent_session_id) {
2377            bail!("sub-agent {child_id:?} cannot belong to another sub-agent");
2378        }
2379        if subagent.task_name.trim().is_empty()
2380            || subagent.profile_id.trim().is_empty()
2381            || subagent.request_key.trim().is_empty()
2382        {
2383            bail!("sub-agent {child_id:?} has incomplete relationship metadata");
2384        }
2385        Ok(())
2386    }
2387
2388    pub fn remember_mount_sources(&mut self, host: &str, mounts: &[AdditionalMount]) {
2389        if mounts.is_empty() {
2390            return;
2391        }
2392        let sources = self
2393            .mount_history
2394            .entry(host.to_owned())
2395            .or_insert_with(Vec::new);
2396        for mount in mounts.iter().rev() {
2397            sources.retain(|source| source != &mount.source);
2398            sources.insert(0, mount.source.clone());
2399        }
2400        sources.truncate(20);
2401    }
2402
2403    pub fn remember_container_size(&mut self, host: &str, size: HostContainerSize) {
2404        self.container_sizes.insert(host.to_owned(), size);
2405    }
2406
2407    pub fn project_directories(&self, host: &str) -> &[PathBuf] {
2408        self.mount_history
2409            .get(&project_history_key(host))
2410            .map(Vec::as_slice)
2411            .unwrap_or_default()
2412    }
2413
2414    pub fn remember_project_directory(&mut self, host: &str, directory: &Path) {
2415        let key = project_history_key(host);
2416        let directories = self.mount_history.entry(key).or_insert_with(Vec::new);
2417        directories.retain(|existing| existing != directory);
2418        directories.insert(0, directory.to_path_buf());
2419        directories.truncate(20);
2420    }
2421
2422    pub fn destroy_stopped_session(&mut self, session_id: &str) -> Result<SessionRecord> {
2423        let session = self
2424            .sessions
2425            .get(session_id)
2426            .with_context(|| format!("unknown session {session_id}"))?;
2427        if session.state.is_active() {
2428            bail!("refusing to destroy active session {session_id}");
2429        }
2430        Ok(self
2431            .sessions
2432            .remove(session_id)
2433            .expect("session checked above"))
2434    }
2435
2436    /// Remove a session record from state regardless of its lifecycle state.
2437    ///
2438    /// Force destruction is the one caller: by the time it runs, every
2439    /// external artifact has been torn down or its loss accepted, so no state
2440    /// is refused here.
2441    pub fn destroy_session_force(&mut self, session_id: &str) -> Result<SessionRecord> {
2442        self.sessions
2443            .get(session_id)
2444            .with_context(|| format!("unknown session {session_id}"))?;
2445        Ok(self
2446            .sessions
2447            .remove(session_id)
2448            .expect("session checked above"))
2449    }
2450
2451    /// Sessions that still read `bundle_id` from the config. A suspended
2452    /// session counts: resume looks its project up again. Only a session
2453    /// opened on a plain directory, or one whose data is already gone, does
2454    /// not need it.
2455    pub fn bundle_users(&self, bundle_id: &str) -> Vec<&SessionRecord> {
2456        self.sessions
2457            .values()
2458            .filter(|session| {
2459                session.bundle_id == bundle_id
2460                    && self
2461                        .checkout(&session.id)
2462                        .is_ok_and(|checkout| checkout.project_directory().is_none())
2463                    && session.state != SessionState::DestroyedWithDataLoss
2464            })
2465            .collect()
2466    }
2467
2468    /// Why `bundle_id` cannot be removed from the config, or `None` when no
2469    /// session uses it.
2470    pub fn bundle_removal_refusal(&self, bundle_id: &str) -> Option<String> {
2471        let users = self.bundle_users(bundle_id);
2472        if users.is_empty() {
2473            return None;
2474        }
2475        let mut names = users
2476            .iter()
2477            .take(3)
2478            .map(|session| format!("{:?}", session.listed_title()))
2479            .collect::<Vec<_>>();
2480        if users.len() > 3 {
2481            names.push(format!("{} more", users.len() - 3));
2482        }
2483        Some(format!(
2484            "Project {bundle_id:?} is used by {}: {}. Destroy those sessions before removing it.",
2485            if users.len() == 1 {
2486                "a session"
2487            } else {
2488                "sessions"
2489            },
2490            names.join(", ")
2491        ))
2492    }
2493
2494    /// Setup may add replacements under new names, but must not rewrite
2495    /// dependencies still owned by active sessions.
2496    pub fn validate_setup_update(&self, before: &Config, after: &Config) -> Result<()> {
2497        for session in self
2498            .sessions
2499            .values()
2500            .filter(|session| session.state.is_active())
2501        {
2502            let protected = if let Some(profile) = before.profiles.get(&session.last_profile) {
2503                let mut comparable = profile.clone();
2504                if let Some(updated) = after.profiles.get(&session.last_profile) {
2505                    comparable.enabled = updated.enabled;
2506                    comparable.subagents = updated.subagents.clone();
2507                }
2508                // A mismatched harness is already broken; allow repairing it.
2509                profile.kind == session.harness_kind
2510                    && after.profiles.get(&session.last_profile) != Some(&comparable)
2511            } else {
2512                false
2513            };
2514            let bundle_changed = self
2515                .checkout(&session.id)
2516                .is_ok_and(|checkout| checkout.project_directory().is_none())
2517                && before
2518                    .bundles
2519                    .get(&session.bundle_id)
2520                    .is_some_and(|bundle| after.bundles.get(&session.bundle_id) != Some(bundle));
2521            // Build cache settings are resolved at provisioning time and kept
2522            // on the session record, so editing them does not disturb a
2523            // running session.
2524            let target_changed =
2525                before
2526                    .targets
2527                    .get(&session.target_template_id)
2528                    .is_some_and(|target| {
2529                        after
2530                            .targets
2531                            .get(&session.target_template_id)
2532                            .map(TargetTemplate::without_launch_only_settings)
2533                            != Some(target.without_launch_only_settings())
2534                    });
2535            if protected || bundle_changed || target_changed {
2536                // Named as the screen names them: the session by its title,
2537                // the project by its name rather than the internal bundle
2538                // id, and only the parts this change touches.
2539                let mut used = Vec::new();
2540                if protected {
2541                    used.push(format!("agent profile {:?}", session.last_profile));
2542                }
2543                if bundle_changed {
2544                    used.push(format!("project {:?}", session.project_name(before)));
2545                }
2546                if target_changed {
2547                    used.push(format!("runtime {:?}", session.target_template_id));
2548                }
2549                let used = match used.as_slice() {
2550                    [only] => only.clone(),
2551                    [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
2552                    [] => unreachable!("something changed"),
2553                };
2554                let title = session.display_title();
2555                let named = if title == session.id {
2556                    format!(
2557                        "a running session in project {:?}",
2558                        session.project_name(before)
2559                    )
2560                } else {
2561                    format!("the running session {title:?}")
2562                };
2563                bail!(
2564                    "Setup would change the {used} that {named} uses. Save the new settings under a new name, or stop the session first."
2565                );
2566            }
2567        }
2568        Ok(())
2569    }
2570
2571    /// Strict validation for callers that need all active references intact.
2572    pub fn validate_against_config(&self, config: &Config) -> Result<()> {
2573        self.validate()?;
2574        config.validate()?;
2575        for session in self.sessions.values() {
2576            session.validate_configuration(config)?;
2577        }
2578        Ok(())
2579    }
2580}
2581
2582fn project_history_key(host: &str) -> String {
2583    format!("project:{host}")
2584}
2585
2586/// Generate an opaque, filesystem-safe stable id for a new logical session.
2587pub fn new_session_id() -> Result<String> {
2588    let mut random = [0u8; 16];
2589    getrandom::fill(&mut random)
2590        .map_err(|error| anyhow::anyhow!("generate Mjolnir session id: {error}"))?;
2591    Ok(crate::hex::lower_hex(random))
2592}
2593
2594/// Return the newest clean ACP session title from canonical worker events.
2595pub fn harness_session_title(events: &[SequencedEvent]) -> Option<String> {
2596    events.iter().rev().find_map(|event| {
2597        let WorkerEvent::Adapter { payload, .. } = &event.event else {
2598            return None;
2599        };
2600        let crate::acp::RuntimeEvent::SessionUpdate { update } =
2601            serde_json::from_value(payload.clone()).ok()?
2602        else {
2603            return None;
2604        };
2605        let kind = update
2606            .get("sessionUpdate")
2607            .and_then(serde_json::Value::as_str)?;
2608        let title = match kind {
2609            "session_info_update" | "session_title" => {
2610                update.get("title").and_then(serde_json::Value::as_str)
2611            }
2612            _ => None,
2613        }?;
2614        normalize_session_title(title)
2615    })
2616}
2617
2618/// The title a new session gets when whoever starts it gives none: the name
2619/// of its project directory (or its bundle id) and the profile, such as
2620/// "project via fake". The dashboard, the HTTP API, and `mj new` all use it,
2621/// so a session reads the same way whichever surface started it.
2622pub fn default_session_title(
2623    project_directory: Option<&Path>,
2624    bundle_id: &str,
2625    profile_id: &str,
2626) -> String {
2627    let project = project_directory.and_then(Path::file_name).map_or_else(
2628        || bundle_id.to_owned(),
2629        |name| name.to_string_lossy().into_owned(),
2630    );
2631    format!("{project} via {profile_id}")
2632}
2633
2634pub const MAX_SESSION_TITLE_CHARS: usize = 256;
2635
2636/// Clean a title and bound it at a word boundary, including the ellipsis.
2637pub fn normalize_session_title(title: &str) -> Option<String> {
2638    let normalized = crate::relay::strip_hidden_prompt_context(title)
2639        .split_whitespace()
2640        .collect::<Vec<_>>()
2641        .join(" ");
2642    (!normalized.is_empty()).then(|| truncate_session_title(normalized, MAX_SESSION_TITLE_CHARS))
2643}
2644
2645fn truncate_session_title(title: String, maximum_chars: usize) -> String {
2646    if title.chars().count() <= maximum_chars {
2647        return title;
2648    }
2649
2650    let mut truncated = title.chars().take(maximum_chars - 1).collect::<String>();
2651    if let Some(boundary) = truncated.rfind(char::is_whitespace) {
2652        truncated.truncate(boundary);
2653    }
2654    truncated.push('…');
2655    truncated
2656}
2657
2658/// Build the short-lived title shown before the harness supplies its own.
2659///
2660/// The first visible user prompt is immediately useful for identifying a
2661/// session, but it can be arbitrarily large. Keep this fallback bounded; a
2662/// later ACP session-info update remains authoritative and replaces it.
2663pub fn provisional_session_title(prompt: &str) -> Option<String> {
2664    const MAX_TITLE_CHARS: usize = 64;
2665
2666    let normalized = normalize_session_title(prompt)?;
2667    Some(truncate_session_title(normalized, MAX_TITLE_CHARS))
2668}
2669
2670pub fn short_id(id: &str) -> &str {
2671    id.get(..8).unwrap_or(id)
2672}
2673
2674#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
2675pub struct RecoveryCandidate {
2676    pub session_id: String,
2677    pub target_template_id: String,
2678    pub locator: TargetLocator,
2679    pub ownership: Option<crate::worker_launch::WorkerOwnership>,
2680    /// Instance that created the worker, from its label or tag, else from
2681    /// the ownership marker. `None` means an older build left no stamp.
2682    #[serde(default)]
2683    pub instance_id: Option<String>,
2684    /// State of the session this resource is labelled for, when the
2685    /// controller still tracks that session. A leftover resource the session
2686    /// record no longer names can only be destroyed, never adopted, because
2687    /// the session id is already taken.
2688    #[serde(default, skip_serializing_if = "Option::is_none")]
2689    pub tracked_session: Option<SessionState>,
2690}
2691
2692#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
2693pub struct RecoveryScan {
2694    pub candidates: Vec<RecoveryCandidate>,
2695    pub warnings: Vec<String>,
2696    /// Identity of the instance that ran the scan.
2697    #[serde(default)]
2698    pub instance_id: String,
2699    /// Candidates left out because another or an unknown instance created
2700    /// them and the scan was not widened to all instances.
2701    #[serde(default)]
2702    pub hidden_other_instances: usize,
2703}
2704
2705#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2706#[serde(deny_unknown_fields)]
2707pub struct ResumeRepositorySourceReceipt {
2708    pub session_id: String,
2709    pub bundle_id: String,
2710    pub checkpoint_sha256: String,
2711    pub repositories: Vec<crate::config::ProjectRepository>,
2712}
2713
2714#[cfg(test)]
2715mod tests;