Skip to main content

trusty_code/tools/
finish_task.rs

1//! `finish_task` tool — structured, schema-validated task completion (#2072, §5.8).
2//!
3//! Why: Before this tool, an `AgentLoop` only recognised completion implicitly —
4//! an assistant turn with NO tool calls (the D3 convention, see
5//! `agent_loop::run_inner`). That works, but it forces the model to convey
6//! "I'm done, here's what happened" as free prose the caller must re-parse.
7//! `finish_task` gives the model an explicit, schema-validated tool call for the
8//! same signal: a `status` enum, a `summary`, and optional structured `changes`/
9//! test-result fields. Malformed arguments (a missing required field, an invalid
10//! `status` enum value, syntactically broken JSON) flow through the EXACT SAME
11//! `llm::tool_call_extractor` plumbing #1023 built for every other tool —
12//! `ToolCallExtractor::parse_and_validate` → `schema::validate_args` — so no new
13//! validation or repair code is needed here; `finish_task` is just another
14//! `ToolExecutor` whose schema happens to describe a completion report.
15//! What: [`FinishTaskTool`] implements `ToolExecutor` with `name()` equal to
16//! [`FINISH_TASK_TOOL_NAME`]. `execute` deserialises the (already
17//! schema-validated) arguments into [`FinishTaskArgs`] and renders them via
18//! [`render_finish_summary`] into the tool's `ToolResult`. `agent_loop::run_inner`
19//! (#2072) recognises a successful `finish_task` dispatch and terminates the loop
20//! immediately, building the final `AgentOutput` from the SAME `FinishTaskArgs` /
21//! `render_finish_summary` this module exposes, instead of waiting for a later
22//! no-tool-call turn.
23//! Test: `finish_task::tests::*` — schema shape, valid execute, execute with
24//! changes/tests fields, and the defensive (should-be-unreachable given upstream
25//! schema validation) malformed-shape branch. `agent_loop::tests::*` covers the
26//! loop-termination integration end to end.
27
28use async_trait::async_trait;
29use serde::Deserialize;
30use serde_json::{Value, json};
31
32use crate::tools::traits::{ToolExecutor, ToolResult};
33
34/// The tool's registered/advertised name.
35///
36/// Why: Shared literal between the `ToolExecutor` impl and `agent_loop`'s
37/// finish-detection check, so the two can never drift.
38/// Test: `tests::name_matches_constant`.
39pub const FINISH_TASK_TOOL_NAME: &str = "finish_task";
40
41/// Completion status reported by the model.
42///
43/// Why: An enum (rather than a free-form string) lets the shared JSON-Schema
44/// `enum` validator (`llm::tool_call_extractor::schema::validate_args`) catch a
45/// hallucinated status value BEFORE it ever reaches `execute`.
46/// What: Mirrors the three values in the §5.8 schema, serialised/deserialised in
47/// `snake_case` to match the wire strings exactly.
48/// Test: `tests::status_display_and_roundtrip`.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
50#[serde(rename_all = "snake_case")]
51pub enum FinishStatus {
52    /// The task was completed successfully.
53    Completed,
54    /// The task could not be completed.
55    Failed,
56    /// The task was abandoned/cancelled before completion.
57    Cancelled,
58}
59
60impl std::fmt::Display for FinishStatus {
61    /// Why: `render_finish_summary` needs the lowercase wire form, not Rust's
62    /// `Debug` casing.
63    /// What: Renders the same lowercase strings the JSON schema's `enum` lists.
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        let s = match self {
66            FinishStatus::Completed => "completed",
67            FinishStatus::Failed => "failed",
68            FinishStatus::Cancelled => "cancelled",
69        };
70        write!(f, "{s}")
71    }
72}
73
74/// One entry of the optional `changes` array.
75///
76/// Why: Lets the model report which files it touched without the caller having
77/// to re-parse a diff out of prose. Every field is optional (including `file`)
78/// because the JSON schema does not mark any of them `required` inside the
79/// array item — a partially-populated entry must still deserialise rather than
80/// hard-failing `execute` for something the schema-level validator already let
81/// through.
82/// What: `file`, `lines_added`, `lines_removed` — all `Option`.
83/// Test: `tests::execute_with_changes_and_tests_renders_all_fields`.
84#[derive(Debug, Clone, Deserialize)]
85pub struct ChangeEntry {
86    /// Path of the changed file, if reported.
87    pub file: Option<String>,
88    /// Lines added, if reported.
89    pub lines_added: Option<i64>,
90    /// Lines removed, if reported.
91    pub lines_removed: Option<i64>,
92}
93
94/// Parsed, validated arguments to a `finish_task` call.
95///
96/// Why: A typed shape is easier for both `execute` and `agent_loop`'s
97/// loop-termination path to work with than a raw `serde_json::Value`.
98/// What: `status` and `summary` are required (matching the schema's `required`
99/// array); `changes` defaults to empty when absent; `tests_run`/`tests_passed`
100/// are optional integers. `tests_run`/`tests_passed` are signed (`i64`) rather
101/// than unsigned so an out-of-range value the JSON-Schema-subset validator does
102/// not itself reject (it declares no `minimum`) still deserialises instead of
103/// hard-failing `execute` for a shape the schema layer already accepted.
104/// Test: `tests::execute_valid_args_renders_summary`,
105/// `tests::execute_with_changes_and_tests_renders_all_fields`.
106#[derive(Debug, Clone, Deserialize)]
107pub struct FinishTaskArgs {
108    /// Completion status.
109    pub status: FinishStatus,
110    /// Free-text summary of what was done.
111    pub summary: String,
112    /// Files/changes made, if reported.
113    #[serde(default)]
114    pub changes: Vec<ChangeEntry>,
115    /// Number of tests run, if reported.
116    pub tests_run: Option<i64>,
117    /// Number of tests that passed, if reported.
118    pub tests_passed: Option<i64>,
119}
120
121/// Render a [`FinishTaskArgs`] into human-readable summary text.
122///
123/// Why: Shared by [`FinishTaskTool::execute`] (so the tool's own `ToolResult`
124/// content is meaningful) AND `agent_loop::build_finish_output` (so the final
125/// `AgentOutput.content` on explicit finish reflects the SAME structured
126/// report) — one rendering, no drift between the two call sites.
127/// What: `"Task <status>: <summary>"` followed by an optional `Changes:` list
128/// and an optional `Tests:` line.
129/// Test: `tests::render_includes_status_and_summary`,
130/// `tests::execute_with_changes_and_tests_renders_all_fields`.
131pub fn render_finish_summary(args: &FinishTaskArgs) -> String {
132    let mut out = format!("Task {}: {}", args.status, args.summary);
133
134    if !args.changes.is_empty() {
135        out.push_str("\nChanges:");
136        for change in &args.changes {
137            let file = change.file.as_deref().unwrap_or("<unknown file>");
138            let added = change.lines_added.unwrap_or(0);
139            let removed = change.lines_removed.unwrap_or(0);
140            out.push_str(&format!("\n  - {file} (+{added}/-{removed})"));
141        }
142    }
143
144    match (args.tests_run, args.tests_passed) {
145        (Some(run), Some(passed)) => out.push_str(&format!("\nTests: {passed}/{run} passed")),
146        (Some(run), None) => out.push_str(&format!("\nTests run: {run}")),
147        (None, Some(passed)) => out.push_str(&format!("\nTests passed: {passed}")),
148        (None, None) => {}
149    }
150
151    out
152}
153
154/// `ToolExecutor` for the `finish_task` tool (#2072, §5.8).
155///
156/// Why: Gives the model an explicit, schema-validated way to signal completion
157/// instead of relying solely on the implicit no-tool-call convention.
158/// What: Stateless — `execute` only formats its (already schema-validated)
159/// arguments; it has no side effects on the filesystem, network, or process.
160/// Test: `tests::*`.
161#[derive(Debug, Default)]
162pub struct FinishTaskTool;
163
164impl FinishTaskTool {
165    /// Construct a new `FinishTaskTool`.
166    ///
167    /// Why: Matches the `Tool::new()` constructor convention every other tool in
168    /// this module follows, even though there is no state to inject.
169    /// What: Returns `Self`.
170    /// Test: `tests::execute_valid_args_renders_summary`.
171    pub fn new() -> Self {
172        Self
173    }
174}
175
176#[async_trait]
177impl ToolExecutor for FinishTaskTool {
178    fn name(&self) -> &str {
179        FINISH_TASK_TOOL_NAME
180    }
181
182    /// JSON schema for `finish_task`, matching §5.8 of the vision spec exactly.
183    ///
184    /// Why: This is the schema `ToolRegistry::schema_for` hands to
185    /// `llm::ToolCallExtractor` (#1023), which validates every call's arguments
186    /// against it before `execute` ever runs.
187    /// What: `status` (enum, required), `summary` (string, required), `changes`
188    /// (optional array of `{file, lines_added, lines_removed}`), `tests_run` /
189    /// `tests_passed` (optional integers). `additionalProperties: false` matches
190    /// this crate's convention for every other tool's schema.
191    /// Test: `tests::schema_has_required_fields_and_enum`.
192    fn schema(&self) -> Value {
193        json!({
194            "type": "function",
195            "function": {
196                "name": FINISH_TASK_TOOL_NAME,
197                "description": "Signal task completion with a structured, machine-readable report. Call this exactly once when the task is finished (successfully, failed, or cancelled) instead of ending your turn with prose.",
198                "parameters": {
199                    "type": "object",
200                    "properties": {
201                        "status": {
202                            "type": "string",
203                            "enum": ["completed", "failed", "cancelled"],
204                            "description": "Outcome of the task."
205                        },
206                        "summary": {
207                            "type": "string",
208                            "description": "Free-text summary of what was done."
209                        },
210                        "changes": {
211                            "type": "array",
212                            "description": "Files changed, if any.",
213                            "items": {
214                                "type": "object",
215                                "properties": {
216                                    "file": { "type": "string" },
217                                    "lines_added": { "type": "integer" },
218                                    "lines_removed": { "type": "integer" }
219                                }
220                            }
221                        },
222                        "tests_run": {
223                            "type": "integer",
224                            "description": "Number of tests run, if applicable."
225                        },
226                        "tests_passed": {
227                            "type": "integer",
228                            "description": "Number of tests that passed, if applicable."
229                        }
230                    },
231                    "required": ["status", "summary"],
232                    "additionalProperties": false
233                }
234            }
235        })
236    }
237
238    /// Render the (already schema-validated) arguments into a `ToolResult`.
239    ///
240    /// Why: By the time `execute` runs, `agent_loop::dispatch_all` has already
241    /// validated `args` against [`Self::schema`] via #1023's
242    /// `ToolCallExtractor::parse_and_validate` — a missing required field or an
243    /// invalid `status` enum value never reaches here at all; those are caught
244    /// upstream and fed back through the SAME recoverable-error + repair path
245    /// every other tool uses. The `Err` branch below is therefore a defensive
246    /// fallback (no `unwrap`/`panic`) for a shape the loose JSON-Schema-subset
247    /// validator accepted but strict `serde` deserialisation still rejects —
248    /// exercised directly in `tests::execute_bypassing_schema_validation_is_recoverable`.
249    /// What: `Ok` → `ToolResult::ok(render_finish_summary(&parsed))`. `Err` →
250    /// `ToolResult::err` naming the deserialisation failure so the model can
251    /// retry with a corrected call.
252    /// Test: `tests::execute_valid_args_renders_summary`,
253    /// `tests::execute_with_changes_and_tests_renders_all_fields`,
254    /// `tests::execute_bypassing_schema_validation_is_recoverable`.
255    async fn execute(&self, args: Value) -> ToolResult {
256        match serde_json::from_value::<FinishTaskArgs>(args) {
257            Ok(parsed) => ToolResult::ok(render_finish_summary(&parsed)),
258            Err(e) => ToolResult::err(format!(
259                "finish_task arguments did not match the expected shape ({e}). \
260                 'status' must be one of completed/failed/cancelled and 'summary' must be a string."
261            )),
262        }
263    }
264}
265
266// ── Tests ─────────────────────────────────────────────────────────────────────
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271
272    /// `FinishTaskTool::name()` matches the exported constant.
273    ///
274    /// Why: `agent_loop`'s finish-detection check compares against
275    /// `FINISH_TASK_TOOL_NAME`; a drift here would silently break termination.
276    /// What: Trivial equality assertion.
277    /// Test: this test.
278    #[test]
279    fn name_matches_constant() {
280        let tool = FinishTaskTool::new();
281        assert_eq!(tool.name(), FINISH_TASK_TOOL_NAME);
282        assert_eq!(FINISH_TASK_TOOL_NAME, "finish_task");
283    }
284
285    /// The schema declares the exact `required` set and `status` enum from §5.8.
286    ///
287    /// Why: Guards the schema contract the extractor's generic validator relies
288    /// on — a drift here would silently change what's rejected upstream.
289    /// What: Assert `required == ["status", "summary"]` and the enum values.
290    /// Test: this test.
291    #[test]
292    fn schema_has_required_fields_and_enum() {
293        let schema = FinishTaskTool::new().schema();
294        let params = &schema["function"]["parameters"];
295        let required: Vec<&str> = params["required"]
296            .as_array()
297            .expect("required array")
298            .iter()
299            .filter_map(|v| v.as_str())
300            .collect();
301        assert_eq!(required, vec!["status", "summary"]);
302
303        let enum_values: Vec<&str> = params["properties"]["status"]["enum"]
304            .as_array()
305            .expect("enum array")
306            .iter()
307            .filter_map(|v| v.as_str())
308            .collect();
309        assert_eq!(enum_values, vec!["completed", "failed", "cancelled"]);
310
311        assert_eq!(params["additionalProperties"], json!(false));
312    }
313
314    /// `FinishStatus` renders its lowercase wire form via `Display`.
315    ///
316    /// Why: `render_finish_summary` depends on this exact casing.
317    /// What: Format each variant, assert the lowercase string.
318    /// Test: this test.
319    #[test]
320    fn status_display_and_roundtrip() {
321        assert_eq!(FinishStatus::Completed.to_string(), "completed");
322        assert_eq!(FinishStatus::Failed.to_string(), "failed");
323        assert_eq!(FinishStatus::Cancelled.to_string(), "cancelled");
324    }
325
326    /// `render_finish_summary` includes the status and summary text.
327    ///
328    /// Why: Guard the minimal happy-path rendering before layering on optional
329    /// fields.
330    /// What: A `FinishTaskArgs` with no changes/tests; assert the rendered text.
331    /// Test: this test.
332    #[test]
333    fn render_includes_status_and_summary() {
334        let args = FinishTaskArgs {
335            status: FinishStatus::Completed,
336            summary: "did the thing".to_string(),
337            changes: vec![],
338            tests_run: None,
339            tests_passed: None,
340        };
341        let rendered = render_finish_summary(&args);
342        assert_eq!(rendered, "Task completed: did the thing");
343    }
344
345    /// A valid, minimal `finish_task` call executes and renders the summary.
346    ///
347    /// Why: The primary happy path — only the two required fields present.
348    /// What: `execute({"status": "completed", "summary": "..."})`.
349    /// Test: this test.
350    #[tokio::test]
351    async fn execute_valid_args_renders_summary() {
352        let tool = FinishTaskTool::new();
353        let result = tool
354            .execute(json!({"status": "completed", "summary": "wrote the feature"}))
355            .await;
356        assert!(!result.is_error());
357        assert_eq!(result.content(), "Task completed: wrote the feature");
358    }
359
360    /// A call with `changes` and both test-count fields renders every section.
361    ///
362    /// Why: Guards the full-shape rendering path, not just the minimal one.
363    /// What: `execute` with two changes entries and matching test counts.
364    /// Test: this test.
365    #[tokio::test]
366    async fn execute_with_changes_and_tests_renders_all_fields() {
367        let tool = FinishTaskTool::new();
368        let result = tool
369            .execute(json!({
370                "status": "completed",
371                "summary": "added the widget",
372                "changes": [
373                    {"file": "src/widget.rs", "lines_added": 42, "lines_removed": 3},
374                    {"file": "src/lib.rs", "lines_added": 1, "lines_removed": 0}
375                ],
376                "tests_run": 12,
377                "tests_passed": 12
378            }))
379            .await;
380        assert!(!result.is_error());
381        let content = result.content();
382        assert!(content.contains("Task completed: added the widget"));
383        assert!(content.contains("src/widget.rs (+42/-3)"));
384        assert!(content.contains("src/lib.rs (+1/-0)"));
385        assert!(content.contains("Tests: 12/12 passed"));
386    }
387
388    /// A `failed` status with only `tests_run` (no `tests_passed`) renders that
389    /// single line, not the combined `x/y passed` form.
390    ///
391    /// Why: Guards the partial-test-info branch of the match in
392    /// `render_finish_summary`.
393    /// What: `execute` with `tests_run` only.
394    /// Test: this test.
395    #[tokio::test]
396    async fn execute_with_only_tests_run_renders_run_count() {
397        let tool = FinishTaskTool::new();
398        let result = tool
399            .execute(json!({
400                "status": "failed",
401                "summary": "tests did not all pass",
402                "tests_run": 5
403            }))
404            .await;
405        assert!(!result.is_error());
406        assert!(result.content().contains("Tests run: 5"));
407        assert!(!result.content().contains("passed\n"));
408    }
409
410    /// Arguments that bypass schema validation (e.g. called directly, as in
411    /// this test) but do not match `FinishTaskArgs`'s shape return a
412    /// recoverable error, never a panic.
413    ///
414    /// Why: `execute` must never `unwrap`/panic on attacker- or model-controlled
415    /// input, even though in the real dispatch path this shape would already
416    /// have been rejected by `schema::validate_args` before reaching here.
417    /// What: `execute({"status": "completed"})` — missing the required
418    /// `summary` field that `FinishTaskArgs` (unlike the schema's own leniency
419    /// elsewhere) requires as non-optional.
420    /// Test: this test.
421    #[tokio::test]
422    async fn execute_bypassing_schema_validation_is_recoverable() {
423        let tool = FinishTaskTool::new();
424        let result = tool.execute(json!({"status": "completed"})).await;
425        assert!(result.is_error());
426        assert!(!result.is_fatal(), "must be recoverable, not fatal");
427        assert!(
428            result
429                .content()
430                .contains("did not match the expected shape")
431        );
432    }
433
434    /// An unrecognised `status` value bypassing schema validation also reports
435    /// a recoverable error rather than panicking.
436    ///
437    /// Why: Guards the enum-deserialisation failure path specifically.
438    /// What: `execute({"status": "in_progress", "summary": "..."})`.
439    /// Test: this test.
440    #[tokio::test]
441    async fn execute_unknown_status_bypassing_schema_validation_is_recoverable() {
442        let tool = FinishTaskTool::new();
443        let result = tool
444            .execute(json!({"status": "in_progress", "summary": "still going"}))
445            .await;
446        assert!(result.is_error());
447        assert!(!result.is_fatal());
448    }
449}