trusty_code/tools/goals.rs
1//! `set_goal` / `clear_goal` tools — model-driven writes to the session's 5
2//! fixed privileged goal slots (#2347, epic #2343 pillar 3).
3//!
4//! Why: `agent_loop::goals::GoalSlots` is the storage; something must let the
5//! PM's own model write to it mid-conversation the same way `finish_task`
6//! (`tools::finish_task`) lets it signal completion — a schema-validated
7//! `ToolExecutor` pair, following that module's stateless-tool pattern except
8//! these two DO hold state: a shared `Arc<Mutex<GoalSlots>>` handle onto the
9//! live session `Transcript` (see `agent_loop::transcript::Transcript::goals_handle`),
10//! rather than an `AgentRunner` or config dir as `delegate_to_agent`
11//! (`tools::delegate`) holds. Both tools write with `GoalSource::Model` — the
12//! future operator-facing `session.set_goal` RPC (#2350) writes the same
13//! `GoalSlots` with `GoalSource::Operator` through a different call path, not
14//! through these tools.
15//! What: [`SetGoalTool`] and [`ClearGoalTool`] each wrap an
16//! `Arc<Mutex<GoalSlots>>`. `execute` parses/validates the JSON args, then
17//! calls [`GoalSlots::set`]/[`GoalSlots::clear`] under the lock; an
18//! out-of-range slot or a poisoned lock both become a recoverable
19//! `ToolResult::err` (never a panic). Registered ONLY in the daemon-session
20//! path's PM tool registry (`task::executor::run_and_record`) — `run_task`'s
21//! one-shot/bake-off path and delegated engineer registries never see these
22//! tools, since goal slots are a session (not sub-agent) feature.
23//! Test: `tests::*` — schema shape, valid set/clear round-trip through a
24//! shared handle, out-of-range slot error handling for both tools.
25
26use std::sync::{Arc, Mutex};
27
28use async_trait::async_trait;
29use serde::Deserialize;
30use serde_json::{Value, json};
31
32use crate::agent_loop::{GoalSlots, GoalSource};
33use crate::tools::traits::{ToolExecutor, ToolResult};
34
35/// The `set_goal` tool's registered/advertised name.
36pub const SET_GOAL_TOOL_NAME: &str = "set_goal";
37
38/// The `clear_goal` tool's registered/advertised name.
39pub const CLEAR_GOAL_TOOL_NAME: &str = "clear_goal";
40
41/// Parsed `set_goal` arguments.
42#[derive(Debug, Deserialize)]
43struct SetGoalArgs {
44 slot: usize,
45 text: String,
46}
47
48/// Parsed `clear_goal` arguments.
49#[derive(Debug, Deserialize)]
50struct ClearGoalArgs {
51 slot: usize,
52}
53
54/// Lock `goals`, degrading a poisoned lock to a recoverable `ToolResult::err`
55/// rather than panicking.
56///
57/// Why: Shared by both tools' `execute` so the poison-handling convention
58/// (mirrors `run_task::recorder`'s `if let Ok(guard) = ...lock() {...}`
59/// pattern, adapted here to return a value rather than silently no-op, since
60/// a dropped goal write is a worse failure mode for a tool call than a
61/// dropped accounting record) can never drift between them.
62fn lock_or_recoverable_error(
63 goals: &Mutex<GoalSlots>,
64) -> Result<std::sync::MutexGuard<'_, GoalSlots>, ToolResult> {
65 goals
66 .lock()
67 .map_err(|_| ToolResult::err("goal slots lock was poisoned by a prior panic"))
68}
69
70/// `ToolExecutor` for `set_goal` (#2347).
71///
72/// Why: See module docs.
73/// What: Holds the shared `Arc<Mutex<GoalSlots>>`; `execute` writes with
74/// `GoalSource::Model`.
75/// Test: `tests::set_goal_valid_args_writes_slot`,
76/// `tests::set_goal_out_of_range_slot_is_recoverable_error`,
77/// `tests::set_goal_malformed_args_is_recoverable_error`.
78pub struct SetGoalTool {
79 goals: Arc<Mutex<GoalSlots>>,
80}
81
82impl SetGoalTool {
83 /// Construct with a shared handle onto the session's live goal slots.
84 ///
85 /// Why: Callers get this handle from `agent_loop::transcript::Transcript::goals_handle`
86 /// so this tool and `to_messages`'s rendering share the exact same state.
87 /// What: Stores the `Arc` clone.
88 /// Test: `tests::set_goal_valid_args_writes_slot`.
89 pub fn new(goals: Arc<Mutex<GoalSlots>>) -> Self {
90 Self { goals }
91 }
92}
93
94#[async_trait]
95impl ToolExecutor for SetGoalTool {
96 fn name(&self) -> &str {
97 SET_GOAL_TOOL_NAME
98 }
99
100 /// JSON schema for `set_goal`.
101 ///
102 /// Why: The tool's `description` carries the "record standing goals, not
103 /// todos" usage guidance directly (#2347 keeps this out of
104 /// `prompt/assembler.rs`/`preamble.rs`), since the schema description is
105 /// always in the model's context whenever the tool is advertised.
106 /// What: `slot` (integer 1-5, required), `text` (string, required).
107 /// Test: `tests::set_goal_schema_has_required_fields`.
108 fn schema(&self) -> Value {
109 json!({
110 "type": "function",
111 "function": {
112 "name": SET_GOAL_TOOL_NAME,
113 "description": "Record or update one of your 5 fixed, privileged standing goals — objectives that persist across turns and survive context compaction. These are NOT a todo list: use this only when your actual, durable objective changes (e.g. the user gives you a new top-level task, or a sub-objective is added). Do not use this for step-by-step task tracking.",
114 "parameters": {
115 "type": "object",
116 "properties": {
117 "slot": {
118 "type": "integer",
119 "description": "Which of the 5 fixed goal slots to write (1-5). Writing an occupied slot replaces its previous content."
120 },
121 "text": {
122 "type": "string",
123 "description": "The standing goal's description."
124 }
125 },
126 "required": ["slot", "text"],
127 "additionalProperties": false
128 }
129 }
130 })
131 }
132
133 /// Write the (already schema-validated) `slot`/`text` into `GoalSlots`.
134 ///
135 /// Why: By the time `execute` runs, `ToolCallExtractor::parse_and_validate`
136 /// has already checked the shape against [`Self::schema`]; the `Err`
137 /// deserialisation branch below is a defensive fallback (no panic) for a
138 /// shape the loose schema validator accepted but strict `serde` rejects —
139 /// mirrors `FinishTaskTool::execute`'s same defensive shape.
140 /// What: `Ok` -> `GoalSlots::set(slot, text, GoalSource::Model)`; an
141 /// out-of-range slot becomes a recoverable `ToolResult::err` naming the
142 /// bad value.
143 /// Test: `tests::set_goal_valid_args_writes_slot`,
144 /// `tests::set_goal_out_of_range_slot_is_recoverable_error`,
145 /// `tests::set_goal_malformed_args_is_recoverable_error`.
146 async fn execute(&self, args: Value) -> ToolResult {
147 let parsed: SetGoalArgs = match serde_json::from_value(args) {
148 Ok(p) => p,
149 Err(e) => {
150 return ToolResult::err(format!(
151 "set_goal arguments did not match the expected shape ({e}). \
152 'slot' must be an integer 1-5 and 'text' must be a string."
153 ));
154 }
155 };
156
157 let mut guard = match lock_or_recoverable_error(&self.goals) {
158 Ok(g) => g,
159 Err(err) => return err,
160 };
161
162 match guard.set(parsed.slot, parsed.text.clone(), GoalSource::Model) {
163 Ok(()) => ToolResult::ok(format!("Goal slot {} set: {}", parsed.slot, parsed.text)),
164 Err(e) => ToolResult::err(e.to_string()),
165 }
166 }
167}
168
169/// `ToolExecutor` for `clear_goal` (#2347).
170///
171/// Why: See module docs.
172/// What: Holds the shared `Arc<Mutex<GoalSlots>>`; `execute` clears the
173/// named slot.
174/// Test: `tests::clear_goal_valid_args_clears_slot`,
175/// `tests::clear_goal_out_of_range_slot_is_recoverable_error`.
176pub struct ClearGoalTool {
177 goals: Arc<Mutex<GoalSlots>>,
178}
179
180impl ClearGoalTool {
181 /// Construct with a shared handle onto the session's live goal slots.
182 ///
183 /// Why: Mirrors `SetGoalTool::new` — same shared handle, so both tools
184 /// and `Transcript::to_messages` stay in sync.
185 /// What: Stores the `Arc` clone.
186 /// Test: `tests::clear_goal_valid_args_clears_slot`.
187 pub fn new(goals: Arc<Mutex<GoalSlots>>) -> Self {
188 Self { goals }
189 }
190}
191
192#[async_trait]
193impl ToolExecutor for ClearGoalTool {
194 fn name(&self) -> &str {
195 CLEAR_GOAL_TOOL_NAME
196 }
197
198 /// JSON schema for `clear_goal`.
199 ///
200 /// What: `slot` (integer 1-5, required).
201 /// Test: `tests::clear_goal_schema_has_required_fields`.
202 fn schema(&self) -> Value {
203 json!({
204 "type": "function",
205 "function": {
206 "name": CLEAR_GOAL_TOOL_NAME,
207 "description": "Retire one of your 5 fixed, privileged standing goals once it is fully accomplished or no longer relevant, leaving that slot empty.",
208 "parameters": {
209 "type": "object",
210 "properties": {
211 "slot": {
212 "type": "integer",
213 "description": "Which of the 5 fixed goal slots to clear (1-5)."
214 }
215 },
216 "required": ["slot"],
217 "additionalProperties": false
218 }
219 }
220 })
221 }
222
223 /// Clear the (already schema-validated) `slot`.
224 ///
225 /// What: `Ok` -> `GoalSlots::clear(slot)`; an out-of-range slot becomes
226 /// a recoverable `ToolResult::err`.
227 /// Test: `tests::clear_goal_valid_args_clears_slot`,
228 /// `tests::clear_goal_out_of_range_slot_is_recoverable_error`.
229 async fn execute(&self, args: Value) -> ToolResult {
230 let parsed: ClearGoalArgs = match serde_json::from_value(args) {
231 Ok(p) => p,
232 Err(e) => {
233 return ToolResult::err(format!(
234 "clear_goal arguments did not match the expected shape ({e}). \
235 'slot' must be an integer 1-5."
236 ));
237 }
238 };
239
240 let mut guard = match lock_or_recoverable_error(&self.goals) {
241 Ok(g) => g,
242 Err(err) => return err,
243 };
244
245 match guard.clear(parsed.slot) {
246 Ok(()) => ToolResult::ok(format!("Goal slot {} cleared.", parsed.slot)),
247 Err(e) => ToolResult::err(e.to_string()),
248 }
249 }
250}
251
252#[cfg(test)]
253#[path = "goals_tests.rs"]
254mod tests;