trusty_code/session/registry.rs
1//! Daemon-owned session registry: storage, per-session sequencing, ring
2//! buffer, and attach/detach bookkeeping (#2054, #2055).
3//!
4//! Why: this is the object Axiom 4 describes — sessions live INSIDE the
5//! daemon, not in a CLI-side tmux pane. `SessionRegistry` is the single
6//! owner of every `Session`'s state, its bounded event history, and (#2055)
7//! the per-session sequence counter that makes replay -> live gap detection
8//! possible. Designed so persistence (Phase 2+, out of scope per §12) can be
9//! added by swapping the storage backing this type without touching
10//! `session::protocol`'s handlers or the wire protocol at all.
11//! What: [`SessionRegistry`] holds `HashMap<String, SessionEntry>` behind a
12//! `std::sync::Mutex` (never held across an `.await` — every method here is
13//! synchronous; `attach` uses `tokio::spawn` to hand off, not to block).
14//! Each entry carries the `Session` snapshot, a monotonic per-session `seq`
15//! counter, a bounded ring buffer of recent
16//! `crate::events::SessionEventEnvelope`s (§12.1.5: default 1000, oldest
17//! dropped first), and a map of live attachments (`connection_id` ->
18//! `oneshot::Sender<()>` used by `detach` to stop that connection's
19//! forwarder task). [`Self::record`] is the ONE place that assigns `seq`
20//! (under the same lock that pushes the ring buffer entry), so replay and
21//! every subsequent live event share one gap-free, strictly increasing
22//! sequence — see `crate::events`'s module docs for the full envelope
23//! rationale. `attach` replays the ring buffer synchronously, then spawns a
24//! task that subscribes to the existing process-global `crate::events` bus,
25//! filters by `session_id`, and forwards matching envelopes into the
26//! caller's `NotifySender` until detached or the channel closes (the
27//! connection is gone).
28//! Test: see `registry_tests` (sibling file, `#[cfg(test)]`).
29
30use std::collections::{HashMap, VecDeque};
31use std::sync::atomic::{AtomicBool, Ordering};
32use std::sync::{Arc, Mutex};
33use std::time::Duration;
34
35use chrono::Utc;
36use serde_json::json;
37use tokio::sync::oneshot;
38use tokio::task::JoinHandle;
39use uuid::Uuid;
40
41use crate::events::{Event, SessionEventEnvelope};
42use crate::jsonrpc::{NotifySender, RpcError};
43use crate::mode::HarnessMode;
44use crate::perf::TokenUsage;
45use crate::run_task::TurnRecord;
46
47use super::model::{Session, SessionStatus};
48use super::transcript::TranscriptRecord;
49
50/// Default ring-buffer capacity per session (vision spec §12, 11.5).
51///
52/// Why: bounds per-session memory use; a freshly-attached client sees
53/// "recent progress but not the full session history" per spec — the ring
54/// buffer is the LIVE-event window, distinct from the full run transcript
55/// `session.get_transcript` (#2058) exposes via `Self::get_transcript`.
56/// Test: `registry_tests::ring_buffer_drops_oldest_when_full`.
57pub const DEFAULT_RING_CAPACITY: usize = 1000;
58
59/// One session's storage: the domain snapshot, its sequence counter, ring
60/// buffer, the live attachments forwarding its events, and (#2056) its
61/// background execution state + last completed run's outcome.
62struct SessionEntry {
63 session: Session,
64 /// Last-assigned per-session sequence number; the next event gets
65 /// `seq + 1`. Starts at `0` so the first recorded event is `seq = 1`.
66 seq: u64,
67 ring: VecDeque<SessionEventEnvelope>,
68 /// `connection_id` -> the cancel sender for that connection's forwarder
69 /// task. Re-attaching the same connection to the same session replaces
70 /// (and thus cancels, via `Sender` drop) the previous forwarder.
71 attachments: HashMap<Uuid, oneshot::Sender<()>>,
72 /// #2056: set while a background task-execution is in flight; `None`
73 /// when idle (never started, or already finished).
74 execution: Option<Execution>,
75 /// #2056: the run transcript populated once an execution finishes;
76 /// exposed read-only via `session.get_transcript` (#2058,
77 /// `Self::get_transcript`). Empty until the first execution completes.
78 transcript: Vec<TurnRecord>,
79 /// #2056: aggregated token usage from the last completed execution.
80 usage: TokenUsage,
81 /// #2056: summed USD cost from the last completed execution (`None` if
82 /// pricing was unavailable — mirrors `run_task::RunReport::cost_usd`).
83 cost_usd: Option<f64>,
84}
85
86/// #2056: bookkeeping for one in-flight background task execution.
87///
88/// Why: `SessionRegistry` needs to (a) reject a second overlapping run for
89/// the same session, (b) signal cooperative cancellation, and (c) — on
90/// graceful daemon shutdown — wait, bounded, for the task to actually stop.
91/// What: `cancel` is shared with every `AgentLoop`/`InProcessAgentRunner`
92/// the execution drives (via `with_cancel_flag`); `handle` is the
93/// `tokio::spawn` join handle, attached shortly after `begin_execution`
94/// returns (see [`SessionRegistry::attach_execution_handle`]) since the
95/// handle does not exist until the caller has actually spawned the task.
96struct Execution {
97 cancel: Arc<AtomicBool>,
98 handle: Option<JoinHandle<()>>,
99}
100
101/// The daemon-owned session registry (Axiom 4).
102///
103/// Why: single source of truth for every session's state, in-memory only
104/// (§12, M1) — see the module docs for the full rationale.
105/// What: see method docs below; `new()` uses [`DEFAULT_RING_CAPACITY`],
106/// `with_capacity` lets tests use a tiny buffer to exercise eviction cheaply.
107/// Test: `registry_tests::*`.
108pub struct SessionRegistry {
109 sessions: Mutex<HashMap<String, SessionEntry>>,
110 ring_capacity: usize,
111}
112
113impl Default for SessionRegistry {
114 fn default() -> Self {
115 Self::new()
116 }
117}
118
119impl SessionRegistry {
120 /// Construct an empty registry with the default ring-buffer capacity.
121 pub fn new() -> Self {
122 Self::with_capacity(DEFAULT_RING_CAPACITY)
123 }
124
125 /// Construct an empty registry with an explicit ring-buffer capacity.
126 ///
127 /// Why: unit tests need a small capacity to exercise eviction without
128 /// pushing 1000 events.
129 pub fn with_capacity(ring_capacity: usize) -> Self {
130 Self {
131 sessions: Mutex::new(HashMap::new()),
132 ring_capacity,
133 }
134 }
135
136 /// `session.create`: register a brand-new session and publish its
137 /// lifecycle-start events.
138 ///
139 /// Why: the sole entry point that mints a session id and puts a
140 /// `Session` into the registry.
141 /// What: builds a `Session` with a fresh UUIDv4 id and
142 /// `status = Created`, inserts it (with a fresh `seq = 0` counter),
143 /// publishes `Event::SessionStarted` (assigned `seq = 1`), then
144 /// immediately transitions to `Running` (M1 has no queue ahead of real
145 /// task execution — see `session::model` docs) which publishes
146 /// `Event::SessionStatusChanged` (`seq = 2`). Returns the
147 /// post-transition snapshot (so the caller sees `status: "running"`,
148 /// not the momentary `"created"`).
149 /// Test: `registry_tests::create_publishes_started_and_status_events`.
150 pub fn create(&self, task: String, agent: Option<String>, project: Option<String>) -> Session {
151 let id = Uuid::new_v4().to_string();
152 let session = Session {
153 id: id.clone(),
154 task,
155 agent,
156 project: project.clone(),
157 status: SessionStatus::Created,
158 created_at: Utc::now(),
159 mode: None,
160 };
161 {
162 let mut sessions = self.lock();
163 sessions.insert(
164 id.clone(),
165 SessionEntry {
166 session: session.clone(),
167 seq: 0,
168 ring: VecDeque::new(),
169 attachments: HashMap::new(),
170 execution: None,
171 transcript: Vec::new(),
172 usage: TokenUsage::default(),
173 cost_usd: None,
174 },
175 );
176 }
177 self.record(
178 &id,
179 Event::SessionStarted {
180 session_id: id.clone(),
181 project: project.unwrap_or_default(),
182 },
183 );
184 self.transition(&id, SessionStatus::Running);
185 self.status(&id).unwrap_or(session)
186 }
187
188 /// `session.list`: snapshot every session currently in the registry.
189 ///
190 /// Why: the read side of the registry for operators/CLI/TUI to enumerate
191 /// running sessions.
192 /// What: clones every `Session` snapshot; order is unspecified (backed
193 /// by a `HashMap`).
194 /// Test: `registry_tests::list_returns_every_created_session`.
195 pub fn list(&self) -> Vec<Session> {
196 self.lock().values().map(|e| e.session.clone()).collect()
197 }
198
199 /// `session.status`: snapshot one session by id.
200 ///
201 /// Why: shared by `create`'s return value and the standalone
202 /// `session.status` method.
203 /// What: `Ok(Session)` if present, `Err(RpcError::session_not_found)`
204 /// otherwise.
205 /// Test: `registry_tests::status_returns_not_found_for_unknown_id`.
206 pub fn status(&self, id: &str) -> Result<Session, RpcError> {
207 self.lock()
208 .get(id)
209 .map(|e| e.session.clone())
210 .ok_or_else(|| RpcError::session_not_found(id))
211 }
212
213 /// `session.send`: deliver input to a session and publish an observable
214 /// event proving the daemon received it.
215 ///
216 /// Why: #2054/#2055 do not wire a real agent loop (that is `task.*`,
217 /// #2056); publishing `Event::SessionInput` is what makes `session.send`
218 /// observably reach a `session.attach`ed client NOW, and gives #2056 a
219 /// concrete event to build real echo/ack behaviour on top of.
220 /// What: errors with `session_not_found` if `id` is unknown; otherwise
221 /// records+publishes `Event::SessionInput { session_id, input }`.
222 /// Test: `registry_tests::send_publishes_input_event`,
223 /// `registry_tests::send_unknown_session_errors`.
224 pub fn send(&self, id: &str, input: &str) -> Result<(), RpcError> {
225 if !self.lock().contains_key(id) {
226 return Err(RpcError::session_not_found(id));
227 }
228 self.record(
229 id,
230 Event::SessionInput {
231 session_id: id.to_string(),
232 input: input.to_string(),
233 },
234 );
235 Ok(())
236 }
237
238 /// `session.cancel`: send a cancellation signal and mark the session
239 /// terminal.
240 ///
241 /// Why: vision spec §12 (11.6) Cancellation Semantics — cancellation is
242 /// a status transition + event, not a deletion. #2054/#2055 have no
243 /// in-flight agent loop to interrupt yet (that lands with #2056), so
244 /// this is the full implementation available today: it marks the
245 /// session `Cancelled` and publishes the terminal events; #2056 hooks
246 /// the actual agent-loop interrupt onto the same status transition.
247 /// What: idempotent — cancelling an already-terminal session is a no-op
248 /// that returns the current snapshot rather than erroring (repeated
249 /// `session.cancel` calls are safe). Errors with `session_not_found` if
250 /// `id` is unknown. On a live session: publishes
251 /// `Event::SessionStatusChanged` (`status: "cancelled"`), then the
252 /// dedicated `Event::SessionCancelled` signal, then the generic terminal
253 /// `Event::SessionDone` (`status: "cancelled"`) — matching the vision
254 /// spec's `started/status-changed/input/cancelled/done` taxonomy — and
255 /// returns the updated snapshot.
256 /// Test: `registry_tests::cancel_transitions_to_cancelled_and_publishes`,
257 /// `registry_tests::cancel_is_idempotent_on_terminal_session`,
258 /// `registry_tests::cancel_unknown_session_errors`.
259 pub fn cancel(&self, id: &str) -> Result<Session, RpcError> {
260 let already_terminal = {
261 let sessions = self.lock();
262 let entry = sessions
263 .get(id)
264 .ok_or_else(|| RpcError::session_not_found(id))?;
265 entry.session.status.is_terminal()
266 };
267 if already_terminal {
268 return self.status(id);
269 }
270 self.transition(id, SessionStatus::Cancelled);
271 self.record(
272 id,
273 Event::SessionCancelled {
274 session_id: id.to_string(),
275 },
276 );
277 self.record(
278 id,
279 Event::SessionDone {
280 session_id: id.to_string(),
281 status: SessionStatus::Cancelled.as_str().to_string(),
282 },
283 );
284 self.status(id)
285 }
286
287 /// Mark a session terminal (finished, failed, or cancelled while
288 /// executing) and publish the terminal `Event::SessionDone` (#2056).
289 ///
290 /// Why: the background executor (`crate::task::executor`) needs to set
291 /// the FINAL status once an agent loop returns, distinctly from the
292 /// user-initiated `session.cancel` JSON-RPC path ([`Self::cancel`]),
293 /// which ALSO emits a dedicated `Event::SessionCancelled` signal that
294 /// only makes sense for an explicit user cancel request — not a natural
295 /// finish or failure, and not a cancellation the EXECUTOR itself
296 /// observed (that path already went through `request_cancel`, which
297 /// does not transition status; the executor calls this afterward to
298 /// actually land the transition once it has unwound).
299 /// What: idempotent — a no-op (returns the current snapshot) if the
300 /// session is already terminal, since a race between `request_cancel`'s
301 /// caller and the executor noticing cancellation is possible but
302 /// harmless. Errors with `session_not_found` if `id` is unknown.
303 /// Otherwise transitions to `status` and publishes
304 /// `Event::SessionDone { status }`.
305 /// Test: `registry_tests::finish_transitions_and_publishes_session_done`,
306 /// `registry_tests::finish_is_idempotent_on_terminal_session`,
307 /// `registry_tests::finish_unknown_session_errors`.
308 pub fn finish(&self, id: &str, status: SessionStatus) -> Result<Session, RpcError> {
309 let already_terminal = {
310 let sessions = self.lock();
311 let entry = sessions
312 .get(id)
313 .ok_or_else(|| RpcError::session_not_found(id))?;
314 entry.session.status.is_terminal()
315 };
316 if !already_terminal {
317 self.transition(id, status);
318 self.record(
319 id,
320 Event::SessionDone {
321 session_id: id.to_string(),
322 status: status.as_str().to_string(),
323 },
324 );
325 }
326 self.status(id)
327 }
328
329 /// `session.attach`: replay recent history and start forwarding this
330 /// session's live events to `notify`.
331 ///
332 /// Why: the streaming half of the session-attach protocol (vision spec
333 /// §4.4/Axiom 4). Works identically regardless of transport — the
334 /// difference between STDIO (long-lived `notify`, events interleaved on
335 /// stdout) and HTTP (throwaway `notify`; the real live path is the `GET
336 /// /sessions/{id}/events` SSE route) lives entirely in
337 /// `crate::jsonrpc::ConnectionContext`'s docs and `crate::serve`'s
338 /// transports, not here.
339 /// What: errors with `session_not_found` if `id` is unknown. Otherwise
340 /// takes a snapshot of the ring buffer (oldest-first, each entry a full
341 /// [`SessionEventEnvelope`] with its `seq` intact) to return as the
342 /// replay, registers `connection_id`'s cancel sender (replacing — and
343 /// thus cancelling — any prior forwarder for the same
344 /// `(session, connection)` pair), and spawns a task that subscribes to
345 /// `crate::events::subscribe()`, filters by `session_id`, and forwards
346 /// each match into `notify` as a JSON-RPC notification whose `params` IS
347 /// the envelope (`{"jsonrpc":"2.0","method":"session.event","params":
348 /// {"session_id":...,"seq":...,"at":...,"kind":...,"event":{...}}}`)
349 /// until `detach` fires the cancel sender or `notify.send` fails (the
350 /// connection is gone). Because every envelope — replayed or live —
351 /// comes from the SAME per-session `seq` counter (`record`), a client
352 /// that concatenates the replay array with the live notifications it
353 /// receives afterward sees one gap-free, strictly increasing sequence.
354 /// Test: `registry_tests::attach_returns_ring_buffer_replay`,
355 /// `registry_tests::attach_forwards_live_events_until_detach`,
356 /// `registry_tests::attach_replay_then_live_seq_is_contiguous`,
357 /// `registry_tests::attach_unknown_session_errors`.
358 pub fn attach(
359 &self,
360 id: &str,
361 connection_id: Uuid,
362 notify: NotifySender,
363 ) -> Result<Vec<SessionEventEnvelope>, RpcError> {
364 let replay = {
365 let mut sessions = self.lock();
366 let entry = sessions
367 .get_mut(id)
368 .ok_or_else(|| RpcError::session_not_found(id))?;
369 let (cancel_tx, cancel_rx) = oneshot::channel();
370 entry.attachments.insert(connection_id, cancel_tx);
371 spawn_forwarder(id.to_string(), notify, cancel_rx);
372 entry.ring.iter().cloned().collect::<Vec<_>>()
373 };
374 Ok(replay)
375 }
376
377 /// `session.detach`: stop forwarding this session's live events to the
378 /// calling connection.
379 ///
380 /// Why: the other half of the attach protocol — releases the forwarder
381 /// task started by `attach` for this `(session, connection)` pair.
382 /// What: errors with `session_not_found` if `id` is unknown. If the
383 /// connection has no live attachment (already detached, or never
384 /// attached), this is a no-op success rather than an error — detach is
385 /// idempotent. Otherwise fires the stored cancel sender, which stops the
386 /// forwarder task on its next `select!` poll.
387 /// Test: `registry_tests::detach_stops_the_forwarder`,
388 /// `registry_tests::detach_without_prior_attach_is_a_noop`,
389 /// `registry_tests::detach_unknown_session_errors`.
390 pub fn detach(&self, id: &str, connection_id: Uuid) -> Result<(), RpcError> {
391 let mut sessions = self.lock();
392 let entry = sessions
393 .get_mut(id)
394 .ok_or_else(|| RpcError::session_not_found(id))?;
395 if let Some(cancel_tx) = entry.attachments.remove(&connection_id) {
396 let _ = cancel_tx.send(());
397 }
398 Ok(())
399 }
400
401 /// Snapshot the ring buffer for a session without attaching to it.
402 ///
403 /// Why: the HTTP SSE route (`crate::serve::http`) needs the same replay
404 /// burst `attach` returns, but subscribes to the live bus itself (one
405 /// `Stream` per SSE connection) rather than going through a
406 /// `NotifySender` forwarder — so it calls this directly instead of
407 /// `attach`.
408 /// What: same replay semantics as `attach` (full envelopes, `seq`
409 /// intact), no side effects (no forwarder spawned, no attachment
410 /// recorded).
411 /// Test: `registry_tests::replay_returns_ring_buffer_without_attaching`.
412 pub fn replay(&self, id: &str) -> Result<Vec<SessionEventEnvelope>, RpcError> {
413 self.lock()
414 .get(id)
415 .map(|e| e.ring.iter().cloned().collect())
416 .ok_or_else(|| RpcError::session_not_found(id))
417 }
418
419 /// Begin tracking a new background task execution for `id` (#2056).
420 ///
421 /// Why: `task.run` (and `session.send` on an idle session) must not start
422 /// a second overlapping run for the same session, and the returned flag
423 /// is how the executor's `AgentLoop`(s) later observe cancellation.
424 /// What: errors with `session_not_found` if `id` is unknown,
425 /// `invalid_argument` if the session is already terminal or already has
426 /// an execution in flight. On success, stores a fresh `Arc<AtomicBool>`
427 /// cancel flag (initially `false`) with `handle: None` — the caller
428 /// attaches the real `JoinHandle` via
429 /// [`Self::attach_execution_handle`] immediately after spawning, since
430 /// the handle cannot exist before that — and returns the flag.
431 /// Test: `registry_tests::begin_execution_rejects_second_overlapping_run`,
432 /// `registry_tests::begin_execution_rejects_terminal_session`,
433 /// `registry_tests::begin_execution_unknown_session_errors`.
434 pub fn begin_execution(&self, id: &str) -> Result<Arc<AtomicBool>, RpcError> {
435 let mut sessions = self.lock();
436 let entry = sessions
437 .get_mut(id)
438 .ok_or_else(|| RpcError::session_not_found(id))?;
439 if entry.session.status.is_terminal() {
440 return Err(RpcError::invalid_argument(format!(
441 "session {id} is already terminal"
442 )));
443 }
444 if entry.execution.is_some() {
445 return Err(RpcError::invalid_argument(format!(
446 "session {id} already has a task running"
447 )));
448 }
449 let cancel = Arc::new(AtomicBool::new(false));
450 entry.execution = Some(Execution {
451 cancel: Arc::clone(&cancel),
452 handle: None,
453 });
454 Ok(cancel)
455 }
456
457 /// Attach the real `JoinHandle` to `id`'s tracked execution (#2056).
458 ///
459 /// Why: the handle only exists once the caller has actually called
460 /// `tokio::spawn`, which must happen after `begin_execution` returns (the
461 /// spawned future needs the cancel flag `begin_execution` produces).
462 /// What: best-effort — a no-op if `id` or its execution is already gone
463 /// (e.g. the run finished astonishingly fast, or the session vanished).
464 /// Test: `registry_tests::shutdown_executions_awaits_cancelled_tasks`
465 /// (exercises this indirectly via a real spawn).
466 pub fn attach_execution_handle(&self, id: &str, handle: JoinHandle<()>) {
467 let mut sessions = self.lock();
468 if let Some(entry) = sessions.get_mut(id)
469 && let Some(execution) = entry.execution.as_mut()
470 {
471 execution.handle = Some(handle);
472 }
473 }
474
475 /// Clear the execution-in-flight marker for `id` (#2056).
476 ///
477 /// Why: called by the executor once the background task has stopped
478 /// (finished, failed, or cancelled) so a later `task.run`/`session.send`
479 /// can start a new run against the same session.
480 /// What: best-effort — a no-op if `id` is already gone.
481 /// Test: `registry_tests::begin_execution_rejects_second_overlapping_run`
482 /// (calls this between the two `begin_execution` attempts).
483 pub fn finish_execution(&self, id: &str) {
484 let mut sessions = self.lock();
485 if let Some(entry) = sessions.get_mut(id) {
486 entry.execution = None;
487 }
488 }
489
490 /// Whether `id` currently has a background execution in flight (#2056).
491 ///
492 /// Why: `session::protocol::cancel` uses this to choose between
493 /// cooperative cancellation ([`Self::request_cancel`]) and the original
494 /// #2054 immediate-transition [`Self::cancel`].
495 /// What: `false` for both "unknown session" and "known but idle" — callers
496 /// that need to distinguish those already call another method first.
497 /// Test: `registry_tests::request_cancel_*`.
498 pub fn is_executing(&self, id: &str) -> bool {
499 self.lock().get(id).is_some_and(|e| e.execution.is_some())
500 }
501
502 /// Request cooperative cancellation of `id`'s in-flight execution, if any
503 /// (#2056).
504 ///
505 /// Why: `session.cancel` on a RUNNING session must signal the background
506 /// task rather than force an immediate status transition — the task
507 /// itself transitions to `Cancelled` once it actually observes the flag
508 /// and unwinds (see `crate::task::executor`).
509 /// What: `Err(session_not_found)` if `id` is unknown. `Ok(true)` if an
510 /// execution was in flight and its flag was set; `Ok(false)` if the
511 /// session exists but nothing is executing (the caller should fall back
512 /// to [`Self::cancel`] for the immediate-transition path).
513 /// Test: `registry_tests::request_cancel_sets_flag_when_executing`,
514 /// `registry_tests::request_cancel_returns_false_when_idle`.
515 pub fn request_cancel(&self, id: &str) -> Result<bool, RpcError> {
516 let sessions = self.lock();
517 let entry = sessions
518 .get(id)
519 .ok_or_else(|| RpcError::session_not_found(id))?;
520 match &entry.execution {
521 Some(execution) => {
522 execution.cancel.store(true, Ordering::Relaxed);
523 Ok(true)
524 }
525 None => Ok(false),
526 }
527 }
528
529 /// Persist a finished execution's transcript/usage/cost into the session
530 /// (#2056).
531 ///
532 /// Why: populates the storage `Self::get_transcript` (#2058) reads back
533 /// over the wire.
534 /// What: best-effort — a no-op if `id` is already gone (e.g. the daemon
535 /// is shutting down mid-run).
536 /// Test: `registry_tests::set_run_outcome_stores_transcript_and_usage`.
537 pub fn set_run_outcome(
538 &self,
539 id: &str,
540 transcript: Vec<TurnRecord>,
541 usage: TokenUsage,
542 cost_usd: Option<f64>,
543 ) {
544 let mut sessions = self.lock();
545 if let Some(entry) = sessions.get_mut(id) {
546 entry.transcript = transcript;
547 entry.usage = usage;
548 entry.cost_usd = cost_usd;
549 }
550 }
551
552 /// `session.get_transcript`: fetch the stored run record for a session
553 /// (#2058).
554 ///
555 /// Why: [`Self::set_run_outcome`] populates the storage; this is its read
556 /// counterpart — the M1 cut-line's "inspect transcript" verb. A never-run
557 /// session is a valid, empty transcript, not an error: `SessionEntry`'s
558 /// `transcript`/`usage`/`cost_usd` fields already default to
559 /// empty/zero/`None` at `create` time, so returning them unconditionally
560 /// (once the session itself is confirmed to exist) is correct with no
561 /// extra branching.
562 /// What: `Err(session_not_found)` if `id` is unknown; otherwise a clone of
563 /// whatever is currently stored, wrapped in a self-describing
564 /// [`TranscriptRecord`]. Never recomputes cost or usage — exposes exactly
565 /// what [`Self::set_run_outcome`] last stored.
566 /// Test: `registry_tests::get_transcript_returns_stored_record`,
567 /// `registry_tests::get_transcript_on_never_run_session_is_empty`,
568 /// `registry_tests::get_transcript_unknown_session_errors`.
569 pub fn get_transcript(&self, id: &str) -> Result<TranscriptRecord, RpcError> {
570 let sessions = self.lock();
571 let entry = sessions
572 .get(id)
573 .ok_or_else(|| RpcError::session_not_found(id))?;
574 Ok(TranscriptRecord {
575 session_id: id.to_string(),
576 turns: entry.transcript.clone(),
577 usage: entry.usage,
578 cost_usd: entry.cost_usd,
579 mode: entry.session.mode,
580 })
581 }
582
583 /// `task.run`: persist the resolved `HarnessMode` onto the session
584 /// (#2059).
585 ///
586 /// Why: `task::protocol::task_run` resolves the mode (env var >
587 /// `task.run` param > `.claude/settings.json` > default) BEFORE spawning
588 /// the execution; storing it here — rather than waiting for
589 /// `set_run_outcome` at the end of the run — makes it queryable via
590 /// `session.status`/`session.list` (`Session.mode`) and
591 /// `session.get_transcript` (`TranscriptRecord.mode`, which reads the
592 /// SAME field) as soon as `task.run` returns, not only after the run
593 /// completes.
594 /// What: `Err(session_not_found)` if `id` is unknown; otherwise sets
595 /// `entry.session.mode = Some(mode)`. No event is published — mode is
596 /// bookkeeping metadata, not a session-lifecycle transition in the
597 /// #2055 event taxonomy.
598 /// Test: `registry_tests::set_mode_stores_on_session`,
599 /// `registry_tests::set_mode_unknown_session_errors`.
600 pub fn set_mode(&self, id: &str, mode: HarnessMode) -> Result<(), RpcError> {
601 let mut sessions = self.lock();
602 let entry = sessions
603 .get_mut(id)
604 .ok_or_else(|| RpcError::session_not_found(id))?;
605 entry.session.mode = Some(mode);
606 Ok(())
607 }
608
609 /// Cooperatively cancel every in-flight execution and wait, bounded by
610 /// `grace`, for them to actually stop (#2056 — graceful daemon shutdown).
611 ///
612 /// Why: without this, a `tokio::spawn`'d background execution would be
613 /// abruptly dropped — never given a chance to unwind — the instant the
614 /// process's tokio runtime shuts down, violating the connection-safe
615 /// daemon-restart convention (issue #534) this extends from connections
616 /// to long-running tasks.
617 /// What: flips every tracked execution's cancel flag, takes ownership of
618 /// each `JoinHandle`, then awaits all of them concurrently with an
619 /// overall `grace` timeout. A handle that doesn't finish in time is left
620 /// to be dropped when the process exits (best-effort, not a hard
621 /// guarantee — matching the same best-effort framing as every other
622 /// shutdown step in this codebase).
623 /// Test: `registry_tests::shutdown_executions_awaits_cancelled_tasks`.
624 pub async fn shutdown_executions(&self, grace: Duration) {
625 let handles: Vec<JoinHandle<()>> = {
626 let mut sessions = self.lock();
627 sessions
628 .values_mut()
629 .filter_map(|entry| {
630 let execution = entry.execution.as_mut()?;
631 execution.cancel.store(true, Ordering::Relaxed);
632 execution.handle.take()
633 })
634 .collect()
635 };
636 if handles.is_empty() {
637 return;
638 }
639 let _ = tokio::time::timeout(grace, futures_util::future::join_all(handles)).await;
640 }
641
642 /// Record a tool invocation starting (#2055 emission plumbing for
643 /// #2056's agent loop).
644 ///
645 /// Why: gives the future agent loop a stable, already-wired call for
646 /// `ToolStarted` without it needing to touch the ring buffer, sequencing,
647 /// or bus directly.
648 /// What: errors with `session_not_found` if `id` is unknown; `args_preview`
649 /// is truncated via `crate::events::preview` before emission so a large
650 /// argument payload can't blow the ring buffer / wire size.
651 /// Test: `registry_tests::record_tool_started_publishes_event`.
652 pub fn record_tool_started(
653 &self,
654 id: &str,
655 tool: &str,
656 call_id: &str,
657 args: &str,
658 ) -> Result<(), RpcError> {
659 self.ensure_exists(id)?;
660 self.record(
661 id,
662 Event::ToolStarted {
663 session_id: id.to_string(),
664 tool: tool.to_string(),
665 call_id: call_id.to_string(),
666 args_preview: crate::events::preview(args, 500),
667 },
668 );
669 Ok(())
670 }
671
672 /// Record a tool invocation finishing (#2055 emission plumbing for
673 /// #2056's agent loop). See [`Self::record_tool_started`].
674 /// Test: `registry_tests::record_tool_finished_publishes_event`.
675 pub fn record_tool_finished(
676 &self,
677 id: &str,
678 tool: &str,
679 call_id: &str,
680 success: bool,
681 result: &str,
682 ) -> Result<(), RpcError> {
683 self.ensure_exists(id)?;
684 self.record(
685 id,
686 Event::ToolFinished {
687 session_id: id.to_string(),
688 tool: tool.to_string(),
689 call_id: call_id.to_string(),
690 success,
691 result_preview: crate::events::preview(result, 500),
692 },
693 );
694 Ok(())
695 }
696
697 /// Record a tool invocation raising an exceptional error (#2055 emission
698 /// plumbing for #2056's agent loop). See [`Self::record_tool_started`].
699 /// Test: `registry_tests::record_tool_error_publishes_event`.
700 pub fn record_tool_error(
701 &self,
702 id: &str,
703 tool: &str,
704 call_id: &str,
705 error: &str,
706 ) -> Result<(), RpcError> {
707 self.ensure_exists(id)?;
708 self.record(
709 id,
710 Event::ToolError {
711 session_id: id.to_string(),
712 tool: tool.to_string(),
713 call_id: call_id.to_string(),
714 error: error.to_string(),
715 },
716 );
717 Ok(())
718 }
719
720 /// Record a session-scoped diagnostic log line (#2055 emission plumbing).
721 /// Test: `registry_tests::record_log_publishes_event`.
722 pub fn record_log(&self, id: &str, level: &str, message: &str) -> Result<(), RpcError> {
723 self.ensure_exists(id)?;
724 self.record(
725 id,
726 Event::Log {
727 session_id: id.to_string(),
728 level: level.to_string(),
729 message: message.to_string(),
730 },
731 );
732 Ok(())
733 }
734
735 /// Record a coarse progress update (#2055 emission plumbing).
736 /// Test: `registry_tests::record_progress_publishes_event`.
737 pub fn record_progress(
738 &self,
739 id: &str,
740 message: &str,
741 percent: Option<f32>,
742 ) -> Result<(), RpcError> {
743 self.ensure_exists(id)?;
744 self.record(
745 id,
746 Event::Progress {
747 session_id: id.to_string(),
748 message: message.to_string(),
749 percent,
750 },
751 );
752 Ok(())
753 }
754
755 /// Record a generic freeform session message (#2055 emission plumbing).
756 /// Test: `registry_tests::record_message_publishes_event`.
757 pub fn record_message(&self, id: &str, text: &str) -> Result<(), RpcError> {
758 self.ensure_exists(id)?;
759 self.record(
760 id,
761 Event::Message {
762 session_id: id.to_string(),
763 text: text.to_string(),
764 },
765 );
766 Ok(())
767 }
768
769 /// Return `Ok(())` if `id` exists, `Err(session_not_found)` otherwise.
770 ///
771 /// Why: every `record_*` plumbing method needs the same existence guard
772 /// before recording; centralising it keeps each one a two-line body.
773 fn ensure_exists(&self, id: &str) -> Result<(), RpcError> {
774 if self.lock().contains_key(id) {
775 Ok(())
776 } else {
777 Err(RpcError::session_not_found(id))
778 }
779 }
780
781 /// Assign the next per-session `seq`, wrap `event` in a
782 /// [`SessionEventEnvelope`], push it onto `id`'s ring buffer (evicting
783 /// the oldest entry if full), and publish the envelope on the
784 /// process-global bus.
785 ///
786 /// Why: every lifecycle/tool/log/progress/message event goes through
787 /// this ONE function so `seq` assignment, the ring buffer, and the live
788 /// bus can never drift out of sync with each other — the correctness
789 /// property `attach_replay_then_live_seq_is_contiguous` verifies.
790 /// What: a no-op (no envelope built, nothing published) if `id` is
791 /// unknown — callers that need a hard error check existence first
792 /// (`send`, `cancel`, every `record_*` plumbing method all do).
793 fn record(&self, id: &str, event: Event) {
794 let envelope = {
795 let mut sessions = self.lock();
796 let Some(entry) = sessions.get_mut(id) else {
797 return;
798 };
799 entry.seq += 1;
800 let envelope = SessionEventEnvelope::new(id.to_string(), entry.seq, Utc::now(), event);
801 if entry.ring.len() >= self.ring_capacity {
802 entry.ring.pop_front();
803 }
804 entry.ring.push_back(envelope.clone());
805 envelope
806 };
807 crate::events::publish(envelope);
808 }
809
810 /// Update a session's status in place, then record+publish
811 /// `Event::SessionStatusChanged`.
812 fn transition(&self, id: &str, status: SessionStatus) {
813 {
814 let mut sessions = self.lock();
815 if let Some(entry) = sessions.get_mut(id) {
816 entry.session.status = status;
817 }
818 }
819 self.record(
820 id,
821 Event::SessionStatusChanged {
822 session_id: id.to_string(),
823 status: status.as_str().to_string(),
824 },
825 );
826 }
827
828 /// Lock the session map, recovering from poisoning.
829 ///
830 /// Why: a panic inside another handler while holding this lock should
831 /// not permanently wedge the whole registry for every other session —
832 /// recovering the poisoned guard is safer than propagating a panic into
833 /// unrelated requests.
834 fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, SessionEntry>> {
835 self.sessions
836 .lock()
837 .unwrap_or_else(|poison| poison.into_inner())
838 }
839}
840
841/// Spawn the background task that forwards one session's live event
842/// envelopes to a connection until cancelled or the connection is gone.
843///
844/// Why: split out of `attach` for readability; also gives `registry_tests`
845/// a single well-named spawn site to reason about. Subscribing to the bus
846/// SYNCHRONOUSLY here — before `tokio::spawn` schedules the forwarder body
847/// — matters: if the subscription happened inside the spawned `async`
848/// block instead, a caller that calls `send()` immediately after `attach()`
849/// returns could publish its event before the spawned task ever gets polled
850/// and subscribes, and `broadcast::Receiver`s only see events published
851/// after `subscribe()` was called — the event would be silently missed.
852/// What: subscribes to `crate::events::subscribe()` immediately, then
853/// spawns a task that forwards envelopes whose `session_id` matches
854/// `session_id` as a JSON-RPC notification via `notify` (`params` is the
855/// envelope itself — `seq`/`at`/`kind`/`event` all present), skips
856/// envelopes for other sessions and lag gaps, and exits on `cancel_rx`
857/// firing (either a real detach or the sender being dropped) or
858/// `notify.send` failing (connection gone).
859/// Test: `registry_tests::attach_forwards_live_events_until_detach`.
860fn spawn_forwarder(session_id: String, notify: NotifySender, cancel_rx: oneshot::Receiver<()>) {
861 use tokio::sync::broadcast::error::RecvError;
862
863 // Subscribe before spawning (see the Why above) so no event published
864 // by the caller right after `attach()` returns can be missed.
865 let mut events = crate::events::subscribe();
866
867 tokio::spawn(async move {
868 tokio::pin!(cancel_rx);
869 loop {
870 tokio::select! {
871 biased;
872 _ = &mut cancel_rx => break,
873 received = events.recv() => match received {
874 Ok(envelope) if envelope.session_id == session_id => {
875 let notification = json!({
876 "jsonrpc": "2.0",
877 "method": "session.event",
878 "params": envelope,
879 });
880 if notify.send(notification).is_err() {
881 break;
882 }
883 }
884 Ok(_) => continue,
885 Err(RecvError::Lagged(_)) => continue,
886 Err(RecvError::Closed) => break,
887 },
888 }
889 }
890 });
891}
892
893#[cfg(test)]
894#[path = "registry_tests.rs"]
895mod registry_tests;