Skip to main content

trusty_code/session/
registry_goals.rs

1//! `SessionRegistry`'s #2350 operator-facing goal-slot plumbing:
2//! `session.set_goal`/`session.clear_goal`/`session.get_goals`. Split out of
3//! `registry.rs` for the same 500-SLOC-cap reason as `registry_events.rs`/
4//! `registry_memory_sink.rs` — this is a child module of `registry`
5//! (declared via `#[path = ...] mod goal_ops;`), so it shares full access to
6//! `SessionRegistry`'s private `lock` helper and `SessionEntry`'s fields
7//! exactly as if these methods were still defined in that file.
8//!
9//! Why: `agent_loop::goals::GoalSlots` already lets the PM's own model write
10//! goals via the `set_goal`/`clear_goal` tools (#2347), each tagged
11//! `GoalSource::Model`. An operator (human, or a future TUI/CLI) needs the
12//! SAME shared slots reachable over `session.*` JSON-RPC, tagged
13//! `GoalSource::Operator` — last-write-wins between the two sources is
14//! implicit in `GoalSlots::set` simply overwriting whichever slot is named,
15//! regardless of who wrote it last.
16//! **Design decision (documented per the ticket):** the goal slots live on
17//! `Transcript` (`SessionEntry.pm_transcript`), which is only seeded on a
18//! session's FIRST `task.run` (`SessionRegistry::begin_pm_transcript`). A
19//! session that has never run a task has no `Transcript` and therefore no
20//! goal-slot storage to write into yet. Rather than adding a second,
21//! parallel "pending goals" slot on `SessionEntry` that would need to be
22//! applied at the first `begin_pm_transcript` call (a real design, but more
23//! moving parts than this ticket's scope needs), `set_goal`/`clear_goal`
24//! return a clear `invalid_argument` error naming the limitation. `get_goals`
25//! takes the simpler read-side convention already established by
26//! `get_transcript`: a session with no transcript yet is a valid EMPTY
27//! result, not an error. Upgrading `set_goal` to a pending-goals path that
28//! applies on the first run is documented future work, not needed here.
29//! What: `set_goal`/`clear_goal` resolve `id`'s `pm_transcript`'s
30//! `goals_handle()`, erroring `session_not_found` if the session itself is
31//! unknown or `invalid_argument` if it has no transcript yet or the slot
32//! index is out of range; `get_goals` returns `[]` for a never-run session
33//! rather than erroring. [`goal_records`] is the shared snapshot helper
34//! `registry.rs`'s `get_transcript` also calls, so `TranscriptRecord.goals`
35//! and `session.get_goals` can never independently drift on shape.
36//! Test: `registry_tests::set_goal_*`, `registry_tests::clear_goal_*`,
37//! `registry_tests::get_goals_*`,
38//! `registry_tests::get_transcript_round_trips_goal_state`.
39
40use super::*;
41use crate::agent_loop::{GoalSlots, GoalSource};
42use crate::session::transcript::GoalSlotRecord;
43
44impl SessionRegistry {
45    /// `session.set_goal`: write an operator-provided goal into a 1-based
46    /// slot (#2350).
47    ///
48    /// Why: the operator-facing counterpart to the model-facing `set_goal`
49    /// tool (#2347) — same shared `GoalSlots`, tagged `GoalSource::Operator`
50    /// so a later read can tell the two apart.
51    /// What: `Err(session_not_found)` if `id` is unknown. `Err(invalid_argument)`
52    /// if the session has no `pm_transcript` yet (see module docs' design
53    /// decision) or if `slot` is `0`/greater than `GOAL_SLOT_COUNT`. A
54    /// poisoned goals lock is recovered (mirrors `tools::goals`'s
55    /// convention) rather than propagating a panic.
56    /// Test: `registry_tests::set_goal_writes_operator_source`,
57    /// `registry_tests::set_goal_no_transcript_yet_errors`,
58    /// `registry_tests::set_goal_out_of_range_slot_errors`,
59    /// `registry_tests::set_goal_unknown_session_errors`.
60    pub fn set_goal(&self, id: &str, slot: usize, text: &str) -> Result<(), RpcError> {
61        let handle = self.goals_handle(id)?;
62        let mut guard = handle.lock().unwrap_or_else(|p| p.into_inner());
63        guard
64            .set(slot, text, GoalSource::Operator)
65            .map_err(|e| RpcError::invalid_argument(e.to_string()))
66    }
67
68    /// `session.clear_goal`: clear an operator-named 1-based slot (#2350).
69    ///
70    /// Why: the operator-facing counterpart to the model-facing `clear_goal`
71    /// tool (#2347).
72    /// What: same error shape as [`Self::set_goal`]. Clearing an
73    /// already-empty slot is idempotent success (mirrors
74    /// `GoalSlots::clear`'s own convention).
75    /// Test: `registry_tests::clear_goal_clears_slot`,
76    /// `registry_tests::clear_goal_no_transcript_yet_errors`,
77    /// `registry_tests::clear_goal_out_of_range_slot_errors`.
78    pub fn clear_goal(&self, id: &str, slot: usize) -> Result<(), RpcError> {
79        let handle = self.goals_handle(id)?;
80        let mut guard = handle.lock().unwrap_or_else(|p| p.into_inner());
81        guard
82            .clear(slot)
83            .map_err(|e| RpcError::invalid_argument(e.to_string()))
84    }
85
86    /// `session.get_goals`: snapshot every currently-occupied goal slot
87    /// (#2350).
88    ///
89    /// Why: the operator-facing read path — lets a client inspect the
90    /// current goal state (from either source) without going through
91    /// `session.get_transcript`'s larger payload.
92    /// What: `Err(session_not_found)` if `id` is unknown; otherwise
93    /// [`goal_records`] — `[]` for a session with no `pm_transcript` yet,
94    /// matching `session.get_transcript`'s never-run convention rather than
95    /// `set_goal`/`clear_goal`'s stricter error.
96    /// Test: `registry_tests::get_goals_returns_operator_and_model_sources`,
97    /// `registry_tests::get_goals_on_never_run_session_is_empty`,
98    /// `registry_tests::get_goals_unknown_session_errors`.
99    pub fn get_goals(&self, id: &str) -> Result<Vec<GoalSlotRecord>, RpcError> {
100        let sessions = self.lock();
101        let entry = sessions
102            .get(id)
103            .ok_or_else(|| RpcError::session_not_found(id))?;
104        Ok(goal_records(entry))
105    }
106
107    /// Resolve `id`'s live `GoalSlots` handle, shared by `set_goal`/`clear_goal`.
108    ///
109    /// Why: both mutators need the identical "unknown session" vs.
110    /// "no transcript yet" error mapping — centralising it here means they
111    /// can never independently drift on the design decision documented in
112    /// the module docs.
113    /// What: `Err(session_not_found)` if `id` is unknown; `Err(invalid_argument)`
114    /// naming the "run a task first" limitation if `pm_transcript` is `None`;
115    /// otherwise the cloned `Arc<Mutex<GoalSlots>>` handle.
116    fn goals_handle(&self, id: &str) -> Result<Arc<Mutex<GoalSlots>>, RpcError> {
117        let sessions = self.lock();
118        let entry = sessions
119            .get(id)
120            .ok_or_else(|| RpcError::session_not_found(id))?;
121        entry
122            .pm_transcript
123            .as_ref()
124            .map(Transcript::goals_handle)
125            .ok_or_else(|| {
126                RpcError::invalid_argument(format!(
127                    "session {id} has no transcript yet — run a task first before setting a goal"
128                ))
129            })
130    }
131}
132
133/// Snapshot a `SessionEntry`'s current goal slots as wire-shaped
134/// [`GoalSlotRecord`]s, or `[]` if it has no `pm_transcript` yet.
135///
136/// Why: shared by [`SessionRegistry::get_goals`] and `registry.rs`'s
137/// `SessionRegistry::get_transcript` (`TranscriptRecord.goals`) so the two
138/// read paths can never disagree on shape or on the never-run-session
139/// convention.
140/// What: `None` `pm_transcript` -> `vec![]`; otherwise locks the transcript's
141/// `goals_handle()` (recovering a poisoned lock) and maps every
142/// `GoalSlots::occupied` pair through `GoalSlotRecord::from_slot`.
143pub(super) fn goal_records(entry: &SessionEntry) -> Vec<GoalSlotRecord> {
144    entry
145        .pm_transcript
146        .as_ref()
147        .map(|t| {
148            let handle = t.goals_handle();
149            let guard = handle.lock().unwrap_or_else(|p| p.into_inner());
150            guard
151                .occupied()
152                .into_iter()
153                .map(|(slot, g)| GoalSlotRecord::from_slot(slot, g))
154                .collect()
155        })
156        .unwrap_or_default()
157}