Skip to main content

trusty_code/session/
task_result.rs

1//! The actionable outcome a caller gets back alongside a `Session` snapshot
2//! (#4351).
3//!
4//! Why: `task.run` and `session.status` used to hand back only `id`/`status`/
5//! `mode` — opaque to an external caller, which then had no way to tell a
6//! caller-facing story ("the change landed on branch X, here is the ref, the
7//! run passed"). [`TaskResult`] is the additive answer: the same snapshot
8//! still ships, with the actionable fields carried beside it.
9//! What: [`TaskResultStatus`] classifies the run; [`TaskResult`] carries that
10//! status plus `diff_ref`, `branch`, `pr_ref` and `summary`, every one of them
11//! nullable so a producer that cannot know a field says so rather than
12//! inventing it. `#[non_exhaustive]` keeps later fields additive: construct
13//! through [`TaskResult::new`] / [`TaskResult::pending`] and the `with_*`
14//! builders, never a struct literal from outside this crate.
15//! Test: `tests::status_maps_every_session_status`,
16//! `tests::partial_exit_code_is_its_own_status_not_a_failure`,
17//! `tests::exit_code_mapping_reads_the_numbers_from_the_enum`,
18//! `tests::task_result_round_trips_through_json`,
19//! `tests::absent_optional_fields_deserialise_as_none`.
20
21use serde::{Deserialize, Serialize};
22
23use super::model::SessionStatus;
24use crate::run_task::ExitCode;
25
26/// Pass/fail classification of a run, wider than a boolean.
27///
28/// Why: "did it work" has more than two useful answers. A run that exhausted
29/// its turn budget after writing a real, on-disk deliverable is NOT a failure
30/// — trusty-code's own CLI has spelled that `ExitCode::Partial` (6) since
31/// #2265, and collapsing it into `Failed` is exactly how a caller ends up
32/// discarding working code (see `crate::run_task::report::ExitCode`'s docs).
33/// What: `Pending` for a run that has not reached a terminal state yet;
34/// `Success`/`Partial`/`Failed`/`Cancelled`/`DeadlineExceeded` for the
35/// terminal ones. The wire form is snake_case, matching `SessionStatus`'s
36/// own convention.
37/// Test: `tests::status_maps_every_session_status`,
38/// `tests::partial_exit_code_is_its_own_status_not_a_failure`,
39/// `tests::status_serialises_snake_case`.
40#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "snake_case")]
42pub enum TaskResultStatus {
43    /// The run has not reached a terminal state yet.
44    Pending,
45    /// The run reached a natural stop without error.
46    Success,
47    /// The run stopped early but produced a deliverable — resumable, not dead.
48    Partial,
49    /// The run errored.
50    Failed,
51    /// The run was cancelled by a caller.
52    Cancelled,
53    /// The run's wall-clock deadline elapsed first.
54    DeadlineExceeded,
55}
56
57impl TaskResultStatus {
58    /// The wire string, identical to the serde representation.
59    pub fn as_str(self) -> &'static str {
60        match self {
61            Self::Pending => "pending",
62            Self::Success => "success",
63            Self::Partial => "partial",
64            Self::Failed => "failed",
65            Self::Cancelled => "cancelled",
66            Self::DeadlineExceeded => "deadline_exceeded",
67        }
68    }
69
70    /// Classify a daemon-side [`SessionStatus`].
71    ///
72    /// Why: the daemon's own producer (`crate::task::executor`) knows the
73    /// session's terminal status and nothing about process exit codes; this is
74    /// its one mapping point.
75    /// What: `Created`/`Running` are not terminal, so they report `Pending`.
76    /// `TurnCapExceeded` reports `Partial` — the same "not done, not dead"
77    /// reading `crate::cli_client::render::exit_code_for_status` already gives
78    /// it.
79    /// Test: `tests::status_maps_every_session_status`.
80    pub fn from_session_status(status: SessionStatus) -> Self {
81        match status {
82            SessionStatus::Created | SessionStatus::Running => Self::Pending,
83            SessionStatus::Finished => Self::Success,
84            SessionStatus::TurnCapExceeded => Self::Partial,
85            SessionStatus::Failed => Self::Failed,
86            SessionStatus::Cancelled => Self::Cancelled,
87            SessionStatus::DeadlineExceeded => Self::DeadlineExceeded,
88        }
89    }
90
91    /// Classify a typed [`ExitCode`].
92    ///
93    /// Why: `ExitCode` is the ONE definition of what a run's outcome means in
94    /// this crate; this match is exhaustive over it, so adding a variant there
95    /// fails to compile here until somebody decides what it classifies as.
96    /// A catch-all would have let `Partial` be absorbed silently — the exact
97    /// shape of #3888.
98    /// What: `NoChanges` is a SUCCESS — the run completed, it simply changed
99    /// nothing. `Partial` keeps its own status rather than collapsing into
100    /// `Failed`, because it means real work is on disk (see that variant's own
101    /// docs).
102    /// Test: `tests::every_exit_code_variant_classifies_deliberately`.
103    pub fn from_exit_kind(exit: ExitCode) -> Self {
104        match exit {
105            ExitCode::Success | ExitCode::NoChanges => Self::Success,
106            ExitCode::ConfigError | ExitCode::RunFailure => Self::Failed,
107            ExitCode::DeadlineExceeded => Self::DeadlineExceeded,
108            ExitCode::Partial => Self::Partial,
109        }
110    }
111
112    /// Classify a `tcode` child process's numeric exit code (#4351).
113    ///
114    /// Why: a caller that shells out to `tcode run-task` (see
115    /// `trusty_agents::tools::pm_bridge_backend::ProcessPmBridge`) reads the
116    /// child's exit status, not a `SessionStatus`. Without this mapping the
117    /// only honest reading of "non-zero" is "failed", which silently throws
118    /// away the `Partial` distinction the exit code exists to draw.
119    /// What: routes the number through [`ExitCode::from_code`] and then
120    /// [`Self::from_exit_kind`], so the numbers live in `ExitCode` alone and
121    /// renumbering a variant there carries this mapping with it. A number that
122    /// enum does not define — and a signal-killed child, which reports no code
123    /// at all — fails closed as `Failed`.
124    /// Test: `tests::partial_exit_code_is_its_own_status_not_a_failure`,
125    /// `tests::exit_code_mapping_reads_the_numbers_from_the_enum`,
126    /// `tests::an_undefined_exit_number_fails_closed`.
127    pub fn from_exit_code(code: Option<i32>) -> Self {
128        code.and_then(ExitCode::from_code)
129            .map(Self::from_exit_kind)
130            .unwrap_or(Self::Failed)
131    }
132}
133
134/// The actionable result of a task run, carried beside the `Session` snapshot.
135///
136/// Why: see the module docs — the `ProposalEnvelope` a calling assistant
137/// renders needs something concrete ("branch, ref, pass/fail"), and a bare
138/// session id is not that.
139/// What: every field except `status` is nullable, and a producer that cannot
140/// know one leaves it `None` rather than guessing. `diff_ref` is whatever ref
141/// names where the change landed (this crate's daemon reports a git tree
142/// object SHA); `branch` is the checked-out branch; `pr_ref` is a PR URL or
143/// number; `summary` is a one-line user-facing description. `pr_ref` is never
144/// populated by this crate's daemon — nothing in it opens a pull request — and
145/// exists for a producer downstream that does.
146/// Test: `tests::task_result_round_trips_through_json`,
147/// `tests::absent_optional_fields_deserialise_as_none`,
148/// `tests::builders_set_each_field`.
149#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
150#[non_exhaustive]
151pub struct TaskResult {
152    /// Pass/fail classification of the run.
153    pub status: TaskResultStatus,
154    /// Where the change landed — a commit hash, tree SHA, branch name, or path.
155    #[serde(default)]
156    pub diff_ref: Option<String>,
157    /// The branch the run left checked out.
158    #[serde(default)]
159    pub branch: Option<String>,
160    /// A pull-request URL or number, when a producer opened one.
161    #[serde(default)]
162    pub pr_ref: Option<String>,
163    /// One-line user-facing description of what happened.
164    #[serde(default)]
165    pub summary: Option<String>,
166}
167
168impl TaskResult {
169    /// A result carrying `status` and nothing else yet.
170    ///
171    /// Why: `#[non_exhaustive]` deliberately blocks struct-literal
172    /// construction outside this crate, so this plus the `with_*` builders are
173    /// the whole construction surface — a field added later cannot break a
174    /// downstream caller.
175    /// What: every optional field starts `None`.
176    /// Test: `tests::builders_set_each_field`.
177    pub fn new(status: TaskResultStatus) -> Self {
178        Self {
179            status,
180            diff_ref: None,
181            branch: None,
182            pr_ref: None,
183            summary: None,
184        }
185    }
186
187    /// The result `task.run` returns immediately, before the run has finished.
188    ///
189    /// Why: `task.run` is asynchronous — it mints the session, spawns the run
190    /// and returns. Reporting `Pending` with empty refs is the truthful
191    /// snapshot at that instant; the caller polls `session.status` for the
192    /// terminal one.
193    /// Test: `crate::task::protocol::tests::task_run_response_carries_a_pending_result`.
194    pub fn pending() -> Self {
195        Self::new(TaskResultStatus::Pending)
196    }
197
198    /// Replace the status, keeping every other field.
199    ///
200    /// Why: a relaying caller learns the outcome from its child's exit code
201    /// while the refs come from the child's own reported result — the two
202    /// arrive from different places and must be composable.
203    /// Test: `tests::builders_set_each_field`.
204    pub fn with_status(mut self, status: TaskResultStatus) -> Self {
205        self.status = status;
206        self
207    }
208
209    /// Set `diff_ref`. `None` leaves it absent.
210    /// Test: `tests::builders_set_each_field`.
211    pub fn with_diff_ref(mut self, diff_ref: Option<String>) -> Self {
212        self.diff_ref = diff_ref;
213        self
214    }
215
216    /// Set `branch`. `None` leaves it absent.
217    /// Test: `tests::builders_set_each_field`.
218    pub fn with_branch(mut self, branch: Option<String>) -> Self {
219        self.branch = branch;
220        self
221    }
222
223    /// Set `pr_ref`. `None` leaves it absent.
224    /// Test: `tests::builders_set_each_field`.
225    pub fn with_pr_ref(mut self, pr_ref: Option<String>) -> Self {
226        self.pr_ref = pr_ref;
227        self
228    }
229
230    /// Set `summary`. `None` leaves it absent.
231    /// Test: `tests::builders_set_each_field`.
232    pub fn with_summary(mut self, summary: Option<String>) -> Self {
233        self.summary = summary;
234        self
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241    use serde_json::json;
242
243    /// Every `SessionStatus` must land on a deliberate classification — the
244    /// non-terminal pair on `Pending`, and `TurnCapExceeded` on `Partial`
245    /// rather than being absorbed into `Failed`.
246    #[test]
247    fn status_maps_every_session_status() {
248        for (session, expected) in [
249            (SessionStatus::Created, TaskResultStatus::Pending),
250            (SessionStatus::Running, TaskResultStatus::Pending),
251            (SessionStatus::Finished, TaskResultStatus::Success),
252            (SessionStatus::TurnCapExceeded, TaskResultStatus::Partial),
253            (SessionStatus::Failed, TaskResultStatus::Failed),
254            (SessionStatus::Cancelled, TaskResultStatus::Cancelled),
255            (
256                SessionStatus::DeadlineExceeded,
257                TaskResultStatus::DeadlineExceeded,
258            ),
259        ] {
260            assert_eq!(
261                TaskResultStatus::from_session_status(session),
262                expected,
263                "session status {session:?} mapped to the wrong result status"
264            );
265        }
266    }
267
268    /// #4351: `ExitCode::Partial` is `Partial`, NOT `Failed` — the whole point
269    /// of that exit code. Asserted through the enum, never the literal `6`, so
270    /// renumbering it cannot make this test pass against the wrong number.
271    #[test]
272    fn partial_exit_code_is_its_own_status_not_a_failure() {
273        let status = TaskResultStatus::from_exit_code(Some(ExitCode::Partial.code()));
274        assert_eq!(status, TaskResultStatus::Partial);
275        assert_ne!(status, TaskResultStatus::Failed);
276    }
277
278    /// Every `ExitCode` variant classifies deliberately. The match in
279    /// `from_exit_kind` is exhaustive, so a new variant breaks the build there
280    /// first; this pins what each existing one means.
281    #[test]
282    fn every_exit_code_variant_classifies_deliberately() {
283        for (exit, expected) in [
284            (ExitCode::Success, TaskResultStatus::Success),
285            (ExitCode::ConfigError, TaskResultStatus::Failed),
286            (ExitCode::RunFailure, TaskResultStatus::Failed),
287            (ExitCode::NoChanges, TaskResultStatus::Success),
288            (
289                ExitCode::DeadlineExceeded,
290                TaskResultStatus::DeadlineExceeded,
291            ),
292            (ExitCode::Partial, TaskResultStatus::Partial),
293        ] {
294            assert_eq!(
295                TaskResultStatus::from_exit_kind(exit),
296                expected,
297                "{exit:?} classified wrongly"
298            );
299        }
300    }
301
302    /// `from_exit_code` reads its numbers from `ExitCode` itself, so the
303    /// numeric path agrees with the typed one for every variant.
304    #[test]
305    fn exit_code_mapping_reads_the_numbers_from_the_enum() {
306        for exit in [
307            ExitCode::Success,
308            ExitCode::ConfigError,
309            ExitCode::RunFailure,
310            ExitCode::NoChanges,
311            ExitCode::DeadlineExceeded,
312            ExitCode::Partial,
313        ] {
314            assert_eq!(
315                TaskResultStatus::from_exit_code(Some(exit.code())),
316                TaskResultStatus::from_exit_kind(exit),
317                "the numeric and typed paths disagree for {exit:?}"
318            );
319        }
320    }
321
322    /// A number `ExitCode` does not define, and a signal-killed child that
323    /// reports no code at all, both fail closed.
324    #[test]
325    fn an_undefined_exit_number_fails_closed() {
326        assert_eq!(
327            TaskResultStatus::from_exit_code(None),
328            TaskResultStatus::Failed
329        );
330        for code in [1, 7, 137] {
331            assert_eq!(
332                TaskResultStatus::from_exit_code(Some(code)),
333                TaskResultStatus::Failed,
334                "undefined code {code}"
335            );
336        }
337    }
338
339    /// `as_str` and the serde representation must not drift apart.
340    #[test]
341    fn status_serialises_snake_case() {
342        for status in [
343            TaskResultStatus::Pending,
344            TaskResultStatus::Success,
345            TaskResultStatus::Partial,
346            TaskResultStatus::Failed,
347            TaskResultStatus::Cancelled,
348            TaskResultStatus::DeadlineExceeded,
349        ] {
350            assert_eq!(
351                serde_json::to_value(status).unwrap(),
352                json!(status.as_str())
353            );
354        }
355    }
356
357    /// A fully-populated result survives a JSON round trip unchanged.
358    #[test]
359    fn task_result_round_trips_through_json() {
360        let result = TaskResult::new(TaskResultStatus::Partial)
361            .with_diff_ref(Some("abc123".to_string()))
362            .with_branch(Some("feat/x".to_string()))
363            .with_pr_ref(Some("https://example.invalid/pull/7".to_string()))
364            .with_summary(Some("wrote one file".to_string()));
365
366        let round_tripped: TaskResult =
367            serde_json::from_value(serde_json::to_value(&result).unwrap()).unwrap();
368        assert_eq!(round_tripped, result);
369    }
370
371    /// A producer that only knows the status emits a result whose other fields
372    /// read back as `None` — and a payload that OMITS them entirely still
373    /// deserialises, so a leaner producer stays compatible.
374    #[test]
375    fn absent_optional_fields_deserialise_as_none() {
376        let parsed: TaskResult = serde_json::from_value(json!({ "status": "success" })).unwrap();
377        assert_eq!(parsed.status, TaskResultStatus::Success);
378        assert_eq!(parsed.diff_ref, None);
379        assert_eq!(parsed.branch, None);
380        assert_eq!(parsed.pr_ref, None);
381        assert_eq!(parsed.summary, None);
382    }
383
384    /// Each builder sets exactly its own field and leaves the rest alone.
385    #[test]
386    fn builders_set_each_field() {
387        let base = TaskResult::pending();
388        assert_eq!(base.status, TaskResultStatus::Pending);
389        assert_eq!(base.diff_ref, None);
390
391        let built = base
392            .clone()
393            .with_status(TaskResultStatus::Success)
394            .with_diff_ref(Some("d".to_string()))
395            .with_branch(Some("b".to_string()))
396            .with_pr_ref(Some("p".to_string()))
397            .with_summary(Some("s".to_string()));
398
399        assert_eq!(built.status, TaskResultStatus::Success);
400        assert_eq!(built.diff_ref.as_deref(), Some("d"));
401        assert_eq!(built.branch.as_deref(), Some("b"));
402        assert_eq!(built.pr_ref.as_deref(), Some("p"));
403        assert_eq!(built.summary.as_deref(), Some("s"));
404        // The builders consume `self`, so the original is untouched.
405        assert_eq!(base.status, TaskResultStatus::Pending);
406    }
407}