Skip to main content

ag_session/
model.rs

1//! Shared session identity, lifecycle, settings, and aggregate models.
2
3use std::borrow::Borrow;
4use std::fmt;
5use std::ops::Deref;
6use std::path::Path;
7use std::str::FromStr;
8use std::sync::Arc;
9
10use ag_agent::{AgentSelection, ReasoningLevel};
11pub use ag_agent::{PermissionMode, ResponseStyle, SpeedMode};
12pub use ag_forge::{ForgeKind, ReviewRequestState, ReviewRequestSummary};
13use ag_protocol::QuestionItem;
14use serde::de::{self, Deserializer};
15use serde::ser::Serializer;
16use serde::{Deserialize, Serialize};
17
18use crate::SessionMessage;
19
20const SESSION_BRANCH_PREFIX: &str = "wt/";
21
22/// Returns the default worktree branch name for a session.
23pub fn session_branch(session_id: &str) -> String {
24    let len = session_id.len().min(8);
25
26    format!("{SESSION_BRANCH_PREFIX}{}", &session_id[..len])
27}
28
29/// Number of seconds in one activity-calendar day.
30const SECONDS_PER_DAY: i64 = 86_400;
31
32/// Shared stable identifier for one session.
33///
34/// Session identifiers are cloned heavily across maps, events, and worker
35/// tasks. Wrapping the identifier in `Arc<str>` keeps those clones cheap while
36/// retaining borrowed `&str` lookup support.
37#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
38pub struct SessionId(Arc<str>);
39
40impl SessionId {
41    /// Returns the session identifier as a string slice.
42    pub fn as_str(&self) -> &str {
43        self.0.as_ref()
44    }
45}
46
47impl AsRef<str> for SessionId {
48    fn as_ref(&self) -> &str {
49        self.as_str()
50    }
51}
52
53impl AsRef<Path> for SessionId {
54    fn as_ref(&self) -> &Path {
55        Path::new(self.as_str())
56    }
57}
58
59impl Borrow<str> for SessionId {
60    fn borrow(&self) -> &str {
61        self.as_str()
62    }
63}
64
65impl Deref for SessionId {
66    type Target = str;
67
68    fn deref(&self) -> &Self::Target {
69        self.as_str()
70    }
71}
72
73impl fmt::Display for SessionId {
74    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
75        formatter.write_str(self.as_str())
76    }
77}
78
79impl From<&str> for SessionId {
80    fn from(value: &str) -> Self {
81        Self(Arc::<str>::from(value))
82    }
83}
84
85impl From<String> for SessionId {
86    fn from(value: String) -> Self {
87        Self(Arc::<str>::from(value))
88    }
89}
90
91impl From<Arc<str>> for SessionId {
92    fn from(value: Arc<str>) -> Self {
93        Self(value)
94    }
95}
96
97impl From<SessionId> for String {
98    fn from(value: SessionId) -> Self {
99        value.as_str().to_string()
100    }
101}
102
103impl PartialEq<str> for SessionId {
104    fn eq(&self, other: &str) -> bool {
105        self.as_str() == other
106    }
107}
108
109impl PartialEq<&str> for SessionId {
110    fn eq(&self, other: &&str) -> bool {
111        self.as_str() == *other
112    }
113}
114
115impl PartialEq<String> for SessionId {
116    fn eq(&self, other: &String) -> bool {
117        self.as_str() == other
118    }
119}
120
121impl PartialEq<&String> for SessionId {
122    fn eq(&self, other: &&String) -> bool {
123        self.as_str() == other.as_str()
124    }
125}
126
127impl Serialize for SessionId {
128    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
129    where
130        S: Serializer,
131    {
132        serializer.serialize_str(self.as_str())
133    }
134}
135
136impl<'de> Deserialize<'de> for SessionId {
137    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
138    where
139        D: Deserializer<'de>,
140    {
141        String::deserialize(deserializer)
142            .map(Self::from)
143            .map_err(de::Error::custom)
144    }
145}
146
147/// Role one session plays in a multi-session workflow.
148///
149/// The role is orthogonal to [`SessionStatus`]: an orchestrator moves through
150/// the same lifecycle states as any other session, but its worktree exists only
151/// for repository reads and never receives commits. Diff, merge, and
152/// review-request affordances are therefore gated on the role rather than on a
153/// dedicated lifecycle state.
154#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
155pub enum SessionRole {
156    /// Ordinary session that owns the changes on its own branch.
157    #[default]
158    Worker,
159    /// Worker whose write capabilities are owned exclusively by an
160    /// orchestration coordinator.
161    OrchestrationWorker,
162    /// Temporary read-only researcher whose worktree changes are discarded
163    /// after its report is captured.
164    OrchestrationResearcher,
165    /// Controller session that plans and supervises child worker sessions.
166    Orchestrator,
167}
168
169impl SessionRole {
170    /// Returns whether this role produces commits on its own session branch.
171    ///
172    /// Orchestrators read the repository to plan work but delegate every edit
173    /// to child sessions, so their branch stays empty for the session's whole
174    /// lifetime.
175    pub fn owns_branch_changes(self) -> bool {
176        matches!(self, SessionRole::Worker | SessionRole::OrchestrationWorker)
177    }
178
179    /// Returns whether Agentty should observe worktree changes after a turn.
180    ///
181    /// Research children do not own their changes, but the coordinator records
182    /// whether a child attempted edits before discarding its worktree.
183    pub fn tracks_worktree_changes(self) -> bool {
184        !matches!(self, SessionRole::Orchestrator)
185    }
186
187    /// Returns whether an end user may submit turns or branch mutations
188    /// directly to this session.
189    pub fn accepts_user_turns(self) -> bool {
190        !self.is_managed()
191    }
192
193    /// Returns whether this worker is owned by an orchestration coordinator.
194    pub fn is_managed(self) -> bool {
195        matches!(
196            self,
197            SessionRole::OrchestrationWorker | SessionRole::OrchestrationResearcher
198        )
199    }
200}
201
202impl fmt::Display for SessionRole {
203    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
204        let value = match self {
205            SessionRole::Worker => "Worker",
206            SessionRole::OrchestrationWorker => "OrchestrationWorker",
207            SessionRole::OrchestrationResearcher => "OrchestrationResearcher",
208            SessionRole::Orchestrator => "Orchestrator",
209        };
210
211        formatter.write_str(value)
212    }
213}
214
215impl FromStr for SessionRole {
216    type Err = String;
217
218    fn from_str(value: &str) -> Result<Self, Self::Err> {
219        match value {
220            "Worker" => Ok(SessionRole::Worker),
221            "OrchestrationWorker" => Ok(SessionRole::OrchestrationWorker),
222            "OrchestrationResearcher" => Ok(SessionRole::OrchestrationResearcher),
223            "Orchestrator" => Ok(SessionRole::Orchestrator),
224            _ => Err(format!("Unknown role: {value}")),
225        }
226    }
227}
228
229/// High-level lifecycle state for one session.
230#[derive(Clone, Copy, Debug, Eq, PartialEq)]
231pub enum SessionStatus {
232    /// Session has been created but has not started its first agent turn yet.
233    Draft,
234    /// An agent turn or its post-processing workflow is running.
235    InProgress,
236    /// The session is ready for user review and follow-up work.
237    Review,
238    /// The session is generating focused-review output.
239    AgentReview,
240    /// The session is waiting for model clarification responses.
241    Question,
242    /// The session is waiting in the merge queue.
243    Queued,
244    /// The session branch is being rebased.
245    Rebasing,
246    /// The session branch is being merged.
247    Merging,
248    /// A remote merge awaits local target-branch synchronization.
249    Merged,
250    /// The session completed successfully.
251    Done,
252    /// The session was canceled before completion.
253    Canceled,
254}
255
256impl SessionStatus {
257    /// Ordered list of all session statuses.
258    pub const ALL: [SessionStatus; 11] = [
259        SessionStatus::Draft,
260        SessionStatus::InProgress,
261        SessionStatus::Review,
262        SessionStatus::AgentReview,
263        SessionStatus::Question,
264        SessionStatus::Queued,
265        SessionStatus::Rebasing,
266        SessionStatus::Merging,
267        SessionStatus::Merged,
268        SessionStatus::Done,
269        SessionStatus::Canceled,
270    ];
271
272    /// Returns whether this status permits opening the chat composer.
273    pub fn allows_chat_composer(self) -> bool {
274        self.allows_session_actions()
275            || matches!(self, SessionStatus::InProgress | SessionStatus::Rebasing)
276    }
277
278    /// Returns whether this status permits idle session actions.
279    pub fn allows_session_actions(self) -> bool {
280        self.allows_review_actions()
281            || matches!(self, SessionStatus::Draft | SessionStatus::Question)
282    }
283
284    /// Returns whether this status permits opening the session diff.
285    pub fn allows_diff_view(self) -> bool {
286        self.allows_review_actions() || self.is_read_only()
287    }
288
289    /// Returns whether this status permits starting or queueing session sync.
290    pub fn allows_rebase_action(self) -> bool {
291        self.allows_review_actions() || self == SessionStatus::InProgress
292    }
293
294    /// Returns whether this status keeps review actions enabled.
295    pub fn allows_review_actions(self) -> bool {
296        matches!(self, SessionStatus::Review | SessionStatus::AgentReview)
297    }
298
299    /// Returns whether this status can seed a follow-on continuation session.
300    pub fn allows_terminal_continuation(self) -> bool {
301        matches!(self, SessionStatus::Done | SessionStatus::Canceled)
302    }
303
304    /// Returns whether this lifecycle state permits only local inspection.
305    pub fn is_read_only(self) -> bool {
306        matches!(self, SessionStatus::Merged)
307    }
308
309    /// Returns whether this status is stable enough to start a stacked child.
310    pub fn allows_stacked_child_start(self) -> bool {
311        self.allows_review_actions()
312    }
313
314    /// Returns whether this status represents branch-mutating stack work.
315    pub fn is_stack_branch_mutating(self) -> bool {
316        matches!(
317            self,
318            SessionStatus::InProgress
319                | SessionStatus::Question
320                | SessionStatus::Queued
321                | SessionStatus::Rebasing
322                | SessionStatus::Merging
323                | SessionStatus::Merged
324        )
325    }
326
327    /// Returns whether a transition to `next` is valid.
328    pub fn can_transition_to(self, next: SessionStatus) -> bool {
329        if self == next {
330            return true;
331        }
332        if self == SessionStatus::Merged {
333            return next == SessionStatus::Done;
334        }
335
336        matches!(
337            (self, next),
338            (
339                SessionStatus::Draft,
340                SessionStatus::InProgress | SessionStatus::Canceled
341            ) | (
342                SessionStatus::Draft | SessionStatus::InProgress,
343                SessionStatus::Rebasing
344            ) | (
345                SessionStatus::InProgress
346                    | SessionStatus::Queued
347                    | SessionStatus::Rebasing
348                    | SessionStatus::Merging,
349                SessionStatus::Canceled
350            ) | (SessionStatus::Review, SessionStatus::AgentReview)
351                | (SessionStatus::AgentReview, SessionStatus::Review)
352                | (
353                    SessionStatus::Review | SessionStatus::AgentReview,
354                    SessionStatus::Merged | SessionStatus::Done
355                )
356                | (
357                    SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Question,
358                    SessionStatus::InProgress
359                        | SessionStatus::Queued
360                        | SessionStatus::Rebasing
361                        | SessionStatus::Merging
362                        | SessionStatus::Canceled
363                )
364                | (
365                    SessionStatus::Queued,
366                    SessionStatus::Merging | SessionStatus::Review | SessionStatus::AgentReview
367                )
368                | (
369                    SessionStatus::InProgress | SessionStatus::Rebasing,
370                    SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Question
371                )
372                | (
373                    SessionStatus::Merging,
374                    SessionStatus::Done | SessionStatus::Review | SessionStatus::AgentReview
375                )
376        )
377    }
378}
379
380impl fmt::Display for SessionStatus {
381    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
382        let value = match self {
383            SessionStatus::Draft => "Draft",
384            SessionStatus::InProgress => "InProgress",
385            SessionStatus::Review => "Review",
386            SessionStatus::AgentReview => "AgentReview",
387            SessionStatus::Question => "Question",
388            SessionStatus::Queued => "Queued",
389            SessionStatus::Rebasing => "Rebasing",
390            SessionStatus::Merging => "Merging",
391            SessionStatus::Merged => "Merged",
392            SessionStatus::Done => "Done",
393            SessionStatus::Canceled => "Canceled",
394        };
395
396        formatter.write_str(value)
397    }
398}
399
400impl FromStr for SessionStatus {
401    type Err = String;
402
403    fn from_str(value: &str) -> Result<Self, Self::Err> {
404        match value {
405            "Draft" => Ok(SessionStatus::Draft),
406            "InProgress" | "Committing" => Ok(SessionStatus::InProgress),
407            "Review" => Ok(SessionStatus::Review),
408            "AgentReview" => Ok(SessionStatus::AgentReview),
409            "Question" => Ok(SessionStatus::Question),
410            "Queued" => Ok(SessionStatus::Queued),
411            "Rebasing" => Ok(SessionStatus::Rebasing),
412            "Merging" => Ok(SessionStatus::Merging),
413            "Merged" => Ok(SessionStatus::Merged),
414            "Done" => Ok(SessionStatus::Done),
415            "Canceled" => Ok(SessionStatus::Canceled),
416            _ => Err(format!("Unknown status: {value}")),
417        }
418    }
419}
420
421/// Complete session-scoped execution settings returned by the API.
422#[derive(Clone, Debug, Eq, PartialEq)]
423pub struct SessionSettings {
424    /// Agent provider and model selected for this session.
425    pub agent: AgentSelection,
426    /// Base branch used to create the session.
427    pub base_branch: String,
428    /// Whether the session uses deferred draft materialization.
429    pub is_draft: bool,
430    /// Immediate parent session for a stacked session.
431    pub parent_session_id: Option<SessionId>,
432    /// Provider permission mode used for future turns.
433    pub permission_mode: PermissionMode,
434    /// Workspace personality selected for future turns, when present.
435    pub personality_id: Option<String>,
436    /// Owning project identifier.
437    pub project_id: i64,
438    /// Session-scoped reasoning level.
439    pub reasoning_level: ReasoningLevel,
440    /// Session-scoped response style.
441    pub response_style: ResponseStyle,
442    /// Role this session plays in a multi-session workflow.
443    pub role: SessionRole,
444    /// Session-scoped response-speed preference.
445    pub speed_mode: SpeedMode,
446}
447
448/// Persisted forge linkage for one session.
449#[derive(Clone, Debug, Eq, PartialEq)]
450pub struct ReviewRequest {
451    /// Unix timestamp of the most recent successful refresh.
452    pub last_refreshed_at: i64,
453    /// Normalized remote summary captured at `last_refreshed_at`.
454    pub summary: ReviewRequestSummary,
455}
456
457/// Complete persisted session aggregate returned by the programmatic API.
458#[derive(Clone, Debug, Eq, PartialEq)]
459pub struct Session {
460    /// Session creation timestamp in Unix seconds.
461    pub created_at: i64,
462    /// Staged draft prompt that has not entered the durable transcript.
463    pub draft_prompt: Option<String>,
464    /// Stable session identifier.
465    pub id: SessionId,
466    /// Ordered durable transcript messages.
467    pub messages: Vec<SessionMessage>,
468    /// Published upstream branch reference, when present.
469    pub published_upstream_ref: Option<String>,
470    /// Structured clarification questions waiting for answers.
471    pub questions: Vec<QuestionItem>,
472    /// Chat messages waiting behind the active turn or queued branch action.
473    pub queued_messages: Vec<String>,
474    /// Persisted review-request linkage, when present.
475    pub review_request: Option<ReviewRequest>,
476    /// Complete session-scoped execution settings.
477    pub settings: SessionSettings,
478    /// Current lifecycle status.
479    pub status: SessionStatus,
480    /// Optional user-visible session title.
481    pub title: Option<String>,
482    /// Last update timestamp in Unix seconds.
483    pub updated_at: i64,
484}
485
486/// Converts Unix timestamp seconds to a day key after applying a UTC offset.
487pub fn activity_day_key_with_offset(timestamp_seconds: i64, utc_offset_seconds: i64) -> i64 {
488    timestamp_seconds
489        .saturating_add(utc_offset_seconds)
490        .div_euclid(SECONDS_PER_DAY)
491}
492
493#[cfg(test)]
494mod tests {
495    use super::*;
496
497    #[test]
498    fn test_session_branch_uses_first_8_chars() {
499        // Arrange
500        let session_id = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";
501
502        // Act
503        let branch = session_branch(session_id);
504
505        // Assert
506        assert_eq!(branch, "wt/a1b2c3d4");
507    }
508
509    #[test]
510    fn session_id_round_trips_json() {
511        // Arrange
512        let session_id = SessionId::from("session-1");
513
514        // Act
515        let serialized = serde_json::to_string(&session_id).expect("id should serialize");
516        let deserialized =
517            serde_json::from_str::<SessionId>(&serialized).expect("id should deserialize");
518
519        // Assert
520        assert_eq!(deserialized, session_id);
521        assert_eq!(deserialized.as_str(), "session-1");
522        assert_eq!(AsRef::<Path>::as_ref(&deserialized), Path::new("session-1"));
523    }
524
525    #[test]
526    fn session_id_supports_owned_conversions_and_comparisons() {
527        // Arrange
528        let source = Arc::<str>::from("session-1");
529        let expected = "session-1".to_string();
530
531        // Act
532        let session_id = SessionId::from(source);
533        let owned = String::from(session_id.clone());
534
535        // Assert
536        assert_eq!(session_id, expected);
537        assert_eq!(session_id, &expected);
538        assert_eq!(owned, expected);
539    }
540
541    #[test]
542    fn session_status_round_trips_persisted_values() {
543        // Arrange
544        let statuses = SessionStatus::ALL;
545
546        // Act
547        let round_tripped = statuses.map(|status| {
548            status
549                .to_string()
550                .parse::<SessionStatus>()
551                .expect("status should parse")
552        });
553
554        // Assert
555        assert_eq!(round_tripped, statuses);
556        assert_eq!(
557            "Committing"
558                .parse::<SessionStatus>()
559                .expect("legacy status should parse"),
560            SessionStatus::InProgress
561        );
562        assert!("Unknown".parse::<SessionStatus>().is_err());
563    }
564
565    #[test]
566    fn session_role_round_trips_persisted_values() {
567        // Arrange
568        let roles = [
569            SessionRole::Worker,
570            SessionRole::OrchestrationWorker,
571            SessionRole::OrchestrationResearcher,
572            SessionRole::Orchestrator,
573        ];
574
575        // Act
576        let round_tripped = roles.map(|role| {
577            role.to_string()
578                .parse::<SessionRole>()
579                .expect("role should parse")
580        });
581
582        // Assert
583        assert_eq!(round_tripped, roles);
584        assert_eq!(SessionRole::default(), SessionRole::Worker);
585        assert!("Unknown".parse::<SessionRole>().is_err());
586    }
587
588    #[test]
589    fn branch_ownership_and_tracking_follow_session_role() {
590        // Arrange / Act / Assert
591        assert!(SessionRole::Worker.owns_branch_changes());
592        assert!(SessionRole::OrchestrationWorker.owns_branch_changes());
593        assert!(!SessionRole::OrchestrationResearcher.owns_branch_changes());
594        assert!(!SessionRole::Orchestrator.owns_branch_changes());
595        assert!(SessionRole::Worker.tracks_worktree_changes());
596        assert!(SessionRole::OrchestrationResearcher.tracks_worktree_changes());
597        assert!(!SessionRole::Orchestrator.tracks_worktree_changes());
598        assert!(SessionRole::Worker.accepts_user_turns());
599        assert!(!SessionRole::OrchestrationWorker.accepts_user_turns());
600        assert!(!SessionRole::OrchestrationResearcher.accepts_user_turns());
601        assert!(SessionRole::OrchestrationWorker.is_managed());
602        assert!(SessionRole::OrchestrationResearcher.is_managed());
603    }
604
605    #[test]
606    fn merged_status_only_transitions_to_done() {
607        // Arrange
608        let status = SessionStatus::Merged;
609
610        // Act / Assert
611        assert!(status.can_transition_to(SessionStatus::Merged));
612        assert!(status.can_transition_to(SessionStatus::Done));
613        assert!(!status.can_transition_to(SessionStatus::Review));
614    }
615
616    #[test]
617    fn active_branch_work_statuses_can_transition_to_canceled() {
618        // Arrange
619        let statuses = [
620            SessionStatus::Question,
621            SessionStatus::Queued,
622            SessionStatus::Rebasing,
623            SessionStatus::Merging,
624        ];
625
626        // Act
627        let cancellation_transitions =
628            statuses.map(|status| status.can_transition_to(SessionStatus::Canceled));
629
630        // Assert
631        assert_eq!(cancellation_transitions, [true; 4]);
632    }
633
634    #[test]
635    fn terminal_continuation_is_available_for_done_and_canceled_sessions() {
636        // Arrange
637        let statuses = SessionStatus::ALL;
638
639        // Act
640        let continuation_statuses = statuses
641            .into_iter()
642            .filter(|status| status.allows_terminal_continuation())
643            .collect::<Vec<_>>();
644
645        // Assert
646        assert_eq!(
647            continuation_statuses,
648            vec![SessionStatus::Done, SessionStatus::Canceled]
649        );
650    }
651
652    #[test]
653    fn activity_day_key_applies_offsets() {
654        // Arrange / Act / Assert
655        assert_eq!(activity_day_key_with_offset(86_399, 1), 1);
656        assert_eq!(activity_day_key_with_offset(0, -1), -1);
657    }
658}