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.
105 ///
106 /// (#8207) `Cancelled` joins them. A cancel is the USER stopping one run,
107 /// not a broken session — and the TUI holds ONE session for the whole
108 /// conversation (`tui_client::engine_state::run_chat_turn` reuses the same
109 /// id for every prompt), so treating a cancelled session as dead forever
110 /// is what made the prompt after Esc fail with `-32003`. `Failed` and
111 /// `DeadlineExceeded` stay dead-forever: those ended without the user
112 /// asking, in a state the daemon cannot describe.
113 /// Test: `model::tests::is_resumable_matches_finished_turn_cap_and_cancelled`.
114 pub fn is_resumable(&self) -> bool {
115 matches!(
116 self,
117 SessionStatus::Finished | SessionStatus::TurnCapExceeded | SessionStatus::Cancelled
118 )
119 }
120}
121
122/// A daemon-owned session (vision spec Axiom 4).
123///
124/// Why: the wire type every `session.*` method (except `send`/`attach`/
125/// `detach`, which acknowledge rather than return a session) sends back to
126/// the caller — `session.create`, `session.list`, `session.status`.
127/// What: `id` is a UUIDv4 string; `agent`/`project` are optional because
128/// `session.create` does not require either in M1 (no real agent-loop
129/// wiring yet); `created_at` is UTC. `mode` (#2059) is `None` until
130/// `task.run` resolves and sets it (`SessionRegistry::set_mode`) — a session
131/// that has never run a task has no mode, mirroring the same "`None` means
132/// not yet run" convention `session::transcript::TranscriptRecord` already
133/// uses for `cost_usd`.
134///
135/// `binding` is the session's TYPED project binding (spec DOC-39 §5.5) — the
136/// single object `task.run` and `session.create` now converge on. `project`
137/// survives as the human display label but is no longer an independent source
138/// of truth: it is DERIVED from `binding` (`ProjectBinding::label`) and so can
139/// never again disagree with it. That derivation is the whole reconciliation —
140/// previously `session.create` took a free-form label that was never validated
141/// and never bound, while `task.run` took a path the label knew nothing about.
142/// Test: `model::tests::session_round_trips_through_json`,
143/// `model::tests::projectless_session_round_trips`.
144#[derive(Debug, Clone, Serialize, Deserialize)]
145pub struct Session {
146 pub id: String,
147 pub task: String,
148 pub agent: Option<String>,
149 /// Display label, derived from `binding` — see the struct docs. Kept for
150 /// wire compatibility with existing `session.list`/`session.status`
151 /// consumers that read a project name.
152 pub project: Option<String>,
153 pub status: SessionStatus,
154 pub created_at: DateTime<Utc>,
155 #[serde(default)]
156 pub mode: Option<crate::mode::HarnessMode>,
157 /// The typed three-state project binding. Defaults to projectless so an
158 /// older persisted/serialized `Session` without the field still reads back.
159 #[serde(default)]
160 pub binding: crate::binding::ProjectBinding,
161 /// (Issue #3298, DOC-48 §4.1) The workstream this session is bound to, if
162 /// any. `None` means projectless/unbound — a fully valid state (DOC-39
163 /// §4.2), not a missing one. Set exactly once, at creation
164 /// (`session::protocol::create` / `task::protocol::task_run` resolve
165 /// either an explicit `workstream_id` param or §4.2's ambient
166 /// active-workstream default before calling
167 /// `SessionRegistry::bind_workstream`); there is no setter that changes
168 /// it afterward, mirroring `binding`'s own immutability convention — see
169 /// `SessionRegistry::bind_workstream`'s docs for the enforcement point.
170 /// `#[serde(default)]` keeps an older persisted/serialized `Session`
171 /// (predating this field) reading back as unbound.
172 #[serde(default)]
173 pub workstream_id: Option<crate::workstreams::model::WorkstreamId>,
174 /// (#4351) The actionable outcome of this session's last run — where the
175 /// change landed and whether it passed — set once the run reaches a
176 /// terminal state (`crate::task::executor` -> `SessionRegistry::
177 /// set_task_result`).
178 ///
179 /// `None` until then, and OMITTED from the JSON entirely while `None`, so
180 /// every pre-#4351 consumer sees a byte-identical `session.status`
181 /// payload for a session that has never run. `#[serde(default)]` is the
182 /// other half: a persisted or hand-written snapshot predating this field
183 /// still reads back.
184 /// Test: `model::tests::session_without_result_deserialises_and_omits_it`,
185 /// `model::tests::session_round_trips_with_a_result`.
186 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub result: Option<crate::session::task_result::TaskResult>,
188 /// (#8184) Whether this session runs the SOLO agent — the #8031
189 /// single-agent shape, where the named agent carries its own tcode tools
190 /// and `delegate_to_agent` is never registered.
191 ///
192 /// Why: an interactive `tcode tui` session has to read and edit files
193 /// itself (Claude Code's basic loop), and the delegating PM registry has
194 /// no filesystem tools at all. The choice belongs to the SESSION rather
195 /// than to each `task.run`, so every turn of one conversation runs the
196 /// same agent shape and `session.status`/`session.list` can state which.
197 /// What: set once, at creation (`SessionRegistry::create_with_delegation`)
198 /// — `session.create` defaults it to `true`, `task.run`'s own mint path
199 /// carries that call's `no_delegate` through. `#[serde(default)]` reads an
200 /// older serialized `Session` back as delegating, the pre-#8184 shape.
201 /// Test: `session::protocol::tests::create_defaults_to_the_solo_agent`,
202 /// `session::protocol::tests::create_with_delegate_true_keeps_the_delegating_pm`.
203 #[serde(default)]
204 pub no_delegate: bool,
205}
206
207#[cfg(test)]
208mod tests {
209 use super::*;
210 use serde_json::json;
211
212 /// The wire representation of every status must be the documented
213 /// snake_case string.
214 #[test]
215 fn session_status_serialises_snake_case() {
216 assert_eq!(
217 serde_json::to_value(SessionStatus::Created).unwrap(),
218 json!("created")
219 );
220 assert_eq!(
221 serde_json::to_value(SessionStatus::Running).unwrap(),
222 json!("running")
223 );
224 assert_eq!(
225 serde_json::to_value(SessionStatus::Cancelled).unwrap(),
226 json!("cancelled")
227 );
228 assert_eq!(
229 serde_json::to_value(SessionStatus::Finished).unwrap(),
230 json!("finished")
231 );
232 assert_eq!(
233 serde_json::to_value(SessionStatus::Failed).unwrap(),
234 json!("failed")
235 );
236 assert_eq!(
237 serde_json::to_value(SessionStatus::DeadlineExceeded).unwrap(),
238 json!("deadline_exceeded")
239 );
240 assert_eq!(
241 serde_json::to_value(SessionStatus::TurnCapExceeded).unwrap(),
242 json!("turn_cap_exceeded")
243 );
244 }
245
246 /// `as_str` must match the serde wire representation exactly.
247 #[test]
248 fn as_str_matches_serde_rename() {
249 for status in [
250 SessionStatus::Created,
251 SessionStatus::Running,
252 SessionStatus::Cancelled,
253 SessionStatus::Finished,
254 SessionStatus::Failed,
255 SessionStatus::DeadlineExceeded,
256 SessionStatus::TurnCapExceeded,
257 ] {
258 let via_str = status.as_str();
259 let via_serde = serde_json::to_value(status).unwrap();
260 assert_eq!(json!(via_str), via_serde);
261 }
262 }
263
264 /// `Cancelled`/`Finished`/`Failed`/`DeadlineExceeded`/`TurnCapExceeded`
265 /// are terminal-per-call; `Finished`, `TurnCapExceeded` and `Cancelled`
266 /// remain resumable through `SessionRegistry::begin_execution`'s narrower
267 /// gate (#3888, #8207) despite being terminal here.
268 #[test]
269 fn is_terminal_covers_terminal_states() {
270 assert!(!SessionStatus::Created.is_terminal());
271 assert!(!SessionStatus::Running.is_terminal());
272 assert!(SessionStatus::Cancelled.is_terminal());
273 assert!(SessionStatus::Finished.is_terminal());
274 assert!(SessionStatus::Failed.is_terminal());
275 assert!(SessionStatus::DeadlineExceeded.is_terminal());
276 assert!(SessionStatus::TurnCapExceeded.is_terminal());
277 }
278
279 /// `Finished`, `TurnCapExceeded` and (#8207) `Cancelled` are resumable —
280 /// the authoritative gate `SessionRegistry::begin_execution` defers to.
281 #[test]
282 fn is_resumable_matches_finished_turn_cap_and_cancelled() {
283 assert!(!SessionStatus::Created.is_resumable());
284 assert!(!SessionStatus::Running.is_resumable());
285 assert!(SessionStatus::Cancelled.is_resumable());
286 assert!(SessionStatus::Finished.is_resumable());
287 assert!(!SessionStatus::Failed.is_resumable());
288 assert!(!SessionStatus::DeadlineExceeded.is_resumable());
289 assert!(SessionStatus::TurnCapExceeded.is_resumable());
290 }
291
292 /// A `Session` must round-trip through JSON with the expected shape.
293 #[test]
294 fn session_round_trips_through_json() {
295 let session = Session {
296 id: "s-1".to_string(),
297 task: "do the thing".to_string(),
298 agent: Some("engineer".to_string()),
299 project: None,
300 binding: crate::binding::ProjectBinding::None,
301 status: SessionStatus::Running,
302 created_at: Utc::now(),
303 mode: Some(crate::mode::HarnessMode::DailyDriver),
304 workstream_id: None,
305 result: None,
306 no_delegate: false,
307 };
308 let value = serde_json::to_value(&session).unwrap();
309 assert_eq!(value["id"], "s-1");
310 assert_eq!(value["status"], "running");
311 assert_eq!(value["agent"], "engineer");
312 assert!(value["project"].is_null());
313 assert_eq!(value["mode"], "daily-driver");
314
315 let back: Session = serde_json::from_value(value).unwrap();
316 assert_eq!(back.id, session.id);
317 assert_eq!(back.status, session.status);
318 assert_eq!(back.mode, session.mode);
319 }
320
321 /// #4351 backward compatibility: the exact `session.status` payload a
322 /// pre-#4351 daemon emitted — no `result` key at all — must still
323 /// deserialise, and a session that has never run must still SERIALISE
324 /// without one, so a consumer written against the old shape sees a
325 /// byte-identical document.
326 #[test]
327 fn session_without_result_deserialises_and_omits_it() {
328 let legacy = json!({
329 "id": "s-1",
330 "task": "do the thing",
331 "agent": "engineer",
332 "project": null,
333 "status": "finished",
334 "created_at": "2026-01-01T00:00:00Z",
335 "mode": "daily-driver",
336 "binding": { "state": "projectless" },
337 "workstream_id": null
338 });
339
340 let parsed: Session = serde_json::from_value(legacy).expect("legacy payload deserialises");
341 assert_eq!(parsed.id, "s-1");
342 assert!(parsed.result.is_none());
343 // #8184: a payload predating the field reads back DELEGATING — the
344 // pre-#8184 shape, never the new solo default.
345 assert!(!parsed.no_delegate);
346
347 let re_encoded = serde_json::to_value(&parsed).expect("serialize");
348 assert!(
349 re_encoded.get("result").is_none(),
350 "a session with no result must omit the key entirely, not emit null: {re_encoded}"
351 );
352 }
353
354 /// #4351: once a run finishes, the result rides along on the same snapshot.
355 #[test]
356 fn session_round_trips_with_a_result() {
357 let session = Session {
358 id: "s-2".to_string(),
359 task: "t".to_string(),
360 agent: None,
361 project: None,
362 binding: crate::binding::ProjectBinding::None,
363 status: SessionStatus::Finished,
364 created_at: Utc::now(),
365 mode: None,
366 workstream_id: None,
367 result: Some(
368 crate::session::TaskResult::new(crate::session::TaskResultStatus::Success)
369 .with_diff_ref(Some("tree-sha".to_string())),
370 ),
371 no_delegate: false,
372 };
373
374 let value = serde_json::to_value(&session).expect("serialize");
375 assert_eq!(value["result"]["status"], "success");
376 assert_eq!(value["result"]["diff_ref"], "tree-sha");
377 assert!(value["result"]["pr_ref"].is_null());
378
379 let back: Session = serde_json::from_value(value).expect("deserialize");
380 assert_eq!(back.result, session.result);
381 }
382}
383
384#[cfg(test)]
385mod binding_model_tests {
386 use super::*;
387
388 /// A projectless `Session` must round-trip, and a payload with NO `binding`
389 /// field at all must read back as projectless rather than failing.
390 #[test]
391 fn projectless_session_round_trips() {
392 let session = Session {
393 id: "s-1".to_string(),
394 task: "t".to_string(),
395 agent: None,
396 project: None,
397 binding: crate::binding::ProjectBinding::None,
398 status: SessionStatus::Running,
399 created_at: Utc::now(),
400 mode: None,
401 workstream_id: None,
402 result: None,
403 no_delegate: false,
404 };
405 let value = serde_json::to_value(&session).expect("serialize");
406 assert_eq!(value["binding"]["state"], "projectless");
407
408 let back: Session = serde_json::from_value(value).expect("deserialize");
409 assert_eq!(back.binding, crate::binding::ProjectBinding::None);
410
411 // An older payload predating the `binding` field must still read back.
412 let legacy = serde_json::json!({
413 "id": "s-2", "task": "t", "agent": null, "project": null,
414 "status": "running", "created_at": Utc::now(),
415 });
416 let back: Session =
417 serde_json::from_value(legacy).expect("legacy payload must deserialize");
418 assert_eq!(
419 back.binding,
420 crate::binding::ProjectBinding::None,
421 "a missing binding field must default to projectless"
422 );
423 assert_eq!(
424 back.workstream_id, None,
425 "a missing workstream_id field must default to unbound"
426 );
427 }
428
429 /// (Issue #3298) A `Session` bound to a workstream must round-trip that
430 /// binding through JSON.
431 #[test]
432 fn workstream_bound_session_round_trips() {
433 let ws_id = crate::workstreams::model::WorkstreamId::new();
434 let session = Session {
435 id: "s-1".to_string(),
436 task: "t".to_string(),
437 agent: None,
438 project: None,
439 binding: crate::binding::ProjectBinding::None,
440 status: SessionStatus::Running,
441 created_at: Utc::now(),
442 mode: None,
443 workstream_id: Some(ws_id),
444 result: None,
445 no_delegate: false,
446 };
447 let value = serde_json::to_value(&session).expect("serialize");
448 assert_eq!(value["workstream_id"], ws_id.to_string());
449
450 let back: Session = serde_json::from_value(value).expect("deserialize");
451 assert_eq!(back.workstream_id, Some(ws_id));
452 }
453}