trusty_code/session/registry_workstream.rs
1//! `SessionRegistry::bind_workstream` (DOC-48 §4.1/§5.3, issue #3298). Split
2//! out of `registry.rs` for the same 500-SLOC-cap reason as
3//! `registry_events.rs`/`registry_goals.rs` — this is a child module of
4//! `registry` (declared via `#[path = ...] mod workstream_binding;`), so it
5//! shares full access to `SessionRegistry`'s private `lock`/`record` helpers
6//! and `SessionEntry`'s fields exactly as if this method were still defined
7//! in that file.
8//!
9//! Why: `session::protocol::create` and `task::protocol::task_run` both need
10//! to stamp a freshly-minted session's immutable workstream binding once
11//! they've resolved it (either an explicit `workstream_id` param, §4.1, or
12//! §4.2's ambient active-workstream default) and PERSISTED it into
13//! [`crate::workstreams::store::WorkstreamStore`] (via
14//! `WorkstreamStore::bind_session`) — this is the registry-side half that
15//! also makes the binding observable on the `Session` snapshot
16//! (`session.status`/`session.list`) and publishes the DOC-48 §5.3
17//! `SessionAdded` event.
18//!
19//! Test: `registry_tests::bind_workstream_sets_field_and_publishes_session_added`,
20//! `registry_tests::bind_workstream_unknown_session_errors`.
21
22use super::*;
23
24impl SessionRegistry {
25 /// Stamp a freshly-minted session's immutable workstream binding, and
26 /// publish `Event::SessionAdded`.
27 ///
28 /// Why: `session::protocol::create` and `task::protocol::task_run` are
29 /// the ONLY callers, each calling this at most once — immediately after
30 /// `Self::create` mints the session's id and the caller has separately
31 /// persisted the binding into the workstream store — so there is no
32 /// setter that changes `Session.workstream_id` a second time; this
33 /// method itself does not enforce that (it would silently overwrite),
34 /// the immutability guarantee comes from the call sites never invoking
35 /// it twice for the same session (a REUSED session on `task.run` never
36 /// calls this again — see `task::protocol::task_run`'s docs on the
37 /// mismatch rejection it performs instead).
38 /// What: `Err(session_not_found)` if `id` is unknown; otherwise sets
39 /// `entry.session.workstream_id = Some(workstream_id)` and records+
40 /// publishes `Event::SessionAdded { session_id, workstream_id,
41 /// binding_time }` through the normal per-session ring buffer/live bus
42 /// (`Self::record`) — see that event's own docs for why this is what
43 /// lets `crate::workstreams::sse::aggregate_live`'s dynamic membership
44 /// re-check pick it up with no changes.
45 pub fn bind_workstream(
46 &self,
47 id: &str,
48 workstream_id: crate::workstreams::model::WorkstreamId,
49 ) -> Result<(), RpcError> {
50 {
51 let mut sessions = self.lock();
52 let entry = sessions
53 .get_mut(id)
54 .ok_or_else(|| RpcError::session_not_found(id))?;
55 entry.session.workstream_id = Some(workstream_id);
56 }
57 self.record(
58 id,
59 Event::SessionAdded {
60 session_id: id.to_string(),
61 workstream_id: workstream_id.to_string(),
62 binding_time: Utc::now(),
63 },
64 );
65 Ok(())
66 }
67
68 /// Record+publish `Event::SessionActivityUpdate` for `id` — a no-op for
69 /// an UNBOUND session.
70 ///
71 /// Why: `Self::set_run_outcome`'s sole activity-signal hook (module
72 /// docs) — split out here purely so that method's own diff stays small
73 /// enough for `registry.rs`'s 500-SLOC cap; behaviourally this is still
74 /// just `Self::record` with the event's shape.
75 /// What: `activity` is `None` when the session is not workstream-bound
76 /// — publish NOTHING, keeping an unbound session's event stream
77 /// byte-identical to the pre-#3298 baseline the M1 cutline e2e contract
78 /// freezes (see `set_run_outcome`'s docs for the full rationale) — and
79 /// `Some(has_running_task)` when it is. `last_turn_at` is stamped
80 /// `Utc::now()` at call time; the caller computes `activity` while
81 /// already holding the lock (reading `Session.workstream_id` and
82 /// `entry.execution`), so this helper does not re-lock.
83 pub(super) fn publish_activity_update(&self, id: &str, activity: Option<bool>) {
84 let Some(has_running_task) = activity else {
85 return;
86 };
87 self.record(
88 id,
89 Event::SessionActivityUpdate {
90 session_id: id.to_string(),
91 last_turn_at: Utc::now(),
92 has_running_task,
93 },
94 );
95 }
96}
97
98#[cfg(test)]
99mod tests {
100 use super::*;
101
102 /// `bind_workstream` must set the field and publish `SessionAdded` on
103 /// the session's own ring buffer/live bus.
104 #[tokio::test]
105 async fn bind_workstream_sets_field_and_publishes_session_added() {
106 let registry = SessionRegistry::new();
107 let session = registry.create("t".to_string(), None, ProjectBinding::None);
108 let ws_id = crate::workstreams::model::WorkstreamId::new();
109
110 registry.bind_workstream(&session.id, ws_id).expect("bind");
111
112 let status = registry.status(&session.id).expect("status");
113 assert_eq!(status.workstream_id, Some(ws_id));
114
115 let events = registry.replay(&session.id).expect("replay");
116 assert!(events.iter().any(|e| matches!(
117 &e.event,
118 Event::SessionAdded { workstream_id, .. } if *workstream_id == ws_id.to_string()
119 )));
120 }
121
122 /// An unknown session id must map to `session_not_found`.
123 #[tokio::test]
124 async fn bind_workstream_unknown_session_errors() {
125 let registry = SessionRegistry::new();
126 let ws_id = crate::workstreams::model::WorkstreamId::new();
127 let err = registry.bind_workstream("nope", ws_id).unwrap_err();
128 assert_eq!(err.code, -32007);
129 }
130}