Skip to main content

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