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::binding::ProjectBinding;
43use crate::events::{
44    ContextBudgetSnapshot, Event, IndexReadinessSnapshot, SearchAuditRecord, SessionEventEnvelope,
45};
46use crate::jsonrpc::{NotifySender, RpcError};
47use crate::mode::HarnessMode;
48use crate::perf::TokenUsage;
49use crate::run_task::TurnRecord;
50
51use super::model::{Session, SessionStatus};
52use super::transcript::MemoryDurabilityStatus;
53
54/// Default ring-buffer capacity per session (vision spec §12, 11.5).
55///
56/// Why: bounds per-session memory use; a freshly-attached client sees
57/// "recent progress but not the full session history" per spec — the ring
58/// buffer is the LIVE-event window, distinct from the full run transcript
59/// `session.get_transcript` (#2058) exposes via `Self::get_transcript`.
60/// Test: `registry_tests::ring_buffer_drops_oldest_when_full`.
61pub const DEFAULT_RING_CAPACITY: usize = 1000;
62
63/// One session's storage: the domain snapshot, its sequence counter, ring
64/// buffer, the live attachments forwarding its events, and (#2056) its
65/// background execution state + last completed run's outcome.
66struct SessionEntry {
67    session: Session,
68    /// Last-assigned per-session sequence number; the next event gets
69    /// `seq + 1`. Starts at `0` so the first recorded event is `seq = 1`.
70    seq: u64,
71    ring: VecDeque<SessionEventEnvelope>,
72    /// `connection_id` -> the cancel sender for that connection's forwarder
73    /// task. Re-attaching the same connection to the same session replaces
74    /// (and thus cancels, via `Sender` drop) the previous forwarder.
75    attachments: HashMap<Uuid, oneshot::Sender<()>>,
76    /// #8100: how many live prompters — clients able to SEE this session's
77    /// permission prompt and answer it — are watching. Held behind an `Arc`
78    /// so a `prompters::PrompterGuard` can decrement without re-entering the
79    /// registry lock. `0` makes an `ask` on this session deny at once.
80    prompters: Arc<std::sync::atomic::AtomicUsize>,
81    /// #2056: set while a background task-execution is in flight; `None`
82    /// when idle (never started, or already finished).
83    execution: Option<Execution>,
84    /// #2056: the run transcript populated once an execution finishes;
85    /// exposed read-only via `session.get_transcript` (#2058,
86    /// `Self::get_transcript`). Empty until the first execution completes.
87    /// (#2344) CUMULATIVE across every run on this session — each
88    /// `set_run_outcome` call APPENDS its turns rather than overwriting.
89    transcript: Vec<TurnRecord>,
90    /// #2056: aggregated token usage from every completed execution on this
91    /// session. (#2344) CUMULATIVE — each `set_run_outcome` call adds its
92    /// usage onto the running total rather than overwriting it.
93    usage: TokenUsage,
94    /// #2056: summed USD cost across every completed execution on this
95    /// session (`None` if pricing was never available for any run — mirrors
96    /// `run_task::RunReport::cost_usd`). (#2344) CUMULATIVE, same rule as
97    /// `usage`.
98    cost_usd: Option<f64>,
99    /// (#2344) The PM's persistent, cumulative conversation `Transcript` —
100    /// distinct from `transcript` above (which is the flat `TurnRecord`
101    /// accounting view). `None` until the session's first `task.run` seeds
102    /// it via [`SessionRegistry::begin_pm_transcript`]; briefly taken back
103    /// out to `None` while a run is in flight (safe — `execution.is_some()`
104    /// already guarantees at most one run at a time per session) and
105    /// restored by [`SessionRegistry::store_pm_transcript`] once that run
106    /// ends, regardless of outcome, so the NEXT run continues from exactly
107    /// where this one left off.
108    pm_transcript: Option<Transcript>,
109    /// (#2345) The session's durable turn-recorder sink — `None` until the
110    /// session's first `task.run` lazily constructs it via
111    /// [`SessionRegistry::memory_sink_for`] (the project directory, needed to
112    /// derive the palace id, is only known once a run starts). Built once and
113    /// reused for the life of the session (see `memory_sink` module docs for
114    /// why its background drain task must outlive any single run).
115    memory_sink: Option<Arc<super::memory_sink::TurnMemorySink>>,
116    /// (#2425) Retained durable-memory degradation status, as
117    /// `session.get_transcript` reports it.
118    memory_durability: MemoryDurabilityStatus,
119    /// (#2425) Bounded logical-order projection folding the sink's detached and
120    /// synchronous outcomes into `memory_durability`.
121    memory_outcomes: super::memory_outcome_reconciler::MemoryOutcomeReconciler,
122    /// (DOC-39 §5.6 Slice D) The most recently recorded `IndexReadiness`
123    /// probe for this session — last-writer-wins, overwritten by every new
124    /// `record_index_readiness` call. `None` until the session's first probe
125    /// lands (or forever, for a session whose `task.run` never indexes —
126    /// e.g. projectless). This is the storage `session.get_readiness` reads
127    /// so a client that attaches AFTER the one-time `Event::IndexReadiness`
128    /// fired can still retrieve the current state.
129    readiness: Option<IndexReadinessSnapshot>,
130    /// (issue #3015) The most recently recorded [`ContextBudgetSnapshot`] for
131    /// this session — last-writer-wins, mirrors `readiness` above but for
132    /// `record_context_budget`'s per-turn measurement. `None` until the
133    /// session's first `Event::ContextBudget` fires (PM-only; a delegated
134    /// sub-agent loop never emits one), so `session.get_context_budget` can
135    /// distinguish "never recorded" from an all-zero snapshot.
136    context_budget: Option<ContextBudgetSnapshot>,
137    /// (issue #3948) This session's retained working-context low-water mark
138    /// and sample count, folded in by every `record_context_budget` call.
139    /// Kept beside `context_budget` rather than inside it so the latest
140    /// point-in-time snapshot stays a pure last-writer-wins value.
141    context_floor: super::registry_context_floor::ContextFloorState,
142    /// (DOC-39 §5.4) Live per-agent roster, in first-seen order — the
143    /// AUTHORITATIVE state `session.get_agents` reads (see
144    /// `session::registry::agents`'s module docs). Updated by [`Self::record`]
145    /// (the SAME call every `record_tool_*` plumbing method already routes
146    /// through) whenever the event carries `agent`/`agent_id`, so it is
147    /// exactly as fresh as the ring buffer — but unlike `ring`, it is NEVER
148    /// evicted by `ring_capacity`. A code-critic HIGH on the #2962 PR caught
149    /// the bug this field exists to close: `session.get_agents` originally
150    /// FOLDED the bounded ring buffer directly, so a long-running agent's
151    /// `ToolStarted` could age out of the ring before any later attributed
152    /// event for that same `agent_id` landed, making it vanish from the
153    /// roster entirely — indistinguishable from "never spawned" while it may
154    /// still genuinely be running. A `Vec` (not a `HashMap`) because the
155    /// roster's first-seen ORDER is part of its contract and one session's
156    /// distinct-agent cardinality is small, so `record`'s linear find-or-insert
157    /// scan is cheap.
158    agents: Vec<AgentRosterState>,
159    /// (issue #3072) Retained search/recall audit trail, oldest-first — see
160    /// `session::registry_search_audit` module docs for the cap and eviction
161    /// policy. Appended by `SessionRegistry::push_search_audit`, called from
162    /// `record_search_performed`/`record_memory_recalled` (`registry_events`)
163    /// alongside the existing SSE emission; unlike `ring`, capacity here is
164    /// its own bound (`SEARCH_AUDIT_CAP`), independent of `ring_capacity`.
165    search_audit: VecDeque<SearchAuditRecord>,
166}
167
168/// One agent's live roster state inside a [`SessionEntry`] (DOC-39 §5.4) —
169/// see that field's own docs for why this exists separately from the ring
170/// buffer. `session::registry::agents::get_agents` reads this directly (not
171/// the ring) to build `session.get_agents`'s wire response.
172///
173/// Why: `agent_id` is stored inline (rather than as a `HashMap` key) so the
174/// containing `Vec`'s order doubles as the roster's first-seen order with no
175/// second parallel structure to keep in sync.
176/// What: `running` is `true` from the last-seen `ToolStarted` for this
177/// `agent_id` until the next `ToolFinished`/`ToolError`/telemetry event for
178/// the SAME id flips it back to `false` — see
179/// `session::registry::agents::tool_attribution`'s docs for why tool-dispatch
180/// ordering makes "last event wins" well-defined without needing to
181/// correlate `call_id`.
182struct AgentRosterState {
183    agent_id: String,
184    name: String,
185    running: bool,
186    /// (#8235) This agent's session checklist, as `todo_write` last replaced
187    /// it — empty until its first call. Per-agent, not per-session, so a
188    /// delegated sub-agent's list can never overwrite the PM's plan (DOC-39
189    /// §4.5 requires per-agent checklists). Written only by
190    /// `SessionRegistry::set_agent_todos` (`registry_todos.rs`) and read only
191    /// by `get_agents`; `note_agent_activity` never touches it, so ordinary
192    /// tool traffic cannot clear a list.
193    todos: Vec<crate::events::TodoItem>,
194}
195
196impl SessionEntry {
197    /// Fold one event into `self.agents` (DOC-39 §5.4) if it carries
198    /// `agent`/`agent_id`; a no-op for every other `Event` variant.
199    ///
200    /// Why: the single update path for the always-retained roster — called
201    /// from [`SessionRegistry::record`] under the SAME lock that pushes onto
202    /// `ring`, so the two can never observe a different set of events.
203    /// What: find-or-insert by `agent_id` (empty ids are skipped — nothing
204    /// to key a roster row on), updating `name` (last-writer-wins) and
205    /// `running` (`true` only for `ToolStarted`; every other attributed kind
206    /// fires only after its tool call already completed — see
207    /// `session::registry::agents`'s module docs for the tool-dispatch
208    /// ordering that makes this well-defined).
209    fn note_agent_activity(&mut self, event: &Event) {
210        let Some((agent, agent_id, running)) = tool_attribution(event) else {
211            return;
212        };
213        if agent_id.is_empty() {
214            return;
215        }
216        match self.agents.iter_mut().find(|a| a.agent_id == agent_id) {
217            Some(existing) => {
218                existing.name = agent.to_string();
219                existing.running = running;
220            }
221            None => self.agents.push(AgentRosterState {
222                agent_id: agent_id.to_string(),
223                name: agent.to_string(),
224                running,
225                todos: Vec::new(),
226            }),
227        }
228    }
229}
230
231/// Extract `(agent, agent_id, is_running)` from the attribution events the
232/// live roster (DOC-39 §5.4) cares about, or `None` for every other `Event`
233/// variant.
234///
235/// Why: shared by [`SessionEntry::note_agent_activity`] (the write path) and
236/// `session::registry::agents::get_agents`'s docs (which point back here) —
237/// centralises which events count as roster-relevant activity.
238/// What: `true` only for `ToolStarted`; every other attributed kind fires
239/// only after its tool call already completed
240/// (`ToolStarted` -> `ToolFinished`/`ToolError` -> optional telemetry).
241fn tool_attribution(event: &Event) -> Option<(&str, &str, bool)> {
242    match event {
243        Event::ToolStarted {
244            agent, agent_id, ..
245        } => Some((agent, agent_id, true)),
246        Event::ToolFinished {
247            agent, agent_id, ..
248        } => Some((agent, agent_id, false)),
249        Event::ToolError {
250            agent, agent_id, ..
251        } => Some((agent, agent_id, false)),
252        Event::SearchPerformed {
253            agent, agent_id, ..
254        } => Some((agent, agent_id, false)),
255        Event::MemoryRecalled {
256            agent, agent_id, ..
257        } => Some((agent, agent_id, false)),
258        _ => None,
259    }
260}
261
262/// #2056: bookkeeping for one in-flight background task execution.
263///
264/// Why: `SessionRegistry` needs to (a) reject a second overlapping run for
265/// the same session, (b) signal cooperative cancellation, and (c) — on
266/// graceful daemon shutdown — wait, bounded, for the task to actually stop.
267/// What: `cancel` is shared with every `AgentLoop`/`InProcessAgentRunner`
268/// the execution drives (via `with_cancel_flag`); `handle` is the
269/// `tokio::spawn` join handle, attached shortly after `begin_execution`
270/// returns (see [`SessionRegistry::attach_execution_handle`]) since the
271/// handle does not exist until the caller has actually spawned the task.
272///
273/// (#8207) `cancel` doubles as this execution's IDENTITY: `begin_execution`
274/// mints a fresh `Arc` per run and every holder keeps a strong clone, so
275/// `Arc::ptr_eq` against a captured clone answers "is the tracked execution
276/// still the one I started waiting on" with no generation counter to keep in
277/// sync. `SessionRegistry::await_cancelled` uses exactly that to avoid
278/// restoring a finished run's handle over a newer run's live one.
279struct Execution {
280    cancel: Arc<AtomicBool>,
281    handle: Option<JoinHandle<()>>,
282    /// (#8207) Set while a `session.cancel` holds this execution's handle, so
283    /// a CONCURRENT cancel can tell "a peer is confirming the stop" from "the
284    /// handle was never attached" — two states that otherwise look identical
285    /// (`handle: None`) and mean opposite things.
286    confirming: bool,
287}
288
289/// The daemon-owned session registry (Axiom 4).
290///
291/// Why: single source of truth for every session's state, in-memory only
292/// (§12, M1) — see the module docs for the full rationale.
293/// What: see method docs below; `new()` uses [`DEFAULT_RING_CAPACITY`],
294/// `with_capacity` lets tests use a tiny buffer to exercise eviction cheaply.
295/// Test: `registry_tests::*`.
296pub struct SessionRegistry {
297    sessions: Mutex<HashMap<String, SessionEntry>>,
298    ring_capacity: usize,
299}
300
301impl Default for SessionRegistry {
302    fn default() -> Self {
303        Self::new()
304    }
305}
306
307impl SessionRegistry {
308    /// Construct an empty registry with the default ring-buffer capacity.
309    pub fn new() -> Self {
310        Self::with_capacity(DEFAULT_RING_CAPACITY)
311    }
312
313    /// Construct an empty registry with an explicit ring-buffer capacity.
314    ///
315    /// Why: unit tests need a small capacity to exercise eviction without
316    /// pushing 1000 events.
317    pub fn with_capacity(ring_capacity: usize) -> Self {
318        Self {
319            sessions: Mutex::new(HashMap::new()),
320            ring_capacity,
321        }
322    }
323
324    /// `session.create`: register a brand-new session and publish its
325    /// lifecycle-start events.
326    ///
327    /// Why: the sole entry point that mints a session id and puts a
328    /// `Session` into the registry.
329    /// What: builds a `Session` with a fresh UUIDv4 id and
330    /// `status = Created`, inserts it (with a fresh `seq = 0` counter),
331    /// publishes `Event::SessionStarted` (assigned `seq = 1`), then
332    /// immediately transitions to `Running` (M1 has no queue ahead of real
333    /// task execution — see `session::model` docs) which publishes
334    /// `Event::SessionStatusChanged` (`seq = 2`). Returns the
335    /// post-transition snapshot (so the caller sees `status: "running"`,
336    /// not the momentary `"created"`).
337    /// `binding` replaces what was an untyped `project: Option<String>` label.
338    /// The label still exists on the wire (`Session.project`) but is now DERIVED
339    /// from the binding via `ProjectBinding::label`, so the two can never
340    /// disagree — see `Session`'s docs. `ProjectBinding::None` (projectless) is
341    /// a fully supported binding, not a missing one.
342    /// Test: `registry_tests::create_publishes_started_and_status_events`,
343    /// `registry_tests::create_derives_project_label_from_binding`.
344    ///
345    /// (#8184) Mints a DELEGATING session — use
346    /// [`SessionRegistry::create_with_delegation`] to mint the solo
347    /// (`no_delegate`) shape. A wrapper rather than a fifth parameter because
348    /// every other call site here wants this same default.
349    pub fn create(&self, task: String, agent: Option<String>, binding: ProjectBinding) -> Session {
350        self.create_with_delegation(task, agent, binding, false)
351    }
352
353    /// [`SessionRegistry::create`] with this session's agent shape chosen
354    /// explicitly (#8184).
355    ///
356    /// Why: `session.create` defaults to the SOLO agent (the interactive TUI's
357    /// default, issue #8184) while `task.run`'s own mint path keeps the
358    /// pre-#8184 delegating default unless its `no_delegate` param says
359    /// otherwise. Both need the same mint, so the flag is a parameter here
360    /// rather than two divergent copies of the body.
361    /// What: `no_delegate` is persisted onto [`Session::no_delegate`] and is
362    /// immutable afterwards — there is no setter, mirroring `binding`'s own
363    /// once-at-creation convention.
364    /// Test: `session::protocol::tests::create_defaults_to_the_solo_agent`,
365    /// `task::protocol::tests::task_run_minted_session_records_its_no_delegate`.
366    pub fn create_with_delegation(
367        &self,
368        task: String,
369        agent: Option<String>,
370        binding: ProjectBinding,
371        no_delegate: bool,
372    ) -> Session {
373        let id = Uuid::new_v4().to_string();
374        let session = Session {
375            id: id.clone(),
376            task,
377            agent,
378            project: binding.label(),
379            binding,
380            status: SessionStatus::Created,
381            created_at: Utc::now(),
382            mode: None,
383            workstream_id: None,
384            result: None,
385            no_delegate,
386        };
387        {
388            let mut sessions = self.lock();
389            sessions.insert(
390                id.clone(),
391                SessionEntry {
392                    session: session.clone(),
393                    seq: 0,
394                    ring: VecDeque::new(),
395                    attachments: HashMap::new(),
396                    // #8100: nobody is watching a brand-new session yet.
397                    prompters: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
398                    execution: None,
399                    transcript: Vec::new(),
400                    usage: TokenUsage::default(),
401                    cost_usd: None,
402                    pm_transcript: None,
403                    memory_sink: None,
404                    memory_durability: MemoryDurabilityStatus::default(),
405                    memory_outcomes: Default::default(),
406                    readiness: None,
407                    context_budget: None,
408                    context_floor: super::registry_context_floor::ContextFloorState::default(),
409                    agents: Vec::new(),
410                    search_audit: VecDeque::new(),
411                },
412            );
413        }
414        self.record(
415            &id,
416            Event::SessionStarted {
417                session_id: id.clone(),
418                // The binding-derived label. Projectless yields `""`, exactly
419                // as an absent `project` label already did before the binding
420                // existed — no wire change for this event.
421                project: session.project.clone().unwrap_or_default(),
422            },
423        );
424        self.transition(&id, SessionStatus::Running);
425        self.status(&id).unwrap_or(session)
426    }
427
428    /// `session.list`: snapshot every session currently in the registry.
429    ///
430    /// Why: the read side of the registry for operators/CLI/TUI to enumerate
431    /// running sessions.
432    /// What: clones every `Session` snapshot; order is unspecified (backed
433    /// by a `HashMap`).
434    /// Test: `registry_tests::list_returns_every_created_session`.
435    pub fn list(&self) -> Vec<Session> {
436        self.lock().values().map(|e| e.session.clone()).collect()
437    }
438
439    /// `session.status`: snapshot one session by id.
440    ///
441    /// Why: shared by `create`'s return value and the standalone
442    /// `session.status` method.
443    /// What: `Ok(Session)` if present, `Err(RpcError::session_not_found)`
444    /// otherwise.
445    /// Test: `registry_tests::status_returns_not_found_for_unknown_id`.
446    pub fn status(&self, id: &str) -> Result<Session, RpcError> {
447        self.lock()
448            .get(id)
449            .map(|e| e.session.clone())
450            .ok_or_else(|| RpcError::session_not_found(id))
451    }
452
453    /// `session.send`: deliver input to a session and publish an observable
454    /// event proving the daemon received it.
455    ///
456    /// Why: #2054/#2055 do not wire a real agent loop (that is `task.*`,
457    /// #2056); publishing `Event::SessionInput` is what makes `session.send`
458    /// observably reach a `session.attach`ed client NOW, and gives #2056 a
459    /// concrete event to build real echo/ack behaviour on top of.
460    /// What: errors with `session_not_found` if `id` is unknown; otherwise
461    /// records+publishes `Event::SessionInput { session_id, input }`.
462    /// Test: `registry_tests::send_publishes_input_event`,
463    /// `registry_tests::send_unknown_session_errors`.
464    pub fn send(&self, id: &str, input: &str) -> Result<(), RpcError> {
465        if !self.lock().contains_key(id) {
466            return Err(RpcError::session_not_found(id));
467        }
468        self.record(
469            id,
470            Event::SessionInput {
471                session_id: id.to_string(),
472                input: input.to_string(),
473            },
474        );
475        Ok(())
476    }
477
478    /// `session.cancel`: send a cancellation signal and mark the session
479    /// terminal.
480    ///
481    /// Why: vision spec §12 (11.6) Cancellation Semantics — cancellation is
482    /// a status transition + event, not a deletion. #2054/#2055 have no
483    /// in-flight agent loop to interrupt yet (that lands with #2056), so
484    /// this is the full implementation available today: it marks the
485    /// session `Cancelled` and publishes the terminal events; #2056 hooks
486    /// the actual agent-loop interrupt onto the same status transition.
487    /// What: idempotent — cancelling an already-terminal session is a no-op
488    /// that returns the current snapshot rather than erroring (repeated
489    /// `session.cancel` calls are safe). Errors with `session_not_found` if
490    /// `id` is unknown. On a live session: publishes
491    /// `Event::SessionStatusChanged` (`status: "cancelled"`), then the
492    /// dedicated `Event::SessionCancelled` signal, then the generic terminal
493    /// `Event::SessionDone` (`status: "cancelled"`) — matching the vision
494    /// spec's `started/status-changed/input/cancelled/done` taxonomy — and
495    /// returns the updated snapshot.
496    ///
497    /// #4351: also records a refless `Cancelled` `TaskResult`, so cancelling is
498    /// not the one terminal state that answers `session.status` with no
499    /// `result` — see [`Self::set_cancelled_result`].
500    /// Test: `registry_tests::cancel_transitions_to_cancelled_and_publishes`,
501    /// `registry_tests::cancel_is_idempotent_on_terminal_session`,
502    /// `registry_tests::cancel_unknown_session_errors`,
503    /// `registry_tests::cancel_records_a_refless_cancelled_result`.
504    pub fn cancel(&self, id: &str) -> Result<Session, RpcError> {
505        let already_terminal = {
506            let sessions = self.lock();
507            let entry = sessions
508                .get(id)
509                .ok_or_else(|| RpcError::session_not_found(id))?;
510            entry.session.status.is_terminal()
511        };
512        if already_terminal {
513            return self.status(id);
514        }
515        // #4351: record the result BEFORE the transition, so the snapshot this
516        // returns and every terminal path agree — see `set_cancelled_result`.
517        self.set_cancelled_result(id);
518        self.transition(id, SessionStatus::Cancelled);
519        self.record(
520            id,
521            Event::SessionCancelled {
522                session_id: id.to_string(),
523            },
524        );
525        self.record(
526            id,
527            Event::SessionDone {
528                session_id: id.to_string(),
529                status: SessionStatus::Cancelled.as_str().to_string(),
530            },
531        );
532        self.status(id)
533    }
534
535    /// Mark a session terminal (finished, failed, or cancelled while
536    /// executing) and publish the terminal `Event::SessionDone` (#2056).
537    ///
538    /// Why: the background executor (`crate::task::executor`) needs to set
539    /// the FINAL status once an agent loop returns, distinctly from the
540    /// user-initiated `session.cancel` JSON-RPC path ([`Self::cancel`]),
541    /// which ALSO emits a dedicated `Event::SessionCancelled` signal that
542    /// only makes sense for an explicit user cancel request — not a natural
543    /// finish or failure, and not a cancellation the EXECUTOR itself
544    /// observed (that path already went through `request_cancel`, which
545    /// does not transition status; the executor calls this afterward to
546    /// actually land the transition once it has unwound).
547    /// What: idempotent — a no-op (returns the current snapshot) if the
548    /// session is already terminal, since a race between `request_cancel`'s
549    /// caller and the executor noticing cancellation is possible but
550    /// harmless. Errors with `session_not_found` if `id` is unknown.
551    /// Otherwise transitions to `status` and publishes
552    /// `Event::SessionDone { status }`.
553    /// Test: `registry_tests::finish_transitions_and_publishes_session_done`,
554    /// `registry_tests::finish_is_idempotent_on_terminal_session`,
555    /// `registry_tests::finish_unknown_session_errors`.
556    pub fn finish(&self, id: &str, status: SessionStatus) -> Result<Session, RpcError> {
557        let already_terminal = {
558            let sessions = self.lock();
559            let entry = sessions
560                .get(id)
561                .ok_or_else(|| RpcError::session_not_found(id))?;
562            entry.session.status.is_terminal()
563        };
564        if !already_terminal {
565            self.transition(id, status);
566            self.record(
567                id,
568                Event::SessionDone {
569                    session_id: id.to_string(),
570                    status: status.as_str().to_string(),
571                },
572            );
573        }
574        self.status(id)
575    }
576
577    /// `session.attach`: replay recent history and start forwarding this
578    /// session's live events to `notify`.
579    ///
580    /// Why: the streaming half of the session-attach protocol (vision spec
581    /// §4.4/Axiom 4). Works identically regardless of transport — the
582    /// difference between STDIO (long-lived `notify`, events interleaved on
583    /// stdout) and HTTP (throwaway `notify`; the real live path is the `GET
584    /// /sessions/{id}/events` SSE route) lives entirely in
585    /// `crate::jsonrpc::ConnectionContext`'s docs and `crate::serve`'s
586    /// transports, not here.
587    /// What: errors with `session_not_found` if `id` is unknown. Otherwise
588    /// takes a snapshot of the ring buffer (oldest-first, each entry a full
589    /// [`SessionEventEnvelope`] with its `seq` intact) to return as the
590    /// replay, registers `connection_id`'s cancel sender (replacing — and
591    /// thus cancelling — any prior forwarder for the same
592    /// `(session, connection)` pair), and spawns a task that subscribes to
593    /// `crate::events::subscribe()`, filters by `session_id`, and forwards
594    /// each match into `notify` as a JSON-RPC notification whose `params` IS
595    /// the envelope (`{"jsonrpc":"2.0","method":"session.event","params":
596    /// {"session_id":...,"seq":...,"at":...,"kind":...,"event":{...}}}`)
597    /// until `detach` fires the cancel sender or `notify.send` fails (the
598    /// connection is gone). Because every envelope — replayed or live —
599    /// comes from the SAME per-session `seq` counter (`record`), a client
600    /// that concatenates the replay array with the live notifications it
601    /// receives afterward sees one gap-free, strictly increasing sequence.
602    /// Test: `registry_tests::attach_returns_ring_buffer_replay`,
603    /// `registry_tests::attach_forwards_live_events_until_detach`,
604    /// `registry_tests::attach_replay_then_live_seq_is_contiguous`,
605    /// `registry_tests::attach_unknown_session_errors`.
606    pub fn attach(
607        &self,
608        id: &str,
609        connection_id: Uuid,
610        notify: NotifySender,
611    ) -> Result<Vec<SessionEventEnvelope>, RpcError> {
612        // #8100: an attached connection can answer this session's prompt, so
613        // it claims a prompter before the forwarder that will hold the claim.
614        let prompter = self.claim_prompter(id);
615        let replay = {
616            let mut sessions = self.lock();
617            let entry = sessions
618                .get_mut(id)
619                .ok_or_else(|| RpcError::session_not_found(id))?;
620            let (cancel_tx, cancel_rx) = oneshot::channel();
621            entry.attachments.insert(connection_id, cancel_tx);
622            prompters::spawn_forwarder(id.to_string(), notify, cancel_rx, prompter);
623            entry.ring.iter().cloned().collect::<Vec<_>>()
624        };
625        Ok(replay)
626    }
627
628    /// `session.detach`: stop forwarding this session's live events to the
629    /// calling connection.
630    ///
631    /// Why: the other half of the attach protocol — releases the forwarder
632    /// task started by `attach` for this `(session, connection)` pair.
633    /// What: errors with `session_not_found` if `id` is unknown. If the
634    /// connection has no live attachment (already detached, or never
635    /// attached), this is a no-op success rather than an error — detach is
636    /// idempotent. Otherwise fires the stored cancel sender, which stops the
637    /// forwarder task on its next `select!` poll.
638    /// Test: `registry_tests::detach_stops_the_forwarder`,
639    /// `registry_tests::detach_without_prior_attach_is_a_noop`,
640    /// `registry_tests::detach_unknown_session_errors`.
641    pub fn detach(&self, id: &str, connection_id: Uuid) -> Result<(), RpcError> {
642        let mut sessions = self.lock();
643        let entry = sessions
644            .get_mut(id)
645            .ok_or_else(|| RpcError::session_not_found(id))?;
646        if let Some(cancel_tx) = entry.attachments.remove(&connection_id) {
647            let _ = cancel_tx.send(());
648        }
649        Ok(())
650    }
651
652    /// Snapshot the ring buffer for a session without attaching to it.
653    ///
654    /// Why: the HTTP SSE route (`crate::serve::http`) needs the same replay
655    /// burst `attach` returns, but subscribes to the live bus itself (one
656    /// `Stream` per SSE connection) rather than going through a
657    /// `NotifySender` forwarder — so it calls this directly instead of
658    /// `attach`.
659    /// What: same replay semantics as `attach` (full envelopes, `seq`
660    /// intact), no side effects (no forwarder spawned, no attachment
661    /// recorded).
662    /// Test: `registry_tests::replay_returns_ring_buffer_without_attaching`.
663    pub fn replay(&self, id: &str) -> Result<Vec<SessionEventEnvelope>, RpcError> {
664        self.lock()
665            .get(id)
666            .map(|e| e.ring.iter().cloned().collect())
667            .ok_or_else(|| RpcError::session_not_found(id))
668    }
669
670    /// Begin tracking a new background task execution for `id` (#2056; #2344
671    /// resumption semantics).
672    ///
673    /// Why: `task.run` (and `session.send` on an idle session) must not start
674    /// a second overlapping run for the same session, and the returned flag
675    /// is how the executor's `AgentLoop`(s) later observe cancellation.
676    /// (#2344/#3888/#8207) A `Finished`, `TurnCapExceeded` or `Cancelled`
677    /// session is NOT dead — see [`SessionStatus::is_resumable`] for which
678    /// statuses resume and why. Only `Failed`/`DeadlineExceeded` remain
679    /// genuinely terminal: those represent a broken run, and resuming one
680    /// still requires a fresh session.
681    /// What: errors with `session_not_found` if `id` is unknown,
682    /// `invalid_argument` if the session is `Failed`/
683    /// `DeadlineExceeded`, or already has an execution in flight — this
684    /// SINGLE in-flight-execution guard is also this ticket's concurrency
685    /// guard for `pm_transcript`: two overlapping `task.run` calls on one
686    /// session can never both hold the transcript, because the second one is
687    /// rejected here before either reaches `begin_pm_transcript`. On success,
688    /// stores a fresh `Arc<AtomicBool>` cancel flag (initially `false`) with
689    /// `handle: None` — the caller attaches the real `JoinHandle` via
690    /// [`Self::attach_execution_handle`] immediately after spawning, since
691    /// the handle cannot exist before that — and returns the flag. If the
692    /// session was resumable (`is_resumable`), transitions it back to
693    /// `Running` and publishes `Event::SessionStatusChanged` — matching the
694    /// transition every other status change in this module publishes.
695    /// Test: `registry_tests::begin_execution_rejects_second_overlapping_run`,
696    /// `registry_tests::begin_execution_rejects_terminal_session`,
697    /// `registry_tests::begin_execution_unknown_session_errors`,
698    /// `registry_tests::begin_execution_resumes_a_finished_session`,
699    /// `registry_tests::begin_execution_resumes_a_turn_cap_exceeded_session`,
700    /// `registry_tests::begin_execution_resumes_a_cancelled_session`.
701    pub fn begin_execution(&self, id: &str) -> Result<Arc<AtomicBool>, RpcError> {
702        let (cancel, resumed) = {
703            let mut sessions = self.lock();
704            let entry = sessions
705                .get_mut(id)
706                .ok_or_else(|| RpcError::session_not_found(id))?;
707            if matches!(
708                entry.session.status,
709                SessionStatus::Failed | SessionStatus::DeadlineExceeded
710            ) {
711                return Err(RpcError::invalid_argument(format!(
712                    "session {id} is already terminal"
713                )));
714            }
715            if entry.execution.is_some() {
716                return Err(RpcError::invalid_argument(format!(
717                    "session {id} already has a task running"
718                )));
719            }
720            let resumed = entry.session.status.is_resumable();
721            if resumed {
722                entry.session.status = SessionStatus::Running;
723            }
724            let cancel = Arc::new(AtomicBool::new(false));
725            entry.execution = Some(Execution {
726                cancel: Arc::clone(&cancel),
727                handle: None,
728                confirming: false,
729            });
730            (cancel, resumed)
731        };
732        if resumed {
733            self.record(
734                id,
735                Event::SessionStatusChanged {
736                    session_id: id.to_string(),
737                    status: SessionStatus::Running.as_str().to_string(),
738                },
739            );
740        }
741        Ok(cancel)
742    }
743
744    /// Attach the real `JoinHandle` to `id`'s tracked execution (#2056).
745    ///
746    /// Why: the handle only exists once the caller has actually called
747    /// `tokio::spawn`, which must happen after `begin_execution` returns (the
748    /// spawned future needs the cancel flag `begin_execution` produces).
749    /// What: best-effort — a no-op if `id` or its execution is already gone
750    /// (e.g. the run finished astonishingly fast, or the session vanished).
751    /// Test: `registry_tests::shutdown_executions_awaits_cancelled_tasks`
752    /// (exercises this indirectly via a real spawn).
753    pub fn attach_execution_handle(&self, id: &str, handle: JoinHandle<()>) {
754        let mut sessions = self.lock();
755        if let Some(entry) = sessions.get_mut(id)
756            && let Some(execution) = entry.execution.as_mut()
757        {
758            execution.handle = Some(handle);
759        }
760    }
761
762    /// Clear the execution-in-flight marker for `id` (#2056).
763    ///
764    /// Why: called by the executor once the background task has stopped
765    /// (finished, failed, or cancelled) so a later `task.run`/`session.send`
766    /// can start a new run against the same session.
767    /// What: best-effort — a no-op if `id` is already gone.
768    /// Test: `registry_tests::begin_execution_rejects_second_overlapping_run`
769    /// (calls this between the two `begin_execution` attempts).
770    pub fn finish_execution(&self, id: &str) {
771        let mut sessions = self.lock();
772        if let Some(entry) = sessions.get_mut(id) {
773            entry.execution = None;
774        }
775    }
776
777    /// Whether `id` currently has a background execution in flight (#2056).
778    ///
779    /// Why: `session::protocol::cancel` uses this to choose between
780    /// cooperative cancellation ([`Self::request_cancel`]) and the original
781    /// #2054 immediate-transition [`Self::cancel`].
782    /// What: `false` for both "unknown session" and "known but idle" — callers
783    /// that need to distinguish those already call another method first.
784    /// Test: `registry_tests::request_cancel_*`.
785    pub fn is_executing(&self, id: &str) -> bool {
786        self.lock().get(id).is_some_and(|e| e.execution.is_some())
787    }
788
789    /// Request cooperative cancellation of `id`'s in-flight execution, if any
790    /// (#2056).
791    ///
792    /// Why: `session.cancel` on a RUNNING session must signal the background
793    /// task rather than force an immediate status transition — the task
794    /// itself transitions to `Cancelled` once it actually observes the flag
795    /// and unwinds (see `crate::task::executor`).
796    /// What: `Err(session_not_found)` if `id` is unknown. `Ok(true)` if an
797    /// execution was in flight and its flag was set; `Ok(false)` if the
798    /// session exists but nothing is executing (the caller should fall back
799    /// to [`Self::cancel`] for the immediate-transition path).
800    /// Test: `registry_tests::request_cancel_sets_flag_when_executing`,
801    /// `registry_tests::request_cancel_returns_false_when_idle`.
802    pub fn request_cancel(&self, id: &str) -> Result<bool, RpcError> {
803        let sessions = self.lock();
804        let entry = sessions
805            .get(id)
806            .ok_or_else(|| RpcError::session_not_found(id))?;
807        match &entry.execution {
808            Some(execution) => {
809                execution.cancel.store(true, Ordering::Relaxed);
810                Ok(true)
811            }
812            None => Ok(false),
813        }
814    }
815
816    /// Persist a finished execution's transcript/usage/cost into the session
817    /// (#2056; #2344 made CUMULATIVE across runs).
818    ///
819    /// Why: populates the storage `Self::get_transcript` (#2058) reads back
820    /// over the wire. (#2344) A session's turns/usage/cost now accumulate
821    /// across every `task.run` rather than the last run overwriting the
822    /// previous one's — the whole point of a persistent session is that
823    /// `session.get_transcript` shows the FULL conversation, not just its
824    /// most recent slice.
825    /// What: best-effort — a no-op if `id` is already gone (e.g. the daemon
826    /// is shutting down mid-run). `transcript` is APPENDED onto the existing
827    /// turns (not replacing them); `usage` is added field-wise via
828    /// `TokenUsage::add` (the same accumulator `run_task::aggregate_usage_per_role`
829    /// uses internally); `cost_usd` sums the two `Option<f64>`s the same way
830    /// `TokenUsage::add` combines its own `cost_usd` field (`Some`+`Some` ->
831    /// sum, either `Some` alone passes through, `None`+`None` stays `None`).
832    /// Test: `registry_tests::set_run_outcome_stores_transcript_and_usage`,
833    /// `registry_tests::set_run_outcome_accumulates_across_two_calls`.
834    ///
835    /// (Issue #3298) Also records+publishes `Event::SessionActivityUpdate` —
836    /// the natural "a turn just happened" hook DOC-48 §5.3's event table asks
837    /// for, so a workstream observer can see which bound sessions are
838    /// recently active without polling. Published ONLY when `id` is
839    /// workstream-bound (`Session.workstream_id.is_some()`): the event
840    /// exists for workstream observers (§5.3 lists it in the WORKSTREAM
841    /// event set), an unbound session has no such observer, and — decisive
842    /// — the M1 cutline e2e contract (`tests/m1_cutline_e2e.rs`) freezes the
843    /// exact event-kind sequence a plain, workstream-less session emits;
844    /// firing this unconditionally inserted a new kind into that baseline
845    /// and broke both transports' frozen sequences (CI failure on PR #3354).
846    /// A no-op alongside the rest of this method if `id` is already gone.
847    /// Test: `registry_tests::set_run_outcome_publishes_activity_update_when_workstream_bound`,
848    /// `registry_tests::set_run_outcome_stays_silent_for_unbound_session`;
849    /// the frozen unbound-session baseline itself in
850    /// `m1_cutline_e2e::m1_cutline_full_scenario_over_stdio`/`_http`.
851    pub fn set_run_outcome(
852        &self,
853        id: &str,
854        transcript: Vec<TurnRecord>,
855        usage: TokenUsage,
856        cost_usd: Option<f64>,
857    ) {
858        let activity = {
859            let mut sessions = self.lock();
860            let Some(entry) = sessions.get_mut(id) else {
861                return;
862            };
863            entry.transcript.extend(transcript);
864            entry.usage.add(&usage);
865            entry.cost_usd = match (entry.cost_usd, cost_usd) {
866                (Some(a), Some(b)) => Some(a + b),
867                (Some(a), None) | (None, Some(a)) => Some(a),
868                (None, None) => None,
869            };
870            let bound = entry.session.workstream_id.is_some();
871            bound.then_some(entry.execution.is_some())
872        };
873        self.publish_activity_update(id, activity);
874    }
875
876    /// Retrieve this session's persistent PM conversation `Transcript`,
877    /// seeding it on the session's FIRST `task.run` and appending `task` as a
878    /// new user turn onto the existing history on every SUBSEQUENT one
879    /// (#2344 — the infinite-sessions conversation-continuity entry point).
880    ///
881    /// Why: `task::executor::run_and_record` must hand the PM's `AgentLoop`
882    /// the SAME growing `Transcript` every run drives via
883    /// `AgentLoop::run_with_transcript`, rather than reseeding fresh each
884    /// time (the pre-#2344 behaviour). Taking ownership OUT of the entry
885    /// (rather than cloning) lets the caller drive the loop against it
886    /// directly with no extra copy; briefly leaving `None` in storage while a
887    /// run is active can never be observed by a second concurrent caller —
888    /// `Self::begin_execution`'s single-in-flight-run guard already rejects a
889    /// second `task.run` on the same session before it would ever reach this
890    /// method (see that method's docs).
891    /// What: `Err(session_not_found)` if `id` is unknown. If `pm_transcript`
892    /// is `None` (the session has never run, or is between runs having been
893    /// `take`n and not yet restored — the call-order guarantee above means
894    /// the latter should never actually happen), seeds a fresh
895    /// `Transcript::seed(system, task)`. If `Some`, takes the existing
896    /// transcript out of storage and appends `task` as a new `user` turn via
897    /// `Transcript::push_user` — `system` is IGNORED on this branch: the
898    /// original seed's system message stays authoritative for the life of
899    /// the session (a refresh mechanism, if `agent`/`mode` config changes
900    /// between runs, is future work — not this ticket).
901    /// Test: `registry_tests::begin_pm_transcript_seeds_on_first_call`,
902    /// `registry_tests::begin_pm_transcript_appends_on_second_call`,
903    /// `registry_tests::begin_pm_transcript_unknown_session_errors`.
904    pub fn begin_pm_transcript(
905        &self,
906        id: &str,
907        system: &str,
908        task: &str,
909    ) -> Result<Transcript, RpcError> {
910        let mut sessions = self.lock();
911        let entry = sessions
912            .get_mut(id)
913            .ok_or_else(|| RpcError::session_not_found(id))?;
914        Ok(match entry.pm_transcript.take() {
915            Some(mut existing) => {
916                existing.push_user(task);
917                existing
918            }
919            None => Transcript::seed(system, task),
920        })
921    }
922
923    /// Persist the PM's conversation `Transcript` back onto the session once
924    /// a run ends (#2344).
925    ///
926    /// Why: pairs with [`Self::begin_pm_transcript`] — MUST be called
927    /// regardless of the run's outcome (success, failure, cancellation, or
928    /// timeout) so the conversation up to the point of interruption survives
929    /// for the NEXT `task.run` to continue from, rather than the session
930    /// being left with no `pm_transcript` at all (which would silently
931    /// re-seed from scratch on the next run instead of erroring).
932    /// What: best-effort — a no-op if `id` is already gone (mirrors
933    /// `Self::set_run_outcome`'s same best-effort framing).
934    /// Test: `registry_tests::begin_pm_transcript_appends_on_second_call`
935    /// (exercises both halves of the round trip).
936    pub fn store_pm_transcript(&self, id: &str, transcript: Transcript) {
937        let mut sessions = self.lock();
938        if let Some(entry) = sessions.get_mut(id) {
939            entry.pm_transcript = Some(transcript);
940        }
941    }
942
943    /// `task.run`: persist the resolved `HarnessMode` onto the session
944    /// (#2059).
945    ///
946    /// Why: `task::protocol::task_run` resolves the mode (env var >
947    /// `task.run` param > `.claude/settings.json` > default) BEFORE spawning
948    /// the execution; storing it here — rather than waiting for
949    /// `set_run_outcome` at the end of the run — makes it queryable via
950    /// `session.status`/`session.list` (`Session.mode`) and
951    /// `session.get_transcript` (`TranscriptRecord.mode`, which reads the
952    /// SAME field) as soon as `task.run` returns, not only after the run
953    /// completes.
954    /// What: `Err(session_not_found)` if `id` is unknown; otherwise sets
955    /// `entry.session.mode = Some(mode)`. No event is published — mode is
956    /// bookkeeping metadata, not a session-lifecycle transition in the
957    /// #2055 event taxonomy.
958    /// Test: `registry_tests::set_mode_stores_on_session`,
959    /// `registry_tests::set_mode_unknown_session_errors`.
960    pub fn set_mode(&self, id: &str, mode: HarnessMode) -> Result<(), RpcError> {
961        let mut sessions = self.lock();
962        let entry = sessions
963            .get_mut(id)
964            .ok_or_else(|| RpcError::session_not_found(id))?;
965        entry.session.mode = Some(mode);
966        Ok(())
967    }
968
969    /// Cooperatively cancel every in-flight execution and wait, bounded by
970    /// `grace`, for them to actually stop (#2056 — graceful daemon shutdown).
971    ///
972    /// Why: without this, a `tokio::spawn`'d background execution would be
973    /// abruptly dropped — never given a chance to unwind — the instant the
974    /// process's tokio runtime shuts down, violating the connection-safe
975    /// daemon-restart convention (issue #534) this extends from connections
976    /// to long-running tasks.
977    /// What: flips every tracked execution's cancel flag, takes ownership of
978    /// each `JoinHandle`, then awaits all of them concurrently with an
979    /// overall `grace` timeout. A handle that doesn't finish in time is left
980    /// to be dropped when the process exits (best-effort, not a hard
981    /// guarantee — matching the same best-effort framing as every other
982    /// shutdown step in this codebase).
983    /// Test: `registry_tests::shutdown_executions_awaits_cancelled_tasks`.
984    pub async fn shutdown_executions(&self, grace: Duration) {
985        let handles: Vec<JoinHandle<()>> = {
986            let mut sessions = self.lock();
987            sessions
988                .values_mut()
989                .filter_map(|entry| {
990                    let execution = entry.execution.as_mut()?;
991                    execution.cancel.store(true, Ordering::Relaxed);
992                    execution.handle.take()
993                })
994                .collect()
995        };
996        if handles.is_empty() {
997            return;
998        }
999        let _ = tokio::time::timeout(grace, futures_util::future::join_all(handles)).await;
1000    }
1001
1002    /// Assign the next per-session `seq`, wrap `event` in a
1003    /// [`SessionEventEnvelope`], push it onto `id`'s ring buffer (evicting
1004    /// the oldest entry if full), and publish the envelope on the
1005    /// process-global bus.
1006    ///
1007    /// Why: every lifecycle/tool/log/progress/message event goes through
1008    /// this ONE function so `seq` assignment, the ring buffer, and the live
1009    /// bus can never drift out of sync with each other — the correctness
1010    /// property `attach_replay_then_live_seq_is_contiguous` verifies. It is
1011    /// ALSO the one place `SessionEntry::agents` (DOC-39 §5.4) is updated —
1012    /// the same critical section that pushes onto the capacity-bounded
1013    /// `ring`, so the always-retained roster and the ring can never observe
1014    /// a different event even transiently.
1015    /// What: a no-op (no envelope built, nothing published) if `id` is
1016    /// unknown — callers that need a hard error check existence first
1017    /// (`send`, `cancel`, every `record_*` plumbing method all do).
1018    fn record(&self, id: &str, event: Event) {
1019        let envelope = {
1020            let mut sessions = self.lock();
1021            let Some(entry) = sessions.get_mut(id) else {
1022                return;
1023            };
1024            entry.seq += 1;
1025            let envelope = SessionEventEnvelope::new(id.to_string(), entry.seq, Utc::now(), event);
1026            if entry.ring.len() >= self.ring_capacity {
1027                entry.ring.pop_front();
1028            }
1029            entry.ring.push_back(envelope.clone());
1030            entry.note_agent_activity(&envelope.event);
1031            envelope
1032        };
1033        crate::events::publish(envelope);
1034    }
1035
1036    /// Update a session's status in place, then record+publish
1037    /// `Event::SessionStatusChanged`.
1038    fn transition(&self, id: &str, status: SessionStatus) {
1039        {
1040            let mut sessions = self.lock();
1041            if let Some(entry) = sessions.get_mut(id) {
1042                entry.session.status = status;
1043            }
1044        }
1045        self.record(
1046            id,
1047            Event::SessionStatusChanged {
1048                session_id: id.to_string(),
1049                status: status.as_str().to_string(),
1050            },
1051        );
1052    }
1053
1054    /// Lock the session map, recovering from poisoning.
1055    ///
1056    /// Why: a panic inside another handler while holding this lock should
1057    /// not permanently wedge the whole registry for every other session —
1058    /// recovering the poisoned guard is safer than propagating a panic into
1059    /// unrelated requests.
1060    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, SessionEntry>> {
1061        self.sessions
1062            .lock()
1063            .unwrap_or_else(|poison| poison.into_inner())
1064    }
1065}
1066
1067/// #2055 tool/log/progress/message event-recording plumbing, split out into
1068/// its own file (#2344) purely to keep this production file under the
1069/// 500-SLOC cap — these methods are still `impl SessionRegistry`, called
1070/// exactly the same way as if they lived here.
1071#[path = "registry_events.rs"]
1072mod events;
1073
1074/// #8100's per-session prompter accounting and the `session.attach`
1075/// forwarder that holds one claim, split out for the same 500-SLOC-cap reason.
1076#[path = "registry_prompters.rs"]
1077mod prompters;
1078pub use prompters::PrompterGuard;
1079
1080/// #7948's permission-prompt recording and the `PermissionEvents` impl, split
1081/// off `events` (#8100) for the same 500-SLOC-cap reason.
1082#[path = "registry_permission_events.rs"]
1083mod permission_events;
1084
1085/// #2345 turn-recorder sink lazy-init/lookup, split out into its own file for
1086/// the same 500-SLOC-cap reason as `events` above.
1087#[path = "registry_memory_sink.rs"]
1088mod memory_sink_ext;
1089
1090/// #2058's `session.get_transcript` projection, split out into its own file
1091/// for the same 500-SLOC-cap reason as `events` above.
1092#[path = "registry_transcript.rs"]
1093mod transcript_ops;
1094
1095/// #2350 operator-facing goal-slot plumbing (`session.set_goal`/
1096/// `clear_goal`/`get_goals`), split out into its own file for the same
1097/// 500-SLOC-cap reason as `events`/`memory_sink_ext` above.
1098#[path = "registry_goals.rs"]
1099mod goal_ops;
1100
1101/// `session.get_agents`'s live-roster fold (DOC-39 §5.4), split out into its
1102/// own file for the same 500-SLOC-cap reason as `events` above.
1103#[path = "registry_agents.rs"]
1104mod agents;
1105
1106/// `SessionRegistry::bind_workstream` (DOC-48 §4.1, issue #3298), split out
1107/// into its own file for the same 500-SLOC-cap reason as `events` above.
1108#[path = "registry_workstream.rs"]
1109mod workstream_binding;
1110
1111/// `session.get_search_audit`'s retained search/recall audit trail (issue
1112/// #3072), split out into its own file for the same 500-SLOC-cap reason as
1113/// `events` above.
1114#[path = "registry_search_audit.rs"]
1115mod search_audit;
1116
1117/// #4351's `SessionRegistry::set_task_result`, split out into its own file for
1118/// the same 500-SLOC-cap reason as `events` above.
1119#[path = "registry_task_result.rs"]
1120mod task_result_ops;
1121
1122/// #8207's `SessionRegistry::await_cancelled`, split out into its own file for
1123/// the same 500-SLOC-cap reason as `events` above.
1124#[path = "registry_cancel.rs"]
1125mod cancel_confirm;
1126
1127/// #8235's `SessionRegistry::set_agent_todos` (the session checklist's write
1128/// path), split out into its own file for the same 500-SLOC-cap reason as
1129/// `events` above.
1130#[path = "registry_todos.rs"]
1131mod todo_ops;
1132
1133#[cfg(test)]
1134#[path = "registry_tests.rs"]
1135mod registry_tests;