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`/`TurnCapExceeded` are the five terminal-per-call
29/// states; `session.cancel` is the only one #2054 can drive directly
30/// (`Finished`/`Failed`/`DeadlineExceeded`/`TurnCapExceeded` are set by
31/// `task::executor::run_and_record` when the PM's `AgentLoop` resolves).
32/// `DeadlineExceeded` (#2207) is distinct from `Failed`: it means the run's
33/// configured wall-clock budget elapsed before the PM reached a terminal
34/// state, NOT that the loop or LLM call errored — a run that hit this
35/// status may have made real, useful progress. `TurnCapExceeded` (#3888) is
36/// likewise distinct from `Failed`: it means this ONE `task.run` call
37/// exhausted its `AgentLoopConfig::max_turns` budget, not that the session
38/// itself failed — per epic #2343's infinite-sessions goal, the PM
39/// transcript is fully persisted and the session is resumable exactly like
40/// `Finished` (see `SessionRegistry::begin_execution`'s resume condition).
41/// Test: `model::tests::session_status_serialises_snake_case`.
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(rename_all = "snake_case")]
44pub enum SessionStatus {
45 Created,
46 Running,
47 Cancelled,
48 Finished,
49 Failed,
50 DeadlineExceeded,
51 /// This call's turn budget was exhausted — see the enum doc above (#3888).
52 TurnCapExceeded,
53}
54
55impl SessionStatus {
56 /// Return the stable wire string for this status (matches the serde
57 /// `rename_all = "snake_case"` representation).
58 ///
59 /// Why: `crate::events::Event::SessionStatusChanged`'s `status` field is
60 /// a plain `String`, not a `SessionStatus`, so registry code needs the
61 /// wire string without round-tripping through `serde_json`.
62 /// What: a `&'static str` per variant.
63 /// Test: `model::tests::as_str_matches_serde_rename`.
64 pub fn as_str(&self) -> &'static str {
65 match self {
66 SessionStatus::Created => "created",
67 SessionStatus::Running => "running",
68 SessionStatus::Cancelled => "cancelled",
69 SessionStatus::Finished => "finished",
70 SessionStatus::Failed => "failed",
71 SessionStatus::DeadlineExceeded => "deadline_exceeded",
72 SessionStatus::TurnCapExceeded => "turn_cap_exceeded",
73 }
74 }
75
76 /// Returns `true` when this status is terminal FOR THIS CALL (the
77 /// current `task.run` invocation will never transition again without a
78 /// fresh `begin_execution`).
79 ///
80 /// Why: `session.cancel` and any future completion handler need to
81 /// reject transitions out of a terminal-per-call state (e.g. cancelling
82 /// an already-finished session is a no-op, not a silent overwrite). This
83 /// is deliberately WIDER than "can never resume" — see [`Self::is_resumable`]
84 /// for the narrower "dead forever" gate (#3888).
85 /// What: `true` for `Cancelled`/`Finished`/`Failed`/`DeadlineExceeded`/
86 /// `TurnCapExceeded`; `false` otherwise.
87 /// Test: `model::tests::is_terminal_covers_terminal_states`.
88 pub fn is_terminal(&self) -> bool {
89 matches!(
90 self,
91 SessionStatus::Cancelled
92 | SessionStatus::Finished
93 | SessionStatus::Failed
94 | SessionStatus::DeadlineExceeded
95 | SessionStatus::TurnCapExceeded
96 )
97 }
98
99 /// Returns `true` when a session at this status may accept another
100 /// `task.run` via `SessionRegistry::begin_execution` — the single
101 /// authoritative "still resumable" gate (#2344 `Finished` + #3888
102 /// `TurnCapExceeded`): both mean only THIS CALL ended, not the session,
103 /// and `pm_transcript` is fully persisted either way, so the next call
104 /// continues the same conversation. `Cancelled`/`Failed`/
105 /// `DeadlineExceeded` are the genuinely dead-forever states.
106 /// Test: `model::tests::is_resumable_matches_finished_and_turn_cap_exceeded`.
107 pub fn is_resumable(&self) -> bool {
108 matches!(
109 self,
110 SessionStatus::Finished | SessionStatus::TurnCapExceeded
111 )
112 }
113}
114
115/// A daemon-owned session (vision spec Axiom 4).
116///
117/// Why: the wire type every `session.*` method (except `send`/`attach`/
118/// `detach`, which acknowledge rather than return a session) sends back to
119/// the caller — `session.create`, `session.list`, `session.status`.
120/// What: `id` is a UUIDv4 string; `agent`/`project` are optional because
121/// `session.create` does not require either in M1 (no real agent-loop
122/// wiring yet); `created_at` is UTC. `mode` (#2059) is `None` until
123/// `task.run` resolves and sets it (`SessionRegistry::set_mode`) — a session
124/// that has never run a task has no mode, mirroring the same "`None` means
125/// not yet run" convention `session::transcript::TranscriptRecord` already
126/// uses for `cost_usd`.
127///
128/// `binding` is the session's TYPED project binding (spec DOC-39 §5.5) — the
129/// single object `task.run` and `session.create` now converge on. `project`
130/// survives as the human display label but is no longer an independent source
131/// of truth: it is DERIVED from `binding` (`ProjectBinding::label`) and so can
132/// never again disagree with it. That derivation is the whole reconciliation —
133/// previously `session.create` took a free-form label that was never validated
134/// and never bound, while `task.run` took a path the label knew nothing about.
135/// Test: `model::tests::session_round_trips_through_json`,
136/// `model::tests::projectless_session_round_trips`.
137#[derive(Debug, Clone, Serialize, Deserialize)]
138pub struct Session {
139 pub id: String,
140 pub task: String,
141 pub agent: Option<String>,
142 /// Display label, derived from `binding` — see the struct docs. Kept for
143 /// wire compatibility with existing `session.list`/`session.status`
144 /// consumers that read a project name.
145 pub project: Option<String>,
146 pub status: SessionStatus,
147 pub created_at: DateTime<Utc>,
148 #[serde(default)]
149 pub mode: Option<crate::mode::HarnessMode>,
150 /// The typed three-state project binding. Defaults to projectless so an
151 /// older persisted/serialized `Session` without the field still reads back.
152 #[serde(default)]
153 pub binding: crate::binding::ProjectBinding,
154 /// (Issue #3298, DOC-48 §4.1) The workstream this session is bound to, if
155 /// any. `None` means projectless/unbound — a fully valid state (DOC-39
156 /// §4.2), not a missing one. Set exactly once, at creation
157 /// (`session::protocol::create` / `task::protocol::task_run` resolve
158 /// either an explicit `workstream_id` param or §4.2's ambient
159 /// active-workstream default before calling
160 /// `SessionRegistry::bind_workstream`); there is no setter that changes
161 /// it afterward, mirroring `binding`'s own immutability convention — see
162 /// `SessionRegistry::bind_workstream`'s docs for the enforcement point.
163 /// `#[serde(default)]` keeps an older persisted/serialized `Session`
164 /// (predating this field) reading back as unbound.
165 #[serde(default)]
166 pub workstream_id: Option<crate::workstreams::model::WorkstreamId>,
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172 use serde_json::json;
173
174 /// The wire representation of every status must be the documented
175 /// snake_case string.
176 #[test]
177 fn session_status_serialises_snake_case() {
178 assert_eq!(
179 serde_json::to_value(SessionStatus::Created).unwrap(),
180 json!("created")
181 );
182 assert_eq!(
183 serde_json::to_value(SessionStatus::Running).unwrap(),
184 json!("running")
185 );
186 assert_eq!(
187 serde_json::to_value(SessionStatus::Cancelled).unwrap(),
188 json!("cancelled")
189 );
190 assert_eq!(
191 serde_json::to_value(SessionStatus::Finished).unwrap(),
192 json!("finished")
193 );
194 assert_eq!(
195 serde_json::to_value(SessionStatus::Failed).unwrap(),
196 json!("failed")
197 );
198 assert_eq!(
199 serde_json::to_value(SessionStatus::DeadlineExceeded).unwrap(),
200 json!("deadline_exceeded")
201 );
202 assert_eq!(
203 serde_json::to_value(SessionStatus::TurnCapExceeded).unwrap(),
204 json!("turn_cap_exceeded")
205 );
206 }
207
208 /// `as_str` must match the serde wire representation exactly.
209 #[test]
210 fn as_str_matches_serde_rename() {
211 for status in [
212 SessionStatus::Created,
213 SessionStatus::Running,
214 SessionStatus::Cancelled,
215 SessionStatus::Finished,
216 SessionStatus::Failed,
217 SessionStatus::DeadlineExceeded,
218 SessionStatus::TurnCapExceeded,
219 ] {
220 let via_str = status.as_str();
221 let via_serde = serde_json::to_value(status).unwrap();
222 assert_eq!(json!(via_str), via_serde);
223 }
224 }
225
226 /// `Cancelled`/`Finished`/`Failed`/`DeadlineExceeded`/`TurnCapExceeded`
227 /// are terminal-per-call; `Finished` and `TurnCapExceeded` remain
228 /// resumable through `SessionRegistry::begin_execution`'s narrower gate
229 /// (#3888) despite being terminal here.
230 #[test]
231 fn is_terminal_covers_terminal_states() {
232 assert!(!SessionStatus::Created.is_terminal());
233 assert!(!SessionStatus::Running.is_terminal());
234 assert!(SessionStatus::Cancelled.is_terminal());
235 assert!(SessionStatus::Finished.is_terminal());
236 assert!(SessionStatus::Failed.is_terminal());
237 assert!(SessionStatus::DeadlineExceeded.is_terminal());
238 assert!(SessionStatus::TurnCapExceeded.is_terminal());
239 }
240
241 /// Only `Finished` and `TurnCapExceeded` are resumable (#3888) — the
242 /// authoritative gate `SessionRegistry::begin_execution` defers to.
243 #[test]
244 fn is_resumable_matches_finished_and_turn_cap_exceeded() {
245 assert!(!SessionStatus::Created.is_resumable());
246 assert!(!SessionStatus::Running.is_resumable());
247 assert!(!SessionStatus::Cancelled.is_resumable());
248 assert!(SessionStatus::Finished.is_resumable());
249 assert!(!SessionStatus::Failed.is_resumable());
250 assert!(!SessionStatus::DeadlineExceeded.is_resumable());
251 assert!(SessionStatus::TurnCapExceeded.is_resumable());
252 }
253
254 /// A `Session` must round-trip through JSON with the expected shape.
255 #[test]
256 fn session_round_trips_through_json() {
257 let session = Session {
258 id: "s-1".to_string(),
259 task: "do the thing".to_string(),
260 agent: Some("engineer".to_string()),
261 project: None,
262 binding: crate::binding::ProjectBinding::None,
263 status: SessionStatus::Running,
264 created_at: Utc::now(),
265 mode: Some(crate::mode::HarnessMode::DailyDriver),
266 workstream_id: None,
267 };
268 let value = serde_json::to_value(&session).unwrap();
269 assert_eq!(value["id"], "s-1");
270 assert_eq!(value["status"], "running");
271 assert_eq!(value["agent"], "engineer");
272 assert!(value["project"].is_null());
273 assert_eq!(value["mode"], "daily-driver");
274
275 let back: Session = serde_json::from_value(value).unwrap();
276 assert_eq!(back.id, session.id);
277 assert_eq!(back.status, session.status);
278 assert_eq!(back.mode, session.mode);
279 }
280}
281
282#[cfg(test)]
283mod binding_model_tests {
284 use super::*;
285
286 /// A projectless `Session` must round-trip, and a payload with NO `binding`
287 /// field at all must read back as projectless rather than failing.
288 #[test]
289 fn projectless_session_round_trips() {
290 let session = Session {
291 id: "s-1".to_string(),
292 task: "t".to_string(),
293 agent: None,
294 project: None,
295 binding: crate::binding::ProjectBinding::None,
296 status: SessionStatus::Running,
297 created_at: Utc::now(),
298 mode: None,
299 workstream_id: None,
300 };
301 let value = serde_json::to_value(&session).expect("serialize");
302 assert_eq!(value["binding"]["state"], "projectless");
303
304 let back: Session = serde_json::from_value(value).expect("deserialize");
305 assert_eq!(back.binding, crate::binding::ProjectBinding::None);
306
307 // An older payload predating the `binding` field must still read back.
308 let legacy = serde_json::json!({
309 "id": "s-2", "task": "t", "agent": null, "project": null,
310 "status": "running", "created_at": Utc::now(),
311 });
312 let back: Session =
313 serde_json::from_value(legacy).expect("legacy payload must deserialize");
314 assert_eq!(
315 back.binding,
316 crate::binding::ProjectBinding::None,
317 "a missing binding field must default to projectless"
318 );
319 assert_eq!(
320 back.workstream_id, None,
321 "a missing workstream_id field must default to unbound"
322 );
323 }
324
325 /// (Issue #3298) A `Session` bound to a workstream must round-trip that
326 /// binding through JSON.
327 #[test]
328 fn workstream_bound_session_round_trips() {
329 let ws_id = crate::workstreams::model::WorkstreamId::new();
330 let session = Session {
331 id: "s-1".to_string(),
332 task: "t".to_string(),
333 agent: None,
334 project: None,
335 binding: crate::binding::ProjectBinding::None,
336 status: SessionStatus::Running,
337 created_at: Utc::now(),
338 mode: None,
339 workstream_id: Some(ws_id),
340 };
341 let value = serde_json::to_value(&session).expect("serialize");
342 assert_eq!(value["workstream_id"], ws_id.to_string());
343
344 let back: Session = serde_json::from_value(value).expect("deserialize");
345 assert_eq!(back.workstream_id, Some(ws_id));
346 }
347}