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