trusty-code 0.7.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
//! Session domain model: the daemon-owned first-class object (#2054, Axiom 4).
//!
//! Why: the vision spec's Axiom 4 ("The Daemon OWNS Sessions; CLI Attaches
//! Over the API") requires a session to be a real object living inside the
//! daemon — not a tmux pane, not a PTY, not something the CLI reconstructs
//! from scrollback. This module defines that object's shape; ownership,
//! storage, and the ring buffer live in `super::registry`.
//! What: [`Session`] (the wire/domain type returned by
//! `session.create`/`session.list`/`session.status`) and [`SessionStatus`]
//! (its lifecycle states, per §12 Session Durability: M1 has no queueing —
//! a session moves directly from `Created` to `Running` — and no
//! persistence, so `Failed` here means "the daemon observed a failure", not
//! "recovered from one after a restart").
//! Test: `model::tests::*`.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// Lifecycle status of a [`Session`].
///
/// Why: a small, closed set of states the registry can transition between
/// and that a client can match on reliably (the wire string is stable —
/// `#[serde(rename_all = "snake_case")]` — independent of Rust variant
/// naming).
/// What: `Created` -> `Running` happens immediately on `session.create` in
/// M1 (there is no queue to sit in ahead of real task execution, which
/// lands with `task.*` in #2056). `Cancelled`/`Finished`/`Failed`/
/// `DeadlineExceeded`/`TurnCapExceeded` are the five terminal-per-call
/// states; `session.cancel` is the only one #2054 can drive directly
/// (`Finished`/`Failed`/`DeadlineExceeded`/`TurnCapExceeded` are set by
/// `task::executor::run_and_record` when the PM's `AgentLoop` resolves).
/// `DeadlineExceeded` (#2207) is distinct from `Failed`: it means the run's
/// configured wall-clock budget elapsed before the PM reached a terminal
/// state, NOT that the loop or LLM call errored — a run that hit this
/// status may have made real, useful progress. `TurnCapExceeded` (#3888) is
/// likewise distinct from `Failed`: it means this ONE `task.run` call
/// exhausted its `AgentLoopConfig::max_turns` budget, not that the session
/// itself failed — per epic #2343's infinite-sessions goal, the PM
/// transcript is fully persisted and the session is resumable exactly like
/// `Finished` (see `SessionRegistry::begin_execution`'s resume condition).
/// Test: `model::tests::session_status_serialises_snake_case`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SessionStatus {
    Created,
    Running,
    Cancelled,
    Finished,
    Failed,
    DeadlineExceeded,
    /// This call's turn budget was exhausted — see the enum doc above (#3888).
    TurnCapExceeded,
}

impl SessionStatus {
    /// Return the stable wire string for this status (matches the serde
    /// `rename_all = "snake_case"` representation).
    ///
    /// Why: `crate::events::Event::SessionStatusChanged`'s `status` field is
    /// a plain `String`, not a `SessionStatus`, so registry code needs the
    /// wire string without round-tripping through `serde_json`.
    /// What: a `&'static str` per variant.
    /// Test: `model::tests::as_str_matches_serde_rename`.
    pub fn as_str(&self) -> &'static str {
        match self {
            SessionStatus::Created => "created",
            SessionStatus::Running => "running",
            SessionStatus::Cancelled => "cancelled",
            SessionStatus::Finished => "finished",
            SessionStatus::Failed => "failed",
            SessionStatus::DeadlineExceeded => "deadline_exceeded",
            SessionStatus::TurnCapExceeded => "turn_cap_exceeded",
        }
    }

    /// Returns `true` when this status is terminal FOR THIS CALL (the
    /// current `task.run` invocation will never transition again without a
    /// fresh `begin_execution`).
    ///
    /// Why: `session.cancel` and any future completion handler need to
    /// reject transitions out of a terminal-per-call state (e.g. cancelling
    /// an already-finished session is a no-op, not a silent overwrite). This
    /// is deliberately WIDER than "can never resume" — see [`Self::is_resumable`]
    /// for the narrower "dead forever" gate (#3888).
    /// What: `true` for `Cancelled`/`Finished`/`Failed`/`DeadlineExceeded`/
    /// `TurnCapExceeded`; `false` otherwise.
    /// Test: `model::tests::is_terminal_covers_terminal_states`.
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            SessionStatus::Cancelled
                | SessionStatus::Finished
                | SessionStatus::Failed
                | SessionStatus::DeadlineExceeded
                | SessionStatus::TurnCapExceeded
        )
    }

    /// Returns `true` when a session at this status may accept another
    /// `task.run` via `SessionRegistry::begin_execution` — the single
    /// authoritative "still resumable" gate (#2344 `Finished` + #3888
    /// `TurnCapExceeded`): both mean only THIS CALL ended, not the session,
    /// and `pm_transcript` is fully persisted either way, so the next call
    /// continues the same conversation.
    ///
    /// (#8207) `Cancelled` joins them. A cancel is the USER stopping one run,
    /// not a broken session — and the TUI holds ONE session for the whole
    /// conversation (`tui_client::engine_state::run_chat_turn` reuses the same
    /// id for every prompt), so treating a cancelled session as dead forever
    /// is what made the prompt after Esc fail with `-32003`. `Failed` and
    /// `DeadlineExceeded` stay dead-forever: those ended without the user
    /// asking, in a state the daemon cannot describe.
    /// Test: `model::tests::is_resumable_matches_finished_turn_cap_and_cancelled`.
    pub fn is_resumable(&self) -> bool {
        matches!(
            self,
            SessionStatus::Finished | SessionStatus::TurnCapExceeded | SessionStatus::Cancelled
        )
    }
}

/// A daemon-owned session (vision spec Axiom 4).
///
/// Why: the wire type every `session.*` method (except `send`/`attach`/
/// `detach`, which acknowledge rather than return a session) sends back to
/// the caller — `session.create`, `session.list`, `session.status`.
/// What: `id` is a UUIDv4 string; `agent`/`project` are optional because
/// `session.create` does not require either in M1 (no real agent-loop
/// wiring yet); `created_at` is UTC. `mode` (#2059) is `None` until
/// `task.run` resolves and sets it (`SessionRegistry::set_mode`) — a session
/// that has never run a task has no mode, mirroring the same "`None` means
/// not yet run" convention `session::transcript::TranscriptRecord` already
/// uses for `cost_usd`.
///
/// `binding` is the session's TYPED project binding (spec DOC-39 §5.5) — the
/// single object `task.run` and `session.create` now converge on. `project`
/// survives as the human display label but is no longer an independent source
/// of truth: it is DERIVED from `binding` (`ProjectBinding::label`) and so can
/// never again disagree with it. That derivation is the whole reconciliation —
/// previously `session.create` took a free-form label that was never validated
/// and never bound, while `task.run` took a path the label knew nothing about.
/// Test: `model::tests::session_round_trips_through_json`,
/// `model::tests::projectless_session_round_trips`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
    pub id: String,
    pub task: String,
    pub agent: Option<String>,
    /// Display label, derived from `binding` — see the struct docs. Kept for
    /// wire compatibility with existing `session.list`/`session.status`
    /// consumers that read a project name.
    pub project: Option<String>,
    pub status: SessionStatus,
    pub created_at: DateTime<Utc>,
    #[serde(default)]
    pub mode: Option<crate::mode::HarnessMode>,
    /// The typed three-state project binding. Defaults to projectless so an
    /// older persisted/serialized `Session` without the field still reads back.
    #[serde(default)]
    pub binding: crate::binding::ProjectBinding,
    /// (Issue #3298, DOC-48 §4.1) The workstream this session is bound to, if
    /// any. `None` means projectless/unbound — a fully valid state (DOC-39
    /// §4.2), not a missing one. Set exactly once, at creation
    /// (`session::protocol::create` / `task::protocol::task_run` resolve
    /// either an explicit `workstream_id` param or §4.2's ambient
    /// active-workstream default before calling
    /// `SessionRegistry::bind_workstream`); there is no setter that changes
    /// it afterward, mirroring `binding`'s own immutability convention — see
    /// `SessionRegistry::bind_workstream`'s docs for the enforcement point.
    /// `#[serde(default)]` keeps an older persisted/serialized `Session`
    /// (predating this field) reading back as unbound.
    #[serde(default)]
    pub workstream_id: Option<crate::workstreams::model::WorkstreamId>,
    /// (#4351) The actionable outcome of this session's last run — where the
    /// change landed and whether it passed — set once the run reaches a
    /// terminal state (`crate::task::executor` -> `SessionRegistry::
    /// set_task_result`).
    ///
    /// `None` until then, and OMITTED from the JSON entirely while `None`, so
    /// every pre-#4351 consumer sees a byte-identical `session.status`
    /// payload for a session that has never run. `#[serde(default)]` is the
    /// other half: a persisted or hand-written snapshot predating this field
    /// still reads back.
    /// Test: `model::tests::session_without_result_deserialises_and_omits_it`,
    /// `model::tests::session_round_trips_with_a_result`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result: Option<crate::session::task_result::TaskResult>,
    /// (#8184) Whether this session runs the SOLO agent — the #8031
    /// single-agent shape, where the named agent carries its own tcode tools
    /// and `delegate_to_agent` is never registered.
    ///
    /// Why: an interactive `tcode tui` session has to read and edit files
    /// itself (Claude Code's basic loop), and the delegating PM registry has
    /// no filesystem tools at all. The choice belongs to the SESSION rather
    /// than to each `task.run`, so every turn of one conversation runs the
    /// same agent shape and `session.status`/`session.list` can state which.
    /// What: set once, at creation (`SessionRegistry::create_with_delegation`)
    /// — `session.create` defaults it to `true`, `task.run`'s own mint path
    /// carries that call's `no_delegate` through. `#[serde(default)]` reads an
    /// older serialized `Session` back as delegating, the pre-#8184 shape.
    /// Test: `session::protocol::tests::create_defaults_to_the_solo_agent`,
    /// `session::protocol::tests::create_with_delegate_true_keeps_the_delegating_pm`.
    #[serde(default)]
    pub no_delegate: bool,
}

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

    /// The wire representation of every status must be the documented
    /// snake_case string.
    #[test]
    fn session_status_serialises_snake_case() {
        assert_eq!(
            serde_json::to_value(SessionStatus::Created).unwrap(),
            json!("created")
        );
        assert_eq!(
            serde_json::to_value(SessionStatus::Running).unwrap(),
            json!("running")
        );
        assert_eq!(
            serde_json::to_value(SessionStatus::Cancelled).unwrap(),
            json!("cancelled")
        );
        assert_eq!(
            serde_json::to_value(SessionStatus::Finished).unwrap(),
            json!("finished")
        );
        assert_eq!(
            serde_json::to_value(SessionStatus::Failed).unwrap(),
            json!("failed")
        );
        assert_eq!(
            serde_json::to_value(SessionStatus::DeadlineExceeded).unwrap(),
            json!("deadline_exceeded")
        );
        assert_eq!(
            serde_json::to_value(SessionStatus::TurnCapExceeded).unwrap(),
            json!("turn_cap_exceeded")
        );
    }

    /// `as_str` must match the serde wire representation exactly.
    #[test]
    fn as_str_matches_serde_rename() {
        for status in [
            SessionStatus::Created,
            SessionStatus::Running,
            SessionStatus::Cancelled,
            SessionStatus::Finished,
            SessionStatus::Failed,
            SessionStatus::DeadlineExceeded,
            SessionStatus::TurnCapExceeded,
        ] {
            let via_str = status.as_str();
            let via_serde = serde_json::to_value(status).unwrap();
            assert_eq!(json!(via_str), via_serde);
        }
    }

    /// `Cancelled`/`Finished`/`Failed`/`DeadlineExceeded`/`TurnCapExceeded`
    /// are terminal-per-call; `Finished`, `TurnCapExceeded` and `Cancelled`
    /// remain resumable through `SessionRegistry::begin_execution`'s narrower
    /// gate (#3888, #8207) despite being terminal here.
    #[test]
    fn is_terminal_covers_terminal_states() {
        assert!(!SessionStatus::Created.is_terminal());
        assert!(!SessionStatus::Running.is_terminal());
        assert!(SessionStatus::Cancelled.is_terminal());
        assert!(SessionStatus::Finished.is_terminal());
        assert!(SessionStatus::Failed.is_terminal());
        assert!(SessionStatus::DeadlineExceeded.is_terminal());
        assert!(SessionStatus::TurnCapExceeded.is_terminal());
    }

    /// `Finished`, `TurnCapExceeded` and (#8207) `Cancelled` are resumable —
    /// the authoritative gate `SessionRegistry::begin_execution` defers to.
    #[test]
    fn is_resumable_matches_finished_turn_cap_and_cancelled() {
        assert!(!SessionStatus::Created.is_resumable());
        assert!(!SessionStatus::Running.is_resumable());
        assert!(SessionStatus::Cancelled.is_resumable());
        assert!(SessionStatus::Finished.is_resumable());
        assert!(!SessionStatus::Failed.is_resumable());
        assert!(!SessionStatus::DeadlineExceeded.is_resumable());
        assert!(SessionStatus::TurnCapExceeded.is_resumable());
    }

    /// A `Session` must round-trip through JSON with the expected shape.
    #[test]
    fn session_round_trips_through_json() {
        let session = Session {
            id: "s-1".to_string(),
            task: "do the thing".to_string(),
            agent: Some("engineer".to_string()),
            project: None,
            binding: crate::binding::ProjectBinding::None,
            status: SessionStatus::Running,
            created_at: Utc::now(),
            mode: Some(crate::mode::HarnessMode::DailyDriver),
            workstream_id: None,
            result: None,
            no_delegate: false,
        };
        let value = serde_json::to_value(&session).unwrap();
        assert_eq!(value["id"], "s-1");
        assert_eq!(value["status"], "running");
        assert_eq!(value["agent"], "engineer");
        assert!(value["project"].is_null());
        assert_eq!(value["mode"], "daily-driver");

        let back: Session = serde_json::from_value(value).unwrap();
        assert_eq!(back.id, session.id);
        assert_eq!(back.status, session.status);
        assert_eq!(back.mode, session.mode);
    }

    /// #4351 backward compatibility: the exact `session.status` payload a
    /// pre-#4351 daemon emitted — no `result` key at all — must still
    /// deserialise, and a session that has never run must still SERIALISE
    /// without one, so a consumer written against the old shape sees a
    /// byte-identical document.
    #[test]
    fn session_without_result_deserialises_and_omits_it() {
        let legacy = json!({
            "id": "s-1",
            "task": "do the thing",
            "agent": "engineer",
            "project": null,
            "status": "finished",
            "created_at": "2026-01-01T00:00:00Z",
            "mode": "daily-driver",
            "binding": { "state": "projectless" },
            "workstream_id": null
        });

        let parsed: Session = serde_json::from_value(legacy).expect("legacy payload deserialises");
        assert_eq!(parsed.id, "s-1");
        assert!(parsed.result.is_none());
        // #8184: a payload predating the field reads back DELEGATING — the
        // pre-#8184 shape, never the new solo default.
        assert!(!parsed.no_delegate);

        let re_encoded = serde_json::to_value(&parsed).expect("serialize");
        assert!(
            re_encoded.get("result").is_none(),
            "a session with no result must omit the key entirely, not emit null: {re_encoded}"
        );
    }

    /// #4351: once a run finishes, the result rides along on the same snapshot.
    #[test]
    fn session_round_trips_with_a_result() {
        let session = Session {
            id: "s-2".to_string(),
            task: "t".to_string(),
            agent: None,
            project: None,
            binding: crate::binding::ProjectBinding::None,
            status: SessionStatus::Finished,
            created_at: Utc::now(),
            mode: None,
            workstream_id: None,
            result: Some(
                crate::session::TaskResult::new(crate::session::TaskResultStatus::Success)
                    .with_diff_ref(Some("tree-sha".to_string())),
            ),
            no_delegate: false,
        };

        let value = serde_json::to_value(&session).expect("serialize");
        assert_eq!(value["result"]["status"], "success");
        assert_eq!(value["result"]["diff_ref"], "tree-sha");
        assert!(value["result"]["pr_ref"].is_null());

        let back: Session = serde_json::from_value(value).expect("deserialize");
        assert_eq!(back.result, session.result);
    }
}

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

    /// A projectless `Session` must round-trip, and a payload with NO `binding`
    /// field at all must read back as projectless rather than failing.
    #[test]
    fn projectless_session_round_trips() {
        let session = Session {
            id: "s-1".to_string(),
            task: "t".to_string(),
            agent: None,
            project: None,
            binding: crate::binding::ProjectBinding::None,
            status: SessionStatus::Running,
            created_at: Utc::now(),
            mode: None,
            workstream_id: None,
            result: None,
            no_delegate: false,
        };
        let value = serde_json::to_value(&session).expect("serialize");
        assert_eq!(value["binding"]["state"], "projectless");

        let back: Session = serde_json::from_value(value).expect("deserialize");
        assert_eq!(back.binding, crate::binding::ProjectBinding::None);

        // An older payload predating the `binding` field must still read back.
        let legacy = serde_json::json!({
            "id": "s-2", "task": "t", "agent": null, "project": null,
            "status": "running", "created_at": Utc::now(),
        });
        let back: Session =
            serde_json::from_value(legacy).expect("legacy payload must deserialize");
        assert_eq!(
            back.binding,
            crate::binding::ProjectBinding::None,
            "a missing binding field must default to projectless"
        );
        assert_eq!(
            back.workstream_id, None,
            "a missing workstream_id field must default to unbound"
        );
    }

    /// (Issue #3298) A `Session` bound to a workstream must round-trip that
    /// binding through JSON.
    #[test]
    fn workstream_bound_session_round_trips() {
        let ws_id = crate::workstreams::model::WorkstreamId::new();
        let session = Session {
            id: "s-1".to_string(),
            task: "t".to_string(),
            agent: None,
            project: None,
            binding: crate::binding::ProjectBinding::None,
            status: SessionStatus::Running,
            created_at: Utc::now(),
            mode: None,
            workstream_id: Some(ws_id),
            result: None,
            no_delegate: false,
        };
        let value = serde_json::to_value(&session).expect("serialize");
        assert_eq!(value["workstream_id"], ws_id.to_string());

        let back: Session = serde_json::from_value(value).expect("deserialize");
        assert_eq!(back.workstream_id, Some(ws_id));
    }
}