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