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