trusty_code/agent_loop/goals.rs
1//! Goal slots: 5 fixed, privileged standing-goal slots pinned near the top
2//! of the prompt (#2347, epic #2343 pillar 3).
3//!
4//! Why: Infinite Sessions (#2343) must keep a long-running PM anchored on
5//! its objective even after many rounds of compaction/summarisation have
6//! discarded the turns that originally stated it. A free-form "remember
7//! your goal" instruction buried in the transcript is exactly the kind of
8//! content non-destructive compaction (#2070) is entitled to fold into a
9//! summary once it ages out of the kept window — so goals cannot live as an
10//! ordinary transcript entry. Fixed, numbered slots (rather than an
11//! unbounded list) keep the injected block small and bounded — the vision
12//! spec's ~2K-token goals budget out of the 200K-window overhead accounting
13//! (#2343) assumes a small constant number of slots, not an
14//! attacker/model-controlled list length.
15//! What: [`GoalSlots`] holds exactly [`GOAL_SLOT_COUNT`] `Option<GoalSlot>`
16//! entries. [`GoalSlots::set`]/[`GoalSlots::clear`] mutate a 1-based slot
17//! number (matching the `set_goal`/`clear_goal` tool schemas in
18//! `tools::goals`), returning [`GoalSlotError::OutOfRange`] rather than
19//! panicking on an out-of-range index. [`GoalSlots::render`] produces the
20//! synthetic prompt block `agent_loop::transcript::Transcript::to_messages`
21//! injects at position `[1]` — `None` when every slot is empty, so an
22//! all-empty `GoalSlots` never adds a message at all.
23//! Test: `goals_tests::*` — set/clear round-trips, out-of-range rejection,
24//! render formatting (numbering skips empty slots, `None` when all empty),
25//! and that `set` overwrites in place (updating `updated_at`) rather than
26//! appending.
27
28use chrono::{DateTime, Utc};
29use serde::{Deserialize, Serialize};
30use thiserror::Error;
31
32/// The number of fixed goal slots (#2343 design decision: exactly 5).
33///
34/// Why: A fixed, small constant — rather than a caller-supplied capacity —
35/// is what makes the rendered block's size bounded and predictable for the
36/// epic's overhead-budget accounting; growing it is a deliberate design
37/// change, not a runtime configuration knob.
38pub const GOAL_SLOT_COUNT: usize = 5;
39
40/// Who last wrote a given [`GoalSlot`].
41///
42/// Why: `set_goal` (the `tools::goals::SetGoalTool` the PM's own model
43/// calls) and the future operator-facing `session.set_goal` RPC (#2350)
44/// both mutate the same [`GoalSlots`]; recording the source lets a future
45/// UI/audit view distinguish "the model decided this" from "an operator
46/// pinned this" without a second parallel data structure.
47/// Test: `goals_tests::set_records_model_source`,
48/// `goals_tests::goal_source_serialises_snake_case`.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
50#[serde(rename_all = "snake_case")]
51pub enum GoalSource {
52 /// Written by the PM's own model via the `set_goal` tool call.
53 Model,
54 /// Written by a human operator (#2350's `session.set_goal` RPC).
55 Operator,
56}
57
58/// One occupied goal slot: its text, who wrote it, and when.
59///
60/// Why: A bare `String` would lose the provenance/recency information a
61/// future operator-facing view (#2350) needs; bundling all three in one
62/// struct keeps `GoalSlots`'s storage a simple fixed-size array of
63/// `Option<GoalSlot>` rather than three parallel arrays.
64/// What: `text` is the free-form goal description; `source` is
65/// [`GoalSource`]; `updated_at` is the UTC timestamp of the last `set` call
66/// that wrote this slot (matching the `chrono::Utc` convention already used
67/// by `session::registry`/`session::model` for session timestamps).
68/// Test: `goals_tests::set_then_get_round_trips_all_fields`.
69#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
70pub struct GoalSlot {
71 /// Free-form goal description.
72 pub text: String,
73 /// Who last wrote this slot.
74 pub source: GoalSource,
75 /// UTC timestamp of the last write.
76 pub updated_at: DateTime<Utc>,
77}
78
79/// Slot-index validation failure.
80///
81/// Why: `set`/`clear` accept a caller- (ultimately model-) supplied 1-based
82/// slot number; an out-of-range value (0, or greater than
83/// [`GOAL_SLOT_COUNT`]) must be a recoverable error the LLM tool layer can
84/// report back to the model, never a panic/index-out-of-bounds.
85/// What: The single variant names the offending `slot` value so the
86/// rendered error message is actionable.
87/// Test: `goals_tests::set_out_of_range_slot_errors`,
88/// `goals_tests::clear_out_of_range_slot_errors`.
89#[derive(Debug, Error, Clone, Copy, PartialEq, Eq)]
90pub enum GoalSlotError {
91 /// `slot` was `0` or greater than [`GOAL_SLOT_COUNT`].
92 #[error("goal slot {slot} out of range: must be between 1 and {GOAL_SLOT_COUNT}")]
93 OutOfRange {
94 /// The invalid slot number as supplied by the caller.
95 slot: usize,
96 },
97}
98
99/// The fixed preamble prefixed to every non-empty [`GoalSlots::render`]
100/// output.
101///
102/// Why: Without an explicit framing line the model has no way to tell this
103/// injected block apart from an ordinary system note, and might treat it as
104/// a todo list to be checked off and discarded rather than a standing
105/// objective to keep re-reading. Fixed rather than configurable per #2347's
106/// scope: the schema descriptions on the `set_goal`/`clear_goal` tools (not
107/// this preamble) carry the "not todos" usage guidance per the issue's
108/// explicit "do NOT modify prompt/assembler.rs or preamble.rs" constraint.
109const GOALS_PREAMBLE: &str = "## Active Goals\n\
110These are your privileged, standing goals — fixed slots that persist across \
111turns and survive context compaction. They are not a todo list; use \
112set_goal/clear_goal only when the underlying objective itself changes.";
113
114/// Exactly [`GOAL_SLOT_COUNT`] fixed, privileged goal slots (#2347).
115///
116/// Why: See module docs — this is the in-memory state
117/// `agent_loop::transcript::Transcript` renders fresh on every
118/// `to_messages()` call and `tools::goals::{SetGoalTool, ClearGoalTool}`
119/// mutate on the model's behalf.
120/// What: A fixed-size array of `Option<GoalSlot>`; `Default` is all-empty.
121/// Test: `goals_tests::*`.
122#[derive(Debug, Clone, Default, PartialEq)]
123pub struct GoalSlots {
124 slots: [Option<GoalSlot>; GOAL_SLOT_COUNT],
125}
126
127impl GoalSlots {
128 /// Construct an all-empty `GoalSlots`.
129 ///
130 /// Why: Explicit constructor mirrors this crate's `Tool::new()`
131 /// convention even though `Default` would do the same.
132 /// Test: `goals_tests::new_is_all_empty`.
133 pub fn new() -> Self {
134 Self::default()
135 }
136
137 /// Write (or overwrite) a 1-based `slot` with `text` from `source`.
138 ///
139 /// Why: The model-facing `set_goal` tool and the future operator RPC
140 /// (#2350) both need one shared, validated write path rather than
141 /// reaching into the array directly.
142 /// What: Validates `slot` via [`Self::validate`], then replaces (does
143 /// NOT append to) that slot with a fresh `GoalSlot { text, source,
144 /// updated_at: Utc::now() }`. Overwriting an occupied slot discards its
145 /// previous content — slots hold the CURRENT goal only, not a history.
146 /// Test: `goals_tests::set_then_get_round_trips_all_fields`,
147 /// `goals_tests::set_overwrites_existing_slot`,
148 /// `goals_tests::set_out_of_range_slot_errors`.
149 pub fn set(
150 &mut self,
151 slot: usize,
152 text: impl Into<String>,
153 source: GoalSource,
154 ) -> Result<(), GoalSlotError> {
155 let idx = Self::validate(slot)?;
156 self.slots[idx] = Some(GoalSlot {
157 text: text.into(),
158 source,
159 updated_at: Utc::now(),
160 });
161 Ok(())
162 }
163
164 /// Clear a 1-based `slot`, leaving it empty.
165 ///
166 /// Why: The model-facing `clear_goal` tool needs a validated way to
167 /// retire a completed/obsolete goal without disturbing the other four
168 /// slots.
169 /// What: Validates `slot` via [`Self::validate`], then sets it to
170 /// `None`. Clearing an already-empty slot is a no-op success, not an
171 /// error — idempotent clearing is simpler for the model to reason about
172 /// than a "nothing to clear" failure.
173 /// Test: `goals_tests::clear_empties_slot`,
174 /// `goals_tests::clear_already_empty_slot_is_ok`,
175 /// `goals_tests::clear_out_of_range_slot_errors`.
176 pub fn clear(&mut self, slot: usize) -> Result<(), GoalSlotError> {
177 let idx = Self::validate(slot)?;
178 self.slots[idx] = None;
179 Ok(())
180 }
181
182 /// Read the current content of a 1-based `slot`, if occupied.
183 ///
184 /// Why: Test/observability accessor; also lets a future operator view
185 /// (#2350) inspect one slot without re-deriving the whole rendered
186 /// block.
187 /// What: Returns `None` for an out-of-range slot OR an empty one — the
188 /// two cases are intentionally not distinguished here (callers that
189 /// need to distinguish "invalid" from "empty" use `set`/`clear`'s
190 /// `Result` instead).
191 /// Test: `goals_tests::set_then_get_round_trips_all_fields`.
192 pub fn get(&self, slot: usize) -> Option<&GoalSlot> {
193 let idx = slot.checked_sub(1)?;
194 self.slots.get(idx)?.as_ref()
195 }
196
197 /// Snapshot every currently-occupied slot as `(1-based slot, GoalSlot)`
198 /// pairs, in slot order (#2350).
199 ///
200 /// Why: `session.get_goals` and `TranscriptRecord.goals`
201 /// (`session::transcript`) both need a serialisable view of every
202 /// occupied slot together with its 1-based index — cloning here (rather
203 /// than returning references) lets the caller build its own DTO without
204 /// holding this `GoalSlots`'s lock any longer than the snapshot itself.
205 /// What: Filters out empty slots, cloning each occupied `GoalSlot` paired
206 /// with its 1-based slot number.
207 /// Test: `goals_tests::occupied_skips_empty_slots_and_preserves_index`,
208 /// `goals_tests::occupied_empty_when_all_slots_empty`.
209 pub fn occupied(&self) -> Vec<(usize, GoalSlot)> {
210 self.slots
211 .iter()
212 .enumerate()
213 .filter_map(|(i, slot)| slot.clone().map(|g| (i + 1, g)))
214 .collect()
215 }
216
217 /// Render the privileged-goals prompt block, or `None` if every slot is
218 /// empty.
219 ///
220 /// Why: This is what `Transcript::to_messages` injects at position
221 /// `[1]` on every call — computed fresh from live state rather than
222 /// stored, so it can never drift from what `set`/`clear` last wrote.
223 /// Returning `None` when nothing is set means an all-empty `GoalSlots`
224 /// injects NOTHING, matching the acceptance criterion that the goals
225 /// message is absent (not an empty stub) when no goal has ever been set.
226 /// What: Numbers each occupied slot by its 1-based position, skipping
227 /// empty slots entirely (so slot 3 alone renders as `"3. <text>"`, not
228 /// `"1. <text>"`), joined under [`GOALS_PREAMBLE`].
229 /// Test: `goals_tests::render_none_when_all_empty`,
230 /// `goals_tests::render_numbers_by_slot_skipping_empty`,
231 /// `goals_tests::render_includes_preamble`.
232 pub fn render(&self) -> Option<String> {
233 let lines: Vec<String> = self
234 .slots
235 .iter()
236 .enumerate()
237 .filter_map(|(i, slot)| slot.as_ref().map(|g| format!("{}. {}", i + 1, g.text)))
238 .collect();
239 if lines.is_empty() {
240 return None;
241 }
242 Some(format!("{GOALS_PREAMBLE}\n{}", lines.join("\n")))
243 }
244
245 /// Validate a 1-based slot number, returning its 0-based array index.
246 ///
247 /// Why: Shared by `set`/`clear` so the range check and error shape can
248 /// never drift between the two mutators.
249 /// What: `Ok(slot - 1)` for `1..=GOAL_SLOT_COUNT`; `Err(OutOfRange)`
250 /// otherwise (covers both `0` and anything past the last slot).
251 fn validate(slot: usize) -> Result<usize, GoalSlotError> {
252 if slot == 0 || slot > GOAL_SLOT_COUNT {
253 return Err(GoalSlotError::OutOfRange { slot });
254 }
255 Ok(slot - 1)
256 }
257}
258
259#[cfg(test)]
260#[path = "goals_tests.rs"]
261mod tests;