ag-session 0.13.7

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! Shared session identity, lifecycle, settings, and aggregate models.

use std::borrow::Borrow;
use std::fmt;
use std::ops::Deref;
use std::path::Path;
use std::str::FromStr;
use std::sync::Arc;

use ag_agent::{AgentSelection, ReasoningLevel};
pub use ag_forge::{ForgeKind, ReviewRequestState, ReviewRequestSummary};
use ag_protocol::QuestionItem;
use serde::de::{self, Deserializer};
use serde::ser::Serializer;
use serde::{Deserialize, Serialize};

use crate::SessionMessage;

/// Number of seconds in one activity-calendar day.
const SECONDS_PER_DAY: i64 = 86_400;

/// Shared stable identifier for one session.
///
/// Session identifiers are cloned heavily across maps, events, and worker
/// tasks. Wrapping the identifier in `Arc<str>` keeps those clones cheap while
/// retaining borrowed `&str` lookup support.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct SessionId(Arc<str>);

impl SessionId {
    /// Returns the session identifier as a string slice.
    pub fn as_str(&self) -> &str {
        self.0.as_ref()
    }
}

impl AsRef<str> for SessionId {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl AsRef<Path> for SessionId {
    fn as_ref(&self) -> &Path {
        Path::new(self.as_str())
    }
}

impl Borrow<str> for SessionId {
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl Deref for SessionId {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl fmt::Display for SessionId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl From<&str> for SessionId {
    fn from(value: &str) -> Self {
        Self(Arc::<str>::from(value))
    }
}

impl From<String> for SessionId {
    fn from(value: String) -> Self {
        Self(Arc::<str>::from(value))
    }
}

impl From<Arc<str>> for SessionId {
    fn from(value: Arc<str>) -> Self {
        Self(value)
    }
}

impl From<SessionId> for String {
    fn from(value: SessionId) -> Self {
        value.as_str().to_string()
    }
}

impl PartialEq<str> for SessionId {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<&str> for SessionId {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

impl PartialEq<String> for SessionId {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<&String> for SessionId {
    fn eq(&self, other: &&String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl Serialize for SessionId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for SessionId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        String::deserialize(deserializer)
            .map(Self::from)
            .map_err(de::Error::custom)
    }
}

/// High-level lifecycle state for one session.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionStatus {
    /// Session has been created but has not started its first agent turn yet.
    Draft,
    /// An agent turn or its post-processing workflow is running.
    InProgress,
    /// The session is ready for user review and follow-up work.
    Review,
    /// The session is generating focused-review output.
    AgentReview,
    /// The session is waiting for model clarification responses.
    Question,
    /// The session is waiting in the merge queue.
    Queued,
    /// The session branch is being rebased.
    Rebasing,
    /// The session branch is being merged.
    Merging,
    /// A remote merge awaits local target-branch synchronization.
    Merged,
    /// The session completed successfully.
    Done,
    /// The session was canceled before completion.
    Canceled,
}

impl SessionStatus {
    /// Ordered list of all session statuses.
    pub const ALL: [SessionStatus; 11] = [
        SessionStatus::Draft,
        SessionStatus::InProgress,
        SessionStatus::Review,
        SessionStatus::AgentReview,
        SessionStatus::Question,
        SessionStatus::Queued,
        SessionStatus::Rebasing,
        SessionStatus::Merging,
        SessionStatus::Merged,
        SessionStatus::Done,
        SessionStatus::Canceled,
    ];

    /// Returns whether this status permits opening the chat composer.
    pub fn allows_chat_composer(self) -> bool {
        self.allows_session_actions()
            || matches!(self, SessionStatus::InProgress | SessionStatus::Rebasing)
    }

    /// Returns whether this status permits idle session actions.
    pub fn allows_session_actions(self) -> bool {
        self.allows_review_actions()
            || matches!(self, SessionStatus::Draft | SessionStatus::Question)
    }

    /// Returns whether this status permits opening the session diff.
    pub fn allows_diff_view(self) -> bool {
        self.allows_review_actions() || self.is_read_only()
    }

    /// Returns whether this status permits starting or queueing session sync.
    pub fn allows_rebase_action(self) -> bool {
        self.allows_review_actions() || self == SessionStatus::InProgress
    }

    /// Returns whether this status keeps review actions enabled.
    pub fn allows_review_actions(self) -> bool {
        matches!(self, SessionStatus::Review | SessionStatus::AgentReview)
    }

    /// Returns whether this status can seed a follow-on continuation session.
    pub fn allows_terminal_continuation(self) -> bool {
        matches!(self, SessionStatus::Done)
    }

    /// Returns whether this lifecycle state permits only local inspection.
    pub fn is_read_only(self) -> bool {
        matches!(self, SessionStatus::Merged)
    }

    /// Returns whether this status is stable enough to start a stacked child.
    pub fn allows_stacked_child_start(self) -> bool {
        self.allows_review_actions()
    }

    /// Returns whether this status represents branch-mutating stack work.
    pub fn is_stack_branch_mutating(self) -> bool {
        matches!(
            self,
            SessionStatus::InProgress
                | SessionStatus::Question
                | SessionStatus::Queued
                | SessionStatus::Rebasing
                | SessionStatus::Merging
                | SessionStatus::Merged
        )
    }

    /// Returns whether a transition to `next` is valid.
    pub fn can_transition_to(self, next: SessionStatus) -> bool {
        if self == next {
            return true;
        }
        if self == SessionStatus::Merged {
            return next == SessionStatus::Done;
        }

        matches!(
            (self, next),
            (
                SessionStatus::Draft,
                SessionStatus::InProgress | SessionStatus::Canceled
            ) | (
                SessionStatus::Draft | SessionStatus::InProgress,
                SessionStatus::Rebasing
            ) | (SessionStatus::InProgress, SessionStatus::Canceled)
                | (SessionStatus::Review, SessionStatus::AgentReview)
                | (SessionStatus::AgentReview, SessionStatus::Review)
                | (
                    SessionStatus::Review | SessionStatus::AgentReview,
                    SessionStatus::Merged | SessionStatus::Done
                )
                | (
                    SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Question,
                    SessionStatus::InProgress
                        | SessionStatus::Queued
                        | SessionStatus::Rebasing
                        | SessionStatus::Merging
                        | SessionStatus::Canceled
                )
                | (
                    SessionStatus::Queued,
                    SessionStatus::Merging | SessionStatus::Review | SessionStatus::AgentReview
                )
                | (
                    SessionStatus::InProgress | SessionStatus::Rebasing,
                    SessionStatus::Review | SessionStatus::AgentReview | SessionStatus::Question
                )
                | (
                    SessionStatus::Merging,
                    SessionStatus::Done | SessionStatus::Review | SessionStatus::AgentReview
                )
        )
    }
}

impl fmt::Display for SessionStatus {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let value = match self {
            SessionStatus::Draft => "Draft",
            SessionStatus::InProgress => "InProgress",
            SessionStatus::Review => "Review",
            SessionStatus::AgentReview => "AgentReview",
            SessionStatus::Question => "Question",
            SessionStatus::Queued => "Queued",
            SessionStatus::Rebasing => "Rebasing",
            SessionStatus::Merging => "Merging",
            SessionStatus::Merged => "Merged",
            SessionStatus::Done => "Done",
            SessionStatus::Canceled => "Canceled",
        };

        formatter.write_str(value)
    }
}

impl FromStr for SessionStatus {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value {
            "Draft" => Ok(SessionStatus::Draft),
            "InProgress" | "Committing" => Ok(SessionStatus::InProgress),
            "Review" => Ok(SessionStatus::Review),
            "AgentReview" => Ok(SessionStatus::AgentReview),
            "Question" => Ok(SessionStatus::Question),
            "Queued" => Ok(SessionStatus::Queued),
            "Rebasing" => Ok(SessionStatus::Rebasing),
            "Merging" => Ok(SessionStatus::Merging),
            "Merged" => Ok(SessionStatus::Merged),
            "Done" => Ok(SessionStatus::Done),
            "Canceled" => Ok(SessionStatus::Canceled),
            _ => Err(format!("Unknown status: {value}")),
        }
    }
}

/// Complete session-scoped execution settings returned by the API.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionSettings {
    /// Agent provider and model selected for this session.
    pub agent: AgentSelection,
    /// Base branch used to create the session.
    pub base_branch: String,
    /// Whether the session uses deferred draft materialization.
    pub is_draft: bool,
    /// Parent session for a one-level stacked session.
    pub parent_session_id: Option<SessionId>,
    /// Workspace personality selected for future turns, when present.
    pub personality_id: Option<String>,
    /// Owning project identifier.
    pub project_id: i64,
    /// Session-scoped reasoning level.
    pub reasoning_level: ReasoningLevel,
}

/// Persisted forge linkage for one session.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ReviewRequest {
    /// Unix timestamp of the most recent successful refresh.
    pub last_refreshed_at: i64,
    /// Normalized remote summary captured at `last_refreshed_at`.
    pub summary: ReviewRequestSummary,
}

/// Complete persisted session aggregate returned by the programmatic API.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Session {
    /// Session creation timestamp in Unix seconds.
    pub created_at: i64,
    /// Staged draft prompt that has not entered the durable transcript.
    pub draft_prompt: Option<String>,
    /// Stable session identifier.
    pub id: SessionId,
    /// Ordered durable transcript messages.
    pub messages: Vec<SessionMessage>,
    /// Published upstream branch reference, when present.
    pub published_upstream_ref: Option<String>,
    /// Structured clarification questions waiting for answers.
    pub questions: Vec<QuestionItem>,
    /// Chat messages waiting behind the active turn or rebase.
    pub queued_messages: Vec<String>,
    /// Persisted review-request linkage, when present.
    pub review_request: Option<ReviewRequest>,
    /// Complete session-scoped execution settings.
    pub settings: SessionSettings,
    /// Current lifecycle status.
    pub status: SessionStatus,
    /// Latest persisted structured summary.
    pub summary: Option<String>,
    /// Optional user-visible session title.
    pub title: Option<String>,
    /// Last update timestamp in Unix seconds.
    pub updated_at: i64,
}

/// Converts Unix timestamp seconds to a day key after applying a UTC offset.
pub fn activity_day_key_with_offset(timestamp_seconds: i64, utc_offset_seconds: i64) -> i64 {
    timestamp_seconds
        .saturating_add(utc_offset_seconds)
        .div_euclid(SECONDS_PER_DAY)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn session_id_round_trips_json() {
        // Arrange
        let session_id = SessionId::from("session-1");

        // Act
        let serialized = serde_json::to_string(&session_id).expect("id should serialize");
        let deserialized =
            serde_json::from_str::<SessionId>(&serialized).expect("id should deserialize");

        // Assert
        assert_eq!(deserialized, session_id);
        assert_eq!(deserialized.as_str(), "session-1");
        assert_eq!(AsRef::<Path>::as_ref(&deserialized), Path::new("session-1"));
    }

    #[test]
    fn session_id_supports_owned_conversions_and_comparisons() {
        // Arrange
        let source = Arc::<str>::from("session-1");
        let expected = "session-1".to_string();

        // Act
        let session_id = SessionId::from(source);
        let owned = String::from(session_id.clone());

        // Assert
        assert_eq!(session_id, expected);
        assert_eq!(session_id, &expected);
        assert_eq!(owned, expected);
    }

    #[test]
    fn session_status_round_trips_persisted_values() {
        // Arrange
        let statuses = SessionStatus::ALL;

        // Act
        let round_tripped = statuses.map(|status| {
            status
                .to_string()
                .parse::<SessionStatus>()
                .expect("status should parse")
        });

        // Assert
        assert_eq!(round_tripped, statuses);
        assert_eq!(
            "Committing"
                .parse::<SessionStatus>()
                .expect("legacy status should parse"),
            SessionStatus::InProgress
        );
        assert!("Unknown".parse::<SessionStatus>().is_err());
    }

    #[test]
    fn merged_status_only_transitions_to_done() {
        // Arrange
        let status = SessionStatus::Merged;

        // Act / Assert
        assert!(status.can_transition_to(SessionStatus::Merged));
        assert!(status.can_transition_to(SessionStatus::Done));
        assert!(!status.can_transition_to(SessionStatus::Review));
    }

    #[test]
    fn activity_day_key_applies_offsets() {
        // Arrange / Act / Assert
        assert_eq!(activity_day_key_with_offset(86_399, 1), 1);
        assert_eq!(activity_day_key_with_offset(0, -1), -1);
    }
}