trusty_code/session/model.rs
1//! Session domain model: the daemon-owned first-class object (#2054, Axiom 4).
2//!
3//! Why: the vision spec's Axiom 4 ("The Daemon OWNS Sessions; CLI Attaches
4//! Over the API") requires a session to be a real object living inside the
5//! daemon — not a tmux pane, not a PTY, not something the CLI reconstructs
6//! from scrollback. This module defines that object's shape; ownership,
7//! storage, and the ring buffer live in `super::registry`.
8//! What: [`Session`] (the wire/domain type returned by
9//! `session.create`/`session.list`/`session.status`) and [`SessionStatus`]
10//! (its lifecycle states, per §12 Session Durability: M1 has no queueing —
11//! a session moves directly from `Created` to `Running` — and no
12//! persistence, so `Failed` here means "the daemon observed a failure", not
13//! "recovered from one after a restart").
14//! Test: `model::tests::*`.
15
16use chrono::{DateTime, Utc};
17use serde::{Deserialize, Serialize};
18
19/// Lifecycle status of a [`Session`].
20///
21/// Why: a small, closed set of states the registry can transition between
22/// and that a client can match on reliably (the wire string is stable —
23/// `#[serde(rename_all = "snake_case")]` — independent of Rust variant
24/// naming).
25/// What: `Created` -> `Running` happens immediately on `session.create` in
26/// M1 (there is no queue to sit in ahead of real task execution, which
27/// lands with `task.*` in #2056). `Cancelled`/`Finished`/`Failed`/
28/// `DeadlineExceeded` are the four terminal states; `session.cancel` is the
29/// only one #2054 can drive directly (`Finished`/`Failed`/`DeadlineExceeded`
30/// are set by `task::executor::run_and_record` when the PM's `AgentLoop`
31/// resolves). `DeadlineExceeded` (#2207) is distinct from `Failed`: it means
32/// the run's configured wall-clock budget elapsed before the PM reached a
33/// terminal state, NOT that the loop or LLM call errored — a run that hit
34/// this status may have made real, useful progress.
35/// Test: `model::tests::session_status_serialises_snake_case`.
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum SessionStatus {
39 Created,
40 Running,
41 Cancelled,
42 Finished,
43 Failed,
44 DeadlineExceeded,
45}
46
47impl SessionStatus {
48 /// Return the stable wire string for this status (matches the serde
49 /// `rename_all = "snake_case"` representation).
50 ///
51 /// Why: `crate::events::Event::SessionStatusChanged`'s `status` field is
52 /// a plain `String`, not a `SessionStatus`, so registry code needs the
53 /// wire string without round-tripping through `serde_json`.
54 /// What: a `&'static str` per variant.
55 /// Test: `model::tests::as_str_matches_serde_rename`.
56 pub fn as_str(&self) -> &'static str {
57 match self {
58 SessionStatus::Created => "created",
59 SessionStatus::Running => "running",
60 SessionStatus::Cancelled => "cancelled",
61 SessionStatus::Finished => "finished",
62 SessionStatus::Failed => "failed",
63 SessionStatus::DeadlineExceeded => "deadline_exceeded",
64 }
65 }
66
67 /// Returns `true` when this status is terminal (the session will never
68 /// transition again).
69 ///
70 /// Why: `session.cancel` and any future completion handler need to
71 /// reject transitions out of a terminal state (e.g. cancelling an
72 /// already-finished session is a no-op error, not a silent overwrite).
73 /// What: `true` for `Cancelled`/`Finished`/`Failed`/`DeadlineExceeded`;
74 /// `false` otherwise.
75 /// Test: `model::tests::is_terminal_covers_terminal_states`.
76 pub fn is_terminal(&self) -> bool {
77 matches!(
78 self,
79 SessionStatus::Cancelled
80 | SessionStatus::Finished
81 | SessionStatus::Failed
82 | SessionStatus::DeadlineExceeded
83 )
84 }
85}
86
87/// A daemon-owned session (vision spec Axiom 4).
88///
89/// Why: the wire type every `session.*` method (except `send`/`attach`/
90/// `detach`, which acknowledge rather than return a session) sends back to
91/// the caller — `session.create`, `session.list`, `session.status`.
92/// What: `id` is a UUIDv4 string; `agent`/`project` are optional because
93/// `session.create` does not require either in M1 (no real agent-loop
94/// wiring yet); `created_at` is UTC. `mode` (#2059) is `None` until
95/// `task.run` resolves and sets it (`SessionRegistry::set_mode`) — a session
96/// that has never run a task has no mode, mirroring the same "`None` means
97/// not yet run" convention `session::transcript::TranscriptRecord` already
98/// uses for `cost_usd`.
99/// Test: `model::tests::session_round_trips_through_json`.
100#[derive(Debug, Clone, Serialize, Deserialize)]
101pub struct Session {
102 pub id: String,
103 pub task: String,
104 pub agent: Option<String>,
105 pub project: Option<String>,
106 pub status: SessionStatus,
107 pub created_at: DateTime<Utc>,
108 #[serde(default)]
109 pub mode: Option<crate::mode::HarnessMode>,
110}
111
112#[cfg(test)]
113mod tests {
114 use super::*;
115 use serde_json::json;
116
117 /// The wire representation of every status must be the documented
118 /// snake_case string.
119 #[test]
120 fn session_status_serialises_snake_case() {
121 assert_eq!(
122 serde_json::to_value(SessionStatus::Created).unwrap(),
123 json!("created")
124 );
125 assert_eq!(
126 serde_json::to_value(SessionStatus::Running).unwrap(),
127 json!("running")
128 );
129 assert_eq!(
130 serde_json::to_value(SessionStatus::Cancelled).unwrap(),
131 json!("cancelled")
132 );
133 assert_eq!(
134 serde_json::to_value(SessionStatus::Finished).unwrap(),
135 json!("finished")
136 );
137 assert_eq!(
138 serde_json::to_value(SessionStatus::Failed).unwrap(),
139 json!("failed")
140 );
141 assert_eq!(
142 serde_json::to_value(SessionStatus::DeadlineExceeded).unwrap(),
143 json!("deadline_exceeded")
144 );
145 }
146
147 /// `as_str` must match the serde wire representation exactly.
148 #[test]
149 fn as_str_matches_serde_rename() {
150 for status in [
151 SessionStatus::Created,
152 SessionStatus::Running,
153 SessionStatus::Cancelled,
154 SessionStatus::Finished,
155 SessionStatus::Failed,
156 SessionStatus::DeadlineExceeded,
157 ] {
158 let via_str = status.as_str();
159 let via_serde = serde_json::to_value(status).unwrap();
160 assert_eq!(json!(via_str), via_serde);
161 }
162 }
163
164 /// Only `Cancelled`/`Finished`/`Failed`/`DeadlineExceeded` are terminal.
165 #[test]
166 fn is_terminal_covers_terminal_states() {
167 assert!(!SessionStatus::Created.is_terminal());
168 assert!(!SessionStatus::Running.is_terminal());
169 assert!(SessionStatus::Cancelled.is_terminal());
170 assert!(SessionStatus::Finished.is_terminal());
171 assert!(SessionStatus::Failed.is_terminal());
172 assert!(SessionStatus::DeadlineExceeded.is_terminal());
173 }
174
175 /// A `Session` must round-trip through JSON with the expected shape.
176 #[test]
177 fn session_round_trips_through_json() {
178 let session = Session {
179 id: "s-1".to_string(),
180 task: "do the thing".to_string(),
181 agent: Some("engineer".to_string()),
182 project: None,
183 status: SessionStatus::Running,
184 created_at: Utc::now(),
185 mode: Some(crate::mode::HarnessMode::DailyDriver),
186 };
187 let value = serde_json::to_value(&session).unwrap();
188 assert_eq!(value["id"], "s-1");
189 assert_eq!(value["status"], "running");
190 assert_eq!(value["agent"], "engineer");
191 assert!(value["project"].is_null());
192 assert_eq!(value["mode"], "daily-driver");
193
194 let back: Session = serde_json::from_value(value).unwrap();
195 assert_eq!(back.id, session.id);
196 assert_eq!(back.status, session.status);
197 assert_eq!(back.mode, session.mode);
198 }
199}